App.tsx

56.4 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { storageGet, storageSet } from "../shared/storage";3import { sendMessage } from "../shared/bridge";4import { ACCENT_COLORS } from "../shared/types";5import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";6import type { IncomingPairingRequest } from "../shared/sync-types";7import { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { ProCelebration } from "./views/ProCelebration";11import { VaultView, type SortOrder } from "./views/Vault";12import { EntryView } from "./views/Entry";13import { AddView } from "./views/Add";14import { PeachMark, PeachWordmark } from "./components/PeachMark";15import { PasskeyApprovalView } from "./views/PasskeyApproval";16import { extractDomain } from "../shared/domain";17import { popupCopy } from "./copy";18import {19  DEFAULT_BINDINGS,20  formatKeybinding,21  getActiveBindings,22  matchKeybinding,23  SHORTCUT_DESCRIPTORS,24  type Keybinding,25  type ShortcutAction,26} from "../shared/shortcuts";27import { generateTOTP } from "../crypto/totp";28import { isNativePlatform, nativePlugin } from "../shared/native";2930export { sendMessage } from "../shared/bridge";3132const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));33const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));34const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));35const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));36const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));37const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));38const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));3940type View =41  | "lock"42  | "pro-celebration"43  | "entry"44  | "list"45  | "add"46  | "settings"47  | "sync-pairing"48  | "import"49  | "export"50  | "health"51  | "trash"52  | "panic";53type BootState = "loading" | "ready";5455const canarySuppressMap = new Map<string, boolean>();56let shellRingAnimation: Animation | null = null;5758export function isCanarySuppressed(entryId: string): boolean {59  return canarySuppressMap.get(entryId) ?? false;60}6162export function setCanarySuppressed(entryId: string, suppressed: boolean): void {63  canarySuppressMap.set(entryId, suppressed);64}6566export function clearCanarySuppressions(): void {67  canarySuppressMap.clear();68}6970export function triggerRing() {71  const shell = document.getElementById("hd-shell");72  if (!shell) return;7374  shellRingAnimation?.cancel();75  shell.dataset.glowing = "true";76  const animation = shell.animate(77    [78      { offset: 0, boxShadow: "var(--copy-shadow)" },79      {80        offset: 0.3,81        boxShadow:82          "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)",83      },84      { offset: 1, boxShadow: "var(--copy-shadow)" },85    ],86    {87      duration: 720,88      easing: "cubic-bezier(0.4, 0, 0.2, 1)",89      fill: "none",90    }91  );92  shellRingAnimation = animation;93  const clearGlow = () => {94    if (shellRingAnimation !== animation) return;95    shellRingAnimation = null;96    delete shell.dataset.glowing;97  };98  animation.onfinish = clearGlow;99  animation.oncancel = clearGlow;100}101102103export function triggerPipPulse() {104  const pip = document.querySelector(".peach-status-pip, .pip");105  if (pip) {106    pip.classList.remove("pulse");107    void (pip as HTMLElement).offsetWidth;108    pip.classList.add("pulse");109  }110}111112const ENTRY_TRANSITION_EXIT_MS = 95;113const ENTRY_TRANSITION_SETTLE_MS = 135;114115export default function App() {116  const [bootState, setBootState] = createSignal<BootState>("loading");117  const [view, setView] = createSignal<View>("lock");118  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(119    "enter"120  );121  const [contentTransitioning, setContentTransitioning] = createSignal(false);122  const [hasVault, setHasVault] = createSignal(false);123  const [onboarded, setOnboarded] = createSignal(true);124  const [entries, setEntries] = createSignal<VaultEntry[]>([]);125  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);126  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);127  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");128  const [theme, setTheme] = createSignal<"dark" | "light">("dark");129  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");130  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");131  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);132  const [lockOnClose, setLockOnClose] = createSignal(true);133  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);134  const [breachMonitoring, setBreachMonitoring] = createSignal(true);135  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);136  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);137  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);138  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);139  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);140  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");141  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");142  // Cached Pro status — synchronous for render paths. Background's143  // GET_LICENSE is async, but render-time reads of isPro() must not block.144  // Refreshed at boot, after activate/deactivate, and whenever the popup145  // re-opens onto a stored license that has changed via another window.146  const [proStatus, setProStatus] = createSignal(false);147  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);148  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);149  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");150  const [listSearchSeed, setListSearchSeed] = createSignal("");151  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);152  const [pendingCelebration, setPendingCelebration] = createSignal(false);153  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);154  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);155  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);156  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);157  const [incomingPairTick, setIncomingPairTick] = createSignal(0);158  const incomingPairSecondsLeft = () => {159    void incomingPairTick();160    const req = incomingPair();161    if (!req) return 0;162    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));163  };164  // True while Panic Step 1 has bounced the user out to Export. When Export's165  // onBack fires we return to Panic instead of Settings so the user keeps the166  // destruction context they came from.167  const [returnToPanic, setReturnToPanic] = createSignal(false);168  // Set on popup boot when peach_recovery_pending flag is found in session169  // storage — instructs LockView to skip the unlock UI and open the recovery170  // words confirmation surface instead. Cleared via handleUnlock once the171  // user has typed the 3 confirmation words.172  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);173174  let contentPhaseTimer: number | undefined;175176  function applyAccent(name: AccentColorName) {177    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;178    const hex = color.hex;179    document.documentElement.style.setProperty("--peach-accent", hex);180    // Ambient surface variables — derived from the accent so surfaces shift181    // subtly toward the accent hue rather than staying fixed warm-brown.182    document.documentElement.style.setProperty("--peach-glow", hex + "2A");183    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");184    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");185  }186187  createEffect(() => {188    applyAccent(accentColor());189  });190191  createEffect(() => {192    document.documentElement.classList.toggle("light", theme() === "light");193    document.body.classList.toggle("light", theme() === "light");194  });195196  createEffect(() => {197    document.documentElement.setAttribute("data-display-font", displayFont());198  });199200  createEffect(() => {201    document.documentElement.setAttribute("data-text-size", textSize());202  });203204  createEffect(() => {205    if (reduceMotion()) {206      document.documentElement.setAttribute("data-motion", "reduce");207    } else {208      document.documentElement.removeAttribute("data-motion");209    }210  });211212  const selectedIndex = createMemo(() => {213    const currentId = selectedEntry()?.id;214    if (!currentId) return entries().length > 0 ? 0 : -1;215    return entries().findIndex((entry) => entry.id === currentId);216  });217218  async function applyAccentColor(name: AccentColorName) {219    applyAccent(name);220    setAccentColor(name);221    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });222  }223224  async function applyTheme(t: "dark" | "light") {225    setTheme(t);226    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });227  }228229  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {230    setDisplayFont(f);231    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });232  }233234  async function applyTextSize(size: "small" | "medium" | "large") {235    setTextSize(size);236    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });237  }238239  async function applyReduceMotion(enabled: boolean) {240    setReduceMotion(enabled);241    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });242  }243244  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload245  // small and lets future default updates land for actions the user hasn't246  // touched. Settings sends us the full active map; we filter and store.247  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {248    setShortcutBindings(active);249    const overrides: Record<string, Keybinding> = {};250    for (const action of Object.keys(active) as ShortcutAction[]) {251      const a = active[action];252      const d = DEFAULT_BINDINGS[action];253      const same = a.key === d.key254        && Boolean(a.ctrl)  === Boolean(d.ctrl)255        && Boolean(a.meta)  === Boolean(d.meta)256        && Boolean(a.shift) === Boolean(d.shift)257        && Boolean(a.alt)   === Boolean(d.alt);258      if (!same) overrides[action] = a;259    }260    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });261  }262263  async function applyLockOnClose(enabled: boolean) {264    setLockOnClose(enabled);265    await sendMessage({266      type: "UPDATE_SETTINGS",267      payload: { lockOnClose: enabled },268    });269  }270271  async function applyAutoLockMinutes(minutes: number) {272    setAutoLockMinutes(minutes);273    await sendMessage({274      type: "UPDATE_SETTINGS",275      payload: { autoLockMinutes: minutes },276    });277  }278279  async function applyBreachMonitoring(enabled: boolean) {280    setBreachMonitoring(enabled);281    await sendMessage({282      type: "UPDATE_SETTINGS",283      payload: { breachMonitoring: enabled },284    });285  }286287  onMount(async () => {288    // Resolve the active tab in parallel with the unlock/has-vault queries —289    // openVault()'s smart selection picks the entry matching currentTabDomain,290    // so it must be populated before openVault runs. Previously refreshCurrentTab291    // ran after openVault, leaving popups that booted already-unlocked falling292    // back to loadedEntries[0] instead of the domain match.293    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([294      sendMessage({ type: "IS_UNLOCKED" }),295      sendMessage({ type: "HAS_VAULT" }),296      refreshCurrentTab(),297      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),298    ]);299    const unlocked = Boolean(300      (unlockResponse as { ok: boolean; data?: boolean }).data301    );302    const vaultExists = Boolean(303      (vaultResponse as { ok: boolean; data?: boolean }).data304    );305    const shouldCelebrate = Boolean(306      (celebrationResponse as { ok: boolean; data?: boolean }).data307    );308    setHasVault(vaultExists);309    // Onboarding gate — show once on first install, never again. Existing310    // users (vaultExists) are auto-marked onboarded so they skip the flow311    // even on the very first popup open after this feature ships.312    try {313      const onboarded = await storageGet("peach_onboarded");314      const seen = onboarded === "true";315      if (vaultExists && !seen) {316        await storageSet("peach_onboarded", "true");317        setOnboarded(true);318      } else {319        setOnboarded(seen);320      }321    } catch {322      // storage unavailable — default to onboarded so we never block boot323      setOnboarded(true);324    }325    await Promise.all([restoreSettings(), refreshProStatus()]);326327    // Mark played before any animation so a crash mid-sequence never replays it328    if (shouldCelebrate) {329      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });330    }331332    // If the user created a vault but hasn't yet confirmed their recovery333    // words, route back to the recovery-words screen instead of opening the334    // entries view. The flag lives in chrome.storage.local so it survives335    // both popup close (SW suppresses lock-on-close) and full browser336    // restart (handleUnlock checks the same flag after a fresh password337    // unlock). Cleared when confirmation succeeds.338    let recoveryPending = false;339    try {340      const out = await chrome.storage.local?.get("peach_recovery_pending");341      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";342    } catch { /* best-effort */ }343344    if (recoveryPending && unlocked) {345      // forceRecoveryWords overrides LockView's hasVault gate so the346      // recovery surface renders even though the vault now exists.347      setForceRecoveryWords(true);348      setView("lock");349    } else if (unlocked && vaultExists) {350      await openVault(undefined, shouldCelebrate);351      if (shouldCelebrate) {352        setView("pro-celebration");353        window.setTimeout(() => setView("entry"), 2500);354      }355    } else if (shouldCelebrate) {356      setPendingCelebration(true);357    }358359    await refreshPendingPasskey();360    await refreshIncomingPairing();361    await consumeRecentPairing();362363    // Track tab changes so smart sort stays current364    const handleTabActivated = () => { void refreshCurrentTab(); };365    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {366      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();367    };368    try {369      chrome.tabs.onActivated.addListener(handleTabActivated);370      chrome.tabs.onUpdated.addListener(handleTabUpdated);371      onCleanup(() => {372        chrome.tabs.onActivated.removeListener(handleTabActivated);373        chrome.tabs.onUpdated.removeListener(handleTabUpdated);374      });375    } catch {376      // tabs permission may not be available in all contexts377    }378379    setBootState("ready");380    document.getElementById("pre-lock")?.setAttribute("hidden", "true");381382    // Check for pending session-storage notices from the background.383    if (chrome.storage.session) {384      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as385        Record<string, { feature?: string } | undefined>;386      if (session.pendingProGate?.feature) {387        await chrome.storage.session.remove("pendingProGate");388        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);389        setSettingsInitialSection("license");390        setView("settings");391      } else if (session.pendingProNotice?.feature) {392        await chrome.storage.session.remove("pendingProNotice");393        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });394      }395    }396397    // Warm the lazy-module cache so the Suspense fallback never shows for398    // locally-bundled extension views. Without this, the first navigation to399    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which400    // covers the shell and absorbs clicks on the header.401    void Promise.all([402      import("./views/Settings").catch(() => {}),403      import("./views/Import").catch(() => {}),404      import("./views/Export").catch(() => {}),405      import("./views/Health").catch(() => {}),406      import("./views/TrashView").catch(() => {}),407    ]);408409    // Lock-on-close via a persistent port. sendMessage in pagehide is410    // unreliable — the popup context tears down before the message lands.411    // The SW's onConnect listener locks when this port disconnects.412    let popupPort: chrome.runtime.Port | null = null;413    try {414      popupPort = chrome.runtime.connect({ name: "popup" });415    } catch { /* extension context invalidated — ignore */ }416    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });417418    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only419    // reliable signal is appStateChange — setTimeout is killed when the OS420    // backgrounds the app. We measure elapsed background time on resume.421    if (isNativePlatform()) {422      let backgroundedAt: number | null = null;423      const CapApp = nativePlugin<{424        addListener: (425          ev: string,426          cb: (s: { isActive: boolean }) => void,427        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };428      }>("App");429      if (CapApp?.addListener) {430        const sub = CapApp.addListener(431          "appStateChange",432          ({ isActive }: { isActive: boolean }) => {433            if (!isActive) {434              backgroundedAt = Date.now();435              return;436            }437            if (backgroundedAt !== null && autoLockMinutes() > 0) {438              const elapsed = Date.now() - backgroundedAt;439              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();440            }441            backgroundedAt = null;442          }443        );444        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.445        onCleanup(() => {446          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});447        });448      }449    }450451    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale452    // entries instead of waiting for the next GET_ENTRIES round-trip.453    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {454      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();455      if (msg?.type === "PRO_GATE_TRIGGERED") {456        setUpgradeHighlight(msg.payload?.feature ?? null);457        setSettingsInitialSection("license");458        setView("settings");459      }460      if (msg?.type === "INCOMING_PAIRING_REQUEST") {461        void refreshIncomingPairing();462      }463    };464    chrome.runtime.onMessage.addListener(handleRuntimeMessage);465    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));466467    // Android hardware/gesture back. MainActivity fires peach:back; the popup468    // decides what "back" means per surface. Lock+no-vault is the common case469    // — return to onboarding rather than letting the OS dismiss the activity.470    const handlePeachBack = () => {471      const v = view();472      if (v === "lock" && !hasVault() && onboarded()) {473        setOnboarded(false);474        return;475      }476      if (v === "list") { setView("entry"); return; }477      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {478        handleBack();479        return;480      }481      if (v === "sync-pairing") { setView("settings"); return; }482    };483    window.addEventListener("peach:back", handlePeachBack);484    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));485486    // Action handlers — keyed by ShortcutAction. The dispatcher below tests487    // each binding against the event and runs the matching handler. New488    // shortcuts only need an entry here; the binding is data, not code.489    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {490      copy_password: () => {491        const entry = selectedEntry();492        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });493      },494      copy_username: () => {495        const entry = selectedEntry();496        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });497      },498      copy_totp: () => {499        const entry = selectedEntry();500        if (!entry?.totp) return;501        try {502          const { code } = generateTOTP(entry.totp);503          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });504        } catch { /* invalid TOTP secret — silent */ }505      },506      new_entry: () => handleAdd(),507      edit_entry: () => {508        const entry = selectedEntry();509        // Passkey-only entries have nothing user-editable in the Add view; the510        // passkey credential itself is opaque. Skip the edit action for them.511        if (!entry || isPasskeyOnly(entry)) return;512        setEditEntry(entry);513        setView("add");514      },515      delete_entry: () => {516        if (selectedEntry()) void handleDelete();517      },518      lock_vault: () => { void handleHeaderLock(); },519      search: () => openList(),520      nav_prev: () => navigate(-1),521      nav_next: () => navigate(1),522      jump_vault: () => setView("entry"),523      jump_settings: () => setView("settings"),524      show_help: () => setShowShortcutsHelp(true),525    };526527    // Actions that are MEANINGFUL only on the entry-detail view. Outside528    // that scope the binding is dormant — pressing C while on Settings529    // does nothing rather than awkwardly copying from a now-stale entry.530    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([531      "copy_password", "copy_username", "copy_totp",532      "edit_entry", "delete_entry", "nav_prev", "nav_next",533    ]);534535    const handleGlobalKeydown = (e: KeyboardEvent) => {536      const v = view();537      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"538        || (e.target as HTMLElement)?.tagName === "TEXTAREA"539        || (e.target as HTMLElement)?.isContentEditable;540      const isPrintableSearchKey =541        e.key.length === 1 &&542        !e.ctrlKey &&543        !e.metaKey &&544        !e.altKey;545546      // No input during the pro celebration sequence547      if (v === "pro-celebration") return;548549      // Help dialog: Escape closes it; eat the keypress so it doesn't550      // also navigate away from the underlying view.551      if (showShortcutsHelp()) {552        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }553        return;554      }555556      // ── Escape — fixed binding (not user-customizable) ───────557      if (e.key === "Escape") {558        if (v === "list") { setView("entry"); return; }559        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }560        if (v === "sync-pairing") { setView("settings"); return; }561      }562563      // Bindings-driven dispatch. Single-key letter bindings without564      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is565      // inside an input, so users can type into search/forms normally.566      const bindings = shortcutBindings();567      for (const action of Object.keys(bindings) as ShortcutAction[]) {568        const binding = bindings[action];569        if (!matchKeybinding(e, binding)) continue;570        // Single-key letter bindings need the input-focus guard. Bindings571        // with any modifier are safe — Ctrl+L doesn't conflict with typing.572        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;573        if (!hasMod && binding.key.length === 1 && inInput) return;574        if (ENTRY_SCOPED.has(action) && v !== "entry") return;575        e.preventDefault();576        SHORTCUT_HANDLERS[action]?.();577        return;578      }579580      // Type-to-search: in entry view, any printable key not consumed by a581      // shortcut above primes the list search seed and opens the list.582      // Kept outside the bindings table because it's a behavior, not a583      // discrete action — every printable character can trigger it.584      if (v === "entry" && !inInput && isPrintableSearchKey) {585        e.preventDefault();586        primeListSearch(e.key);587        return;588      }589    };590    window.addEventListener("keydown", handleGlobalKeydown);591    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));592593    const handleStorageChanged = (594      changes: Record<string, chrome.storage.StorageChange>,595      areaName: string596    ) => {597      if (areaName !== "session") return;598      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {599        return;600      }601      void refreshPendingPasskey();602    };603    chrome.storage.onChanged.addListener(handleStorageChanged);604    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));605  });606607  async function refreshCurrentTab() {608    try {609      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });610      const url = tab?.url ?? tab?.pendingUrl ?? "";611      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");612      // Skip extension/internal URLs — adding chrome://, about:, or613      // chrome-extension:// to a vault entry is never what the user wants.614      const isWebUrl = /^https?:\/\//i.test(url);615      setCurrentTabUrl(isWebUrl ? url : "");616    } catch {617      setCurrentTabDomain("");618      setCurrentTabUrl("");619    }620  }621622  async function refreshPendingPasskey() {623    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });624    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);625  }626627  async function refreshIncomingPairing() {628    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });629    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;630    setIncomingPair(data);631  }632633  // Drains a single one-shot record left by the background when 6-digit634  // pairing succeeded while the popup was closed (or the SyncPairing view was635  // navigated away from before it could show its own success card).636  async function consumeRecentPairing() {637    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });638    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;639    if (data?.deviceName) {640      setRecentPairToast(data.deviceName);641      window.setTimeout(() => setRecentPairToast(null), 4000);642    }643  }644645  async function respondIncomingPairing(accept: boolean) {646    if (incomingPairResponding()) return;647    setIncomingPairResponding(true);648    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });649    setIncomingPair(null);650    setIncomingPairResponding(false);651  }652653  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a654  // request appears, ticks once per second, and clears the banner if the655  // request expires while the popup is open.656  createEffect(() => {657    const req = incomingPair();658    if (!req) return;659    const handle = window.setInterval(() => {660      setIncomingPairTick((tick) => tick + 1);661      if (Date.now() >= req.expiresAt) {662        setIncomingPair(null);663        window.clearInterval(handle);664      }665    }, 1000);666    onCleanup(() => window.clearInterval(handle));667  });668669  async function refreshProStatus() {670    const res = await sendMessage({ type: "GET_LICENSE" });671    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;672    setProStatus(Boolean(data?.valid && data?.plan === "pro"));673  }674675  async function restoreSettings() {676    const res = await sendMessage({ type: "GET_SETTINGS" });677    const s = (res as { ok: boolean; data?: any }).data ?? {};678    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {679      setAccentColor(s.accentColor as AccentColorName);680    }681    setTheme(s.theme === "light" ? "light" : "dark");682    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {683      setDisplayFont(s.displayFont);684    } else {685      setDisplayFont("cormorant-italic");686    }687    if (s.textSize === "small" || s.textSize === "large") {688      setTextSize(s.textSize);689    } else {690      setTextSize("medium");691    }692    setReduceMotion(s.reduceMotion === true);693    setLockOnClose(s.lockOnClose !== false);694    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);695    setBreachMonitoring(s.breachMonitoring !== false);696    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);697    setShortcutBindings(getActiveBindings(s.shortcuts));698  }699700  async function applyTrashRetention(days: number) {701    setTrashRetentionDays(days);702    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });703  }704705  function primeListSearch(seed: string) {706    setListSearchSeed(seed);707    setListSearchSeedNonce((value) => value + 1);708    openList();709  }710711  // Returns null when it detected a dead service worker and triggered handleLock().712  // Callers that need to abort (e.g. openVault) check for null rather than relying713  // on view() state, which may already be "lock" during normal startup flows.714  async function loadEntries(): Promise<VaultEntry[] | null> {715    const response = await sendMessage({ type: "GET_ENTRIES" });716    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };717718    // If the service worker was killed and restarted (MV3 workers sleep), the719    // vault will be locked again — or the worker may not respond at all.720    // In either case, send the user to the lock screen rather than silently721    // showing an empty vault (which looks like data loss).722    if (!res.ok) {723      if (724        res.error === "vault locked" ||725        res.error === "SERVICE_WORKER_UNAVAILABLE" ||726        (typeof res.error === "string" && res.error.includes("locked"))727      ) {728        handleLock();729        return null; // signal emergency lock to callers730      }731      return [];732    }733734    const loadedEntries = res.data ?? [];735    setEntries(loadedEntries);736737    const currentId = selectedEntry()?.id;738    if (currentId) {739      setSelectedEntry(740        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null741      );742    }743744    return loadedEntries;745  }746747  async function openVault(preferredEntryId?: string, skipViewSet = false) {748    // Purge expired trash entries on each vault open749    const retDays = trashRetentionDays();750    if (retDays > 0) {751      void sendMessage({752        type: "PURGE_EXPIRED_TRASH",753        payload: { retentionMs: retDays * 86_400_000 },754      });755    }756757    const loadedEntries = await loadEntries();758759    // null means loadEntries() triggered an emergency lock (service worker died).760    // Don't override it by setting view back to "entry" with an empty vault.761    if (loadedEntries === null) return;762763    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry764    let nextSelectedEntry: VaultEntry | null = null;765    if (preferredEntryId) {766      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;767    }768    if (!nextSelectedEntry) {769      const tabDomain = currentTabDomain();770      if (tabDomain) {771        nextSelectedEntry = loadedEntries.find((e) => {772          if (e.type === "login") {773            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;774            for (const extra of e.additionalUrls ?? []) {775              if ((extractDomain(extra) ?? "") === tabDomain) return true;776            }777            return false;778          }779          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;780          return false;781        }) ?? null;782      }783    }784    nextSelectedEntry ??= loadedEntries[0] ?? null;785786    setSelectedEntry(nextSelectedEntry);787    setEditEntry(undefined);788    setContentTransitioning(false);789    setContentPhase("enter");790    queueContentIdle();791    if (!skipViewSet) setView("entry");792  }793794  async function handleUnlock() {795    // If the user previously created a vault but hadn't yet confirmed their796    // recovery words (and the browser was closed before they could), the797    // peach_recovery_pending flag is still set in storage.local. Re-route798    // back to the recovery surface so they finish the confirmation step799    // before reaching the entries view — the words can be re-derived now800    // that the vault is unlocked again.801    let recoveryPending = false;802    try {803      const out = await chrome.storage.local?.get("peach_recovery_pending");804      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";805    } catch { /* best-effort */ }806    if (recoveryPending) {807      setForceRecoveryWords(true);808      setView("lock");809      triggerPipPulse();810      await restoreSettings();811      return;812    }813    setHasVault(true);814    triggerPipPulse();815    await restoreSettings();816    const celebrating = pendingCelebration();817    if (celebrating) {818      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });819      setPendingCelebration(false);820    }821    await openVault(undefined, celebrating);822    if (celebrating) {823      setView("pro-celebration");824      window.setTimeout(() => setView("entry"), 2500);825    }826  }827828  function handleSelectEntry(entry: VaultEntry) {829    setSelectedEntry(entry);830    setContentTransitioning(false);831    setContentPhase("enter");832    queueContentIdle();833    setView("entry");834  }835836  function handleAdd() {837    setEditEntry(undefined);838    setView("add");839  }840841  async function handleDelete() {842    const entry = selectedEntry();843    if (!entry) return;844    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });845    const loadedEntries = await loadEntries() ?? [];846    setSelectedEntry(loadedEntries[0] ?? null);847    setView("entry");848  }849850  async function handleDeleteMany(ids: string[]) {851    for (const id of ids) {852      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });853    }854    const loadedEntries = await loadEntries() ?? [];855    // If the currently selected entry was among the deleted, move to first856    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);857    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);858  }859860  async function handleSave(savedEntry?: VaultEntry) {861    await openVault(savedEntry?.id);862  }863864  function handleBack() {865    setEditEntry(undefined);866    setView("entry");867  }868869  function handleLock() {870    clearCanarySuppressions();871    setEntries([]);872    setSelectedEntry(null);873    setEditEntry(undefined);874    setContentPhase("idle");875    setView("lock");876  }877878  function handleHeaderLock() {879    // Lock the UI immediately — do not wait for the service worker. If the SW880    // is dead or slow, the 5s sendMessage timeout would create a dead-click881    // window. The SW will lock on its next wake regardless.882    handleLock();883    void sendMessage({ type: "LOCK" });884  }885886  function navigate(dir: number) {887    const allEntries = entries();888    if (allEntries.length === 0) return;889    const currentIndex = selectedIndex();890    const baseIndex = currentIndex >= 0 ? currentIndex : 0;891    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;892    setSelectedEntry(allEntries[nextIndex]);893    setContentPhase("enter");894    queueContentIdle();895  }896897  function openList() {898    setView("list");899  }900901  function openHealth() {902    setEditEntry(undefined);903    setView("health");904  }905906  function handleOpenFileImport() {907    setRestoreView("file");908  }909910  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;911912  function handleFixEntry(entry: VaultEntry) {913    // Passkey-only entries have no editable surface — drop into view mode914    // instead of opening the Add editor.915    if (isPasskeyOnly(entry)) {916      setSelectedEntry(entry);917      setView("entry");918      return;919    }920    setEditEntry(entry);921    setView("add");922  }923924  const isLockedView = () => view() === "lock";925926  async function handleApprovePendingPasskey() {927    const pending = pendingPasskey();928    if (!pending) return;929    if (pending.browser === "firefox" && pending.type === "create") {930      // Firefox path: popup itself runs navigator.credentials.create. The931      // background never approved/rejected anything — it just stashed932      // intent. After the popup-driven flow resolves (success or cancel),933      // clear the pending key so the popup doesn't re-show this on next open.934      const { createFirefoxPasskey } = await import("./firefox-passkey");935      const result = await createFirefoxPasskey(pending);936      if (!result.ok) {937        console.warn("Peach Firefox passkey create failed:", result.error);938      }939      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });940      setPendingPasskey(null);941      void loadEntries();942      return;943    }944    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });945    setPendingPasskey(null);946  }947948  async function handleDenyPendingPasskey() {949    const pending = pendingPasskey();950    if (!pending) return;951    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });952    setPendingPasskey(null);953  }954955  function queueContentIdle(after?: () => void) {956    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);957    contentPhaseTimer = window.setTimeout(() => {958      setContentPhase("idle");959      after?.();960    }, ENTRY_TRANSITION_SETTLE_MS);961  }962963  return (964    <div class="popup-root peach-theme">965      <Show when={bootState() === "ready"}>966        <Show967          when={!pendingPasskey()}968          fallback={969            <PasskeyApprovalView970              type={pendingPasskey()!.type}971              rpName={pendingPasskey()!.rpName}972              rpId={pendingPasskey()!.rpId}973              userName={pendingPasskey()!.userName}974              userDisplayName={pendingPasskey()!.userDisplayName}975              onApprove={handleApprovePendingPasskey}976              onDeny={handleDenyPendingPasskey}977            />978          }979        >980          <Show981            when={!isLockedView()}982            fallback={983              <Show984                when={onboarded() || hasVault()}985                fallback={986                  <Onboarding987                    onComplete={() => { setOnboarded(true); }}988                  />989                }990              >991                <LockView992                  hasVault={hasVault()}993                  ready={bootState() === "ready"}994                  isPro={proStatus()}995                  forceRecoveryWords={forceRecoveryWords()}996                  onUnlock={() => {997                    // RecoveryWordDisplay clears the storage flag before998                    // calling onDone, so handleUnlock will see no pending999                    // confirmation and proceed through the normal path.1000                    if (forceRecoveryWords()) setForceRecoveryWords(false);1001                    return handleUnlock();1002                  }}1003                  onBackToOnboarding={1004                    !hasVault()1005                      ? () => setOnboarded(false)1006                      : undefined1007                  }1008                />1009              </Show>1010            }1011          >1012            <Show1013              when={view() !== "pro-celebration"}1014              fallback={<ProCelebration />}1015            >1016            <section1017              id="hd-shell"1018              class="peach-shell peach-theme"1019              data-surface="extension"1020            >1021            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1022              <PeachWordmark unlocked />1023              <div class="peach-chrome-actions">1024                <button1025                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1026                  onClick={() => setView("settings")}1027                  aria-label="Settings"1028                >1029                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1030                    <path1031                      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"1032                      stroke="currentColor"1033                      stroke-width="0.9"1034                    />1035                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1036                  </svg>1037                </button>1038                <button1039                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1040                  onClick={handleAdd}1041                  aria-label="New entry"1042                >1043                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1044                    <path d="M5.5 1v9M1 5.5h9" />1045                  </svg>1046                </button>1047                <button1048                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1049                  onClick={() => void handleHeaderLock()}1050                  aria-label="Lock vault"1051                >1052                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1053                    <path1054                      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"1055                      stroke="currentColor"1056                      stroke-width="1"1057                      stroke-linecap="round"1058                    />1059                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1060                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1061                  </svg>1062                </button>1063              </div>1064            </header>10651066            <Show when={recentPairToast()}>1067              <div class="peach-pair-toast" role="status" aria-live="polite">1068                Paired with <strong>{recentPairToast()}</strong>1069              </div>1070            </Show>10711072            <Show when={incomingPair() !== null}>1073              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1074                <div class="peach-pair-request-header">1075                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1076                  <span class="peach-pair-request-title">Pairing request</span>1077                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1078                </div>1079                <p class="peach-pair-request-body">1080                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1081                </p>1082                <div class="peach-pair-request-actions">1083                  <button1084                    class="peach-btn peach-btn--ghost peach-btn--sm"1085                    onClick={() => void respondIncomingPairing(false)}1086                    disabled={incomingPairResponding()}1087                  >1088                    Reject1089                  </button>1090                  <button1091                    class="peach-btn peach-btn--accent peach-btn--sm"1092                    onClick={() => void respondIncomingPairing(true)}1093                    disabled={incomingPairResponding()}1094                  >1095                    Accept1096                  </button>1097                </div>1098              </div>1099            </Show>11001101            <Show when={pendingProNotice() !== null}>1102              <div class="peach-pro-notice-banner">1103                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1104                <button1105                  class="peach-pro-notice-link"1106                  onClick={() => {1107                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1108                    setSettingsInitialSection("license");1109                    setView("settings");1110                    setPendingProNotice(null);1111                  }}1112                >1113                  Learn more →1114                </button>1115                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1116              </div>1117            </Show>11181119            <div class="peach-shell-body">1120              <div class="peach-shell-veil"></div>1121              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1122                <EntryView1123                  entry={selectedEntry()}1124                  currentTabUrl={currentTabUrl()}1125                  onDelete={handleDelete}1126                  onFieldSaved={() => void loadEntries()}1127                  onEscape={() => { setView("list"); }}1128                />1129              </div>11301131              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1132                <div class="peach-search-bar">1133                  <span class="peach-search-icon">1134                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1135                      <circle cx="5.5" cy="5.5" r="3.75" />1136                      <path d="M8.75 8.75L11.5 11.5" />1137                    </svg>1138                  </span>1139                  <input1140                    class="peach-search-input"1141                    placeholder="search vault..."1142                    autocomplete="off"1143                    aria-label="Search vault entries"1144                    onClick={openList}1145                    onFocus={openList}1146                    readOnly1147                  />1148                  <div class="peach-search-meta">1149                    <span class="peach-search-counter">1150                      {entries().length > 01151                        ? `${selectedIndex() + 1} / ${entries().length}`1152                        : "0 entries"}1153                    </span>1154                    <span class="peach-divider"></span>1155                    <button1156                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1157                      onClick={() => navigate(-1)}1158                      aria-label="Previous entry"1159                      disabled={entries().length === 0}1160                    >1161                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1162                        <path d="M5 1L1 5.5L5 10" />1163                      </svg>1164                    </button>1165                    <button1166                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1167                      onClick={() => navigate(1)}1168                      aria-label="Next entry"1169                      disabled={entries().length === 0}1170                    >1171                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1172                        <path d="M1 1L5 5.5L1 10" />1173                      </svg>1174                    </button>1175                  </div>1176                </div>1177              </section>1178            </div>11791180            <Show when={view() === "list"}>1181              <VaultView1182                entries={entries()}1183                selectedEntryId={selectedEntry()?.id}1184                currentTabDomain={currentTabDomain()}1185                sortOrder={sortOrder()}1186                searchSeed={listSearchSeed()}1187                searchSeedNonce={listSearchSeedNonce()}1188                onSelectEntry={handleSelectEntry}1189                onSortOrderChange={setSortOrder}1190                onAdd={handleAdd}1191                onClose={() => setView("entry")}1192                onOpenTrash={() => setView("trash")}1193                onDeleteMany={handleDeleteMany}1194              />1195            </Show>1196            <Show when={view() === "settings"}>1197              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1198                <SettingsView1199                  entriesCount={entries().length}1200                  breachMonitoring={breachMonitoring()}1201                  lockOnClose={lockOnClose()}1202                  autoLockMinutes={autoLockMinutes()}1203                  trashRetentionDays={trashRetentionDays()}1204                  theme={theme()}1205                  accentColor={accentColor()}1206                  displayFont={displayFont()}1207                  textSize={textSize()}1208                  reduceMotion={reduceMotion()}1209                  isPro={proStatus()}1210                  initialSection={settingsInitialSection()}1211                  upgradeHighlight={upgradeHighlight()}1212                  onBreachMonitoringChange={applyBreachMonitoring}1213                  onLockOnCloseChange={applyLockOnClose}1214                  onAutoLockMinutesChange={applyAutoLockMinutes}1215                  onTrashRetentionChange={applyTrashRetention}1216                  onThemeChange={applyTheme}1217                  onAccentChange={applyAccentColor}1218                  onDisplayFontChange={applyDisplayFont}1219                  onTextSizeChange={applyTextSize}1220                  onReduceMotionChange={applyReduceMotion}1221                  shortcuts={shortcutBindings()}1222                  onShortcutsChange={applyShortcuts}1223                  onLicenseChange={async () => {1224                    // After activation/deactivation: refresh Pro status,1225                    // re-load entries (defensive — signal state can drift if1226                    // the SW briefly restarts during the verify+save round-trip),1227                    // and replay the Pro celebration if this is the first time1228                    // a valid Pro license is seen on this device.1229                    await refreshProStatus();1230                    void loadEntries();1231                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1232                    if ((should as { ok: boolean; data?: boolean }).data === true) {1233                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1234                      setView("pro-celebration");1235                      window.setTimeout(() => setView("settings"), 2500);1236                    }1237                  }}1238                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1239                  onImport={() => setView("import")}1240                  onExport={() => setView("export")}1241                  onBreachCheckDone={loadEntries}1242                  onOpenHealth={openHealth}1243                  onOpenSyncPairing={() => setView("sync-pairing")}1244                  onOpenFileImport={handleOpenFileImport}1245                  onOpenPanic={() => setView("panic")}1246                />1247              </Suspense>1248            </Show>1249            <Show when={view() === "sync-pairing"}>1250              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1251                <SyncPairingView1252                  onClose={() => setView("settings")}1253                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1254                />1255              </Suspense>1256            </Show>1257            <Show when={view() === "add"}>1258              <AddView1259                entry={editEntry()}1260                entries={entries()}1261                onBack={handleBack}1262                onSave={handleSave}1263              />1264            </Show>1265            <Show when={view() === "import"}>1266              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1267                <ImportView onBack={handleBack} onImport={handleSave} />1268              </Suspense>1269            </Show>1270            <Show when={view() === "export"}>1271              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1272                <ExportView1273                  onBack={() => {1274                    if (returnToPanic()) {1275                      setReturnToPanic(false);1276                      setView("panic");1277                    } else {1278                      handleBack();1279                    }1280                  }}1281                />1282              </Suspense>1283            </Show>1284            <Show when={view() === "panic"}>1285              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1286                <PanicView1287                  onCancel={() => setView("settings")}1288                  onOpenExport={() => {1289                    setReturnToPanic(true);1290                    setView("export");1291                  }}1292                  onDestroyed={async () => {1293                    clearCanarySuppressions();1294                    setEntries([]);1295                    setSelectedEntry(null);1296                    setEditEntry(undefined);1297                    setHasVault(false);1298                    setOnboarded(false);1299                    setProStatus(false);1300                    setPendingPasskey(null);1301                    setUpgradeHighlight(null);1302                    setSettingsInitialSection(null);1303                    setPendingProNotice(null);1304                    setPendingCelebration(false);1305                    setReturnToPanic(false);1306                    setContentPhase("idle");1307                    setView("lock");1308                  }}1309                />1310              </Suspense>1311            </Show>1312            <Show when={view() === "health"}>1313              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1314                <HealthView1315                  entries={entries()}1316                  isPro={proStatus()}1317                  onFixEntry={handleFixEntry}1318                  onBack={() => setView("settings")}1319                  onRefresh={loadEntries}1320                />1321              </Suspense>1322            </Show>1323            <Show when={view() === "trash"}>1324              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1325                <TrashView1326                  onBack={() => setView("list")}1327                  onRestored={() => void loadEntries()}1328                />1329              </Suspense>1330            </Show>1331            <Show when={restoreView() === "file"}>1332              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1333                <ImportView1334                  mode="onboarding"1335                  replacesExistingVault={true}1336                  onBack={() => setRestoreView(null)}1337                  onImport={async () => {1338                    setRestoreView(null);1339                    await handleUnlock();1340                  }}1341                />1342              </Suspense>1343            </Show>1344            </section>1345            </Show>1346          </Show>1347        </Show>1348      </Show>1349      <Show when={showShortcutsHelp()}>1350        <ShortcutsHelpOverlay1351          bindings={shortcutBindings()}1352          onClose={() => setShowShortcutsHelp(false)}1353        />1354      </Show>1355    </div>1356  );1357}13581359function ShortcutsHelpOverlay(props: {1360  bindings: Record<ShortcutAction, Keybinding>;1361  onClose: () => void;1362}) {1363  return (1364    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1365      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1366        <div class="peach-shortcuts-help-head">1367          <h3>Keyboard shortcuts</h3>1368          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1369        </div>1370        <div class="peach-shortcuts-help-body">1371          <p class="peach-settings-sub-label">ENTRY VIEW</p>1372          <ul>1373            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1374              <li>1375                <span>{d.label}</span>1376                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1377              </li>1378            ))}1379          </ul>1380          <p class="peach-settings-sub-label">ANYWHERE</p>1381          <ul>1382            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1383              <li>1384                <span>{d.label}</span>1385                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1386              </li>1387            ))}1388          </ul>1389        </div>1390      </div>1391    </div>1392  );1393}