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): rebuild the launcher as a grouped grid
Tioit-Wang20572abca2b1
diff --git a/apps/desktop/electron/main/bootstrap/launcher.ts b/apps/desktop/electron/main/bootstrap/launcher.tsindex d44d8beec..f09faff51 100644--- a/apps/desktop/electron/main/bootstrap/launcher.ts+++ b/apps/desktop/electron/main/bootstrap/launcher.ts@@ -14,6 +14,15 @@ import type { HostProcess } from "../host-process";import type { Logger } from "../logger";import type { WindowLifecycleState } from "./window";import { suppressLinuxFramelessSystemMenu } from "../frameless-system-menu";+import {+ PLUGIN_LAUNCHER_MAX_HEIGHT,+ PLUGIN_LAUNCHER_MAX_WIDTH,+ PLUGIN_LAUNCHER_MIN_HEIGHT,+ PLUGIN_LAUNCHER_MIN_WIDTH,+ readLauncherWindowState,+ resolveLauncherBounds,+ writeLauncherWindowState,+} from "../plugin-launcher-state";export type LauncherState = {creationPromise: Promise<BrowserWindow> | null;@@ -29,6 +38,8 @@ export type LauncherDependencies = {logger: Pick<Logger, "app">;safeOpenExternal: (rawUrl: unknown) => Promise<void>;toggleMainWindow: () => void;+ /** Where `plugin-launcher-state.json` lives (ADR 0090 shell-state rule). */+ dataDir: string;};/**@@ -57,20 +68,49 @@ export function createLauncher({logger,safeOpenExternal,toggleMainWindow,+ dataDir,}: LauncherDependencies) {+ /** Debounced write of the panel's own size and position. */+ let persistBoundsTimer: ReturnType<typeof setTimeout> | null = null;- const PLUGIN_LAUNCHER_WIDTH = 620;- const PLUGIN_LAUNCHER_HEIGHT = 440;+ function launcherWorkArea() {+ return screen.getDisplayNearestPoint(screen.getCursorScreenPoint()).workArea;+ }+ /**+ * Bounds to open with: the size the user dragged to, kept only when the saved+ * position still lands inside the display the panel is opening on. A display+ * that was unplugged must not leave the panel off-screen (ADR 0090).+ */function pluginLauncherBounds() {- const display = screen.getDisplayNearestPoint(screen.getCursorScreenPoint());- const { x, y, width, height } = display.workArea;- return {- x: Math.round(x + (width - PLUGIN_LAUNCHER_WIDTH) / 2),- y: Math.round(y + (height - PLUGIN_LAUNCHER_HEIGHT) / 2),- width: PLUGIN_LAUNCHER_WIDTH,- height: PLUGIN_LAUNCHER_HEIGHT,- };+ return resolveLauncherBounds(+ readLauncherWindowState(dataDir),+ launcherWorkArea(),+ );+ }++ function persistPluginLauncherBounds(window: BrowserWindow): void {+ if (window.isDestroyed() || window.isMinimized() || window.isFullScreen()) {+ return;+ }+ writeLauncherWindowState(dataDir, window.getBounds());+ }++ function flushPluginLauncherBounds(window: BrowserWindow): void {+ if (persistBoundsTimer) {+ clearTimeout(persistBoundsTimer);+ persistBoundsTimer = null;+ }+ persistPluginLauncherBounds(window);+ }++ function schedulePluginLauncherBounds(window: BrowserWindow): void {+ if (persistBoundsTimer) clearTimeout(persistBoundsTimer);+ persistBoundsTimer = setTimeout(() => {+ persistBoundsTimer = null;+ persistPluginLauncherBounds(window);+ }, 400);+ persistBoundsTimer.unref?.();}function createPluginLauncherWindow(): Promise<BrowserWindow> {@@ -87,7 +127,13 @@ export function createLauncher({frame: false,transparent: true,backgroundColor: "#00000000",- resizable: false,+ // The user drags this panel wider to fit their own grid; the eight+ // columns stay aligned from the minimum width up.+ resizable: true,+ minWidth: PLUGIN_LAUNCHER_MIN_WIDTH,+ minHeight: PLUGIN_LAUNCHER_MIN_HEIGHT,+ maxWidth: PLUGIN_LAUNCHER_MAX_WIDTH,+ maxHeight: PLUGIN_LAUNCHER_MAX_HEIGHT,minimizable: false,maximizable: false,fullscreenable: false,@@ -129,11 +175,17 @@ export function createLauncher({if (devOrigin && url.startsWith(devOrigin)) return;event.preventDefault();});+ window.on("resize", () => schedulePluginLauncherBounds(window));+ window.on("move", () => schedulePluginLauncherBounds(window));window.on("blur", () => {if (!window.isDestroyed() && !window.webContents.isDevToolsOpened()) {+ // Persist before hiding: the panel is only ever hidden, never closed,+ // so a size the user dragged stays until shutdown flushes again.+ flushPluginLauncherBounds(window);window.hide();}});+ window.on("close", () => flushPluginLauncherBounds(window));window.on("closed", () => {if (state.pluginLauncherWindow === window) state.pluginLauncherWindow = null;});diff --git a/apps/desktop/electron/main/plugin-launcher-state.ts b/apps/desktop/electron/main/plugin-launcher-state.tsnew file mode 100644index 000000000..7b33c19c0--- /dev/null+++ b/apps/desktop/electron/main/plugin-launcher-state.ts@@ -0,0 +1,159 @@+/**+ * Persisted size and position of the plugin launcher window.+ *+ * The launcher is app-shell chrome, not user data: it follows the same rule as+ * `window-state.json` (ADR 0090) and lives as a small JSON file in the app data+ * directory, written best-effort by the main process only. Nothing here touches+ * host-core, so no schema or migration is involved.+ *+ * All geometry logic is pure and unit-tested: the window code only wires the+ * read on show and the debounced write on move/resize.+ */+import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";++export const PLUGIN_LAUNCHER_STATE_FILE = "plugin-launcher-state.json";++/**+ * The launcher must fit eight columns without squeezing: below this width the+ * grid drops to six columns, which is the one thing the user cannot undo by+ * dragging.+ */+export const PLUGIN_LAUNCHER_MIN_WIDTH = 560;+export const PLUGIN_LAUNCHER_MIN_HEIGHT = 380;+/** Wider than this the eight tiles stop being scannable. */+export const PLUGIN_LAUNCHER_MAX_WIDTH = 1280;+export const PLUGIN_LAUNCHER_MAX_HEIGHT = 940;+export const PLUGIN_LAUNCHER_DEFAULT_WIDTH = 760;+export const PLUGIN_LAUNCHER_DEFAULT_HEIGHT = 440;++export type LauncherWindowState = {+ width: number;+ height: number;+ /** Absent until the user has dragged the panel at least once. */+ x?: number;+ y?: number;+};++export type LauncherBounds = {+ x: number;+ y: number;+ width: number;+ height: number;+};++export type LauncherWorkArea = {+ x: number;+ y: number;+ width: number;+ height: number;+};++function isFiniteNumber(value: unknown): value is number {+ return typeof value === "number" && Number.isFinite(value);+}++function clampDimension(value: unknown, min: number, max: number, fallback: number): number {+ if (!isFiniteNumber(value)) return fallback;+ return Math.min(max, Math.max(min, Math.round(value)));+}++/**+ * Read a persisted state defensively: another version's payload, a truncated+ * write, or a hand-edited file must all degrade to "no remembered size" rather+ * than to a window the user cannot see.+ */+export function parseLauncherWindowState(raw: unknown): LauncherWindowState | null {+ if (!raw || typeof raw !== "object") return null;+ const record = raw as Record<string, unknown>;+ if (!isFiniteNumber(record.width) || !isFiniteNumber(record.height)) return null;+ const state: LauncherWindowState = {+ width: clampDimension(+ record.width,+ PLUGIN_LAUNCHER_MIN_WIDTH,+ PLUGIN_LAUNCHER_MAX_WIDTH,+ PLUGIN_LAUNCHER_DEFAULT_WIDTH,+ ),+ height: clampDimension(+ record.height,+ PLUGIN_LAUNCHER_MIN_HEIGHT,+ PLUGIN_LAUNCHER_MAX_HEIGHT,+ PLUGIN_LAUNCHER_DEFAULT_HEIGHT,+ ),+ };+ if (isFiniteNumber(record.x) && isFiniteNumber(record.y)) {+ state.x = Math.round(record.x);+ state.y = Math.round(record.y);+ }+ return state;+}++/**+ * Resolve the bounds to apply on show.+ *+ * A remembered position is kept only when it still falls inside the work area it+ * is asked to fit — after a display is unplugged or a resolution changes, the+ * saved point would otherwise place the panel off-screen with no way back.+ * Without a usable position the panel is centred on that work area.+ */+export function resolveLauncherBounds(+ state: LauncherWindowState | null,+ workArea: LauncherWorkArea,+): LauncherBounds {+ const width = clampDimension(+ state?.width,+ PLUGIN_LAUNCHER_MIN_WIDTH,+ Math.max(PLUGIN_LAUNCHER_MIN_WIDTH, Math.min(PLUGIN_LAUNCHER_MAX_WIDTH, workArea.width)),+ Math.min(PLUGIN_LAUNCHER_DEFAULT_WIDTH, workArea.width),+ );+ const height = clampDimension(+ state?.height,+ PLUGIN_LAUNCHER_MIN_HEIGHT,+ Math.max(PLUGIN_LAUNCHER_MIN_HEIGHT, Math.min(PLUGIN_LAUNCHER_MAX_HEIGHT, workArea.height)),+ Math.min(PLUGIN_LAUNCHER_DEFAULT_HEIGHT, workArea.height),+ );+ const centeredX = Math.round(workArea.x + (workArea.width - width) / 2);+ const centeredY = Math.round(workArea.y + (workArea.height - height) / 2);+ const candidateX = state?.x;+ const candidateY = state?.y;+ const inside =+ isFiniteNumber(candidateX) &&+ isFiniteNumber(candidateY) &&+ candidateX >= workArea.x &&+ candidateY >= workArea.y &&+ candidateX + width <= workArea.x + workArea.width &&+ candidateY + height <= workArea.y + workArea.height;+ return {+ x: inside && isFiniteNumber(candidateX) ? candidateX : centeredX,+ y: inside && isFiniteNumber(candidateY) ? candidateY : centeredY,+ width,+ height,+ };+}++export function readLauncherWindowState(dataDir: string): LauncherWindowState | null {+ try {+ const raw = readFileSync(join(dataDir, PLUGIN_LAUNCHER_STATE_FILE), "utf8");+ return parseLauncherWindowState(JSON.parse(raw) as unknown);+ } catch {+ // Missing, unreadable, or invalid: the panel opens at its default size.+ return null;+ }+}++export function writeLauncherWindowState(+ dataDir: string,+ bounds: LauncherBounds | LauncherWindowState,+): void {+ const state = parseLauncherWindowState(bounds);+ if (!state) return;+ try {+ writeFileSync(+ join(dataDir, PLUGIN_LAUNCHER_STATE_FILE),+ `${JSON.stringify(state)}\n`,+ "utf8",+ );+ } catch {+ // Best-effort persistence, like the main window's bounds.+ }+}diff --git a/apps/desktop/src/components/PluginLauncher.tsx b/apps/desktop/src/components/PluginLauncher.tsxindex e652a9ffa..91512d687 100644--- a/apps/desktop/src/components/PluginLauncher.tsx+++ b/apps/desktop/src/components/PluginLauncher.tsx@@ -1,31 +1,115 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { isThemeColorScheme, type PluginSummary } from "@pi-desktop/shared";+import {+ isThemeColorScheme,+ type LauncherCatalog,+} from "@pi-desktop/shared";import { api } from "../lib/api";-import { searchLaunchablePlugins } from "../lib/plugin-launcher-search";import {- loadPluginLaunchHistory,- rememberPluginLaunch,-} from "../lib/plugin-launcher-history";-import { IconArrowUpRight, IconPlug, IconSearch } from "./icons";+ LAUNCHER_COLUMNS,+ buildLauncherPinnedSection,+ buildLauncherRecentSection,+ indexLauncherCatalog,+ searchLauncherItems,+ type LauncherSection,+ type LauncherTile,+} from "../lib/launcher-search";+import {+ readLauncherState,+ pruneLauncherState,+ rememberLauncherUse,+ setLauncherAliases,+ setLauncherPinned,+ type LauncherStoreSnapshot,+} from "../lib/launcher-store";+import { LauncherTileButton } from "./launcher/LauncherTileButton";+import { LauncherItemMenu } from "./launcher/LauncherItemMenu";+import { IconPlug, IconSearch } from "./icons";++/** Above this many matches the panel asks the user to keep typing. */+const UNLIMITED = Number.MAX_SAFE_INTEGER;+/** A background application scan is retried this many times before it is final. */+const SCAN_RETRY_LIMIT = 3;+const SCAN_RETRY_DELAY_MS = 1200;-function monogram(name: string): string {- return Array.from(name.trim())[0]?.toLocaleUpperCase() ?? "P";+function optionId(itemId: string): string {+ return `plugin-launcher-option-${itemId.replace(/[^a-zA-Z0-9_-]+/g, "-")}`;+}++/**+ * One titled grid of tiles.+ *+ * The header carries the section's affordance — expand when the grid had to drop+ * entries, collapse when it shows everything — and the grid itself is always+ * eight columns wide, so widening the window widens tiles instead of reflowing+ * them onto other rows.+ */+function LauncherSectionGrid({+ title,+ section,+ startIndex,+ activeIndex,+ disabled,+ onOpen,+ onMenu,+ action,+}: {+ title: string;+ section: LauncherSection;+ startIndex: number;+ activeIndex: number;+ disabled: boolean;+ onOpen: (tile: LauncherTile) => void;+ onMenu: (tile: LauncherTile) => void;+ action?: { label: string; title: string; onSelect: () => void };+}) {+ if (!section.tiles.length) return null;+ return (+ <section className="plugin-launcher-group" aria-label={title}>+ <header className="plugin-launcher-group-header">+ <h2>{title}</h2>+ {action ? (+ <button+ type="button"+ className="plugin-launcher-group-action"+ tabIndex={-1}+ onClick={action.onSelect}+ >+ {action.label}+ </button>+ ) : null}+ </header>+ <div className="plugin-launcher-grid" role="presentation">+ {section.tiles.map((tile, index) => (+ <LauncherTileButton+ key={tile.id}+ tile={tile}+ active={activeIndex === startIndex + index}+ disabled={disabled}+ optionId={optionId(tile.id)}+ onOpen={() => onOpen(tile)}+ onMenu={() => onMenu(tile)}+ />+ ))}+ </div>+ </section>+ );}export function PluginLauncher() {const { t } = useTranslation();const inputRef = useRef<HTMLInputElement>(null);const [query, setQuery] = useState("");- const [plugins, setPlugins] = useState<PluginSummary[]>([]);- const [highlighted, setHighlighted] = useState(0);+ const [catalog, setCatalog] = useState<LauncherCatalog | null>(null);+ const [store, setStore] = useState<LauncherStoreSnapshot>(() => readLauncherState());+ const [activeIndex, setActiveIndex] = useState(0);+ const [expanded, setExpanded] = useState(false);const [loading, setLoading] = useState(true);const [openingId, setOpeningId] = useState<string | null>(null);const [error, setError] = useState<string | null>(null);- const [recentIds, setRecentIds] = useState<string[]>(() =>- loadPluginLaunchHistory().map((record) => record.id),- );+ const [menuTile, setMenuTile] = useState<LauncherTile | null>(null);const loadPromiseRef = useRef<Promise<void> | null>(null);+ const scanRetriesRef = useRef(0);useEffect(() => {let disposed = false;@@ -59,22 +143,27 @@ export function PluginLauncher() {};}, []);- const results = useMemo(- () => searchLaunchablePlugins(plugins, query, recentIds).slice(0, 7),- [plugins, query, recentIds],- );-- const load = useCallback(async () => {+ const load = useCallback(async (): Promise<void> => {if (loadPromiseRef.current) {await loadPromiseRef.current;return;}- setLoading(true);- setError(null);const request = (async () => {try {- const result = await api.listPlugins();- setPlugins(result.plugins);+ const next = await api.launcherCatalog();+ setCatalog(next);+ setError(null);+ const known = [+ ...next.plugins.map((plugin) => plugin.id),+ ...next.apps.map((app) => app.id),+ ];+ setStore(pruneLauncherState(known));+ if (next.appsScanning && scanRetriesRef.current < SCAN_RETRY_LIMIT) {+ scanRetriesRef.current += 1;+ window.setTimeout(() => {+ void load();+ }, SCAN_RETRY_DELAY_MS);+ }} catch (loadError) {setError(loadError instanceof Error ? loadError.message : String(loadError));} finally {@@ -91,10 +180,13 @@ export function PluginLauncher() {const reset = useCallback(() => {setQuery("");- setHighlighted(0);+ setActiveIndex(0);+ setExpanded(false);setOpeningId(null);setError(null);- setRecentIds(loadPluginLaunchHistory().map((record) => record.id));+ setMenuTile(null);+ scanRetriesRef.current = 0;+ setStore(readLauncherState());// Warm-up may run before the host is ready, so retry the persisted theme// when the launcher is actually shown instead of keeping the fallback.void api@@ -116,34 +208,154 @@ export function PluginLauncher() {return api.onPluginLauncherShown(reset);}, [reset]);+ // Pins and aliases can be changed in another window; web storage already+ // broadcasts that, so the panel does not need its own cross-window channel.useEffect(() => {- setHighlighted(0);- }, [query]);+ const onStorage = () => setStore(readLauncherState());+ window.addEventListener("storage", onStorage);+ return () => window.removeEventListener("storage", onStorage);+ }, []);++ const index = useMemo(+ () => (catalog ? indexLauncherCatalog(catalog, store) : null),+ [catalog, store],+ );+ const recentSection = useMemo(+ () =>+ index+ ? buildLauncherRecentSection(index, store, expanded ? UNLIMITED : undefined)+ : { tiles: [], total: 0 },+ [index, store, expanded],+ );+ const pinnedSection = useMemo(+ () =>+ index+ ? buildLauncherPinnedSection(index, store, expanded ? UNLIMITED : undefined)+ : { tiles: [], total: 0 },+ [index, store, expanded],+ );+ const matchSection = useMemo(+ () =>+ index+ ? searchLauncherItems(index, query, store)+ : { tiles: [], total: 0 },+ [index, query, store],+ );++ const searching = query.trim().length > 0;+ const navTiles = useMemo(+ () =>+ searching+ ? matchSection.tiles+ : [...recentSection.tiles, ...pinnedSection.tiles],+ [searching, matchSection.tiles, recentSection.tiles, pinnedSection.tiles],+ );useEffect(() => {- if (highlighted < results.length) return;- setHighlighted(Math.max(0, results.length - 1));- }, [highlighted, results.length]);+ setActiveIndex((current) =>+ navTiles.length ? Math.min(current, navTiles.length - 1) : 0,+ );+ }, [navTiles.length]);- const openPlugin = async (plugin: PluginSummary | undefined) => {- if (!plugin || openingId) return;- setOpeningId(plugin.id);- setError(null);- try {- await api.openPluginPanel(plugin.id);- setRecentIds(rememberPluginLaunch(plugin.id).map((record) => record.id));- await api.dismissPluginLauncher();- } catch (openError) {- setError(openError instanceof Error ? openError.message : String(openError));- setOpeningId(null);- }- };+ const openTile = useCallback(+ async (tile: LauncherTile | undefined) => {+ if (!tile || openingId) return;+ setOpeningId(tile.id);+ setError(null);+ try {+ if (tile.kind === "plugin" && tile.pluginId) {+ await api.launcherOpenPlugin({+ pluginId: tile.pluginId,+ ...(tile.trigger+ ? { triggerId: tile.trigger.id, payload: tile.trigger.payload }+ : {}),+ });+ } else {+ await api.launcherOpenApp(tile.id);+ }+ setStore(rememberLauncherUse(tile.id));+ await api.dismissPluginLauncher();+ } catch (openError) {+ setError(openError instanceof Error ? openError.message : String(openError));+ setOpeningId(null);+ }+ },+ [openingId],+ );++ const moveActive = useCallback(+ (delta: number) => {+ if (!navTiles.length) return;+ setActiveIndex((current) => {+ const next = current + delta;+ if (next < 0) return 0;+ if (next >= navTiles.length) return navTiles.length - 1;+ return next;+ });+ },+ [navTiles.length],+ );++ const handleKeyDown = useCallback(+ (event: React.KeyboardEvent<HTMLInputElement>) => {+ // A Chinese IME confirms candidates with Enter and moves with arrows; the+ // panel must not open a tile while a composition is still in progress.+ if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) {+ return;+ }+ if (event.key === "Escape") {+ event.preventDefault();+ void api.dismissPluginLauncher();+ return;+ }+ if (event.key === "Enter") {+ if (!navTiles.length) return;+ event.preventDefault();+ void openTile(navTiles[activeIndex]);+ return;+ }+ if (event.key === "ArrowDown") {+ event.preventDefault();+ moveActive(LAUNCHER_COLUMNS);+ return;+ }+ if (event.key === "ArrowUp") {+ event.preventDefault();+ moveActive(-LAUNCHER_COLUMNS);+ return;+ }+ if (event.key === "ArrowRight") {+ event.preventDefault();+ moveActive(1);+ return;+ }+ if (event.key === "ArrowLeft") {+ event.preventDefault();+ moveActive(-1);+ }+ },+ [activeIndex, moveActive, navTiles, openTile],+ );++ const togglePin = useCallback((tile: LauncherTile) => {+ const pinned = store.pins.includes(tile.id);+ setStore(setLauncherPinned(tile.id, !pinned));+ }, [store.pins]);++ const saveAliases = useCallback((tile: LauncherTile, aliases: string[]) => {+ setStore(setLauncherAliases(tile.id, aliases));+ }, []);const emptyText = loading? t("pluginLauncher.loading")- : query.trim()+ : searching? t("pluginLauncher.noResults")- : t("pluginLauncher.empty");+ : catalog?.appsScanning+ ? t("pluginLauncher.scanningApps")+ : t("pluginLauncher.empty");++ const expandLabel = (section: LauncherSection) =>+ t("pluginLauncher.expandRecent", { count: section.total });return (<main className="plugin-launcher" aria-label={t("pluginLauncher.title")}>@@ -160,37 +372,13 @@ export function PluginLauncher() {autoCapitalize="off"spellCheck={false}role="combobox"- aria-expanded={results.length > 0}+ aria-expanded={navTiles.length > 0}aria-controls="plugin-launcher-results"aria-activedescendant={- results[highlighted]- ? `plugin-launcher-option-${results[highlighted].id}`- : undefined+ navTiles[activeIndex] ? optionId(navTiles[activeIndex].id) : undefined}onChange={(event) => setQuery(event.target.value)}- onKeyDown={(event) => {- if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) {- return;- }- if (event.key === "Escape") {- event.preventDefault();- void api.dismissPluginLauncher();- return;- }- if (!results.length) return;- if (event.key === "ArrowDown" || event.key === "ArrowUp") {- event.preventDefault();- const delta = event.key === "ArrowDown" ? 1 : -1;- setHighlighted(- (current) => (current + delta + results.length) % results.length,- );- return;- }- if (event.key === "Enter") {- event.preventDefault();- void openPlugin(results[highlighted]);- }- }}+ onKeyDown={handleKeyDown}/><span className="plugin-launcher-shortcut" aria-hidden>{window.piDesktop?.platform === "darwin" ? "⌥ Space" : "Alt + Space"}@@ -199,34 +387,79 @@ export function PluginLauncher() {<divid="plugin-launcher-results"- className="plugin-launcher-results"+ className={`plugin-launcher-results${expanded ? " expanded" : ""}`}role="listbox"+ aria-label={t("pluginLauncher.results")}>- {results.length ? (- results.map((plugin, index) => (- <button- id={`plugin-launcher-option-${plugin.id}`}- key={plugin.id}- type="button"- role="option"- aria-selected={highlighted === index}- className={`plugin-launcher-option${- highlighted === index ? " active" : ""- }`}+ {searching ? (+ matchSection.tiles.length ? (+ <LauncherSectionGrid+ title={t("pluginLauncher.matches")}+ section={matchSection}+ startIndex={0}+ activeIndex={activeIndex}+ disabled={openingId !== null}+ onOpen={(tile) => void openTile(tile)}+ onMenu={setMenuTile}+ action={+ matchSection.total > matchSection.tiles.length+ ? {+ label: t("pluginLauncher.overflow", {+ count: matchSection.total - matchSection.tiles.length,+ }),+ title: t("pluginLauncher.overflowHint"),+ onSelect: () => undefined,+ }+ : undefined+ }+ />+ ) : (+ <div className="plugin-launcher-empty" role="status">+ <IconPlug size={20} aria-hidden />+ <span>{emptyText}</span>+ </div>+ )+ ) : recentSection.tiles.length || pinnedSection.tiles.length ? (+ <>+ <LauncherSectionGrid+ title={t("pluginLauncher.recent")}+ section={recentSection}+ startIndex={0}+ activeIndex={activeIndex}+ disabled={openingId !== null}+ onOpen={(tile) => void openTile(tile)}+ onMenu={setMenuTile}+ action={+ recentSection.total > recentSection.tiles.length || expanded+ ? {+ label: expanded+ ? t("pluginLauncher.collapse")+ : expandLabel(recentSection),+ title: t("pluginLauncher.recent"),+ onSelect: () => setExpanded((current) => !current),+ }+ : undefined+ }+ />+ <LauncherSectionGrid+ title={t("pluginLauncher.pinned")}+ section={pinnedSection}+ startIndex={recentSection.tiles.length}+ activeIndex={activeIndex}disabled={openingId !== null}- onPointerMove={() => setHighlighted(index)}- onClick={() => void openPlugin(plugin)}- >- <span className="plugin-launcher-monogram" aria-hidden>- {monogram(plugin.name)}- </span>- <span className="plugin-launcher-option-copy">- <strong>{plugin.name}</strong>- <span>{plugin.description || plugin.id}</span>- </span>- <IconArrowUpRight size={15} aria-hidden />- </button>- ))+ onOpen={(tile) => void openTile(tile)}+ onMenu={setMenuTile}+ action={+ pinnedSection.total > pinnedSection.tiles.length+ ? {+ label: t("pluginLauncher.showAll"),+ title: t("pluginLauncher.pinned"),+ onSelect: () => setExpanded(true),+ }+ : undefined+ }+ />+ </>) : (<div className="plugin-launcher-empty" role="status"><IconPlug size={20} aria-hidden />@@ -241,6 +474,17 @@ export function PluginLauncher() {<span>{t("pluginLauncher.dismissHint")}</span>{error ? <strong role="alert">{error}</strong> : null}</footer>++ {menuTile ? (+ <LauncherItemMenu+ tile={menuTile}+ pinned={store.pins.includes(menuTile.id)}+ aliases={store.aliases[menuTile.id] ?? []}+ onClose={() => setMenuTile(null)}+ onTogglePin={() => togglePin(menuTile)}+ onSaveAliases={(aliases) => saveAliases(menuTile, aliases)}+ />+ ) : null}</section></main>);diff --git a/apps/desktop/src/components/launcher/LauncherItemMenu.tsx b/apps/desktop/src/components/launcher/LauncherItemMenu.tsxnew file mode 100644index 000000000..da8bd3b23--- /dev/null+++ b/apps/desktop/src/components/launcher/LauncherItemMenu.tsx@@ -0,0 +1,121 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import type { LauncherTile } from "../../lib/launcher-search";++/**+ * Per-tile actions the panel cannot show as tiles: pin or unpin the item, and+ * teach the launcher a second name for it.+ *+ * The alias is what makes tools the host cannot guess ("微信" for WeChat) findable+ * by the word the user actually types, so it is edited inline here rather than in+ * a settings page (issue #2085 §4).+ */+export function LauncherItemMenu({+ tile,+ pinned,+ aliases,+ onClose,+ onTogglePin,+ onSaveAliases,+}: {+ tile: LauncherTile;+ pinned: boolean;+ aliases: string[];+ onClose: () => void;+ onTogglePin: () => void;+ onSaveAliases: (aliases: string[]) => void;+}) {+ const { t } = useTranslation();+ const [alias, setAlias] = useState(aliases.join(" "));+ const inputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ inputRef.current?.focus();+ }, []);++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ onClose();+ }+ };+ window.addEventListener("keydown", onKeyDown, true);+ return () => window.removeEventListener("keydown", onKeyDown, true);+ }, [onClose]);++ const commit = () => {+ onSaveAliases(+ alias+ .split(/\s+/)+ .map((entry) => entry.trim())+ .filter(Boolean),+ );+ onClose();+ };++ return (+ <>+ <div+ className="plugin-launcher-menu-backdrop"+ role="presentation"+ onClick={onClose}+ />+ <div className="plugin-launcher-menu" role="dialog" aria-label={tile.name}>+ <strong className="plugin-launcher-menu-title">{tile.name}</strong>+ <button+ type="button"+ className="plugin-launcher-menu-action"+ onClick={() => {+ onTogglePin();+ onClose();+ }}+ >+ {pinned ? t("pluginLauncher.unpin") : t("pluginLauncher.pin")}+ </button>+ <label className="plugin-launcher-menu-label" htmlFor="launcher-alias">+ {t("pluginLauncher.alias")}+ </label>+ <input+ id="launcher-alias"+ ref={inputRef}+ className="plugin-launcher-menu-input"+ value={alias}+ placeholder={t("pluginLauncher.aliasHint")}+ onChange={(event) => setAlias(event.target.value)}+ onKeyDown={(event) => {+ if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) {+ return;+ }+ if (event.key === "Enter") {+ event.preventDefault();+ commit();+ }+ }}+ />+ <div className="plugin-launcher-menu-row">+ <button+ type="button"+ className="plugin-launcher-menu-action"+ onClick={commit}+ >+ {t("pluginLauncher.aliasSave")}+ </button>+ {aliases.length ? (+ <button+ type="button"+ className="plugin-launcher-menu-action"+ onClick={() => {+ onSaveAliases([]);+ onClose();+ }}+ >+ {t("pluginLauncher.aliasClear")}+ </button>+ ) : null}+ </div>+ </div>+ </>+ );+}diff --git a/apps/desktop/src/components/launcher/LauncherTileButton.tsx b/apps/desktop/src/components/launcher/LauncherTileButton.tsxnew file mode 100644index 000000000..6ecc69c3a--- /dev/null+++ b/apps/desktop/src/components/launcher/LauncherTileButton.tsx@@ -0,0 +1,102 @@+import { useTranslation } from "react-i18next";+import type { LauncherTile } from "../../lib/launcher-search";++/**+ * The second line of a tile.+ *+ * It answers "why is this here": the reason the query matched, or, for a+ * trigger hit, the text the plugin is about to receive. The launcher shows one+ * line, so the text is truncated rather than wrapped — a wrapped line would+ * break the eight-column grid alignment the panel promises.+ */+function useTileDetail(tile: LauncherTile): string {+ const { t } = useTranslation();+ switch (tile.reason) {+ case "pattern":+ return t("pluginLauncher.reasonReceived", { value: tile.detail });+ case "name":+ return t("pluginLauncher.reasonName", { value: tile.detail });+ case "pinyin":+ return t("pluginLauncher.reasonPinyin", { value: tile.detail });+ case "initials":+ return t("pluginLauncher.reasonInitials", { value: tile.detail });+ case "alias":+ return t("pluginLauncher.reasonAlias", { value: tile.detail });+ case "description":+ return t("pluginLauncher.reasonDescription", { value: tile.detail });+ case "pinned":+ return t("pluginLauncher.reasonPinned");+ default:+ return t("pluginLauncher.reasonRecent");+ }+}++export function LauncherTileButton({+ tile,+ active,+ disabled,+ optionId,+ onOpen,+ onMenu,+}: {+ tile: LauncherTile;+ active: boolean;+ disabled: boolean;+ optionId: string;+ onOpen: () => void;+ onMenu: (target: { tile: LauncherTile; anchor: DOMRect }) => void;+}) {+ const { t } = useTranslation();+ const detail = useTileDetail(tile);+ const sourceLabel =+ tile.kind === "plugin"+ ? t("pluginLauncher.sourcePlugin")+ : t("pluginLauncher.sourceApp");+ const executable = tile.kind === "app" ? tile.executableName : undefined;++ return (+ <div className={`plugin-launcher-tile${active ? " active" : ""}`}>+ <button+ id={optionId}+ type="button"+ role="option"+ aria-selected={active}+ disabled={disabled}+ className="plugin-launcher-tile-open"+ title={`${tile.name} · ${sourceLabel}${executable ? ` · ${executable}` : ""} · ${detail}`}+ onClick={onOpen}+ >+ <span+ className={`plugin-launcher-icon plugin-launcher-icon-${tile.kind}`}+ aria-hidden+ >+ {tile.iconDataUrl ? (+ <img src={tile.iconDataUrl} alt="" draggable={false} />+ ) : (+ <span className="plugin-launcher-monogram">{tile.monogram}</span>+ )}+ </span>+ <span className="plugin-launcher-tile-name">{tile.name}</span>+ <span className="plugin-launcher-tile-detail">+ <span className="plugin-launcher-source">{sourceLabel}</span>+ <span className="plugin-launcher-detail-text">{detail}</span>+ </span>+ </button>+ <button+ type="button"+ tabIndex={-1}+ className="plugin-launcher-tile-menu"+ aria-label={t("pluginLauncher.menuOpen", { name: tile.name })}+ onClick={(event) => {+ event.stopPropagation();+ onMenu({+ tile,+ anchor: event.currentTarget.getBoundingClientRect(),+ });+ }}+ >+ ⋯+ </button>+ </div>+ );+}diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex cb003fc31..f69b1628a 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -60,9 +60,11 @@ import type {OnboardingState,OAuthLoginEvent,OAuthRespondInput,- OAuthStartResult,OAuthVendor,+ OAuthStartResult,PluginSummary,+ LauncherCatalog,+ LauncherOpenPluginRequest,PluginPermissionReview,PluginSettingDefinition,PluginServiceStatus,@@ -1506,6 +1508,12 @@ export const api = {openPluginPanel: (id: string) => invoke(IPC.invoke.pluginOpenPanel, id),togglePluginLauncher: () => invoke(IPC.invoke.pluginLauncherToggle),dismissPluginLauncher: () => invoke(IPC.invoke.pluginLauncherDismiss),+ /** Everything the launcher can show: launchable plugins plus installed apps. */+ launcherCatalog: () => invoke<LauncherCatalog>(IPC.invoke.pluginLauncherCatalog),+ launcherOpenApp: (appId: string) =>+ invoke(IPC.invoke.pluginLauncherOpenApp, { appId }),+ launcherOpenPlugin: (request: LauncherOpenPluginRequest) =>+ invoke(IPC.invoke.pluginOpenPanel, request),listPluginThemes: () => invoke<PluginTheme[]>(IPC.invoke.pluginThemes),listPluginProviderCatalog: () =>invoke<PluginProviderCatalogMeta[]>(IPC.invoke.pluginProviderCatalog),diff --git a/apps/desktop/src/lib/launcher-search.ts b/apps/desktop/src/lib/launcher-search.tsnew file mode 100644index 000000000..cdf989f58--- /dev/null+++ b/apps/desktop/src/lib/launcher-search.ts@@ -0,0 +1,394 @@+/**+ * Matching and ranking for the plugin launcher surface.+ *+ * Pure functions over the host-provided catalog plus the user's local store, so+ * every ordering rule here is unit-testable without a DOM: which tile wins, why+ * it won, how many matches there were, and which plugin (if any) receives the+ * typed input.+ *+ * Ranking, best first:+ * 0 declared trigger (whole-input regex match) — a plugin asking for `1+1`+ * outranks every name that merely contains `1`+ * 1 exact name 2 exact alias+ * 3 name prefix 4 pinyin prefix 5 initials prefix+ * 6 name substring 7 pinyin substring 8 alias substring 9 description+ * Ties break on recency, then plugins before applications, then name, then+ * catalog order — so the order is stable across renders.+ */+import {+ LAUNCHER_TRIGGER_INPUT_MAX_LENGTH,+ type LauncherAppEntry,+ type LauncherAppSource,+ type LauncherCatalog,+ type LauncherItemKind,+ type LauncherMatchReason,+ type LauncherPluginEntry,+ type LauncherTriggerMeta,+} from "@pi-desktop/shared";+import {+ launcherMonogram,+ launcherPinyinTokens,+ normalizeLauncherText,+} from "./launcher-text.ts";+import {+ launcherTriggerKey,+ type LauncherStoreSnapshot,+} from "./launcher-store.ts";++/** Tiles per grid row. */+export const LAUNCHER_COLUMNS = 8;+export const LAUNCHER_RECENT_ROWS = 2;+export const LAUNCHER_PINNED_ROWS = 1;+export const LAUNCHER_MATCH_ROWS = 3;+export const LAUNCHER_RECENT_TILES = LAUNCHER_COLUMNS * LAUNCHER_RECENT_ROWS;+export const LAUNCHER_PINNED_TILES = LAUNCHER_COLUMNS * LAUNCHER_PINNED_ROWS;+export const LAUNCHER_MATCH_TILES = LAUNCHER_COLUMNS * LAUNCHER_MATCH_ROWS;+++/** One grid cell. */+export type LauncherTile = {+ /** `plugin:<id>` or `app:<key>`. */+ id: string;+ kind: LauncherItemKind;+ name: string;+ /** Second line: how it matched, or what the plugin will receive. */+ detail: string;+ reason: LauncherMatchReason;+ monogram: string;+ iconDataUrl?: string;+ executableName?: string;+ appSource?: LauncherAppSource;+ pluginId?: string;+ trigger?: { id: string; payload: string };+};++type IndexedItem = {+ id: string;+ kind: LauncherItemKind;+ name: string;+ nameText: string;+ pinyin: string;+ initials: string;+ aliases: AliasKeys[];+ description?: string;+ descriptionText: string;+ iconDataUrl?: string;+ executableName?: string;+ appSource?: LauncherAppSource;+ pluginId?: string;+ triggers: LauncherTriggerMeta[];+ order: number;+};++/** One alias with every form the matcher compares against. */+type AliasKeys = {+ raw: string;+ text: string;+ pinyin: string;+ initials: string;+};++function aliasKeys(raw: string): AliasKeys {+ const tokens = launcherPinyinTokens(raw);+ return {+ raw,+ text: normalizeLauncherText(raw),+ pinyin: tokens.full,+ initials: tokens.initials,+ };+}++/** The first alias whose text, pinyin or initials satisfy `test`. */+function aliasHit(+ aliases: readonly AliasKeys[],+ test: (form: string) => boolean,+): AliasKeys | undefined {+ return aliases.find(+ (alias) => test(alias.text) || test(alias.pinyin) || test(alias.initials),+ );+}++/** A launchable item plus everything the matcher needs, computed once. */+export type LauncherIndex = {+ items: IndexedItem[];+ byId: Map<string, IndexedItem>;+};++function indexEntry(+ entry: LauncherPluginEntry | LauncherAppEntry,+ order: number,+ store: LauncherStoreSnapshot,+): IndexedItem {+ const aliases = (store.aliases[entry.id] ?? []).map(aliasKeys);+ const tokens = launcherPinyinTokens(entry.name);+ const triggers =+ entry.kind === "plugin"+ ? entry.triggers.filter(+ (trigger) =>+ !store.disabledTriggers.includes(+ launcherTriggerKey(entry.pluginId, trigger.id),+ ),+ )+ : [];+ return {+ id: entry.id,+ kind: entry.kind,+ name: entry.name,+ nameText: normalizeLauncherText(entry.name),+ pinyin: tokens.full,+ initials: tokens.initials,+ aliases,+ description: entry.kind === "plugin" ? entry.description : undefined,+ descriptionText: normalizeLauncherText(+ entry.kind === "plugin" ? (entry.description ?? "") : "",+ ),+ iconDataUrl: entry.kind === "app" ? entry.iconDataUrl : undefined,+ executableName: entry.kind === "app" ? entry.executableName : undefined,+ appSource: entry.kind === "app" ? entry.source : undefined,+ pluginId: entry.kind === "plugin" ? entry.pluginId : undefined,+ triggers,+ order,+ };+}++/**+ * Build the search index. Plugins the user hid from the launcher are left out+ * entirely; disabled triggers are already removed from each plugin's list.+ */+export function indexLauncherCatalog(+ catalog: LauncherCatalog,+ store: LauncherStoreSnapshot,+): LauncherIndex {+ const items: IndexedItem[] = [];+ catalog.plugins.forEach((plugin, index) => {+ if (store.disabledPlugins.includes(plugin.pluginId)) return;+ items.push(indexEntry(plugin, index, store));+ });+ catalog.apps.forEach((app, index) => {+ items.push(indexEntry(app, catalog.plugins.length + index, store));+ });+ return { items, byId: new Map(items.map((item) => [item.id, item])) };+}++function tile(+ item: IndexedItem,+ reason: LauncherMatchReason,+ detail: string,+ trigger?: { id: string; payload: string },+): LauncherTile {+ return {+ id: item.id,+ kind: item.kind,+ name: item.name,+ detail,+ reason,+ monogram: launcherMonogram(item.name),+ iconDataUrl: item.iconDataUrl,+ executableName: item.executableName,+ appSource: item.appSource,+ pluginId: item.pluginId,+ trigger,+ };+}++function recencyRank(store: LauncherStoreSnapshot): Map<string, number> {+ return new Map(store.recents.map((id, index) => [id, index]));+}++/** `{ tiles, total }` — `total` survives the grid cap so the panel can say how many. */+export type LauncherSection = {+ tiles: LauncherTile[];+ total: number;+};++function section(tiles: LauncherTile[], limit: number): LauncherSection {+ return { tiles: tiles.slice(0, limit), total: tiles.length };+}++function resolveIds(+ ids: readonly string[],+ index: LauncherIndex,+ reason: LauncherMatchReason,+): LauncherTile[] {+ const tiles: LauncherTile[] = [];+ for (const id of ids) {+ const item = index.byId.get(id);+ if (item) tiles.push(tile(item, reason, ""));+ }+ return tiles;+}++/** Recents section: two rows by default, with the true total reported. */+export function buildLauncherRecentSection(+ index: LauncherIndex,+ store: LauncherStoreSnapshot,+ limit: number = LAUNCHER_RECENT_TILES,+): LauncherSection {+ return section(resolveIds(store.recents, index, "recent"), limit);+}++/** Pinned section: one row by default. */+export function buildLauncherPinnedSection(+ index: LauncherIndex,+ store: LauncherStoreSnapshot,+ limit: number = LAUNCHER_PINNED_TILES,+): LauncherSection {+ return section(resolveIds(store.pins, index, "pinned"), limit);+}++const TRIGGER_PATTERN_MAX_LENGTH = 200;+const triggerCache = new Map<string, RegExp | null>();++function compileTrigger(trigger: LauncherTriggerMeta): RegExp | null {+ const key = `${trigger.flags ?? ""}/${trigger.pattern}`;+ if (triggerCache.has(key)) return triggerCache.get(key) ?? null;+ let compiled: RegExp | null = null;+ if (trigger.pattern.length <= TRIGGER_PATTERN_MAX_LENGTH) {+ try {+ compiled = new RegExp(trigger.pattern, trigger.flags);+ } catch {+ // The host validates patterns at load; a stale catalog entry is ignored+ // rather than allowed to throw on every keystroke.+ compiled = null;+ }+ }+ if (triggerCache.size > 512) triggerCache.clear();+ triggerCache.set(key, compiled);+ return compiled;+}++/**+ * Whole-input trigger match.+ *+ * The whole trimmed input must match — `includes` semantics would let a single+ * `1` summon every arithmetic plugin. Input longer than+ * `LAUNCHER_TRIGGER_INPUT_MAX_LENGTH` is never matched, so a pasted wall of text+ * costs one length check instead of a regex run.+ */+export function matchLauncherTrigger(+ trigger: LauncherTriggerMeta,+ input: string,+): string | null {+ if (!input || input.length > LAUNCHER_TRIGGER_INPUT_MAX_LENGTH) return null;+ const compiled = compileTrigger(trigger);+ if (!compiled) return null;+ const match = compiled.exec(input);+ if (!match || match[0] !== input) return null;+ return input;+}++type Scored = {+ item: IndexedItem;+ score: number;+ reason: LauncherMatchReason;+ detail: string;+ trigger?: { id: string; payload: string };+};++function queryTrimmed(query: string): string {+ return query.trim();+}++/**+ * The hit view: at most `LAUNCHER_MATCH_TILES` tiles, plus the number of matches+ * the grid had to drop so the footer can ask the user to keep typing.+ */+export function searchLauncherItems(+ index: LauncherIndex,+ query: string,+ store: LauncherStoreSnapshot,+): LauncherSection {+ const trimmed = queryTrimmed(query);+ if (!trimmed) return { tiles: [], total: 0 };+ const normalized = normalizeLauncherText(trimmed);+ const rank = recencyRank(store);+ const scored: Scored[] = [];+ for (const item of index.items) {+ const hit = scoreItemNormalized(item, normalized, trimmed);+ if (hit) scored.push(hit);+ }+ scored.sort(+ (left, right) =>+ left.score - right.score ||+ (rank.get(left.item.id) ?? rank.size) - (rank.get(right.item.id) ?? rank.size) ||+ kindRank(left.item.kind) - kindRank(right.item.kind) ||+ left.item.name.localeCompare(right.item.name) ||+ left.item.order - right.item.order,+ );+ return section(+ scored.map((hit) => tile(hit.item, hit.reason, hit.detail, hit.trigger)),+ LAUNCHER_MATCH_TILES,+ );+}++function kindRank(kind: LauncherItemKind): number {+ return kind === "plugin" ? 0 : 1;+}++function scoreItemNormalized(+ item: IndexedItem,+ normalized: string,+ raw: string,+): Scored | null {+ // Triggers compare against the raw input (a pattern may care about spaces or+ // case), name matching compares against the folded form.+ for (const trigger of item.triggers) {+ const payload = matchLauncherTrigger(trigger, raw);+ if (payload) {+ return {+ item,+ score: 0,+ reason: "pattern",+ detail: payload,+ trigger: { id: trigger.id, payload },+ };+ }+ }+ if (!normalized) return null;+ return scoreByName(item, normalized);+}++function scoreByName(item: IndexedItem, query: string): Scored | null {+ if (item.nameText === query) {+ return { item, score: 1, reason: "name", detail: item.name };+ }+ const exactAlias = aliasHit(item.aliases, (form) => form === query);+ if (exactAlias) {+ return { item, score: 2, reason: "alias", detail: exactAlias.raw };+ }+ if (item.nameText.startsWith(query)) {+ return { item, score: 3, reason: "name", detail: item.name };+ }+ const prefixAlias = aliasHit(item.aliases, (form) => form.startsWith(query));+ if (prefixAlias) {+ return { item, score: 3, reason: "alias", detail: prefixAlias.raw };+ }+ if (item.pinyin.startsWith(query)) {+ return { item, score: 4, reason: "pinyin", detail: item.pinyin };+ }+ if (item.initials.startsWith(query)) {+ return { item, score: 5, reason: "initials", detail: item.initials };+ }+ if (item.nameText.includes(query)) {+ return { item, score: 6, reason: "name", detail: item.name };+ }+ if (item.pinyin.includes(query)) {+ return { item, score: 7, reason: "pinyin", detail: item.pinyin };+ }+ if (item.initials.includes(query)) {+ return { item, score: 7, reason: "initials", detail: item.initials };+ }+ const partialAlias = aliasHit(item.aliases, (form) => form.includes(query));+ if (partialAlias) {+ return { item, score: 8, reason: "alias", detail: partialAlias.raw };+ }+ if (item.descriptionText.includes(query)) {+ return {+ item,+ score: 9,+ reason: "description",+ detail: item.description ?? "",+ };+ }+ return null;+}diff --git a/apps/desktop/src/lib/launcher-store.ts b/apps/desktop/src/lib/launcher-store.tsnew file mode 100644index 000000000..10223554b--- /dev/null+++ b/apps/desktop/src/lib/launcher-store.ts@@ -0,0 +1,284 @@+/**+ * Launcher preferences and usage history.+ *+ * These live in the renderer's `localStorage` rather than host-core: they are+ * presentation state for one floating panel (which tiles the user pinned, what+ * they typed an alias for, what they opened last), and both the launcher window+ * and the main window share one origin, so the plain web storage already+ * survives a restart and already notifies the other window through `storage`.+ *+ * Every read is defensive: storage can hold another version's payload, a+ * truncated write, or a hand-edited value, and none of those may break the+ * panel. Unreadable records are dropped, and the store only ever returns ids it+ * can still resolve against the live catalog (`pruneLauncherState`).+ */++const STATE_KEY = "pi.desktop.launcher.state";+/** Pre-existing plugin-only history; read once so upgrades keep the order. */+const LEGACY_HISTORY_KEY = "pi.desktop.pluginLaunchHistory";++/** Recency list cap. The panel shows 16 at a time but reports the total. */+export const LAUNCHER_RECENT_LIMIT = 60;+/** Pin cap, so a runaway script cannot grow the state file without bound. */+export const LAUNCHER_PIN_LIMIT = 24;+/** Aliases kept per item. */+export const LAUNCHER_ALIAS_LIMIT = 6;+/** Longest single alias, in characters. */+export const LAUNCHER_ALIAS_MAX_LENGTH = 32;+/** Items that may carry aliases. */+const LAUNCHER_ALIAS_ENTRY_LIMIT = 200;++export type LauncherStoreSnapshot = {+ /** Item ids, most recently used first. */+ recents: string[];+ /** Item ids in the order the user pinned them. */+ pins: string[];+ /** Item id -> user-authored search aliases. */+ aliases: Record<string, string[]>;+ /** Plugin ids the user hid from the launcher only. */+ disabledPlugins: string[];+ /** `<pluginId>::<triggerId>` entries the user switched off. */+ disabledTriggers: string[];+};++export type LauncherStorage = Pick<Storage, "getItem" | "setItem">;++export const EMPTY_LAUNCHER_STATE: LauncherStoreSnapshot = {+ recents: [],+ pins: [],+ aliases: {},+ disabledPlugins: [],+ disabledTriggers: [],+};++function defaultStorage(): LauncherStorage | null {+ try {+ return typeof globalThis !== "undefined" && "localStorage" in globalThis+ ? (globalThis.localStorage as LauncherStorage)+ : null;+ } catch {+ // A blocked or partitioned storage must not break the launcher.+ return null;+ }+}++function readRaw(storage: LauncherStorage | null, key: string): unknown {+ if (!storage) return null;+ try {+ const raw = storage.getItem(key);+ return raw ? (JSON.parse(raw) as unknown) : null;+ } catch {+ return null;+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function stringList(value: unknown, limit: number): string[] {+ if (!Array.isArray(value)) return [];+ const seen = new Set<string>();+ const out: string[] = [];+ for (const entry of value) {+ if (typeof entry !== "string") continue;+ const trimmed = entry.trim();+ if (!trimmed || seen.has(trimmed)) continue;+ seen.add(trimmed);+ out.push(trimmed);+ if (out.length >= limit) break;+ }+ return out;+}++/** Trigger ids are namespaced by plugin so one plugin cannot mute another. */+export function launcherTriggerKey(pluginId: string, triggerId: string): string {+ return `${pluginId}::${triggerId}`;+}++function sanitizeAliases(value: unknown): Record<string, string[]> {+ if (!isRecord(value)) return {};+ const out: Record<string, string[]> = {};+ let entries = 0;+ for (const [itemId, aliases] of Object.entries(value)) {+ if (entries >= LAUNCHER_ALIAS_ENTRY_LIMIT) break;+ if (!itemId.trim() || !Array.isArray(aliases)) continue;+ const cleaned = stringList(aliases, LAUNCHER_ALIAS_LIMIT)+ .map((alias) => alias.slice(0, LAUNCHER_ALIAS_MAX_LENGTH))+ .filter(Boolean);+ if (!cleaned.length) continue;+ out[itemId] = cleaned;+ entries += 1;+ }+ return out;+}++/** Legacy plugin-only history, translated to the launcher's item ids. */+function legacyRecents(storage: LauncherStorage | null): string[] {+ const parsed = readRaw(storage, LEGACY_HISTORY_KEY);+ if (!Array.isArray(parsed)) return [];+ const ordered = parsed+ .filter(+ (record): record is { id: string; usedAt: number } =>+ isRecord(record) &&+ typeof record.id === "string" &&+ typeof record.usedAt === "number",+ )+ .sort((left, right) => right.usedAt - left.usedAt);+ return stringList(+ ordered.map((record) => `plugin:${record.id}`),+ LAUNCHER_RECENT_LIMIT,+ );+}++export function readLauncherState(+ storage: LauncherStorage | null = defaultStorage(),+): LauncherStoreSnapshot {+ const stored = readRaw(storage, STATE_KEY);+ if (!isRecord(stored)) {+ // First run after an upgrade: keep the plugin history the old panel wrote.+ return { ...EMPTY_LAUNCHER_STATE, recents: legacyRecents(storage) };+ }+ const recents = stringList(stored.recents, LAUNCHER_RECENT_LIMIT);+ return {+ recents: recents.length ? recents : legacyRecents(storage),+ pins: stringList(stored.pins, LAUNCHER_PIN_LIMIT),+ aliases: sanitizeAliases(stored.aliases),+ disabledPlugins: stringList(stored.disabledPlugins, LAUNCHER_ALIAS_ENTRY_LIMIT),+ disabledTriggers: stringList(stored.disabledTriggers, LAUNCHER_ALIAS_ENTRY_LIMIT * 4),+ };+}++export function writeLauncherState(+ snapshot: LauncherStoreSnapshot,+ storage: LauncherStorage | null = defaultStorage(),+): void {+ if (!storage) return;+ try {+ storage.setItem(STATE_KEY, JSON.stringify(snapshot));+ } catch {+ // Best-effort: a full or blocked quota must not break launching.+ }+}++function updateLauncherState(+ mutate: (current: LauncherStoreSnapshot) => LauncherStoreSnapshot,+ storage: LauncherStorage | null = defaultStorage(),+): LauncherStoreSnapshot {+ const next = mutate(readLauncherState(storage));+ writeLauncherState(next, storage);+ return next;+}++/** Record an open, keeping one entry per item at the front of the list. */+export function rememberLauncherUse(+ itemId: string,+ storage: LauncherStorage | null = defaultStorage(),+): LauncherStoreSnapshot {+ if (!itemId) return readLauncherState(storage);+ return updateLauncherState(+ (current) => ({+ ...current,+ recents: [itemId, ...current.recents.filter((id) => id !== itemId)].slice(+ 0,+ LAUNCHER_RECENT_LIMIT,+ ),+ }),+ storage,+ );+}++export function setLauncherPinned(+ itemId: string,+ pinned: boolean,+ storage: LauncherStorage | null = defaultStorage(),+): LauncherStoreSnapshot {+ return updateLauncherState((current) => {+ const without = current.pins.filter((id) => id !== itemId);+ if (!pinned) return { ...current, pins: without };+ return { ...current, pins: [...without, itemId].slice(-LAUNCHER_PIN_LIMIT) };+ }, storage);+}++export function setLauncherAliases(+ itemId: string,+ aliases: string[],+ storage: LauncherStorage | null = defaultStorage(),+): LauncherStoreSnapshot {+ const cleaned = stringList(+ aliases.map((alias) => alias.trim().slice(0, LAUNCHER_ALIAS_MAX_LENGTH)),+ LAUNCHER_ALIAS_LIMIT,+ ).filter(Boolean);+ return updateLauncherState((current) => {+ const next = { ...current.aliases };+ if (cleaned.length) next[itemId] = cleaned;+ else delete next[itemId];+ return { ...current, aliases: next };+ }, storage);+}++export function setLauncherPluginDisabled(+ pluginId: string,+ disabled: boolean,+ storage: LauncherStorage | null = defaultStorage(),+): LauncherStoreSnapshot {+ return updateLauncherState((current) => {+ const without = current.disabledPlugins.filter((id) => id !== pluginId);+ return {+ ...current,+ disabledPlugins: disabled+ ? [...without, pluginId].slice(-LAUNCHER_ALIAS_ENTRY_LIMIT)+ : without,+ };+ }, storage);+}++export function setLauncherTriggerDisabled(+ pluginId: string,+ triggerId: string,+ disabled: boolean,+ storage: LauncherStorage | null = defaultStorage(),+): LauncherStoreSnapshot {+ const key = launcherTriggerKey(pluginId, triggerId);+ return updateLauncherState((current) => {+ const without = current.disabledTriggers.filter((entry) => entry !== key);+ return {+ ...current,+ disabledTriggers: disabled ? [...without, key] : without,+ };+ }, storage);+}++/**+ * Drop everything that names an item the catalog no longer offers, so an+ * uninstalled plugin or a removed application disappears from recents, pins and+ * aliases instead of leaving a tile that cannot open.+ */+export function pruneLauncherState(+ knownItemIds: Iterable<string>,+ storage: LauncherStorage | null = defaultStorage(),+): LauncherStoreSnapshot {+ const known = new Set(knownItemIds);+ const current = readLauncherState(storage);+ const aliases: Record<string, string[]> = {};+ for (const [itemId, value] of Object.entries(current.aliases)) {+ if (known.has(itemId)) aliases[itemId] = value;+ }+ const next: LauncherStoreSnapshot = {+ recents: current.recents.filter((id) => known.has(id)),+ pins: current.pins.filter((id) => known.has(id)),+ aliases,+ // Plugin ids stay: a disabled plugin keeps its preference across a reload+ // that momentarily reports it as not-ready.+ disabledPlugins: current.disabledPlugins,+ disabledTriggers: current.disabledTriggers,+ };+ if (+ next.recents.length !== current.recents.length ||+ next.pins.length !== current.pins.length ||+ Object.keys(next.aliases).length !== Object.keys(current.aliases).length+ ) {+ writeLauncherState(next, storage);+ }+ return next;+}diff --git a/apps/desktop/src/lib/launcher-text.ts b/apps/desktop/src/lib/launcher-text.tsnew file mode 100644index 000000000..a7dc38990--- /dev/null+++ b/apps/desktop/src/lib/launcher-text.ts@@ -0,0 +1,49 @@+/**+ * Text normalization shared by launcher matching and tile rendering.+ *+ * Kept separate from the matching rules so the normalization can be tested on+ * its own: every rule in `launcher-search.ts` compares normalized strings, and a+ * change here silently reorders every section.+ */+import { pinyin } from "pinyin-pro";++/**+ * Fold a display string into the comparable form the launcher matches with:+ * diacritics removed, lower-cased, and stripped of everything that is not a+ * letter or a number. `VS Code` and `vscode` therefore compare equal.+ */+export function normalizeLauncherText(value: string): string {+ return value+ .normalize("NFKD")+ .replace(/[\u0300-\u036f]/g, "")+ .toLocaleLowerCase()+ .replace(/[^\p{Letter}\p{Number}]+/gu, "");+}++/** Full pinyin and pinyin initials, both normalized. */+export function launcherPinyinTokens(value: string): {+ full: string;+ initials: string;+} {+ return {+ full: normalizeLauncherText(+ pinyin(value, { toneType: "none", type: "array" }).join(""),+ ),+ initials: normalizeLauncherText(+ pinyin(value, {+ pattern: "first",+ toneType: "none",+ type: "array",+ }).join(""),+ ),+ };+}++/**+ * One-character tile fallback for an item with no icon. Grapheme-aware enough+ * for the launcher's own labels: it takes the first code point, so an emoji or a+ * Chinese character is never split into half a surrogate pair.+ */+export function launcherMonogram(name: string): string {+ return Array.from(name.trim())[0]?.toLocaleUpperCase() ?? "?";+}diff --git a/apps/desktop/src/lib/plugin-launcher-history.ts b/apps/desktop/src/lib/plugin-launcher-history.tsdeleted file mode 100644index cbe2f30a2..000000000--- a/apps/desktop/src/lib/plugin-launcher-history.ts+++ /dev/null@@ -1,55 +0,0 @@-export type PluginLaunchRecord = {- id: string;- usedAt: number;-};--const KEY = "pi.desktop.pluginLaunchHistory";-const MAX = 24;--function historyStorage(): Storage | null {- try {- return typeof globalThis !== "undefined" && "localStorage" in globalThis- ? globalThis.localStorage- : null;- } catch {- return null;- }-}--export function loadPluginLaunchHistory(): PluginLaunchRecord[] {- const storage = historyStorage();- if (!storage) return [];- try {- const raw = storage.getItem(KEY);- if (!raw) return [];- const parsed = JSON.parse(raw) as unknown;- if (!Array.isArray(parsed)) return [];- return parsed- .filter(- (record): record is PluginLaunchRecord =>- Boolean(record) &&- typeof (record as PluginLaunchRecord).id === "string" &&- typeof (record as PluginLaunchRecord).usedAt === "number",- )- .sort((left, right) => right.usedAt - left.usedAt)- .slice(0, MAX);- } catch {- return [];- }-}--export function rememberPluginLaunch(id: string): PluginLaunchRecord[] {- const next = [- { id, usedAt: Date.now() },- ...loadPluginLaunchHistory().filter((record) => record.id !== id),- ].slice(0, MAX);- const storage = historyStorage();- if (storage) {- try {- storage.setItem(KEY, JSON.stringify(next));- } catch {- // History is best-effort; a blocked storage must not break launching.- }- }- return next;-}diff --git a/apps/desktop/src/lib/plugin-launcher-search.ts b/apps/desktop/src/lib/plugin-launcher-search.tsdeleted file mode 100644index 54944d1c4..000000000--- a/apps/desktop/src/lib/plugin-launcher-search.ts+++ /dev/null@@ -1,79 +0,0 @@-import { pinyin } from "pinyin-pro";-import type { PluginSummary } from "@pi-desktop/shared";--function normalizeSearchText(value: string): string {- return value- .normalize("NFKD")- .replace(/[\u0300-\u036f]/g, "")- .toLocaleLowerCase()- .replace(/[^\p{Letter}\p{Number}]+/gu, "");-}--function pinyinTokens(value: string): { full: string; initials: string } {- return {- full: normalizeSearchText(- pinyin(value, { toneType: "none", type: "array" }).join(""),- ),- initials: normalizeSearchText(- pinyin(value, {- pattern: "first",- toneType: "none",- type: "array",- }).join(""),- ),- };-}--export function isLaunchablePlugin(plugin: PluginSummary): boolean {- return Boolean(plugin.enabled && plugin.status === "ready" && plugin.ui?.panel);-}--export function searchLaunchablePlugins(- plugins: readonly PluginSummary[],- query: string,- recentIds?: readonly string[],-): PluginSummary[] {- const normalizedQuery = normalizeSearchText(query);- const recencyRank = new Map(recentIds?.map((id, index) => [id, index]) ?? []);- return plugins- .filter(isLaunchablePlugin)- .map((plugin, index) => {- const name = normalizeSearchText(plugin.name);- const id = normalizeSearchText(plugin.id);- const description = normalizeSearchText(plugin.description ?? "");- const romanized = pinyinTokens(plugin.name);- const score = !normalizedQuery- ? 0- : name === normalizedQuery || id === normalizedQuery- ? 1- : name.startsWith(normalizedQuery) || id.startsWith(normalizedQuery)- ? 2- : romanized.full.startsWith(normalizedQuery)- ? 3- : romanized.initials.startsWith(normalizedQuery)- ? 4- : name.includes(normalizedQuery) || id.includes(normalizedQuery)- ? 5- : romanized.full.includes(normalizedQuery) ||- romanized.initials.includes(normalizedQuery)- ? 6- : description.includes(normalizedQuery)- ? 7- : Number.POSITIVE_INFINITY;- return {- plugin,- score,- index,- recentRank: recencyRank.get(plugin.id) ?? recencyRank.size,- };- })- .filter((candidate) => Number.isFinite(candidate.score))- .sort(- (left, right) =>- left.score - right.score ||- left.recentRank - right.recentRank ||- left.plugin.name.localeCompare(right.plugin.name) ||- left.index - right.index,- )- .map(({ plugin }) => plugin);-}diff --git a/apps/desktop/src/styles/plugin-launcher.css b/apps/desktop/src/styles/plugin-launcher.cssindex 63d8e8e01..8599a9da2 100644--- a/apps/desktop/src/styles/plugin-launcher.css+++ b/apps/desktop/src/styles/plugin-launcher.css@@ -16,6 +16,7 @@ html[data-surface="plugin-launcher"] #root {}.plugin-launcher-surface {+ position: relative;width: 100%;min-height: 0;overflow: hidden;@@ -69,72 +70,205 @@ html[data-surface="plugin-launcher"] #root {.plugin-launcher-results {min-height: 0;+ overflow-y: auto;+ overflow-x: hidden;+ padding: 8px 12px 10px;+ display: flex;+ flex-direction: column;+ gap: 10px;+}++.plugin-launcher-group {+ min-width: 0;+}++.plugin-launcher-group-header {+ display: flex;+ align-items: center;+ gap: 10px;+ min-width: 0;+ padding: 0 2px 4px;+}++.plugin-launcher-group-header h2 {+ margin: 0;+ min-width: 0;overflow: hidden;- padding: 6px;+ color: var(--ds-text-muted);+ font-size: var(--text-xs);+ font-weight: var(--font-weight-medium-plus);+ letter-spacing: 0.02em;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.plugin-launcher-group-action {+ margin-left: auto;+ flex: 0 0 auto;+ border: 0;+ padding: 2px 4px;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--ds-text-faint);+ font-size: var(--text-xs);+ cursor: pointer;+}++.plugin-launcher-group-action:hover {+ color: var(--ds-text-primary);+ background: var(--ds-bg-hover);+}++/*+ * Eight fixed columns. Widening the window widens the tiles; it never reflows+ * them onto other rows, which is what keeps the grid stable while the user+ * drags the panel wider.+ */+.plugin-launcher-grid {+ display: grid;+ grid-template-columns: repeat(8, minmax(0, 1fr));+ gap: 6px;}-.plugin-launcher-option {+.plugin-launcher-tile {+ position: relative;+ min-width: 0;+}++.plugin-launcher-tile-open {width: 100%;min-width: 0;- height: 44px;display: flex;+ flex-direction: column;align-items: center;- gap: 10px;- padding: 5px 10px;+ gap: 4px;+ padding: 8px 4px 6px;+ border: 1px solid transparent;border-radius: var(--radius-md);+ background: transparent;color: var(--ds-text-secondary);- text-align: left;+ text-align: center;+ cursor: pointer;+}++.plugin-launcher-tile:hover .plugin-launcher-tile-open {+ background: var(--ds-bg-hover);+ color: var(--ds-text-primary);}-.plugin-launcher-option:hover,-.plugin-launcher-option.active {+.plugin-launcher-tile.active .plugin-launcher-tile-open {+ border-color: var(--ds-border-strong);background: var(--ds-bg-hover);color: var(--ds-text-primary);}-.plugin-launcher-option:focus-visible {+.plugin-launcher-tile-open:focus-visible {+ outline: 2px solid var(--ds-accent);outline-offset: -2px;}-.plugin-launcher-monogram {- width: 30px;- height: 30px;- flex: 0 0 30px;+/*+ * Shape is the fastest source signal: plugins are square, applications are+ * round. A plugin and an application with the same name stay distinguishable+ * without reading the tag line.+ */+.plugin-launcher-icon {+ width: 34px;+ height: 34px;+ flex: 0 0 34px;display: grid;place-items: center;- border-radius: var(--radius-sm);+ overflow: hidden;background: var(--ds-tile-deep);color: var(--ds-text-primary);+}++.plugin-launcher-icon-plugin {+ border-radius: var(--radius-sm);+}++.plugin-launcher-icon-app {+ border-radius: 50%;+}++.plugin-launcher-icon img {+ width: 24px;+ height: 24px;+ object-fit: contain;+ /** Native icons are already round or square; never stretch them. */+ pointer-events: none;+}++.plugin-launcher-monogram {font-size: var(--text-sm-plus);font-weight: var(--font-weight-semibold);+ line-height: 1;}-.plugin-launcher-option-copy {+.plugin-launcher-tile-name {+ width: 100%;min-width: 0;- flex: 1;- display: flex;- flex-direction: column;- gap: 1px;-}--.plugin-launcher-option-copy strong,-.plugin-launcher-option-copy span {overflow: hidden;+ color: inherit;+ font-size: var(--text-xs);+ font-weight: var(--font-weight-medium-plus);+ line-height: var(--leading-compact);text-overflow: ellipsis;white-space: nowrap;}-.plugin-launcher-option-copy strong {- color: var(--ds-text-primary);- font-size: var(--text-sm-plus);- font-weight: var(--font-weight-medium-plus);+.plugin-launcher-tile-detail {+ width: 100%;+ min-width: 0;+ display: flex;+ align-items: baseline;+ gap: 4px;+ overflow: hidden;+ color: var(--ds-text-faint);+ font-size: var(--text-2xs, 10px);line-height: var(--leading-compact);}-.plugin-launcher-option-copy span {+.plugin-launcher-source {+ flex: 0 0 auto;color: var(--ds-text-muted);+ opacity: 0.85;+}++.plugin-launcher-detail-text {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.plugin-launcher-tile-menu {+ position: absolute;+ top: 2px;+ right: 2px;+ width: 18px;+ height: 18px;+ display: grid;+ place-items: center;+ border: 0;+ border-radius: var(--radius-sm);+ background: transparent;+ color: var(--ds-text-faint);font-size: var(--text-xs);- line-height: var(--leading-compact);+ line-height: 1;+ opacity: 0;+ cursor: pointer;+}++.plugin-launcher-tile:hover .plugin-launcher-tile-menu,+.plugin-launcher-tile.active .plugin-launcher-tile-menu,+.plugin-launcher-tile:focus-within .plugin-launcher-tile-menu {+ opacity: 1;+}++.plugin-launcher-tile-menu:hover {+ background: var(--ds-tile-deep);+ color: var(--ds-text-primary);}.plugin-launcher-empty {@@ -170,10 +304,84 @@ html[data-surface="plugin-launcher"] #root {white-space: nowrap;}+.plugin-launcher-menu-backdrop {+ position: absolute;+ inset: 0;+ z-index: 2;+}++.plugin-launcher-menu {+ position: absolute;+ right: 14px;+ bottom: 46px;+ z-index: 3;+ width: 240px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ padding: 10px;+ border: 1px solid var(--ds-border-strong);+ border-radius: var(--radius-md);+ background: var(--ds-bg-elevated-opaque);+ box-shadow: var(--shadow-popover, none);+}++.plugin-launcher-menu-title {+ overflow: hidden;+ color: var(--ds-text-primary);+ font-size: var(--text-sm-plus);+ text-overflow: ellipsis;+ white-space: nowrap;+}++.plugin-launcher-menu-label {+ color: var(--ds-text-muted);+ font-size: var(--text-xs);+}++.plugin-launcher-menu-input {+ width: 100%;+ min-width: 0;+ padding: 6px 8px;+ border: 1px solid var(--ds-border-strong);+ border-radius: var(--radius-sm);+ background: var(--ds-tile-deep);+ color: var(--ds-text-primary);+ font-size: var(--text-sm);+ outline: 0;+}++.plugin-launcher-menu-input:focus-visible {+ border-color: var(--ds-accent);+}++.plugin-launcher-menu-row {+ display: flex;+ gap: 8px;+}++.plugin-launcher-menu-action {+ flex: 1;+ padding: 6px 8px;+ border: 1px solid var(--ds-border);+ border-radius: var(--radius-sm);+ background: var(--ds-tile);+ color: var(--ds-text-secondary);+ font-size: var(--text-xs);+ cursor: pointer;+}++.plugin-launcher-menu-action:hover {+ background: var(--ds-bg-hover);+ color: var(--ds-text-primary);+}+@media (prefers-reduced-motion: no-preference) {- .plugin-launcher-option {+ .plugin-launcher-tile-open,+ .plugin-launcher-tile-menu {transition:background-color 120ms ease,- color 120ms ease;+ color 120ms ease,+ opacity 120ms ease;}}diff --git a/apps/desktop/test/launcher-search.test.mjs b/apps/desktop/test/launcher-search.test.mjsnew file mode 100644index 000000000..951107741--- /dev/null+++ b/apps/desktop/test/launcher-search.test.mjs@@ -0,0 +1,251 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ LAUNCHER_COLUMNS,+ LAUNCHER_MATCH_TILES,+ LAUNCHER_PINNED_TILES,+ LAUNCHER_RECENT_TILES,+ buildLauncherPinnedSection,+ buildLauncherRecentSection,+ indexLauncherCatalog,+ matchLauncherTrigger,+ searchLauncherItems,+} from "../src/lib/launcher-search.ts";++const EMPTY_STORE = {+ recents: [],+ pins: [],+ aliases: {},+ disabledPlugins: [],+ disabledTriggers: [],+};++function plugin(id, name, extra = {}) {+ return {+ kind: "plugin",+ id: `plugin:${id}`,+ pluginId: id,+ name,+ triggers: [],+ ...extra,+ };+}++function app(key, name, extra = {}) {+ return {+ kind: "app",+ id: `app:${key}`,+ name,+ source: "start-menu",+ ...extra,+ };+}++function catalog(plugins = [], apps = []) {+ return { plugins, apps, appsScanning: false };+}++function search(items, query, store = EMPTY_STORE) {+ return searchLauncherItems(+ indexLauncherCatalog(items, store),+ query,+ store,+ );+}++test("the grid is 8 columns wide with the documented row budget", () => {+ assert.equal(LAUNCHER_COLUMNS, 8);+ assert.equal(LAUNCHER_RECENT_TILES, 16);+ assert.equal(LAUNCHER_PINNED_TILES, 8);+ assert.equal(LAUNCHER_MATCH_TILES, 24);+});++test("a declared trigger outranks a plugin whose name merely contains the input", () => {+ const items = catalog([+ plugin("calc.name-only", "1+1 helper"),+ plugin("calculator", "计算器", {+ triggers: [{ id: "expr", pattern: "^[0-9+\\-*/(). ]+$" }],+ }),+ ]);++ const result = search(items, "1+1");++ assert.equal(result.tiles[0].id, "plugin:calculator");+ assert.equal(result.tiles[0].reason, "pattern");+ assert.deepEqual(result.tiles[0].trigger, { id: "expr", payload: "1+1" });+});++test("trigger matching is a whole-input match, not contains", () => {+ const trigger = { id: "expr", pattern: "^[0-9]+$" };++ assert.equal(matchLauncherTrigger(trigger, "123"), "123");+ assert.equal(matchLauncherTrigger(trigger, "123+"), null);+ assert.equal(matchLauncherTrigger(trigger, " 123 "), null);+});++test("an input longer than the trigger budget never runs a declared pattern", () => {+ const trigger = { id: "expr", pattern: "^.*$" };+ const garbage = "乱".repeat(500);++ assert.equal(matchLauncherTrigger(trigger, garbage), null);+ const result = search(+ catalog([plugin("calculator", "计算器", { triggers: [trigger] })]),+ garbage,+ );+ assert.equal(result.total, 0);+});++test("an unusable pattern is ignored instead of throwing on every keystroke", () => {+ const result = search(+ catalog([+ plugin("broken", "Broken", { triggers: [{ id: "bad", pattern: "([a-z" }] }),+ ]),+ "1",+ );++ assert.deepEqual(result.tiles, []);+ assert.equal(result.total, 0);+});++test("Chinese names match by full pinyin and by initials", () => {+ const items = catalog([], [app("wechat", "微信")]);++ assert.equal(search(items, "weixin").tiles[0].id, "app:wechat");+ assert.equal(search(items, "weixin").tiles[0].reason, "pinyin");+ assert.equal(search(items, "wx").tiles[0].id, "app:wechat");+ assert.equal(search(items, "wx").tiles[0].reason, "initials");+ assert.equal(search(items, "微信").tiles[0].id, "app:wechat");+});++test("a user alias matches and reports that it was the alias", () => {+ const store = { ...EMPTY_STORE, aliases: { "app:wechat": ["聊天"] } };+ const items = catalog([], [app("wechat", "WeChat")]);++ const result = search(items, "liaotian", store);++ assert.equal(result.tiles[0].id, "app:wechat");+ assert.equal(result.tiles[0].reason, "alias");+ assert.equal(result.tiles[0].detail, "聊天");+});++test("same-named plugin and application both appear, plugins first", () => {+ const items = catalog(+ [plugin("calculator", "计算器")],+ [app("calculator-app", "计算器")],+ );++ const result = search(items, "计算器");++ assert.equal(result.total, 2);+ assert.deepEqual(+ result.tiles.map((tile) => tile.kind),+ ["plugin", "app"],+ );+});++test("matches past the 3-row budget are counted but not rendered", () => {+ const apps = Array.from({ length: 30 }, (_, index) =>+ app(`app-${index}`, `Tool ${index}`),+ );++ const result = search(catalog([], apps), "tool");++ assert.equal(result.tiles.length, 24);+ assert.equal(result.total, 30);+});++test("a description-only match ranks last", () => {+ const items = catalog([+ plugin("notes", "Notes", { description: "Write markdown" }),+ plugin("markdown", "Markdown"),+ ]);++ const result = search(items, "markdown");++ assert.equal(result.tiles[0].id, "plugin:markdown");+ assert.equal(result.tiles[1].id, "plugin:notes");+ assert.equal(result.tiles[1].reason, "description");+});++test("recents report their real total while the grid shows two rows", () => {+ const apps = Array.from({ length: 20 }, (_, index) =>+ app(`app-${index}`, `App ${index}`),+ );+ const store = {+ ...EMPTY_STORE,+ recents: apps.map((entry) => entry.id),+ };++ const section = buildLauncherRecentSection(+ indexLauncherCatalog(catalog([], apps), store),+ store,+ );++ assert.equal(section.tiles.length, 16);+ assert.equal(section.total, 20);+ assert.equal(section.tiles[0].reason, "recent");+});++test("pins show one row and keep the pin order", () => {+ const apps = [app("a", "A"), app("b", "B"), app("c", "C")];+ const store = { ...EMPTY_STORE, pins: ["app:c", "app:a", "app:b"] };++ const section = buildLauncherPinnedSection(+ indexLauncherCatalog(catalog([], apps), store),+ store,+ );++ assert.deepEqual(+ section.tiles.map((tile) => tile.id),+ ["app:c", "app:a", "app:b"],+ );+ assert.equal(section.tiles[0].reason, "pinned");+});++test("a plugin the user hid from the launcher is not searchable", () => {+ const items = catalog([plugin("noisy", "Noisy"), plugin("quiet", "Quiet")]);+ const store = { ...EMPTY_STORE, disabledPlugins: ["noisy"] };++ const result = search(items, "no", store);++ assert.deepEqual(+ result.tiles.map((tile) => tile.id),+ [],+ );+ assert.equal(search(items, "quiet", store).tiles.length, 1);+});++test("a disabled trigger no longer claims the input", () => {+ const items = catalog([+ plugin("calculator", "计算器", {+ triggers: [{ id: "expr", pattern: "^[0-9+]+$" }],+ }),+ ]);+ const store = { ...EMPTY_STORE, disabledTriggers: ["calculator::expr"] };++ const result = search(items, "1+1", store);++ assert.equal(+ result.tiles.every((tile) => tile.reason !== "pattern"),+ true,+ );+});++test("recency breaks a tie between equal matches", () => {+ const items = catalog([plugin("alpha", "Tool A"), plugin("beta", "Tool B")]);+ const store = { ...EMPTY_STORE, recents: ["plugin:beta"] };++ const noHistory = search(items, "tool");+ const withHistory = search(items, "tool", store);++ assert.equal(noHistory.tiles[0].id, "plugin:alpha");+ assert.equal(withHistory.tiles[0].id, "plugin:beta");+});++test("an empty query produces no hit tiles", () => {+ const result = search(catalog([plugin("alpha", "Alpha")]), " ");++ assert.equal(result.tiles.length, 0);+ assert.equal(result.total, 0);+});diff --git a/apps/desktop/test/launcher-store.test.mjs b/apps/desktop/test/launcher-store.test.mjsnew file mode 100644index 000000000..79dd5418a--- /dev/null+++ b/apps/desktop/test/launcher-store.test.mjs@@ -0,0 +1,221 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ EMPTY_LAUNCHER_STATE,+ LAUNCHER_ALIAS_LIMIT,+ LAUNCHER_RECENT_LIMIT,+ launcherTriggerKey,+ pruneLauncherState,+ readLauncherState,+ rememberLauncherUse,+ setLauncherAliases,+ setLauncherPinned,+ setLauncherPluginDisabled,+ setLauncherTriggerDisabled,+} from "../src/lib/launcher-store.ts";++const STATE_KEY = "pi.desktop.launcher.state";+const LEGACY_KEY = "pi.desktop.pluginLaunchHistory";++function fakeStorage(initial = {}) {+ const map = new Map(Object.entries(initial));+ return {+ map,+ getItem(key) {+ return map.has(key) ? map.get(key) : null;+ },+ setItem(key, value) {+ map.set(key, String(value));+ },+ };+}++function withStorage(storage, run) {+ const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage");+ Object.defineProperty(globalThis, "localStorage", {+ value: storage,+ configurable: true,+ writable: true,+ });+ try {+ return run();+ } finally {+ if (previous) Object.defineProperty(globalThis, "localStorage", previous);+ else delete globalThis.localStorage;+ }+}++test("plugin history written by the previous panel survives the upgrade", () => {+ const storage = fakeStorage({+ [LEGACY_KEY]: JSON.stringify([+ { id: "pi.file-manager", usedAt: 200 },+ { id: "pi.browser", usedAt: 100 },+ ]),+ });++ const state = withStorage(storage, () => readLauncherState());++ assert.deepEqual(state.recents, ["plugin:pi.file-manager", "plugin:pi.browser"]);+});++test("an empty store reports nothing pinned or disabled", () => {+ const state = withStorage(fakeStorage(), () => readLauncherState());++ assert.deepEqual(state.pins, []);+ assert.deepEqual(state.aliases, {});+ assert.deepEqual(state.disabledPlugins, []);+ assert.deepEqual(state.disabledTriggers, []);+});++test("opening an item moves it to the front exactly once", () => {+ const storage = fakeStorage();++ withStorage(storage, () => {+ rememberLauncherUse("app:a");+ rememberLauncherUse("app:b");+ const state = rememberLauncherUse("app:a");++ assert.deepEqual(state.recents, ["app:a", "app:b"]);+ });+});++test("recents stay capped", () => {+ const storage = fakeStorage();++ withStorage(storage, () => {+ for (let index = 0; index < LAUNCHER_RECENT_LIMIT + 10; index += 1) {+ rememberLauncherUse(`app:${index}`);+ }+ const state = readLauncherState();++ assert.equal(state.recents.length, LAUNCHER_RECENT_LIMIT);+ assert.equal(state.recents[0], `app:${LAUNCHER_RECENT_LIMIT + 9}`);+ });+});++test("pinning is idempotent and unpinning removes the entry", () => {+ const storage = fakeStorage();++ withStorage(storage, () => {+ setLauncherPinned("app:a", true);+ setLauncherPinned("app:b", true);+ assert.deepEqual(setLauncherPinned("app:a", true).pins, ["app:b", "app:a"]);+ assert.deepEqual(setLauncherPinned("app:b", false).pins, ["app:a"]);+ });+});++test("aliases are trimmed, deduplicated and capped", () => {+ const storage = fakeStorage();+ const aliases = Array.from(+ { length: LAUNCHER_ALIAS_LIMIT + 4 },+ (_, index) => ` alias ${index} `,+ );++ withStorage(storage, () => {+ const state = setLauncherAliases("app:wechat", ["微信", "微信", ...aliases]);++ assert.deepEqual(state.aliases["app:wechat"], [+ "微信",+ ...aliases.slice(0, LAUNCHER_ALIAS_LIMIT - 1).map((alias) => alias.trim()),+ ]);+ });+});++test("clearing every alias drops the item key", () => {+ const storage = fakeStorage();++ withStorage(storage, () => {+ setLauncherAliases("app:wechat", ["微信"]);+ const state = setLauncherAliases("app:wechat", [" "]);++ assert.equal("app:wechat" in state.aliases, false);+ });+});++test("trigger preferences are namespaced by plugin", () => {+ const storage = fakeStorage();++ withStorage(storage, () => {+ const state = setLauncherTriggerDisabled("calculator", "expr", true);++ assert.deepEqual(state.disabledTriggers, [launcherTriggerKey("calculator", "expr")]);+ assert.deepEqual(+ setLauncherTriggerDisabled("calculator", "expr", false).disabledTriggers,+ [],+ );+ });+});++test("a plugin hidden from the launcher keeps that preference through pruning", () => {+ const storage = fakeStorage();++ withStorage(storage, () => {+ setLauncherPluginDisabled("noisy", true);+ const state = pruneLauncherState(["plugin:quiet"]);++ assert.deepEqual(state.disabledPlugins, ["noisy"]);+ });+});++test("pruning forgets recents, pins and aliases of items that are gone", () => {+ const storage = fakeStorage();++ withStorage(storage, () => {+ rememberLauncherUse("plugin:gone");+ rememberLauncherUse("app:kept");+ setLauncherPinned("plugin:gone", true);+ setLauncherAliases("plugin:gone", ["x"]);++ const state = pruneLauncherState(["app:kept"]);++ assert.deepEqual(state.recents, ["app:kept"]);+ assert.deepEqual(state.pins, []);+ assert.deepEqual(state.aliases, {});+ assert.deepEqual(readLauncherState().recents, ["app:kept"]);+ });+});++test("unreadable persisted state degrades to an empty store", () => {+ const storage = fakeStorage({ [STATE_KEY]: "{not json" });++ const state = withStorage(storage, () => readLauncherState());++ assert.deepEqual(state, EMPTY_LAUNCHER_STATE);+});++test("a wrong-shaped payload is sanitized instead of trusted", () => {+ const storage = fakeStorage({+ [STATE_KEY]: JSON.stringify({+ recents: ["app:a", 7, "app:a", ""],+ pins: "nope",+ aliases: { "app:a": ["ok", 5], " ": ["bad"] },+ disabledPlugins: null,+ disabledTriggers: ["calculator::expr", 1],+ }),+ });++ const state = withStorage(storage, () => readLauncherState());++ assert.deepEqual(state.recents, ["app:a"]);+ assert.deepEqual(state.pins, []);+ assert.deepEqual(state.aliases, { "app:a": ["ok"] });+ assert.deepEqual(state.disabledPlugins, []);+ assert.deepEqual(state.disabledTriggers, ["calculator::expr"]);+});++test("a storage that refuses writes does not break the launcher", () => {+ const storage = {+ getItem: () => null,+ setItem: () => {+ throw new Error("quota exceeded");+ },+ };++ const state = withStorage(storage, () => {+ rememberLauncherUse("app:a");+ return readLauncherState();+ });++ assert.deepEqual(state.recents, []);+});diff --git a/apps/desktop/test/plugin-launcher-history.test.mjs b/apps/desktop/test/plugin-launcher-history.test.mjsdeleted file mode 100644index 67df4a9d8..000000000--- a/apps/desktop/test/plugin-launcher-history.test.mjs+++ /dev/null@@ -1,90 +0,0 @@-import assert from "node:assert/strict";-import test from "node:test";-import {- loadPluginLaunchHistory,- rememberPluginLaunch,-} from "../src/lib/plugin-launcher-history.ts";--const KEY = "pi.desktop.pluginLaunchHistory";--function installStorage(values = new Map()) {- const previousStorage = globalThis.localStorage;- globalThis.localStorage = {- getItem(key) {- return values.get(key) ?? null;- },- setItem(key, value) {- values.set(key, String(value));- },- removeItem(key) {- values.delete(key);- },- clear() {- values.clear();- },- key() {- return null;- },- get length() {- return values.size;- },- };- return { values, restore: () => (globalThis.localStorage = previousStorage) };-}--test("remembering a plugin moves it to the front and deduplicates", () => {- const { restore } = installStorage();- try {- rememberPluginLaunch("mail");- rememberPluginLaunch("canvas");- rememberPluginLaunch("mail");- assert.deepEqual(loadPluginLaunchHistory().map((record) => record.id), [- "mail",- "canvas",- ]);- assert.deepEqual(- JSON.parse(globalThis.localStorage.getItem(KEY)).map((record) => record.id),- ["mail", "canvas"],- );- } finally {- restore();- }-});--test("history is bounded and sorted newest first", () => {- const { values, restore } = installStorage();- try {- const ids = Array.from({ length: 30 }, (_, index) => `plugin-${index}`);- for (const id of ids) rememberPluginLaunch(id);- assert.deepEqual(- loadPluginLaunchHistory().map((record) => record.id),- ids.slice(-24).reverse(),- );- assert.equal(JSON.parse(values.get(KEY)).length, 24);- } finally {- restore();- }-});--test("history tolerates corrupted storage and missing localStorage", () => {- const { values, restore } = installStorage();- try {- values.set(KEY, "{not json");- assert.deepEqual(loadPluginLaunchHistory(), []);- values.set(KEY, JSON.stringify([{ id: 42 }, null, { id: "ok", usedAt: 1 }]));- assert.deepEqual(loadPluginLaunchHistory(), [{ id: "ok", usedAt: 1 }]);- } finally {- restore();- }-- const previousStorage = globalThis.localStorage;- globalThis.localStorage = undefined;- try {- assert.deepEqual(loadPluginLaunchHistory(), []);- assert.deepEqual(rememberPluginLaunch("mail").map((record) => record.id), [- "mail",- ]);- } finally {- globalThis.localStorage = previousStorage;- }-});diff --git a/apps/desktop/test/plugin-launcher-search.test.mjs b/apps/desktop/test/plugin-launcher-search.test.mjsdeleted file mode 100644index f3cd9886e..000000000--- a/apps/desktop/test/plugin-launcher-search.test.mjs+++ /dev/null@@ -1,91 +0,0 @@-import assert from "node:assert/strict";-import test from "node:test";-import {- isLaunchablePlugin,- searchLaunchablePlugins,-} from "../src/lib/plugin-launcher-search.ts";--function plugin(id, name, extra = {}) {- return {- id,- name,- version: "1.0.0",- enabled: true,- source: "installed",- status: "ready",- permissions: [],- ui: { panel: { entry: "dist/panel.html" } },- ...extra,- };-}--const plugins = [- plugin("canvas", "无限画布", { description: "Create visual workflows" }),- plugin("mail", "邮件助手"),- plugin("disabled", "无限插件", { enabled: false, status: "disabled" }),- plugin("broken", "坏插件", { status: "error" }),- plugin("headless", "后台服务", { ui: undefined }),-];--test("launcher searches Chinese plugin names by Chinese, pinyin, and initials", () => {- assert.deepEqual(searchLaunchablePlugins(plugins, "画布").map((item) => item.id), [- "canvas",- ]);- assert.deepEqual(searchLaunchablePlugins(plugins, "wuxianhuabu").map((item) => item.id), [- "canvas",- ]);- assert.deepEqual(searchLaunchablePlugins(plugins, "wxhb").map((item) => item.id), [- "canvas",- ]);-});--test("launcher searches ids and excludes plugins that cannot open a panel", () => {- assert.equal(isLaunchablePlugin(plugins[0]), true);- assert.equal(isLaunchablePlugin(plugins[2]), false);- assert.equal(isLaunchablePlugin(plugins[3]), false);- assert.equal(isLaunchablePlugin(plugins[4]), false);- assert.deepEqual(searchLaunchablePlugins(plugins, "mail").map((item) => item.id), [- "mail",- ]);- assert.deepEqual(searchLaunchablePlugins(plugins, "").map((item) => item.id), [- "canvas",- "mail",- ]);-});--test("launcher orders an empty query by most recent use", () => {- assert.deepEqual(- searchLaunchablePlugins(plugins, "", ["mail", "canvas"]).map((item) => item.id),- ["mail", "canvas"],- );- assert.deepEqual(- searchLaunchablePlugins(plugins, "", ["mail"]).map((item) => item.id),- ["mail", "canvas"],- );-});--test("launcher keeps search relevance ahead of recency", () => {- assert.deepEqual(- searchLaunchablePlugins(plugins, "wuxianhuabu", ["mail"]).map((item) => item.id),- ["canvas"],- );- assert.deepEqual(- searchLaunchablePlugins(plugins, "邮件", ["canvas"]).map((item) => item.id),- ["mail"],- );-});--test("launcher uses recency as a tiebreaker between equal matches", () => {- const tie = [- plugin("alpha", "Alpha Plugin"),- plugin("beta", "Beta Plugin"),- ];- assert.deepEqual(- searchLaunchablePlugins(tie, "", ["beta", "alpha"]).map((item) => item.id),- ["beta", "alpha"],- );- assert.deepEqual(- searchLaunchablePlugins(tie, "", ["alpha"]).map((item) => item.id),- ["alpha", "beta"],- );-});diff --git a/apps/desktop/test/plugin-launcher-state.test.mjs b/apps/desktop/test/plugin-launcher-state.test.mjsnew file mode 100644index 000000000..e185dc9a8--- /dev/null+++ b/apps/desktop/test/plugin-launcher-state.test.mjs@@ -0,0 +1,116 @@+import assert from "node:assert/strict";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++import {+ PLUGIN_LAUNCHER_DEFAULT_HEIGHT,+ PLUGIN_LAUNCHER_DEFAULT_WIDTH,+ PLUGIN_LAUNCHER_MAX_WIDTH,+ PLUGIN_LAUNCHER_MIN_HEIGHT,+ PLUGIN_LAUNCHER_MIN_WIDTH,+ PLUGIN_LAUNCHER_STATE_FILE,+ parseLauncherWindowState,+ readLauncherWindowState,+ resolveLauncherBounds,+ writeLauncherWindowState,+} from "../electron/main/plugin-launcher-state.ts";++const WORK_AREA = { x: 0, y: 0, width: 1920, height: 1040 };++function withTempDir(run) {+ const dir = mkdtempSync(join(tmpdir(), "pi-launcher-state-"));+ try {+ return run(dir);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++test("a missing state file means the panel opens at its default size", () => {+ withTempDir((dir) => {+ assert.equal(readLauncherWindowState(dir), null);+ const bounds = resolveLauncherBounds(null, WORK_AREA);+ assert.equal(bounds.width, PLUGIN_LAUNCHER_DEFAULT_WIDTH);+ assert.equal(bounds.height, PLUGIN_LAUNCHER_DEFAULT_HEIGHT);+ });+});++test("the window cannot be persisted narrower than the eight-column floor", () => {+ const state = parseLauncherWindowState({ width: 120, height: 100 });++ assert.equal(state.width, PLUGIN_LAUNCHER_MIN_WIDTH);+ assert.equal(state.height, PLUGIN_LAUNCHER_MIN_HEIGHT);+});++test("an oversized remembered width is clamped", () => {+ const state = parseLauncherWindowState({ width: 5000, height: 5000 });++ assert.equal(state.width, PLUGIN_LAUNCHER_MAX_WIDTH);+});++test("a payload without a usable size is not remembered", () => {+ assert.equal(parseLauncherWindowState(null), null);+ assert.equal(parseLauncherWindowState("760x440"), null);+ assert.equal(parseLauncherWindowState({ width: "wide", height: 440 }), null);+});++test("a remembered position inside the work area is kept", () => {+ const bounds = resolveLauncherBounds(+ { width: 800, height: 500, x: 100, y: 120 },+ WORK_AREA,+ );++ assert.deepEqual(bounds, { x: 100, y: 120, width: 800, height: 500 });+});++test("a remembered position on a display that is gone falls back to centre", () => {+ const bounds = resolveLauncherBounds(+ { width: 800, height: 500, x: 4000, y: 3000 },+ WORK_AREA,+ );++ assert.equal(bounds.x, Math.round((WORK_AREA.width - 800) / 2));+ assert.equal(bounds.y, Math.round((WORK_AREA.height - 500) / 2));+});++test("a remembered size larger than the work area is reduced to fit", () => {+ const bounds = resolveLauncherBounds(+ { width: 1280, height: 940 },+ { x: 0, y: 0, width: 1000, height: 700 },+ );++ assert.equal(bounds.width, 1000);+ assert.equal(bounds.height, 700);+});++test("the size survives a write and read round trip", () => {+ withTempDir((dir) => {+ writeLauncherWindowState(dir, { x: 40, y: 60, width: 900, height: 620 });++ assert.deepEqual(readLauncherWindowState(dir), {+ width: 900,+ height: 620,+ x: 40,+ y: 60,+ });+ });+});++test("an unreadable state file degrades to no remembered size", () => {+ withTempDir((dir) => {+ writeFileSync(join(dir, PLUGIN_LAUNCHER_STATE_FILE), "{not json", "utf8");++ assert.equal(readLauncherWindowState(dir), null);+ });+});++test("a write into a directory that does not exist does not throw", () => {+ assert.doesNotThrow(() =>+ writeLauncherWindowState(join(tmpdir(), "pi-launcher-missing-dir"), {+ width: 800,+ height: 500,+ }),+ );+});diff --git a/apps/desktop/test/plugin-launcher-window.test.mjs b/apps/desktop/test/plugin-launcher-window.test.mjsindex be9dcbd9d..c9c92b024 100644--- a/apps/desktop/test/plugin-launcher-window.test.mjs+++ b/apps/desktop/test/plugin-launcher-window.test.mjs@@ -58,14 +58,40 @@ test("launcher renderer supports keyboard selection and has no window controls",renderer,/rendererSurface === "plugin-launcher" \? \([\s\S]*?<ErrorBoundary>\s*<PluginLauncher \/>/,);+ // An IME composition never opens a tile: Enter confirms the candidate first.assert.match(launcher, /event\.nativeEvent\.isComposing/);- assert.match(launcher, /event\.key === "ArrowDown" \|\| event\.key === "ArrowUp"/);+ assert.match(launcher, /event\.nativeEvent\.keyCode === 229/);+ // Two-dimensional movement: rows move by the column count, tiles by one.+ assert.match(launcher, /event\.key === "ArrowDown"[\s\S]*moveActive\(LAUNCHER_COLUMNS\)/);+ assert.match(launcher, /event\.key === "ArrowUp"[\s\S]*moveActive\(-LAUNCHER_COLUMNS\)/);+ assert.match(launcher, /event\.key === "ArrowRight"[\s\S]*moveActive\(1\)/);+ assert.match(launcher, /event\.key === "ArrowLeft"[\s\S]*moveActive\(-1\)/);assert.match(launcher, /event\.key === "Enter"/);assert.match(launcher, /event\.key === "Escape"/);- assert.match(launcher, /api\.openPluginPanel\(plugin\.id\)/);+ // Opening goes through the launcher channels, which can carry a payload.+ assert.match(launcher, /api\.launcherOpenPlugin\(/);+ assert.match(launcher, /api\.launcherOpenApp\(/);assert.match(launcher, /loadPromiseRef/);assert.match(launcher, /inputRef\.current\?\.focus\(\)/);assert.doesNotMatch(launcher, /requestAnimationFrame\(\(\) => inputRef/);assert.doesNotMatch(launcher, /WindowControls|window-controls/);assert.match(styles, /html\[data-surface="plugin-launcher"\][\s\S]*background: transparent/);});++test("the launcher grid is eight fixed columns with square plugins and round apps", () => {+ assert.match(+ styles,+ /\.plugin-launcher-grid \{[\s\S]*grid-template-columns: repeat\(8, minmax\(0, 1fr\)\)/,+ );+ assert.match(styles, /\.plugin-launcher-icon-plugin \{[\s\S]*border-radius: var\(--radius-sm\)/);+ assert.match(styles, /\.plugin-launcher-icon-app \{[\s\S]*border-radius: 50%/);+});++test("the launcher window is resizable and remembers its size", () => {+ assert.match(main, /resizable: true/);+ assert.match(main, /minWidth: PLUGIN_LAUNCHER_MIN_WIDTH/);+ assert.match(main, /resolveLauncherBounds\(/);+ assert.match(main, /writeLauncherWindowState\(dataDir/);+ assert.match(main, /window\.on\("resize", \(\) => schedulePluginLauncherBounds/);+ assert.match(main, /window\.on\("move", \(\) => schedulePluginLauncherBounds/);+});diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex bbdea6855..3e5eb26bc 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -339,6 +339,8 @@ export const IPC = {pluginOpenPanel: "pi-desktop/plugin/openPanel",pluginLauncherToggle: "pi-desktop/pluginLauncher/toggle",pluginLauncherDismiss: "pi-desktop/pluginLauncher/dismiss",+ pluginLauncherCatalog: "pi-desktop/pluginLauncher/catalog",+ pluginLauncherOpenApp: "pi-desktop/pluginLauncher/openApp",pluginThemes: "pi-desktop/plugin/themes",pluginProviderCatalog: "pi-desktop/plugin/providerCatalog",pluginScenicThemesDestinations: "pi-desktop/plugin/scenicThemes/destinations",diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex a3bfbfef9..d46a40169 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -25,3 +25,4 @@ export * from "./types/speech.js";export * from "./types/remote-host.js";export * from "./types/config-sync.js";export * from "./types/live-voice.js";+export * from "./types/launcher.js";diff --git a/packages/shared/src/types/launcher.ts b/packages/shared/src/types/launcher.tsnew file mode 100644index 000000000..27135870e--- /dev/null+++ b/packages/shared/src/types/launcher.ts@@ -0,0 +1,118 @@+/**+ * Shared contract for the plugin launcher surface (`Alt+Space`).+ *+ * The launcher is its own renderer surface backed by one browser window, so the+ * main process owns every authoritative fact here: which plugins are launchable,+ * which OS applications the machine actually has, and what a click is allowed to+ * open. The renderer receives *display and matching* metadata and an opaque+ * item id — never an executable path, so it can only ask the host to launch an+ * item the host itself discovered (docs/spec/07-plugins/17-plugin-launcher.md).+ */++/** What a launcher tile opens. */+export type LauncherItemKind = "plugin" | "app";++/**+ * Why the launcher surfaced an item. Rendered as the tile's second line so the+ * user learns how they matched instead of guessing.+ */+export type LauncherMatchReason =+ | "name"+ | "pinyin"+ | "initials"+ | "alias"+ | "description"+ | "pattern"+ | "pinned"+ | "recent";++/** Where a discovered application came from, shown as its source tag. */+export type LauncherAppSource = "start-menu" | "app-bundle" | "desktop-entry";++/**+ * One regex a plugin declares in `contributes.launcherTriggers`.+ *+ * `pattern` is matched against the *whole* trimmed launcher input, so a plugin+ * that declares an arithmetic character class never competes with a+ * one-character query. The host validates the pattern at manifest load and+ * refuses constructs that can backtrack catastrophically (a nested quantifier+ * such as a repeated group over a repeated atom), so a bad declaration cannot+ * freeze the panel.+ */+export type LauncherTriggerMeta = {+ id: string;+ pattern: string;+ /** Declared flags, already filtered to `i` / `s` / `m` / `u`. */+ flags?: string;+ /** Author-facing label; resolved against the active locale by the host. */+ title?: string;+};++/** A launchable plugin as the launcher sees it. */+export type LauncherPluginEntry = {+ kind: "plugin";+ /** Opaque item id: `plugin:<pluginId>`. */+ id: string;+ pluginId: string;+ name: string;+ description?: string;+ /** Declared triggers that survived manifest validation. */+ triggers: LauncherTriggerMeta[];+};++/**+ * An installed application as the launcher sees it.+ *+ * Deliberately carries no path: `id` is resolved against the host's own scan+ * result when the user opens the tile, so a compromised renderer cannot use the+ * launcher to start an arbitrary program.+ */+export type LauncherAppEntry = {+ kind: "app";+ /** Opaque item id: `app:<stableKey>`. */+ id: string;+ name: string;+ /** Executable file name without extension, for the tile's source tag. */+ executableName?: string;+ source: LauncherAppSource;+ /** Small PNG data URL, when the platform could produce one. */+ iconDataUrl?: string;+};++/** Everything the launcher can show, in one payload. */+export type LauncherCatalog = {+ plugins: LauncherPluginEntry[];+ apps: LauncherAppEntry[];+ /**+ * True while the background application scan is still running, so the panel+ * can show "scanning" instead of an authoritative empty section.+ */+ appsScanning: boolean;+};++export type LauncherOpenAppRequest = {+ appId: string;+};++/**+ * Open a plugin panel from the launcher, optionally handing it the input that+ * triggered it. `payload` is delivered to the plugin exactly once, only to the+ * plugin the user chose (docs/spec/07-plugins/17-plugin-launcher.md §5).+ */+export type LauncherOpenPluginRequest = {+ pluginId: string;+ triggerId?: string;+ payload?: string;+};++/** The launch payload a plugin panel receives, as `pi.launcher.consume()`. */+export type PluginLauncherPayload = {+ triggerId: string;+ payload: string;+};++/** Longest payload the host forwards to a plugin; longer inputs are refused. */+export const LAUNCHER_PAYLOAD_MAX_LENGTH = 512;++/** Longest launcher input the renderer matches declared triggers against. */+export const LAUNCHER_TRIGGER_INPUT_MAX_LENGTH = 256;