App.tsx

64.8 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageSet } from "../shared/storage";4import { sendMessage } from "../shared/bridge";5import { ACCENT_COLORS } from "../shared/types";6import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";7import { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { NotesMode } from "./views/NotesMode";11import { ProCelebration } from "./views/ProCelebration";12import { VaultView, type SortOrder } from "./views/Vault";13import { EntryView } from "./views/Entry";14import { AddView } from "./views/Add";15import { PeachWordmark } from "./components/PeachMark";16import { PasskeyApprovalView } from "./views/PasskeyApproval";17import { extractDomain } from "../shared/domain";18import { popupCopy } from "./copy";19import {20  DEFAULT_BINDINGS,21  formatKeybinding,22  getActiveBindings,23  matchKeybinding,24  SHORTCUT_DESCRIPTORS,25  type Keybinding,26  type ShortcutAction,27} from "../shared/shortcuts";28import { generateTOTP } from "../crypto/totp";29import { isNativePlatform, nativePlugin } from "../shared/native";3031export { sendMessage } from "../shared/bridge";3233const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));34const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));35const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));36const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));37const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));38const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));39const ChirpSyncView   = lazy(() => import("./views/ChirpSync").then(m => ({ default: m.ChirpSyncView })));40const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));41const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));4243type View =44  | "lock"45  | "pro-celebration"46  | "entry"47  | "list"48  | "add"49  | "settings"50  | "chirp-sync"51  | "import"52  | "export"53  | "health"54  | "trash"55  | "panic"56  | "codex-generate"57  | "codex-restore";58type BootState = "loading" | "ready";5960const canarySuppressMap = new Map<string, boolean>();61let shellRingAnimation: Animation | null = null;6263export function isCanarySuppressed(entryId: string): boolean {64  return canarySuppressMap.get(entryId) ?? false;65}6667export function setCanarySuppressed(entryId: string, suppressed: boolean): void {68  canarySuppressMap.set(entryId, suppressed);69}7071export function clearCanarySuppressions(): void {72  canarySuppressMap.clear();73}7475export function triggerRing() {76  const shell = document.getElementById("hd-shell");77  if (!shell) return;7879  shellRingAnimation?.cancel();80  shell.dataset.glowing = "true";81  const animation = shell.animate(82    [83      { offset: 0, boxShadow: "var(--copy-shadow)" },84      {85        offset: 0.3,86        boxShadow:87          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",88      },89      { offset: 1, boxShadow: "var(--copy-shadow)" },90    ],91    {92      duration: 720,93      easing: "cubic-bezier(0.4, 0, 0.2, 1)",94      fill: "none",95    }96  );97  shellRingAnimation = animation;98  const clearGlow = () => {99    if (shellRingAnimation !== animation) return;100    shellRingAnimation = null;101    delete shell.dataset.glowing;102  };103  animation.onfinish = clearGlow;104  animation.oncancel = clearGlow;105}106107108export function triggerPipPulse() {109  const pip = document.querySelector(".peach-status-pip, .pip");110  if (pip) {111    pip.classList.remove("pulse");112    void (pip as HTMLElement).offsetWidth;113    pip.classList.add("pulse");114  }115}116117const ENTRY_TRANSITION_SETTLE_MS = 135;118119export default function App() {120  const [bootState, setBootState] = createSignal<BootState>("loading");121  const [view, setView] = createSignal<View>("lock");122  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,123  // CSS transition takes over for snap animation).124  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);125  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(126    "enter"127  );128  const [contentTransitioning, setContentTransitioning] = createSignal(false);129  const [hasVault, setHasVault] = createSignal(false);130  const [onboarded, setOnboarded] = createSignal(true);131  const [entries, setEntries] = createSignal<VaultEntry[]>([]);132  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);133  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);134  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");135  const [theme, setTheme] = createSignal<"dark" | "light">("dark");136  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");137  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);138  const [lockOnClose, setLockOnClose] = createSignal(true);139  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);140  const [breachMonitoring, setBreachMonitoring] = createSignal(true);141  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);142  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);143  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);144  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);145  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);146  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");147  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");148  // Cached Pro status — synchronous for render paths. Background's149  // GET_LICENSE is async, but render-time reads of isPro() must not block.150  // Refreshed at boot, after activate/deactivate, and whenever the popup151  // re-opens onto a stored license that has changed via another window.152  const [proStatus, setProStatus] = createSignal(false);153  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);154  const [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  // The view to return to when the add/edit view is dismissed. Normally "entry"166  // but "health" when the user arrives via the fix-entry path from Vault Health.167  const [editBackView, setEditBackView] = createSignal<View>("entry");168  const [settingsExiting, setSettingsExiting] = createSignal(false);169  const [showNotes, setShowNotes] = createSignal(false);170  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);171  // Set on popup boot when peach_recovery_pending flag is found in session172  // storage — instructs LockView to skip the unlock UI and open the recovery173  // words confirmation surface instead. Cleared via handleUnlock once the174  // user has typed the 3 confirmation words.175  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);176177  let contentPhaseTimer: number | undefined;178179  function applyAccent(name: AccentColorName) {180    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;181    const hex = color.hex;182    document.documentElement.style.setProperty("--peach-accent", hex);183    // Ambient surface variables — derived from the accent so surfaces shift184    // subtly toward the accent hue rather than staying fixed warm-brown.185    document.documentElement.style.setProperty("--peach-glow", hex + "2A");186    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");187    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");188  }189190  createEffect(() => {191    applyAccent(accentColor());192  });193194  createEffect(() => {195    document.documentElement.classList.toggle("light", theme() === "light");196    document.body.classList.toggle("light", theme() === "light");197  });198199  createEffect(() => {200    document.documentElement.setAttribute("data-text-size", textSize());201  });202203  createEffect(() => {204    if (reduceMotion()) {205      document.documentElement.setAttribute("data-motion", "reduce");206    } else {207      document.documentElement.removeAttribute("data-motion");208    }209  });210211  const selectedIndex = createMemo(() => {212    const currentId = selectedEntry()?.id;213    if (!currentId) return entries().length > 0 ? 0 : -1;214    return entries().findIndex((entry) => entry.id === currentId);215  });216217  async function applyAccentColor(name: AccentColorName) {218    applyAccent(name);219    setAccentColor(name);220    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });221  }222223  async function applyTheme(t: "dark" | "light") {224    setTheme(t);225    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });226  }227228  async function applyTextSize(size: "small" | "medium" | "large") {229    setTextSize(size);230    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });231  }232233  async function applyReduceMotion(enabled: boolean) {234    setReduceMotion(enabled);235    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });236  }237238  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload239  // small and lets future default updates land for actions the user hasn't240  // touched. Settings sends us the full active map; we filter and store.241  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {242    setShortcutBindings(active);243    const overrides: Record<string, Keybinding> = {};244    for (const action of Object.keys(active) as ShortcutAction[]) {245      const a = active[action];246      const d = DEFAULT_BINDINGS[action];247      const same = a.key === d.key248        && Boolean(a.ctrl)  === Boolean(d.ctrl)249        && Boolean(a.meta)  === Boolean(d.meta)250        && Boolean(a.shift) === Boolean(d.shift)251        && Boolean(a.alt)   === Boolean(d.alt);252      if (!same) overrides[action] = a;253    }254    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });255  }256257  async function applyLockOnClose(enabled: boolean) {258    setLockOnClose(enabled);259    await sendMessage({260      type: "UPDATE_SETTINGS",261      payload: { lockOnClose: enabled },262    });263  }264265  async function applyAutoLockMinutes(minutes: number) {266    setAutoLockMinutes(minutes);267    await sendMessage({268      type: "UPDATE_SETTINGS",269      payload: { autoLockMinutes: minutes },270    });271  }272273  async function applyBreachMonitoring(enabled: boolean) {274    setBreachMonitoring(enabled);275    await sendMessage({276      type: "UPDATE_SETTINGS",277      payload: { breachMonitoring: enabled },278    });279  }280281  onMount(async () => {282    // Resolve the active tab in parallel with the unlock/has-vault queries —283    // openVault()'s smart selection picks the entry matching currentTabDomain,284    // so it must be populated before openVault runs. Previously refreshCurrentTab285    // ran after openVault, leaving popups that booted already-unlocked falling286    // back to loadedEntries[0] instead of the domain match.287    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([288      sendMessage({ type: "IS_UNLOCKED" }),289      sendMessage({ type: "HAS_VAULT" }),290      refreshCurrentTab(),291      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),292    ]);293    const unlocked = Boolean(294      (unlockResponse as { ok: boolean; data?: boolean }).data295    );296    const vaultExists = Boolean(297      (vaultResponse as { ok: boolean; data?: boolean }).data298    );299    const shouldCelebrate = Boolean(300      (celebrationResponse as { ok: boolean; data?: boolean }).data301    );302    setHasVault(vaultExists);303    // Onboarding gate — show once on first install, never again. Existing304    // users (vaultExists) are auto-marked onboarded so they skip the flow305    // even on the very first popup open after this feature ships.306    try {307      const onboarded = await storageGet("peach_onboarded");308      const seen = onboarded === "true";309      if (vaultExists && !seen) {310        await storageSet("peach_onboarded", "true");311        setOnboarded(true);312      } else {313        setOnboarded(seen);314      }315    } catch {316      // storage unavailable — default to onboarded so we never block boot317      setOnboarded(true);318    }319    await Promise.all([restoreSettings(), refreshProStatus()]);320321    // Mark played before any animation so a crash mid-sequence never replays it322    if (shouldCelebrate) {323      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });324    }325326    // If the user created a vault but hasn't yet confirmed their recovery327    // words, route back to the recovery-words screen instead of opening the328    // entries view. The flag lives in chrome.storage.local so it survives329    // both popup close (SW suppresses lock-on-close) and full browser330    // restart (handleUnlock checks the same flag after a fresh password331    // unlock). Cleared when confirmation succeeds.332    let recoveryPending = false;333    try {334      const out = await chrome.storage.local?.get("peach_recovery_pending");335      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";336    } catch { /* best-effort */ }337338    // Native: closing the app before recovery-words confirmation means the339    // user didn't finish vault creation. Throw the partial vault away and340    // restart onboarding rather than asking them to unlock a vault they341    // never finished creating. Desktop keeps the existing "unlock to342    // resume" flow because closing the popup there is much more casual.343    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {344      try {345        await chrome.storage.local?.remove([346          "peach_vault_a",347          "peach_vault_b",348          "peach_recovery_pending",349          "peach_onboarded",350          "peach_vault_history",351        ]);352      } catch { /* best-effort */ }353      setHasVault(false);354      setOnboarded(false);355      setView("lock");356      setBootState("ready");357      document.getElementById("pre-lock")?.setAttribute("hidden", "true");358      return;359    }360361    if (recoveryPending && unlocked) {362      // forceRecoveryWords overrides LockView's hasVault gate so the363      // recovery surface renders even though the vault now exists.364      setForceRecoveryWords(true);365      setView("lock");366    } else if (unlocked && vaultExists) {367      await openVault(undefined, shouldCelebrate);368      if (shouldCelebrate) {369        setView("pro-celebration");370        window.setTimeout(() => setView("entry"), 2500);371      }372    } else if (shouldCelebrate) {373      setPendingCelebration(true);374    }375376    await refreshPendingPasskey();377378    // Track tab changes so smart sort stays current379    const handleTabActivated = () => { void refreshCurrentTab(); };380    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {381      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();382    };383    try {384      chrome.tabs.onActivated.addListener(handleTabActivated);385      chrome.tabs.onUpdated.addListener(handleTabUpdated);386      onCleanup(() => {387        chrome.tabs.onActivated.removeListener(handleTabActivated);388        chrome.tabs.onUpdated.removeListener(handleTabUpdated);389      });390    } catch {391      // tabs permission may not be available in all contexts392    }393394    setBootState("ready");395    document.getElementById("pre-lock")?.setAttribute("hidden", "true");396397    // Check for pending session-storage notices from the background.398    if (chrome.storage.session) {399      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as400        Record<string, { feature?: string } | undefined>;401      if (session.pendingProGate?.feature) {402        await chrome.storage.session.remove("pendingProGate");403        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);404        setSettingsInitialSection("license");405        setView("settings");406      } else if (session.pendingProNotice?.feature) {407        await chrome.storage.session.remove("pendingProNotice");408        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });409      }410    }411412    // Warm the lazy-module cache so the Suspense fallback never shows for413    // locally-bundled extension views. Without this, the first navigation to414    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which415    // covers the shell and absorbs clicks on the header.416    void Promise.all([417      import("./views/Settings").catch(() => {}),418      import("./views/Import").catch(() => {}),419      import("./views/Export").catch(() => {}),420      import("./views/Health").catch(() => {}),421      import("./views/TrashView").catch(() => {}),422    ]);423424    // Lock-on-close via a persistent port. sendMessage in pagehide is425    // unreliable — the popup context tears down before the message lands.426    // The SW's onConnect listener locks when this port disconnects.427    let popupPort: chrome.runtime.Port | null = null;428    try {429      popupPort = chrome.runtime.connect({ name: "popup" });430    } catch { /* extension context invalidated — ignore */ }431    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });432433    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only434    // reliable signal is appStateChange — setTimeout is killed when the OS435    // backgrounds the app. We measure elapsed background time on resume.436    if (isNativePlatform()) {437      let backgroundedAt: number | null = null;438439      const CapApp = nativePlugin<{440        addListener: (441          ev: string,442          cb: (s: { isActive: boolean }) => void,443        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };444      }>("App");445      if (CapApp?.addListener) {446        const sub = CapApp.addListener(447          "appStateChange",448          ({ isActive }: { isActive: boolean }) => {449            if (!isActive) {450              backgroundedAt = Date.now();451              return;452            }453            if (backgroundedAt !== null && autoLockMinutes() > 0) {454              const elapsed = Date.now() - backgroundedAt;455              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();456            }457            backgroundedAt = null;458          }459        );460        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.461        onCleanup(() => {462          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});463        });464      }465466      // L12/COR-011: foreground idle autolock. appStateChange only fires when467      // the OS backgrounds the app — if the user idles with the screen on,468      // chrome.alarms is no-op'd in Capacitor so the vault would stay open469      // indefinitely. Poll every 30s and lock if elapsed since last user470      // interaction exceeds autoLockMinutes.471      let lastUserActivityAt = Date.now();472      const bumpActivity = () => { lastUserActivityAt = Date.now(); };473      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;474      for (const ev of ACTIVITY_EVENTS) {475        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });476      }477      const idleLockInterval = setInterval(() => {478        const minutes = autoLockMinutes();479        if (!minutes || minutes <= 0) return;480        const elapsed = Date.now() - lastUserActivityAt;481        if (elapsed >= minutes * 60_000) {482          lastUserActivityAt = Date.now();483          handleHeaderLock();484        }485      }, 30_000);486      onCleanup(() => {487        clearInterval(idleLockInterval);488        for (const ev of ACTIVITY_EVENTS) {489          document.removeEventListener(ev, bumpActivity, { capture: true });490        }491      });492    }493494    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale495    // entries instead of waiting for the next GET_ENTRIES round-trip.496    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {497      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();498      if (msg?.type === "PRO_GATE_TRIGGERED") {499        setUpgradeHighlight(msg.payload?.feature ?? null);500        setSettingsInitialSection("license");501        setView("settings");502      }503    };504    chrome.runtime.onMessage.addListener(handleRuntimeMessage);505    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));506507    // Android hardware/gesture back. MainActivity fires peach:back; the popup508    // decides what "back" means per surface. Lock+no-vault is the common case509    // — return to onboarding rather than letting the OS dismiss the activity.510    const handlePeachBack = () => {511      // Notes mode captures back first512      if (showNotes()) {513        setShowNotes(false);514        setOpenNoteId(undefined);515        return;516      }517      const v = view();518      if (v === "lock" && !hasVault() && onboarded()) {519        setOnboarded(false);520        return;521      }522      if (v === "list") { setView("entry"); return; }523      if (v === "settings") {524        window.dispatchEvent(new Event("peach:settings-back"));525        return;526      }527      if (v === "import" || v === "health") { setView("settings"); return; }528      if (v === "export") { handleExportBack(); return; }529      if (v === "add") { handleBack(); return; }530      if (v === "chirp-sync") { setView("settings"); return; }531    };532    window.addEventListener("peach:back", handlePeachBack);533    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));534535    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that536    // peeks from the bottom (search bar handle visible) and drags up to fill537    // the screen. dragOffset is the LIVE finger offset during a drag, in px,538    // 0 when no drag in progress. The wrapper element computes transform =539    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.540    if (isNativePlatform()) {541      let touchStartY = 0;542      let touchStartX = 0;543      let lastY = 0;544      let lastT = 0;545      let dragging = false;546      let captured = false;547      const HORIZONTAL_TOLERANCE = 16;548      const ACTIVATION_DY = 8;549      const PEEK_PX = 60;550551      const onTouchStart = (e: TouchEvent) => {552        const t = e.touches[0];553        if (!t) return;554        const v = view();555        if (v !== "entry" && v !== "list") return;556        // Entry view: only intercept drags starting in the bottom 40%.557        // List view: intercept drags starting in the top 35% (the search/handle row).558        const inBand = v === "entry"559          ? t.clientY > window.innerHeight * 0.6560          : t.clientY < window.innerHeight * 0.35;561        if (!inBand) return;562        touchStartY = lastY = t.clientY;563        touchStartX = t.clientX;564        lastT = e.timeStamp;565        dragging = true;566        captured = false;567      };568569      const onTouchMove = (e: TouchEvent) => {570        if (!dragging) return;571        const t = e.touches[0];572        if (!t) return;573        const dy = t.clientY - touchStartY;574        const dx = Math.abs(t.clientX - touchStartX);575576        if (!captured) {577          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {578            // Looks like a horizontal swipe — release.579            dragging = false;580            return;581          }582          if (Math.abs(dy) < ACTIVATION_DY) return;583          captured = true;584        }585586        // Translate the sheet by dy from its rest (peek) position. Peek is587        // (viewport height - PEEK_PX). Open is 0.588        const v = view();589        const restClosed = window.innerHeight - PEEK_PX;590        const baseTranslate = v === "list" ? 0 : restClosed;591        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));592        setSheetTranslate(next);593        lastY = t.clientY;594        lastT = e.timeStamp;595      };596597      const onTouchEnd = (e: TouchEvent) => {598        if (!dragging) { return; }599        const t = e.changedTouches[0];600        const elapsed = Math.max(1, e.timeStamp - lastT);601        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms602        const wasCaptured = captured;603        dragging = false;604        captured = false;605        const v = view();606607        if (!wasCaptured) {608          // Tap in the peek strip while in entry view → open the vault list.609          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");610          setSheetTranslate(null);611          return;612        }613614        const restClosed = window.innerHeight - PEEK_PX;615        const current = sheetTranslate() ?? restClosed;616617        // Snap rules:618        //   - Strong upward velocity → open619        //   - Strong downward velocity → close620        //   - Otherwise snap to whichever rest is closer621        let nextOpen: boolean;622        if (velocity < -0.05) nextOpen = true;623        else if (velocity > 0.05) nextOpen = false;624        else nextOpen = current < restClosed * 0.5;625626        if (nextOpen && v !== "list") setView("list");627        if (!nextOpen && v !== "entry") setView("entry");628        // Release the live offset so CSS transition handles the snap.629        setSheetTranslate(null);630      };631632      document.addEventListener("touchstart", onTouchStart, { passive: true });633      document.addEventListener("touchmove",  onTouchMove,  { passive: true });634      document.addEventListener("touchend",   onTouchEnd,   { passive: true });635      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });636      onCleanup(() => {637        document.removeEventListener("touchstart", onTouchStart);638        document.removeEventListener("touchmove",  onTouchMove);639        document.removeEventListener("touchend",   onTouchEnd);640      });641    }642643    // Action handlers — keyed by ShortcutAction. The dispatcher below tests644    // each binding against the event and runs the matching handler. New645    // shortcuts only need an entry here; the binding is data, not code.646    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {647      copy_password: () => {648        const entry = selectedEntry();649        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });650      },651      copy_username: () => {652        const entry = selectedEntry();653        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });654      },655      copy_totp: () => {656        const entry = selectedEntry();657        if (!entry?.totp) return;658        try {659          const { code } = generateTOTP(entry.totp);660          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });661        } catch { /* invalid TOTP secret — silent */ }662      },663      new_entry: () => handleAdd(),664      edit_entry: () => {665        const entry = selectedEntry();666        // Passkey-only entries have nothing user-editable in the Add view; the667        // passkey credential itself is opaque. Skip the edit action for them.668        if (!entry || isPasskeyOnly(entry)) return;669        setEditEntry(entry);670        setView("add");671      },672      delete_entry: () => {673        if (selectedEntry()) void handleDelete();674      },675      lock_vault: () => { void handleHeaderLock(); },676      search: () => openList(),677      nav_prev: () => navigate(-1),678      nav_next: () => navigate(1),679      jump_vault: () => setView("entry"),680      jump_settings: () => setView("settings"),681      show_help: () => setShowShortcutsHelp(true),682    };683684    // Actions that are MEANINGFUL only on the entry-detail view. Outside685    // that scope the binding is dormant — pressing C while on Settings686    // does nothing rather than awkwardly copying from a now-stale entry.687    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([688      "copy_password", "copy_username", "copy_totp",689      "edit_entry", "delete_entry", "nav_prev", "nav_next",690    ]);691692    const handleGlobalKeydown = (e: KeyboardEvent) => {693      const v = view();694      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"695        || (e.target as HTMLElement)?.tagName === "TEXTAREA"696        || (e.target as HTMLElement)?.isContentEditable;697      const isPrintableSearchKey =698        e.key.length === 1 &&699        !e.ctrlKey &&700        !e.metaKey &&701        !e.altKey;702703      // No input during the pro celebration sequence704      if (v === "pro-celebration") return;705706      // Help dialog: Escape closes it; eat the keypress so it doesn't707      // also navigate away from the underlying view.708      if (showShortcutsHelp()) {709        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }710        return;711      }712713      // ── Escape — fixed binding (not user-customizable) ───────714      if (e.key === "Escape") {715        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }716        if (v === "list") { setView("entry"); return; }717        if (v === "settings" || v === "add") { handleBack(); return; }718        if (v === "import" || v === "health") { setView("settings"); return; }719        if (v === "export") { handleExportBack(); return; }720        if (v === "chirp-sync") { setView("settings"); return; }721      }722723      // Bindings-driven dispatch. Single-key letter bindings without724      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is725      // inside an input, so users can type into search/forms normally.726      const bindings = shortcutBindings();727      for (const action of Object.keys(bindings) as ShortcutAction[]) {728        const binding = bindings[action];729        if (!matchKeybinding(e, binding)) continue;730        // Single-key letter bindings need the input-focus guard. Bindings731        // with any modifier are safe — Ctrl+L doesn't conflict with typing.732        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;733        if (!hasMod && binding.key.length === 1 && inInput) return;734        if (ENTRY_SCOPED.has(action) && v !== "entry") return;735        e.preventDefault();736        SHORTCUT_HANDLERS[action]?.();737        return;738      }739740      // Type-to-search: in entry view, any printable key not consumed by a741      // shortcut above primes the list search seed and opens the list.742      // Kept outside the bindings table because it's a behavior, not a743      // discrete action — every printable character can trigger it.744      if (v === "entry" && !inInput && isPrintableSearchKey) {745        e.preventDefault();746        primeListSearch(e.key);747        return;748      }749    };750    window.addEventListener("keydown", handleGlobalKeydown);751    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));752753    const handleStorageChanged = (754      changes: Record<string, chrome.storage.StorageChange>,755      areaName: string756    ) => {757      if (areaName !== "session") return;758      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {759        return;760      }761      void refreshPendingPasskey();762    };763    chrome.storage.onChanged.addListener(handleStorageChanged);764    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));765  });766767  async function refreshCurrentTab() {768    try {769      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });770      const url = tab?.url ?? tab?.pendingUrl ?? "";771      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");772      // Skip extension/internal URLs — adding chrome://, about:, or773      // chrome-extension:// to a vault entry is never what the user wants.774      const isWebUrl = /^https?:\/\//i.test(url);775      setCurrentTabUrl(isWebUrl ? url : "");776    } catch {777      setCurrentTabDomain("");778      setCurrentTabUrl("");779    }780  }781782  async function refreshPendingPasskey() {783    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });784    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);785  }786787  async function refreshProStatus() {788    const res = await sendMessage({ type: "GET_LICENSE" });789    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;790    setProStatus(Boolean(data?.valid && data?.plan === "pro"));791  }792793  async function restoreSettings() {794    const res = await sendMessage({ type: "GET_SETTINGS" });795    const s = (res as { ok: boolean; data?: any }).data ?? {};796    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {797      setAccentColor(s.accentColor as AccentColorName);798    }799    setTheme(s.theme === "light" ? "light" : "dark");800    if (s.textSize === "small" || s.textSize === "large") {801      setTextSize(s.textSize);802    } else {803      setTextSize("medium");804    }805    setReduceMotion(s.reduceMotion === true);806    setLockOnClose(s.lockOnClose !== false);807    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);808    setBreachMonitoring(s.breachMonitoring !== false);809    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);810    setShortcutBindings(getActiveBindings(s.shortcuts));811  }812813  async function applyTrashRetention(days: number) {814    setTrashRetentionDays(days);815    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });816  }817818  function primeListSearch(seed: string) {819    setListSearchSeed(seed);820    setListSearchSeedNonce((value) => value + 1);821    openList();822  }823824  // Returns null when it detected a dead service worker and triggered handleLock().825  // Callers that need to abort (e.g. openVault) check for null rather than relying826  // on view() state, which may already be "lock" during normal startup flows.827  async function loadEntries(): Promise<VaultEntry[] | null> {828    const response = await sendMessage({ type: "GET_ENTRIES" });829    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };830831    // If the service worker was killed and restarted (MV3 workers sleep), the832    // vault will be locked again — or the worker may not respond at all.833    // In either case, send the user to the lock screen rather than silently834    // showing an empty vault (which looks like data loss).835    if (!res.ok) {836      if (837        res.error === "vault_locked" ||838        res.error === "SERVICE_WORKER_UNAVAILABLE" ||839        (typeof res.error === "string" && res.error.includes("locked"))840      ) {841        handleLock();842        return null; // signal emergency lock to callers843      }844      return [];845    }846847    const loadedEntries = res.data ?? [];848    setEntries(loadedEntries);849850    const currentId = selectedEntry()?.id;851    if (currentId) {852      setSelectedEntry(853        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null854      );855    }856857    return loadedEntries;858  }859860  async function openVault(preferredEntryId?: string, skipViewSet = false) {861    // Purge expired trash entries on each vault open862    const retDays = trashRetentionDays();863    if (retDays > 0) {864      void sendMessage({865        type: "PURGE_EXPIRED_TRASH",866        payload: { retentionMs: retDays * 86_400_000 },867      });868    }869870    const loadedEntries = await loadEntries();871872    // null means loadEntries() triggered an emergency lock (service worker died).873    // Don't override it by setting view back to "entry" with an empty vault.874    if (loadedEntries === null) return;875876    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry877    let nextSelectedEntry: VaultEntry | null = null;878    if (preferredEntryId) {879      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;880    }881    if (!nextSelectedEntry) {882      const tabDomain = currentTabDomain();883      if (tabDomain) {884        nextSelectedEntry = loadedEntries.find((e) => {885          if (e.type === "login") {886            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;887            for (const extra of e.additionalUrls ?? []) {888              if ((extractDomain(extra) ?? "") === tabDomain) return true;889            }890            return false;891          }892          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;893          return false;894        }) ?? null;895      }896    }897    nextSelectedEntry ??= loadedEntries[0] ?? null;898899    setSelectedEntry(nextSelectedEntry);900    setEditEntry(undefined);901    setContentTransitioning(false);902    setContentPhase("enter");903    queueContentIdle();904    if (!skipViewSet) setView("entry");905  }906907  async function handleUnlock() {908    // If the user previously created a vault but hadn't yet confirmed their909    // recovery words (and the browser was closed before they could), the910    // peach_recovery_pending flag is still set in storage.local. Re-route911    // back to the recovery surface so they finish the confirmation step912    // before reaching the entries view — the words can be re-derived now913    // that the vault is unlocked again.914    let recoveryPending = false;915    try {916      const out = await chrome.storage.local?.get("peach_recovery_pending");917      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";918    } catch { /* best-effort */ }919    if (recoveryPending) {920      setForceRecoveryWords(true);921      setView("lock");922      triggerPipPulse();923      await restoreSettings();924      return;925    }926    setHasVault(true);927    triggerPipPulse();928    await restoreSettings();929    const celebrating = pendingCelebration();930    if (celebrating) {931      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });932      setPendingCelebration(false);933    }934    await openVault(undefined, celebrating);935    if (celebrating) {936      setView("pro-celebration");937      window.setTimeout(() => setView("entry"), 2500);938    }939  }940941  function handleSelectEntry(entry: VaultEntry) {942    if (entry.type === "note") {943      setOpenNoteId(entry.id);944      setShowNotes(true);945      return;946    }947    setSelectedEntry(entry);948    setContentTransitioning(false);949    setContentPhase("enter");950    queueContentIdle();951    setView("entry");952  }953954  function handleAdd() {955    setEditEntry(undefined);956    setView("add");957  }958959  async function handleDelete() {960    const entry = selectedEntry();961    if (!entry) return;962    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });963    const loadedEntries = await loadEntries() ?? [];964    setSelectedEntry(loadedEntries[0] ?? null);965    setView("entry");966  }967968  async function handleDeleteMany(ids: string[]) {969    for (const id of ids) {970      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });971    }972    const loadedEntries = await loadEntries() ?? [];973    // If the currently selected entry was among the deleted, move to first974    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);975    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);976  }977978  async function handleSave(savedEntry?: VaultEntry) {979    await openVault(savedEntry?.id);980  }981982  function handleBack() {983    const dest = editBackView();984    setEditBackView("entry");985    setEditEntry(undefined);986    setView(dest);987  }988989  function handleExportBack() {990    if (returnToPanic()) {991      setReturnToPanic(false);992      setView("panic");993      return;994    }995    setView("settings");996  }997998  function handleLock() {999    clearCanarySuppressions();1000    setEntries([]);1001    setSelectedEntry(null);1002    setEditEntry(undefined);1003    setContentPhase("idle");1004    setView("lock");1005  }10061007  function handleHeaderLock() {1008    // Lock the UI immediately — do not wait for the service worker. If the SW1009    // is dead or slow, the 5s sendMessage timeout would create a dead-click1010    // window. The SW will lock on its next wake regardless.1011    handleLock();1012    void sendMessage({ type: "LOCK" });1013  }10141015  function navigate(dir: number) {1016    const allEntries = entries();1017    if (allEntries.length === 0) return;1018    const currentIndex = selectedIndex();1019    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1020    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1021    setSelectedEntry(allEntries[nextIndex]);1022    setContentPhase("enter");1023    queueContentIdle();1024  }10251026  function openList() {1027    setView("list");1028  }10291030  function openHealth() {1031    setEditEntry(undefined);1032    setView("health");1033  }10341035  function handleOpenFileImport() {1036    setRestoreView("file");1037  }10381039  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10401041  function handleFixEntry(entry: VaultEntry) {1042    setSelectedEntry(entry);1043    // Passkey-only entries have no editable surface — drop into view mode1044    // instead of opening the Add editor.1045    if (isPasskeyOnly(entry)) {1046      setView("entry");1047      return;1048    }1049    setEditBackView(view()); // preserve caller view so back returns here1050    setEditEntry(entry);1051    setView("add");1052  }10531054  const isLockedView = () => view() === "lock";10551056  async function handleApprovePendingPasskey() {1057    const pending = pendingPasskey();1058    if (!pending) return;1059    if (pending.browser === "firefox" && pending.type === "create") {1060      // Firefox path: popup itself runs navigator.credentials.create. The1061      // background never approved/rejected anything — it just stashed1062      // intent. After the popup-driven flow resolves (success or cancel),1063      // clear the pending key so the popup doesn't re-show this on next open.1064      const { createFirefoxPasskey } = await import("./firefox-passkey");1065      const result = await createFirefoxPasskey(pending);1066      if (!result.ok) {1067        console.warn("Peach Firefox passkey create failed:", result.error);1068      }1069      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1070      setPendingPasskey(null);1071      void loadEntries();1072      window.close();1073      return;1074    }1075    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1076    window.close();1077  }10781079  async function handleDenyPendingPasskey() {1080    const pending = pendingPasskey();1081    if (!pending) return;1082    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1083    window.close();1084  }10851086  function queueContentIdle(after?: () => void) {1087    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1088    contentPhaseTimer = window.setTimeout(() => {1089      setContentPhase("idle");1090      after?.();1091    }, ENTRY_TRANSITION_SETTLE_MS);1092  }10931094  return (1095    <div class="popup-root peach-theme">1096      <Show when={bootState() === "ready"}>1097        <Show1098          when={!pendingPasskey()}1099          fallback={1100            <PasskeyApprovalView1101              type={pendingPasskey()!.type}1102              rpName={pendingPasskey()!.rpName}1103              rpId={pendingPasskey()!.rpId}1104              userName={pendingPasskey()!.userName}1105              userDisplayName={pendingPasskey()!.userDisplayName}1106              onApprove={handleApprovePendingPasskey}1107              onDeny={handleDenyPendingPasskey}1108            />1109          }1110        >1111          <Show1112            when={!isLockedView()}1113            fallback={1114              <Show1115                when={onboarded() || hasVault()}1116                fallback={1117                  <Onboarding1118                    onComplete={() => { setOnboarded(true); }}1119                  />1120                }1121              >1122                <LockView1123                  hasVault={hasVault()}1124                  ready={bootState() === "ready"}1125                  isPro={proStatus()}1126                  forceRecoveryWords={forceRecoveryWords()}1127                  onUnlock={() => {1128                    // RecoveryWordDisplay clears the storage flag before1129                    // calling onDone, so handleUnlock will see no pending1130                    // confirmation and proceed through the normal path.1131                    if (forceRecoveryWords()) setForceRecoveryWords(false);1132                    return handleUnlock();1133                  }}1134                  onBackToOnboarding={1135                    !hasVault()1136                      ? () => setOnboarded(false)1137                      : undefined1138                  }1139                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1140                />1141              </Show>1142            }1143          >1144            <Show1145              when={view() !== "pro-celebration"}1146              fallback={<ProCelebration />}1147            >1148            <section1149              id="hd-shell"1150              class="peach-shell peach-theme"1151              data-surface="extension"1152            >1153            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1154              <PeachWordmark unlocked />1155              <div class="peach-chrome-actions">1156                <button1157                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1158                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1159                  aria-label="Notes"1160                  title="Notes"1161                >1162                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1163                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1164                    <line x1="4" y1="5" x2="10" y2="5" />1165                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1166                    <line x1="4" y1="10" x2="7" y2="10" />1167                  </svg>1168                </button>1169                <button1170                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1171                  onClick={() => setView("settings")}1172                  aria-label="Settings"1173                >1174                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1175                    <path1176                      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"1177                      stroke="currentColor"1178                      stroke-width="0.9"1179                    />1180                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1181                  </svg>1182                </button>1183                <button1184                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1185                  onClick={handleAdd}1186                  aria-label="New entry"1187                >1188                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1189                    <path d="M5.5 1v9M1 5.5h9" />1190                  </svg>1191                </button>1192                <button1193                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1194                  onClick={() => void handleHeaderLock()}1195                  aria-label="Lock vault"1196                >1197                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1198                    <path1199                      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"1200                      stroke="currentColor"1201                      stroke-width="1"1202                      stroke-linecap="round"1203                    />1204                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1205                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1206                  </svg>1207                </button>1208              </div>1209            </header>12101211            <Show when={pendingProNotice() !== null}>1212              <div class="peach-pro-notice-banner">1213                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1214                <button1215                  class="peach-pro-notice-link"1216                  onClick={() => {1217                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1218                    setSettingsInitialSection("license");1219                    setView("settings");1220                    setPendingProNotice(null);1221                  }}1222                >1223                  Learn more →1224                </button>1225                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1226              </div>1227            </Show>12281229            <div class="peach-shell-body">1230              <div class="peach-shell-veil"></div>1231              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1232                <EntryView1233                  entry={selectedEntry()}1234                  currentTabUrl={currentTabUrl()}1235                  entries={entries()}1236                  isPro={proStatus()}1237                  onDelete={handleDelete}1238                  onFieldSaved={() => void loadEntries()}1239                  onEscape={() => { setView("list"); }}1240                  onProGate={(feature) => {1241                    setUpgradeHighlight(feature);1242                    setSettingsInitialSection("license");1243                    setView("settings");1244                  }}1245                />1246              </div>12471248              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1249                <div class="peach-search-bar">1250                  <span class="peach-search-icon">1251                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1252                      <circle cx="5.5" cy="5.5" r="3.75" />1253                      <path d="M8.75 8.75L11.5 11.5" />1254                    </svg>1255                  </span>1256                  <input1257                    class="peach-search-input"1258                    placeholder="search vault..."1259                    autocomplete="off"1260                    aria-label="Search vault entries"1261                    onClick={openList}1262                    onFocus={openList}1263                    readOnly1264                  />1265                  <div class="peach-search-meta">1266                    <span class="peach-search-counter">1267                      {entries().length > 01268                        ? `${selectedIndex() + 1} / ${entries().length}`1269                        : "0 entries"}1270                    </span>1271                    <span class="peach-divider"></span>1272                    <button1273                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1274                      onClick={() => navigate(-1)}1275                      aria-label="Previous entry"1276                      disabled={entries().length === 0}1277                    >1278                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1279                        <path d="M5 1L1 5.5L5 10" />1280                      </svg>1281                    </button>1282                    <button1283                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1284                      onClick={() => navigate(1)}1285                      aria-label="Next entry"1286                      disabled={entries().length === 0}1287                    >1288                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1289                        <path d="M1 1L5 5.5L1 10" />1290                      </svg>1291                    </button>1292                  </div>1293                </div>1294              </section>1295            </div>12961297            {/* Desktop: shown on demand via Show. Native sheet is rendered1298                via Portal below at the document root so its position:fixed1299                isn't trapped by .peach-shell's transform-based animations. */}1300            <Show when={!isNativePlatform() && view() === "list"}>1301              <VaultView1302                entries={entries()}1303                selectedEntryId={selectedEntry()?.id}1304                currentTabDomain={currentTabDomain()}1305                sortOrder={sortOrder()}1306                searchSeed={listSearchSeed()}1307                searchSeedNonce={listSearchSeedNonce()}1308                onSelectEntry={handleSelectEntry}1309                onSortOrderChange={setSortOrder}1310                onAdd={handleAdd}1311                onClose={() => setView("entry")}1312                onOpenTrash={() => setView("trash")}1313                onDeleteMany={handleDeleteMany}1314              />1315            </Show>1316            <Show when={isNativePlatform() && hasVault()}>1317              <Portal>1318                <div1319                  class="peach-vault-sheet"1320                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1321                  style={(() => {1322                    const live = sheetTranslate();1323                    if (live === null) return undefined;1324                    return { transform: `translateY(${live}px)` };1325                  })()}1326                >1327                  <VaultView1328                    entries={entries()}1329                    selectedEntryId={selectedEntry()?.id}1330                    currentTabDomain={currentTabDomain()}1331                    sortOrder={sortOrder()}1332                    searchSeed={listSearchSeed()}1333                    searchSeedNonce={listSearchSeedNonce()}1334                    isNative={true}1335                    onSelectEntry={handleSelectEntry}1336                    onSortOrderChange={setSortOrder}1337                    onAdd={handleAdd}1338                    onClose={() => setView("entry")}1339                    onOpenTrash={() => setView("trash")}1340                    onDeleteMany={handleDeleteMany}1341                  />1342                </div>1343              </Portal>1344            </Show>1345            <Show when={view() === "settings" || settingsExiting()}>1346              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1347                <SettingsView1348                  entriesCount={entries().length}1349                  breachMonitoring={breachMonitoring()}1350                  lockOnClose={lockOnClose()}1351                  autoLockMinutes={autoLockMinutes()}1352                  trashRetentionDays={trashRetentionDays()}1353                  theme={theme()}1354                  accentColor={accentColor()}1355                  textSize={textSize()}1356                  reduceMotion={reduceMotion()}1357                  isPro={proStatus()}1358                  initialSection={settingsInitialSection()}1359                  upgradeHighlight={upgradeHighlight()}1360                  isExiting={settingsExiting()}1361                  onBreachMonitoringChange={applyBreachMonitoring}1362                  onLockOnCloseChange={applyLockOnClose}1363                  onAutoLockMinutesChange={applyAutoLockMinutes}1364                  onTrashRetentionChange={applyTrashRetention}1365                  onThemeChange={applyTheme}1366                  onAccentChange={applyAccentColor}1367                  onTextSizeChange={applyTextSize}1368                  onReduceMotionChange={applyReduceMotion}1369                  shortcuts={shortcutBindings()}1370                  onShortcutsChange={applyShortcuts}1371                  onLicenseChange={async () => {1372                    // After activation/deactivation: refresh Pro status,1373                    // re-load entries (defensive — signal state can drift if1374                    // the SW briefly restarts during the verify+save round-trip),1375                    // and replay the Pro celebration if this is the first time1376                    // a valid Pro license is seen on this device.1377                    await refreshProStatus();1378                    void loadEntries();1379                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1380                    if ((should as { ok: boolean; data?: boolean }).data === true) {1381                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1382                      setView("pro-celebration");1383                      window.setTimeout(() => setView("settings"), 2500);1384                    }1385                  }}1386                  onBack={() => {1387                    setSettingsExiting(true);1388                    window.setTimeout(() => {1389                      setSettingsExiting(false);1390                      setSettingsInitialSection(null);1391                      setUpgradeHighlight(null);1392                      handleBack();1393                    }, 200);1394                  }}1395                  onImport={() => setView("import")}1396                  onExport={() => setView("export")}1397                  onBreachCheckDone={loadEntries}1398                  onOpenHealth={openHealth}1399                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("chirp-sync"); }}1400                  onOpenFileImport={handleOpenFileImport}1401                  onOpenPanic={() => setView("panic")}1402                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1403                  onOpenCodexRestore={() => setView("codex-restore")}1404                  onCardChange={setSettingsActiveCard}1405                  onProGate={(feature) => {1406                    setUpgradeHighlight(feature);1407                    setSettingsInitialSection("license");1408                  }}1409                />1410              </Suspense>1411            </Show>1412            <Show when={view() === "codex-generate"}>1413              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1414                <CodexGenerateView1415                  isPro={proStatus()}1416                  onBack={() => setView("settings")}1417                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1418                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1419                  onVaultLocked={() => handleLock()}1420                />1421              </Suspense>1422            </Show>1423            <Show when={view() === "codex-restore"}>1424              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1425                <CodexRestoreView1426                  onBack={() => setView("lock")}1427                  onRestoreSuccess={async () => {1428                    // After restore the vault is unlocked; refresh entries1429                    // and route to the main vault list. handleUnlock is the1430                    // canonical post-unlock setup path.1431                    await handleUnlock();1432                  }}1433                />1434              </Suspense>1435            </Show>1436            <Show when={view() === "chirp-sync"}>1437              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1438                <ChirpSyncView1439                  isPro={proStatus()}1440                  onBack={() => setView("settings")}1441                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1442                />1443              </Suspense>1444            </Show>1445            <Show when={view() === "add"}>1446              <AddView1447                entry={editEntry()}1448                entries={entries()}1449                onBack={handleBack}1450                onSave={handleSave}1451              />1452            </Show>1453            <Show when={view() === "import"}>1454              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1455                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1456              </Suspense>1457            </Show>1458            <Show when={view() === "export"}>1459              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1460                <ExportView onBack={handleExportBack} />1461              </Suspense>1462            </Show>1463            <Show when={view() === "panic"}>1464              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1465                <PanicView1466                  onCancel={() => setView("settings")}1467                  onOpenExport={() => {1468                    setReturnToPanic(true);1469                    setView("export");1470                  }}1471                  onDestroyed={async () => {1472                    clearCanarySuppressions();1473                    setEntries([]);1474                    setSelectedEntry(null);1475                    setEditEntry(undefined);1476                    setHasVault(false);1477                    setOnboarded(false);1478                    setProStatus(false);1479                    setPendingPasskey(null);1480                    setUpgradeHighlight(null);1481                    setSettingsInitialSection(null);1482                    setPendingProNotice(null);1483                    setPendingCelebration(false);1484                    setReturnToPanic(false);1485                    setContentPhase("idle");1486                    setView("lock");1487                  }}1488                />1489              </Suspense>1490            </Show>1491            <Show when={view() === "health"}>1492              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1493                <HealthView1494                  entries={entries()}1495                  isPro={proStatus()}1496                  onFixEntry={handleFixEntry}1497                  onBack={() => setView("settings")}1498                  onRefresh={loadEntries}1499                />1500              </Suspense>1501            </Show>1502            <Show when={view() === "trash"}>1503              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1504                <TrashView1505                  onBack={() => setView("list")}1506                  onRestored={() => void loadEntries()}1507                />1508              </Suspense>1509            </Show>1510            <Show when={showNotes()}>1511              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1512                <NotesMode1513                  notes={entries().filter((e) => e.type === "note")}1514                  initialNoteId={openNoteId()}1515                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1516                  onNoteListChanged={() => void loadEntries()}1517                />1518              </div>1519            </Show>1520            <Show when={restoreView() === "file"}>1521              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1522                <ImportView1523                  mode="onboarding"1524                  replacesExistingVault={true}1525                  onBack={() => setRestoreView(null)}1526                  onImport={async () => {1527                    setRestoreView(null);1528                    await handleUnlock();1529                  }}1530                />1531              </Suspense>1532            </Show>1533            </section>1534            </Show>1535          </Show>1536        </Show>1537      </Show>1538      <Show when={showShortcutsHelp()}>1539        <ShortcutsHelpOverlay1540          bindings={shortcutBindings()}1541          onClose={() => setShowShortcutsHelp(false)}1542        />1543      </Show>1544    </div>1545  );1546}15471548function ShortcutsHelpOverlay(props: {1549  bindings: Record<ShortcutAction, Keybinding>;1550  onClose: () => void;1551}) {1552  return (1553    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1554      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1555        <div class="peach-shortcuts-help-head">1556          <h3>Keyboard shortcuts</h3>1557          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1558        </div>1559        <div class="peach-shortcuts-help-body">1560          <p class="peach-settings-sub-label">ENTRY VIEW</p>1561          <ul>1562            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1563              <li>1564                <span>{d.label}</span>1565                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1566              </li>1567            ))}1568          </ul>1569          <p class="peach-settings-sub-label">ANYWHERE</p>1570          <ul>1571            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1572              <li>1573                <span>{d.label}</span>1574                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1575              </li>1576            ))}1577          </ul>1578        </div>1579      </div>1580    </div>1581  );1582}