App.tsx

64.4 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 [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");155  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);156  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");157  const [listSearchSeed, setListSearchSeed] = createSignal("");158  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);159  const [pendingCelebration, setPendingCelebration] = createSignal(false);160  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);161  // True while Panic Step 1 has bounced the user out to Export. When Export's162  // onBack fires we return to Panic instead of Settings so the user keeps the163  // destruction context they came from.164  const [returnToPanic, setReturnToPanic] = createSignal(false);165  const [settingsExiting, setSettingsExiting] = createSignal(false);166  const [showNotes, setShowNotes] = createSignal(false);167  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);168  // Set on popup boot when peach_recovery_pending flag is found in session169  // storage — instructs LockView to skip the unlock UI and open the recovery170  // words confirmation surface instead. Cleared via handleUnlock once the171  // user has typed the 3 confirmation words.172  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);173174  let contentPhaseTimer: number | undefined;175176  function applyAccent(name: AccentColorName) {177    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;178    const hex = color.hex;179    document.documentElement.style.setProperty("--peach-accent", hex);180    // Ambient surface variables — derived from the accent so surfaces shift181    // subtly toward the accent hue rather than staying fixed warm-brown.182    document.documentElement.style.setProperty("--peach-glow", hex + "2A");183    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");184    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");185  }186187  createEffect(() => {188    applyAccent(accentColor());189  });190191  createEffect(() => {192    document.documentElement.classList.toggle("light", theme() === "light");193    document.body.classList.toggle("light", theme() === "light");194  });195196  createEffect(() => {197    document.documentElement.setAttribute("data-text-size", textSize());198  });199200  createEffect(() => {201    if (reduceMotion()) {202      document.documentElement.setAttribute("data-motion", "reduce");203    } else {204      document.documentElement.removeAttribute("data-motion");205    }206  });207208  const selectedIndex = createMemo(() => {209    const currentId = selectedEntry()?.id;210    if (!currentId) return entries().length > 0 ? 0 : -1;211    return entries().findIndex((entry) => entry.id === currentId);212  });213214  async function applyAccentColor(name: AccentColorName) {215    applyAccent(name);216    setAccentColor(name);217    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });218  }219220  async function applyTheme(t: "dark" | "light") {221    setTheme(t);222    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });223  }224225  async function applyTextSize(size: "small" | "medium" | "large") {226    setTextSize(size);227    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });228  }229230  async function applyReduceMotion(enabled: boolean) {231    setReduceMotion(enabled);232    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });233  }234235  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload236  // small and lets future default updates land for actions the user hasn't237  // touched. Settings sends us the full active map; we filter and store.238  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {239    setShortcutBindings(active);240    const overrides: Record<string, Keybinding> = {};241    for (const action of Object.keys(active) as ShortcutAction[]) {242      const a = active[action];243      const d = DEFAULT_BINDINGS[action];244      const same = a.key === d.key245        && Boolean(a.ctrl)  === Boolean(d.ctrl)246        && Boolean(a.meta)  === Boolean(d.meta)247        && Boolean(a.shift) === Boolean(d.shift)248        && Boolean(a.alt)   === Boolean(d.alt);249      if (!same) overrides[action] = a;250    }251    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });252  }253254  async function applyLockOnClose(enabled: boolean) {255    setLockOnClose(enabled);256    await sendMessage({257      type: "UPDATE_SETTINGS",258      payload: { lockOnClose: enabled },259    });260  }261262  async function applyAutoLockMinutes(minutes: number) {263    setAutoLockMinutes(minutes);264    await sendMessage({265      type: "UPDATE_SETTINGS",266      payload: { autoLockMinutes: minutes },267    });268  }269270  async function applyBreachMonitoring(enabled: boolean) {271    setBreachMonitoring(enabled);272    await sendMessage({273      type: "UPDATE_SETTINGS",274      payload: { breachMonitoring: enabled },275    });276  }277278  onMount(async () => {279    // Resolve the active tab in parallel with the unlock/has-vault queries —280    // openVault()'s smart selection picks the entry matching currentTabDomain,281    // so it must be populated before openVault runs. Previously refreshCurrentTab282    // ran after openVault, leaving popups that booted already-unlocked falling283    // back to loadedEntries[0] instead of the domain match.284    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([285      sendMessage({ type: "IS_UNLOCKED" }),286      sendMessage({ type: "HAS_VAULT" }),287      refreshCurrentTab(),288      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),289    ]);290    const unlocked = Boolean(291      (unlockResponse as { ok: boolean; data?: boolean }).data292    );293    const vaultExists = Boolean(294      (vaultResponse as { ok: boolean; data?: boolean }).data295    );296    const shouldCelebrate = Boolean(297      (celebrationResponse as { ok: boolean; data?: boolean }).data298    );299    setHasVault(vaultExists);300    // Onboarding gate — show once on first install, never again. Existing301    // users (vaultExists) are auto-marked onboarded so they skip the flow302    // even on the very first popup open after this feature ships.303    try {304      const onboarded = await storageGet("peach_onboarded");305      const seen = onboarded === "true";306      if (vaultExists && !seen) {307        await storageSet("peach_onboarded", "true");308        setOnboarded(true);309      } else {310        setOnboarded(seen);311      }312    } catch {313      // storage unavailable — default to onboarded so we never block boot314      setOnboarded(true);315    }316    await Promise.all([restoreSettings(), refreshProStatus()]);317318    // Mark played before any animation so a crash mid-sequence never replays it319    if (shouldCelebrate) {320      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });321    }322323    // If the user created a vault but hasn't yet confirmed their recovery324    // words, route back to the recovery-words screen instead of opening the325    // entries view. The flag lives in chrome.storage.local so it survives326    // both popup close (SW suppresses lock-on-close) and full browser327    // restart (handleUnlock checks the same flag after a fresh password328    // unlock). Cleared when confirmation succeeds.329    let recoveryPending = false;330    try {331      const out = await chrome.storage.local?.get("peach_recovery_pending");332      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";333    } catch { /* best-effort */ }334335    // Native: closing the app before recovery-words confirmation means the336    // user didn't finish vault creation. Throw the partial vault away and337    // restart onboarding rather than asking them to unlock a vault they338    // never finished creating. Desktop keeps the existing "unlock to339    // resume" flow because closing the popup there is much more casual.340    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {341      try {342        await chrome.storage.local?.remove([343          "peach_vault_a",344          "peach_vault_b",345          "peach_recovery_pending",346          "peach_onboarded",347          "peach_vault_history",348        ]);349      } catch { /* best-effort */ }350      setHasVault(false);351      setOnboarded(false);352      setView("lock");353      setBootState("ready");354      document.getElementById("pre-lock")?.setAttribute("hidden", "true");355      return;356    }357358    if (recoveryPending && unlocked) {359      // forceRecoveryWords overrides LockView's hasVault gate so the360      // recovery surface renders even though the vault now exists.361      setForceRecoveryWords(true);362      setView("lock");363    } else if (unlocked && vaultExists) {364      await openVault(undefined, shouldCelebrate);365      if (shouldCelebrate) {366        setView("pro-celebration");367        window.setTimeout(() => setView("entry"), 2500);368      }369    } else if (shouldCelebrate) {370      setPendingCelebration(true);371    }372373    await refreshPendingPasskey();374375    // Track tab changes so smart sort stays current376    const handleTabActivated = () => { void refreshCurrentTab(); };377    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {378      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();379    };380    try {381      chrome.tabs.onActivated.addListener(handleTabActivated);382      chrome.tabs.onUpdated.addListener(handleTabUpdated);383      onCleanup(() => {384        chrome.tabs.onActivated.removeListener(handleTabActivated);385        chrome.tabs.onUpdated.removeListener(handleTabUpdated);386      });387    } catch {388      // tabs permission may not be available in all contexts389    }390391    setBootState("ready");392    document.getElementById("pre-lock")?.setAttribute("hidden", "true");393394    // Check for pending session-storage notices from the background.395    if (chrome.storage.session) {396      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as397        Record<string, { feature?: string } | undefined>;398      if (session.pendingProGate?.feature) {399        await chrome.storage.session.remove("pendingProGate");400        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);401        setSettingsInitialSection("license");402        setView("settings");403      } else if (session.pendingProNotice?.feature) {404        await chrome.storage.session.remove("pendingProNotice");405        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });406      }407    }408409    // Warm the lazy-module cache so the Suspense fallback never shows for410    // locally-bundled extension views. Without this, the first navigation to411    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which412    // covers the shell and absorbs clicks on the header.413    void Promise.all([414      import("./views/Settings").catch(() => {}),415      import("./views/Import").catch(() => {}),416      import("./views/Export").catch(() => {}),417      import("./views/Health").catch(() => {}),418      import("./views/TrashView").catch(() => {}),419    ]);420421    // Lock-on-close via a persistent port. sendMessage in pagehide is422    // unreliable — the popup context tears down before the message lands.423    // The SW's onConnect listener locks when this port disconnects.424    let popupPort: chrome.runtime.Port | null = null;425    try {426      popupPort = chrome.runtime.connect({ name: "popup" });427    } catch { /* extension context invalidated — ignore */ }428    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });429430    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only431    // reliable signal is appStateChange — setTimeout is killed when the OS432    // backgrounds the app. We measure elapsed background time on resume.433    if (isNativePlatform()) {434      let backgroundedAt: number | null = null;435436      const CapApp = nativePlugin<{437        addListener: (438          ev: string,439          cb: (s: { isActive: boolean }) => void,440        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };441      }>("App");442      if (CapApp?.addListener) {443        const sub = CapApp.addListener(444          "appStateChange",445          ({ isActive }: { isActive: boolean }) => {446            if (!isActive) {447              backgroundedAt = Date.now();448              return;449            }450            if (backgroundedAt !== null && autoLockMinutes() > 0) {451              const elapsed = Date.now() - backgroundedAt;452              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();453            }454            backgroundedAt = null;455          }456        );457        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.458        onCleanup(() => {459          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});460        });461      }462463      // L12/COR-011: foreground idle autolock. appStateChange only fires when464      // the OS backgrounds the app — if the user idles with the screen on,465      // chrome.alarms is no-op'd in Capacitor so the vault would stay open466      // indefinitely. Poll every 30s and lock if elapsed since last user467      // interaction exceeds autoLockMinutes.468      let lastUserActivityAt = Date.now();469      const bumpActivity = () => { lastUserActivityAt = Date.now(); };470      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;471      for (const ev of ACTIVITY_EVENTS) {472        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });473      }474      const idleLockInterval = setInterval(() => {475        const minutes = autoLockMinutes();476        if (!minutes || minutes <= 0) return;477        const elapsed = Date.now() - lastUserActivityAt;478        if (elapsed >= minutes * 60_000) {479          lastUserActivityAt = Date.now();480          handleHeaderLock();481        }482      }, 30_000);483      onCleanup(() => {484        clearInterval(idleLockInterval);485        for (const ev of ACTIVITY_EVENTS) {486          document.removeEventListener(ev, bumpActivity, { capture: true });487        }488      });489    }490491    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale492    // entries instead of waiting for the next GET_ENTRIES round-trip.493    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {494      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();495      if (msg?.type === "PRO_GATE_TRIGGERED") {496        setUpgradeHighlight(msg.payload?.feature ?? null);497        setSettingsInitialSection("license");498        setView("settings");499      }500    };501    chrome.runtime.onMessage.addListener(handleRuntimeMessage);502    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));503504    // Android hardware/gesture back. MainActivity fires peach:back; the popup505    // decides what "back" means per surface. Lock+no-vault is the common case506    // — return to onboarding rather than letting the OS dismiss the activity.507    const handlePeachBack = () => {508      // Notes mode captures back first509      if (showNotes()) {510        setShowNotes(false);511        setOpenNoteId(undefined);512        return;513      }514      const v = view();515      if (v === "lock" && !hasVault() && onboarded()) {516        setOnboarded(false);517        return;518      }519      if (v === "list") { setView("entry"); return; }520      if (v === "settings") {521        window.dispatchEvent(new Event("peach:settings-back"));522        return;523      }524      if (v === "import" || v === "export" || v === "add" || v === "health") {525        handleBack();526        return;527      }528      if (v === "chirp-sync") { setView("settings"); return; }529    };530    window.addEventListener("peach:back", handlePeachBack);531    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));532533    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that534    // peeks from the bottom (search bar handle visible) and drags up to fill535    // the screen. dragOffset is the LIVE finger offset during a drag, in px,536    // 0 when no drag in progress. The wrapper element computes transform =537    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.538    if (isNativePlatform()) {539      let touchStartY = 0;540      let touchStartX = 0;541      let lastY = 0;542      let lastT = 0;543      let dragging = false;544      let captured = false;545      const HORIZONTAL_TOLERANCE = 16;546      const ACTIVATION_DY = 8;547      const PEEK_PX = 60;548549      const onTouchStart = (e: TouchEvent) => {550        const t = e.touches[0];551        if (!t) return;552        const v = view();553        if (v !== "entry" && v !== "list") return;554        // Entry view: only intercept drags starting in the bottom 40%.555        // List view: intercept drags starting in the top 35% (the search/handle row).556        const inBand = v === "entry"557          ? t.clientY > window.innerHeight * 0.6558          : t.clientY < window.innerHeight * 0.35;559        if (!inBand) return;560        touchStartY = lastY = t.clientY;561        touchStartX = t.clientX;562        lastT = e.timeStamp;563        dragging = true;564        captured = false;565      };566567      const onTouchMove = (e: TouchEvent) => {568        if (!dragging) return;569        const t = e.touches[0];570        if (!t) return;571        const dy = t.clientY - touchStartY;572        const dx = Math.abs(t.clientX - touchStartX);573574        if (!captured) {575          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {576            // Looks like a horizontal swipe — release.577            dragging = false;578            return;579          }580          if (Math.abs(dy) < ACTIVATION_DY) return;581          captured = true;582        }583584        // Translate the sheet by dy from its rest (peek) position. Peek is585        // (viewport height - PEEK_PX). Open is 0.586        const v = view();587        const restClosed = window.innerHeight - PEEK_PX;588        const baseTranslate = v === "list" ? 0 : restClosed;589        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));590        setSheetTranslate(next);591        lastY = t.clientY;592        lastT = e.timeStamp;593      };594595      const onTouchEnd = (e: TouchEvent) => {596        if (!dragging) { return; }597        const t = e.changedTouches[0];598        const elapsed = Math.max(1, e.timeStamp - lastT);599        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms600        const wasCaptured = captured;601        dragging = false;602        captured = false;603        const v = view();604605        if (!wasCaptured) {606          // Tap in the peek strip while in entry view → open the vault list.607          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");608          setSheetTranslate(null);609          return;610        }611612        const restClosed = window.innerHeight - PEEK_PX;613        const current = sheetTranslate() ?? restClosed;614615        // Snap rules:616        //   - Strong upward velocity → open617        //   - Strong downward velocity → close618        //   - Otherwise snap to whichever rest is closer619        let nextOpen: boolean;620        if (velocity < -0.05) nextOpen = true;621        else if (velocity > 0.05) nextOpen = false;622        else nextOpen = current < restClosed * 0.5;623624        if (nextOpen && v !== "list") setView("list");625        if (!nextOpen && v !== "entry") setView("entry");626        // Release the live offset so CSS transition handles the snap.627        setSheetTranslate(null);628      };629630      document.addEventListener("touchstart", onTouchStart, { passive: true });631      document.addEventListener("touchmove",  onTouchMove,  { passive: true });632      document.addEventListener("touchend",   onTouchEnd,   { passive: true });633      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });634      onCleanup(() => {635        document.removeEventListener("touchstart", onTouchStart);636        document.removeEventListener("touchmove",  onTouchMove);637        document.removeEventListener("touchend",   onTouchEnd);638      });639    }640641    // Action handlers — keyed by ShortcutAction. The dispatcher below tests642    // each binding against the event and runs the matching handler. New643    // shortcuts only need an entry here; the binding is data, not code.644    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {645      copy_password: () => {646        const entry = selectedEntry();647        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });648      },649      copy_username: () => {650        const entry = selectedEntry();651        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });652      },653      copy_totp: () => {654        const entry = selectedEntry();655        if (!entry?.totp) return;656        try {657          const { code } = generateTOTP(entry.totp);658          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });659        } catch { /* invalid TOTP secret — silent */ }660      },661      new_entry: () => handleAdd(),662      edit_entry: () => {663        const entry = selectedEntry();664        // Passkey-only entries have nothing user-editable in the Add view; the665        // passkey credential itself is opaque. Skip the edit action for them.666        if (!entry || isPasskeyOnly(entry)) return;667        setEditEntry(entry);668        setView("add");669      },670      delete_entry: () => {671        if (selectedEntry()) void handleDelete();672      },673      lock_vault: () => { void handleHeaderLock(); },674      search: () => openList(),675      nav_prev: () => navigate(-1),676      nav_next: () => navigate(1),677      jump_vault: () => setView("entry"),678      jump_settings: () => setView("settings"),679      show_help: () => setShowShortcutsHelp(true),680    };681682    // Actions that are MEANINGFUL only on the entry-detail view. Outside683    // that scope the binding is dormant — pressing C while on Settings684    // does nothing rather than awkwardly copying from a now-stale entry.685    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([686      "copy_password", "copy_username", "copy_totp",687      "edit_entry", "delete_entry", "nav_prev", "nav_next",688    ]);689690    const handleGlobalKeydown = (e: KeyboardEvent) => {691      const v = view();692      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"693        || (e.target as HTMLElement)?.tagName === "TEXTAREA"694        || (e.target as HTMLElement)?.isContentEditable;695      const isPrintableSearchKey =696        e.key.length === 1 &&697        !e.ctrlKey &&698        !e.metaKey &&699        !e.altKey;700701      // No input during the pro celebration sequence702      if (v === "pro-celebration") return;703704      // Help dialog: Escape closes it; eat the keypress so it doesn't705      // also navigate away from the underlying view.706      if (showShortcutsHelp()) {707        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }708        return;709      }710711      // ── Escape — fixed binding (not user-customizable) ───────712      if (e.key === "Escape") {713        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }714        if (v === "list") { setView("entry"); return; }715        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }716        if (v === "chirp-sync") { setView("settings"); return; }717      }718719      // Bindings-driven dispatch. Single-key letter bindings without720      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is721      // inside an input, so users can type into search/forms normally.722      const bindings = shortcutBindings();723      for (const action of Object.keys(bindings) as ShortcutAction[]) {724        const binding = bindings[action];725        if (!matchKeybinding(e, binding)) continue;726        // Single-key letter bindings need the input-focus guard. Bindings727        // with any modifier are safe — Ctrl+L doesn't conflict with typing.728        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;729        if (!hasMod && binding.key.length === 1 && inInput) return;730        if (ENTRY_SCOPED.has(action) && v !== "entry") return;731        e.preventDefault();732        SHORTCUT_HANDLERS[action]?.();733        return;734      }735736      // Type-to-search: in entry view, any printable key not consumed by a737      // shortcut above primes the list search seed and opens the list.738      // Kept outside the bindings table because it's a behavior, not a739      // discrete action — every printable character can trigger it.740      if (v === "entry" && !inInput && isPrintableSearchKey) {741        e.preventDefault();742        primeListSearch(e.key);743        return;744      }745    };746    window.addEventListener("keydown", handleGlobalKeydown);747    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));748749    const handleStorageChanged = (750      changes: Record<string, chrome.storage.StorageChange>,751      areaName: string752    ) => {753      if (areaName !== "session") return;754      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {755        return;756      }757      void refreshPendingPasskey();758    };759    chrome.storage.onChanged.addListener(handleStorageChanged);760    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));761  });762763  async function refreshCurrentTab() {764    try {765      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });766      const url = tab?.url ?? tab?.pendingUrl ?? "";767      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");768      // Skip extension/internal URLs — adding chrome://, about:, or769      // chrome-extension:// to a vault entry is never what the user wants.770      const isWebUrl = /^https?:\/\//i.test(url);771      setCurrentTabUrl(isWebUrl ? url : "");772    } catch {773      setCurrentTabDomain("");774      setCurrentTabUrl("");775    }776  }777778  async function refreshPendingPasskey() {779    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });780    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);781  }782783  async function refreshProStatus() {784    const res = await sendMessage({ type: "GET_LICENSE" });785    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;786    setProStatus(Boolean(data?.valid && data?.plan === "pro"));787  }788789  async function restoreSettings() {790    const res = await sendMessage({ type: "GET_SETTINGS" });791    const s = (res as { ok: boolean; data?: any }).data ?? {};792    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {793      setAccentColor(s.accentColor as AccentColorName);794    }795    setTheme(s.theme === "light" ? "light" : "dark");796    if (s.textSize === "small" || s.textSize === "large") {797      setTextSize(s.textSize);798    } else {799      setTextSize("medium");800    }801    setReduceMotion(s.reduceMotion === true);802    setLockOnClose(s.lockOnClose !== false);803    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);804    setBreachMonitoring(s.breachMonitoring !== false);805    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);806    setShortcutBindings(getActiveBindings(s.shortcuts));807  }808809  async function applyTrashRetention(days: number) {810    setTrashRetentionDays(days);811    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });812  }813814  function primeListSearch(seed: string) {815    setListSearchSeed(seed);816    setListSearchSeedNonce((value) => value + 1);817    openList();818  }819820  // Returns null when it detected a dead service worker and triggered handleLock().821  // Callers that need to abort (e.g. openVault) check for null rather than relying822  // on view() state, which may already be "lock" during normal startup flows.823  async function loadEntries(): Promise<VaultEntry[] | null> {824    const response = await sendMessage({ type: "GET_ENTRIES" });825    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };826827    // If the service worker was killed and restarted (MV3 workers sleep), the828    // vault will be locked again — or the worker may not respond at all.829    // In either case, send the user to the lock screen rather than silently830    // showing an empty vault (which looks like data loss).831    if (!res.ok) {832      if (833        res.error === "vault_locked" ||834        res.error === "SERVICE_WORKER_UNAVAILABLE" ||835        (typeof res.error === "string" && res.error.includes("locked"))836      ) {837        handleLock();838        return null; // signal emergency lock to callers839      }840      return [];841    }842843    const loadedEntries = res.data ?? [];844    setEntries(loadedEntries);845846    const currentId = selectedEntry()?.id;847    if (currentId) {848      setSelectedEntry(849        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null850      );851    }852853    return loadedEntries;854  }855856  async function openVault(preferredEntryId?: string, skipViewSet = false) {857    // Purge expired trash entries on each vault open858    const retDays = trashRetentionDays();859    if (retDays > 0) {860      void sendMessage({861        type: "PURGE_EXPIRED_TRASH",862        payload: { retentionMs: retDays * 86_400_000 },863      });864    }865866    const loadedEntries = await loadEntries();867868    // null means loadEntries() triggered an emergency lock (service worker died).869    // Don't override it by setting view back to "entry" with an empty vault.870    if (loadedEntries === null) return;871872    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry873    let nextSelectedEntry: VaultEntry | null = null;874    if (preferredEntryId) {875      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;876    }877    if (!nextSelectedEntry) {878      const tabDomain = currentTabDomain();879      if (tabDomain) {880        nextSelectedEntry = loadedEntries.find((e) => {881          if (e.type === "login") {882            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;883            for (const extra of e.additionalUrls ?? []) {884              if ((extractDomain(extra) ?? "") === tabDomain) return true;885            }886            return false;887          }888          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;889          return false;890        }) ?? null;891      }892    }893    nextSelectedEntry ??= loadedEntries[0] ?? null;894895    setSelectedEntry(nextSelectedEntry);896    setEditEntry(undefined);897    setContentTransitioning(false);898    setContentPhase("enter");899    queueContentIdle();900    if (!skipViewSet) setView("entry");901  }902903  async function handleUnlock() {904    // If the user previously created a vault but hadn't yet confirmed their905    // recovery words (and the browser was closed before they could), the906    // peach_recovery_pending flag is still set in storage.local. Re-route907    // back to the recovery surface so they finish the confirmation step908    // before reaching the entries view — the words can be re-derived now909    // that the vault is unlocked again.910    let recoveryPending = false;911    try {912      const out = await chrome.storage.local?.get("peach_recovery_pending");913      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";914    } catch { /* best-effort */ }915    if (recoveryPending) {916      setForceRecoveryWords(true);917      setView("lock");918      triggerPipPulse();919      await restoreSettings();920      return;921    }922    setHasVault(true);923    triggerPipPulse();924    await restoreSettings();925    const celebrating = pendingCelebration();926    if (celebrating) {927      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });928      setPendingCelebration(false);929    }930    await openVault(undefined, celebrating);931    if (celebrating) {932      setView("pro-celebration");933      window.setTimeout(() => setView("entry"), 2500);934    }935  }936937  function handleSelectEntry(entry: VaultEntry) {938    if (entry.type === "note") {939      setOpenNoteId(entry.id);940      setShowNotes(true);941      return;942    }943    setSelectedEntry(entry);944    setContentTransitioning(false);945    setContentPhase("enter");946    queueContentIdle();947    setView("entry");948  }949950  function handleAdd() {951    setEditEntry(undefined);952    setView("add");953  }954955  async function handleDelete() {956    const entry = selectedEntry();957    if (!entry) return;958    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });959    const loadedEntries = await loadEntries() ?? [];960    setSelectedEntry(loadedEntries[0] ?? null);961    setView("entry");962  }963964  async function handleDeleteMany(ids: string[]) {965    for (const id of ids) {966      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });967    }968    const loadedEntries = await loadEntries() ?? [];969    // If the currently selected entry was among the deleted, move to first970    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);971    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);972  }973974  async function handleSave(savedEntry?: VaultEntry) {975    await openVault(savedEntry?.id);976  }977978  function handleBack() {979    setEditEntry(undefined);980    setView("entry");981  }982983  function handleLock() {984    clearCanarySuppressions();985    setEntries([]);986    setSelectedEntry(null);987    setEditEntry(undefined);988    setContentPhase("idle");989    setView("lock");990  }991992  function handleHeaderLock() {993    // Lock the UI immediately — do not wait for the service worker. If the SW994    // is dead or slow, the 5s sendMessage timeout would create a dead-click995    // window. The SW will lock on its next wake regardless.996    handleLock();997    void sendMessage({ type: "LOCK" });998  }9991000  function navigate(dir: number) {1001    const allEntries = entries();1002    if (allEntries.length === 0) return;1003    const currentIndex = selectedIndex();1004    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1005    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1006    setSelectedEntry(allEntries[nextIndex]);1007    setContentPhase("enter");1008    queueContentIdle();1009  }10101011  function openList() {1012    setView("list");1013  }10141015  function openHealth() {1016    setEditEntry(undefined);1017    setView("health");1018  }10191020  function handleOpenFileImport() {1021    setRestoreView("file");1022  }10231024  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10251026  function handleFixEntry(entry: VaultEntry) {1027    // Passkey-only entries have no editable surface — drop into view mode1028    // instead of opening the Add editor.1029    if (isPasskeyOnly(entry)) {1030      setSelectedEntry(entry);1031      setView("entry");1032      return;1033    }1034    setEditEntry(entry);1035    setView("add");1036  }10371038  const isLockedView = () => view() === "lock";10391040  async function handleApprovePendingPasskey() {1041    const pending = pendingPasskey();1042    if (!pending) return;1043    if (pending.browser === "firefox" && pending.type === "create") {1044      // Firefox path: popup itself runs navigator.credentials.create. The1045      // background never approved/rejected anything — it just stashed1046      // intent. After the popup-driven flow resolves (success or cancel),1047      // clear the pending key so the popup doesn't re-show this on next open.1048      const { createFirefoxPasskey } = await import("./firefox-passkey");1049      const result = await createFirefoxPasskey(pending);1050      if (!result.ok) {1051        console.warn("Peach Firefox passkey create failed:", result.error);1052      }1053      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1054      setPendingPasskey(null);1055      void loadEntries();1056      window.close();1057      return;1058    }1059    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1060    window.close();1061  }10621063  async function handleDenyPendingPasskey() {1064    const pending = pendingPasskey();1065    if (!pending) return;1066    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1067    window.close();1068  }10691070  function queueContentIdle(after?: () => void) {1071    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1072    contentPhaseTimer = window.setTimeout(() => {1073      setContentPhase("idle");1074      after?.();1075    }, ENTRY_TRANSITION_SETTLE_MS);1076  }10771078  return (1079    <div class="popup-root peach-theme">1080      <Show when={bootState() === "ready"}>1081        <Show1082          when={!pendingPasskey()}1083          fallback={1084            <PasskeyApprovalView1085              type={pendingPasskey()!.type}1086              rpName={pendingPasskey()!.rpName}1087              rpId={pendingPasskey()!.rpId}1088              userName={pendingPasskey()!.userName}1089              userDisplayName={pendingPasskey()!.userDisplayName}1090              onApprove={handleApprovePendingPasskey}1091              onDeny={handleDenyPendingPasskey}1092            />1093          }1094        >1095          <Show1096            when={!isLockedView()}1097            fallback={1098              <Show1099                when={onboarded() || hasVault()}1100                fallback={1101                  <Onboarding1102                    onComplete={() => { setOnboarded(true); }}1103                  />1104                }1105              >1106                <LockView1107                  hasVault={hasVault()}1108                  ready={bootState() === "ready"}1109                  isPro={proStatus()}1110                  forceRecoveryWords={forceRecoveryWords()}1111                  onUnlock={() => {1112                    // RecoveryWordDisplay clears the storage flag before1113                    // calling onDone, so handleUnlock will see no pending1114                    // confirmation and proceed through the normal path.1115                    if (forceRecoveryWords()) setForceRecoveryWords(false);1116                    return handleUnlock();1117                  }}1118                  onBackToOnboarding={1119                    !hasVault()1120                      ? () => setOnboarded(false)1121                      : undefined1122                  }1123                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1124                />1125              </Show>1126            }1127          >1128            <Show1129              when={view() !== "pro-celebration"}1130              fallback={<ProCelebration />}1131            >1132            <section1133              id="hd-shell"1134              class="peach-shell peach-theme"1135              data-surface="extension"1136            >1137            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1138              <PeachWordmark unlocked />1139              <div class="peach-chrome-actions">1140                <button1141                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1142                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1143                  aria-label="Notes"1144                  title="Notes"1145                >1146                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1147                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1148                    <line x1="4" y1="5" x2="10" y2="5" />1149                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1150                    <line x1="4" y1="10" x2="7" y2="10" />1151                  </svg>1152                </button>1153                <button1154                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1155                  onClick={() => setView("settings")}1156                  aria-label="Settings"1157                >1158                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1159                    <path1160                      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"1161                      stroke="currentColor"1162                      stroke-width="0.9"1163                    />1164                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1165                  </svg>1166                </button>1167                <button1168                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1169                  onClick={handleAdd}1170                  aria-label="New entry"1171                >1172                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1173                    <path d="M5.5 1v9M1 5.5h9" />1174                  </svg>1175                </button>1176                <button1177                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1178                  onClick={() => void handleHeaderLock()}1179                  aria-label="Lock vault"1180                >1181                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1182                    <path1183                      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"1184                      stroke="currentColor"1185                      stroke-width="1"1186                      stroke-linecap="round"1187                    />1188                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1189                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1190                  </svg>1191                </button>1192              </div>1193            </header>11941195            <Show when={pendingProNotice() !== null}>1196              <div class="peach-pro-notice-banner">1197                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1198                <button1199                  class="peach-pro-notice-link"1200                  onClick={() => {1201                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1202                    setSettingsInitialSection("license");1203                    setView("settings");1204                    setPendingProNotice(null);1205                  }}1206                >1207                  Learn more →1208                </button>1209                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1210              </div>1211            </Show>12121213            <div class="peach-shell-body">1214              <div class="peach-shell-veil"></div>1215              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1216                <EntryView1217                  entry={selectedEntry()}1218                  currentTabUrl={currentTabUrl()}1219                  entries={entries()}1220                  isPro={proStatus()}1221                  onDelete={handleDelete}1222                  onFieldSaved={() => void loadEntries()}1223                  onEscape={() => { setView("list"); }}1224                  onProGate={(feature) => {1225                    setUpgradeHighlight(feature);1226                    setSettingsInitialSection("license");1227                    setView("settings");1228                  }}1229                />1230              </div>12311232              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1233                <div class="peach-search-bar">1234                  <span class="peach-search-icon">1235                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1236                      <circle cx="5.5" cy="5.5" r="3.75" />1237                      <path d="M8.75 8.75L11.5 11.5" />1238                    </svg>1239                  </span>1240                  <input1241                    class="peach-search-input"1242                    placeholder="search vault..."1243                    autocomplete="off"1244                    aria-label="Search vault entries"1245                    onClick={openList}1246                    onFocus={openList}1247                    readOnly1248                  />1249                  <div class="peach-search-meta">1250                    <span class="peach-search-counter">1251                      {entries().length > 01252                        ? `${selectedIndex() + 1} / ${entries().length}`1253                        : "0 entries"}1254                    </span>1255                    <span class="peach-divider"></span>1256                    <button1257                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1258                      onClick={() => navigate(-1)}1259                      aria-label="Previous entry"1260                      disabled={entries().length === 0}1261                    >1262                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1263                        <path d="M5 1L1 5.5L5 10" />1264                      </svg>1265                    </button>1266                    <button1267                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1268                      onClick={() => navigate(1)}1269                      aria-label="Next entry"1270                      disabled={entries().length === 0}1271                    >1272                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1273                        <path d="M1 1L5 5.5L1 10" />1274                      </svg>1275                    </button>1276                  </div>1277                </div>1278              </section>1279            </div>12801281            {/* Desktop: shown on demand via Show. Native sheet is rendered1282                via Portal below at the document root so its position:fixed1283                isn't trapped by .peach-shell's transform-based animations. */}1284            <Show when={!isNativePlatform() && view() === "list"}>1285              <VaultView1286                entries={entries()}1287                selectedEntryId={selectedEntry()?.id}1288                currentTabDomain={currentTabDomain()}1289                sortOrder={sortOrder()}1290                searchSeed={listSearchSeed()}1291                searchSeedNonce={listSearchSeedNonce()}1292                onSelectEntry={handleSelectEntry}1293                onSortOrderChange={setSortOrder}1294                onAdd={handleAdd}1295                onClose={() => setView("entry")}1296                onOpenTrash={() => setView("trash")}1297                onDeleteMany={handleDeleteMany}1298              />1299            </Show>1300            <Show when={isNativePlatform() && hasVault()}>1301              <Portal>1302                <div1303                  class="peach-vault-sheet"1304                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1305                  style={(() => {1306                    const live = sheetTranslate();1307                    if (live === null) return undefined;1308                    return { transform: `translateY(${live}px)` };1309                  })()}1310                >1311                  <VaultView1312                    entries={entries()}1313                    selectedEntryId={selectedEntry()?.id}1314                    currentTabDomain={currentTabDomain()}1315                    sortOrder={sortOrder()}1316                    searchSeed={listSearchSeed()}1317                    searchSeedNonce={listSearchSeedNonce()}1318                    isNative={true}1319                    onSelectEntry={handleSelectEntry}1320                    onSortOrderChange={setSortOrder}1321                    onAdd={handleAdd}1322                    onClose={() => setView("entry")}1323                    onOpenTrash={() => setView("trash")}1324                    onDeleteMany={handleDeleteMany}1325                  />1326                </div>1327              </Portal>1328            </Show>1329            <Show when={view() === "settings" || settingsExiting()}>1330              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1331                <SettingsView1332                  entriesCount={entries().length}1333                  breachMonitoring={breachMonitoring()}1334                  lockOnClose={lockOnClose()}1335                  autoLockMinutes={autoLockMinutes()}1336                  trashRetentionDays={trashRetentionDays()}1337                  theme={theme()}1338                  accentColor={accentColor()}1339                  textSize={textSize()}1340                  reduceMotion={reduceMotion()}1341                  isPro={proStatus()}1342                  initialSection={settingsInitialSection()}1343                  upgradeHighlight={upgradeHighlight()}1344                  isExiting={settingsExiting()}1345                  onBreachMonitoringChange={applyBreachMonitoring}1346                  onLockOnCloseChange={applyLockOnClose}1347                  onAutoLockMinutesChange={applyAutoLockMinutes}1348                  onTrashRetentionChange={applyTrashRetention}1349                  onThemeChange={applyTheme}1350                  onAccentChange={applyAccentColor}1351                  onTextSizeChange={applyTextSize}1352                  onReduceMotionChange={applyReduceMotion}1353                  shortcuts={shortcutBindings()}1354                  onShortcutsChange={applyShortcuts}1355                  onLicenseChange={async () => {1356                    // After activation/deactivation: refresh Pro status,1357                    // re-load entries (defensive — signal state can drift if1358                    // the SW briefly restarts during the verify+save round-trip),1359                    // and replay the Pro celebration if this is the first time1360                    // a valid Pro license is seen on this device.1361                    await refreshProStatus();1362                    void loadEntries();1363                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1364                    if ((should as { ok: boolean; data?: boolean }).data === true) {1365                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1366                      setView("pro-celebration");1367                      window.setTimeout(() => setView("settings"), 2500);1368                    }1369                  }}1370                  onBack={() => {1371                    setSettingsExiting(true);1372                    window.setTimeout(() => {1373                      setSettingsExiting(false);1374                      setSettingsInitialSection(null);1375                      setUpgradeHighlight(null);1376                      handleBack();1377                    }, 200);1378                  }}1379                  onImport={() => setView("import")}1380                  onExport={() => setView("export")}1381                  onBreachCheckDone={loadEntries}1382                  onOpenHealth={openHealth}1383                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("chirp-sync"); }}1384                  onOpenFileImport={handleOpenFileImport}1385                  onOpenPanic={() => setView("panic")}1386                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1387                  onOpenCodexRestore={() => setView("codex-restore")}1388                  onCardChange={setSettingsActiveCard}1389                  onProGate={(feature) => {1390                    setUpgradeHighlight(feature);1391                    setSettingsInitialSection("license");1392                  }}1393                />1394              </Suspense>1395            </Show>1396            <Show when={view() === "codex-generate"}>1397              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1398                <CodexGenerateView1399                  isPro={proStatus()}1400                  onBack={() => setView("settings")}1401                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1402                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1403                  onVaultLocked={() => handleLock()}1404                />1405              </Suspense>1406            </Show>1407            <Show when={view() === "codex-restore"}>1408              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1409                <CodexRestoreView1410                  onBack={() => setView("lock")}1411                  onRestoreSuccess={async () => {1412                    // After restore the vault is unlocked; refresh entries1413                    // and route to the main vault list. handleUnlock is the1414                    // canonical post-unlock setup path.1415                    await handleUnlock();1416                  }}1417                />1418              </Suspense>1419            </Show>1420            <Show when={view() === "chirp-sync"}>1421              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1422                <ChirpSyncView1423                  isPro={proStatus()}1424                  onBack={() => setView("settings")}1425                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1426                />1427              </Suspense>1428            </Show>1429            <Show when={view() === "add"}>1430              <AddView1431                entry={editEntry()}1432                entries={entries()}1433                onBack={handleBack}1434                onSave={handleSave}1435              />1436            </Show>1437            <Show when={view() === "import"}>1438              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1439                <ImportView onBack={handleBack} onImport={handleSave} />1440              </Suspense>1441            </Show>1442            <Show when={view() === "export"}>1443              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1444                <ExportView1445                  onBack={() => {1446                    if (returnToPanic()) {1447                      setReturnToPanic(false);1448                      setView("panic");1449                    } else {1450                      handleBack();1451                    }1452                  }}1453                />1454              </Suspense>1455            </Show>1456            <Show when={view() === "panic"}>1457              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1458                <PanicView1459                  onCancel={() => setView("settings")}1460                  onOpenExport={() => {1461                    setReturnToPanic(true);1462                    setView("export");1463                  }}1464                  onDestroyed={async () => {1465                    clearCanarySuppressions();1466                    setEntries([]);1467                    setSelectedEntry(null);1468                    setEditEntry(undefined);1469                    setHasVault(false);1470                    setOnboarded(false);1471                    setProStatus(false);1472                    setPendingPasskey(null);1473                    setUpgradeHighlight(null);1474                    setSettingsInitialSection(null);1475                    setPendingProNotice(null);1476                    setPendingCelebration(false);1477                    setReturnToPanic(false);1478                    setContentPhase("idle");1479                    setView("lock");1480                  }}1481                />1482              </Suspense>1483            </Show>1484            <Show when={view() === "health"}>1485              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1486                <HealthView1487                  entries={entries()}1488                  isPro={proStatus()}1489                  onFixEntry={handleFixEntry}1490                  onBack={() => setView("settings")}1491                  onRefresh={loadEntries}1492                />1493              </Suspense>1494            </Show>1495            <Show when={view() === "trash"}>1496              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1497                <TrashView1498                  onBack={() => setView("list")}1499                  onRestored={() => void loadEntries()}1500                />1501              </Suspense>1502            </Show>1503            <Show when={showNotes()}>1504              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1505                <NotesMode1506                  notes={entries().filter((e) => e.type === "note")}1507                  initialNoteId={openNoteId()}1508                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1509                  onNoteListChanged={() => void loadEntries()}1510                />1511              </div>1512            </Show>1513            <Show when={restoreView() === "file"}>1514              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1515                <ImportView1516                  mode="onboarding"1517                  replacesExistingVault={true}1518                  onBack={() => setRestoreView(null)}1519                  onImport={async () => {1520                    setRestoreView(null);1521                    await handleUnlock();1522                  }}1523                />1524              </Suspense>1525            </Show>1526            </section>1527            </Show>1528          </Show>1529        </Show>1530      </Show>1531      <Show when={showShortcutsHelp()}>1532        <ShortcutsHelpOverlay1533          bindings={shortcutBindings()}1534          onClose={() => setShowShortcutsHelp(false)}1535        />1536      </Show>1537    </div>1538  );1539}15401541function ShortcutsHelpOverlay(props: {1542  bindings: Record<ShortcutAction, Keybinding>;1543  onClose: () => void;1544}) {1545  return (1546    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1547      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1548        <div class="peach-shortcuts-help-head">1549          <h3>Keyboard shortcuts</h3>1550          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1551        </div>1552        <div class="peach-shortcuts-help-body">1553          <p class="peach-settings-sub-label">ENTRY VIEW</p>1554          <ul>1555            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1556              <li>1557                <span>{d.label}</span>1558                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1559              </li>1560            ))}1561          </ul>1562          <p class="peach-settings-sub-label">ANYWHERE</p>1563          <ul>1564            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1565              <li>1566                <span>{d.label}</span>1567                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1568              </li>1569            ))}1570          </ul>1571        </div>1572      </div>1573    </div>1574  );1575}