App.tsx

63.8 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageSet } from "../shared/storage";4import { sendMessage } from "../shared/bridge";5import { ACCENT_COLORS } from "../shared/types";6import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";7import { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { NotesMode } from "./views/NotesMode";11import { ProCelebration } from "./views/ProCelebration";12import { VaultView, type SortOrder } from "./views/Vault";13import { EntryView } from "./views/Entry";14import { AddView } from "./views/Add";15import { PeachWordmark } from "./components/PeachMark";16import { PasskeyApprovalView } from "./views/PasskeyApproval";17import { extractDomain } from "../shared/domain";18import { popupCopy } from "./copy";19import {20  DEFAULT_BINDINGS,21  formatKeybinding,22  getActiveBindings,23  matchKeybinding,24  SHORTCUT_DESCRIPTORS,25  type Keybinding,26  type ShortcutAction,27} from "../shared/shortcuts";28import { generateTOTP } from "../crypto/totp";29import { isNativePlatform, nativePlugin } from "../shared/native";3031export { sendMessage } from "../shared/bridge";3233const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));34const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));35const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));36const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));37const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));38const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));39const ChirpSyncView   = lazy(() => import("./views/ChirpSync").then(m => ({ default: m.ChirpSyncView })));40const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));41const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));4243type View =44  | "lock"45  | "pro-celebration"46  | "entry"47  | "list"48  | "add"49  | "settings"50  | "chirp-sync"51  | "import"52  | "export"53  | "health"54  | "trash"55  | "panic"56  | "codex-generate"57  | "codex-restore";58type BootState = "loading" | "ready";5960const canarySuppressMap = new Map<string, boolean>();61let shellRingAnimation: Animation | null = null;6263export function isCanarySuppressed(entryId: string): boolean {64  return canarySuppressMap.get(entryId) ?? false;65}6667export function setCanarySuppressed(entryId: string, suppressed: boolean): void {68  canarySuppressMap.set(entryId, suppressed);69}7071export function clearCanarySuppressions(): void {72  canarySuppressMap.clear();73}7475export function triggerRing() {76  const shell = document.getElementById("hd-shell");77  if (!shell) return;7879  shellRingAnimation?.cancel();80  shell.dataset.glowing = "true";81  const animation = shell.animate(82    [83      { offset: 0, boxShadow: "var(--copy-shadow)" },84      {85        offset: 0.3,86        boxShadow:87          "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)",88      },89      { offset: 1, boxShadow: "var(--copy-shadow)" },90    ],91    {92      duration: 720,93      easing: "cubic-bezier(0.4, 0, 0.2, 1)",94      fill: "none",95    }96  );97  shellRingAnimation = animation;98  const clearGlow = () => {99    if (shellRingAnimation !== animation) return;100    shellRingAnimation = null;101    delete shell.dataset.glowing;102  };103  animation.onfinish = clearGlow;104  animation.oncancel = clearGlow;105}106107108export function triggerPipPulse() {109  const pip = document.querySelector(".peach-status-pip, .pip");110  if (pip) {111    pip.classList.remove("pulse");112    void (pip as HTMLElement).offsetWidth;113    pip.classList.add("pulse");114  }115}116117const ENTRY_TRANSITION_SETTLE_MS = 135;118119export default function App() {120  const [bootState, setBootState] = createSignal<BootState>("loading");121  const [view, setView] = createSignal<View>("lock");122  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,123  // CSS transition takes over for snap animation).124  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);125  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(126    "enter"127  );128  const [contentTransitioning, setContentTransitioning] = createSignal(false);129  const [hasVault, setHasVault] = createSignal(false);130  const [onboarded, setOnboarded] = createSignal(true);131  const [entries, setEntries] = createSignal<VaultEntry[]>([]);132  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);133  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);134  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");135  const [theme, setTheme] = createSignal<"dark" | "light">("dark");136  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");137  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);138  const [lockOnClose, setLockOnClose] = createSignal(true);139  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);140  const [breachMonitoring, setBreachMonitoring] = createSignal(true);141  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);142  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);143  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);144  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);145  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);146  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");147  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");148  // Cached Pro status — synchronous for render paths. Background's149  // GET_LICENSE is async, but render-time reads of isPro() must not block.150  // Refreshed at boot, after activate/deactivate, and whenever the popup151  // re-opens onto a stored license that has changed via another window.152  const [proStatus, setProStatus] = createSignal(false);153  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);154  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);155  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");156  const [listSearchSeed, setListSearchSeed] = createSignal("");157  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);158  const [pendingCelebration, setPendingCelebration] = createSignal(false);159  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);160  // True while Panic Step 1 has bounced the user out to Export. When Export's161  // onBack fires we return to Panic instead of Settings so the user keeps the162  // destruction context they came from.163  const [returnToPanic, setReturnToPanic] = createSignal(false);164  const [showNotes, setShowNotes] = createSignal(false);165  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);166  // Set on popup boot when peach_recovery_pending flag is found in session167  // storage — instructs LockView to skip the unlock UI and open the recovery168  // words confirmation surface instead. Cleared via handleUnlock once the169  // user has typed the 3 confirmation words.170  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);171172  let contentPhaseTimer: number | undefined;173174  function applyAccent(name: AccentColorName) {175    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;176    const hex = color.hex;177    document.documentElement.style.setProperty("--peach-accent", hex);178    // Ambient surface variables — derived from the accent so surfaces shift179    // subtly toward the accent hue rather than staying fixed warm-brown.180    document.documentElement.style.setProperty("--peach-glow", hex + "2A");181    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");182    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");183  }184185  createEffect(() => {186    applyAccent(accentColor());187  });188189  createEffect(() => {190    document.documentElement.classList.toggle("light", theme() === "light");191    document.body.classList.toggle("light", theme() === "light");192  });193194  createEffect(() => {195    document.documentElement.setAttribute("data-text-size", textSize());196  });197198  createEffect(() => {199    if (reduceMotion()) {200      document.documentElement.setAttribute("data-motion", "reduce");201    } else {202      document.documentElement.removeAttribute("data-motion");203    }204  });205206  const selectedIndex = createMemo(() => {207    const currentId = selectedEntry()?.id;208    if (!currentId) return entries().length > 0 ? 0 : -1;209    return entries().findIndex((entry) => entry.id === currentId);210  });211212  async function applyAccentColor(name: AccentColorName) {213    applyAccent(name);214    setAccentColor(name);215    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });216  }217218  async function applyTheme(t: "dark" | "light") {219    setTheme(t);220    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });221  }222223  async function applyTextSize(size: "small" | "medium" | "large") {224    setTextSize(size);225    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });226  }227228  async function applyReduceMotion(enabled: boolean) {229    setReduceMotion(enabled);230    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });231  }232233  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload234  // small and lets future default updates land for actions the user hasn't235  // touched. Settings sends us the full active map; we filter and store.236  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {237    setShortcutBindings(active);238    const overrides: Record<string, Keybinding> = {};239    for (const action of Object.keys(active) as ShortcutAction[]) {240      const a = active[action];241      const d = DEFAULT_BINDINGS[action];242      const same = a.key === d.key243        && Boolean(a.ctrl)  === Boolean(d.ctrl)244        && Boolean(a.meta)  === Boolean(d.meta)245        && Boolean(a.shift) === Boolean(d.shift)246        && Boolean(a.alt)   === Boolean(d.alt);247      if (!same) overrides[action] = a;248    }249    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });250  }251252  async function applyLockOnClose(enabled: boolean) {253    setLockOnClose(enabled);254    await sendMessage({255      type: "UPDATE_SETTINGS",256      payload: { lockOnClose: enabled },257    });258  }259260  async function applyAutoLockMinutes(minutes: number) {261    setAutoLockMinutes(minutes);262    await sendMessage({263      type: "UPDATE_SETTINGS",264      payload: { autoLockMinutes: minutes },265    });266  }267268  async function applyBreachMonitoring(enabled: boolean) {269    setBreachMonitoring(enabled);270    await sendMessage({271      type: "UPDATE_SETTINGS",272      payload: { breachMonitoring: enabled },273    });274  }275276  onMount(async () => {277    // Resolve the active tab in parallel with the unlock/has-vault queries —278    // openVault()'s smart selection picks the entry matching currentTabDomain,279    // so it must be populated before openVault runs. Previously refreshCurrentTab280    // ran after openVault, leaving popups that booted already-unlocked falling281    // back to loadedEntries[0] instead of the domain match.282    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([283      sendMessage({ type: "IS_UNLOCKED" }),284      sendMessage({ type: "HAS_VAULT" }),285      refreshCurrentTab(),286      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),287    ]);288    const unlocked = Boolean(289      (unlockResponse as { ok: boolean; data?: boolean }).data290    );291    const vaultExists = Boolean(292      (vaultResponse as { ok: boolean; data?: boolean }).data293    );294    const shouldCelebrate = Boolean(295      (celebrationResponse as { ok: boolean; data?: boolean }).data296    );297    setHasVault(vaultExists);298    // Onboarding gate — show once on first install, never again. Existing299    // users (vaultExists) are auto-marked onboarded so they skip the flow300    // even on the very first popup open after this feature ships.301    try {302      const onboarded = await storageGet("peach_onboarded");303      const seen = onboarded === "true";304      if (vaultExists && !seen) {305        await storageSet("peach_onboarded", "true");306        setOnboarded(true);307      } else {308        setOnboarded(seen);309      }310    } catch {311      // storage unavailable — default to onboarded so we never block boot312      setOnboarded(true);313    }314    await Promise.all([restoreSettings(), refreshProStatus()]);315316    // Mark played before any animation so a crash mid-sequence never replays it317    if (shouldCelebrate) {318      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });319    }320321    // If the user created a vault but hasn't yet confirmed their recovery322    // words, route back to the recovery-words screen instead of opening the323    // entries view. The flag lives in chrome.storage.local so it survives324    // both popup close (SW suppresses lock-on-close) and full browser325    // restart (handleUnlock checks the same flag after a fresh password326    // unlock). Cleared when confirmation succeeds.327    let recoveryPending = false;328    try {329      const out = await chrome.storage.local?.get("peach_recovery_pending");330      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";331    } catch { /* best-effort */ }332333    // Native: closing the app before recovery-words confirmation means the334    // user didn't finish vault creation. Throw the partial vault away and335    // restart onboarding rather than asking them to unlock a vault they336    // never finished creating. Desktop keeps the existing "unlock to337    // resume" flow because closing the popup there is much more casual.338    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {339      try {340        await chrome.storage.local?.remove([341          "peach_vault_a",342          "peach_vault_b",343          "peach_recovery_pending",344          "peach_onboarded",345          "peach_vault_history",346        ]);347      } catch { /* best-effort */ }348      setHasVault(false);349      setOnboarded(false);350      setView("lock");351      setBootState("ready");352      document.getElementById("pre-lock")?.setAttribute("hidden", "true");353      return;354    }355356    if (recoveryPending && unlocked) {357      // forceRecoveryWords overrides LockView's hasVault gate so the358      // recovery surface renders even though the vault now exists.359      setForceRecoveryWords(true);360      setView("lock");361    } else if (unlocked && vaultExists) {362      await openVault(undefined, shouldCelebrate);363      if (shouldCelebrate) {364        setView("pro-celebration");365        window.setTimeout(() => setView("entry"), 2500);366      }367    } else if (shouldCelebrate) {368      setPendingCelebration(true);369    }370371    await refreshPendingPasskey();372373    // Track tab changes so smart sort stays current374    const handleTabActivated = () => { void refreshCurrentTab(); };375    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {376      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();377    };378    try {379      chrome.tabs.onActivated.addListener(handleTabActivated);380      chrome.tabs.onUpdated.addListener(handleTabUpdated);381      onCleanup(() => {382        chrome.tabs.onActivated.removeListener(handleTabActivated);383        chrome.tabs.onUpdated.removeListener(handleTabUpdated);384      });385    } catch {386      // tabs permission may not be available in all contexts387    }388389    setBootState("ready");390    document.getElementById("pre-lock")?.setAttribute("hidden", "true");391392    // Check for pending session-storage notices from the background.393    if (chrome.storage.session) {394      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as395        Record<string, { feature?: string } | undefined>;396      if (session.pendingProGate?.feature) {397        await chrome.storage.session.remove("pendingProGate");398        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);399        setSettingsInitialSection("license");400        setView("settings");401      } else if (session.pendingProNotice?.feature) {402        await chrome.storage.session.remove("pendingProNotice");403        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });404      }405    }406407    // Warm the lazy-module cache so the Suspense fallback never shows for408    // locally-bundled extension views. Without this, the first navigation to409    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which410    // covers the shell and absorbs clicks on the header.411    void Promise.all([412      import("./views/Settings").catch(() => {}),413      import("./views/Import").catch(() => {}),414      import("./views/Export").catch(() => {}),415      import("./views/Health").catch(() => {}),416      import("./views/TrashView").catch(() => {}),417    ]);418419    // Lock-on-close via a persistent port. sendMessage in pagehide is420    // unreliable — the popup context tears down before the message lands.421    // The SW's onConnect listener locks when this port disconnects.422    let popupPort: chrome.runtime.Port | null = null;423    try {424      popupPort = chrome.runtime.connect({ name: "popup" });425    } catch { /* extension context invalidated — ignore */ }426    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });427428    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only429    // reliable signal is appStateChange — setTimeout is killed when the OS430    // backgrounds the app. We measure elapsed background time on resume.431    if (isNativePlatform()) {432      let backgroundedAt: number | null = null;433434      const CapApp = nativePlugin<{435        addListener: (436          ev: string,437          cb: (s: { isActive: boolean }) => void,438        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };439      }>("App");440      if (CapApp?.addListener) {441        const sub = CapApp.addListener(442          "appStateChange",443          ({ isActive }: { isActive: boolean }) => {444            if (!isActive) {445              backgroundedAt = Date.now();446              return;447            }448            if (backgroundedAt !== null && autoLockMinutes() > 0) {449              const elapsed = Date.now() - backgroundedAt;450              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();451            }452            backgroundedAt = null;453          }454        );455        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.456        onCleanup(() => {457          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});458        });459      }460461      // L12/COR-011: foreground idle autolock. appStateChange only fires when462      // the OS backgrounds the app — if the user idles with the screen on,463      // chrome.alarms is no-op'd in Capacitor so the vault would stay open464      // indefinitely. Poll every 30s and lock if elapsed since last user465      // interaction exceeds autoLockMinutes.466      let lastUserActivityAt = Date.now();467      const bumpActivity = () => { lastUserActivityAt = Date.now(); };468      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;469      for (const ev of ACTIVITY_EVENTS) {470        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });471      }472      const idleLockInterval = setInterval(() => {473        const minutes = autoLockMinutes();474        if (!minutes || minutes <= 0) return;475        const elapsed = Date.now() - lastUserActivityAt;476        if (elapsed >= minutes * 60_000) {477          lastUserActivityAt = Date.now();478          handleHeaderLock();479        }480      }, 30_000);481      onCleanup(() => {482        clearInterval(idleLockInterval);483        for (const ev of ACTIVITY_EVENTS) {484          document.removeEventListener(ev, bumpActivity, { capture: true });485        }486      });487    }488489    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale490    // entries instead of waiting for the next GET_ENTRIES round-trip.491    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {492      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();493      if (msg?.type === "PRO_GATE_TRIGGERED") {494        setUpgradeHighlight(msg.payload?.feature ?? null);495        setSettingsInitialSection("license");496        setView("settings");497      }498    };499    chrome.runtime.onMessage.addListener(handleRuntimeMessage);500    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));501502    // Android hardware/gesture back. MainActivity fires peach:back; the popup503    // decides what "back" means per surface. Lock+no-vault is the common case504    // — return to onboarding rather than letting the OS dismiss the activity.505    const handlePeachBack = () => {506      // Notes mode captures back first507      if (showNotes()) {508        setShowNotes(false);509        setOpenNoteId(undefined);510        return;511      }512      const v = view();513      if (v === "lock" && !hasVault() && onboarded()) {514        setOnboarded(false);515        return;516      }517      if (v === "list") { setView("entry"); return; }518      if (v === "settings") {519        window.dispatchEvent(new Event("peach:settings-back"));520        return;521      }522      if (v === "import" || v === "export" || v === "add" || v === "health") {523        handleBack();524        return;525      }526      if (v === "chirp-sync") { setView("settings"); return; }527    };528    window.addEventListener("peach:back", handlePeachBack);529    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));530531    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that532    // peeks from the bottom (search bar handle visible) and drags up to fill533    // the screen. dragOffset is the LIVE finger offset during a drag, in px,534    // 0 when no drag in progress. The wrapper element computes transform =535    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.536    if (isNativePlatform()) {537      let touchStartY = 0;538      let touchStartX = 0;539      let lastY = 0;540      let lastT = 0;541      let dragging = false;542      let captured = false;543      const HORIZONTAL_TOLERANCE = 16;544      const ACTIVATION_DY = 8;545      const PEEK_PX = 60;546547      const onTouchStart = (e: TouchEvent) => {548        const t = e.touches[0];549        if (!t) return;550        const v = view();551        if (v !== "entry" && v !== "list") return;552        // Entry view: only intercept drags starting in the bottom 40%.553        // List view: intercept drags starting in the top 35% (the search/handle row).554        const inBand = v === "entry"555          ? t.clientY > window.innerHeight * 0.6556          : t.clientY < window.innerHeight * 0.35;557        if (!inBand) return;558        touchStartY = lastY = t.clientY;559        touchStartX = t.clientX;560        lastT = e.timeStamp;561        dragging = true;562        captured = false;563      };564565      const onTouchMove = (e: TouchEvent) => {566        if (!dragging) return;567        const t = e.touches[0];568        if (!t) return;569        const dy = t.clientY - touchStartY;570        const dx = Math.abs(t.clientX - touchStartX);571572        if (!captured) {573          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {574            // Looks like a horizontal swipe — release.575            dragging = false;576            return;577          }578          if (Math.abs(dy) < ACTIVATION_DY) return;579          captured = true;580        }581582        // Translate the sheet by dy from its rest (peek) position. Peek is583        // (viewport height - PEEK_PX). Open is 0.584        const v = view();585        const restClosed = window.innerHeight - PEEK_PX;586        const baseTranslate = v === "list" ? 0 : restClosed;587        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));588        setSheetTranslate(next);589        lastY = t.clientY;590        lastT = e.timeStamp;591      };592593      const onTouchEnd = (e: TouchEvent) => {594        if (!dragging) { return; }595        const t = e.changedTouches[0];596        const elapsed = Math.max(1, e.timeStamp - lastT);597        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms598        const wasCaptured = captured;599        dragging = false;600        captured = false;601        const v = view();602603        if (!wasCaptured) {604          // Tap in the peek strip while in entry view → open the vault list.605          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");606          setSheetTranslate(null);607          return;608        }609610        const restClosed = window.innerHeight - PEEK_PX;611        const current = sheetTranslate() ?? restClosed;612613        // Snap rules:614        //   - Strong upward velocity → open615        //   - Strong downward velocity → close616        //   - Otherwise snap to whichever rest is closer617        let nextOpen: boolean;618        if (velocity < -0.05) nextOpen = true;619        else if (velocity > 0.05) nextOpen = false;620        else nextOpen = current < restClosed * 0.5;621622        if (nextOpen && v !== "list") setView("list");623        if (!nextOpen && v !== "entry") setView("entry");624        // Release the live offset so CSS transition handles the snap.625        setSheetTranslate(null);626      };627628      document.addEventListener("touchstart", onTouchStart, { passive: true });629      document.addEventListener("touchmove",  onTouchMove,  { passive: true });630      document.addEventListener("touchend",   onTouchEnd,   { passive: true });631      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });632      onCleanup(() => {633        document.removeEventListener("touchstart", onTouchStart);634        document.removeEventListener("touchmove",  onTouchMove);635        document.removeEventListener("touchend",   onTouchEnd);636      });637    }638639    // Action handlers — keyed by ShortcutAction. The dispatcher below tests640    // each binding against the event and runs the matching handler. New641    // shortcuts only need an entry here; the binding is data, not code.642    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {643      copy_password: () => {644        const entry = selectedEntry();645        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });646      },647      copy_username: () => {648        const entry = selectedEntry();649        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });650      },651      copy_totp: () => {652        const entry = selectedEntry();653        if (!entry?.totp) return;654        try {655          const { code } = generateTOTP(entry.totp);656          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });657        } catch { /* invalid TOTP secret — silent */ }658      },659      new_entry: () => handleAdd(),660      edit_entry: () => {661        const entry = selectedEntry();662        // Passkey-only entries have nothing user-editable in the Add view; the663        // passkey credential itself is opaque. Skip the edit action for them.664        if (!entry || isPasskeyOnly(entry)) return;665        setEditEntry(entry);666        setView("add");667      },668      delete_entry: () => {669        if (selectedEntry()) void handleDelete();670      },671      lock_vault: () => { void handleHeaderLock(); },672      search: () => openList(),673      nav_prev: () => navigate(-1),674      nav_next: () => navigate(1),675      jump_vault: () => setView("entry"),676      jump_settings: () => setView("settings"),677      show_help: () => setShowShortcutsHelp(true),678    };679680    // Actions that are MEANINGFUL only on the entry-detail view. Outside681    // that scope the binding is dormant — pressing C while on Settings682    // does nothing rather than awkwardly copying from a now-stale entry.683    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([684      "copy_password", "copy_username", "copy_totp",685      "edit_entry", "delete_entry", "nav_prev", "nav_next",686    ]);687688    const handleGlobalKeydown = (e: KeyboardEvent) => {689      const v = view();690      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"691        || (e.target as HTMLElement)?.tagName === "TEXTAREA"692        || (e.target as HTMLElement)?.isContentEditable;693      const isPrintableSearchKey =694        e.key.length === 1 &&695        !e.ctrlKey &&696        !e.metaKey &&697        !e.altKey;698699      // No input during the pro celebration sequence700      if (v === "pro-celebration") return;701702      // Help dialog: Escape closes it; eat the keypress so it doesn't703      // also navigate away from the underlying view.704      if (showShortcutsHelp()) {705        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }706        return;707      }708709      // ── Escape — fixed binding (not user-customizable) ───────710      if (e.key === "Escape") {711        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }712        if (v === "list") { setView("entry"); return; }713        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }714        if (v === "chirp-sync") { setView("settings"); return; }715      }716717      // Bindings-driven dispatch. Single-key letter bindings without718      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is719      // inside an input, so users can type into search/forms normally.720      const bindings = shortcutBindings();721      for (const action of Object.keys(bindings) as ShortcutAction[]) {722        const binding = bindings[action];723        if (!matchKeybinding(e, binding)) continue;724        // Single-key letter bindings need the input-focus guard. Bindings725        // with any modifier are safe — Ctrl+L doesn't conflict with typing.726        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;727        if (!hasMod && binding.key.length === 1 && inInput) return;728        if (ENTRY_SCOPED.has(action) && v !== "entry") return;729        e.preventDefault();730        SHORTCUT_HANDLERS[action]?.();731        return;732      }733734      // Type-to-search: in entry view, any printable key not consumed by a735      // shortcut above primes the list search seed and opens the list.736      // Kept outside the bindings table because it's a behavior, not a737      // discrete action — every printable character can trigger it.738      if (v === "entry" && !inInput && isPrintableSearchKey) {739        e.preventDefault();740        primeListSearch(e.key);741        return;742      }743    };744    window.addEventListener("keydown", handleGlobalKeydown);745    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));746747    const handleStorageChanged = (748      changes: Record<string, chrome.storage.StorageChange>,749      areaName: string750    ) => {751      if (areaName !== "session") return;752      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {753        return;754      }755      void refreshPendingPasskey();756    };757    chrome.storage.onChanged.addListener(handleStorageChanged);758    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));759  });760761  async function refreshCurrentTab() {762    try {763      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });764      const url = tab?.url ?? tab?.pendingUrl ?? "";765      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");766      // Skip extension/internal URLs — adding chrome://, about:, or767      // chrome-extension:// to a vault entry is never what the user wants.768      const isWebUrl = /^https?:\/\//i.test(url);769      setCurrentTabUrl(isWebUrl ? url : "");770    } catch {771      setCurrentTabDomain("");772      setCurrentTabUrl("");773    }774  }775776  async function refreshPendingPasskey() {777    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });778    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);779  }780781  async function refreshProStatus() {782    const res = await sendMessage({ type: "GET_LICENSE" });783    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;784    setProStatus(Boolean(data?.valid && data?.plan === "pro"));785  }786787  async function restoreSettings() {788    const res = await sendMessage({ type: "GET_SETTINGS" });789    const s = (res as { ok: boolean; data?: any }).data ?? {};790    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {791      setAccentColor(s.accentColor as AccentColorName);792    }793    setTheme(s.theme === "light" ? "light" : "dark");794    if (s.textSize === "small" || s.textSize === "large") {795      setTextSize(s.textSize);796    } else {797      setTextSize("medium");798    }799    setReduceMotion(s.reduceMotion === true);800    setLockOnClose(s.lockOnClose !== false);801    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);802    setBreachMonitoring(s.breachMonitoring !== false);803    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);804    setShortcutBindings(getActiveBindings(s.shortcuts));805  }806807  async function applyTrashRetention(days: number) {808    setTrashRetentionDays(days);809    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });810  }811812  function primeListSearch(seed: string) {813    setListSearchSeed(seed);814    setListSearchSeedNonce((value) => value + 1);815    openList();816  }817818  // Returns null when it detected a dead service worker and triggered handleLock().819  // Callers that need to abort (e.g. openVault) check for null rather than relying820  // on view() state, which may already be "lock" during normal startup flows.821  async function loadEntries(): Promise<VaultEntry[] | null> {822    const response = await sendMessage({ type: "GET_ENTRIES" });823    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };824825    // If the service worker was killed and restarted (MV3 workers sleep), the826    // vault will be locked again — or the worker may not respond at all.827    // In either case, send the user to the lock screen rather than silently828    // showing an empty vault (which looks like data loss).829    if (!res.ok) {830      if (831        res.error === "vault_locked" ||832        res.error === "SERVICE_WORKER_UNAVAILABLE" ||833        (typeof res.error === "string" && res.error.includes("locked"))834      ) {835        handleLock();836        return null; // signal emergency lock to callers837      }838      return [];839    }840841    const loadedEntries = res.data ?? [];842    setEntries(loadedEntries);843844    const currentId = selectedEntry()?.id;845    if (currentId) {846      setSelectedEntry(847        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null848      );849    }850851    return loadedEntries;852  }853854  async function openVault(preferredEntryId?: string, skipViewSet = false) {855    // Purge expired trash entries on each vault open856    const retDays = trashRetentionDays();857    if (retDays > 0) {858      void sendMessage({859        type: "PURGE_EXPIRED_TRASH",860        payload: { retentionMs: retDays * 86_400_000 },861      });862    }863864    const loadedEntries = await loadEntries();865866    // null means loadEntries() triggered an emergency lock (service worker died).867    // Don't override it by setting view back to "entry" with an empty vault.868    if (loadedEntries === null) return;869870    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry871    let nextSelectedEntry: VaultEntry | null = null;872    if (preferredEntryId) {873      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;874    }875    if (!nextSelectedEntry) {876      const tabDomain = currentTabDomain();877      if (tabDomain) {878        nextSelectedEntry = loadedEntries.find((e) => {879          if (e.type === "login") {880            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;881            for (const extra of e.additionalUrls ?? []) {882              if ((extractDomain(extra) ?? "") === tabDomain) return true;883            }884            return false;885          }886          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;887          return false;888        }) ?? null;889      }890    }891    nextSelectedEntry ??= loadedEntries[0] ?? null;892893    setSelectedEntry(nextSelectedEntry);894    setEditEntry(undefined);895    setContentTransitioning(false);896    setContentPhase("enter");897    queueContentIdle();898    if (!skipViewSet) setView("entry");899  }900901  async function handleUnlock() {902    // If the user previously created a vault but hadn't yet confirmed their903    // recovery words (and the browser was closed before they could), the904    // peach_recovery_pending flag is still set in storage.local. Re-route905    // back to the recovery surface so they finish the confirmation step906    // before reaching the entries view — the words can be re-derived now907    // that the vault is unlocked again.908    let recoveryPending = false;909    try {910      const out = await chrome.storage.local?.get("peach_recovery_pending");911      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";912    } catch { /* best-effort */ }913    if (recoveryPending) {914      setForceRecoveryWords(true);915      setView("lock");916      triggerPipPulse();917      await restoreSettings();918      return;919    }920    setHasVault(true);921    triggerPipPulse();922    await restoreSettings();923    const celebrating = pendingCelebration();924    if (celebrating) {925      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });926      setPendingCelebration(false);927    }928    await openVault(undefined, celebrating);929    if (celebrating) {930      setView("pro-celebration");931      window.setTimeout(() => setView("entry"), 2500);932    }933  }934935  function handleSelectEntry(entry: VaultEntry) {936    if (entry.type === "note") {937      setOpenNoteId(entry.id);938      setShowNotes(true);939      return;940    }941    setSelectedEntry(entry);942    setContentTransitioning(false);943    setContentPhase("enter");944    queueContentIdle();945    setView("entry");946  }947948  function handleAdd() {949    setEditEntry(undefined);950    setView("add");951  }952953  async function handleDelete() {954    const entry = selectedEntry();955    if (!entry) return;956    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });957    const loadedEntries = await loadEntries() ?? [];958    setSelectedEntry(loadedEntries[0] ?? null);959    setView("entry");960  }961962  async function handleDeleteMany(ids: string[]) {963    for (const id of ids) {964      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });965    }966    const loadedEntries = await loadEntries() ?? [];967    // If the currently selected entry was among the deleted, move to first968    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);969    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);970  }971972  async function handleSave(savedEntry?: VaultEntry) {973    await openVault(savedEntry?.id);974  }975976  function handleBack() {977    setEditEntry(undefined);978    setView("entry");979  }980981  function handleLock() {982    clearCanarySuppressions();983    setEntries([]);984    setSelectedEntry(null);985    setEditEntry(undefined);986    setContentPhase("idle");987    setView("lock");988  }989990  function handleHeaderLock() {991    // Lock the UI immediately — do not wait for the service worker. If the SW992    // is dead or slow, the 5s sendMessage timeout would create a dead-click993    // window. The SW will lock on its next wake regardless.994    handleLock();995    void sendMessage({ type: "LOCK" });996  }997998  function navigate(dir: number) {999    const allEntries = entries();1000    if (allEntries.length === 0) return;1001    const currentIndex = selectedIndex();1002    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1003    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1004    setSelectedEntry(allEntries[nextIndex]);1005    setContentPhase("enter");1006    queueContentIdle();1007  }10081009  function openList() {1010    setView("list");1011  }10121013  function openHealth() {1014    setEditEntry(undefined);1015    setView("health");1016  }10171018  function handleOpenFileImport() {1019    setRestoreView("file");1020  }10211022  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10231024  function handleFixEntry(entry: VaultEntry) {1025    // Passkey-only entries have no editable surface — drop into view mode1026    // instead of opening the Add editor.1027    if (isPasskeyOnly(entry)) {1028      setSelectedEntry(entry);1029      setView("entry");1030      return;1031    }1032    setEditEntry(entry);1033    setView("add");1034  }10351036  const isLockedView = () => view() === "lock";10371038  async function handleApprovePendingPasskey() {1039    const pending = pendingPasskey();1040    if (!pending) return;1041    if (pending.browser === "firefox" && pending.type === "create") {1042      // Firefox path: popup itself runs navigator.credentials.create. The1043      // background never approved/rejected anything — it just stashed1044      // intent. After the popup-driven flow resolves (success or cancel),1045      // clear the pending key so the popup doesn't re-show this on next open.1046      const { createFirefoxPasskey } = await import("./firefox-passkey");1047      const result = await createFirefoxPasskey(pending);1048      if (!result.ok) {1049        console.warn("Peach Firefox passkey create failed:", result.error);1050      }1051      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1052      setPendingPasskey(null);1053      void loadEntries();1054      window.close();1055      return;1056    }1057    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1058    window.close();1059  }10601061  async function handleDenyPendingPasskey() {1062    const pending = pendingPasskey();1063    if (!pending) return;1064    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1065    window.close();1066  }10671068  function queueContentIdle(after?: () => void) {1069    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1070    contentPhaseTimer = window.setTimeout(() => {1071      setContentPhase("idle");1072      after?.();1073    }, ENTRY_TRANSITION_SETTLE_MS);1074  }10751076  return (1077    <div class="popup-root peach-theme">1078      <Show when={bootState() === "ready"}>1079        <Show1080          when={!pendingPasskey()}1081          fallback={1082            <PasskeyApprovalView1083              type={pendingPasskey()!.type}1084              rpName={pendingPasskey()!.rpName}1085              rpId={pendingPasskey()!.rpId}1086              userName={pendingPasskey()!.userName}1087              userDisplayName={pendingPasskey()!.userDisplayName}1088              onApprove={handleApprovePendingPasskey}1089              onDeny={handleDenyPendingPasskey}1090            />1091          }1092        >1093          <Show1094            when={!isLockedView()}1095            fallback={1096              <Show1097                when={onboarded() || hasVault()}1098                fallback={1099                  <Onboarding1100                    onComplete={() => { setOnboarded(true); }}1101                  />1102                }1103              >1104                <LockView1105                  hasVault={hasVault()}1106                  ready={bootState() === "ready"}1107                  isPro={proStatus()}1108                  forceRecoveryWords={forceRecoveryWords()}1109                  onUnlock={() => {1110                    // RecoveryWordDisplay clears the storage flag before1111                    // calling onDone, so handleUnlock will see no pending1112                    // confirmation and proceed through the normal path.1113                    if (forceRecoveryWords()) setForceRecoveryWords(false);1114                    return handleUnlock();1115                  }}1116                  onBackToOnboarding={1117                    !hasVault()1118                      ? () => setOnboarded(false)1119                      : undefined1120                  }1121                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1122                />1123              </Show>1124            }1125          >1126            <Show1127              when={view() !== "pro-celebration"}1128              fallback={<ProCelebration />}1129            >1130            <section1131              id="hd-shell"1132              class="peach-shell peach-theme"1133              data-surface="extension"1134            >1135            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1136              <PeachWordmark unlocked />1137              <div class="peach-chrome-actions">1138                <button1139                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1140                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1141                  aria-label="Notes"1142                  title="Notes"1143                >1144                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1145                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1146                    <line x1="4" y1="5" x2="10" y2="5" />1147                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1148                    <line x1="4" y1="10" x2="7" y2="10" />1149                  </svg>1150                </button>1151                <button1152                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1153                  onClick={() => setView("settings")}1154                  aria-label="Settings"1155                >1156                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1157                    <path1158                      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"1159                      stroke="currentColor"1160                      stroke-width="0.9"1161                    />1162                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1163                  </svg>1164                </button>1165                <button1166                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1167                  onClick={handleAdd}1168                  aria-label="New entry"1169                >1170                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1171                    <path d="M5.5 1v9M1 5.5h9" />1172                  </svg>1173                </button>1174                <button1175                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1176                  onClick={() => void handleHeaderLock()}1177                  aria-label="Lock vault"1178                >1179                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1180                    <path1181                      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"1182                      stroke="currentColor"1183                      stroke-width="1"1184                      stroke-linecap="round"1185                    />1186                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1187                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1188                  </svg>1189                </button>1190              </div>1191            </header>11921193            <Show when={pendingProNotice() !== null}>1194              <div class="peach-pro-notice-banner">1195                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1196                <button1197                  class="peach-pro-notice-link"1198                  onClick={() => {1199                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1200                    setSettingsInitialSection("license");1201                    setView("settings");1202                    setPendingProNotice(null);1203                  }}1204                >1205                  Learn more →1206                </button>1207                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1208              </div>1209            </Show>12101211            <div class="peach-shell-body">1212              <div class="peach-shell-veil"></div>1213              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1214                <EntryView1215                  entry={selectedEntry()}1216                  currentTabUrl={currentTabUrl()}1217                  entries={entries()}1218                  isPro={proStatus()}1219                  onDelete={handleDelete}1220                  onFieldSaved={() => void loadEntries()}1221                  onEscape={() => { setView("list"); }}1222                  onProGate={(feature) => {1223                    setUpgradeHighlight(feature);1224                    setSettingsInitialSection("license");1225                    setView("settings");1226                  }}1227                />1228              </div>12291230              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1231                <div class="peach-search-bar">1232                  <span class="peach-search-icon">1233                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1234                      <circle cx="5.5" cy="5.5" r="3.75" />1235                      <path d="M8.75 8.75L11.5 11.5" />1236                    </svg>1237                  </span>1238                  <input1239                    class="peach-search-input"1240                    placeholder="search vault..."1241                    autocomplete="off"1242                    aria-label="Search vault entries"1243                    onClick={openList}1244                    onFocus={openList}1245                    readOnly1246                  />1247                  <div class="peach-search-meta">1248                    <span class="peach-search-counter">1249                      {entries().length > 01250                        ? `${selectedIndex() + 1} / ${entries().length}`1251                        : "0 entries"}1252                    </span>1253                    <span class="peach-divider"></span>1254                    <button1255                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1256                      onClick={() => navigate(-1)}1257                      aria-label="Previous 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="M5 1L1 5.5L5 10" />1262                      </svg>1263                    </button>1264                    <button1265                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1266                      onClick={() => navigate(1)}1267                      aria-label="Next entry"1268                      disabled={entries().length === 0}1269                    >1270                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1271                        <path d="M1 1L5 5.5L1 10" />1272                      </svg>1273                    </button>1274                  </div>1275                </div>1276              </section>1277            </div>12781279            {/* Desktop: shown on demand via Show. Native sheet is rendered1280                via Portal below at the document root so its position:fixed1281                isn't trapped by .peach-shell's transform-based animations. */}1282            <Show when={!isNativePlatform() && view() === "list"}>1283              <VaultView1284                entries={entries()}1285                selectedEntryId={selectedEntry()?.id}1286                currentTabDomain={currentTabDomain()}1287                sortOrder={sortOrder()}1288                searchSeed={listSearchSeed()}1289                searchSeedNonce={listSearchSeedNonce()}1290                onSelectEntry={handleSelectEntry}1291                onSortOrderChange={setSortOrder}1292                onAdd={handleAdd}1293                onClose={() => setView("entry")}1294                onOpenTrash={() => setView("trash")}1295                onDeleteMany={handleDeleteMany}1296              />1297            </Show>1298            <Show when={isNativePlatform() && hasVault()}>1299              <Portal>1300                <div1301                  class="peach-vault-sheet"1302                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1303                  style={(() => {1304                    const live = sheetTranslate();1305                    if (live === null) return undefined;1306                    return { transform: `translateY(${live}px)` };1307                  })()}1308                >1309                  <VaultView1310                    entries={entries()}1311                    selectedEntryId={selectedEntry()?.id}1312                    currentTabDomain={currentTabDomain()}1313                    sortOrder={sortOrder()}1314                    searchSeed={listSearchSeed()}1315                    searchSeedNonce={listSearchSeedNonce()}1316                    isNative={true}1317                    onSelectEntry={handleSelectEntry}1318                    onSortOrderChange={setSortOrder}1319                    onAdd={handleAdd}1320                    onClose={() => setView("entry")}1321                    onOpenTrash={() => setView("trash")}1322                    onDeleteMany={handleDeleteMany}1323                  />1324                </div>1325              </Portal>1326            </Show>1327            <Show when={view() === "settings"}>1328              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1329                <SettingsView1330                  entriesCount={entries().length}1331                  breachMonitoring={breachMonitoring()}1332                  lockOnClose={lockOnClose()}1333                  autoLockMinutes={autoLockMinutes()}1334                  trashRetentionDays={trashRetentionDays()}1335                  theme={theme()}1336                  accentColor={accentColor()}1337                  textSize={textSize()}1338                  reduceMotion={reduceMotion()}1339                  isPro={proStatus()}1340                  initialSection={settingsInitialSection()}1341                  upgradeHighlight={upgradeHighlight()}1342                  onBreachMonitoringChange={applyBreachMonitoring}1343                  onLockOnCloseChange={applyLockOnClose}1344                  onAutoLockMinutesChange={applyAutoLockMinutes}1345                  onTrashRetentionChange={applyTrashRetention}1346                  onThemeChange={applyTheme}1347                  onAccentChange={applyAccentColor}1348                  onTextSizeChange={applyTextSize}1349                  onReduceMotionChange={applyReduceMotion}1350                  shortcuts={shortcutBindings()}1351                  onShortcutsChange={applyShortcuts}1352                  onLicenseChange={async () => {1353                    // After activation/deactivation: refresh Pro status,1354                    // re-load entries (defensive — signal state can drift if1355                    // the SW briefly restarts during the verify+save round-trip),1356                    // and replay the Pro celebration if this is the first time1357                    // a valid Pro license is seen on this device.1358                    await refreshProStatus();1359                    void loadEntries();1360                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1361                    if ((should as { ok: boolean; data?: boolean }).data === true) {1362                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1363                      setView("pro-celebration");1364                      window.setTimeout(() => setView("settings"), 2500);1365                    }1366                  }}1367                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1368                  onImport={() => setView("import")}1369                  onExport={() => setView("export")}1370                  onBreachCheckDone={loadEntries}1371                  onOpenHealth={openHealth}1372                  onOpenSyncPairing={() => setView("chirp-sync")}1373                  onOpenFileImport={handleOpenFileImport}1374                  onOpenPanic={() => setView("panic")}1375                  onOpenCodexGenerate={() => setView("codex-generate")}1376                  onOpenCodexRestore={() => setView("codex-restore")}1377                  onProGate={(feature) => {1378                    setUpgradeHighlight(feature);1379                    setSettingsInitialSection("license");1380                  }}1381                />1382              </Suspense>1383            </Show>1384            <Show when={view() === "codex-generate"}>1385              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1386                <CodexGenerateView1387                  isPro={proStatus()}1388                  onBack={() => setView("settings")}1389                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1390                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1391                  onVaultLocked={() => handleLock()}1392                />1393              </Suspense>1394            </Show>1395            <Show when={view() === "codex-restore"}>1396              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1397                <CodexRestoreView1398                  onBack={() => setView("lock")}1399                  onRestoreSuccess={async () => {1400                    // After restore the vault is unlocked; refresh entries1401                    // and route to the main vault list. handleUnlock is the1402                    // canonical post-unlock setup path.1403                    await handleUnlock();1404                  }}1405                />1406              </Suspense>1407            </Show>1408            <Show when={view() === "chirp-sync"}>1409              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1410                <ChirpSyncView1411                  isPro={proStatus()}1412                  onBack={() => setView("settings")}1413                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1414                />1415              </Suspense>1416            </Show>1417            <Show when={view() === "add"}>1418              <AddView1419                entry={editEntry()}1420                entries={entries()}1421                onBack={handleBack}1422                onSave={handleSave}1423              />1424            </Show>1425            <Show when={view() === "import"}>1426              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1427                <ImportView onBack={handleBack} onImport={handleSave} />1428              </Suspense>1429            </Show>1430            <Show when={view() === "export"}>1431              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1432                <ExportView1433                  onBack={() => {1434                    if (returnToPanic()) {1435                      setReturnToPanic(false);1436                      setView("panic");1437                    } else {1438                      handleBack();1439                    }1440                  }}1441                />1442              </Suspense>1443            </Show>1444            <Show when={view() === "panic"}>1445              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1446                <PanicView1447                  onCancel={() => setView("settings")}1448                  onOpenExport={() => {1449                    setReturnToPanic(true);1450                    setView("export");1451                  }}1452                  onDestroyed={async () => {1453                    clearCanarySuppressions();1454                    setEntries([]);1455                    setSelectedEntry(null);1456                    setEditEntry(undefined);1457                    setHasVault(false);1458                    setOnboarded(false);1459                    setProStatus(false);1460                    setPendingPasskey(null);1461                    setUpgradeHighlight(null);1462                    setSettingsInitialSection(null);1463                    setPendingProNotice(null);1464                    setPendingCelebration(false);1465                    setReturnToPanic(false);1466                    setContentPhase("idle");1467                    setView("lock");1468                  }}1469                />1470              </Suspense>1471            </Show>1472            <Show when={view() === "health"}>1473              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1474                <HealthView1475                  entries={entries()}1476                  isPro={proStatus()}1477                  onFixEntry={handleFixEntry}1478                  onBack={() => setView("settings")}1479                  onRefresh={loadEntries}1480                />1481              </Suspense>1482            </Show>1483            <Show when={view() === "trash"}>1484              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1485                <TrashView1486                  onBack={() => setView("list")}1487                  onRestored={() => void loadEntries()}1488                />1489              </Suspense>1490            </Show>1491            <Show when={showNotes()}>1492              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1493                <NotesMode1494                  notes={entries().filter((e) => e.type === "note")}1495                  initialNoteId={openNoteId()}1496                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1497                  onNoteListChanged={() => void loadEntries()}1498                />1499              </div>1500            </Show>1501            <Show when={restoreView() === "file"}>1502              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1503                <ImportView1504                  mode="onboarding"1505                  replacesExistingVault={true}1506                  onBack={() => setRestoreView(null)}1507                  onImport={async () => {1508                    setRestoreView(null);1509                    await handleUnlock();1510                  }}1511                />1512              </Suspense>1513            </Show>1514            </section>1515            </Show>1516          </Show>1517        </Show>1518      </Show>1519      <Show when={showShortcutsHelp()}>1520        <ShortcutsHelpOverlay1521          bindings={shortcutBindings()}1522          onClose={() => setShowShortcutsHelp(false)}1523        />1524      </Show>1525    </div>1526  );1527}15281529function ShortcutsHelpOverlay(props: {1530  bindings: Record<ShortcutAction, Keybinding>;1531  onClose: () => void;1532}) {1533  return (1534    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1535      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1536        <div class="peach-shortcuts-help-head">1537          <h3>Keyboard shortcuts</h3>1538          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1539        </div>1540        <div class="peach-shortcuts-help-body">1541          <p class="peach-settings-sub-label">ENTRY VIEW</p>1542          <ul>1543            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1544              <li>1545                <span>{d.label}</span>1546                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1547              </li>1548            ))}1549          </ul>1550          <p class="peach-settings-sub-label">ANYWHERE</p>1551          <ul>1552            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1553              <li>1554                <span>{d.label}</span>1555                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1556              </li>1557            ))}1558          </ul>1559        </div>1560      </div>1561    </div>1562  );1563}