App.tsx

64.2 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 [settingsExiting, setSettingsExiting] = createSignal(false);165  const [showNotes, setShowNotes] = createSignal(false);166  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);167  // Set on popup boot when peach_recovery_pending flag is found in session168  // storage — instructs LockView to skip the unlock UI and open the recovery169  // words confirmation surface instead. Cleared via handleUnlock once the170  // user has typed the 3 confirmation words.171  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);172173  let contentPhaseTimer: number | undefined;174175  function applyAccent(name: AccentColorName) {176    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;177    const hex = color.hex;178    document.documentElement.style.setProperty("--peach-accent", hex);179    // Ambient surface variables — derived from the accent so surfaces shift180    // subtly toward the accent hue rather than staying fixed warm-brown.181    document.documentElement.style.setProperty("--peach-glow", hex + "2A");182    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");183    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");184  }185186  createEffect(() => {187    applyAccent(accentColor());188  });189190  createEffect(() => {191    document.documentElement.classList.toggle("light", theme() === "light");192    document.body.classList.toggle("light", theme() === "light");193  });194195  createEffect(() => {196    document.documentElement.setAttribute("data-text-size", textSize());197  });198199  createEffect(() => {200    if (reduceMotion()) {201      document.documentElement.setAttribute("data-motion", "reduce");202    } else {203      document.documentElement.removeAttribute("data-motion");204    }205  });206207  const selectedIndex = createMemo(() => {208    const currentId = selectedEntry()?.id;209    if (!currentId) return entries().length > 0 ? 0 : -1;210    return entries().findIndex((entry) => entry.id === currentId);211  });212213  async function applyAccentColor(name: AccentColorName) {214    applyAccent(name);215    setAccentColor(name);216    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });217  }218219  async function applyTheme(t: "dark" | "light") {220    setTheme(t);221    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });222  }223224  async function applyTextSize(size: "small" | "medium" | "large") {225    setTextSize(size);226    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });227  }228229  async function applyReduceMotion(enabled: boolean) {230    setReduceMotion(enabled);231    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });232  }233234  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload235  // small and lets future default updates land for actions the user hasn't236  // touched. Settings sends us the full active map; we filter and store.237  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {238    setShortcutBindings(active);239    const overrides: Record<string, Keybinding> = {};240    for (const action of Object.keys(active) as ShortcutAction[]) {241      const a = active[action];242      const d = DEFAULT_BINDINGS[action];243      const same = a.key === d.key244        && Boolean(a.ctrl)  === Boolean(d.ctrl)245        && Boolean(a.meta)  === Boolean(d.meta)246        && Boolean(a.shift) === Boolean(d.shift)247        && Boolean(a.alt)   === Boolean(d.alt);248      if (!same) overrides[action] = a;249    }250    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });251  }252253  async function applyLockOnClose(enabled: boolean) {254    setLockOnClose(enabled);255    await sendMessage({256      type: "UPDATE_SETTINGS",257      payload: { lockOnClose: enabled },258    });259  }260261  async function applyAutoLockMinutes(minutes: number) {262    setAutoLockMinutes(minutes);263    await sendMessage({264      type: "UPDATE_SETTINGS",265      payload: { autoLockMinutes: minutes },266    });267  }268269  async function applyBreachMonitoring(enabled: boolean) {270    setBreachMonitoring(enabled);271    await sendMessage({272      type: "UPDATE_SETTINGS",273      payload: { breachMonitoring: enabled },274    });275  }276277  onMount(async () => {278    // Resolve the active tab in parallel with the unlock/has-vault queries —279    // openVault()'s smart selection picks the entry matching currentTabDomain,280    // so it must be populated before openVault runs. Previously refreshCurrentTab281    // ran after openVault, leaving popups that booted already-unlocked falling282    // back to loadedEntries[0] instead of the domain match.283    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([284      sendMessage({ type: "IS_UNLOCKED" }),285      sendMessage({ type: "HAS_VAULT" }),286      refreshCurrentTab(),287      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),288    ]);289    const unlocked = Boolean(290      (unlockResponse as { ok: boolean; data?: boolean }).data291    );292    const vaultExists = Boolean(293      (vaultResponse as { ok: boolean; data?: boolean }).data294    );295    const shouldCelebrate = Boolean(296      (celebrationResponse as { ok: boolean; data?: boolean }).data297    );298    setHasVault(vaultExists);299    // Onboarding gate — show once on first install, never again. Existing300    // users (vaultExists) are auto-marked onboarded so they skip the flow301    // even on the very first popup open after this feature ships.302    try {303      const onboarded = await storageGet("peach_onboarded");304      const seen = onboarded === "true";305      if (vaultExists && !seen) {306        await storageSet("peach_onboarded", "true");307        setOnboarded(true);308      } else {309        setOnboarded(seen);310      }311    } catch {312      // storage unavailable — default to onboarded so we never block boot313      setOnboarded(true);314    }315    await Promise.all([restoreSettings(), refreshProStatus()]);316317    // Mark played before any animation so a crash mid-sequence never replays it318    if (shouldCelebrate) {319      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });320    }321322    // If the user created a vault but hasn't yet confirmed their recovery323    // words, route back to the recovery-words screen instead of opening the324    // entries view. The flag lives in chrome.storage.local so it survives325    // both popup close (SW suppresses lock-on-close) and full browser326    // restart (handleUnlock checks the same flag after a fresh password327    // unlock). Cleared when confirmation succeeds.328    let recoveryPending = false;329    try {330      const out = await chrome.storage.local?.get("peach_recovery_pending");331      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";332    } catch { /* best-effort */ }333334    // Native: closing the app before recovery-words confirmation means the335    // user didn't finish vault creation. Throw the partial vault away and336    // restart onboarding rather than asking them to unlock a vault they337    // never finished creating. Desktop keeps the existing "unlock to338    // resume" flow because closing the popup there is much more casual.339    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {340      try {341        await chrome.storage.local?.remove([342          "peach_vault_a",343          "peach_vault_b",344          "peach_recovery_pending",345          "peach_onboarded",346          "peach_vault_history",347        ]);348      } catch { /* best-effort */ }349      setHasVault(false);350      setOnboarded(false);351      setView("lock");352      setBootState("ready");353      document.getElementById("pre-lock")?.setAttribute("hidden", "true");354      return;355    }356357    if (recoveryPending && unlocked) {358      // forceRecoveryWords overrides LockView's hasVault gate so the359      // recovery surface renders even though the vault now exists.360      setForceRecoveryWords(true);361      setView("lock");362    } else if (unlocked && vaultExists) {363      await openVault(undefined, shouldCelebrate);364      if (shouldCelebrate) {365        setView("pro-celebration");366        window.setTimeout(() => setView("entry"), 2500);367      }368    } else if (shouldCelebrate) {369      setPendingCelebration(true);370    }371372    await refreshPendingPasskey();373374    // Track tab changes so smart sort stays current375    const handleTabActivated = () => { void refreshCurrentTab(); };376    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {377      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();378    };379    try {380      chrome.tabs.onActivated.addListener(handleTabActivated);381      chrome.tabs.onUpdated.addListener(handleTabUpdated);382      onCleanup(() => {383        chrome.tabs.onActivated.removeListener(handleTabActivated);384        chrome.tabs.onUpdated.removeListener(handleTabUpdated);385      });386    } catch {387      // tabs permission may not be available in all contexts388    }389390    setBootState("ready");391    document.getElementById("pre-lock")?.setAttribute("hidden", "true");392393    // Check for pending session-storage notices from the background.394    if (chrome.storage.session) {395      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as396        Record<string, { feature?: string } | undefined>;397      if (session.pendingProGate?.feature) {398        await chrome.storage.session.remove("pendingProGate");399        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);400        setSettingsInitialSection("license");401        setView("settings");402      } else if (session.pendingProNotice?.feature) {403        await chrome.storage.session.remove("pendingProNotice");404        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });405      }406    }407408    // Warm the lazy-module cache so the Suspense fallback never shows for409    // locally-bundled extension views. Without this, the first navigation to410    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which411    // covers the shell and absorbs clicks on the header.412    void Promise.all([413      import("./views/Settings").catch(() => {}),414      import("./views/Import").catch(() => {}),415      import("./views/Export").catch(() => {}),416      import("./views/Health").catch(() => {}),417      import("./views/TrashView").catch(() => {}),418    ]);419420    // Lock-on-close via a persistent port. sendMessage in pagehide is421    // unreliable — the popup context tears down before the message lands.422    // The SW's onConnect listener locks when this port disconnects.423    let popupPort: chrome.runtime.Port | null = null;424    try {425      popupPort = chrome.runtime.connect({ name: "popup" });426    } catch { /* extension context invalidated — ignore */ }427    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });428429    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only430    // reliable signal is appStateChange — setTimeout is killed when the OS431    // backgrounds the app. We measure elapsed background time on resume.432    if (isNativePlatform()) {433      let backgroundedAt: number | null = null;434435      const CapApp = nativePlugin<{436        addListener: (437          ev: string,438          cb: (s: { isActive: boolean }) => void,439        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };440      }>("App");441      if (CapApp?.addListener) {442        const sub = CapApp.addListener(443          "appStateChange",444          ({ isActive }: { isActive: boolean }) => {445            if (!isActive) {446              backgroundedAt = Date.now();447              return;448            }449            if (backgroundedAt !== null && autoLockMinutes() > 0) {450              const elapsed = Date.now() - backgroundedAt;451              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();452            }453            backgroundedAt = null;454          }455        );456        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.457        onCleanup(() => {458          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});459        });460      }461462      // L12/COR-011: foreground idle autolock. appStateChange only fires when463      // the OS backgrounds the app — if the user idles with the screen on,464      // chrome.alarms is no-op'd in Capacitor so the vault would stay open465      // indefinitely. Poll every 30s and lock if elapsed since last user466      // interaction exceeds autoLockMinutes.467      let lastUserActivityAt = Date.now();468      const bumpActivity = () => { lastUserActivityAt = Date.now(); };469      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;470      for (const ev of ACTIVITY_EVENTS) {471        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });472      }473      const idleLockInterval = setInterval(() => {474        const minutes = autoLockMinutes();475        if (!minutes || minutes <= 0) return;476        const elapsed = Date.now() - lastUserActivityAt;477        if (elapsed >= minutes * 60_000) {478          lastUserActivityAt = Date.now();479          handleHeaderLock();480        }481      }, 30_000);482      onCleanup(() => {483        clearInterval(idleLockInterval);484        for (const ev of ACTIVITY_EVENTS) {485          document.removeEventListener(ev, bumpActivity, { capture: true });486        }487      });488    }489490    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale491    // entries instead of waiting for the next GET_ENTRIES round-trip.492    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {493      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();494      if (msg?.type === "PRO_GATE_TRIGGERED") {495        setUpgradeHighlight(msg.payload?.feature ?? null);496        setSettingsInitialSection("license");497        setView("settings");498      }499    };500    chrome.runtime.onMessage.addListener(handleRuntimeMessage);501    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));502503    // Android hardware/gesture back. MainActivity fires peach:back; the popup504    // decides what "back" means per surface. Lock+no-vault is the common case505    // — return to onboarding rather than letting the OS dismiss the activity.506    const handlePeachBack = () => {507      // Notes mode captures back first508      if (showNotes()) {509        setShowNotes(false);510        setOpenNoteId(undefined);511        return;512      }513      const v = view();514      if (v === "lock" && !hasVault() && onboarded()) {515        setOnboarded(false);516        return;517      }518      if (v === "list") { setView("entry"); return; }519      if (v === "settings") {520        window.dispatchEvent(new Event("peach:settings-back"));521        return;522      }523      if (v === "import" || v === "export" || v === "add" || v === "health") {524        handleBack();525        return;526      }527      if (v === "chirp-sync") { setView("settings"); return; }528    };529    window.addEventListener("peach:back", handlePeachBack);530    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));531532    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that533    // peeks from the bottom (search bar handle visible) and drags up to fill534    // the screen. dragOffset is the LIVE finger offset during a drag, in px,535    // 0 when no drag in progress. The wrapper element computes transform =536    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.537    if (isNativePlatform()) {538      let touchStartY = 0;539      let touchStartX = 0;540      let lastY = 0;541      let lastT = 0;542      let dragging = false;543      let captured = false;544      const HORIZONTAL_TOLERANCE = 16;545      const ACTIVATION_DY = 8;546      const PEEK_PX = 60;547548      const onTouchStart = (e: TouchEvent) => {549        const t = e.touches[0];550        if (!t) return;551        const v = view();552        if (v !== "entry" && v !== "list") return;553        // Entry view: only intercept drags starting in the bottom 40%.554        // List view: intercept drags starting in the top 35% (the search/handle row).555        const inBand = v === "entry"556          ? t.clientY > window.innerHeight * 0.6557          : t.clientY < window.innerHeight * 0.35;558        if (!inBand) return;559        touchStartY = lastY = t.clientY;560        touchStartX = t.clientX;561        lastT = e.timeStamp;562        dragging = true;563        captured = false;564      };565566      const onTouchMove = (e: TouchEvent) => {567        if (!dragging) return;568        const t = e.touches[0];569        if (!t) return;570        const dy = t.clientY - touchStartY;571        const dx = Math.abs(t.clientX - touchStartX);572573        if (!captured) {574          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {575            // Looks like a horizontal swipe — release.576            dragging = false;577            return;578          }579          if (Math.abs(dy) < ACTIVATION_DY) return;580          captured = true;581        }582583        // Translate the sheet by dy from its rest (peek) position. Peek is584        // (viewport height - PEEK_PX). Open is 0.585        const v = view();586        const restClosed = window.innerHeight - PEEK_PX;587        const baseTranslate = v === "list" ? 0 : restClosed;588        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));589        setSheetTranslate(next);590        lastY = t.clientY;591        lastT = e.timeStamp;592      };593594      const onTouchEnd = (e: TouchEvent) => {595        if (!dragging) { return; }596        const t = e.changedTouches[0];597        const elapsed = Math.max(1, e.timeStamp - lastT);598        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms599        const wasCaptured = captured;600        dragging = false;601        captured = false;602        const v = view();603604        if (!wasCaptured) {605          // Tap in the peek strip while in entry view → open the vault list.606          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");607          setSheetTranslate(null);608          return;609        }610611        const restClosed = window.innerHeight - PEEK_PX;612        const current = sheetTranslate() ?? restClosed;613614        // Snap rules:615        //   - Strong upward velocity → open616        //   - Strong downward velocity → close617        //   - Otherwise snap to whichever rest is closer618        let nextOpen: boolean;619        if (velocity < -0.05) nextOpen = true;620        else if (velocity > 0.05) nextOpen = false;621        else nextOpen = current < restClosed * 0.5;622623        if (nextOpen && v !== "list") setView("list");624        if (!nextOpen && v !== "entry") setView("entry");625        // Release the live offset so CSS transition handles the snap.626        setSheetTranslate(null);627      };628629      document.addEventListener("touchstart", onTouchStart, { passive: true });630      document.addEventListener("touchmove",  onTouchMove,  { passive: true });631      document.addEventListener("touchend",   onTouchEnd,   { passive: true });632      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });633      onCleanup(() => {634        document.removeEventListener("touchstart", onTouchStart);635        document.removeEventListener("touchmove",  onTouchMove);636        document.removeEventListener("touchend",   onTouchEnd);637      });638    }639640    // Action handlers — keyed by ShortcutAction. The dispatcher below tests641    // each binding against the event and runs the matching handler. New642    // shortcuts only need an entry here; the binding is data, not code.643    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {644      copy_password: () => {645        const entry = selectedEntry();646        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });647      },648      copy_username: () => {649        const entry = selectedEntry();650        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });651      },652      copy_totp: () => {653        const entry = selectedEntry();654        if (!entry?.totp) return;655        try {656          const { code } = generateTOTP(entry.totp);657          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });658        } catch { /* invalid TOTP secret — silent */ }659      },660      new_entry: () => handleAdd(),661      edit_entry: () => {662        const entry = selectedEntry();663        // Passkey-only entries have nothing user-editable in the Add view; the664        // passkey credential itself is opaque. Skip the edit action for them.665        if (!entry || isPasskeyOnly(entry)) return;666        setEditEntry(entry);667        setView("add");668      },669      delete_entry: () => {670        if (selectedEntry()) void handleDelete();671      },672      lock_vault: () => { void handleHeaderLock(); },673      search: () => openList(),674      nav_prev: () => navigate(-1),675      nav_next: () => navigate(1),676      jump_vault: () => setView("entry"),677      jump_settings: () => setView("settings"),678      show_help: () => setShowShortcutsHelp(true),679    };680681    // Actions that are MEANINGFUL only on the entry-detail view. Outside682    // that scope the binding is dormant — pressing C while on Settings683    // does nothing rather than awkwardly copying from a now-stale entry.684    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([685      "copy_password", "copy_username", "copy_totp",686      "edit_entry", "delete_entry", "nav_prev", "nav_next",687    ]);688689    const handleGlobalKeydown = (e: KeyboardEvent) => {690      const v = view();691      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"692        || (e.target as HTMLElement)?.tagName === "TEXTAREA"693        || (e.target as HTMLElement)?.isContentEditable;694      const isPrintableSearchKey =695        e.key.length === 1 &&696        !e.ctrlKey &&697        !e.metaKey &&698        !e.altKey;699700      // No input during the pro celebration sequence701      if (v === "pro-celebration") return;702703      // Help dialog: Escape closes it; eat the keypress so it doesn't704      // also navigate away from the underlying view.705      if (showShortcutsHelp()) {706        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }707        return;708      }709710      // ── Escape — fixed binding (not user-customizable) ───────711      if (e.key === "Escape") {712        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }713        if (v === "list") { setView("entry"); return; }714        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }715        if (v === "chirp-sync") { setView("settings"); return; }716      }717718      // Bindings-driven dispatch. Single-key letter bindings without719      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is720      // inside an input, so users can type into search/forms normally.721      const bindings = shortcutBindings();722      for (const action of Object.keys(bindings) as ShortcutAction[]) {723        const binding = bindings[action];724        if (!matchKeybinding(e, binding)) continue;725        // Single-key letter bindings need the input-focus guard. Bindings726        // with any modifier are safe — Ctrl+L doesn't conflict with typing.727        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;728        if (!hasMod && binding.key.length === 1 && inInput) return;729        if (ENTRY_SCOPED.has(action) && v !== "entry") return;730        e.preventDefault();731        SHORTCUT_HANDLERS[action]?.();732        return;733      }734735      // Type-to-search: in entry view, any printable key not consumed by a736      // shortcut above primes the list search seed and opens the list.737      // Kept outside the bindings table because it's a behavior, not a738      // discrete action — every printable character can trigger it.739      if (v === "entry" && !inInput && isPrintableSearchKey) {740        e.preventDefault();741        primeListSearch(e.key);742        return;743      }744    };745    window.addEventListener("keydown", handleGlobalKeydown);746    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));747748    const handleStorageChanged = (749      changes: Record<string, chrome.storage.StorageChange>,750      areaName: string751    ) => {752      if (areaName !== "session") return;753      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {754        return;755      }756      void refreshPendingPasskey();757    };758    chrome.storage.onChanged.addListener(handleStorageChanged);759    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));760  });761762  async function refreshCurrentTab() {763    try {764      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });765      const url = tab?.url ?? tab?.pendingUrl ?? "";766      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");767      // Skip extension/internal URLs — adding chrome://, about:, or768      // chrome-extension:// to a vault entry is never what the user wants.769      const isWebUrl = /^https?:\/\//i.test(url);770      setCurrentTabUrl(isWebUrl ? url : "");771    } catch {772      setCurrentTabDomain("");773      setCurrentTabUrl("");774    }775  }776777  async function refreshPendingPasskey() {778    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });779    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);780  }781782  async function refreshProStatus() {783    const res = await sendMessage({ type: "GET_LICENSE" });784    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;785    setProStatus(Boolean(data?.valid && data?.plan === "pro"));786  }787788  async function restoreSettings() {789    const res = await sendMessage({ type: "GET_SETTINGS" });790    const s = (res as { ok: boolean; data?: any }).data ?? {};791    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {792      setAccentColor(s.accentColor as AccentColorName);793    }794    setTheme(s.theme === "light" ? "light" : "dark");795    if (s.textSize === "small" || s.textSize === "large") {796      setTextSize(s.textSize);797    } else {798      setTextSize("medium");799    }800    setReduceMotion(s.reduceMotion === true);801    setLockOnClose(s.lockOnClose !== false);802    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);803    setBreachMonitoring(s.breachMonitoring !== false);804    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);805    setShortcutBindings(getActiveBindings(s.shortcuts));806  }807808  async function applyTrashRetention(days: number) {809    setTrashRetentionDays(days);810    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });811  }812813  function primeListSearch(seed: string) {814    setListSearchSeed(seed);815    setListSearchSeedNonce((value) => value + 1);816    openList();817  }818819  // Returns null when it detected a dead service worker and triggered handleLock().820  // Callers that need to abort (e.g. openVault) check for null rather than relying821  // on view() state, which may already be "lock" during normal startup flows.822  async function loadEntries(): Promise<VaultEntry[] | null> {823    const response = await sendMessage({ type: "GET_ENTRIES" });824    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };825826    // If the service worker was killed and restarted (MV3 workers sleep), the827    // vault will be locked again — or the worker may not respond at all.828    // In either case, send the user to the lock screen rather than silently829    // showing an empty vault (which looks like data loss).830    if (!res.ok) {831      if (832        res.error === "vault_locked" ||833        res.error === "SERVICE_WORKER_UNAVAILABLE" ||834        (typeof res.error === "string" && res.error.includes("locked"))835      ) {836        handleLock();837        return null; // signal emergency lock to callers838      }839      return [];840    }841842    const loadedEntries = res.data ?? [];843    setEntries(loadedEntries);844845    const currentId = selectedEntry()?.id;846    if (currentId) {847      setSelectedEntry(848        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null849      );850    }851852    return loadedEntries;853  }854855  async function openVault(preferredEntryId?: string, skipViewSet = false) {856    // Purge expired trash entries on each vault open857    const retDays = trashRetentionDays();858    if (retDays > 0) {859      void sendMessage({860        type: "PURGE_EXPIRED_TRASH",861        payload: { retentionMs: retDays * 86_400_000 },862      });863    }864865    const loadedEntries = await loadEntries();866867    // null means loadEntries() triggered an emergency lock (service worker died).868    // Don't override it by setting view back to "entry" with an empty vault.869    if (loadedEntries === null) return;870871    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry872    let nextSelectedEntry: VaultEntry | null = null;873    if (preferredEntryId) {874      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;875    }876    if (!nextSelectedEntry) {877      const tabDomain = currentTabDomain();878      if (tabDomain) {879        nextSelectedEntry = loadedEntries.find((e) => {880          if (e.type === "login") {881            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;882            for (const extra of e.additionalUrls ?? []) {883              if ((extractDomain(extra) ?? "") === tabDomain) return true;884            }885            return false;886          }887          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;888          return false;889        }) ?? null;890      }891    }892    nextSelectedEntry ??= loadedEntries[0] ?? null;893894    setSelectedEntry(nextSelectedEntry);895    setEditEntry(undefined);896    setContentTransitioning(false);897    setContentPhase("enter");898    queueContentIdle();899    if (!skipViewSet) setView("entry");900  }901902  async function handleUnlock() {903    // If the user previously created a vault but hadn't yet confirmed their904    // recovery words (and the browser was closed before they could), the905    // peach_recovery_pending flag is still set in storage.local. Re-route906    // back to the recovery surface so they finish the confirmation step907    // before reaching the entries view — the words can be re-derived now908    // that the vault is unlocked again.909    let recoveryPending = false;910    try {911      const out = await chrome.storage.local?.get("peach_recovery_pending");912      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";913    } catch { /* best-effort */ }914    if (recoveryPending) {915      setForceRecoveryWords(true);916      setView("lock");917      triggerPipPulse();918      await restoreSettings();919      return;920    }921    setHasVault(true);922    triggerPipPulse();923    await restoreSettings();924    const celebrating = pendingCelebration();925    if (celebrating) {926      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });927      setPendingCelebration(false);928    }929    await openVault(undefined, celebrating);930    if (celebrating) {931      setView("pro-celebration");932      window.setTimeout(() => setView("entry"), 2500);933    }934  }935936  function handleSelectEntry(entry: VaultEntry) {937    if (entry.type === "note") {938      setOpenNoteId(entry.id);939      setShowNotes(true);940      return;941    }942    setSelectedEntry(entry);943    setContentTransitioning(false);944    setContentPhase("enter");945    queueContentIdle();946    setView("entry");947  }948949  function handleAdd() {950    setEditEntry(undefined);951    setView("add");952  }953954  async function handleDelete() {955    const entry = selectedEntry();956    if (!entry) return;957    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });958    const loadedEntries = await loadEntries() ?? [];959    setSelectedEntry(loadedEntries[0] ?? null);960    setView("entry");961  }962963  async function handleDeleteMany(ids: string[]) {964    for (const id of ids) {965      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });966    }967    const loadedEntries = await loadEntries() ?? [];968    // If the currently selected entry was among the deleted, move to first969    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);970    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);971  }972973  async function handleSave(savedEntry?: VaultEntry) {974    await openVault(savedEntry?.id);975  }976977  function handleBack() {978    setEditEntry(undefined);979    setView("entry");980  }981982  function handleLock() {983    clearCanarySuppressions();984    setEntries([]);985    setSelectedEntry(null);986    setEditEntry(undefined);987    setContentPhase("idle");988    setView("lock");989  }990991  function handleHeaderLock() {992    // Lock the UI immediately — do not wait for the service worker. If the SW993    // is dead or slow, the 5s sendMessage timeout would create a dead-click994    // window. The SW will lock on its next wake regardless.995    handleLock();996    void sendMessage({ type: "LOCK" });997  }998999  function navigate(dir: number) {1000    const allEntries = entries();1001    if (allEntries.length === 0) return;1002    const currentIndex = selectedIndex();1003    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1004    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1005    setSelectedEntry(allEntries[nextIndex]);1006    setContentPhase("enter");1007    queueContentIdle();1008  }10091010  function openList() {1011    setView("list");1012  }10131014  function openHealth() {1015    setEditEntry(undefined);1016    setView("health");1017  }10181019  function handleOpenFileImport() {1020    setRestoreView("file");1021  }10221023  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10241025  function handleFixEntry(entry: VaultEntry) {1026    // Passkey-only entries have no editable surface — drop into view mode1027    // instead of opening the Add editor.1028    if (isPasskeyOnly(entry)) {1029      setSelectedEntry(entry);1030      setView("entry");1031      return;1032    }1033    setEditEntry(entry);1034    setView("add");1035  }10361037  const isLockedView = () => view() === "lock";10381039  async function handleApprovePendingPasskey() {1040    const pending = pendingPasskey();1041    if (!pending) return;1042    if (pending.browser === "firefox" && pending.type === "create") {1043      // Firefox path: popup itself runs navigator.credentials.create. The1044      // background never approved/rejected anything — it just stashed1045      // intent. After the popup-driven flow resolves (success or cancel),1046      // clear the pending key so the popup doesn't re-show this on next open.1047      const { createFirefoxPasskey } = await import("./firefox-passkey");1048      const result = await createFirefoxPasskey(pending);1049      if (!result.ok) {1050        console.warn("Peach Firefox passkey create failed:", result.error);1051      }1052      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1053      setPendingPasskey(null);1054      void loadEntries();1055      window.close();1056      return;1057    }1058    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1059    window.close();1060  }10611062  async function handleDenyPendingPasskey() {1063    const pending = pendingPasskey();1064    if (!pending) return;1065    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1066    window.close();1067  }10681069  function queueContentIdle(after?: () => void) {1070    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1071    contentPhaseTimer = window.setTimeout(() => {1072      setContentPhase("idle");1073      after?.();1074    }, ENTRY_TRANSITION_SETTLE_MS);1075  }10761077  return (1078    <div class="popup-root peach-theme">1079      <Show when={bootState() === "ready"}>1080        <Show1081          when={!pendingPasskey()}1082          fallback={1083            <PasskeyApprovalView1084              type={pendingPasskey()!.type}1085              rpName={pendingPasskey()!.rpName}1086              rpId={pendingPasskey()!.rpId}1087              userName={pendingPasskey()!.userName}1088              userDisplayName={pendingPasskey()!.userDisplayName}1089              onApprove={handleApprovePendingPasskey}1090              onDeny={handleDenyPendingPasskey}1091            />1092          }1093        >1094          <Show1095            when={!isLockedView()}1096            fallback={1097              <Show1098                when={onboarded() || hasVault()}1099                fallback={1100                  <Onboarding1101                    onComplete={() => { setOnboarded(true); }}1102                  />1103                }1104              >1105                <LockView1106                  hasVault={hasVault()}1107                  ready={bootState() === "ready"}1108                  isPro={proStatus()}1109                  forceRecoveryWords={forceRecoveryWords()}1110                  onUnlock={() => {1111                    // RecoveryWordDisplay clears the storage flag before1112                    // calling onDone, so handleUnlock will see no pending1113                    // confirmation and proceed through the normal path.1114                    if (forceRecoveryWords()) setForceRecoveryWords(false);1115                    return handleUnlock();1116                  }}1117                  onBackToOnboarding={1118                    !hasVault()1119                      ? () => setOnboarded(false)1120                      : undefined1121                  }1122                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1123                />1124              </Show>1125            }1126          >1127            <Show1128              when={view() !== "pro-celebration"}1129              fallback={<ProCelebration />}1130            >1131            <section1132              id="hd-shell"1133              class="peach-shell peach-theme"1134              data-surface="extension"1135            >1136            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1137              <PeachWordmark unlocked />1138              <div class="peach-chrome-actions">1139                <button1140                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1141                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1142                  aria-label="Notes"1143                  title="Notes"1144                >1145                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1146                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1147                    <line x1="4" y1="5" x2="10" y2="5" />1148                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1149                    <line x1="4" y1="10" x2="7" y2="10" />1150                  </svg>1151                </button>1152                <button1153                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1154                  onClick={() => setView("settings")}1155                  aria-label="Settings"1156                >1157                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1158                    <path1159                      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"1160                      stroke="currentColor"1161                      stroke-width="0.9"1162                    />1163                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1164                  </svg>1165                </button>1166                <button1167                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1168                  onClick={handleAdd}1169                  aria-label="New entry"1170                >1171                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1172                    <path d="M5.5 1v9M1 5.5h9" />1173                  </svg>1174                </button>1175                <button1176                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1177                  onClick={() => void handleHeaderLock()}1178                  aria-label="Lock vault"1179                >1180                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1181                    <path1182                      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"1183                      stroke="currentColor"1184                      stroke-width="1"1185                      stroke-linecap="round"1186                    />1187                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1188                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1189                  </svg>1190                </button>1191              </div>1192            </header>11931194            <Show when={pendingProNotice() !== null}>1195              <div class="peach-pro-notice-banner">1196                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1197                <button1198                  class="peach-pro-notice-link"1199                  onClick={() => {1200                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1201                    setSettingsInitialSection("license");1202                    setView("settings");1203                    setPendingProNotice(null);1204                  }}1205                >1206                  Learn more →1207                </button>1208                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1209              </div>1210            </Show>12111212            <div class="peach-shell-body">1213              <div class="peach-shell-veil"></div>1214              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1215                <EntryView1216                  entry={selectedEntry()}1217                  currentTabUrl={currentTabUrl()}1218                  entries={entries()}1219                  isPro={proStatus()}1220                  onDelete={handleDelete}1221                  onFieldSaved={() => void loadEntries()}1222                  onEscape={() => { setView("list"); }}1223                  onProGate={(feature) => {1224                    setUpgradeHighlight(feature);1225                    setSettingsInitialSection("license");1226                    setView("settings");1227                  }}1228                />1229              </div>12301231              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1232                <div class="peach-search-bar">1233                  <span class="peach-search-icon">1234                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1235                      <circle cx="5.5" cy="5.5" r="3.75" />1236                      <path d="M8.75 8.75L11.5 11.5" />1237                    </svg>1238                  </span>1239                  <input1240                    class="peach-search-input"1241                    placeholder="search vault..."1242                    autocomplete="off"1243                    aria-label="Search vault entries"1244                    onClick={openList}1245                    onFocus={openList}1246                    readOnly1247                  />1248                  <div class="peach-search-meta">1249                    <span class="peach-search-counter">1250                      {entries().length > 01251                        ? `${selectedIndex() + 1} / ${entries().length}`1252                        : "0 entries"}1253                    </span>1254                    <span class="peach-divider"></span>1255                    <button1256                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1257                      onClick={() => navigate(-1)}1258                      aria-label="Previous entry"1259                      disabled={entries().length === 0}1260                    >1261                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1262                        <path d="M5 1L1 5.5L5 10" />1263                      </svg>1264                    </button>1265                    <button1266                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1267                      onClick={() => navigate(1)}1268                      aria-label="Next entry"1269                      disabled={entries().length === 0}1270                    >1271                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1272                        <path d="M1 1L5 5.5L1 10" />1273                      </svg>1274                    </button>1275                  </div>1276                </div>1277              </section>1278            </div>12791280            {/* Desktop: shown on demand via Show. Native sheet is rendered1281                via Portal below at the document root so its position:fixed1282                isn't trapped by .peach-shell's transform-based animations. */}1283            <Show when={!isNativePlatform() && view() === "list"}>1284              <VaultView1285                entries={entries()}1286                selectedEntryId={selectedEntry()?.id}1287                currentTabDomain={currentTabDomain()}1288                sortOrder={sortOrder()}1289                searchSeed={listSearchSeed()}1290                searchSeedNonce={listSearchSeedNonce()}1291                onSelectEntry={handleSelectEntry}1292                onSortOrderChange={setSortOrder}1293                onAdd={handleAdd}1294                onClose={() => setView("entry")}1295                onOpenTrash={() => setView("trash")}1296                onDeleteMany={handleDeleteMany}1297              />1298            </Show>1299            <Show when={isNativePlatform() && hasVault()}>1300              <Portal>1301                <div1302                  class="peach-vault-sheet"1303                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1304                  style={(() => {1305                    const live = sheetTranslate();1306                    if (live === null) return undefined;1307                    return { transform: `translateY(${live}px)` };1308                  })()}1309                >1310                  <VaultView1311                    entries={entries()}1312                    selectedEntryId={selectedEntry()?.id}1313                    currentTabDomain={currentTabDomain()}1314                    sortOrder={sortOrder()}1315                    searchSeed={listSearchSeed()}1316                    searchSeedNonce={listSearchSeedNonce()}1317                    isNative={true}1318                    onSelectEntry={handleSelectEntry}1319                    onSortOrderChange={setSortOrder}1320                    onAdd={handleAdd}1321                    onClose={() => setView("entry")}1322                    onOpenTrash={() => setView("trash")}1323                    onDeleteMany={handleDeleteMany}1324                  />1325                </div>1326              </Portal>1327            </Show>1328            <Show when={view() === "settings" || settingsExiting()}>1329              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1330                <SettingsView1331                  entriesCount={entries().length}1332                  breachMonitoring={breachMonitoring()}1333                  lockOnClose={lockOnClose()}1334                  autoLockMinutes={autoLockMinutes()}1335                  trashRetentionDays={trashRetentionDays()}1336                  theme={theme()}1337                  accentColor={accentColor()}1338                  textSize={textSize()}1339                  reduceMotion={reduceMotion()}1340                  isPro={proStatus()}1341                  initialSection={settingsInitialSection()}1342                  upgradeHighlight={upgradeHighlight()}1343                  isExiting={settingsExiting()}1344                  onBreachMonitoringChange={applyBreachMonitoring}1345                  onLockOnCloseChange={applyLockOnClose}1346                  onAutoLockMinutesChange={applyAutoLockMinutes}1347                  onTrashRetentionChange={applyTrashRetention}1348                  onThemeChange={applyTheme}1349                  onAccentChange={applyAccentColor}1350                  onTextSizeChange={applyTextSize}1351                  onReduceMotionChange={applyReduceMotion}1352                  shortcuts={shortcutBindings()}1353                  onShortcutsChange={applyShortcuts}1354                  onLicenseChange={async () => {1355                    // After activation/deactivation: refresh Pro status,1356                    // re-load entries (defensive — signal state can drift if1357                    // the SW briefly restarts during the verify+save round-trip),1358                    // and replay the Pro celebration if this is the first time1359                    // a valid Pro license is seen on this device.1360                    await refreshProStatus();1361                    void loadEntries();1362                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1363                    if ((should as { ok: boolean; data?: boolean }).data === true) {1364                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1365                      setView("pro-celebration");1366                      window.setTimeout(() => setView("settings"), 2500);1367                    }1368                  }}1369                  onBack={() => {1370                    setSettingsExiting(true);1371                    window.setTimeout(() => {1372                      setSettingsExiting(false);1373                      setSettingsInitialSection(null);1374                      setUpgradeHighlight(null);1375                      handleBack();1376                    }, 200);1377                  }}1378                  onImport={() => setView("import")}1379                  onExport={() => setView("export")}1380                  onBreachCheckDone={loadEntries}1381                  onOpenHealth={openHealth}1382                  onOpenSyncPairing={() => setView("chirp-sync")}1383                  onOpenFileImport={handleOpenFileImport}1384                  onOpenPanic={() => setView("panic")}1385                  onOpenCodexGenerate={() => setView("codex-generate")}1386                  onOpenCodexRestore={() => setView("codex-restore")}1387                  onProGate={(feature) => {1388                    setUpgradeHighlight(feature);1389                    setSettingsInitialSection("license");1390                  }}1391                />1392              </Suspense>1393            </Show>1394            <Show when={view() === "codex-generate"}>1395              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1396                <CodexGenerateView1397                  isPro={proStatus()}1398                  onBack={() => setView("settings")}1399                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1400                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1401                  onVaultLocked={() => handleLock()}1402                />1403              </Suspense>1404            </Show>1405            <Show when={view() === "codex-restore"}>1406              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1407                <CodexRestoreView1408                  onBack={() => setView("lock")}1409                  onRestoreSuccess={async () => {1410                    // After restore the vault is unlocked; refresh entries1411                    // and route to the main vault list. handleUnlock is the1412                    // canonical post-unlock setup path.1413                    await handleUnlock();1414                  }}1415                />1416              </Suspense>1417            </Show>1418            <Show when={view() === "chirp-sync"}>1419              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1420                <ChirpSyncView1421                  isPro={proStatus()}1422                  onBack={() => setView("settings")}1423                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1424                />1425              </Suspense>1426            </Show>1427            <Show when={view() === "add"}>1428              <AddView1429                entry={editEntry()}1430                entries={entries()}1431                onBack={handleBack}1432                onSave={handleSave}1433              />1434            </Show>1435            <Show when={view() === "import"}>1436              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1437                <ImportView onBack={handleBack} onImport={handleSave} />1438              </Suspense>1439            </Show>1440            <Show when={view() === "export"}>1441              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1442                <ExportView1443                  onBack={() => {1444                    if (returnToPanic()) {1445                      setReturnToPanic(false);1446                      setView("panic");1447                    } else {1448                      handleBack();1449                    }1450                  }}1451                />1452              </Suspense>1453            </Show>1454            <Show when={view() === "panic"}>1455              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1456                <PanicView1457                  onCancel={() => setView("settings")}1458                  onOpenExport={() => {1459                    setReturnToPanic(true);1460                    setView("export");1461                  }}1462                  onDestroyed={async () => {1463                    clearCanarySuppressions();1464                    setEntries([]);1465                    setSelectedEntry(null);1466                    setEditEntry(undefined);1467                    setHasVault(false);1468                    setOnboarded(false);1469                    setProStatus(false);1470                    setPendingPasskey(null);1471                    setUpgradeHighlight(null);1472                    setSettingsInitialSection(null);1473                    setPendingProNotice(null);1474                    setPendingCelebration(false);1475                    setReturnToPanic(false);1476                    setContentPhase("idle");1477                    setView("lock");1478                  }}1479                />1480              </Suspense>1481            </Show>1482            <Show when={view() === "health"}>1483              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1484                <HealthView1485                  entries={entries()}1486                  isPro={proStatus()}1487                  onFixEntry={handleFixEntry}1488                  onBack={() => setView("settings")}1489                  onRefresh={loadEntries}1490                />1491              </Suspense>1492            </Show>1493            <Show when={view() === "trash"}>1494              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1495                <TrashView1496                  onBack={() => setView("list")}1497                  onRestored={() => void loadEntries()}1498                />1499              </Suspense>1500            </Show>1501            <Show when={showNotes()}>1502              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1503                <NotesMode1504                  notes={entries().filter((e) => e.type === "note")}1505                  initialNoteId={openNoteId()}1506                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1507                  onNoteListChanged={() => void loadEntries()}1508                />1509              </div>1510            </Show>1511            <Show when={restoreView() === "file"}>1512              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1513                <ImportView1514                  mode="onboarding"1515                  replacesExistingVault={true}1516                  onBack={() => setRestoreView(null)}1517                  onImport={async () => {1518                    setRestoreView(null);1519                    await handleUnlock();1520                  }}1521                />1522              </Suspense>1523            </Show>1524            </section>1525            </Show>1526          </Show>1527        </Show>1528      </Show>1529      <Show when={showShortcutsHelp()}>1530        <ShortcutsHelpOverlay1531          bindings={shortcutBindings()}1532          onClose={() => setShowShortcutsHelp(false)}1533        />1534      </Show>1535    </div>1536  );1537}15381539function ShortcutsHelpOverlay(props: {1540  bindings: Record<ShortcutAction, Keybinding>;1541  onClose: () => void;1542}) {1543  return (1544    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1545      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1546        <div class="peach-shortcuts-help-head">1547          <h3>Keyboard shortcuts</h3>1548          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1549        </div>1550        <div class="peach-shortcuts-help-body">1551          <p class="peach-settings-sub-label">ENTRY VIEW</p>1552          <ul>1553            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1554              <li>1555                <span>{d.label}</span>1556                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1557              </li>1558            ))}1559          </ul>1560          <p class="peach-settings-sub-label">ANYWHERE</p>1561          <ul>1562            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1563              <li>1564                <span>{d.label}</span>1565                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1566              </li>1567            ))}1568          </ul>1569        </div>1570      </div>1571    </div>1572  );1573}