App.tsx

66.0 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    // Small zoom shrinks the html element itself, leaving a black strip in the232    // already-open popup frame. Reload so Chrome measures fresh 294px dimensions.233    if (size === "small" && chrome.storage.session) {234      await chrome.storage.session.set({235        peach_size_restore: {236          view: view(),237          entryId: selectedEntry()?.id ?? null,238          settingsCard: settingsActiveCard(),239        },240      });241      window.location.reload();242    }243  }244245  async function applyReduceMotion(enabled: boolean) {246    setReduceMotion(enabled);247    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });248  }249250  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload251  // small and lets future default updates land for actions the user hasn't252  // touched. Settings sends us the full active map; we filter and store.253  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {254    setShortcutBindings(active);255    const overrides: Record<string, Keybinding> = {};256    for (const action of Object.keys(active) as ShortcutAction[]) {257      const a = active[action];258      const d = DEFAULT_BINDINGS[action];259      const same = a.key === d.key260        && Boolean(a.ctrl)  === Boolean(d.ctrl)261        && Boolean(a.meta)  === Boolean(d.meta)262        && Boolean(a.shift) === Boolean(d.shift)263        && Boolean(a.alt)   === Boolean(d.alt);264      if (!same) overrides[action] = a;265    }266    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });267  }268269  async function applyLockOnClose(enabled: boolean) {270    setLockOnClose(enabled);271    await sendMessage({272      type: "UPDATE_SETTINGS",273      payload: { lockOnClose: enabled },274    });275  }276277  async function applyAutoLockMinutes(minutes: number) {278    setAutoLockMinutes(minutes);279    await sendMessage({280      type: "UPDATE_SETTINGS",281      payload: { autoLockMinutes: minutes },282    });283  }284285  async function applyBreachMonitoring(enabled: boolean) {286    setBreachMonitoring(enabled);287    await sendMessage({288      type: "UPDATE_SETTINGS",289      payload: { breachMonitoring: enabled },290    });291  }292293  onMount(async () => {294    // Resolve the active tab in parallel with the unlock/has-vault queries —295    // openVault()'s smart selection picks the entry matching currentTabDomain,296    // so it must be populated before openVault runs. Previously refreshCurrentTab297    // ran after openVault, leaving popups that booted already-unlocked falling298    // back to loadedEntries[0] instead of the domain match.299    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([300      sendMessage({ type: "IS_UNLOCKED" }),301      sendMessage({ type: "HAS_VAULT" }),302      refreshCurrentTab(),303      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),304    ]);305    const unlocked = Boolean(306      (unlockResponse as { ok: boolean; data?: boolean }).data307    );308    const vaultExists = Boolean(309      (vaultResponse as { ok: boolean; data?: boolean }).data310    );311    const shouldCelebrate = Boolean(312      (celebrationResponse as { ok: boolean; data?: boolean }).data313    );314    setHasVault(vaultExists);315    // Onboarding gate — show once on first install, never again. Existing316    // users (vaultExists) are auto-marked onboarded so they skip the flow317    // even on the very first popup open after this feature ships.318    try {319      const onboarded = await storageGet("peach_onboarded");320      const seen = onboarded === "true";321      if (vaultExists && !seen) {322        await storageSet("peach_onboarded", "true");323        setOnboarded(true);324      } else {325        setOnboarded(seen);326      }327    } catch {328      // storage unavailable — default to onboarded so we never block boot329      setOnboarded(true);330    }331    await Promise.all([restoreSettings(), refreshProStatus()]);332333    // Mark played before any animation so a crash mid-sequence never replays it334    if (shouldCelebrate) {335      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });336    }337338    // If the user created a vault but hasn't yet confirmed their recovery339    // words, route back to the recovery-words screen instead of opening the340    // entries view. The flag lives in chrome.storage.local so it survives341    // both popup close (SW suppresses lock-on-close) and full browser342    // restart (handleUnlock checks the same flag after a fresh password343    // unlock). Cleared when confirmation succeeds.344    let recoveryPending = false;345    try {346      const out = await chrome.storage.local?.get("peach_recovery_pending");347      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";348    } catch { /* best-effort */ }349350    // Native: closing the app before recovery-words confirmation means the351    // user didn't finish vault creation. Throw the partial vault away and352    // restart onboarding rather than asking them to unlock a vault they353    // never finished creating. Desktop keeps the existing "unlock to354    // resume" flow because closing the popup there is much more casual.355    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {356      try {357        await chrome.storage.local?.remove([358          "peach_vault_a",359          "peach_vault_b",360          "peach_recovery_pending",361          "peach_onboarded",362          "peach_vault_history",363        ]);364      } catch { /* best-effort */ }365      setHasVault(false);366      setOnboarded(false);367      setView("lock");368      setBootState("ready");369      document.getElementById("pre-lock")?.setAttribute("hidden", "true");370      return;371    }372373    if (recoveryPending && unlocked) {374      // forceRecoveryWords overrides LockView's hasVault gate so the375      // recovery surface renders even though the vault now exists.376      setForceRecoveryWords(true);377      setView("lock");378    } else if (unlocked && vaultExists) {379      await openVault(undefined, shouldCelebrate);380      if (shouldCelebrate) {381        setView("pro-celebration");382        window.setTimeout(() => setView("entry"), 2500);383      }384    } else if (shouldCelebrate) {385      setPendingCelebration(true);386    }387388    await refreshPendingPasskey();389390    // Track tab changes so smart sort stays current391    const handleTabActivated = () => { void refreshCurrentTab(); };392    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {393      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();394    };395    try {396      chrome.tabs.onActivated.addListener(handleTabActivated);397      chrome.tabs.onUpdated.addListener(handleTabUpdated);398      onCleanup(() => {399        chrome.tabs.onActivated.removeListener(handleTabActivated);400        chrome.tabs.onUpdated.removeListener(handleTabUpdated);401      });402    } catch {403      // tabs permission may not be available in all contexts404    }405406    setBootState("ready");407    document.getElementById("pre-lock")?.setAttribute("hidden", "true");408409    // Check for pending session-storage notices from the background.410    if (chrome.storage.session) {411      const session = await chrome.storage.session.get([412        "pendingProGate",413        "pendingProNotice",414        "peach_size_restore",415      ]) as Record<string, unknown>;416      const proGate = session.pendingProGate as { feature?: string } | undefined;417      const proNotice = session.pendingProNotice as { feature?: string } | undefined;418      if (proGate?.feature) {419        await chrome.storage.session.remove("pendingProGate");420        setUpgradeHighlight((proGate.feature as ProFeature) ?? null);421        setSettingsInitialSection("license");422        setView("settings");423      } else if (proNotice?.feature) {424        await chrome.storage.session.remove("pendingProNotice");425        setPendingProNotice({ feature: proNotice.feature ?? "" });426      }427      const r = session.peach_size_restore as428        { view: View; entryId: string | null; settingsCard: string } | undefined;429      if (r) {430        await chrome.storage.session.remove("peach_size_restore");431        if (r.settingsCard) setSettingsActiveCard(r.settingsCard);432        if (r.view === "settings") {433          setView("settings");434        } else if (r.view === "entry" && r.entryId) {435          const entry = entries().find((e) => e.id === r.entryId);436          if (entry) { setSelectedEntry(entry); setView("entry"); }437        } else if (r.view !== "lock") {438          setView(r.view);439        }440      }441    }442443    // Warm the lazy-module cache so the Suspense fallback never shows for444    // locally-bundled extension views. Without this, the first navigation to445    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which446    // covers the shell and absorbs clicks on the header.447    void Promise.all([448      import("./views/Settings").catch(() => {}),449      import("./views/Import").catch(() => {}),450      import("./views/Export").catch(() => {}),451      import("./views/Health").catch(() => {}),452      import("./views/TrashView").catch(() => {}),453    ]);454455    // Lock-on-close via a persistent port. sendMessage in pagehide is456    // unreliable — the popup context tears down before the message lands.457    // The SW's onConnect listener locks when this port disconnects.458    let popupPort: chrome.runtime.Port | null = null;459    try {460      popupPort = chrome.runtime.connect({ name: "popup" });461    } catch { /* extension context invalidated — ignore */ }462    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });463464    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only465    // reliable signal is appStateChange — setTimeout is killed when the OS466    // backgrounds the app. We measure elapsed background time on resume.467    if (isNativePlatform()) {468      let backgroundedAt: number | null = null;469470      const CapApp = nativePlugin<{471        addListener: (472          ev: string,473          cb: (s: { isActive: boolean }) => void,474        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };475      }>("App");476      if (CapApp?.addListener) {477        const sub = CapApp.addListener(478          "appStateChange",479          ({ isActive }: { isActive: boolean }) => {480            if (!isActive) {481              backgroundedAt = Date.now();482              return;483            }484            if (backgroundedAt !== null && autoLockMinutes() > 0) {485              const elapsed = Date.now() - backgroundedAt;486              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();487            }488            backgroundedAt = null;489          }490        );491        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.492        onCleanup(() => {493          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});494        });495      }496497      // L12/COR-011: foreground idle autolock. appStateChange only fires when498      // the OS backgrounds the app — if the user idles with the screen on,499      // chrome.alarms is no-op'd in Capacitor so the vault would stay open500      // indefinitely. Poll every 30s and lock if elapsed since last user501      // interaction exceeds autoLockMinutes.502      let lastUserActivityAt = Date.now();503      const bumpActivity = () => { lastUserActivityAt = Date.now(); };504      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;505      for (const ev of ACTIVITY_EVENTS) {506        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });507      }508      const idleLockInterval = setInterval(() => {509        const minutes = autoLockMinutes();510        if (!minutes || minutes <= 0) return;511        const elapsed = Date.now() - lastUserActivityAt;512        if (elapsed >= minutes * 60_000) {513          lastUserActivityAt = Date.now();514          handleHeaderLock();515        }516      }, 30_000);517      onCleanup(() => {518        clearInterval(idleLockInterval);519        for (const ev of ACTIVITY_EVENTS) {520          document.removeEventListener(ev, bumpActivity, { capture: true });521        }522      });523    }524525    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale526    // entries instead of waiting for the next GET_ENTRIES round-trip.527    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {528      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();529      if (msg?.type === "PRO_GATE_TRIGGERED") {530        setUpgradeHighlight(msg.payload?.feature ?? null);531        setSettingsInitialSection("license");532        setView("settings");533      }534    };535    chrome.runtime.onMessage.addListener(handleRuntimeMessage);536    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));537538    // Android hardware/gesture back. MainActivity fires peach:back; the popup539    // decides what "back" means per surface. Lock+no-vault is the common case540    // — return to onboarding rather than letting the OS dismiss the activity.541    const handlePeachBack = () => {542      // Notes mode captures back first543      if (showNotes()) {544        setShowNotes(false);545        setOpenNoteId(undefined);546        return;547      }548      const v = view();549      if (v === "lock" && !hasVault() && onboarded()) {550        setOnboarded(false);551        return;552      }553      if (v === "list") { setView("entry"); return; }554      if (v === "settings") {555        window.dispatchEvent(new Event("peach:settings-back"));556        return;557      }558      if (v === "import" || v === "health") { setView("settings"); return; }559      if (v === "export") { handleExportBack(); return; }560      if (v === "add") { handleBack(); return; }561      if (v === "chirp-sync") { setView("settings"); return; }562    };563    window.addEventListener("peach:back", handlePeachBack);564    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));565566    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that567    // peeks from the bottom (search bar handle visible) and drags up to fill568    // the screen. dragOffset is the LIVE finger offset during a drag, in px,569    // 0 when no drag in progress. The wrapper element computes transform =570    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.571    if (isNativePlatform()) {572      let touchStartY = 0;573      let touchStartX = 0;574      let lastY = 0;575      let lastT = 0;576      let dragging = false;577      let captured = false;578      const HORIZONTAL_TOLERANCE = 16;579      const ACTIVATION_DY = 8;580      const PEEK_PX = 60;581582      const onTouchStart = (e: TouchEvent) => {583        const t = e.touches[0];584        if (!t) return;585        const v = view();586        if (v !== "entry" && v !== "list") return;587        // Entry view: only intercept drags starting in the bottom 40%.588        // List view: intercept drags starting in the top 35% (the search/handle row).589        const inBand = v === "entry"590          ? t.clientY > window.innerHeight * 0.6591          : t.clientY < window.innerHeight * 0.35;592        if (!inBand) return;593        touchStartY = lastY = t.clientY;594        touchStartX = t.clientX;595        lastT = e.timeStamp;596        dragging = true;597        captured = false;598      };599600      const onTouchMove = (e: TouchEvent) => {601        if (!dragging) return;602        const t = e.touches[0];603        if (!t) return;604        const dy = t.clientY - touchStartY;605        const dx = Math.abs(t.clientX - touchStartX);606607        if (!captured) {608          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {609            // Looks like a horizontal swipe — release.610            dragging = false;611            return;612          }613          if (Math.abs(dy) < ACTIVATION_DY) return;614          captured = true;615        }616617        // Translate the sheet by dy from its rest (peek) position. Peek is618        // (viewport height - PEEK_PX). Open is 0.619        const v = view();620        const restClosed = window.innerHeight - PEEK_PX;621        const baseTranslate = v === "list" ? 0 : restClosed;622        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));623        setSheetTranslate(next);624        lastY = t.clientY;625        lastT = e.timeStamp;626      };627628      const onTouchEnd = (e: TouchEvent) => {629        if (!dragging) { return; }630        const t = e.changedTouches[0];631        const elapsed = Math.max(1, e.timeStamp - lastT);632        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms633        const wasCaptured = captured;634        dragging = false;635        captured = false;636        const v = view();637638        if (!wasCaptured) {639          // Tap in the peek strip while in entry view → open the vault list.640          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");641          setSheetTranslate(null);642          return;643        }644645        const restClosed = window.innerHeight - PEEK_PX;646        const current = sheetTranslate() ?? restClosed;647648        // Snap rules:649        //   - Strong upward velocity → open650        //   - Strong downward velocity → close651        //   - Otherwise snap to whichever rest is closer652        let nextOpen: boolean;653        if (velocity < -0.05) nextOpen = true;654        else if (velocity > 0.05) nextOpen = false;655        else nextOpen = current < restClosed * 0.5;656657        if (nextOpen && v !== "list") setView("list");658        if (!nextOpen && v !== "entry") setView("entry");659        // Release the live offset so CSS transition handles the snap.660        setSheetTranslate(null);661      };662663      document.addEventListener("touchstart", onTouchStart, { passive: true });664      document.addEventListener("touchmove",  onTouchMove,  { passive: true });665      document.addEventListener("touchend",   onTouchEnd,   { passive: true });666      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });667      onCleanup(() => {668        document.removeEventListener("touchstart", onTouchStart);669        document.removeEventListener("touchmove",  onTouchMove);670        document.removeEventListener("touchend",   onTouchEnd);671      });672    }673674    // Action handlers — keyed by ShortcutAction. The dispatcher below tests675    // each binding against the event and runs the matching handler. New676    // shortcuts only need an entry here; the binding is data, not code.677    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {678      copy_password: () => {679        const entry = selectedEntry();680        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });681      },682      copy_username: () => {683        const entry = selectedEntry();684        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });685      },686      copy_totp: () => {687        const entry = selectedEntry();688        if (!entry?.totp) return;689        try {690          const { code } = generateTOTP(entry.totp);691          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });692        } catch { /* invalid TOTP secret — silent */ }693      },694      new_entry: () => handleAdd(),695      edit_entry: () => {696        const entry = selectedEntry();697        // Passkey-only entries have nothing user-editable in the Add view; the698        // passkey credential itself is opaque. Skip the edit action for them.699        if (!entry || isPasskeyOnly(entry)) return;700        setEditEntry(entry);701        setView("add");702      },703      delete_entry: () => {704        if (selectedEntry()) void handleDelete();705      },706      lock_vault: () => { void handleHeaderLock(); },707      search: () => openList(),708      nav_prev: () => navigate(-1),709      nav_next: () => navigate(1),710      jump_vault: () => setView("entry"),711      jump_settings: () => setView("settings"),712      show_help: () => setShowShortcutsHelp(true),713    };714715    // Actions that are MEANINGFUL only on the entry-detail view. Outside716    // that scope the binding is dormant — pressing C while on Settings717    // does nothing rather than awkwardly copying from a now-stale entry.718    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([719      "copy_password", "copy_username", "copy_totp",720      "edit_entry", "delete_entry", "nav_prev", "nav_next",721    ]);722723    const handleGlobalKeydown = (e: KeyboardEvent) => {724      const v = view();725      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"726        || (e.target as HTMLElement)?.tagName === "TEXTAREA"727        || (e.target as HTMLElement)?.isContentEditable;728      const isPrintableSearchKey =729        e.key.length === 1 &&730        !e.ctrlKey &&731        !e.metaKey &&732        !e.altKey;733734      // No input during the pro celebration sequence735      if (v === "pro-celebration") return;736737      // Help dialog: Escape closes it; eat the keypress so it doesn't738      // also navigate away from the underlying view.739      if (showShortcutsHelp()) {740        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }741        return;742      }743744      // ── Escape — fixed binding (not user-customizable) ───────745      if (e.key === "Escape") {746        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }747        if (v === "list") { setView("entry"); return; }748        if (v === "settings" || v === "add") { handleBack(); return; }749        if (v === "import" || v === "health") { setView("settings"); return; }750        if (v === "export") { handleExportBack(); return; }751        if (v === "chirp-sync") { setView("settings"); return; }752      }753754      // Bindings-driven dispatch. Single-key letter bindings without755      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is756      // inside an input, so users can type into search/forms normally.757      const bindings = shortcutBindings();758      for (const action of Object.keys(bindings) as ShortcutAction[]) {759        const binding = bindings[action];760        if (!matchKeybinding(e, binding)) continue;761        // Single-key letter bindings need the input-focus guard. Bindings762        // with any modifier are safe — Ctrl+L doesn't conflict with typing.763        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;764        if (!hasMod && binding.key.length === 1 && inInput) return;765        if (ENTRY_SCOPED.has(action) && v !== "entry") return;766        e.preventDefault();767        SHORTCUT_HANDLERS[action]?.();768        return;769      }770771      // Type-to-search: in entry view, any printable key not consumed by a772      // shortcut above primes the list search seed and opens the list.773      // Kept outside the bindings table because it's a behavior, not a774      // discrete action — every printable character can trigger it.775      if (v === "entry" && !inInput && isPrintableSearchKey) {776        e.preventDefault();777        primeListSearch(e.key);778        return;779      }780    };781    window.addEventListener("keydown", handleGlobalKeydown);782    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));783784    const handleStorageChanged = (785      changes: Record<string, chrome.storage.StorageChange>,786      areaName: string787    ) => {788      if (areaName !== "session") return;789      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {790        return;791      }792      void refreshPendingPasskey();793    };794    chrome.storage.onChanged.addListener(handleStorageChanged);795    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));796  });797798  async function refreshCurrentTab() {799    try {800      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });801      const url = tab?.url ?? tab?.pendingUrl ?? "";802      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");803      // Skip extension/internal URLs — adding chrome://, about:, or804      // chrome-extension:// to a vault entry is never what the user wants.805      const isWebUrl = /^https?:\/\//i.test(url);806      setCurrentTabUrl(isWebUrl ? url : "");807    } catch {808      setCurrentTabDomain("");809      setCurrentTabUrl("");810    }811  }812813  async function refreshPendingPasskey() {814    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });815    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);816  }817818  async function refreshProStatus() {819    const res = await sendMessage({ type: "GET_LICENSE" });820    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;821    setProStatus(Boolean(data?.valid && data?.plan === "pro"));822  }823824  async function restoreSettings() {825    const res = await sendMessage({ type: "GET_SETTINGS" });826    const s = (res as { ok: boolean; data?: any }).data ?? {};827    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {828      setAccentColor(s.accentColor as AccentColorName);829    }830    setTheme(s.theme === "light" ? "light" : "dark");831    if (s.textSize === "small" || s.textSize === "large") {832      setTextSize(s.textSize);833    } else {834      setTextSize("medium");835    }836    setReduceMotion(s.reduceMotion === true);837    setLockOnClose(s.lockOnClose !== false);838    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);839    setBreachMonitoring(s.breachMonitoring !== false);840    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);841    setShortcutBindings(getActiveBindings(s.shortcuts));842  }843844  async function applyTrashRetention(days: number) {845    setTrashRetentionDays(days);846    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });847  }848849  function primeListSearch(seed: string) {850    setListSearchSeed(seed);851    setListSearchSeedNonce((value) => value + 1);852    openList();853  }854855  // Returns null when it detected a dead service worker and triggered handleLock().856  // Callers that need to abort (e.g. openVault) check for null rather than relying857  // on view() state, which may already be "lock" during normal startup flows.858  async function loadEntries(): Promise<VaultEntry[] | null> {859    const response = await sendMessage({ type: "GET_ENTRIES" });860    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };861862    // If the service worker was killed and restarted (MV3 workers sleep), the863    // vault will be locked again — or the worker may not respond at all.864    // In either case, send the user to the lock screen rather than silently865    // showing an empty vault (which looks like data loss).866    if (!res.ok) {867      if (868        res.error === "vault_locked" ||869        res.error === "SERVICE_WORKER_UNAVAILABLE" ||870        (typeof res.error === "string" && res.error.includes("locked"))871      ) {872        handleLock();873        return null; // signal emergency lock to callers874      }875      return [];876    }877878    const loadedEntries = res.data ?? [];879    setEntries(loadedEntries);880881    const currentId = selectedEntry()?.id;882    if (currentId) {883      setSelectedEntry(884        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null885      );886    }887888    return loadedEntries;889  }890891  async function openVault(preferredEntryId?: string, skipViewSet = false) {892    // Purge expired trash entries on each vault open893    const retDays = trashRetentionDays();894    if (retDays > 0) {895      void sendMessage({896        type: "PURGE_EXPIRED_TRASH",897        payload: { retentionMs: retDays * 86_400_000 },898      });899    }900901    const loadedEntries = await loadEntries();902903    // null means loadEntries() triggered an emergency lock (service worker died).904    // Don't override it by setting view back to "entry" with an empty vault.905    if (loadedEntries === null) return;906907    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry908    let nextSelectedEntry: VaultEntry | null = null;909    if (preferredEntryId) {910      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;911    }912    if (!nextSelectedEntry) {913      const tabDomain = currentTabDomain();914      if (tabDomain) {915        nextSelectedEntry = loadedEntries.find((e) => {916          if (e.type === "login") {917            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;918            for (const extra of e.additionalUrls ?? []) {919              if ((extractDomain(extra) ?? "") === tabDomain) return true;920            }921            return false;922          }923          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;924          return false;925        }) ?? null;926      }927    }928    nextSelectedEntry ??= loadedEntries[0] ?? null;929930    setSelectedEntry(nextSelectedEntry);931    setEditEntry(undefined);932    setContentTransitioning(false);933    setContentPhase("enter");934    queueContentIdle();935    if (!skipViewSet) setView("entry");936  }937938  async function handleUnlock() {939    // If the user previously created a vault but hadn't yet confirmed their940    // recovery words (and the browser was closed before they could), the941    // peach_recovery_pending flag is still set in storage.local. Re-route942    // back to the recovery surface so they finish the confirmation step943    // before reaching the entries view — the words can be re-derived now944    // that the vault is unlocked again.945    let recoveryPending = false;946    try {947      const out = await chrome.storage.local?.get("peach_recovery_pending");948      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";949    } catch { /* best-effort */ }950    if (recoveryPending) {951      setForceRecoveryWords(true);952      setView("lock");953      triggerPipPulse();954      await restoreSettings();955      return;956    }957    setHasVault(true);958    triggerPipPulse();959    await restoreSettings();960    const celebrating = pendingCelebration();961    if (celebrating) {962      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });963      setPendingCelebration(false);964    }965    await openVault(undefined, celebrating);966    if (celebrating) {967      setView("pro-celebration");968      window.setTimeout(() => setView("entry"), 2500);969    }970  }971972  function handleSelectEntry(entry: VaultEntry) {973    if (entry.type === "note") {974      setOpenNoteId(entry.id);975      setShowNotes(true);976      return;977    }978    setSelectedEntry(entry);979    setContentTransitioning(false);980    setContentPhase("enter");981    queueContentIdle();982    setView("entry");983  }984985  function handleAdd() {986    setEditEntry(undefined);987    setView("add");988  }989990  async function handleDelete() {991    const entry = selectedEntry();992    if (!entry) return;993    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });994    const loadedEntries = await loadEntries() ?? [];995    setSelectedEntry(loadedEntries[0] ?? null);996    setView("entry");997  }998999  async function handleDeleteMany(ids: string[]) {1000    for (const id of ids) {1001      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1002    }1003    const loadedEntries = await loadEntries() ?? [];1004    // If the currently selected entry was among the deleted, move to first1005    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1006    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1007  }10081009  async function handleSave(savedEntry?: VaultEntry) {1010    await openVault(savedEntry?.id);1011  }10121013  function handleBack() {1014    const dest = editBackView();1015    setEditBackView("entry");1016    setEditEntry(undefined);1017    setView(dest);1018  }10191020  function handleExportBack() {1021    if (returnToPanic()) {1022      setReturnToPanic(false);1023      setView("panic");1024      return;1025    }1026    setView("settings");1027  }10281029  function handleLock() {1030    clearCanarySuppressions();1031    setEntries([]);1032    setSelectedEntry(null);1033    setEditEntry(undefined);1034    setContentPhase("idle");1035    setView("lock");1036  }10371038  function handleHeaderLock() {1039    // Lock the UI immediately — do not wait for the service worker. If the SW1040    // is dead or slow, the 5s sendMessage timeout would create a dead-click1041    // window. The SW will lock on its next wake regardless.1042    handleLock();1043    void sendMessage({ type: "LOCK" });1044  }10451046  function navigate(dir: number) {1047    const allEntries = entries();1048    if (allEntries.length === 0) return;1049    const currentIndex = selectedIndex();1050    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1051    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1052    setSelectedEntry(allEntries[nextIndex]);1053    setContentPhase("enter");1054    queueContentIdle();1055  }10561057  function openList() {1058    setView("list");1059  }10601061  function openHealth() {1062    setEditEntry(undefined);1063    setView("health");1064  }10651066  function handleOpenFileImport() {1067    setRestoreView("file");1068  }10691070  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10711072  function handleFixEntry(entry: VaultEntry) {1073    setSelectedEntry(entry);1074    // Passkey-only entries have no editable surface — drop into view mode1075    // instead of opening the Add editor.1076    if (isPasskeyOnly(entry)) {1077      setView("entry");1078      return;1079    }1080    setEditBackView(view()); // preserve caller view so back returns here1081    setEditEntry(entry);1082    setView("add");1083  }10841085  const isLockedView = () => view() === "lock";10861087  async function handleApprovePendingPasskey() {1088    const pending = pendingPasskey();1089    if (!pending) return;1090    if (pending.browser === "firefox" && pending.type === "create") {1091      // Firefox path: popup itself runs navigator.credentials.create. The1092      // background never approved/rejected anything — it just stashed1093      // intent. After the popup-driven flow resolves (success or cancel),1094      // clear the pending key so the popup doesn't re-show this on next open.1095      const { createFirefoxPasskey } = await import("./firefox-passkey");1096      const result = await createFirefoxPasskey(pending);1097      if (!result.ok) {1098        console.warn("Peach Firefox passkey create failed:", result.error);1099      }1100      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1101      setPendingPasskey(null);1102      void loadEntries();1103      window.close();1104      return;1105    }1106    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1107    window.close();1108  }11091110  async function handleDenyPendingPasskey() {1111    const pending = pendingPasskey();1112    if (!pending) return;1113    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1114    window.close();1115  }11161117  function queueContentIdle(after?: () => void) {1118    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1119    contentPhaseTimer = window.setTimeout(() => {1120      setContentPhase("idle");1121      after?.();1122    }, ENTRY_TRANSITION_SETTLE_MS);1123  }11241125  return (1126    <div class="popup-root peach-theme">1127      <Show when={bootState() === "ready"}>1128        <Show1129          when={!pendingPasskey()}1130          fallback={1131            <PasskeyApprovalView1132              type={pendingPasskey()!.type}1133              rpName={pendingPasskey()!.rpName}1134              rpId={pendingPasskey()!.rpId}1135              userName={pendingPasskey()!.userName}1136              userDisplayName={pendingPasskey()!.userDisplayName}1137              onApprove={handleApprovePendingPasskey}1138              onDeny={handleDenyPendingPasskey}1139            />1140          }1141        >1142          <Show1143            when={!isLockedView()}1144            fallback={1145              <Show1146                when={onboarded() || hasVault()}1147                fallback={1148                  <Onboarding1149                    onComplete={() => { setOnboarded(true); }}1150                  />1151                }1152              >1153                <LockView1154                  hasVault={hasVault()}1155                  ready={bootState() === "ready"}1156                  isPro={proStatus()}1157                  forceRecoveryWords={forceRecoveryWords()}1158                  onUnlock={() => {1159                    // RecoveryWordDisplay clears the storage flag before1160                    // calling onDone, so handleUnlock will see no pending1161                    // confirmation and proceed through the normal path.1162                    if (forceRecoveryWords()) setForceRecoveryWords(false);1163                    return handleUnlock();1164                  }}1165                  onBackToOnboarding={1166                    !hasVault()1167                      ? () => setOnboarded(false)1168                      : undefined1169                  }1170                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1171                />1172              </Show>1173            }1174          >1175            <Show1176              when={view() !== "pro-celebration"}1177              fallback={<ProCelebration />}1178            >1179            <section1180              id="hd-shell"1181              class="peach-shell peach-theme"1182              data-surface="extension"1183            >1184            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1185              <PeachWordmark unlocked />1186              <div class="peach-chrome-actions">1187                <button1188                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1189                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1190                  aria-label="Notes"1191                  title="Notes"1192                >1193                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1194                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1195                    <line x1="4" y1="5" x2="10" y2="5" />1196                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1197                    <line x1="4" y1="10" x2="7" y2="10" />1198                  </svg>1199                </button>1200                <button1201                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1202                  onClick={() => setView("settings")}1203                  aria-label="Settings"1204                >1205                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1206                    <path1207                      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"1208                      stroke="currentColor"1209                      stroke-width="0.9"1210                    />1211                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1212                  </svg>1213                </button>1214                <button1215                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1216                  onClick={handleAdd}1217                  aria-label="New entry"1218                >1219                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1220                    <path d="M5.5 1v9M1 5.5h9" />1221                  </svg>1222                </button>1223                <button1224                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1225                  onClick={() => void handleHeaderLock()}1226                  aria-label="Lock vault"1227                >1228                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1229                    <path1230                      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"1231                      stroke="currentColor"1232                      stroke-width="1"1233                      stroke-linecap="round"1234                    />1235                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1236                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1237                  </svg>1238                </button>1239              </div>1240            </header>12411242            <Show when={pendingProNotice() !== null}>1243              <div class="peach-pro-notice-banner">1244                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1245                <button1246                  class="peach-pro-notice-link"1247                  onClick={() => {1248                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1249                    setSettingsInitialSection("license");1250                    setView("settings");1251                    setPendingProNotice(null);1252                  }}1253                >1254                  Learn more →1255                </button>1256                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1257              </div>1258            </Show>12591260            <div class="peach-shell-body">1261              <div class="peach-shell-veil"></div>1262              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1263                <EntryView1264                  entry={selectedEntry()}1265                  currentTabUrl={currentTabUrl()}1266                  entries={entries()}1267                  isPro={proStatus()}1268                  onDelete={handleDelete}1269                  onFieldSaved={() => void loadEntries()}1270                  onEscape={() => { setView("list"); }}1271                  onProGate={(feature) => {1272                    setUpgradeHighlight(feature);1273                    setSettingsInitialSection("license");1274                    setView("settings");1275                  }}1276                />1277              </div>12781279              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1280                <div class="peach-search-bar">1281                  <span class="peach-search-icon">1282                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1283                      <circle cx="5.5" cy="5.5" r="3.75" />1284                      <path d="M8.75 8.75L11.5 11.5" />1285                    </svg>1286                  </span>1287                  <input1288                    class="peach-search-input"1289                    placeholder="search vault..."1290                    autocomplete="off"1291                    aria-label="Search vault entries"1292                    onClick={openList}1293                    onFocus={openList}1294                    readOnly1295                  />1296                  <div class="peach-search-meta">1297                    <span class="peach-search-counter">1298                      {entries().length > 01299                        ? `${selectedIndex() + 1} / ${entries().length}`1300                        : "0 entries"}1301                    </span>1302                    <span class="peach-divider"></span>1303                    <button1304                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1305                      onClick={() => navigate(-1)}1306                      aria-label="Previous entry"1307                      disabled={entries().length === 0}1308                    >1309                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1310                        <path d="M5 1L1 5.5L5 10" />1311                      </svg>1312                    </button>1313                    <button1314                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1315                      onClick={() => navigate(1)}1316                      aria-label="Next entry"1317                      disabled={entries().length === 0}1318                    >1319                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1320                        <path d="M1 1L5 5.5L1 10" />1321                      </svg>1322                    </button>1323                  </div>1324                </div>1325              </section>1326            </div>13271328            {/* Desktop: shown on demand via Show. Native sheet is rendered1329                via Portal below at the document root so its position:fixed1330                isn't trapped by .peach-shell's transform-based animations. */}1331            <Show when={!isNativePlatform() && view() === "list"}>1332              <VaultView1333                entries={entries()}1334                selectedEntryId={selectedEntry()?.id}1335                currentTabDomain={currentTabDomain()}1336                sortOrder={sortOrder()}1337                searchSeed={listSearchSeed()}1338                searchSeedNonce={listSearchSeedNonce()}1339                onSelectEntry={handleSelectEntry}1340                onSortOrderChange={setSortOrder}1341                onAdd={handleAdd}1342                onClose={() => setView("entry")}1343                onOpenTrash={() => setView("trash")}1344                onDeleteMany={handleDeleteMany}1345              />1346            </Show>1347            <Show when={isNativePlatform() && hasVault()}>1348              <Portal>1349                <div1350                  class="peach-vault-sheet"1351                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1352                  style={(() => {1353                    const live = sheetTranslate();1354                    if (live === null) return undefined;1355                    return { transform: `translateY(${live}px)` };1356                  })()}1357                >1358                  <VaultView1359                    entries={entries()}1360                    selectedEntryId={selectedEntry()?.id}1361                    currentTabDomain={currentTabDomain()}1362                    sortOrder={sortOrder()}1363                    searchSeed={listSearchSeed()}1364                    searchSeedNonce={listSearchSeedNonce()}1365                    isNative={true}1366                    onSelectEntry={handleSelectEntry}1367                    onSortOrderChange={setSortOrder}1368                    onAdd={handleAdd}1369                    onClose={() => setView("entry")}1370                    onOpenTrash={() => setView("trash")}1371                    onDeleteMany={handleDeleteMany}1372                  />1373                </div>1374              </Portal>1375            </Show>1376            <Show when={view() === "settings" || settingsExiting()}>1377              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1378                <SettingsView1379                  entriesCount={entries().length}1380                  breachMonitoring={breachMonitoring()}1381                  lockOnClose={lockOnClose()}1382                  autoLockMinutes={autoLockMinutes()}1383                  trashRetentionDays={trashRetentionDays()}1384                  theme={theme()}1385                  accentColor={accentColor()}1386                  textSize={textSize()}1387                  reduceMotion={reduceMotion()}1388                  isPro={proStatus()}1389                  initialSection={settingsInitialSection()}1390                  upgradeHighlight={upgradeHighlight()}1391                  isExiting={settingsExiting()}1392                  onBreachMonitoringChange={applyBreachMonitoring}1393                  onLockOnCloseChange={applyLockOnClose}1394                  onAutoLockMinutesChange={applyAutoLockMinutes}1395                  onTrashRetentionChange={applyTrashRetention}1396                  onThemeChange={applyTheme}1397                  onAccentChange={applyAccentColor}1398                  onTextSizeChange={applyTextSize}1399                  onReduceMotionChange={applyReduceMotion}1400                  shortcuts={shortcutBindings()}1401                  onShortcutsChange={applyShortcuts}1402                  onLicenseChange={async () => {1403                    // After activation/deactivation: refresh Pro status,1404                    // re-load entries (defensive — signal state can drift if1405                    // the SW briefly restarts during the verify+save round-trip),1406                    // and replay the Pro celebration if this is the first time1407                    // a valid Pro license is seen on this device.1408                    await refreshProStatus();1409                    void loadEntries();1410                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1411                    if ((should as { ok: boolean; data?: boolean }).data === true) {1412                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1413                      setView("pro-celebration");1414                      window.setTimeout(() => setView("settings"), 2500);1415                    }1416                  }}1417                  onBack={() => {1418                    setSettingsExiting(true);1419                    window.setTimeout(() => {1420                      setSettingsExiting(false);1421                      setSettingsInitialSection(null);1422                      setUpgradeHighlight(null);1423                      handleBack();1424                    }, 200);1425                  }}1426                  onImport={() => setView("import")}1427                  onExport={() => setView("export")}1428                  onBreachCheckDone={loadEntries}1429                  onOpenHealth={openHealth}1430                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("chirp-sync"); }}1431                  onOpenFileImport={handleOpenFileImport}1432                  onOpenPanic={() => setView("panic")}1433                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1434                  onOpenCodexRestore={() => setView("codex-restore")}1435                  onCardChange={setSettingsActiveCard}1436                  onProGate={(feature) => {1437                    setUpgradeHighlight(feature);1438                    setSettingsInitialSection("license");1439                  }}1440                />1441              </Suspense>1442            </Show>1443            <Show when={view() === "codex-generate"}>1444              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1445                <CodexGenerateView1446                  isPro={proStatus()}1447                  onBack={() => setView("settings")}1448                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1449                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1450                  onVaultLocked={() => handleLock()}1451                />1452              </Suspense>1453            </Show>1454            <Show when={view() === "codex-restore"}>1455              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1456                <CodexRestoreView1457                  onBack={() => setView("lock")}1458                  onRestoreSuccess={async () => {1459                    // After restore the vault is unlocked; refresh entries1460                    // and route to the main vault list. handleUnlock is the1461                    // canonical post-unlock setup path.1462                    await handleUnlock();1463                  }}1464                />1465              </Suspense>1466            </Show>1467            <Show when={view() === "chirp-sync"}>1468              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1469                <ChirpSyncView1470                  isPro={proStatus()}1471                  onBack={() => setView("settings")}1472                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1473                />1474              </Suspense>1475            </Show>1476            <Show when={view() === "add"}>1477              <AddView1478                entry={editEntry()}1479                entries={entries()}1480                onBack={handleBack}1481                onSave={handleSave}1482              />1483            </Show>1484            <Show when={view() === "import"}>1485              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1486                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1487              </Suspense>1488            </Show>1489            <Show when={view() === "export"}>1490              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1491                <ExportView onBack={handleExportBack} />1492              </Suspense>1493            </Show>1494            <Show when={view() === "panic"}>1495              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1496                <PanicView1497                  onCancel={() => setView("settings")}1498                  onOpenExport={() => {1499                    setReturnToPanic(true);1500                    setView("export");1501                  }}1502                  onDestroyed={async () => {1503                    clearCanarySuppressions();1504                    setEntries([]);1505                    setSelectedEntry(null);1506                    setEditEntry(undefined);1507                    setHasVault(false);1508                    setOnboarded(false);1509                    setProStatus(false);1510                    setPendingPasskey(null);1511                    setUpgradeHighlight(null);1512                    setSettingsInitialSection(null);1513                    setPendingProNotice(null);1514                    setPendingCelebration(false);1515                    setReturnToPanic(false);1516                    setContentPhase("idle");1517                    setView("lock");1518                  }}1519                />1520              </Suspense>1521            </Show>1522            <Show when={view() === "health"}>1523              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1524                <HealthView1525                  entries={entries()}1526                  isPro={proStatus()}1527                  onFixEntry={handleFixEntry}1528                  onBack={() => setView("settings")}1529                  onRefresh={loadEntries}1530                />1531              </Suspense>1532            </Show>1533            <Show when={view() === "trash"}>1534              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1535                <TrashView1536                  onBack={() => setView("list")}1537                  onRestored={() => void loadEntries()}1538                />1539              </Suspense>1540            </Show>1541            <Show when={showNotes()}>1542              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1543                <NotesMode1544                  notes={entries().filter((e) => e.type === "note")}1545                  initialNoteId={openNoteId()}1546                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1547                  onNoteListChanged={() => void loadEntries()}1548                />1549              </div>1550            </Show>1551            <Show when={restoreView() === "file"}>1552              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1553                <ImportView1554                  mode="onboarding"1555                  replacesExistingVault={true}1556                  onBack={() => setRestoreView(null)}1557                  onImport={async () => {1558                    setRestoreView(null);1559                    await handleUnlock();1560                  }}1561                />1562              </Suspense>1563            </Show>1564            </section>1565            </Show>1566          </Show>1567        </Show>1568      </Show>1569      <Show when={showShortcutsHelp()}>1570        <ShortcutsHelpOverlay1571          bindings={shortcutBindings()}1572          onClose={() => setShowShortcutsHelp(false)}1573        />1574      </Show>1575    </div>1576  );1577}15781579function ShortcutsHelpOverlay(props: {1580  bindings: Record<ShortcutAction, Keybinding>;1581  onClose: () => void;1582}) {1583  return (1584    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1585      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1586        <div class="peach-shortcuts-help-head">1587          <h3>Keyboard shortcuts</h3>1588          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1589        </div>1590        <div class="peach-shortcuts-help-body">1591          <p class="peach-settings-sub-label">ENTRY VIEW</p>1592          <ul>1593            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1594              <li>1595                <span>{d.label}</span>1596                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1597              </li>1598            ))}1599          </ul>1600          <p class="peach-settings-sub-label">ANYWHERE</p>1601          <ul>1602            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1603              <li>1604                <span>{d.label}</span>1605                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1606              </li>1607            ))}1608          </ul>1609        </div>1610      </div>1611    </div>1612  );1613}