App.tsx

63.6 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" || v === "import" || v === "export" || v === "add" || v === "health") {519        handleBack();520        return;521      }522      if (v === "chirp-sync") { setView("settings"); return; }523    };524    window.addEventListener("peach:back", handlePeachBack);525    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));526527    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that528    // peeks from the bottom (search bar handle visible) and drags up to fill529    // the screen. dragOffset is the LIVE finger offset during a drag, in px,530    // 0 when no drag in progress. The wrapper element computes transform =531    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.532    if (isNativePlatform()) {533      let touchStartY = 0;534      let touchStartX = 0;535      let lastY = 0;536      let lastT = 0;537      let dragging = false;538      let captured = false;539      const HORIZONTAL_TOLERANCE = 16;540      const ACTIVATION_DY = 8;541      const PEEK_PX = 60;542543      const onTouchStart = (e: TouchEvent) => {544        const t = e.touches[0];545        if (!t) return;546        const v = view();547        if (v !== "entry" && v !== "list") return;548        // Entry view: only intercept drags starting in the bottom 40%.549        // List view: intercept drags starting in the top 35% (the search/handle row).550        const inBand = v === "entry"551          ? t.clientY > window.innerHeight * 0.6552          : t.clientY < window.innerHeight * 0.35;553        if (!inBand) return;554        touchStartY = lastY = t.clientY;555        touchStartX = t.clientX;556        lastT = e.timeStamp;557        dragging = true;558        captured = false;559      };560561      const onTouchMove = (e: TouchEvent) => {562        if (!dragging) return;563        const t = e.touches[0];564        if (!t) return;565        const dy = t.clientY - touchStartY;566        const dx = Math.abs(t.clientX - touchStartX);567568        if (!captured) {569          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {570            // Looks like a horizontal swipe — release.571            dragging = false;572            return;573          }574          if (Math.abs(dy) < ACTIVATION_DY) return;575          captured = true;576        }577578        // Translate the sheet by dy from its rest (peek) position. Peek is579        // (viewport height - PEEK_PX). Open is 0.580        const v = view();581        const restClosed = window.innerHeight - PEEK_PX;582        const baseTranslate = v === "list" ? 0 : restClosed;583        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));584        setSheetTranslate(next);585        lastY = t.clientY;586        lastT = e.timeStamp;587      };588589      const onTouchEnd = (e: TouchEvent) => {590        if (!dragging) { return; }591        const t = e.changedTouches[0];592        const elapsed = Math.max(1, e.timeStamp - lastT);593        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms594        const wasCaptured = captured;595        dragging = false;596        captured = false;597        const v = view();598599        if (!wasCaptured) {600          // Tap in the peek strip while in entry view → open the vault list.601          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");602          setSheetTranslate(null);603          return;604        }605606        const restClosed = window.innerHeight - PEEK_PX;607        const current = sheetTranslate() ?? restClosed;608609        // Snap rules:610        //   - Strong upward velocity → open611        //   - Strong downward velocity → close612        //   - Otherwise snap to whichever rest is closer613        let nextOpen: boolean;614        if (velocity < -0.05) nextOpen = true;615        else if (velocity > 0.05) nextOpen = false;616        else nextOpen = current < restClosed * 0.5;617618        if (nextOpen && v !== "list") setView("list");619        if (!nextOpen && v !== "entry") setView("entry");620        // Release the live offset so CSS transition handles the snap.621        setSheetTranslate(null);622      };623624      document.addEventListener("touchstart", onTouchStart, { passive: true });625      document.addEventListener("touchmove",  onTouchMove,  { passive: true });626      document.addEventListener("touchend",   onTouchEnd,   { passive: true });627      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });628      onCleanup(() => {629        document.removeEventListener("touchstart", onTouchStart);630        document.removeEventListener("touchmove",  onTouchMove);631        document.removeEventListener("touchend",   onTouchEnd);632      });633    }634635    // Action handlers — keyed by ShortcutAction. The dispatcher below tests636    // each binding against the event and runs the matching handler. New637    // shortcuts only need an entry here; the binding is data, not code.638    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {639      copy_password: () => {640        const entry = selectedEntry();641        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });642      },643      copy_username: () => {644        const entry = selectedEntry();645        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });646      },647      copy_totp: () => {648        const entry = selectedEntry();649        if (!entry?.totp) return;650        try {651          const { code } = generateTOTP(entry.totp);652          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });653        } catch { /* invalid TOTP secret — silent */ }654      },655      new_entry: () => handleAdd(),656      edit_entry: () => {657        const entry = selectedEntry();658        // Passkey-only entries have nothing user-editable in the Add view; the659        // passkey credential itself is opaque. Skip the edit action for them.660        if (!entry || isPasskeyOnly(entry)) return;661        setEditEntry(entry);662        setView("add");663      },664      delete_entry: () => {665        if (selectedEntry()) void handleDelete();666      },667      lock_vault: () => { void handleHeaderLock(); },668      search: () => openList(),669      nav_prev: () => navigate(-1),670      nav_next: () => navigate(1),671      jump_vault: () => setView("entry"),672      jump_settings: () => setView("settings"),673      show_help: () => setShowShortcutsHelp(true),674    };675676    // Actions that are MEANINGFUL only on the entry-detail view. Outside677    // that scope the binding is dormant — pressing C while on Settings678    // does nothing rather than awkwardly copying from a now-stale entry.679    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([680      "copy_password", "copy_username", "copy_totp",681      "edit_entry", "delete_entry", "nav_prev", "nav_next",682    ]);683684    const handleGlobalKeydown = (e: KeyboardEvent) => {685      const v = view();686      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"687        || (e.target as HTMLElement)?.tagName === "TEXTAREA"688        || (e.target as HTMLElement)?.isContentEditable;689      const isPrintableSearchKey =690        e.key.length === 1 &&691        !e.ctrlKey &&692        !e.metaKey &&693        !e.altKey;694695      // No input during the pro celebration sequence696      if (v === "pro-celebration") return;697698      // Help dialog: Escape closes it; eat the keypress so it doesn't699      // also navigate away from the underlying view.700      if (showShortcutsHelp()) {701        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }702        return;703      }704705      // ── Escape — fixed binding (not user-customizable) ───────706      if (e.key === "Escape") {707        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }708        if (v === "list") { setView("entry"); return; }709        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }710        if (v === "chirp-sync") { setView("settings"); return; }711      }712713      // Bindings-driven dispatch. Single-key letter bindings without714      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is715      // inside an input, so users can type into search/forms normally.716      const bindings = shortcutBindings();717      for (const action of Object.keys(bindings) as ShortcutAction[]) {718        const binding = bindings[action];719        if (!matchKeybinding(e, binding)) continue;720        // Single-key letter bindings need the input-focus guard. Bindings721        // with any modifier are safe — Ctrl+L doesn't conflict with typing.722        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;723        if (!hasMod && binding.key.length === 1 && inInput) return;724        if (ENTRY_SCOPED.has(action) && v !== "entry") return;725        e.preventDefault();726        SHORTCUT_HANDLERS[action]?.();727        return;728      }729730      // Type-to-search: in entry view, any printable key not consumed by a731      // shortcut above primes the list search seed and opens the list.732      // Kept outside the bindings table because it's a behavior, not a733      // discrete action — every printable character can trigger it.734      if (v === "entry" && !inInput && isPrintableSearchKey) {735        e.preventDefault();736        primeListSearch(e.key);737        return;738      }739    };740    window.addEventListener("keydown", handleGlobalKeydown);741    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));742743    const handleStorageChanged = (744      changes: Record<string, chrome.storage.StorageChange>,745      areaName: string746    ) => {747      if (areaName !== "session") return;748      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {749        return;750      }751      void refreshPendingPasskey();752    };753    chrome.storage.onChanged.addListener(handleStorageChanged);754    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));755  });756757  async function refreshCurrentTab() {758    try {759      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });760      const url = tab?.url ?? tab?.pendingUrl ?? "";761      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");762      // Skip extension/internal URLs — adding chrome://, about:, or763      // chrome-extension:// to a vault entry is never what the user wants.764      const isWebUrl = /^https?:\/\//i.test(url);765      setCurrentTabUrl(isWebUrl ? url : "");766    } catch {767      setCurrentTabDomain("");768      setCurrentTabUrl("");769    }770  }771772  async function refreshPendingPasskey() {773    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });774    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);775  }776777  async function refreshProStatus() {778    const res = await sendMessage({ type: "GET_LICENSE" });779    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;780    setProStatus(Boolean(data?.valid && data?.plan === "pro"));781  }782783  async function restoreSettings() {784    const res = await sendMessage({ type: "GET_SETTINGS" });785    const s = (res as { ok: boolean; data?: any }).data ?? {};786    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {787      setAccentColor(s.accentColor as AccentColorName);788    }789    setTheme(s.theme === "light" ? "light" : "dark");790    if (s.textSize === "small" || s.textSize === "large") {791      setTextSize(s.textSize);792    } else {793      setTextSize("medium");794    }795    setReduceMotion(s.reduceMotion === true);796    setLockOnClose(s.lockOnClose !== false);797    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);798    setBreachMonitoring(s.breachMonitoring !== false);799    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);800    setShortcutBindings(getActiveBindings(s.shortcuts));801  }802803  async function applyTrashRetention(days: number) {804    setTrashRetentionDays(days);805    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });806  }807808  function primeListSearch(seed: string) {809    setListSearchSeed(seed);810    setListSearchSeedNonce((value) => value + 1);811    openList();812  }813814  // Returns null when it detected a dead service worker and triggered handleLock().815  // Callers that need to abort (e.g. openVault) check for null rather than relying816  // on view() state, which may already be "lock" during normal startup flows.817  async function loadEntries(): Promise<VaultEntry[] | null> {818    const response = await sendMessage({ type: "GET_ENTRIES" });819    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };820821    // If the service worker was killed and restarted (MV3 workers sleep), the822    // vault will be locked again — or the worker may not respond at all.823    // In either case, send the user to the lock screen rather than silently824    // showing an empty vault (which looks like data loss).825    if (!res.ok) {826      if (827        res.error === "vault_locked" ||828        res.error === "SERVICE_WORKER_UNAVAILABLE" ||829        (typeof res.error === "string" && res.error.includes("locked"))830      ) {831        handleLock();832        return null; // signal emergency lock to callers833      }834      return [];835    }836837    const loadedEntries = res.data ?? [];838    setEntries(loadedEntries);839840    const currentId = selectedEntry()?.id;841    if (currentId) {842      setSelectedEntry(843        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null844      );845    }846847    return loadedEntries;848  }849850  async function openVault(preferredEntryId?: string, skipViewSet = false) {851    // Purge expired trash entries on each vault open852    const retDays = trashRetentionDays();853    if (retDays > 0) {854      void sendMessage({855        type: "PURGE_EXPIRED_TRASH",856        payload: { retentionMs: retDays * 86_400_000 },857      });858    }859860    const loadedEntries = await loadEntries();861862    // null means loadEntries() triggered an emergency lock (service worker died).863    // Don't override it by setting view back to "entry" with an empty vault.864    if (loadedEntries === null) return;865866    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry867    let nextSelectedEntry: VaultEntry | null = null;868    if (preferredEntryId) {869      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;870    }871    if (!nextSelectedEntry) {872      const tabDomain = currentTabDomain();873      if (tabDomain) {874        nextSelectedEntry = loadedEntries.find((e) => {875          if (e.type === "login") {876            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;877            for (const extra of e.additionalUrls ?? []) {878              if ((extractDomain(extra) ?? "") === tabDomain) return true;879            }880            return false;881          }882          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;883          return false;884        }) ?? null;885      }886    }887    nextSelectedEntry ??= loadedEntries[0] ?? null;888889    setSelectedEntry(nextSelectedEntry);890    setEditEntry(undefined);891    setContentTransitioning(false);892    setContentPhase("enter");893    queueContentIdle();894    if (!skipViewSet) setView("entry");895  }896897  async function handleUnlock() {898    // If the user previously created a vault but hadn't yet confirmed their899    // recovery words (and the browser was closed before they could), the900    // peach_recovery_pending flag is still set in storage.local. Re-route901    // back to the recovery surface so they finish the confirmation step902    // before reaching the entries view — the words can be re-derived now903    // that the vault is unlocked again.904    let recoveryPending = false;905    try {906      const out = await chrome.storage.local?.get("peach_recovery_pending");907      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";908    } catch { /* best-effort */ }909    if (recoveryPending) {910      setForceRecoveryWords(true);911      setView("lock");912      triggerPipPulse();913      await restoreSettings();914      return;915    }916    setHasVault(true);917    triggerPipPulse();918    await restoreSettings();919    const celebrating = pendingCelebration();920    if (celebrating) {921      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });922      setPendingCelebration(false);923    }924    await openVault(undefined, celebrating);925    if (celebrating) {926      setView("pro-celebration");927      window.setTimeout(() => setView("entry"), 2500);928    }929  }930931  function handleSelectEntry(entry: VaultEntry) {932    if (entry.type === "note") {933      setOpenNoteId(entry.id);934      setShowNotes(true);935      return;936    }937    setSelectedEntry(entry);938    setContentTransitioning(false);939    setContentPhase("enter");940    queueContentIdle();941    setView("entry");942  }943944  function handleAdd() {945    setEditEntry(undefined);946    setView("add");947  }948949  async function handleDelete() {950    const entry = selectedEntry();951    if (!entry) return;952    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });953    const loadedEntries = await loadEntries() ?? [];954    setSelectedEntry(loadedEntries[0] ?? null);955    setView("entry");956  }957958  async function handleDeleteMany(ids: string[]) {959    for (const id of ids) {960      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });961    }962    const loadedEntries = await loadEntries() ?? [];963    // If the currently selected entry was among the deleted, move to first964    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);965    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);966  }967968  async function handleSave(savedEntry?: VaultEntry) {969    await openVault(savedEntry?.id);970  }971972  function handleBack() {973    setEditEntry(undefined);974    setView("entry");975  }976977  function handleLock() {978    clearCanarySuppressions();979    setEntries([]);980    setSelectedEntry(null);981    setEditEntry(undefined);982    setContentPhase("idle");983    setView("lock");984  }985986  function handleHeaderLock() {987    // Lock the UI immediately — do not wait for the service worker. If the SW988    // is dead or slow, the 5s sendMessage timeout would create a dead-click989    // window. The SW will lock on its next wake regardless.990    handleLock();991    void sendMessage({ type: "LOCK" });992  }993994  function navigate(dir: number) {995    const allEntries = entries();996    if (allEntries.length === 0) return;997    const currentIndex = selectedIndex();998    const baseIndex = currentIndex >= 0 ? currentIndex : 0;999    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1000    setSelectedEntry(allEntries[nextIndex]);1001    setContentPhase("enter");1002    queueContentIdle();1003  }10041005  function openList() {1006    setView("list");1007  }10081009  function openHealth() {1010    setEditEntry(undefined);1011    setView("health");1012  }10131014  function handleOpenFileImport() {1015    setRestoreView("file");1016  }10171018  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10191020  function handleFixEntry(entry: VaultEntry) {1021    // Passkey-only entries have no editable surface — drop into view mode1022    // instead of opening the Add editor.1023    if (isPasskeyOnly(entry)) {1024      setSelectedEntry(entry);1025      setView("entry");1026      return;1027    }1028    setEditEntry(entry);1029    setView("add");1030  }10311032  const isLockedView = () => view() === "lock";10331034  async function handleApprovePendingPasskey() {1035    const pending = pendingPasskey();1036    if (!pending) return;1037    if (pending.browser === "firefox" && pending.type === "create") {1038      // Firefox path: popup itself runs navigator.credentials.create. The1039      // background never approved/rejected anything — it just stashed1040      // intent. After the popup-driven flow resolves (success or cancel),1041      // clear the pending key so the popup doesn't re-show this on next open.1042      const { createFirefoxPasskey } = await import("./firefox-passkey");1043      const result = await createFirefoxPasskey(pending);1044      if (!result.ok) {1045        console.warn("Peach Firefox passkey create failed:", result.error);1046      }1047      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1048      setPendingPasskey(null);1049      void loadEntries();1050      window.close();1051      return;1052    }1053    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1054    window.close();1055  }10561057  async function handleDenyPendingPasskey() {1058    const pending = pendingPasskey();1059    if (!pending) return;1060    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1061    window.close();1062  }10631064  function queueContentIdle(after?: () => void) {1065    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1066    contentPhaseTimer = window.setTimeout(() => {1067      setContentPhase("idle");1068      after?.();1069    }, ENTRY_TRANSITION_SETTLE_MS);1070  }10711072  return (1073    <div class="popup-root peach-theme">1074      <Show when={bootState() === "ready"}>1075        <Show1076          when={!pendingPasskey()}1077          fallback={1078            <PasskeyApprovalView1079              type={pendingPasskey()!.type}1080              rpName={pendingPasskey()!.rpName}1081              rpId={pendingPasskey()!.rpId}1082              userName={pendingPasskey()!.userName}1083              userDisplayName={pendingPasskey()!.userDisplayName}1084              onApprove={handleApprovePendingPasskey}1085              onDeny={handleDenyPendingPasskey}1086            />1087          }1088        >1089          <Show1090            when={!isLockedView()}1091            fallback={1092              <Show1093                when={onboarded() || hasVault()}1094                fallback={1095                  <Onboarding1096                    onComplete={() => { setOnboarded(true); }}1097                  />1098                }1099              >1100                <LockView1101                  hasVault={hasVault()}1102                  ready={bootState() === "ready"}1103                  isPro={proStatus()}1104                  forceRecoveryWords={forceRecoveryWords()}1105                  onUnlock={() => {1106                    // RecoveryWordDisplay clears the storage flag before1107                    // calling onDone, so handleUnlock will see no pending1108                    // confirmation and proceed through the normal path.1109                    if (forceRecoveryWords()) setForceRecoveryWords(false);1110                    return handleUnlock();1111                  }}1112                  onBackToOnboarding={1113                    !hasVault()1114                      ? () => setOnboarded(false)1115                      : undefined1116                  }1117                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1118                />1119              </Show>1120            }1121          >1122            <Show1123              when={view() !== "pro-celebration"}1124              fallback={<ProCelebration />}1125            >1126            <section1127              id="hd-shell"1128              class="peach-shell peach-theme"1129              data-surface="extension"1130            >1131            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1132              <PeachWordmark unlocked />1133              <div class="peach-chrome-actions">1134                <button1135                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1136                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1137                  aria-label="Notes"1138                  title="Notes"1139                >1140                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1141                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1142                    <line x1="4" y1="5" x2="10" y2="5" />1143                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1144                    <line x1="4" y1="10" x2="7" y2="10" />1145                  </svg>1146                </button>1147                <button1148                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1149                  onClick={() => setView("settings")}1150                  aria-label="Settings"1151                >1152                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1153                    <path1154                      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"1155                      stroke="currentColor"1156                      stroke-width="0.9"1157                    />1158                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1159                  </svg>1160                </button>1161                <button1162                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1163                  onClick={handleAdd}1164                  aria-label="New entry"1165                >1166                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1167                    <path d="M5.5 1v9M1 5.5h9" />1168                  </svg>1169                </button>1170                <button1171                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1172                  onClick={() => void handleHeaderLock()}1173                  aria-label="Lock vault"1174                >1175                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1176                    <path1177                      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"1178                      stroke="currentColor"1179                      stroke-width="1"1180                      stroke-linecap="round"1181                    />1182                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1183                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1184                  </svg>1185                </button>1186              </div>1187            </header>11881189            <Show when={pendingProNotice() !== null}>1190              <div class="peach-pro-notice-banner">1191                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1192                <button1193                  class="peach-pro-notice-link"1194                  onClick={() => {1195                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1196                    setSettingsInitialSection("license");1197                    setView("settings");1198                    setPendingProNotice(null);1199                  }}1200                >1201                  Learn more →1202                </button>1203                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1204              </div>1205            </Show>12061207            <div class="peach-shell-body">1208              <div class="peach-shell-veil"></div>1209              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1210                <EntryView1211                  entry={selectedEntry()}1212                  currentTabUrl={currentTabUrl()}1213                  entries={entries()}1214                  isPro={proStatus()}1215                  onDelete={handleDelete}1216                  onFieldSaved={() => void loadEntries()}1217                  onEscape={() => { setView("list"); }}1218                  onProGate={(feature) => {1219                    setUpgradeHighlight(feature);1220                    setSettingsInitialSection("license");1221                    setView("settings");1222                  }}1223                />1224              </div>12251226              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1227                <div class="peach-search-bar">1228                  <span class="peach-search-icon">1229                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1230                      <circle cx="5.5" cy="5.5" r="3.75" />1231                      <path d="M8.75 8.75L11.5 11.5" />1232                    </svg>1233                  </span>1234                  <input1235                    class="peach-search-input"1236                    placeholder="search vault..."1237                    autocomplete="off"1238                    aria-label="Search vault entries"1239                    onClick={openList}1240                    onFocus={openList}1241                    readOnly1242                  />1243                  <div class="peach-search-meta">1244                    <span class="peach-search-counter">1245                      {entries().length > 01246                        ? `${selectedIndex() + 1} / ${entries().length}`1247                        : "0 entries"}1248                    </span>1249                    <span class="peach-divider"></span>1250                    <button1251                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1252                      onClick={() => navigate(-1)}1253                      aria-label="Previous entry"1254                      disabled={entries().length === 0}1255                    >1256                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1257                        <path d="M5 1L1 5.5L5 10" />1258                      </svg>1259                    </button>1260                    <button1261                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1262                      onClick={() => navigate(1)}1263                      aria-label="Next entry"1264                      disabled={entries().length === 0}1265                    >1266                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1267                        <path d="M1 1L5 5.5L1 10" />1268                      </svg>1269                    </button>1270                  </div>1271                </div>1272              </section>1273            </div>12741275            {/* Desktop: shown on demand via Show. Native sheet is rendered1276                via Portal below at the document root so its position:fixed1277                isn't trapped by .peach-shell's transform-based animations. */}1278            <Show when={!isNativePlatform() && view() === "list"}>1279              <VaultView1280                entries={entries()}1281                selectedEntryId={selectedEntry()?.id}1282                currentTabDomain={currentTabDomain()}1283                sortOrder={sortOrder()}1284                searchSeed={listSearchSeed()}1285                searchSeedNonce={listSearchSeedNonce()}1286                onSelectEntry={handleSelectEntry}1287                onSortOrderChange={setSortOrder}1288                onAdd={handleAdd}1289                onClose={() => setView("entry")}1290                onOpenTrash={() => setView("trash")}1291                onDeleteMany={handleDeleteMany}1292              />1293            </Show>1294            <Show when={isNativePlatform() && hasVault()}>1295              <Portal>1296                <div1297                  class="peach-vault-sheet"1298                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1299                  style={(() => {1300                    const live = sheetTranslate();1301                    if (live === null) return undefined;1302                    return { transform: `translateY(${live}px)` };1303                  })()}1304                >1305                  <VaultView1306                    entries={entries()}1307                    selectedEntryId={selectedEntry()?.id}1308                    currentTabDomain={currentTabDomain()}1309                    sortOrder={sortOrder()}1310                    searchSeed={listSearchSeed()}1311                    searchSeedNonce={listSearchSeedNonce()}1312                    isNative={true}1313                    onSelectEntry={handleSelectEntry}1314                    onSortOrderChange={setSortOrder}1315                    onAdd={handleAdd}1316                    onClose={() => setView("entry")}1317                    onOpenTrash={() => setView("trash")}1318                    onDeleteMany={handleDeleteMany}1319                  />1320                </div>1321              </Portal>1322            </Show>1323            <Show when={view() === "settings"}>1324              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1325                <SettingsView1326                  entriesCount={entries().length}1327                  breachMonitoring={breachMonitoring()}1328                  lockOnClose={lockOnClose()}1329                  autoLockMinutes={autoLockMinutes()}1330                  trashRetentionDays={trashRetentionDays()}1331                  theme={theme()}1332                  accentColor={accentColor()}1333                  textSize={textSize()}1334                  reduceMotion={reduceMotion()}1335                  isPro={proStatus()}1336                  initialSection={settingsInitialSection()}1337                  upgradeHighlight={upgradeHighlight()}1338                  onBreachMonitoringChange={applyBreachMonitoring}1339                  onLockOnCloseChange={applyLockOnClose}1340                  onAutoLockMinutesChange={applyAutoLockMinutes}1341                  onTrashRetentionChange={applyTrashRetention}1342                  onThemeChange={applyTheme}1343                  onAccentChange={applyAccentColor}1344                  onTextSizeChange={applyTextSize}1345                  onReduceMotionChange={applyReduceMotion}1346                  shortcuts={shortcutBindings()}1347                  onShortcutsChange={applyShortcuts}1348                  onLicenseChange={async () => {1349                    // After activation/deactivation: refresh Pro status,1350                    // re-load entries (defensive — signal state can drift if1351                    // the SW briefly restarts during the verify+save round-trip),1352                    // and replay the Pro celebration if this is the first time1353                    // a valid Pro license is seen on this device.1354                    await refreshProStatus();1355                    void loadEntries();1356                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1357                    if ((should as { ok: boolean; data?: boolean }).data === true) {1358                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1359                      setView("pro-celebration");1360                      window.setTimeout(() => setView("settings"), 2500);1361                    }1362                  }}1363                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1364                  onImport={() => setView("import")}1365                  onExport={() => setView("export")}1366                  onBreachCheckDone={loadEntries}1367                  onOpenHealth={openHealth}1368                  onOpenSyncPairing={() => setView("chirp-sync")}1369                  onOpenFileImport={handleOpenFileImport}1370                  onOpenPanic={() => setView("panic")}1371                  onOpenCodexGenerate={() => setView("codex-generate")}1372                  onOpenCodexRestore={() => setView("codex-restore")}1373                  onProGate={(feature) => {1374                    setUpgradeHighlight(feature);1375                    setSettingsInitialSection("license");1376                  }}1377                />1378              </Suspense>1379            </Show>1380            <Show when={view() === "codex-generate"}>1381              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1382                <CodexGenerateView1383                  isPro={proStatus()}1384                  onBack={() => setView("settings")}1385                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1386                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1387                />1388              </Suspense>1389            </Show>1390            <Show when={view() === "codex-restore"}>1391              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1392                <CodexRestoreView1393                  onBack={() => setView("lock")}1394                  onRestoreSuccess={async () => {1395                    // After restore the vault is unlocked; refresh entries1396                    // and route to the main vault list. handleUnlock is the1397                    // canonical post-unlock setup path.1398                    await handleUnlock();1399                  }}1400                />1401              </Suspense>1402            </Show>1403            <Show when={view() === "chirp-sync"}>1404              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1405                <ChirpSyncView1406                  isPro={proStatus()}1407                  onBack={() => setView("settings")}1408                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1409                />1410              </Suspense>1411            </Show>1412            <Show when={view() === "add"}>1413              <AddView1414                entry={editEntry()}1415                entries={entries()}1416                onBack={handleBack}1417                onSave={handleSave}1418              />1419            </Show>1420            <Show when={view() === "import"}>1421              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1422                <ImportView onBack={handleBack} onImport={handleSave} />1423              </Suspense>1424            </Show>1425            <Show when={view() === "export"}>1426              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1427                <ExportView1428                  onBack={() => {1429                    if (returnToPanic()) {1430                      setReturnToPanic(false);1431                      setView("panic");1432                    } else {1433                      handleBack();1434                    }1435                  }}1436                />1437              </Suspense>1438            </Show>1439            <Show when={view() === "panic"}>1440              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1441                <PanicView1442                  onCancel={() => setView("settings")}1443                  onOpenExport={() => {1444                    setReturnToPanic(true);1445                    setView("export");1446                  }}1447                  onDestroyed={async () => {1448                    clearCanarySuppressions();1449                    setEntries([]);1450                    setSelectedEntry(null);1451                    setEditEntry(undefined);1452                    setHasVault(false);1453                    setOnboarded(false);1454                    setProStatus(false);1455                    setPendingPasskey(null);1456                    setUpgradeHighlight(null);1457                    setSettingsInitialSection(null);1458                    setPendingProNotice(null);1459                    setPendingCelebration(false);1460                    setReturnToPanic(false);1461                    setContentPhase("idle");1462                    setView("lock");1463                  }}1464                />1465              </Suspense>1466            </Show>1467            <Show when={view() === "health"}>1468              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1469                <HealthView1470                  entries={entries()}1471                  isPro={proStatus()}1472                  onFixEntry={handleFixEntry}1473                  onBack={() => setView("settings")}1474                  onRefresh={loadEntries}1475                />1476              </Suspense>1477            </Show>1478            <Show when={view() === "trash"}>1479              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1480                <TrashView1481                  onBack={() => setView("list")}1482                  onRestored={() => void loadEntries()}1483                />1484              </Suspense>1485            </Show>1486            <Show when={showNotes()}>1487              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1488                <NotesMode1489                  notes={entries().filter((e) => e.type === "note")}1490                  initialNoteId={openNoteId()}1491                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1492                  onNoteListChanged={() => void loadEntries()}1493                />1494              </div>1495            </Show>1496            <Show when={restoreView() === "file"}>1497              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1498                <ImportView1499                  mode="onboarding"1500                  replacesExistingVault={true}1501                  onBack={() => setRestoreView(null)}1502                  onImport={async () => {1503                    setRestoreView(null);1504                    await handleUnlock();1505                  }}1506                />1507              </Suspense>1508            </Show>1509            </section>1510            </Show>1511          </Show>1512        </Show>1513      </Show>1514      <Show when={showShortcutsHelp()}>1515        <ShortcutsHelpOverlay1516          bindings={shortcutBindings()}1517          onClose={() => setShowShortcutsHelp(false)}1518        />1519      </Show>1520    </div>1521  );1522}15231524function ShortcutsHelpOverlay(props: {1525  bindings: Record<ShortcutAction, Keybinding>;1526  onClose: () => void;1527}) {1528  return (1529    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1530      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1531        <div class="peach-shortcuts-help-head">1532          <h3>Keyboard shortcuts</h3>1533          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1534        </div>1535        <div class="peach-shortcuts-help-body">1536          <p class="peach-settings-sub-label">ENTRY VIEW</p>1537          <ul>1538            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1539              <li>1540                <span>{d.label}</span>1541                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1542              </li>1543            ))}1544          </ul>1545          <p class="peach-settings-sub-label">ANYWHERE</p>1546          <ul>1547            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1548              <li>1549                <span>{d.label}</span>1550                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1551              </li>1552            ))}1553          </ul>1554        </div>1555      </div>1556    </div>1557  );1558}