App.tsx

59.9 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    // Native: closing the app before recovery-words confirmation means the345    // user didn't finish vault creation. Throw the partial vault away and346    // restart onboarding rather than asking them to unlock a vault they347    // never finished creating. Desktop keeps the existing "unlock to348    // resume" flow because closing the popup there is much more casual.349    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {350      try {351        await chrome.storage.local?.remove([352          "peach_vault_a",353          "peach_vault_b",354          "peach_recovery_pending",355          "peach_onboarded",356          "peach_vault_history",357        ]);358      } catch { /* best-effort */ }359      setHasVault(false);360      setOnboarded(false);361      setView("lock");362      setBootState("ready");363      document.getElementById("pre-lock")?.setAttribute("hidden", "true");364      return;365    }366367    if (recoveryPending && unlocked) {368      // forceRecoveryWords overrides LockView's hasVault gate so the369      // recovery surface renders even though the vault now exists.370      setForceRecoveryWords(true);371      setView("lock");372    } else if (unlocked && vaultExists) {373      await openVault(undefined, shouldCelebrate);374      if (shouldCelebrate) {375        setView("pro-celebration");376        window.setTimeout(() => setView("entry"), 2500);377      }378    } else if (shouldCelebrate) {379      setPendingCelebration(true);380    }381382    await refreshPendingPasskey();383    await refreshIncomingPairing();384    await consumeRecentPairing();385386    // Track tab changes so smart sort stays current387    const handleTabActivated = () => { void refreshCurrentTab(); };388    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {389      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();390    };391    try {392      chrome.tabs.onActivated.addListener(handleTabActivated);393      chrome.tabs.onUpdated.addListener(handleTabUpdated);394      onCleanup(() => {395        chrome.tabs.onActivated.removeListener(handleTabActivated);396        chrome.tabs.onUpdated.removeListener(handleTabUpdated);397      });398    } catch {399      // tabs permission may not be available in all contexts400    }401402    setBootState("ready");403    document.getElementById("pre-lock")?.setAttribute("hidden", "true");404405    // Check for pending session-storage notices from the background.406    if (chrome.storage.session) {407      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as408        Record<string, { feature?: string } | undefined>;409      if (session.pendingProGate?.feature) {410        await chrome.storage.session.remove("pendingProGate");411        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);412        setSettingsInitialSection("license");413        setView("settings");414      } else if (session.pendingProNotice?.feature) {415        await chrome.storage.session.remove("pendingProNotice");416        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });417      }418    }419420    // Warm the lazy-module cache so the Suspense fallback never shows for421    // locally-bundled extension views. Without this, the first navigation to422    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which423    // covers the shell and absorbs clicks on the header.424    void Promise.all([425      import("./views/Settings").catch(() => {}),426      import("./views/Import").catch(() => {}),427      import("./views/Export").catch(() => {}),428      import("./views/Health").catch(() => {}),429      import("./views/TrashView").catch(() => {}),430    ]);431432    // Lock-on-close via a persistent port. sendMessage in pagehide is433    // unreliable — the popup context tears down before the message lands.434    // The SW's onConnect listener locks when this port disconnects.435    let popupPort: chrome.runtime.Port | null = null;436    try {437      popupPort = chrome.runtime.connect({ name: "popup" });438    } catch { /* extension context invalidated — ignore */ }439    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });440441    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only442    // reliable signal is appStateChange — setTimeout is killed when the OS443    // backgrounds the app. We measure elapsed background time on resume.444    if (isNativePlatform()) {445      let backgroundedAt: number | null = null;446      const CapApp = nativePlugin<{447        addListener: (448          ev: string,449          cb: (s: { isActive: boolean }) => void,450        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };451      }>("App");452      if (CapApp?.addListener) {453        const sub = CapApp.addListener(454          "appStateChange",455          ({ isActive }: { isActive: boolean }) => {456            if (!isActive) {457              backgroundedAt = Date.now();458              return;459            }460            if (backgroundedAt !== null && autoLockMinutes() > 0) {461              const elapsed = Date.now() - backgroundedAt;462              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();463            }464            backgroundedAt = null;465          }466        );467        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.468        onCleanup(() => {469          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});470        });471      }472    }473474    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale475    // entries instead of waiting for the next GET_ENTRIES round-trip.476    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {477      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();478      if (msg?.type === "PRO_GATE_TRIGGERED") {479        setUpgradeHighlight(msg.payload?.feature ?? null);480        setSettingsInitialSection("license");481        setView("settings");482      }483      if (msg?.type === "INCOMING_PAIRING_REQUEST") {484        void refreshIncomingPairing();485      }486    };487    chrome.runtime.onMessage.addListener(handleRuntimeMessage);488    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));489490    // Android hardware/gesture back. MainActivity fires peach:back; the popup491    // decides what "back" means per surface. Lock+no-vault is the common case492    // — return to onboarding rather than letting the OS dismiss the activity.493    const handlePeachBack = () => {494      const v = view();495      if (v === "lock" && !hasVault() && onboarded()) {496        setOnboarded(false);497        return;498      }499      if (v === "list") { setView("entry"); return; }500      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {501        handleBack();502        return;503      }504      if (v === "sync-pairing") { setView("settings"); return; }505    };506    window.addEventListener("peach:back", handlePeachBack);507    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));508509    // Mobile bottom-sheet gesture: swipe up from the bottom 40% of the screen510    // reveals the vault list; swipe down from the top of the list dismisses it.511    // Tracked at document level so the search bar input doesn't have to be the512    // touch target — anywhere in the lower band counts.513    if (isNativePlatform()) {514      let touchStartY = 0;515      let touchStartX = 0;516      let dragging = false;517      let startedInBand = false;518      const SWIPE_THRESHOLD = 60;519      const HORIZONTAL_TOLERANCE = 30;520521      const onTouchStart = (e: TouchEvent) => {522        const t = e.touches[0];523        if (!t) return;524        touchStartY = t.clientY;525        touchStartX = t.clientX;526        dragging = true;527        const v = view();528        if (v === "entry") {529          // Only count starts inside the bottom 40% band (top 60% reserved530          // for entry interactions, taps, swipes between entries).531          startedInBand = t.clientY > window.innerHeight * 0.6;532        } else if (v === "list") {533          // From list: any downward drag near the top of the list dismisses it.534          startedInBand = t.clientY < window.innerHeight * 0.35;535        } else {536          startedInBand = false;537        }538      };539540      const onTouchMove = (e: TouchEvent) => {541        if (!dragging || !startedInBand) return;542        const t = e.touches[0];543        if (!t) return;544        const dy = t.clientY - touchStartY;545        const dx = Math.abs(t.clientX - touchStartX);546        if (dx > HORIZONTAL_TOLERANCE) {547          // Treat as a horizontal swipe — give it back to the entry view.548          dragging = false;549          return;550        }551        const v = view();552        if (v === "entry" && dy < -SWIPE_THRESHOLD) {553          dragging = false;554          setView("list");555        } else if (v === "list" && dy > SWIPE_THRESHOLD) {556          dragging = false;557          setView("entry");558        }559      };560561      const onTouchEnd = () => { dragging = false; startedInBand = false; };562563      document.addEventListener("touchstart", onTouchStart, { passive: true });564      document.addEventListener("touchmove",  onTouchMove,  { passive: true });565      document.addEventListener("touchend",   onTouchEnd,   { passive: true });566      document.addEventListener("touchcancel", onTouchEnd,  { passive: true });567      onCleanup(() => {568        document.removeEventListener("touchstart", onTouchStart);569        document.removeEventListener("touchmove",  onTouchMove);570        document.removeEventListener("touchend",   onTouchEnd);571        document.removeEventListener("touchcancel", onTouchEnd);572      });573    }574575    // Action handlers — keyed by ShortcutAction. The dispatcher below tests576    // each binding against the event and runs the matching handler. New577    // shortcuts only need an entry here; the binding is data, not code.578    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {579      copy_password: () => {580        const entry = selectedEntry();581        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });582      },583      copy_username: () => {584        const entry = selectedEntry();585        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });586      },587      copy_totp: () => {588        const entry = selectedEntry();589        if (!entry?.totp) return;590        try {591          const { code } = generateTOTP(entry.totp);592          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });593        } catch { /* invalid TOTP secret — silent */ }594      },595      new_entry: () => handleAdd(),596      edit_entry: () => {597        const entry = selectedEntry();598        // Passkey-only entries have nothing user-editable in the Add view; the599        // passkey credential itself is opaque. Skip the edit action for them.600        if (!entry || isPasskeyOnly(entry)) return;601        setEditEntry(entry);602        setView("add");603      },604      delete_entry: () => {605        if (selectedEntry()) void handleDelete();606      },607      lock_vault: () => { void handleHeaderLock(); },608      search: () => openList(),609      nav_prev: () => navigate(-1),610      nav_next: () => navigate(1),611      jump_vault: () => setView("entry"),612      jump_settings: () => setView("settings"),613      show_help: () => setShowShortcutsHelp(true),614    };615616    // Actions that are MEANINGFUL only on the entry-detail view. Outside617    // that scope the binding is dormant — pressing C while on Settings618    // does nothing rather than awkwardly copying from a now-stale entry.619    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([620      "copy_password", "copy_username", "copy_totp",621      "edit_entry", "delete_entry", "nav_prev", "nav_next",622    ]);623624    const handleGlobalKeydown = (e: KeyboardEvent) => {625      const v = view();626      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"627        || (e.target as HTMLElement)?.tagName === "TEXTAREA"628        || (e.target as HTMLElement)?.isContentEditable;629      const isPrintableSearchKey =630        e.key.length === 1 &&631        !e.ctrlKey &&632        !e.metaKey &&633        !e.altKey;634635      // No input during the pro celebration sequence636      if (v === "pro-celebration") return;637638      // Help dialog: Escape closes it; eat the keypress so it doesn't639      // also navigate away from the underlying view.640      if (showShortcutsHelp()) {641        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }642        return;643      }644645      // ── Escape — fixed binding (not user-customizable) ───────646      if (e.key === "Escape") {647        if (v === "list") { setView("entry"); return; }648        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }649        if (v === "sync-pairing") { setView("settings"); return; }650      }651652      // Bindings-driven dispatch. Single-key letter bindings without653      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is654      // inside an input, so users can type into search/forms normally.655      const bindings = shortcutBindings();656      for (const action of Object.keys(bindings) as ShortcutAction[]) {657        const binding = bindings[action];658        if (!matchKeybinding(e, binding)) continue;659        // Single-key letter bindings need the input-focus guard. Bindings660        // with any modifier are safe — Ctrl+L doesn't conflict with typing.661        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;662        if (!hasMod && binding.key.length === 1 && inInput) return;663        if (ENTRY_SCOPED.has(action) && v !== "entry") return;664        e.preventDefault();665        SHORTCUT_HANDLERS[action]?.();666        return;667      }668669      // Type-to-search: in entry view, any printable key not consumed by a670      // shortcut above primes the list search seed and opens the list.671      // Kept outside the bindings table because it's a behavior, not a672      // discrete action — every printable character can trigger it.673      if (v === "entry" && !inInput && isPrintableSearchKey) {674        e.preventDefault();675        primeListSearch(e.key);676        return;677      }678    };679    window.addEventListener("keydown", handleGlobalKeydown);680    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));681682    const handleStorageChanged = (683      changes: Record<string, chrome.storage.StorageChange>,684      areaName: string685    ) => {686      if (areaName !== "session") return;687      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {688        return;689      }690      void refreshPendingPasskey();691    };692    chrome.storage.onChanged.addListener(handleStorageChanged);693    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));694  });695696  async function refreshCurrentTab() {697    try {698      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });699      const url = tab?.url ?? tab?.pendingUrl ?? "";700      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");701      // Skip extension/internal URLs — adding chrome://, about:, or702      // chrome-extension:// to a vault entry is never what the user wants.703      const isWebUrl = /^https?:\/\//i.test(url);704      setCurrentTabUrl(isWebUrl ? url : "");705    } catch {706      setCurrentTabDomain("");707      setCurrentTabUrl("");708    }709  }710711  async function refreshPendingPasskey() {712    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });713    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);714  }715716  async function refreshIncomingPairing() {717    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });718    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;719    setIncomingPair(data);720  }721722  // Drains a single one-shot record left by the background when 6-digit723  // pairing succeeded while the popup was closed (or the SyncPairing view was724  // navigated away from before it could show its own success card).725  async function consumeRecentPairing() {726    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });727    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;728    if (data?.deviceName) {729      setRecentPairToast(data.deviceName);730      window.setTimeout(() => setRecentPairToast(null), 4000);731    }732  }733734  async function respondIncomingPairing(accept: boolean) {735    if (incomingPairResponding()) return;736    setIncomingPairResponding(true);737    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });738    setIncomingPair(null);739    setIncomingPairResponding(false);740  }741742  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a743  // request appears, ticks once per second, and clears the banner if the744  // request expires while the popup is open.745  createEffect(() => {746    const req = incomingPair();747    if (!req) return;748    const handle = window.setInterval(() => {749      setIncomingPairTick((tick) => tick + 1);750      if (Date.now() >= req.expiresAt) {751        setIncomingPair(null);752        window.clearInterval(handle);753      }754    }, 1000);755    onCleanup(() => window.clearInterval(handle));756  });757758  async function refreshProStatus() {759    const res = await sendMessage({ type: "GET_LICENSE" });760    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;761    setProStatus(Boolean(data?.valid && data?.plan === "pro"));762  }763764  async function restoreSettings() {765    const res = await sendMessage({ type: "GET_SETTINGS" });766    const s = (res as { ok: boolean; data?: any }).data ?? {};767    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {768      setAccentColor(s.accentColor as AccentColorName);769    }770    setTheme(s.theme === "light" ? "light" : "dark");771    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {772      setDisplayFont(s.displayFont);773    } else {774      setDisplayFont("cormorant-italic");775    }776    if (s.textSize === "small" || s.textSize === "large") {777      setTextSize(s.textSize);778    } else {779      setTextSize("medium");780    }781    setReduceMotion(s.reduceMotion === true);782    setLockOnClose(s.lockOnClose !== false);783    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);784    setBreachMonitoring(s.breachMonitoring !== false);785    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);786    setShortcutBindings(getActiveBindings(s.shortcuts));787  }788789  async function applyTrashRetention(days: number) {790    setTrashRetentionDays(days);791    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });792  }793794  function primeListSearch(seed: string) {795    setListSearchSeed(seed);796    setListSearchSeedNonce((value) => value + 1);797    openList();798  }799800  // Returns null when it detected a dead service worker and triggered handleLock().801  // Callers that need to abort (e.g. openVault) check for null rather than relying802  // on view() state, which may already be "lock" during normal startup flows.803  async function loadEntries(): Promise<VaultEntry[] | null> {804    const response = await sendMessage({ type: "GET_ENTRIES" });805    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };806807    // If the service worker was killed and restarted (MV3 workers sleep), the808    // vault will be locked again — or the worker may not respond at all.809    // In either case, send the user to the lock screen rather than silently810    // showing an empty vault (which looks like data loss).811    if (!res.ok) {812      if (813        res.error === "vault locked" ||814        res.error === "SERVICE_WORKER_UNAVAILABLE" ||815        (typeof res.error === "string" && res.error.includes("locked"))816      ) {817        handleLock();818        return null; // signal emergency lock to callers819      }820      return [];821    }822823    const loadedEntries = res.data ?? [];824    setEntries(loadedEntries);825826    const currentId = selectedEntry()?.id;827    if (currentId) {828      setSelectedEntry(829        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null830      );831    }832833    return loadedEntries;834  }835836  async function openVault(preferredEntryId?: string, skipViewSet = false) {837    // Purge expired trash entries on each vault open838    const retDays = trashRetentionDays();839    if (retDays > 0) {840      void sendMessage({841        type: "PURGE_EXPIRED_TRASH",842        payload: { retentionMs: retDays * 86_400_000 },843      });844    }845846    const loadedEntries = await loadEntries();847848    // null means loadEntries() triggered an emergency lock (service worker died).849    // Don't override it by setting view back to "entry" with an empty vault.850    if (loadedEntries === null) return;851852    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry853    let nextSelectedEntry: VaultEntry | null = null;854    if (preferredEntryId) {855      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;856    }857    if (!nextSelectedEntry) {858      const tabDomain = currentTabDomain();859      if (tabDomain) {860        nextSelectedEntry = loadedEntries.find((e) => {861          if (e.type === "login") {862            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;863            for (const extra of e.additionalUrls ?? []) {864              if ((extractDomain(extra) ?? "") === tabDomain) return true;865            }866            return false;867          }868          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;869          return false;870        }) ?? null;871      }872    }873    nextSelectedEntry ??= loadedEntries[0] ?? null;874875    setSelectedEntry(nextSelectedEntry);876    setEditEntry(undefined);877    setContentTransitioning(false);878    setContentPhase("enter");879    queueContentIdle();880    if (!skipViewSet) setView("entry");881  }882883  async function handleUnlock() {884    // If the user previously created a vault but hadn't yet confirmed their885    // recovery words (and the browser was closed before they could), the886    // peach_recovery_pending flag is still set in storage.local. Re-route887    // back to the recovery surface so they finish the confirmation step888    // before reaching the entries view — the words can be re-derived now889    // that the vault is unlocked again.890    let recoveryPending = false;891    try {892      const out = await chrome.storage.local?.get("peach_recovery_pending");893      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";894    } catch { /* best-effort */ }895    if (recoveryPending) {896      setForceRecoveryWords(true);897      setView("lock");898      triggerPipPulse();899      await restoreSettings();900      return;901    }902    setHasVault(true);903    triggerPipPulse();904    await restoreSettings();905    const celebrating = pendingCelebration();906    if (celebrating) {907      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });908      setPendingCelebration(false);909    }910    await openVault(undefined, celebrating);911    if (celebrating) {912      setView("pro-celebration");913      window.setTimeout(() => setView("entry"), 2500);914    }915  }916917  function handleSelectEntry(entry: VaultEntry) {918    setSelectedEntry(entry);919    setContentTransitioning(false);920    setContentPhase("enter");921    queueContentIdle();922    setView("entry");923  }924925  function handleAdd() {926    setEditEntry(undefined);927    setView("add");928  }929930  async function handleDelete() {931    const entry = selectedEntry();932    if (!entry) return;933    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });934    const loadedEntries = await loadEntries() ?? [];935    setSelectedEntry(loadedEntries[0] ?? null);936    setView("entry");937  }938939  async function handleDeleteMany(ids: string[]) {940    for (const id of ids) {941      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });942    }943    const loadedEntries = await loadEntries() ?? [];944    // If the currently selected entry was among the deleted, move to first945    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);946    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);947  }948949  async function handleSave(savedEntry?: VaultEntry) {950    await openVault(savedEntry?.id);951  }952953  function handleBack() {954    setEditEntry(undefined);955    setView("entry");956  }957958  function handleLock() {959    clearCanarySuppressions();960    setEntries([]);961    setSelectedEntry(null);962    setEditEntry(undefined);963    setContentPhase("idle");964    setView("lock");965  }966967  function handleHeaderLock() {968    // Lock the UI immediately — do not wait for the service worker. If the SW969    // is dead or slow, the 5s sendMessage timeout would create a dead-click970    // window. The SW will lock on its next wake regardless.971    handleLock();972    void sendMessage({ type: "LOCK" });973  }974975  function navigate(dir: number) {976    const allEntries = entries();977    if (allEntries.length === 0) return;978    const currentIndex = selectedIndex();979    const baseIndex = currentIndex >= 0 ? currentIndex : 0;980    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;981    setSelectedEntry(allEntries[nextIndex]);982    setContentPhase("enter");983    queueContentIdle();984  }985986  function openList() {987    setView("list");988  }989990  function openHealth() {991    setEditEntry(undefined);992    setView("health");993  }994995  function handleOpenFileImport() {996    setRestoreView("file");997  }998999  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10001001  function handleFixEntry(entry: VaultEntry) {1002    // Passkey-only entries have no editable surface — drop into view mode1003    // instead of opening the Add editor.1004    if (isPasskeyOnly(entry)) {1005      setSelectedEntry(entry);1006      setView("entry");1007      return;1008    }1009    setEditEntry(entry);1010    setView("add");1011  }10121013  const isLockedView = () => view() === "lock";10141015  async function handleApprovePendingPasskey() {1016    const pending = pendingPasskey();1017    if (!pending) return;1018    if (pending.browser === "firefox" && pending.type === "create") {1019      // Firefox path: popup itself runs navigator.credentials.create. The1020      // background never approved/rejected anything — it just stashed1021      // intent. After the popup-driven flow resolves (success or cancel),1022      // clear the pending key so the popup doesn't re-show this on next open.1023      const { createFirefoxPasskey } = await import("./firefox-passkey");1024      const result = await createFirefoxPasskey(pending);1025      if (!result.ok) {1026        console.warn("Peach Firefox passkey create failed:", result.error);1027      }1028      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1029      setPendingPasskey(null);1030      void loadEntries();1031      return;1032    }1033    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1034    setPendingPasskey(null);1035  }10361037  async function handleDenyPendingPasskey() {1038    const pending = pendingPasskey();1039    if (!pending) return;1040    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1041    setPendingPasskey(null);1042  }10431044  function queueContentIdle(after?: () => void) {1045    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1046    contentPhaseTimer = window.setTimeout(() => {1047      setContentPhase("idle");1048      after?.();1049    }, ENTRY_TRANSITION_SETTLE_MS);1050  }10511052  return (1053    <div class="popup-root peach-theme">1054      <Show when={bootState() === "ready"}>1055        <Show1056          when={!pendingPasskey()}1057          fallback={1058            <PasskeyApprovalView1059              type={pendingPasskey()!.type}1060              rpName={pendingPasskey()!.rpName}1061              rpId={pendingPasskey()!.rpId}1062              userName={pendingPasskey()!.userName}1063              userDisplayName={pendingPasskey()!.userDisplayName}1064              onApprove={handleApprovePendingPasskey}1065              onDeny={handleDenyPendingPasskey}1066            />1067          }1068        >1069          <Show1070            when={!isLockedView()}1071            fallback={1072              <Show1073                when={onboarded() || hasVault()}1074                fallback={1075                  <Onboarding1076                    onComplete={() => { setOnboarded(true); }}1077                  />1078                }1079              >1080                <LockView1081                  hasVault={hasVault()}1082                  ready={bootState() === "ready"}1083                  isPro={proStatus()}1084                  forceRecoveryWords={forceRecoveryWords()}1085                  onUnlock={() => {1086                    // RecoveryWordDisplay clears the storage flag before1087                    // calling onDone, so handleUnlock will see no pending1088                    // confirmation and proceed through the normal path.1089                    if (forceRecoveryWords()) setForceRecoveryWords(false);1090                    return handleUnlock();1091                  }}1092                  onBackToOnboarding={1093                    !hasVault()1094                      ? () => setOnboarded(false)1095                      : undefined1096                  }1097                />1098              </Show>1099            }1100          >1101            <Show1102              when={view() !== "pro-celebration"}1103              fallback={<ProCelebration />}1104            >1105            <section1106              id="hd-shell"1107              class="peach-shell peach-theme"1108              data-surface="extension"1109            >1110            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1111              <PeachWordmark unlocked />1112              <div class="peach-chrome-actions">1113                <button1114                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1115                  onClick={() => setView("settings")}1116                  aria-label="Settings"1117                >1118                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1119                    <path1120                      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"1121                      stroke="currentColor"1122                      stroke-width="0.9"1123                    />1124                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1125                  </svg>1126                </button>1127                <button1128                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1129                  onClick={handleAdd}1130                  aria-label="New entry"1131                >1132                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1133                    <path d="M5.5 1v9M1 5.5h9" />1134                  </svg>1135                </button>1136                <button1137                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1138                  onClick={() => void handleHeaderLock()}1139                  aria-label="Lock vault"1140                >1141                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1142                    <path1143                      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"1144                      stroke="currentColor"1145                      stroke-width="1"1146                      stroke-linecap="round"1147                    />1148                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1149                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1150                  </svg>1151                </button>1152              </div>1153            </header>11541155            <Show when={recentPairToast()}>1156              <div class="peach-pair-toast" role="status" aria-live="polite">1157                Paired with <strong>{recentPairToast()}</strong>1158              </div>1159            </Show>11601161            <Show when={incomingPair() !== null}>1162              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1163                <div class="peach-pair-request-header">1164                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1165                  <span class="peach-pair-request-title">Pairing request</span>1166                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1167                </div>1168                <p class="peach-pair-request-body">1169                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1170                </p>1171                <div class="peach-pair-request-actions">1172                  <button1173                    class="peach-btn peach-btn--ghost peach-btn--sm"1174                    onClick={() => void respondIncomingPairing(false)}1175                    disabled={incomingPairResponding()}1176                  >1177                    Reject1178                  </button>1179                  <button1180                    class="peach-btn peach-btn--accent peach-btn--sm"1181                    onClick={() => void respondIncomingPairing(true)}1182                    disabled={incomingPairResponding()}1183                  >1184                    Accept1185                  </button>1186                </div>1187              </div>1188            </Show>11891190            <Show when={pendingProNotice() !== null}>1191              <div class="peach-pro-notice-banner">1192                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1193                <button1194                  class="peach-pro-notice-link"1195                  onClick={() => {1196                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1197                    setSettingsInitialSection("license");1198                    setView("settings");1199                    setPendingProNotice(null);1200                  }}1201                >1202                  Learn more →1203                </button>1204                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1205              </div>1206            </Show>12071208            <div class="peach-shell-body">1209              <div class="peach-shell-veil"></div>1210              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1211                <EntryView1212                  entry={selectedEntry()}1213                  currentTabUrl={currentTabUrl()}1214                  onDelete={handleDelete}1215                  onFieldSaved={() => void loadEntries()}1216                  onEscape={() => { setView("list"); }}1217                />1218              </div>12191220              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1221                <div class="peach-search-bar">1222                  <span class="peach-search-icon">1223                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1224                      <circle cx="5.5" cy="5.5" r="3.75" />1225                      <path d="M8.75 8.75L11.5 11.5" />1226                    </svg>1227                  </span>1228                  <input1229                    class="peach-search-input"1230                    placeholder="search vault..."1231                    autocomplete="off"1232                    aria-label="Search vault entries"1233                    onClick={openList}1234                    onFocus={openList}1235                    readOnly1236                  />1237                  <div class="peach-search-meta">1238                    <span class="peach-search-counter">1239                      {entries().length > 01240                        ? `${selectedIndex() + 1} / ${entries().length}`1241                        : "0 entries"}1242                    </span>1243                    <span class="peach-divider"></span>1244                    <button1245                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1246                      onClick={() => navigate(-1)}1247                      aria-label="Previous entry"1248                      disabled={entries().length === 0}1249                    >1250                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1251                        <path d="M5 1L1 5.5L5 10" />1252                      </svg>1253                    </button>1254                    <button1255                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1256                      onClick={() => navigate(1)}1257                      aria-label="Next entry"1258                      disabled={entries().length === 0}1259                    >1260                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1261                        <path d="M1 1L5 5.5L1 10" />1262                      </svg>1263                    </button>1264                  </div>1265                </div>1266              </section>1267            </div>12681269            <Show when={view() === "list"}>1270              <VaultView1271                entries={entries()}1272                selectedEntryId={selectedEntry()?.id}1273                currentTabDomain={currentTabDomain()}1274                sortOrder={sortOrder()}1275                searchSeed={listSearchSeed()}1276                searchSeedNonce={listSearchSeedNonce()}1277                onSelectEntry={handleSelectEntry}1278                onSortOrderChange={setSortOrder}1279                onAdd={handleAdd}1280                onClose={() => setView("entry")}1281                onOpenTrash={() => setView("trash")}1282                onDeleteMany={handleDeleteMany}1283              />1284            </Show>1285            <Show when={view() === "settings"}>1286              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1287                <SettingsView1288                  entriesCount={entries().length}1289                  breachMonitoring={breachMonitoring()}1290                  lockOnClose={lockOnClose()}1291                  autoLockMinutes={autoLockMinutes()}1292                  trashRetentionDays={trashRetentionDays()}1293                  theme={theme()}1294                  accentColor={accentColor()}1295                  displayFont={displayFont()}1296                  textSize={textSize()}1297                  reduceMotion={reduceMotion()}1298                  isPro={proStatus()}1299                  initialSection={settingsInitialSection()}1300                  upgradeHighlight={upgradeHighlight()}1301                  onBreachMonitoringChange={applyBreachMonitoring}1302                  onLockOnCloseChange={applyLockOnClose}1303                  onAutoLockMinutesChange={applyAutoLockMinutes}1304                  onTrashRetentionChange={applyTrashRetention}1305                  onThemeChange={applyTheme}1306                  onAccentChange={applyAccentColor}1307                  onDisplayFontChange={applyDisplayFont}1308                  onTextSizeChange={applyTextSize}1309                  onReduceMotionChange={applyReduceMotion}1310                  shortcuts={shortcutBindings()}1311                  onShortcutsChange={applyShortcuts}1312                  onLicenseChange={async () => {1313                    // After activation/deactivation: refresh Pro status,1314                    // re-load entries (defensive — signal state can drift if1315                    // the SW briefly restarts during the verify+save round-trip),1316                    // and replay the Pro celebration if this is the first time1317                    // a valid Pro license is seen on this device.1318                    await refreshProStatus();1319                    void loadEntries();1320                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1321                    if ((should as { ok: boolean; data?: boolean }).data === true) {1322                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1323                      setView("pro-celebration");1324                      window.setTimeout(() => setView("settings"), 2500);1325                    }1326                  }}1327                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1328                  onImport={() => setView("import")}1329                  onExport={() => setView("export")}1330                  onBreachCheckDone={loadEntries}1331                  onOpenHealth={openHealth}1332                  onOpenSyncPairing={() => setView("sync-pairing")}1333                  onOpenFileImport={handleOpenFileImport}1334                  onOpenPanic={() => setView("panic")}1335                />1336              </Suspense>1337            </Show>1338            <Show when={view() === "sync-pairing"}>1339              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1340                <SyncPairingView1341                  onClose={() => setView("settings")}1342                  onPaired={() => { /* sync state refreshes when popup returns to Settings */ }}1343                />1344              </Suspense>1345            </Show>1346            <Show when={view() === "add"}>1347              <AddView1348                entry={editEntry()}1349                entries={entries()}1350                onBack={handleBack}1351                onSave={handleSave}1352              />1353            </Show>1354            <Show when={view() === "import"}>1355              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1356                <ImportView onBack={handleBack} onImport={handleSave} />1357              </Suspense>1358            </Show>1359            <Show when={view() === "export"}>1360              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1361                <ExportView1362                  onBack={() => {1363                    if (returnToPanic()) {1364                      setReturnToPanic(false);1365                      setView("panic");1366                    } else {1367                      handleBack();1368                    }1369                  }}1370                />1371              </Suspense>1372            </Show>1373            <Show when={view() === "panic"}>1374              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1375                <PanicView1376                  onCancel={() => setView("settings")}1377                  onOpenExport={() => {1378                    setReturnToPanic(true);1379                    setView("export");1380                  }}1381                  onDestroyed={async () => {1382                    clearCanarySuppressions();1383                    setEntries([]);1384                    setSelectedEntry(null);1385                    setEditEntry(undefined);1386                    setHasVault(false);1387                    setOnboarded(false);1388                    setProStatus(false);1389                    setPendingPasskey(null);1390                    setUpgradeHighlight(null);1391                    setSettingsInitialSection(null);1392                    setPendingProNotice(null);1393                    setPendingCelebration(false);1394                    setReturnToPanic(false);1395                    setContentPhase("idle");1396                    setView("lock");1397                  }}1398                />1399              </Suspense>1400            </Show>1401            <Show when={view() === "health"}>1402              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1403                <HealthView1404                  entries={entries()}1405                  isPro={proStatus()}1406                  onFixEntry={handleFixEntry}1407                  onBack={() => setView("settings")}1408                  onRefresh={loadEntries}1409                />1410              </Suspense>1411            </Show>1412            <Show when={view() === "trash"}>1413              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1414                <TrashView1415                  onBack={() => setView("list")}1416                  onRestored={() => void loadEntries()}1417                />1418              </Suspense>1419            </Show>1420            <Show when={restoreView() === "file"}>1421              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1422                <ImportView1423                  mode="onboarding"1424                  replacesExistingVault={true}1425                  onBack={() => setRestoreView(null)}1426                  onImport={async () => {1427                    setRestoreView(null);1428                    await handleUnlock();1429                  }}1430                />1431              </Suspense>1432            </Show>1433            </section>1434            </Show>1435          </Show>1436        </Show>1437      </Show>1438      <Show when={showShortcutsHelp()}>1439        <ShortcutsHelpOverlay1440          bindings={shortcutBindings()}1441          onClose={() => setShowShortcutsHelp(false)}1442        />1443      </Show>1444    </div>1445  );1446}14471448function ShortcutsHelpOverlay(props: {1449  bindings: Record<ShortcutAction, Keybinding>;1450  onClose: () => void;1451}) {1452  return (1453    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1454      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1455        <div class="peach-shortcuts-help-head">1456          <h3>Keyboard shortcuts</h3>1457          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1458        </div>1459        <div class="peach-shortcuts-help-body">1460          <p class="peach-settings-sub-label">ENTRY VIEW</p>1461          <ul>1462            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1463              <li>1464                <span>{d.label}</span>1465                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1466              </li>1467            ))}1468          </ul>1469          <p class="peach-settings-sub-label">ANYWHERE</p>1470          <ul>1471            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1472              <li>1473                <span>{d.label}</span>1474                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1475              </li>1476            ))}1477          </ul>1478        </div>1479      </div>1480    </div>1481  );1482}