App.tsx

55.6 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    // Action handlers — keyed by ShortcutAction. The dispatcher below tests468    // each binding against the event and runs the matching handler. New469    // shortcuts only need an entry here; the binding is data, not code.470    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {471      copy_password: () => {472        const entry = selectedEntry();473        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });474      },475      copy_username: () => {476        const entry = selectedEntry();477        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });478      },479      copy_totp: () => {480        const entry = selectedEntry();481        if (!entry?.totp) return;482        try {483          const { code } = generateTOTP(entry.totp);484          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });485        } catch { /* invalid TOTP secret — silent */ }486      },487      new_entry: () => handleAdd(),488      edit_entry: () => {489        const entry = selectedEntry();490        // Passkey-only entries have nothing user-editable in the Add view; the491        // passkey credential itself is opaque. Skip the edit action for them.492        if (!entry || isPasskeyOnly(entry)) return;493        setEditEntry(entry);494        setView("add");495      },496      delete_entry: () => {497        if (selectedEntry()) void handleDelete();498      },499      lock_vault: () => { void handleHeaderLock(); },500      search: () => openList(),501      nav_prev: () => navigate(-1),502      nav_next: () => navigate(1),503      jump_vault: () => setView("entry"),504      jump_settings: () => setView("settings"),505      show_help: () => setShowShortcutsHelp(true),506    };507508    // Actions that are MEANINGFUL only on the entry-detail view. Outside509    // that scope the binding is dormant — pressing C while on Settings510    // does nothing rather than awkwardly copying from a now-stale entry.511    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([512      "copy_password", "copy_username", "copy_totp",513      "edit_entry", "delete_entry", "nav_prev", "nav_next",514    ]);515516    const handleGlobalKeydown = (e: KeyboardEvent) => {517      const v = view();518      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"519        || (e.target as HTMLElement)?.tagName === "TEXTAREA"520        || (e.target as HTMLElement)?.isContentEditable;521      const isPrintableSearchKey =522        e.key.length === 1 &&523        !e.ctrlKey &&524        !e.metaKey &&525        !e.altKey;526527      // No input during the pro celebration sequence528      if (v === "pro-celebration") return;529530      // Help dialog: Escape closes it; eat the keypress so it doesn't531      // also navigate away from the underlying view.532      if (showShortcutsHelp()) {533        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }534        return;535      }536537      // ── Escape — fixed binding (not user-customizable) ───────538      if (e.key === "Escape") {539        if (v === "list") { setView("entry"); return; }540        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }541        if (v === "sync-pairing") { setView("settings"); return; }542      }543544      // Bindings-driven dispatch. Single-key letter bindings without545      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is546      // inside an input, so users can type into search/forms normally.547      const bindings = shortcutBindings();548      for (const action of Object.keys(bindings) as ShortcutAction[]) {549        const binding = bindings[action];550        if (!matchKeybinding(e, binding)) continue;551        // Single-key letter bindings need the input-focus guard. Bindings552        // with any modifier are safe — Ctrl+L doesn't conflict with typing.553        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;554        if (!hasMod && binding.key.length === 1 && inInput) return;555        if (ENTRY_SCOPED.has(action) && v !== "entry") return;556        e.preventDefault();557        SHORTCUT_HANDLERS[action]?.();558        return;559      }560561      // Type-to-search: in entry view, any printable key not consumed by a562      // shortcut above primes the list search seed and opens the list.563      // Kept outside the bindings table because it's a behavior, not a564      // discrete action — every printable character can trigger it.565      if (v === "entry" && !inInput && isPrintableSearchKey) {566        e.preventDefault();567        primeListSearch(e.key);568        return;569      }570    };571    window.addEventListener("keydown", handleGlobalKeydown);572    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));573574    const handleStorageChanged = (575      changes: Record<string, chrome.storage.StorageChange>,576      areaName: string577    ) => {578      if (areaName !== "session") return;579      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {580        return;581      }582      void refreshPendingPasskey();583    };584    chrome.storage.onChanged.addListener(handleStorageChanged);585    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));586  });587588  async function refreshCurrentTab() {589    try {590      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });591      const url = tab?.url ?? tab?.pendingUrl ?? "";592      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");593      // Skip extension/internal URLs — adding chrome://, about:, or594      // chrome-extension:// to a vault entry is never what the user wants.595      const isWebUrl = /^https?:\/\//i.test(url);596      setCurrentTabUrl(isWebUrl ? url : "");597    } catch {598      setCurrentTabDomain("");599      setCurrentTabUrl("");600    }601  }602603  async function refreshPendingPasskey() {604    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });605    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);606  }607608  async function refreshIncomingPairing() {609    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });610    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;611    setIncomingPair(data);612  }613614  // Drains a single one-shot record left by the background when 6-digit615  // pairing succeeded while the popup was closed (or the SyncPairing view was616  // navigated away from before it could show its own success card).617  async function consumeRecentPairing() {618    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });619    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;620    if (data?.deviceName) {621      setRecentPairToast(data.deviceName);622      window.setTimeout(() => setRecentPairToast(null), 4000);623    }624  }625626  async function respondIncomingPairing(accept: boolean) {627    if (incomingPairResponding()) return;628    setIncomingPairResponding(true);629    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });630    setIncomingPair(null);631    setIncomingPairResponding(false);632  }633634  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a635  // request appears, ticks once per second, and clears the banner if the636  // request expires while the popup is open.637  createEffect(() => {638    const req = incomingPair();639    if (!req) return;640    const handle = window.setInterval(() => {641      setIncomingPairTick((tick) => tick + 1);642      if (Date.now() >= req.expiresAt) {643        setIncomingPair(null);644        window.clearInterval(handle);645      }646    }, 1000);647    onCleanup(() => window.clearInterval(handle));648  });649650  async function refreshProStatus() {651    const res = await sendMessage({ type: "GET_LICENSE" });652    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;653    setProStatus(Boolean(data?.valid && data?.plan === "pro"));654  }655656  async function restoreSettings() {657    const res = await sendMessage({ type: "GET_SETTINGS" });658    const s = (res as { ok: boolean; data?: any }).data ?? {};659    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {660      setAccentColor(s.accentColor as AccentColorName);661    }662    setTheme(s.theme === "light" ? "light" : "dark");663    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {664      setDisplayFont(s.displayFont);665    } else {666      setDisplayFont("cormorant-italic");667    }668    if (s.textSize === "small" || s.textSize === "large") {669      setTextSize(s.textSize);670    } else {671      setTextSize("medium");672    }673    setReduceMotion(s.reduceMotion === true);674    setLockOnClose(s.lockOnClose !== false);675    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);676    setBreachMonitoring(s.breachMonitoring !== false);677    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);678    setShortcutBindings(getActiveBindings(s.shortcuts));679  }680681  async function applyTrashRetention(days: number) {682    setTrashRetentionDays(days);683    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });684  }685686  function primeListSearch(seed: string) {687    setListSearchSeed(seed);688    setListSearchSeedNonce((value) => value + 1);689    openList();690  }691692  // Returns null when it detected a dead service worker and triggered handleLock().693  // Callers that need to abort (e.g. openVault) check for null rather than relying694  // on view() state, which may already be "lock" during normal startup flows.695  async function loadEntries(): Promise<VaultEntry[] | null> {696    const response = await sendMessage({ type: "GET_ENTRIES" });697    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };698699    // If the service worker was killed and restarted (MV3 workers sleep), the700    // vault will be locked again — or the worker may not respond at all.701    // In either case, send the user to the lock screen rather than silently702    // showing an empty vault (which looks like data loss).703    if (!res.ok) {704      if (705        res.error === "vault locked" ||706        res.error === "SERVICE_WORKER_UNAVAILABLE" ||707        (typeof res.error === "string" && res.error.includes("locked"))708      ) {709        handleLock();710        return null; // signal emergency lock to callers711      }712      return [];713    }714715    const loadedEntries = res.data ?? [];716    setEntries(loadedEntries);717718    const currentId = selectedEntry()?.id;719    if (currentId) {720      setSelectedEntry(721        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null722      );723    }724725    return loadedEntries;726  }727728  async function openVault(preferredEntryId?: string, skipViewSet = false) {729    // Purge expired trash entries on each vault open730    const retDays = trashRetentionDays();731    if (retDays > 0) {732      void sendMessage({733        type: "PURGE_EXPIRED_TRASH",734        payload: { retentionMs: retDays * 86_400_000 },735      });736    }737738    const loadedEntries = await loadEntries();739740    // null means loadEntries() triggered an emergency lock (service worker died).741    // Don't override it by setting view back to "entry" with an empty vault.742    if (loadedEntries === null) return;743744    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry745    let nextSelectedEntry: VaultEntry | null = null;746    if (preferredEntryId) {747      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;748    }749    if (!nextSelectedEntry) {750      const tabDomain = currentTabDomain();751      if (tabDomain) {752        nextSelectedEntry = loadedEntries.find((e) => {753          if (e.type === "login") {754            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;755            for (const extra of e.additionalUrls ?? []) {756              if ((extractDomain(extra) ?? "") === tabDomain) return true;757            }758            return false;759          }760          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;761          return false;762        }) ?? null;763      }764    }765    nextSelectedEntry ??= loadedEntries[0] ?? null;766767    setSelectedEntry(nextSelectedEntry);768    setEditEntry(undefined);769    setContentTransitioning(false);770    setContentPhase("enter");771    queueContentIdle();772    if (!skipViewSet) setView("entry");773  }774775  async function handleUnlock() {776    // If the user previously created a vault but hadn't yet confirmed their777    // recovery words (and the browser was closed before they could), the778    // peach_recovery_pending flag is still set in storage.local. Re-route779    // back to the recovery surface so they finish the confirmation step780    // before reaching the entries view — the words can be re-derived now781    // that the vault is unlocked again.782    let recoveryPending = false;783    try {784      const out = await chrome.storage.local?.get("peach_recovery_pending");785      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";786    } catch { /* best-effort */ }787    if (recoveryPending) {788      setForceRecoveryWords(true);789      setView("lock");790      triggerPipPulse();791      await restoreSettings();792      return;793    }794    setHasVault(true);795    triggerPipPulse();796    await restoreSettings();797    const celebrating = pendingCelebration();798    if (celebrating) {799      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });800      setPendingCelebration(false);801    }802    await openVault(undefined, celebrating);803    if (celebrating) {804      setView("pro-celebration");805      window.setTimeout(() => setView("entry"), 2500);806    }807  }808809  function handleSelectEntry(entry: VaultEntry) {810    setSelectedEntry(entry);811    setContentTransitioning(false);812    setContentPhase("enter");813    queueContentIdle();814    setView("entry");815  }816817  function handleAdd() {818    setEditEntry(undefined);819    setView("add");820  }821822  async function handleDelete() {823    const entry = selectedEntry();824    if (!entry) return;825    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });826    const loadedEntries = await loadEntries() ?? [];827    setSelectedEntry(loadedEntries[0] ?? null);828    setView("entry");829  }830831  async function handleDeleteMany(ids: string[]) {832    for (const id of ids) {833      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });834    }835    const loadedEntries = await loadEntries() ?? [];836    // If the currently selected entry was among the deleted, move to first837    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);838    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);839  }840841  async function handleSave(savedEntry?: VaultEntry) {842    await openVault(savedEntry?.id);843  }844845  function handleBack() {846    setEditEntry(undefined);847    setView("entry");848  }849850  function handleLock() {851    clearCanarySuppressions();852    setEntries([]);853    setSelectedEntry(null);854    setEditEntry(undefined);855    setContentPhase("idle");856    setView("lock");857  }858859  function handleHeaderLock() {860    // Lock the UI immediately — do not wait for the service worker. If the SW861    // is dead or slow, the 5s sendMessage timeout would create a dead-click862    // window. The SW will lock on its next wake regardless.863    handleLock();864    void sendMessage({ type: "LOCK" });865  }866867  function navigate(dir: number) {868    const allEntries = entries();869    if (allEntries.length === 0) return;870    const currentIndex = selectedIndex();871    const baseIndex = currentIndex >= 0 ? currentIndex : 0;872    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;873    setSelectedEntry(allEntries[nextIndex]);874    setContentPhase("enter");875    queueContentIdle();876  }877878  function openList() {879    setView("list");880  }881882  function openHealth() {883    setEditEntry(undefined);884    setView("health");885  }886887  function handleOpenFileImport() {888    setRestoreView("file");889  }890891  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;892893  function handleFixEntry(entry: VaultEntry) {894    // Passkey-only entries have no editable surface — drop into view mode895    // instead of opening the Add editor.896    if (isPasskeyOnly(entry)) {897      setSelectedEntry(entry);898      setView("entry");899      return;900    }901    setEditEntry(entry);902    setView("add");903  }904905  const isLockedView = () => view() === "lock";906907  async function handleApprovePendingPasskey() {908    const pending = pendingPasskey();909    if (!pending) return;910    if (pending.browser === "firefox" && pending.type === "create") {911      // Firefox path: popup itself runs navigator.credentials.create. The912      // background never approved/rejected anything — it just stashed913      // intent. After the popup-driven flow resolves (success or cancel),914      // clear the pending key so the popup doesn't re-show this on next open.915      const { createFirefoxPasskey } = await import("./firefox-passkey");916      const result = await createFirefoxPasskey(pending);917      if (!result.ok) {918        console.warn("Peach Firefox passkey create failed:", result.error);919      }920      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });921      setPendingPasskey(null);922      void loadEntries();923      return;924    }925    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });926    setPendingPasskey(null);927  }928929  async function handleDenyPendingPasskey() {930    const pending = pendingPasskey();931    if (!pending) return;932    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });933    setPendingPasskey(null);934  }935936  function queueContentIdle(after?: () => void) {937    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);938    contentPhaseTimer = window.setTimeout(() => {939      setContentPhase("idle");940      after?.();941    }, ENTRY_TRANSITION_SETTLE_MS);942  }943944  return (945    <div class="popup-root peach-theme">946      <Show when={bootState() === "ready"}>947        <Show948          when={!pendingPasskey()}949          fallback={950            <PasskeyApprovalView951              type={pendingPasskey()!.type}952              rpName={pendingPasskey()!.rpName}953              rpId={pendingPasskey()!.rpId}954              userName={pendingPasskey()!.userName}955              userDisplayName={pendingPasskey()!.userDisplayName}956              onApprove={handleApprovePendingPasskey}957              onDeny={handleDenyPendingPasskey}958            />959          }960        >961          <Show962            when={!isLockedView()}963            fallback={964              <Show965                when={onboarded() || hasVault()}966                fallback={967                  <Onboarding968                    onComplete={() => { setOnboarded(true); }}969                  />970                }971              >972                <LockView973                  hasVault={hasVault()}974                  ready={bootState() === "ready"}975                  isPro={proStatus()}976                  forceRecoveryWords={forceRecoveryWords()}977                  onUnlock={() => {978                    // RecoveryWordDisplay clears the storage flag before979                    // calling onDone, so handleUnlock will see no pending980                    // confirmation and proceed through the normal path.981                    if (forceRecoveryWords()) setForceRecoveryWords(false);982                    return handleUnlock();983                  }}984                  onBackToOnboarding={985                    !hasVault()986                      ? () => setOnboarded(false)987                      : undefined988                  }989                />990              </Show>991            }992          >993            <Show994              when={view() !== "pro-celebration"}995              fallback={<ProCelebration />}996            >997            <section998              id="hd-shell"999              class="peach-shell peach-theme"1000              data-surface="extension"1001            >1002            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1003              <PeachWordmark unlocked />1004              <div class="peach-chrome-actions">1005                <button1006                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1007                  onClick={() => setView("settings")}1008                  aria-label="Settings"1009                >1010                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1011                    <path1012                      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"1013                      stroke="currentColor"1014                      stroke-width="0.9"1015                    />1016                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1017                  </svg>1018                </button>1019                <button1020                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1021                  onClick={handleAdd}1022                  aria-label="New entry"1023                >1024                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1025                    <path d="M5.5 1v9M1 5.5h9" />1026                  </svg>1027                </button>1028                <button1029                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1030                  onClick={() => void handleHeaderLock()}1031                  aria-label="Lock vault"1032                >1033                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1034                    <path1035                      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"1036                      stroke="currentColor"1037                      stroke-width="1"1038                      stroke-linecap="round"1039                    />1040                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1041                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1042                  </svg>1043                </button>1044              </div>1045            </header>10461047            <Show when={recentPairToast()}>1048              <div class="peach-pair-toast" role="status" aria-live="polite">1049                Paired with <strong>{recentPairToast()}</strong>1050              </div>1051            </Show>10521053            <Show when={incomingPair() !== null}>1054              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1055                <div class="peach-pair-request-header">1056                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1057                  <span class="peach-pair-request-title">Pairing request</span>1058                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1059                </div>1060                <p class="peach-pair-request-body">1061                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1062                </p>1063                <div class="peach-pair-request-actions">1064                  <button1065                    class="peach-btn peach-btn--ghost peach-btn--sm"1066                    onClick={() => void respondIncomingPairing(false)}1067                    disabled={incomingPairResponding()}1068                  >1069                    Reject1070                  </button>1071                  <button1072                    class="peach-btn peach-btn--accent peach-btn--sm"1073                    onClick={() => void respondIncomingPairing(true)}1074                    disabled={incomingPairResponding()}1075                  >1076                    Accept1077                  </button>1078                </div>1079              </div>1080            </Show>10811082            <Show when={pendingProNotice() !== null}>1083              <div class="peach-pro-notice-banner">1084                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1085                <button1086                  class="peach-pro-notice-link"1087                  onClick={() => {1088                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1089                    setSettingsInitialSection("license");1090                    setView("settings");1091                    setPendingProNotice(null);1092                  }}1093                >1094                  Learn more →1095                </button>1096                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1097              </div>1098            </Show>10991100            <div class="peach-shell-body">1101              <div class="peach-shell-veil"></div>1102              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1103                <EntryView1104                  entry={selectedEntry()}1105                  currentTabUrl={currentTabUrl()}1106                  onDelete={handleDelete}1107                  onFieldSaved={() => void loadEntries()}1108                  onEscape={() => { setView("list"); }}1109                />1110              </div>11111112              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1113                <div class="peach-search-bar">1114                  <span class="peach-search-icon">1115                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1116                      <circle cx="5.5" cy="5.5" r="3.75" />1117                      <path d="M8.75 8.75L11.5 11.5" />1118                    </svg>1119                  </span>1120                  <input1121                    class="peach-search-input"1122                    placeholder="search vault..."1123                    autocomplete="off"1124                    aria-label="Search vault entries"1125                    onClick={openList}1126                    onFocus={openList}1127                    readOnly1128                  />1129                  <div class="peach-search-meta">1130                    <span class="peach-search-counter">1131                      {entries().length > 01132                        ? `${selectedIndex() + 1} / ${entries().length}`1133                        : "0 entries"}1134                    </span>1135                    <span class="peach-divider"></span>1136                    <button1137                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1138                      onClick={() => navigate(-1)}1139                      aria-label="Previous entry"1140                      disabled={entries().length === 0}1141                    >1142                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1143                        <path d="M5 1L1 5.5L5 10" />1144                      </svg>1145                    </button>1146                    <button1147                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1148                      onClick={() => navigate(1)}1149                      aria-label="Next entry"1150                      disabled={entries().length === 0}1151                    >1152                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1153                        <path d="M1 1L5 5.5L1 10" />1154                      </svg>1155                    </button>1156                  </div>1157                </div>1158              </section>1159            </div>11601161            <Show when={view() === "list"}>1162              <VaultView1163                entries={entries()}1164                selectedEntryId={selectedEntry()?.id}1165                currentTabDomain={currentTabDomain()}1166                sortOrder={sortOrder()}1167                searchSeed={listSearchSeed()}1168                searchSeedNonce={listSearchSeedNonce()}1169                onSelectEntry={handleSelectEntry}1170                onSortOrderChange={setSortOrder}1171                onAdd={handleAdd}1172                onClose={() => setView("entry")}1173                onOpenTrash={() => setView("trash")}1174                onDeleteMany={handleDeleteMany}1175              />1176            </Show>1177            <Show when={view() === "settings"}>1178              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1179                <SettingsView1180                  entriesCount={entries().length}1181                  breachMonitoring={breachMonitoring()}1182                  lockOnClose={lockOnClose()}1183                  autoLockMinutes={autoLockMinutes()}1184                  trashRetentionDays={trashRetentionDays()}1185                  theme={theme()}1186                  accentColor={accentColor()}1187                  displayFont={displayFont()}1188                  textSize={textSize()}1189                  reduceMotion={reduceMotion()}1190                  isPro={proStatus()}1191                  initialSection={settingsInitialSection()}1192                  upgradeHighlight={upgradeHighlight()}1193                  onBreachMonitoringChange={applyBreachMonitoring}1194                  onLockOnCloseChange={applyLockOnClose}1195                  onAutoLockMinutesChange={applyAutoLockMinutes}1196                  onTrashRetentionChange={applyTrashRetention}1197                  onThemeChange={applyTheme}1198                  onAccentChange={applyAccentColor}1199                  onDisplayFontChange={applyDisplayFont}1200                  onTextSizeChange={applyTextSize}1201                  onReduceMotionChange={applyReduceMotion}1202                  shortcuts={shortcutBindings()}1203                  onShortcutsChange={applyShortcuts}1204                  onLicenseChange={async () => {1205                    // After activation/deactivation: refresh Pro status,1206                    // re-load entries (defensive — signal state can drift if1207                    // the SW briefly restarts during the verify+save round-trip),1208                    // and replay the Pro celebration if this is the first time1209                    // a valid Pro license is seen on this device.1210                    await refreshProStatus();1211                    void loadEntries();1212                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1213                    if ((should as { ok: boolean; data?: boolean }).data === true) {1214                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1215                      setView("pro-celebration");1216                      window.setTimeout(() => setView("settings"), 2500);1217                    }1218                  }}1219                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1220                  onImport={() => setView("import")}1221                  onExport={() => setView("export")}1222                  onBreachCheckDone={loadEntries}1223                  onOpenHealth={openHealth}1224                  onOpenSyncPairing={() => setView("sync-pairing")}1225                  onOpenFileImport={handleOpenFileImport}1226                  onOpenPanic={() => setView("panic")}1227                />1228              </Suspense>1229            </Show>1230            <Show when={view() === "sync-pairing"}>1231              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1232                <SyncPairingView1233                  onClose={() => setView("settings")}1234                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1235                />1236              </Suspense>1237            </Show>1238            <Show when={view() === "add"}>1239              <AddView1240                entry={editEntry()}1241                entries={entries()}1242                onBack={handleBack}1243                onSave={handleSave}1244              />1245            </Show>1246            <Show when={view() === "import"}>1247              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1248                <ImportView onBack={handleBack} onImport={handleSave} />1249              </Suspense>1250            </Show>1251            <Show when={view() === "export"}>1252              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1253                <ExportView1254                  onBack={() => {1255                    if (returnToPanic()) {1256                      setReturnToPanic(false);1257                      setView("panic");1258                    } else {1259                      handleBack();1260                    }1261                  }}1262                />1263              </Suspense>1264            </Show>1265            <Show when={view() === "panic"}>1266              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1267                <PanicView1268                  onCancel={() => setView("settings")}1269                  onOpenExport={() => {1270                    setReturnToPanic(true);1271                    setView("export");1272                  }}1273                  onDestroyed={async () => {1274                    clearCanarySuppressions();1275                    setEntries([]);1276                    setSelectedEntry(null);1277                    setEditEntry(undefined);1278                    setHasVault(false);1279                    setOnboarded(false);1280                    setProStatus(false);1281                    setPendingPasskey(null);1282                    setUpgradeHighlight(null);1283                    setSettingsInitialSection(null);1284                    setPendingProNotice(null);1285                    setPendingCelebration(false);1286                    setReturnToPanic(false);1287                    setContentPhase("idle");1288                    setView("lock");1289                  }}1290                />1291              </Suspense>1292            </Show>1293            <Show when={view() === "health"}>1294              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1295                <HealthView1296                  entries={entries()}1297                  isPro={proStatus()}1298                  onFixEntry={handleFixEntry}1299                  onBack={() => setView("settings")}1300                  onRefresh={loadEntries}1301                />1302              </Suspense>1303            </Show>1304            <Show when={view() === "trash"}>1305              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1306                <TrashView1307                  onBack={() => setView("list")}1308                  onRestored={() => void loadEntries()}1309                />1310              </Suspense>1311            </Show>1312            <Show when={restoreView() === "file"}>1313              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1314                <ImportView1315                  mode="onboarding"1316                  replacesExistingVault={true}1317                  onBack={() => setRestoreView(null)}1318                  onImport={async () => {1319                    setRestoreView(null);1320                    await handleUnlock();1321                  }}1322                />1323              </Suspense>1324            </Show>1325            </section>1326            </Show>1327          </Show>1328        </Show>1329      </Show>1330      <Show when={showShortcutsHelp()}>1331        <ShortcutsHelpOverlay1332          bindings={shortcutBindings()}1333          onClose={() => setShowShortcutsHelp(false)}1334        />1335      </Show>1336    </div>1337  );1338}13391340function ShortcutsHelpOverlay(props: {1341  bindings: Record<ShortcutAction, Keybinding>;1342  onClose: () => void;1343}) {1344  return (1345    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1346      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1347        <div class="peach-shortcuts-help-head">1348          <h3>Keyboard shortcuts</h3>1349          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1350        </div>1351        <div class="peach-shortcuts-help-body">1352          <p class="peach-settings-sub-label">ENTRY VIEW</p>1353          <ul>1354            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1355              <li>1356                <span>{d.label}</span>1357                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1358              </li>1359            ))}1360          </ul>1361          <p class="peach-settings-sub-label">ANYWHERE</p>1362          <ul>1363            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1364              <li>1365                <span>{d.label}</span>1366                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1367              </li>1368            ))}1369          </ul>1370        </div>1371      </div>1372    </div>1373  );1374}