App.tsx

76.5 KB · raw

1import { createEffect, createMemo, createSignal, For, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageSet } from "../shared/storage";4import { sendMessage } from "../shared/bridge";5import { ACCENT_COLORS } from "../shared/types";6import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";7import { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { NotesMode } from "./views/NotesMode";11import { ProCelebration } from "./views/ProCelebration";12import { VaultView, type SortOrder } from "./views/Vault";13import { EntryView } from "./views/Entry";14import { AddView } from "./views/Add";15import { PeachWordmark } from "./components/PeachMark";16import { PasskeyApprovalView } from "./views/PasskeyApproval";17import { extractDomain } from "../shared/domain";18import {19  syncIndicator,20  syncIndicatorLabel,21  type SyncOutcomeSummary,22} from "../shared/sync-outcome";23import { popupCopy } from "./copy";24import {25  DEFAULT_BINDINGS,26  formatKeybinding,27  getActiveBindings,28  matchKeybinding,29  SHORTCUT_DESCRIPTORS,30  type Keybinding,31  type ShortcutAction,32} from "../shared/shortcuts";33import { generateTOTP } from "../crypto/totp";34import { isNativePlatform, nativePlugin } from "../shared/native";3536export { sendMessage } from "../shared/bridge";3738const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));39const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));40const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));41const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));42const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));43const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));44const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));45const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));46const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));47const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));4849type View =50  | "lock"51  | "pro-celebration"52  | "entry"53  | "list"54  | "add"55  | "settings"56  | "pair-device"57  | "import"58  | "export"59  | "health"60  | "trash"61  | "panic"62  | "adopting"63  | "codex-generate"64  | "codex-restore";65type BootState = "loading" | "ready";6667const canarySuppressMap = new Map<string, boolean>();68let shellRingAnimation: Animation | null = null;6970export function isCanarySuppressed(entryId: string): boolean {71  return canarySuppressMap.get(entryId) ?? false;72}7374export function setCanarySuppressed(entryId: string, suppressed: boolean): void {75  canarySuppressMap.set(entryId, suppressed);76}7778export function clearCanarySuppressions(): void {79  canarySuppressMap.clear();80}8182export function triggerRing() {83  const shell = document.getElementById("hd-shell");84  if (!shell) return;8586  shellRingAnimation?.cancel();87  shell.dataset.glowing = "true";88  const animation = shell.animate(89    [90      { offset: 0, boxShadow: "var(--copy-shadow)" },91      {92        offset: 0.3,93        boxShadow:94          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",95      },96      { offset: 1, boxShadow: "var(--copy-shadow)" },97    ],98    {99      duration: 720,100      easing: "cubic-bezier(0.4, 0, 0.2, 1)",101      fill: "none",102    }103  );104  shellRingAnimation = animation;105  const clearGlow = () => {106    if (shellRingAnimation !== animation) return;107    shellRingAnimation = null;108    delete shell.dataset.glowing;109  };110  animation.onfinish = clearGlow;111  animation.oncancel = clearGlow;112}113114115export function triggerPipPulse() {116  const pip = document.querySelector(".peach-status-pip, .pip");117  if (pip) {118    pip.classList.remove("pulse");119    void (pip as HTMLElement).offsetWidth;120    pip.classList.add("pulse");121  }122}123124const ENTRY_TRANSITION_SETTLE_MS = 135;125126export default function App() {127  const [bootState, setBootState] = createSignal<BootState>("loading");128  const [view, setView] = createSignal<View>("lock");129  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,130  // CSS transition takes over for snap animation).131  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);132  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(133    "enter"134  );135  const [contentTransitioning, setContentTransitioning] = createSignal(false);136  const [hasVault, setHasVault] = createSignal(false);137  const [onboarded, setOnboarded] = createSignal(true);138  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);139  const [entries, setEntries] = createSignal<VaultEntry[]>([]);140  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);141  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);142143  // Rare device-trust alerts stay visible; routine entry sync is silent.144  interface SyncAlert {145    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";146    entryId: string;147    entryTitle: string;148    deviceName: string;149    timestamp: number;150  }151  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);152  async function loadSyncAlerts() {153    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {154      ok: boolean;155      data?: SyncAlert[];156    };157    if (r.ok && (r.data?.length ?? 0) > 0) {158      setSyncAlerts(r.data ?? []);159      // Acknowledge so a crash between read and render doesn't lose them —160      // they remain on screen until the user dismisses each.161      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });162    }163  }164  function dismissSyncAlert(index: number) {165    setSyncAlerts((arr) => arr.filter((_, i) => i !== index));166  }167  function syncAlertText(a: SyncAlert): string {168    if (a.type === "DEVICE_REVOKED") {169      return `${a.deviceName} revoked a paired device — review your devices in Settings`;170    }171    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;172  }173  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");174  const [theme, setTheme] = createSignal<"dark" | "light">("dark");175  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");176  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);177  const [lockOnClose, setLockOnClose] = createSignal(true);178  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);179  const [breachMonitoring, setBreachMonitoring] = createSignal(true);180  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);181  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);182  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);183  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);184  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);185  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");186  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");187  // Cached Pro status — synchronous for render paths. Background's188  // GET_LICENSE is async, but render-time reads of isPro() must not block.189  // Refreshed at boot, after activate/deactivate, and whenever the popup190  // re-opens onto a stored license that has changed via another window.191  const [proStatus, setProStatus] = createSignal(false);192  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);193  // When the sync card's pairing button opens the pairing view, deep-link194  // straight into that pairing path instead of the rest screen.195  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");196  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);197  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");198  const [listSearchSeed, setListSearchSeed] = createSignal("");199  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);200  const [pendingCelebration, setPendingCelebration] = createSignal(false);201  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);202  // True while Panic Step 1 has bounced the user out to Export. When Export's203  // onBack fires we return to Panic instead of Settings so the user keeps the204  // destruction context they came from.205  const [returnToPanic, setReturnToPanic] = createSignal(false);206  // The view to return to when the add/edit view is dismissed. Normally "entry"207  // but "health" when the user arrives via the fix-entry path from Vault Health.208  const [editBackView, setEditBackView] = createSignal<View>("entry");209  const [settingsExiting, setSettingsExiting] = createSignal(false);210  const [showNotes, setShowNotes] = createSignal(false);211  // Topbar sync affordance. Always present: gating it on having a paired device212  // meant it never appeared for the person trying to set pairing up, which is213  // exactly when you reach for it.214  const [syncBusy, setSyncBusy] = createSignal(false);215  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);216  // The indicator light + its spoken-word equivalent. Colour alone is not the217  // signal; the title/aria-label always carries the same claim in English.218  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});219  const [pairedCount, setPairedCount] = createSignal(0);220  const syncLight = () =>221    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());222  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());223  async function loadSyncIndicator() {224    const [stateRes, devicesRes] = await Promise.all([225      sendMessage({ type: "GET_SYNC_STATE" }),226      sendMessage({ type: "LIST_PAIRED_DEVICES" }),227    ]);228    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };229    if (s.ok && s.data) setSyncSummary(s.data);230    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };231    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);232  }233  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);234  // Set on popup boot when peach_recovery_pending flag is found in session235  // storage — instructs LockView to skip the unlock UI and open the recovery236  // words confirmation surface instead. Cleared via handleUnlock once the237  // user has typed the 3 confirmation words.238  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);239240  let contentPhaseTimer: number | undefined;241  // Set when the popup was opened from the inline "Open Peach to unlock" button.242  // handleUnlock() closes the popup after unlock so the user returns to the page.243  let openedForInlineUnlock = false;244245  function applyAccent(name: AccentColorName) {246    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;247    const hex = color.hex;248    document.documentElement.style.setProperty("--peach-accent", hex);249    // Ambient surface variables — derived from the accent so surfaces shift250    // subtly toward the accent hue rather than staying fixed warm-brown.251    document.documentElement.style.setProperty("--peach-glow", hex + "2A");252    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");253    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");254  }255256  createEffect(() => {257    applyAccent(accentColor());258  });259260  createEffect(() => {261    document.documentElement.classList.toggle("light", theme() === "light");262    document.body.classList.toggle("light", theme() === "light");263  });264265  createEffect(() => {266    document.documentElement.setAttribute("data-text-size", textSize());267  });268269  createEffect(() => {270    if (reduceMotion()) {271      document.documentElement.setAttribute("data-motion", "reduce");272    } else {273      document.documentElement.removeAttribute("data-motion");274    }275  });276277  // Notes are not a destination of the Entry view; selecting a note opens the278  // notes surface instead (handleSelectEntry). Anything that walks or counts279  // the Entry view's neighbours (counter, prev/next, index) must use this280  // filtered list, otherwise the user can arrow into a note and is stuck —281  // the Entry view can't render a note and the prev/next buttons stop moving.282  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));283284  const selectedIndex = createMemo(() => {285    const currentId = selectedEntry()?.id;286    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;287    return nonNoteEntries().findIndex((entry) => entry.id === currentId);288  });289290  async function applyAccentColor(name: AccentColorName) {291    applyAccent(name);292    setAccentColor(name);293    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });294  }295296  async function applyTheme(t: "dark" | "light") {297    setTheme(t);298    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });299  }300301  async function applyTextSize(size: "small" | "medium" | "large") {302    setTextSize(size);303    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });304  }305306  async function applyReduceMotion(enabled: boolean) {307    setReduceMotion(enabled);308    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });309  }310311  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload312  // small and lets future default updates land for actions the user hasn't313  // touched. Settings sends us the full active map; we filter and store.314  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {315    setShortcutBindings(active);316    const overrides: Record<string, Keybinding> = {};317    for (const action of Object.keys(active) as ShortcutAction[]) {318      const a = active[action];319      const d = DEFAULT_BINDINGS[action];320      const same = a.key === d.key321        && Boolean(a.ctrl)  === Boolean(d.ctrl)322        && Boolean(a.meta)  === Boolean(d.meta)323        && Boolean(a.shift) === Boolean(d.shift)324        && Boolean(a.alt)   === Boolean(d.alt);325      if (!same) overrides[action] = a;326    }327    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });328  }329330  async function applyLockOnClose(enabled: boolean) {331    setLockOnClose(enabled);332    await sendMessage({333      type: "UPDATE_SETTINGS",334      payload: { lockOnClose: enabled },335    });336  }337338  async function applyAutoLockMinutes(minutes: number) {339    setAutoLockMinutes(minutes);340    await sendMessage({341      type: "UPDATE_SETTINGS",342      payload: { autoLockMinutes: minutes },343    });344  }345346  async function applyBreachMonitoring(enabled: boolean) {347    setBreachMonitoring(enabled);348    await sendMessage({349      type: "UPDATE_SETTINGS",350      payload: { breachMonitoring: enabled },351    });352  }353354  onMount(async () => {355    // Resolve the active tab in parallel with the unlock/has-vault queries —356    // openVault()'s smart selection picks the entry matching currentTabDomain,357    // so it must be populated before openVault runs. Previously refreshCurrentTab358    // ran after openVault, leaving popups that booted already-unlocked falling359    // back to loadedEntries[0] instead of the domain match.360    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([361      sendMessage({ type: "IS_UNLOCKED" }),362      sendMessage({ type: "HAS_VAULT" }),363      refreshCurrentTab(),364      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),365    ]);366    const unlocked = Boolean(367      (unlockResponse as { ok: boolean; data?: boolean }).data368    );369    const vaultExists = Boolean(370      (vaultResponse as { ok: boolean; data?: boolean }).data371    );372    const shouldCelebrate = Boolean(373      (celebrationResponse as { ok: boolean; data?: boolean }).data374    );375    setHasVault(vaultExists);376    // Onboarding gate — show once on first install, never again. Existing377    // users (vaultExists) are auto-marked onboarded so they skip the flow378    // even on the very first popup open after this feature ships.379    try {380      const onboarded = await storageGet("peach_onboarded");381      const seen = onboarded === "true";382      if (vaultExists && !seen) {383        await storageSet("peach_onboarded", "true");384        setOnboarded(true);385      } else {386        setOnboarded(seen);387      }388    } catch {389      // storage unavailable — default to onboarded so we never block boot390      setOnboarded(true);391    }392    await Promise.all([restoreSettings(), refreshProStatus()]);393394    // Mark played before any animation so a crash mid-sequence never replays it395    if (shouldCelebrate) {396      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });397    }398399    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome400    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.401    if (unlocked && vaultExists) {402      void sendMessage({403        type: "TRIGGER_SYNC",404        payload: { reason: "foreground" },405      });406      void loadSyncIndicator();407      // Rare device-trust alerts only; routine entry sync stays quiet.408      void loadSyncAlerts();409    }410411    // If the user created a vault but hasn't yet confirmed their recovery412    // words, route back to the recovery-words screen instead of opening the413    // entries view. The flag lives in chrome.storage.local so it survives414    // both popup close (SW suppresses lock-on-close) and full browser415    // restart (handleUnlock checks the same flag after a fresh password416    // unlock). Cleared when confirmation succeeds.417    let recoveryPending = false;418    try {419      const out = await chrome.storage.local?.get("peach_recovery_pending");420      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";421    } catch { /* best-effort */ }422423    // If this popup was opened from the inline "Open Peach to unlock" button,424    // the background set a session flag. Read and clear it so handleUnlock()425    // can close the popup after unlock and return the user to the page.426    if (chrome.storage.session) {427      try {428        const s = await chrome.storage.session.get("peach_inline_unlock");429        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {430          openedForInlineUnlock = true;431          await chrome.storage.session.remove("peach_inline_unlock");432        }433      } catch { /* best-effort */ }434    }435436    // Native: closing the app before recovery-words confirmation means the437    // user didn't finish vault creation. Throw the partial vault away and438    // restart onboarding rather than asking them to unlock a vault they439    // never finished creating. Desktop keeps the existing "unlock to440    // resume" flow because closing the popup there is much more casual.441    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {442      try {443        await chrome.storage.local?.remove([444          "peach_vault_a",445          "peach_vault_b",446          "peach_recovery_pending",447          "peach_onboarded",448          "peach_vault_history",449        ]);450      } catch { /* best-effort */ }451      setHasVault(false);452      setOnboarded(false);453      setView("lock");454      setBootState("ready");455      return;456    }457458    if (recoveryPending && unlocked) {459      // forceRecoveryWords overrides LockView's hasVault gate so the460      // recovery surface renders even though the vault now exists.461      setForceRecoveryWords(true);462      setView("lock");463    } else if (unlocked && vaultExists) {464      await openVault(undefined, shouldCelebrate);465      if (shouldCelebrate) {466        setView("pro-celebration");467        window.setTimeout(() => setView("entry"), 2500);468      }469    } else if (shouldCelebrate) {470      setPendingCelebration(true);471    }472473    await refreshPendingPasskey();474475    // Track tab changes so smart sort stays current476    const handleTabActivated = () => { void refreshCurrentTab(); };477    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {478      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();479    };480    try {481      chrome.tabs.onActivated.addListener(handleTabActivated);482      chrome.tabs.onUpdated.addListener(handleTabUpdated);483      onCleanup(() => {484        chrome.tabs.onActivated.removeListener(handleTabActivated);485        chrome.tabs.onUpdated.removeListener(handleTabUpdated);486      });487    } catch {488      // tabs permission may not be available in all contexts489    }490491    setBootState("ready");492493    // Deep-link: ?codex=pdf opens a detached window straight into the494    // Codex restore flow with auto-picked PDF. The action popup can't host495    // a file dialog without dismissing itself, so this is the only way the496    // PDF import path survives. See CodexRestoreView.openPdfPicker().497    try {498      const route = new URLSearchParams(window.location.search).get("codex");499      if (route === "pdf" || route === "restore") {500        setView("codex-restore");501      }502    } catch {503      // location.search unavailable — ignore.504    }505506    // Check for pending session-storage notices from the background.507    if (chrome.storage.session) {508      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as509        Record<string, { feature?: string } | undefined>;510      if (session.pendingProGate?.feature) {511        await chrome.storage.session.remove("pendingProGate");512        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);513        setSettingsInitialSection("license");514        setView("settings");515      } else if (session.pendingProNotice?.feature) {516        await chrome.storage.session.remove("pendingProNotice");517        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });518      }519    }520521    // Warm the lazy-module cache so the Suspense fallback never shows for522    // locally-bundled extension views. Without this, the first navigation to523    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which524    // covers the shell and absorbs clicks on the header.525    void Promise.all([526      import("./views/Settings").catch(() => {}),527      import("./views/Import").catch(() => {}),528      import("./views/Export").catch(() => {}),529      import("./views/Health").catch(() => {}),530      import("./views/TrashView").catch(() => {}),531    ]);532533    // Lock-on-close via a persistent port. sendMessage in pagehide is534    // unreliable — the popup context tears down before the message lands.535    // The SW's onConnect listener locks when this port disconnects.536    let popupPort: chrome.runtime.Port | null = null;537    try {538      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect539      // listener accepts the "popup-" prefix; the random suffix is defence in540      // depth against a port named exactly "popup" from anything but our popup.541      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });542    } catch { /* extension context invalidated — ignore */ }543    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });544545    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only546    // reliable signal is appStateChange — setTimeout is killed when the OS547    // backgrounds the app. We measure elapsed background time on resume.548    if (isNativePlatform()) {549      let backgroundedAt: number | null = null;550551      const CapApp = nativePlugin<{552        addListener: (553          ev: string,554          cb: (s: { isActive: boolean }) => void,555        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };556      }>("App");557      if (CapApp?.addListener) {558        const sub = CapApp.addListener(559          "appStateChange",560          ({ isActive }: { isActive: boolean }) => {561            if (!isActive) {562              backgroundedAt = Date.now();563              return;564            }565            if (backgroundedAt !== null && autoLockMinutes() > 0) {566              const elapsed = Date.now() - backgroundedAt;567              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();568            }569            backgroundedAt = null;570          }571        );572        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.573        onCleanup(() => {574          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});575        });576      }577578      // L12/COR-011: foreground idle autolock. appStateChange only fires when579      // the OS backgrounds the app — if the user idles with the screen on,580      // chrome.alarms is no-op'd in Capacitor so the vault would stay open581      // indefinitely. Poll every 30s and lock if elapsed since last user582      // interaction exceeds autoLockMinutes.583      let lastUserActivityAt = Date.now();584      const bumpActivity = () => { lastUserActivityAt = Date.now(); };585      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;586      for (const ev of ACTIVITY_EVENTS) {587        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });588      }589      const idleLockInterval = setInterval(() => {590        const minutes = autoLockMinutes();591        if (!minutes || minutes <= 0) return;592        const elapsed = Date.now() - lastUserActivityAt;593        if (elapsed >= minutes * 60_000) {594          lastUserActivityAt = Date.now();595          handleHeaderLock();596        }597      }, 30_000);598      onCleanup(() => {599        clearInterval(idleLockInterval);600        for (const ev of ACTIVITY_EVENTS) {601          document.removeEventListener(ev, bumpActivity, { capture: true });602        }603      });604605      // The retired native peer-discovery trigger went with the old Capacitor606      // pairing plugin. Reconnection is address-cache first, subnet probe second607      // (sync-runner.ts); relocating a peer that changed networks is an608      // Android-side discovery concern now.609      if (isNativePlatform()) {610        // Android runs the background/sync dispatcher in-process with the611        // popup, so the production runner has to be registered from the612        // UI bootstrap path instead of the MV3 service-worker entry.613        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>614          import("../background/sync-runner").then(({ productionSyncRunner }) => {615            setSyncRunner(productionSyncRunner);616            void hydratePersistedSyncState();617          })618        );619      }620    }621622    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale623    // entries instead of waiting for the next GET_ENTRIES round-trip.624    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {625      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();626      if (msg?.type === "SYNC_STATE_CHANGED") {627        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);628      }629      if (msg?.type === "PRO_GATE_TRIGGERED") {630        setUpgradeHighlight(msg.payload?.feature ?? null);631        setSettingsInitialSection("license");632        setView("settings");633      }634    };635    chrome.runtime.onMessage.addListener(handleRuntimeMessage);636    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));637638    // Android hardware/gesture back. MainActivity fires peach:back; the popup639    // decides what "back" means per surface. Lock+no-vault is the common case640    // — return to onboarding rather than letting the OS dismiss the activity.641    const handlePeachBack = () => {642      // Notes mode captures back first643      if (showNotes()) {644        setShowNotes(false);645        setOpenNoteId(undefined);646        return;647      }648      const v = view();649      if (v === "lock" && !hasVault() && onboarded()) {650        setOnboarded(false);651        return;652      }653      if (v === "list") { setView("entry"); return; }654      if (v === "settings") {655        window.dispatchEvent(new Event("peach:settings-back"));656        return;657      }658      if (v === "import" || v === "health") { setView("settings"); return; }659      if (v === "export") { handleExportBack(); return; }660      if (v === "add") { handleBack(); return; }661      if (v === "pair-device") { setView("settings"); return; }662    };663    window.addEventListener("peach:back", handlePeachBack);664    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));665666    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that667    // peeks from the bottom (search bar handle visible) and drags up to fill668    // the screen. dragOffset is the LIVE finger offset during a drag, in px,669    // 0 when no drag in progress. The wrapper element computes transform =670    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.671    if (isNativePlatform()) {672      let touchStartY = 0;673      let touchStartX = 0;674      let lastY = 0;675      let lastT = 0;676      let dragging = false;677      let captured = false;678      const HORIZONTAL_TOLERANCE = 16;679      const ACTIVATION_DY = 8;680      const PEEK_PX = 60;681682      const onTouchStart = (e: TouchEvent) => {683        const t = e.touches[0];684        if (!t) return;685        const v = view();686        if (v !== "entry" && v !== "list") return;687        // Entry view: only intercept drags starting in the bottom 40%.688        // List view: intercept drags starting in the top 35% (the search/handle row).689        const inBand = v === "entry"690          ? t.clientY > window.innerHeight * 0.6691          : t.clientY < window.innerHeight * 0.35;692        if (!inBand) return;693        touchStartY = lastY = t.clientY;694        touchStartX = t.clientX;695        lastT = e.timeStamp;696        dragging = true;697        captured = false;698      };699700      const onTouchMove = (e: TouchEvent) => {701        if (!dragging) return;702        const t = e.touches[0];703        if (!t) return;704        const dy = t.clientY - touchStartY;705        const dx = Math.abs(t.clientX - touchStartX);706707        if (!captured) {708          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {709            // Looks like a horizontal swipe — release.710            dragging = false;711            return;712          }713          if (Math.abs(dy) < ACTIVATION_DY) return;714          captured = true;715        }716717        // Translate the sheet by dy from its rest (peek) position. Peek is718        // (viewport height - PEEK_PX). Open is 0.719        const v = view();720        const restClosed = window.innerHeight - PEEK_PX;721        const baseTranslate = v === "list" ? 0 : restClosed;722        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));723        setSheetTranslate(next);724        lastY = t.clientY;725        lastT = e.timeStamp;726      };727728      const onTouchEnd = (e: TouchEvent) => {729        if (!dragging) { return; }730        const t = e.changedTouches[0];731        const elapsed = Math.max(1, e.timeStamp - lastT);732        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms733        const wasCaptured = captured;734        dragging = false;735        captured = false;736        const v = view();737738        if (!wasCaptured) {739          // Tap in the peek strip while in entry view → open the vault list.740          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");741          setSheetTranslate(null);742          return;743        }744745        const restClosed = window.innerHeight - PEEK_PX;746        const current = sheetTranslate() ?? restClosed;747748        // Snap rules:749        //   - Strong upward velocity → open750        //   - Strong downward velocity → close751        //   - Otherwise snap to whichever rest is closer752        let nextOpen: boolean;753        if (velocity < -0.05) nextOpen = true;754        else if (velocity > 0.05) nextOpen = false;755        else nextOpen = current < restClosed * 0.5;756757        if (nextOpen && v !== "list") setView("list");758        if (!nextOpen && v !== "entry") setView("entry");759        // Release the live offset so CSS transition handles the snap.760        setSheetTranslate(null);761      };762763      document.addEventListener("touchstart", onTouchStart, { passive: true });764      document.addEventListener("touchmove",  onTouchMove,  { passive: true });765      document.addEventListener("touchend",   onTouchEnd,   { passive: true });766      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });767      onCleanup(() => {768        document.removeEventListener("touchstart", onTouchStart);769        document.removeEventListener("touchmove",  onTouchMove);770        document.removeEventListener("touchend",   onTouchEnd);771      });772    }773774    // Action handlers — keyed by ShortcutAction. The dispatcher below tests775    // each binding against the event and runs the matching handler. New776    // shortcuts only need an entry here; the binding is data, not code.777    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {778      copy_password: () => {779        const entry = selectedEntry();780        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });781      },782      copy_username: () => {783        const entry = selectedEntry();784        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });785      },786      copy_totp: () => {787        const entry = selectedEntry();788        if (!entry?.totp) return;789        try {790          const { code } = generateTOTP(entry.totp);791          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });792        } catch { /* invalid TOTP secret — silent */ }793      },794      new_entry: () => handleAdd(),795      edit_entry: () => {796        const entry = selectedEntry();797        // Passkey-only entries have nothing user-editable in the Add view; the798        // passkey credential itself is opaque. Skip the edit action for them.799        if (!entry || isPasskeyOnly(entry)) return;800        setEditEntry(entry);801        setView("add");802      },803      delete_entry: () => {804        if (selectedEntry()) void handleDelete();805      },806      lock_vault: () => { void handleHeaderLock(); },807      search: () => openList(),808      nav_prev: () => navigate(-1),809      nav_next: () => navigate(1),810      jump_vault: () => setView("entry"),811      jump_settings: () => setView("settings"),812      show_help: () => setShowShortcutsHelp(true),813    };814815    // Actions that are MEANINGFUL only on the entry-detail view. Outside816    // that scope the binding is dormant — pressing C while on Settings817    // does nothing rather than awkwardly copying from a now-stale entry.818    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([819      "copy_password", "copy_username", "copy_totp",820      "edit_entry", "delete_entry", "nav_prev", "nav_next",821    ]);822823    const handleGlobalKeydown = (e: KeyboardEvent) => {824      const v = view();825      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"826        || (e.target as HTMLElement)?.tagName === "TEXTAREA"827        || (e.target as HTMLElement)?.isContentEditable;828      const isPrintableSearchKey =829        e.key.length === 1 &&830        !e.ctrlKey &&831        !e.metaKey &&832        !e.altKey;833834      // No input during the pro celebration sequence835      if (v === "pro-celebration") return;836837      // Help dialog: Escape closes it; eat the keypress so it doesn't838      // also navigate away from the underlying view.839      if (showShortcutsHelp()) {840        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }841        return;842      }843844      // ── Escape — fixed binding (not user-customizable) ───────845      if (e.key === "Escape") {846        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }847        if (v === "list") { setView("entry"); return; }848        if (v === "settings" || v === "add") { handleBack(); return; }849        if (v === "import" || v === "health") { setView("settings"); return; }850        if (v === "export") { handleExportBack(); return; }851        if (v === "pair-device") { setView("settings"); return; }852      }853854      // Bindings-driven dispatch. Single-key letter bindings without855      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is856      // inside an input, so users can type into search/forms normally.857      const bindings = shortcutBindings();858      for (const action of Object.keys(bindings) as ShortcutAction[]) {859        const binding = bindings[action];860        if (!matchKeybinding(e, binding)) continue;861        // Single-key letter bindings need the input-focus guard. Bindings862        // with any modifier are safe — Ctrl+L doesn't conflict with typing.863        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;864        if (!hasMod && binding.key.length === 1 && inInput) return;865        if (ENTRY_SCOPED.has(action) && v !== "entry") return;866        e.preventDefault();867        SHORTCUT_HANDLERS[action]?.();868        return;869      }870871      // Type-to-search: in entry view, any printable key not consumed by a872      // shortcut above primes the list search seed and opens the list.873      // Kept outside the bindings table because it's a behavior, not a874      // discrete action — every printable character can trigger it.875      if (v === "entry" && !inInput && isPrintableSearchKey) {876        e.preventDefault();877        primeListSearch(e.key);878        return;879      }880    };881    window.addEventListener("keydown", handleGlobalKeydown);882    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));883884    const handleStorageChanged = (885      changes: Record<string, chrome.storage.StorageChange>,886      areaName: string887    ) => {888      if (areaName !== "session") return;889      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {890        return;891      }892      void refreshPendingPasskey();893    };894    chrome.storage.onChanged.addListener(handleStorageChanged);895    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));896  });897898  async function refreshCurrentTab() {899    try {900      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });901      const url = tab?.url ?? tab?.pendingUrl ?? "";902      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");903      // Skip extension/internal URLs — adding chrome://, about:, or904      // chrome-extension:// to a vault entry is never what the user wants.905      const isWebUrl = /^https?:\/\//i.test(url);906      setCurrentTabUrl(isWebUrl ? url : "");907    } catch {908      setCurrentTabDomain("");909      setCurrentTabUrl("");910    }911  }912913  async function refreshPendingPasskey() {914    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });915    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);916  }917918  async function refreshProStatus() {919    const res = await sendMessage({ type: "GET_LICENSE" });920    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;921    setProStatus(Boolean(data?.valid && data?.plan === "pro"));922  }923924  async function restoreSettings() {925    const res = await sendMessage({ type: "GET_SETTINGS" });926    const s = (res as { ok: boolean; data?: any }).data ?? {};927    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {928      setAccentColor(s.accentColor as AccentColorName);929    }930    setTheme(s.theme === "light" ? "light" : "dark");931    if (s.textSize === "small" || s.textSize === "large") {932      setTextSize(s.textSize);933    } else {934      setTextSize("medium");935    }936    setReduceMotion(s.reduceMotion === true);937    setLockOnClose(s.lockOnClose !== false);938    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);939    setBreachMonitoring(s.breachMonitoring !== false);940    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);941    setShortcutBindings(getActiveBindings(s.shortcuts));942  }943944  async function applyTrashRetention(days: number) {945    setTrashRetentionDays(days);946    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });947  }948949  function primeListSearch(seed: string) {950    setListSearchSeed(seed);951    setListSearchSeedNonce((value) => value + 1);952    openList();953  }954955  // Returns null when it detected a dead service worker and triggered handleLock().956  // Callers that need to abort (e.g. openVault) check for null rather than relying957  // on view() state, which may already be "lock" during normal startup flows.958  async function loadEntries(): Promise<VaultEntry[] | null> {959    const response = await sendMessage({ type: "GET_ENTRIES" });960    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };961962    // If the service worker was killed and restarted (MV3 workers sleep), the963    // vault will be locked again — or the worker may not respond at all.964    // In either case, send the user to the lock screen rather than silently965    // showing an empty vault (which looks like data loss).966    if (!res.ok) {967      if (968        res.error === "vault_locked" ||969        res.error === "SERVICE_WORKER_UNAVAILABLE" ||970        (typeof res.error === "string" && res.error.includes("locked"))971      ) {972        handleLock();973        return null; // signal emergency lock to callers974      }975      return [];976    }977978    const loadedEntries = res.data ?? [];979    setEntries(loadedEntries);980981    const currentId = selectedEntry()?.id;982    if (currentId) {983      setSelectedEntry(984        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)985      );986    }987988    return loadedEntries;989  }990991  async function openVault(preferredEntryId?: string, skipViewSet = false) {992    // Purge expired trash entries on each vault open993    const retDays = trashRetentionDays();994    if (retDays > 0) {995      void sendMessage({996        type: "PURGE_EXPIRED_TRASH",997        payload: { retentionMs: retDays * 86_400_000 },998      });999    }10001001    const loadedEntries = await loadEntries();10021003    // null means loadEntries() triggered an emergency lock (service worker died).1004    // Don't override it by setting view back to "entry" with an empty vault.1005    if (loadedEntries === null) return;10061007    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1008    let nextSelectedEntry: VaultEntry | null = null;1009    if (preferredEntryId) {1010      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1011    }1012    if (!nextSelectedEntry) {1013      const tabDomain = currentTabDomain();1014      if (tabDomain) {1015        nextSelectedEntry = loadedEntries.find((e) => {1016          if (e.type === "login") {1017            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1018            for (const extra of e.additionalUrls ?? []) {1019              if ((extractDomain(extra) ?? "") === tabDomain) return true;1020            }1021            return false;1022          }1023          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1024          return false;1025        }) ?? null;1026      }1027    }1028    nextSelectedEntry ??= pickNavigable(loadedEntries);10291030    setSelectedEntry(nextSelectedEntry);1031    setEditEntry(undefined);1032    setContentTransitioning(false);1033    setContentPhase("enter");1034    queueContentIdle();1035    if (!skipViewSet) setView("entry");1036  }10371038  async function handleUnlock() {1039    // If the user previously created a vault but hadn't yet confirmed their1040    // recovery words (and the browser was closed before they could), the1041    // peach_recovery_pending flag is still set in storage.local. Re-route1042    // back to the recovery surface so they finish the confirmation step1043    // before reaching the entries view — the words can be re-derived now1044    // that the vault is unlocked again.1045    let recoveryPending = false;1046    try {1047      const out = await chrome.storage.local?.get("peach_recovery_pending");1048      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1049    } catch { /* best-effort */ }1050    if (recoveryPending) {1051      setForceRecoveryWords(true);1052      setView("lock");1053      triggerPipPulse();1054      await restoreSettings();1055      return;1056    }1057    setHasVault(true);1058    triggerPipPulse();1059    await restoreSettings();1060    const celebrating = pendingCelebration();1061    if (celebrating) {1062      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1063      setPendingCelebration(false);1064    }1065    await openVault(undefined, celebrating);1066    if (celebrating) {1067      setView("pro-celebration");1068      window.setTimeout(() => setView("entry"), 2500);1069    }1070    // Popup was opened from the inline "Open Peach to unlock" button — close it1071    // now so the user lands back on the page with the autofill selector ready.1072    if (openedForInlineUnlock) {1073      openedForInlineUnlock = false;1074      window.close();1075    }1076  }10771078  function handleSelectEntry(entry: VaultEntry) {1079    if (entry.type === "note") {1080      setOpenNoteId(entry.id);1081      setShowNotes(true);1082      return;1083    }1084    setSelectedEntry(entry);1085    setContentTransitioning(false);1086    setContentPhase("enter");1087    queueContentIdle();1088    setView("entry");1089  }10901091  function handleAdd() {1092    setEditEntry(undefined);1093    setView("add");1094  }10951096  async function handleDelete() {1097    const entry = selectedEntry();1098    if (!entry) return;1099    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1100    const loadedEntries = await loadEntries() ?? [];1101    setSelectedEntry(pickNavigable(loadedEntries));1102    setView("entry");1103  }11041105  async function handleDeleteMany(ids: string[]) {1106    for (const id of ids) {1107      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1108    }1109    const loadedEntries = await loadEntries() ?? [];1110    // If the currently selected entry was among the deleted, move to first1111    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1112    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1113  }11141115  async function handleSave(savedEntry?: VaultEntry) {1116    await openVault(savedEntry?.id);1117  }11181119  function handleBack() {1120    const dest = editBackView();1121    setEditBackView("entry");1122    setEditEntry(undefined);1123    setView(dest);1124  }11251126  function handleExportBack() {1127    if (returnToPanic()) {1128      setReturnToPanic(false);1129      setView("panic");1130      return;1131    }1132    setView("settings");1133  }11341135  function handleLock() {1136    clearCanarySuppressions();1137    setEntries([]);1138    setSelectedEntry(null);1139    setEditEntry(undefined);1140    setContentPhase("idle");1141    setView("lock");1142  }11431144  function handleHeaderLock() {1145    // Lock the UI immediately — do not wait for the service worker. If the SW1146    // is dead or slow, the 5s sendMessage timeout would create a dead-click1147    // window. The SW will lock on its next wake regardless.1148    handleLock();1149    void sendMessage({ type: "LOCK" });1150  }11511152  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1153  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1154  // the trigger's own reply.1155  async function handleHeaderSync(): Promise<void> {1156    if (syncBusy()) return;1157    setSyncBusy(true);1158    setSyncFlash(null);1159    try {1160      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1161      let state: SyncOutcomeSummary = { status: "syncing" };1162      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1163        await new Promise((r) => setTimeout(r, 250));1164        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1165          ok: boolean;1166          data?: SyncOutcomeSummary;1167        };1168        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1169      }1170      setSyncSummary(state);1171      setSyncFlash(state.status === "error" ? "error" : "ok");1172      await loadSyncAlerts();1173      await loadEntries();1174      await loadSyncIndicator();1175    } catch {1176      setSyncSummary({ status: "error", outcome: "run_failed" });1177      setSyncFlash("error");1178    } finally {1179      setSyncBusy(false);1180      setTimeout(() => setSyncFlash(null), 2_000);1181    }1182  }11831184  function navigate(dir: number) {1185    const navigable = nonNoteEntries();1186    if (navigable.length === 0) return;1187    const currentIndex = selectedIndex();1188    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1189    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1190    setSelectedEntry(navigable[nextIndex]);1191    setContentPhase("enter");1192    queueContentIdle();1193  }11941195  /**1196   * The Entry view's selection invariant: never select a note. Notes are a1197   * separate surface (handleSelectEntry opens the notes view), so any code path1198   * that picks a default — vault open, post-delete, refresh — must skip them1199   * and return null if the only entries are notes.1200   */1201  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1202    return list.find((e) => e.type !== "note") ?? null;1203  }12041205  function openList() {1206    setView("list");1207  }12081209  function openHealth() {1210    setEditEntry(undefined);1211    setView("health");1212  }12131214  function handleOpenFileImport() {1215    setRestoreView("file");1216  }12171218  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12191220  function handleFixEntry(entry: VaultEntry) {1221    setSelectedEntry(entry);1222    // Passkey-only entries have no editable surface — drop into view mode1223    // instead of opening the Add editor.1224    if (isPasskeyOnly(entry)) {1225      setView("entry");1226      return;1227    }1228    setEditBackView(view()); // preserve caller view so back returns here1229    setEditEntry(entry);1230    setView("add");1231  }12321233  const isLockedView = () => view() === "lock" || view() === "adopting";12341235  async function handleAdoptionDone() {1236    await storageSet("peach_onboarded", "true").catch(() => {});1237    setOnboarded(true);1238    setHasVault(true);1239    await handleUnlock();1240    void sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "foreground" } });1241  }12421243  async function handleApprovePendingPasskey() {1244    const pending = pendingPasskey();1245    if (!pending) return;1246    if (pending.browser === "firefox" && pending.type === "create") {1247      // Firefox path: popup itself runs navigator.credentials.create. The1248      // background never approved/rejected anything — it just stashed1249      // intent. After the popup-driven flow resolves (success or cancel),1250      // clear the pending key so the popup doesn't re-show this on next open.1251      const { createFirefoxPasskey } = await import("./firefox-passkey");1252      const result = await createFirefoxPasskey(pending);1253      if (!result.ok) {1254        console.warn("Peach Firefox passkey create failed:", result.error);1255      }1256      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1257      setPendingPasskey(null);1258      void loadEntries();1259      window.close();1260      return;1261    }1262    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1263    window.close();1264  }12651266  async function handleDenyPendingPasskey() {1267    const pending = pendingPasskey();1268    if (!pending) return;1269    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1270    window.close();1271  }12721273  function queueContentIdle(after?: () => void) {1274    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1275    contentPhaseTimer = window.setTimeout(() => {1276      setContentPhase("idle");1277      after?.();1278    }, ENTRY_TRANSITION_SETTLE_MS);1279  }12801281  return (1282    <div class="popup-root peach-theme">1283      <Show when={bootState() === "ready"}>1284        <Show1285          when={!pendingPasskey()}1286          fallback={1287            <PasskeyApprovalView1288              type={pendingPasskey()!.type}1289              rpName={pendingPasskey()!.rpName}1290              rpId={pendingPasskey()!.rpId}1291              userName={pendingPasskey()!.userName}1292              userDisplayName={pendingPasskey()!.userDisplayName}1293              onApprove={handleApprovePendingPasskey}1294              onDeny={handleDenyPendingPasskey}1295            />1296          }1297        >1298          <Show1299            when={!isLockedView()}1300            fallback={1301              <Show1302                when={view() !== "adopting"}1303                fallback={1304                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1305                    <AdoptVaultView1306                      onCancel={() => {1307                        setOnboarded(false);1308                        setView("lock");1309                      }}1310                      onDone={handleAdoptionDone}1311                    />1312                  </Suspense>1313                }1314              >1315                <Show1316                  when={onboarded() || hasVault()}1317                  fallback={1318                    <Onboarding1319                      onComplete={() => {1320                        setStartOnboardingRestore(false);1321                        setOnboarded(true);1322                      }}1323                      onRestore={() => {1324                        setStartOnboardingRestore(true);1325                        setOnboarded(true);1326                      }}1327                      onAdopt={() => {1328                        setStartOnboardingRestore(false);1329                        setOnboarded(true);1330                        setView("adopting");1331                      }}1332                    />1333                  }1334                >1335                  <LockView1336                    hasVault={hasVault()}1337                    ready={bootState() === "ready"}1338                    isPro={proStatus()}1339                    forceRecoveryWords={forceRecoveryWords()}1340                    initialRestore={startOnboardingRestore()}1341                    onUnlock={() => {1342                      // RecoveryWordDisplay clears the storage flag before1343                      // calling onDone, so handleUnlock will see no pending1344                      // confirmation and proceed through the normal path.1345                      if (forceRecoveryWords()) setForceRecoveryWords(false);1346                      return handleUnlock();1347                    }}1348                    onBackToOnboarding={1349                      !hasVault()1350                        ? () => {1351                            setStartOnboardingRestore(false);1352                            setOnboarded(false);1353                          }1354                        : undefined1355                    }1356                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1357                  />1358                </Show>1359              </Show>1360            }1361          >1362            <Show1363              when={view() !== "pro-celebration"}1364              fallback={<ProCelebration />}1365            >1366            <section1367              id="hd-shell"1368              class="peach-shell peach-theme"1369              data-surface="extension"1370            >1371            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1372              <PeachWordmark unlocked />1373              <div class="peach-chrome-actions">1374                <button1375                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1376                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1377                  aria-label="Notes"1378                  title="Notes"1379                >1380                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1381                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1382                    <line x1="4" y1="5" x2="10" y2="5" />1383                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1384                    <line x1="4" y1="10" x2="7" y2="10" />1385                  </svg>1386                </button>1387                <button1388                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1389                    classList={{1390                      "is-syncing": syncBusy(),1391                      "is-ok": syncFlash() === "ok",1392                      "is-error": syncFlash() === "error",1393                    }}1394                    onClick={() => void handleHeaderSync()}1395                    disabled={syncBusy()}1396                    aria-label={`Sync now. ${syncLabel()}`}1397                    title={syncLabel()}1398                  >1399                    <svg class="peach-sync-icon" width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1400                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1401                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1402                      <path d="M2.6 1v2.4h2.4" />1403                      <path d="M11.4 13v-2.4H9" />1404                    </svg>1405                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1406                  </button>1407                <button1408                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1409                  onClick={() => setView("settings")}1410                  aria-label="Settings"1411                >1412                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1413                    <path1414                      d="M5.91 1.11C6.38-.02 7.62-.02 8.09 1.11L8.31 1.64C8.48 2.05 8.91 2.27 9.34 2.17L9.9 2.04C11.1 1.76 11.98 2.64 11.7 3.84L11.57 4.4C11.47 4.83 11.69 5.26 12.1 5.43L12.63 5.65C13.76 6.12 13.76 7.36 12.63 7.83L12.1 8.05C11.69 8.22 11.47 8.65 11.57 9.08L11.7 9.64C11.98 10.84 11.1 11.72 9.9 11.44L9.34 11.31C8.91 11.21 8.48 11.43 8.31 11.84L8.09 12.37C7.62 13.5 6.38 13.5 5.91 12.37L5.69 11.84C5.52 11.43 5.09 11.21 4.66 11.31L4.1 11.44C2.9 11.72 2.02 10.84 2.3 9.64L2.43 9.08C2.53 8.65 2.31 8.22 1.9 8.05L1.37 7.83C.24 7.36.24 6.12 1.37 5.65L1.9 5.43C2.31 5.26 2.53 4.83 2.43 4.4L2.3 3.84C2.02 2.64 2.9 1.76 4.1 2.04L4.66 2.17C5.09 2.27 5.52 2.05 5.69 1.64L5.91 1.11Z"1415                      stroke="currentColor"1416                      stroke-width="0.9"1417                    />1418                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1419                  </svg>1420                </button>1421                <button1422                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1423                  onClick={handleAdd}1424                  aria-label="New entry"1425                >1426                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1427                    <path d="M5.5 1v9M1 5.5h9" />1428                  </svg>1429                </button>1430                <button1431                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1432                  onClick={() => void handleHeaderLock()}1433                  aria-label="Lock vault"1434                >1435                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1436                    <path1437                      d="M3.75 6V4.75C3.75 2.96 5.21 1.5 7 1.5C8.79 1.5 10.25 2.96 10.25 4.75V6"1438                      stroke="currentColor"1439                      stroke-width="1"1440                      stroke-linecap="round"1441                    />1442                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1443                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1444                  </svg>1445                </button>1446              </div>1447            </header>14481449            <Show when={pendingProNotice() !== null}>1450              <div class="peach-pro-notice-banner">1451                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1452                <button1453                  class="peach-pro-notice-link"1454                  onClick={() => {1455                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1456                    setSettingsInitialSection("license");1457                    setView("settings");1458                    setPendingProNotice(null);1459                  }}1460                >1461                  Learn more →1462                </button>1463                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1464              </div>1465            </Show>14661467            <div class="peach-shell-body">1468              <div class="peach-shell-veil"></div>1469              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1470                <EntryView1471                  entry={selectedEntry()}1472                  currentTabUrl={currentTabUrl()}1473                  entries={entries()}1474                  isPro={proStatus()}1475                  onDelete={handleDelete}1476                  onFieldSaved={() => void loadEntries()}1477                  onEscape={() => { setView("list"); }}1478                  onProGate={(feature) => {1479                    setUpgradeHighlight(feature);1480                    setSettingsInitialSection("license");1481                    setView("settings");1482                  }}1483                />1484              </div>14851486              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1487                <div class="peach-search-bar">1488                  <span class="peach-search-icon">1489                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1490                      <circle cx="5.5" cy="5.5" r="3.75" />1491                      <path d="M8.75 8.75L11.5 11.5" />1492                    </svg>1493                  </span>1494                  <input1495                    class="peach-search-input"1496                    placeholder="search vault..."1497                    autocomplete="off"1498                    aria-label="Search vault entries"1499                    onClick={openList}1500                    onFocus={openList}1501                    readOnly1502                  />1503                  <div class="peach-search-meta">1504                    <span class="peach-search-counter">1505                      {nonNoteEntries().length > 01506                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1507                        : "0 entries"}1508                    </span>1509                    <span class="peach-divider"></span>1510                    <button1511                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1512                      onClick={() => navigate(-1)}1513                      aria-label="Previous entry"1514                      disabled={nonNoteEntries().length === 0}1515                    >1516                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1517                        <path d="M5 1L1 5.5L5 10" />1518                      </svg>1519                    </button>1520                    <button1521                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1522                      onClick={() => navigate(1)}1523                      aria-label="Next entry"1524                      disabled={nonNoteEntries().length === 0}1525                    >1526                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1527                        <path d="M1 1L5 5.5L1 10" />1528                      </svg>1529                    </button>1530                  </div>1531                </div>1532              </section>1533            </div>15341535            {/* Desktop: shown on demand via Show. Native sheet is rendered1536                via Portal below at the document root so its position:fixed1537                isn't trapped by .peach-shell's transform-based animations. */}1538            {/* Rare device-trust alerts; normal sync changes are silent. */}1539            <Show when={syncAlerts().length > 0}>1540              <div class="peach-sync-alerts">1541                <For each={syncAlerts()}>1542                  {(alert, i) => (1543                    <div class="peach-sync-alert">1544                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1545                      <button1546                        class="peach-sync-alert-dismiss"1547                        type="button"1548                        aria-label="Dismiss"1549                        onClick={() => dismissSyncAlert(i())}1550                      >×</button>1551                    </div>1552                  )}1553                </For>1554              </div>1555            </Show>15561557            <Show when={!isNativePlatform() && view() === "list"}>1558              <VaultView1559                entries={entries()}1560                selectedEntryId={selectedEntry()?.id}1561                currentTabDomain={currentTabDomain()}1562                sortOrder={sortOrder()}1563                searchSeed={listSearchSeed()}1564                searchSeedNonce={listSearchSeedNonce()}1565                onSelectEntry={handleSelectEntry}1566                onSortOrderChange={setSortOrder}1567                onAdd={handleAdd}1568                onClose={() => setView("entry")}1569                onOpenTrash={() => setView("trash")}1570                onDeleteMany={handleDeleteMany}1571              />1572            </Show>1573            <Show when={isNativePlatform() && hasVault()}>1574              <Portal>1575                <div1576                  class="peach-vault-sheet"1577                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1578                  style={(() => {1579                    const live = sheetTranslate();1580                    if (live === null) return undefined;1581                    return { transform: `translateY(${live}px)` };1582                  })()}1583                >1584                  <VaultView1585                    entries={entries()}1586                    selectedEntryId={selectedEntry()?.id}1587                    currentTabDomain={currentTabDomain()}1588                    sortOrder={sortOrder()}1589                    searchSeed={listSearchSeed()}1590                    searchSeedNonce={listSearchSeedNonce()}1591                    isNative={true}1592                    onSelectEntry={handleSelectEntry}1593                    onSortOrderChange={setSortOrder}1594                    onAdd={handleAdd}1595                    onClose={() => setView("entry")}1596                    onOpenTrash={() => setView("trash")}1597                    onDeleteMany={handleDeleteMany}1598                  />1599                </div>1600              </Portal>1601            </Show>1602            <Show when={view() === "settings" || settingsExiting()}>1603              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1604                <SettingsView1605                  entriesCount={entries().length}1606                  breachMonitoring={breachMonitoring()}1607                  lockOnClose={lockOnClose()}1608                  autoLockMinutes={autoLockMinutes()}1609                  trashRetentionDays={trashRetentionDays()}1610                  theme={theme()}1611                  accentColor={accentColor()}1612                  textSize={textSize()}1613                  reduceMotion={reduceMotion()}1614                  isPro={proStatus()}1615                  initialSection={settingsInitialSection()}1616                  upgradeHighlight={upgradeHighlight()}1617                  isExiting={settingsExiting()}1618                  onBreachMonitoringChange={applyBreachMonitoring}1619                  onLockOnCloseChange={applyLockOnClose}1620                  onAutoLockMinutesChange={applyAutoLockMinutes}1621                  onTrashRetentionChange={applyTrashRetention}1622                  onThemeChange={applyTheme}1623                  onAccentChange={applyAccentColor}1624                  onTextSizeChange={applyTextSize}1625                  onReduceMotionChange={applyReduceMotion}1626                  shortcuts={shortcutBindings()}1627                  onShortcutsChange={applyShortcuts}1628                  onLicenseChange={async () => {1629                    // After activation/deactivation: refresh Pro status,1630                    // re-load entries (defensive — signal state can drift if1631                    // the SW briefly restarts during the verify+save round-trip),1632                    // and replay the Pro celebration if this is the first time1633                    // a valid Pro license is seen on this device.1634                    await refreshProStatus();1635                    void loadEntries();1636                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1637                    if ((should as { ok: boolean; data?: boolean }).data === true) {1638                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1639                      setView("pro-celebration");1640                      window.setTimeout(() => setView("settings"), 2500);1641                    }1642                  }}1643                  onBack={() => {1644                    setSettingsExiting(true);1645                    window.setTimeout(() => {1646                      setSettingsExiting(false);1647                      setSettingsInitialSection(null);1648                      setUpgradeHighlight(null);1649                      handleBack();1650                    }, 200);1651                  }}1652                  onImport={() => setView("import")}1653                  onExport={() => setView("export")}1654                  onBreachCheckDone={loadEntries}1655                  onOpenHealth={openHealth}1656                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1657                  onOpenFileImport={handleOpenFileImport}1658                  onOpenPanic={() => setView("panic")}1659                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1660                  onOpenCodexRestore={() => setView("codex-restore")}1661                  onCardChange={setSettingsActiveCard}1662                  onProGate={(feature) => {1663                    setUpgradeHighlight(feature);1664                    setSettingsInitialSection("license");1665                  }}1666                />1667              </Suspense>1668            </Show>1669            <Show when={view() === "codex-generate"}>1670              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1671                <CodexGenerateView1672                  isPro={proStatus()}1673                  onBack={() => setView("settings")}1674                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1675                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1676                  onVaultLocked={() => handleLock()}1677                />1678              </Suspense>1679            </Show>1680            <Show when={view() === "codex-restore"}>1681              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1682                <CodexRestoreView1683                  onBack={() => setView("lock")}1684                  onRestoreSuccess={async () => {1685                    // After restore the vault is unlocked; refresh entries1686                    // and route to the main vault list. handleUnlock is the1687                    // canonical post-unlock setup path.1688                    await handleUnlock();1689                  }}1690                />1691              </Suspense>1692            </Show>1693            <Show when={view() === "pair-device"}>1694              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1695                <PairDeviceView1696                  isPro={proStatus()}1697                  onProChanged={() => { void refreshProStatus(); }}1698                  onBack={() => setView("settings")}1699                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1700                />1701              </Suspense>1702            </Show>1703            <Show when={view() === "add"}>1704              <AddView1705                entry={editEntry()}1706                entries={entries()}1707                onBack={handleBack}1708                onSave={handleSave}1709              />1710            </Show>1711            <Show when={view() === "import"}>1712              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1713                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1714              </Suspense>1715            </Show>1716            <Show when={view() === "export"}>1717              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1718                <ExportView onBack={handleExportBack} />1719              </Suspense>1720            </Show>1721            <Show when={view() === "panic"}>1722              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1723                <PanicView1724                  onCancel={() => setView("settings")}1725                  onOpenExport={() => {1726                    setReturnToPanic(true);1727                    setView("export");1728                  }}1729                  onDestroyed={async () => {1730                    clearCanarySuppressions();1731                    setEntries([]);1732                    setSelectedEntry(null);1733                    setEditEntry(undefined);1734                    setHasVault(false);1735                    setOnboarded(false);1736                    setProStatus(false);1737                    setPendingPasskey(null);1738                    setUpgradeHighlight(null);1739                    setSettingsInitialSection(null);1740                    setPendingProNotice(null);1741                    setPendingCelebration(false);1742                    setReturnToPanic(false);1743                    setContentPhase("idle");1744                    setView("lock");1745                  }}1746                />1747              </Suspense>1748            </Show>1749            {/* Health stays mounted while editing an entry from it so1750                computeReused() doesn't rerun on every cancel/back. */}1751            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1752              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1753                <HealthView1754                  entries={entries()}1755                  isPro={proStatus()}1756                  onFixEntry={handleFixEntry}1757                  onBack={() => setView("settings")}1758                  onRefresh={loadEntries}1759                  hidden={view() !== "health"}1760                />1761              </Suspense>1762            </Show>1763            <Show when={view() === "trash"}>1764              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1765                <TrashView1766                  onBack={() => setView("list")}1767                  onRestored={() => void loadEntries()}1768                />1769              </Suspense>1770            </Show>1771            <Show when={showNotes()}>1772              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1773                <NotesMode1774                  notes={entries().filter((e) => e.type === "note")}1775                  initialNoteId={openNoteId()}1776                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1777                  onNoteListChanged={() => void loadEntries()}1778                />1779              </div>1780            </Show>1781            <Show when={restoreView() === "file"}>1782              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1783                <ImportView1784                  mode="onboarding"1785                  replacesExistingVault={true}1786                  onBack={() => setRestoreView(null)}1787                  onImport={async () => {1788                    setRestoreView(null);1789                    await handleUnlock();1790                  }}1791                />1792              </Suspense>1793            </Show>1794            </section>1795            </Show>1796          </Show>1797        </Show>1798      </Show>1799      <Show when={showShortcutsHelp()}>1800        <ShortcutsHelpOverlay1801          bindings={shortcutBindings()}1802          onClose={() => setShowShortcutsHelp(false)}1803        />1804      </Show>1805    </div>1806  );1807}18081809function ShortcutsHelpOverlay(props: {1810  bindings: Record<ShortcutAction, Keybinding>;1811  onClose: () => void;1812}) {1813  return (1814    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1815      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1816        <div class="peach-shortcuts-help-head">1817          <h3>Keyboard shortcuts</h3>1818          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1819        </div>1820        <div class="peach-shortcuts-help-body">1821          <p class="peach-settings-sub-label">ENTRY VIEW</p>1822          <ul>1823            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1824              <li>1825                <span>{d.label}</span>1826                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1827              </li>1828            ))}1829          </ul>1830          <p class="peach-settings-sub-label">ANYWHERE</p>1831          <ul>1832            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1833              <li>1834                <span>{d.label}</span>1835                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1836              </li>1837            ))}1838          </ul>1839        </div>1840      </div>1841    </div>1842  );1843}