App.tsx

54.3 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";2829export { sendMessage } from "../shared/bridge";3031const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));32const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));33const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));34const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));35const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));36const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));37const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));3839type View =40  | "lock"41  | "pro-celebration"42  | "entry"43  | "list"44  | "add"45  | "settings"46  | "sync-pairing"47  | "import"48  | "export"49  | "health"50  | "trash"51  | "panic";52type BootState = "loading" | "ready";5354const canarySuppressMap = new Map<string, boolean>();55let shellRingAnimation: Animation | null = null;5657export function isCanarySuppressed(entryId: string): boolean {58  return canarySuppressMap.get(entryId) ?? false;59}6061export function setCanarySuppressed(entryId: string, suppressed: boolean): void {62  canarySuppressMap.set(entryId, suppressed);63}6465export function clearCanarySuppressions(): void {66  canarySuppressMap.clear();67}6869export function triggerRing() {70  const shell = document.getElementById("hd-shell");71  if (!shell) return;7273  shellRingAnimation?.cancel();74  shell.dataset.glowing = "true";75  const animation = shell.animate(76    [77      { offset: 0, boxShadow: "var(--copy-shadow)" },78      {79        offset: 0.3,80        boxShadow:81          "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)",82      },83      { offset: 1, boxShadow: "var(--copy-shadow)" },84    ],85    {86      duration: 720,87      easing: "cubic-bezier(0.4, 0, 0.2, 1)",88      fill: "none",89    }90  );91  shellRingAnimation = animation;92  const clearGlow = () => {93    if (shellRingAnimation !== animation) return;94    shellRingAnimation = null;95    delete shell.dataset.glowing;96  };97  animation.onfinish = clearGlow;98  animation.oncancel = clearGlow;99}100101102export function triggerPipPulse() {103  const pip = document.querySelector(".peach-status-pip, .pip");104  if (pip) {105    pip.classList.remove("pulse");106    void (pip as HTMLElement).offsetWidth;107    pip.classList.add("pulse");108  }109}110111const ENTRY_TRANSITION_EXIT_MS = 95;112const ENTRY_TRANSITION_SETTLE_MS = 135;113114export default function App() {115  const [bootState, setBootState] = createSignal<BootState>("loading");116  const [view, setView] = createSignal<View>("lock");117  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(118    "enter"119  );120  const [contentTransitioning, setContentTransitioning] = createSignal(false);121  const [hasVault, setHasVault] = createSignal(false);122  const [onboarded, setOnboarded] = createSignal(true);123  const [entries, setEntries] = createSignal<VaultEntry[]>([]);124  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);125  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);126  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");127  const [theme, setTheme] = createSignal<"dark" | "light">("dark");128  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");129  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");130  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);131  const [lockOnClose, setLockOnClose] = createSignal(true);132  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);133  const [breachMonitoring, setBreachMonitoring] = createSignal(true);134  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);135  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);136  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);137  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);138  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);139  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");140  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");141  // Cached Pro status — synchronous for render paths. Background's142  // GET_LICENSE is async, but render-time reads of isPro() must not block.143  // Refreshed at boot, after activate/deactivate, and whenever the popup144  // re-opens onto a stored license that has changed via another window.145  const [proStatus, setProStatus] = createSignal(false);146  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);147  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);148  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");149  const [listSearchSeed, setListSearchSeed] = createSignal("");150  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);151  const [pendingCelebration, setPendingCelebration] = createSignal(false);152  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);153  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);154  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);155  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);156  const [incomingPairTick, setIncomingPairTick] = createSignal(0);157  const incomingPairSecondsLeft = () => {158    void incomingPairTick();159    const req = incomingPair();160    if (!req) return 0;161    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));162  };163  // True while Panic Step 1 has bounced the user out to Export. When Export's164  // onBack fires we return to Panic instead of Settings so the user keeps the165  // destruction context they came from.166  const [returnToPanic, setReturnToPanic] = createSignal(false);167  // Set on popup boot when peach_recovery_pending flag is found in session168  // storage — instructs LockView to skip the unlock UI and open the recovery169  // words confirmation surface instead. Cleared via handleUnlock once the170  // user has typed the 3 confirmation words.171  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);172173  let contentPhaseTimer: number | undefined;174175  function applyAccent(name: AccentColorName) {176    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;177    const hex = color.hex;178    document.documentElement.style.setProperty("--peach-accent", hex);179    // Ambient surface variables — derived from the accent so surfaces shift180    // subtly toward the accent hue rather than staying fixed warm-brown.181    document.documentElement.style.setProperty("--peach-glow", hex + "2A");182    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");183    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");184  }185186  createEffect(() => {187    applyAccent(accentColor());188  });189190  createEffect(() => {191    document.documentElement.classList.toggle("light", theme() === "light");192    document.body.classList.toggle("light", theme() === "light");193  });194195  createEffect(() => {196    document.documentElement.setAttribute("data-display-font", displayFont());197  });198199  createEffect(() => {200    document.documentElement.setAttribute("data-text-size", textSize());201  });202203  createEffect(() => {204    if (reduceMotion()) {205      document.documentElement.setAttribute("data-motion", "reduce");206    } else {207      document.documentElement.removeAttribute("data-motion");208    }209  });210211  const selectedIndex = createMemo(() => {212    const currentId = selectedEntry()?.id;213    if (!currentId) return entries().length > 0 ? 0 : -1;214    return entries().findIndex((entry) => entry.id === currentId);215  });216217  async function applyAccentColor(name: AccentColorName) {218    applyAccent(name);219    setAccentColor(name);220    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });221  }222223  async function applyTheme(t: "dark" | "light") {224    setTheme(t);225    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });226  }227228  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {229    setDisplayFont(f);230    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });231  }232233  async function applyTextSize(size: "small" | "medium" | "large") {234    setTextSize(size);235    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });236  }237238  async function applyReduceMotion(enabled: boolean) {239    setReduceMotion(enabled);240    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });241  }242243  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload244  // small and lets future default updates land for actions the user hasn't245  // touched. Settings sends us the full active map; we filter and store.246  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {247    setShortcutBindings(active);248    const overrides: Record<string, Keybinding> = {};249    for (const action of Object.keys(active) as ShortcutAction[]) {250      const a = active[action];251      const d = DEFAULT_BINDINGS[action];252      const same = a.key === d.key253        && Boolean(a.ctrl)  === Boolean(d.ctrl)254        && Boolean(a.meta)  === Boolean(d.meta)255        && Boolean(a.shift) === Boolean(d.shift)256        && Boolean(a.alt)   === Boolean(d.alt);257      if (!same) overrides[action] = a;258    }259    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });260  }261262  async function applyLockOnClose(enabled: boolean) {263    setLockOnClose(enabled);264    await sendMessage({265      type: "UPDATE_SETTINGS",266      payload: { lockOnClose: enabled },267    });268  }269270  async function applyAutoLockMinutes(minutes: number) {271    setAutoLockMinutes(minutes);272    await sendMessage({273      type: "UPDATE_SETTINGS",274      payload: { autoLockMinutes: minutes },275    });276  }277278  async function applyBreachMonitoring(enabled: boolean) {279    setBreachMonitoring(enabled);280    await sendMessage({281      type: "UPDATE_SETTINGS",282      payload: { breachMonitoring: enabled },283    });284  }285286  onMount(async () => {287    // Resolve the active tab in parallel with the unlock/has-vault queries —288    // openVault()'s smart selection picks the entry matching currentTabDomain,289    // so it must be populated before openVault runs. Previously refreshCurrentTab290    // ran after openVault, leaving popups that booted already-unlocked falling291    // back to loadedEntries[0] instead of the domain match.292    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([293      sendMessage({ type: "IS_UNLOCKED" }),294      sendMessage({ type: "HAS_VAULT" }),295      refreshCurrentTab(),296      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),297    ]);298    const unlocked = Boolean(299      (unlockResponse as { ok: boolean; data?: boolean }).data300    );301    const vaultExists = Boolean(302      (vaultResponse as { ok: boolean; data?: boolean }).data303    );304    const shouldCelebrate = Boolean(305      (celebrationResponse as { ok: boolean; data?: boolean }).data306    );307    setHasVault(vaultExists);308    // Onboarding gate — show once on first install, never again. Existing309    // users (vaultExists) are auto-marked onboarded so they skip the flow310    // even on the very first popup open after this feature ships.311    try {312      const onboarded = await storageGet("peach_onboarded");313      const seen = onboarded === "true";314      if (vaultExists && !seen) {315        await storageSet("peach_onboarded", "true");316        setOnboarded(true);317      } else {318        setOnboarded(seen);319      }320    } catch {321      // storage unavailable — default to onboarded so we never block boot322      setOnboarded(true);323    }324    await Promise.all([restoreSettings(), refreshProStatus()]);325326    // Mark played before any animation so a crash mid-sequence never replays it327    if (shouldCelebrate) {328      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });329    }330331    // If the user created a vault but hasn't yet confirmed their recovery332    // words, route back to the recovery-words screen instead of opening the333    // entries view. The flag lives in chrome.storage.local so it survives334    // both popup close (SW suppresses lock-on-close) and full browser335    // restart (handleUnlock checks the same flag after a fresh password336    // unlock). Cleared when confirmation succeeds.337    let recoveryPending = false;338    try {339      const out = await chrome.storage.local?.get("peach_recovery_pending");340      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";341    } catch { /* best-effort */ }342343    if (recoveryPending && unlocked) {344      // forceRecoveryWords overrides LockView's hasVault gate so the345      // recovery surface renders even though the vault now exists.346      setForceRecoveryWords(true);347      setView("lock");348    } else if (unlocked && vaultExists) {349      await openVault(undefined, shouldCelebrate);350      if (shouldCelebrate) {351        setView("pro-celebration");352        window.setTimeout(() => setView("entry"), 2500);353      }354    } else if (shouldCelebrate) {355      setPendingCelebration(true);356    }357358    await refreshPendingPasskey();359    await refreshIncomingPairing();360    await consumeRecentPairing();361362    // Track tab changes so smart sort stays current363    const handleTabActivated = () => { void refreshCurrentTab(); };364    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {365      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();366    };367    try {368      chrome.tabs.onActivated.addListener(handleTabActivated);369      chrome.tabs.onUpdated.addListener(handleTabUpdated);370      onCleanup(() => {371        chrome.tabs.onActivated.removeListener(handleTabActivated);372        chrome.tabs.onUpdated.removeListener(handleTabUpdated);373      });374    } catch {375      // tabs permission may not be available in all contexts376    }377378    setBootState("ready");379    document.getElementById("pre-lock")?.setAttribute("hidden", "true");380381    // Check for pending session-storage notices from the background.382    if (chrome.storage.session) {383      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as384        Record<string, { feature?: string } | undefined>;385      if (session.pendingProGate?.feature) {386        await chrome.storage.session.remove("pendingProGate");387        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);388        setSettingsInitialSection("license");389        setView("settings");390      } else if (session.pendingProNotice?.feature) {391        await chrome.storage.session.remove("pendingProNotice");392        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });393      }394    }395396    // Warm the lazy-module cache so the Suspense fallback never shows for397    // locally-bundled extension views. Without this, the first navigation to398    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which399    // covers the shell and absorbs clicks on the header.400    void Promise.all([401      import("./views/Settings").catch(() => {}),402      import("./views/Import").catch(() => {}),403      import("./views/Export").catch(() => {}),404      import("./views/Health").catch(() => {}),405      import("./views/TrashView").catch(() => {}),406    ]);407408    // Lock-on-close via a persistent port. sendMessage in pagehide is409    // unreliable — the popup context tears down before the message lands.410    // The SW's onConnect listener locks when this port disconnects.411    let popupPort: chrome.runtime.Port | null = null;412    try {413      popupPort = chrome.runtime.connect({ name: "popup" });414    } catch { /* extension context invalidated — ignore */ }415    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });416417    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale418    // entries instead of waiting for the next GET_ENTRIES round-trip.419    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {420      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();421      if (msg?.type === "PRO_GATE_TRIGGERED") {422        setUpgradeHighlight(msg.payload?.feature ?? null);423        setSettingsInitialSection("license");424        setView("settings");425      }426      if (msg?.type === "INCOMING_PAIRING_REQUEST") {427        void refreshIncomingPairing();428      }429    };430    chrome.runtime.onMessage.addListener(handleRuntimeMessage);431    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));432433    // Action handlers — keyed by ShortcutAction. The dispatcher below tests434    // each binding against the event and runs the matching handler. New435    // shortcuts only need an entry here; the binding is data, not code.436    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {437      copy_password: () => {438        const entry = selectedEntry();439        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });440      },441      copy_username: () => {442        const entry = selectedEntry();443        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });444      },445      copy_totp: () => {446        const entry = selectedEntry();447        if (!entry?.totp) return;448        try {449          const { code } = generateTOTP(entry.totp);450          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });451        } catch { /* invalid TOTP secret — silent */ }452      },453      new_entry: () => handleAdd(),454      edit_entry: () => {455        const entry = selectedEntry();456        // Passkey-only entries have nothing user-editable in the Add view; the457        // passkey credential itself is opaque. Skip the edit action for them.458        if (!entry || isPasskeyOnly(entry)) return;459        setEditEntry(entry);460        setView("add");461      },462      delete_entry: () => {463        if (selectedEntry()) void handleDelete();464      },465      lock_vault: () => { void handleHeaderLock(); },466      search: () => openList(),467      nav_prev: () => navigate(-1),468      nav_next: () => navigate(1),469      jump_vault: () => setView("entry"),470      jump_settings: () => setView("settings"),471      show_help: () => setShowShortcutsHelp(true),472    };473474    // Actions that are MEANINGFUL only on the entry-detail view. Outside475    // that scope the binding is dormant — pressing C while on Settings476    // does nothing rather than awkwardly copying from a now-stale entry.477    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([478      "copy_password", "copy_username", "copy_totp",479      "edit_entry", "delete_entry", "nav_prev", "nav_next",480    ]);481482    const handleGlobalKeydown = (e: KeyboardEvent) => {483      const v = view();484      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"485        || (e.target as HTMLElement)?.tagName === "TEXTAREA"486        || (e.target as HTMLElement)?.isContentEditable;487      const isPrintableSearchKey =488        e.key.length === 1 &&489        !e.ctrlKey &&490        !e.metaKey &&491        !e.altKey;492493      // No input during the pro celebration sequence494      if (v === "pro-celebration") return;495496      // Help dialog: Escape closes it; eat the keypress so it doesn't497      // also navigate away from the underlying view.498      if (showShortcutsHelp()) {499        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }500        return;501      }502503      // ── Escape — fixed binding (not user-customizable) ───────504      if (e.key === "Escape") {505        if (v === "list") { setView("entry"); return; }506        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }507        if (v === "sync-pairing") { setView("settings"); return; }508      }509510      // Bindings-driven dispatch. Single-key letter bindings without511      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is512      // inside an input, so users can type into search/forms normally.513      const bindings = shortcutBindings();514      for (const action of Object.keys(bindings) as ShortcutAction[]) {515        const binding = bindings[action];516        if (!matchKeybinding(e, binding)) continue;517        // Single-key letter bindings need the input-focus guard. Bindings518        // with any modifier are safe — Ctrl+L doesn't conflict with typing.519        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;520        if (!hasMod && binding.key.length === 1 && inInput) return;521        if (ENTRY_SCOPED.has(action) && v !== "entry") return;522        e.preventDefault();523        SHORTCUT_HANDLERS[action]?.();524        return;525      }526527      // Type-to-search: in entry view, any printable key not consumed by a528      // shortcut above primes the list search seed and opens the list.529      // Kept outside the bindings table because it's a behavior, not a530      // discrete action — every printable character can trigger it.531      if (v === "entry" && !inInput && isPrintableSearchKey) {532        e.preventDefault();533        primeListSearch(e.key);534        return;535      }536    };537    window.addEventListener("keydown", handleGlobalKeydown);538    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));539540    const handleStorageChanged = (541      changes: Record<string, chrome.storage.StorageChange>,542      areaName: string543    ) => {544      if (areaName !== "session") return;545      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {546        return;547      }548      void refreshPendingPasskey();549    };550    chrome.storage.onChanged.addListener(handleStorageChanged);551    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));552  });553554  async function refreshCurrentTab() {555    try {556      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });557      const url = tab?.url ?? tab?.pendingUrl ?? "";558      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");559      // Skip extension/internal URLs — adding chrome://, about:, or560      // chrome-extension:// to a vault entry is never what the user wants.561      const isWebUrl = /^https?:\/\//i.test(url);562      setCurrentTabUrl(isWebUrl ? url : "");563    } catch {564      setCurrentTabDomain("");565      setCurrentTabUrl("");566    }567  }568569  async function refreshPendingPasskey() {570    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });571    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);572  }573574  async function refreshIncomingPairing() {575    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });576    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;577    setIncomingPair(data);578  }579580  // Drains a single one-shot record left by the background when 6-digit581  // pairing succeeded while the popup was closed (or the SyncPairing view was582  // navigated away from before it could show its own success card).583  async function consumeRecentPairing() {584    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });585    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;586    if (data?.deviceName) {587      setRecentPairToast(data.deviceName);588      window.setTimeout(() => setRecentPairToast(null), 4000);589    }590  }591592  async function respondIncomingPairing(accept: boolean) {593    if (incomingPairResponding()) return;594    setIncomingPairResponding(true);595    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });596    setIncomingPair(null);597    setIncomingPairResponding(false);598  }599600  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a601  // request appears, ticks once per second, and clears the banner if the602  // request expires while the popup is open.603  createEffect(() => {604    const req = incomingPair();605    if (!req) return;606    const handle = window.setInterval(() => {607      setIncomingPairTick((tick) => tick + 1);608      if (Date.now() >= req.expiresAt) {609        setIncomingPair(null);610        window.clearInterval(handle);611      }612    }, 1000);613    onCleanup(() => window.clearInterval(handle));614  });615616  async function refreshProStatus() {617    const res = await sendMessage({ type: "GET_LICENSE" });618    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;619    setProStatus(Boolean(data?.valid && data?.plan === "pro"));620  }621622  async function restoreSettings() {623    const res = await sendMessage({ type: "GET_SETTINGS" });624    const s = (res as { ok: boolean; data?: any }).data ?? {};625    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {626      setAccentColor(s.accentColor as AccentColorName);627    }628    setTheme(s.theme === "light" ? "light" : "dark");629    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {630      setDisplayFont(s.displayFont);631    } else {632      setDisplayFont("cormorant-italic");633    }634    if (s.textSize === "small" || s.textSize === "large") {635      setTextSize(s.textSize);636    } else {637      setTextSize("medium");638    }639    setReduceMotion(s.reduceMotion === true);640    setLockOnClose(s.lockOnClose !== false);641    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);642    setBreachMonitoring(s.breachMonitoring !== false);643    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);644    setShortcutBindings(getActiveBindings(s.shortcuts));645  }646647  async function applyTrashRetention(days: number) {648    setTrashRetentionDays(days);649    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });650  }651652  function primeListSearch(seed: string) {653    setListSearchSeed(seed);654    setListSearchSeedNonce((value) => value + 1);655    openList();656  }657658  // Returns null when it detected a dead service worker and triggered handleLock().659  // Callers that need to abort (e.g. openVault) check for null rather than relying660  // on view() state, which may already be "lock" during normal startup flows.661  async function loadEntries(): Promise<VaultEntry[] | null> {662    const response = await sendMessage({ type: "GET_ENTRIES" });663    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };664665    // If the service worker was killed and restarted (MV3 workers sleep), the666    // vault will be locked again — or the worker may not respond at all.667    // In either case, send the user to the lock screen rather than silently668    // showing an empty vault (which looks like data loss).669    if (!res.ok) {670      if (671        res.error === "vault locked" ||672        res.error === "SERVICE_WORKER_UNAVAILABLE" ||673        (typeof res.error === "string" && res.error.includes("locked"))674      ) {675        handleLock();676        return null; // signal emergency lock to callers677      }678      return [];679    }680681    const loadedEntries = res.data ?? [];682    setEntries(loadedEntries);683684    const currentId = selectedEntry()?.id;685    if (currentId) {686      setSelectedEntry(687        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null688      );689    }690691    return loadedEntries;692  }693694  async function openVault(preferredEntryId?: string, skipViewSet = false) {695    // Purge expired trash entries on each vault open696    const retDays = trashRetentionDays();697    if (retDays > 0) {698      void sendMessage({699        type: "PURGE_EXPIRED_TRASH",700        payload: { retentionMs: retDays * 86_400_000 },701      });702    }703704    const loadedEntries = await loadEntries();705706    // null means loadEntries() triggered an emergency lock (service worker died).707    // Don't override it by setting view back to "entry" with an empty vault.708    if (loadedEntries === null) return;709710    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry711    let nextSelectedEntry: VaultEntry | null = null;712    if (preferredEntryId) {713      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;714    }715    if (!nextSelectedEntry) {716      const tabDomain = currentTabDomain();717      if (tabDomain) {718        nextSelectedEntry = loadedEntries.find((e) => {719          if (e.type === "login") {720            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;721            for (const extra of e.additionalUrls ?? []) {722              if ((extractDomain(extra) ?? "") === tabDomain) return true;723            }724            return false;725          }726          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;727          return false;728        }) ?? null;729      }730    }731    nextSelectedEntry ??= loadedEntries[0] ?? null;732733    setSelectedEntry(nextSelectedEntry);734    setEditEntry(undefined);735    setContentTransitioning(false);736    setContentPhase("enter");737    queueContentIdle();738    if (!skipViewSet) setView("entry");739  }740741  async function handleUnlock() {742    // If the user previously created a vault but hadn't yet confirmed their743    // recovery words (and the browser was closed before they could), the744    // peach_recovery_pending flag is still set in storage.local. Re-route745    // back to the recovery surface so they finish the confirmation step746    // before reaching the entries view — the words can be re-derived now747    // that the vault is unlocked again.748    let recoveryPending = false;749    try {750      const out = await chrome.storage.local?.get("peach_recovery_pending");751      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";752    } catch { /* best-effort */ }753    if (recoveryPending) {754      setForceRecoveryWords(true);755      setView("lock");756      triggerPipPulse();757      await restoreSettings();758      return;759    }760    setHasVault(true);761    triggerPipPulse();762    await restoreSettings();763    const celebrating = pendingCelebration();764    if (celebrating) {765      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });766      setPendingCelebration(false);767    }768    await openVault(undefined, celebrating);769    if (celebrating) {770      setView("pro-celebration");771      window.setTimeout(() => setView("entry"), 2500);772    }773  }774775  function handleSelectEntry(entry: VaultEntry) {776    setSelectedEntry(entry);777    setContentTransitioning(false);778    setContentPhase("enter");779    queueContentIdle();780    setView("entry");781  }782783  function handleAdd() {784    setEditEntry(undefined);785    setView("add");786  }787788  async function handleDelete() {789    const entry = selectedEntry();790    if (!entry) return;791    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });792    const loadedEntries = await loadEntries() ?? [];793    setSelectedEntry(loadedEntries[0] ?? null);794    setView("entry");795  }796797  async function handleDeleteMany(ids: string[]) {798    for (const id of ids) {799      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });800    }801    const loadedEntries = await loadEntries() ?? [];802    // If the currently selected entry was among the deleted, move to first803    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);804    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);805  }806807  async function handleSave(savedEntry?: VaultEntry) {808    await openVault(savedEntry?.id);809  }810811  function handleBack() {812    setEditEntry(undefined);813    setView("entry");814  }815816  function handleLock() {817    clearCanarySuppressions();818    setEntries([]);819    setSelectedEntry(null);820    setEditEntry(undefined);821    setContentPhase("idle");822    setView("lock");823  }824825  function handleHeaderLock() {826    // Lock the UI immediately — do not wait for the service worker. If the SW827    // is dead or slow, the 5s sendMessage timeout would create a dead-click828    // window. The SW will lock on its next wake regardless.829    handleLock();830    void sendMessage({ type: "LOCK" });831  }832833  function navigate(dir: number) {834    const allEntries = entries();835    if (allEntries.length === 0) return;836    const currentIndex = selectedIndex();837    const baseIndex = currentIndex >= 0 ? currentIndex : 0;838    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;839    setSelectedEntry(allEntries[nextIndex]);840    setContentPhase("enter");841    queueContentIdle();842  }843844  function openList() {845    setView("list");846  }847848  function openHealth() {849    setEditEntry(undefined);850    setView("health");851  }852853  function handleOpenFileImport() {854    setRestoreView("file");855  }856857  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;858859  function handleFixEntry(entry: VaultEntry) {860    // Passkey-only entries have no editable surface — drop into view mode861    // instead of opening the Add editor.862    if (isPasskeyOnly(entry)) {863      setSelectedEntry(entry);864      setView("entry");865      return;866    }867    setEditEntry(entry);868    setView("add");869  }870871  const isLockedView = () => view() === "lock";872873  async function handleApprovePendingPasskey() {874    const pending = pendingPasskey();875    if (!pending) return;876    if (pending.browser === "firefox" && pending.type === "create") {877      // Firefox path: popup itself runs navigator.credentials.create. The878      // background never approved/rejected anything — it just stashed879      // intent. After the popup-driven flow resolves (success or cancel),880      // clear the pending key so the popup doesn't re-show this on next open.881      const { createFirefoxPasskey } = await import("./firefox-passkey");882      const result = await createFirefoxPasskey(pending);883      if (!result.ok) {884        console.warn("Peach Firefox passkey create failed:", result.error);885      }886      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });887      setPendingPasskey(null);888      void loadEntries();889      return;890    }891    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });892    setPendingPasskey(null);893  }894895  async function handleDenyPendingPasskey() {896    const pending = pendingPasskey();897    if (!pending) return;898    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });899    setPendingPasskey(null);900  }901902  function queueContentIdle(after?: () => void) {903    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);904    contentPhaseTimer = window.setTimeout(() => {905      setContentPhase("idle");906      after?.();907    }, ENTRY_TRANSITION_SETTLE_MS);908  }909910  return (911    <div class="popup-root peach-theme">912      <Show when={bootState() === "ready"}>913        <Show914          when={!pendingPasskey()}915          fallback={916            <PasskeyApprovalView917              type={pendingPasskey()!.type}918              rpName={pendingPasskey()!.rpName}919              rpId={pendingPasskey()!.rpId}920              userName={pendingPasskey()!.userName}921              userDisplayName={pendingPasskey()!.userDisplayName}922              onApprove={handleApprovePendingPasskey}923              onDeny={handleDenyPendingPasskey}924            />925          }926        >927          <Show928            when={!isLockedView()}929            fallback={930              <Show931                when={onboarded() || hasVault()}932                fallback={933                  <Onboarding934                    onComplete={() => { setOnboarded(true); }}935                  />936                }937              >938                <LockView939                  hasVault={hasVault()}940                  ready={bootState() === "ready"}941                  isPro={proStatus()}942                  forceRecoveryWords={forceRecoveryWords()}943                  onUnlock={() => {944                    // RecoveryWordDisplay clears the storage flag before945                    // calling onDone, so handleUnlock will see no pending946                    // confirmation and proceed through the normal path.947                    if (forceRecoveryWords()) setForceRecoveryWords(false);948                    return handleUnlock();949                  }}950                  onBackToOnboarding={951                    !hasVault()952                      ? () => setOnboarded(false)953                      : undefined954                  }955                />956              </Show>957            }958          >959            <Show960              when={view() !== "pro-celebration"}961              fallback={<ProCelebration />}962            >963            <section964              id="hd-shell"965              class="peach-shell peach-theme"966              data-surface="extension"967            >968            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>969              <PeachWordmark unlocked />970              <div class="peach-chrome-actions">971                <button972                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"973                  onClick={() => setView("settings")}974                  aria-label="Settings"975                >976                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">977                    <path978                      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"979                      stroke="currentColor"980                      stroke-width="0.9"981                    />982                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />983                  </svg>984                </button>985                <button986                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"987                  onClick={handleAdd}988                  aria-label="New entry"989                >990                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">991                    <path d="M5.5 1v9M1 5.5h9" />992                  </svg>993                </button>994                <button995                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"996                  onClick={() => void handleHeaderLock()}997                  aria-label="Lock vault"998                >999                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1000                    <path1001                      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"1002                      stroke="currentColor"1003                      stroke-width="1"1004                      stroke-linecap="round"1005                    />1006                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1007                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1008                  </svg>1009                </button>1010              </div>1011            </header>10121013            <Show when={recentPairToast()}>1014              <div class="peach-pair-toast" role="status" aria-live="polite">1015                Paired with <strong>{recentPairToast()}</strong>1016              </div>1017            </Show>10181019            <Show when={incomingPair() !== null}>1020              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1021                <div class="peach-pair-request-header">1022                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1023                  <span class="peach-pair-request-title">Pairing request</span>1024                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1025                </div>1026                <p class="peach-pair-request-body">1027                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1028                </p>1029                <div class="peach-pair-request-actions">1030                  <button1031                    class="peach-btn peach-btn--ghost peach-btn--sm"1032                    onClick={() => void respondIncomingPairing(false)}1033                    disabled={incomingPairResponding()}1034                  >1035                    Reject1036                  </button>1037                  <button1038                    class="peach-btn peach-btn--accent peach-btn--sm"1039                    onClick={() => void respondIncomingPairing(true)}1040                    disabled={incomingPairResponding()}1041                  >1042                    Accept1043                  </button>1044                </div>1045              </div>1046            </Show>10471048            <Show when={pendingProNotice() !== null}>1049              <div class="peach-pro-notice-banner">1050                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1051                <button1052                  class="peach-pro-notice-link"1053                  onClick={() => {1054                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1055                    setSettingsInitialSection("license");1056                    setView("settings");1057                    setPendingProNotice(null);1058                  }}1059                >1060                  Learn more →1061                </button>1062                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1063              </div>1064            </Show>10651066            <div class="peach-shell-body">1067              <div class="peach-shell-veil"></div>1068              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1069                <EntryView1070                  entry={selectedEntry()}1071                  currentTabUrl={currentTabUrl()}1072                  onDelete={handleDelete}1073                  onFieldSaved={() => void loadEntries()}1074                  onEscape={() => { setView("list"); }}1075                />1076              </div>10771078              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1079                <div class="peach-search-bar">1080                  <span class="peach-search-icon">1081                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1082                      <circle cx="5.5" cy="5.5" r="3.75" />1083                      <path d="M8.75 8.75L11.5 11.5" />1084                    </svg>1085                  </span>1086                  <input1087                    class="peach-search-input"1088                    placeholder="search vault..."1089                    autocomplete="off"1090                    aria-label="Search vault entries"1091                    onClick={openList}1092                    onFocus={openList}1093                    readOnly1094                  />1095                  <div class="peach-search-meta">1096                    <span class="peach-search-counter">1097                      {entries().length > 01098                        ? `${selectedIndex() + 1} / ${entries().length}`1099                        : "0 entries"}1100                    </span>1101                    <span class="peach-divider"></span>1102                    <button1103                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1104                      onClick={() => navigate(-1)}1105                      aria-label="Previous entry"1106                      disabled={entries().length === 0}1107                    >1108                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1109                        <path d="M5 1L1 5.5L5 10" />1110                      </svg>1111                    </button>1112                    <button1113                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1114                      onClick={() => navigate(1)}1115                      aria-label="Next entry"1116                      disabled={entries().length === 0}1117                    >1118                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1119                        <path d="M1 1L5 5.5L1 10" />1120                      </svg>1121                    </button>1122                  </div>1123                </div>1124              </section>1125            </div>11261127            <Show when={view() === "list"}>1128              <VaultView1129                entries={entries()}1130                selectedEntryId={selectedEntry()?.id}1131                currentTabDomain={currentTabDomain()}1132                sortOrder={sortOrder()}1133                searchSeed={listSearchSeed()}1134                searchSeedNonce={listSearchSeedNonce()}1135                onSelectEntry={handleSelectEntry}1136                onSortOrderChange={setSortOrder}1137                onAdd={handleAdd}1138                onClose={() => setView("entry")}1139                onOpenTrash={() => setView("trash")}1140                onDeleteMany={handleDeleteMany}1141              />1142            </Show>1143            <Show when={view() === "settings"}>1144              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1145                <SettingsView1146                  entriesCount={entries().length}1147                  breachMonitoring={breachMonitoring()}1148                  lockOnClose={lockOnClose()}1149                  autoLockMinutes={autoLockMinutes()}1150                  trashRetentionDays={trashRetentionDays()}1151                  theme={theme()}1152                  accentColor={accentColor()}1153                  displayFont={displayFont()}1154                  textSize={textSize()}1155                  reduceMotion={reduceMotion()}1156                  isPro={proStatus()}1157                  initialSection={settingsInitialSection()}1158                  upgradeHighlight={upgradeHighlight()}1159                  onBreachMonitoringChange={applyBreachMonitoring}1160                  onLockOnCloseChange={applyLockOnClose}1161                  onAutoLockMinutesChange={applyAutoLockMinutes}1162                  onTrashRetentionChange={applyTrashRetention}1163                  onThemeChange={applyTheme}1164                  onAccentChange={applyAccentColor}1165                  onDisplayFontChange={applyDisplayFont}1166                  onTextSizeChange={applyTextSize}1167                  onReduceMotionChange={applyReduceMotion}1168                  shortcuts={shortcutBindings()}1169                  onShortcutsChange={applyShortcuts}1170                  onLicenseChange={async () => {1171                    // After activation/deactivation: refresh Pro status,1172                    // re-load entries (defensive — signal state can drift if1173                    // the SW briefly restarts during the verify+save round-trip),1174                    // and replay the Pro celebration if this is the first time1175                    // a valid Pro license is seen on this device.1176                    await refreshProStatus();1177                    void loadEntries();1178                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1179                    if ((should as { ok: boolean; data?: boolean }).data === true) {1180                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1181                      setView("pro-celebration");1182                      window.setTimeout(() => setView("settings"), 2500);1183                    }1184                  }}1185                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1186                  onImport={() => setView("import")}1187                  onExport={() => setView("export")}1188                  onBreachCheckDone={loadEntries}1189                  onOpenHealth={openHealth}1190                  onOpenSyncPairing={() => setView("sync-pairing")}1191                  onOpenFileImport={handleOpenFileImport}1192                  onOpenPanic={() => setView("panic")}1193                />1194              </Suspense>1195            </Show>1196            <Show when={view() === "sync-pairing"}>1197              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1198                <SyncPairingView1199                  onClose={() => setView("settings")}1200                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1201                />1202              </Suspense>1203            </Show>1204            <Show when={view() === "add"}>1205              <AddView1206                entry={editEntry()}1207                entries={entries()}1208                onBack={handleBack}1209                onSave={handleSave}1210              />1211            </Show>1212            <Show when={view() === "import"}>1213              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1214                <ImportView onBack={handleBack} onImport={handleSave} />1215              </Suspense>1216            </Show>1217            <Show when={view() === "export"}>1218              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1219                <ExportView1220                  onBack={() => {1221                    if (returnToPanic()) {1222                      setReturnToPanic(false);1223                      setView("panic");1224                    } else {1225                      handleBack();1226                    }1227                  }}1228                />1229              </Suspense>1230            </Show>1231            <Show when={view() === "panic"}>1232              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1233                <PanicView1234                  onCancel={() => setView("settings")}1235                  onOpenExport={() => {1236                    setReturnToPanic(true);1237                    setView("export");1238                  }}1239                  onDestroyed={async () => {1240                    clearCanarySuppressions();1241                    setEntries([]);1242                    setSelectedEntry(null);1243                    setEditEntry(undefined);1244                    setHasVault(false);1245                    setOnboarded(false);1246                    setProStatus(false);1247                    setPendingPasskey(null);1248                    setUpgradeHighlight(null);1249                    setSettingsInitialSection(null);1250                    setPendingProNotice(null);1251                    setPendingCelebration(false);1252                    setReturnToPanic(false);1253                    setContentPhase("idle");1254                    setView("lock");1255                  }}1256                />1257              </Suspense>1258            </Show>1259            <Show when={view() === "health"}>1260              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1261                <HealthView1262                  entries={entries()}1263                  isPro={proStatus()}1264                  onFixEntry={handleFixEntry}1265                  onBack={() => setView("settings")}1266                  onRefresh={loadEntries}1267                />1268              </Suspense>1269            </Show>1270            <Show when={view() === "trash"}>1271              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1272                <TrashView1273                  onBack={() => setView("list")}1274                  onRestored={() => void loadEntries()}1275                />1276              </Suspense>1277            </Show>1278            <Show when={restoreView() === "file"}>1279              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1280                <ImportView1281                  mode="onboarding"1282                  replacesExistingVault={true}1283                  onBack={() => setRestoreView(null)}1284                  onImport={async () => {1285                    setRestoreView(null);1286                    await handleUnlock();1287                  }}1288                />1289              </Suspense>1290            </Show>1291            </section>1292            </Show>1293          </Show>1294        </Show>1295      </Show>1296      <Show when={showShortcutsHelp()}>1297        <ShortcutsHelpOverlay1298          bindings={shortcutBindings()}1299          onClose={() => setShowShortcutsHelp(false)}1300        />1301      </Show>1302    </div>1303  );1304}13051306function ShortcutsHelpOverlay(props: {1307  bindings: Record<ShortcutAction, Keybinding>;1308  onClose: () => void;1309}) {1310  return (1311    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1312      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1313        <div class="peach-shortcuts-help-head">1314          <h3>Keyboard shortcuts</h3>1315          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1316        </div>1317        <div class="peach-shortcuts-help-body">1318          <p class="peach-settings-sub-label">ENTRY VIEW</p>1319          <ul>1320            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1321              <li>1322                <span>{d.label}</span>1323                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1324              </li>1325            ))}1326          </ul>1327          <p class="peach-settings-sub-label">ANYWHERE</p>1328          <ul>1329            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1330              <li>1331                <span>{d.label}</span>1332                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1333              </li>1334            ))}1335          </ul>1336        </div>1337      </div>1338    </div>1339  );1340}