App.tsx

66.2 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageSet } from "../shared/storage";4import { sendMessage } from "../shared/bridge";5import { ACCENT_COLORS } from "../shared/types";6import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";7import { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { NotesMode } from "./views/NotesMode";11import { ProCelebration } from "./views/ProCelebration";12import { VaultView, type SortOrder } from "./views/Vault";13import { EntryView } from "./views/Entry";14import { AddView } from "./views/Add";15import { PeachWordmark } from "./components/PeachMark";16import { PasskeyApprovalView } from "./views/PasskeyApproval";17import { extractDomain } from "../shared/domain";18import { popupCopy } from "./copy";19import {20  DEFAULT_BINDINGS,21  formatKeybinding,22  getActiveBindings,23  matchKeybinding,24  SHORTCUT_DESCRIPTORS,25  type Keybinding,26  type ShortcutAction,27} from "../shared/shortcuts";28import { generateTOTP } from "../crypto/totp";29import { isNativePlatform, nativePlugin } from "../shared/native";3031export { sendMessage } from "../shared/bridge";3233const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));34const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));35const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));36const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));37const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));38const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));39const ChirpSyncView   = lazy(() => import("./views/ChirpSync").then(m => ({ default: m.ChirpSyncView })));40const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));41const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));4243type View =44  | "lock"45  | "pro-celebration"46  | "entry"47  | "list"48  | "add"49  | "settings"50  | "chirp-sync"51  | "import"52  | "export"53  | "health"54  | "trash"55  | "panic"56  | "codex-generate"57  | "codex-restore";58type BootState = "loading" | "ready";5960const canarySuppressMap = new Map<string, boolean>();61let shellRingAnimation: Animation | null = null;6263export function isCanarySuppressed(entryId: string): boolean {64  return canarySuppressMap.get(entryId) ?? false;65}6667export function setCanarySuppressed(entryId: string, suppressed: boolean): void {68  canarySuppressMap.set(entryId, suppressed);69}7071export function clearCanarySuppressions(): void {72  canarySuppressMap.clear();73}7475export function triggerRing() {76  const shell = document.getElementById("hd-shell");77  if (!shell) return;7879  shellRingAnimation?.cancel();80  shell.dataset.glowing = "true";81  const animation = shell.animate(82    [83      { offset: 0, boxShadow: "var(--copy-shadow)" },84      {85        offset: 0.3,86        boxShadow:87          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",88      },89      { offset: 1, boxShadow: "var(--copy-shadow)" },90    ],91    {92      duration: 720,93      easing: "cubic-bezier(0.4, 0, 0.2, 1)",94      fill: "none",95    }96  );97  shellRingAnimation = animation;98  const clearGlow = () => {99    if (shellRingAnimation !== animation) return;100    shellRingAnimation = null;101    delete shell.dataset.glowing;102  };103  animation.onfinish = clearGlow;104  animation.oncancel = clearGlow;105}106107108export function triggerPipPulse() {109  const pip = document.querySelector(".peach-status-pip, .pip");110  if (pip) {111    pip.classList.remove("pulse");112    void (pip as HTMLElement).offsetWidth;113    pip.classList.add("pulse");114  }115}116117const ENTRY_TRANSITION_SETTLE_MS = 135;118119export default function App() {120  const [bootState, setBootState] = createSignal<BootState>("loading");121  const [view, setView] = createSignal<View>("lock");122  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,123  // CSS transition takes over for snap animation).124  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);125  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(126    "enter"127  );128  const [contentTransitioning, setContentTransitioning] = createSignal(false);129  const [hasVault, setHasVault] = createSignal(false);130  const [onboarded, setOnboarded] = createSignal(true);131  const [entries, setEntries] = createSignal<VaultEntry[]>([]);132  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);133  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);134  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");135  const [theme, setTheme] = createSignal<"dark" | "light">("dark");136  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");137  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);138  const [lockOnClose, setLockOnClose] = createSignal(true);139  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);140  const [breachMonitoring, setBreachMonitoring] = createSignal(true);141  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);142  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);143  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);144  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);145  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);146  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");147  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");148  // Cached Pro status — synchronous for render paths. Background's149  // GET_LICENSE is async, but render-time reads of isPro() must not block.150  // Refreshed at boot, after activate/deactivate, and whenever the popup151  // re-opens onto a stored license that has changed via another window.152  const [proStatus, setProStatus] = createSignal(false);153  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);154  const [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    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the327    // background ignores it when no mobile hosts are paired or while328    // another sync is already in flight.329    if (unlocked && vaultExists) {330      void sendMessage({331        type: "TRIGGER_SYNC",332        payload: { reason: "foreground" },333      });334    }335336    // If the user created a vault but hasn't yet confirmed their recovery337    // words, route back to the recovery-words screen instead of opening the338    // entries view. The flag lives in chrome.storage.local so it survives339    // both popup close (SW suppresses lock-on-close) and full browser340    // restart (handleUnlock checks the same flag after a fresh password341    // unlock). Cleared when confirmation succeeds.342    let recoveryPending = false;343    try {344      const out = await chrome.storage.local?.get("peach_recovery_pending");345      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";346    } catch { /* best-effort */ }347348    // Native: closing the app before recovery-words confirmation means the349    // user didn't finish vault creation. Throw the partial vault away and350    // restart onboarding rather than asking them to unlock a vault they351    // never finished creating. Desktop keeps the existing "unlock to352    // resume" flow because closing the popup there is much more casual.353    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {354      try {355        await chrome.storage.local?.remove([356          "peach_vault_a",357          "peach_vault_b",358          "peach_recovery_pending",359          "peach_onboarded",360          "peach_vault_history",361        ]);362      } catch { /* best-effort */ }363      setHasVault(false);364      setOnboarded(false);365      setView("lock");366      setBootState("ready");367      document.getElementById("pre-lock")?.setAttribute("hidden", "true");368      return;369    }370371    if (recoveryPending && unlocked) {372      // forceRecoveryWords overrides LockView's hasVault gate so the373      // recovery surface renders even though the vault now exists.374      setForceRecoveryWords(true);375      setView("lock");376    } else if (unlocked && vaultExists) {377      await openVault(undefined, shouldCelebrate);378      if (shouldCelebrate) {379        setView("pro-celebration");380        window.setTimeout(() => setView("entry"), 2500);381      }382    } else if (shouldCelebrate) {383      setPendingCelebration(true);384    }385386    await refreshPendingPasskey();387388    // Track tab changes so smart sort stays current389    const handleTabActivated = () => { void refreshCurrentTab(); };390    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {391      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();392    };393    try {394      chrome.tabs.onActivated.addListener(handleTabActivated);395      chrome.tabs.onUpdated.addListener(handleTabUpdated);396      onCleanup(() => {397        chrome.tabs.onActivated.removeListener(handleTabActivated);398        chrome.tabs.onUpdated.removeListener(handleTabUpdated);399      });400    } catch {401      // tabs permission may not be available in all contexts402    }403404    setBootState("ready");405    document.getElementById("pre-lock")?.setAttribute("hidden", "true");406407    // Deep-link: ?codex=pdf opens a detached window straight into the408    // Codex restore flow with auto-picked PDF. The action popup can't host409    // a file dialog without dismissing itself, so this is the only way the410    // PDF import path survives. See CodexRestoreView.openPdfPicker().411    try {412      const route = new URLSearchParams(window.location.search).get("codex");413      if (route === "pdf" || route === "restore") {414        setView("codex-restore");415      }416    } catch {417      // location.search unavailable — ignore.418    }419420    // Check for pending session-storage notices from the background.421    if (chrome.storage.session) {422      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as423        Record<string, { feature?: string } | undefined>;424      if (session.pendingProGate?.feature) {425        await chrome.storage.session.remove("pendingProGate");426        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);427        setSettingsInitialSection("license");428        setView("settings");429      } else if (session.pendingProNotice?.feature) {430        await chrome.storage.session.remove("pendingProNotice");431        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });432      }433    }434435    // Warm the lazy-module cache so the Suspense fallback never shows for436    // locally-bundled extension views. Without this, the first navigation to437    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which438    // covers the shell and absorbs clicks on the header.439    void Promise.all([440      import("./views/Settings").catch(() => {}),441      import("./views/Import").catch(() => {}),442      import("./views/Export").catch(() => {}),443      import("./views/Health").catch(() => {}),444      import("./views/TrashView").catch(() => {}),445    ]);446447    // Lock-on-close via a persistent port. sendMessage in pagehide is448    // unreliable — the popup context tears down before the message lands.449    // The SW's onConnect listener locks when this port disconnects.450    let popupPort: chrome.runtime.Port | null = null;451    try {452      popupPort = chrome.runtime.connect({ name: "popup" });453    } catch { /* extension context invalidated — ignore */ }454    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });455456    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only457    // reliable signal is appStateChange — setTimeout is killed when the OS458    // backgrounds the app. We measure elapsed background time on resume.459    if (isNativePlatform()) {460      let backgroundedAt: number | null = null;461462      const CapApp = nativePlugin<{463        addListener: (464          ev: string,465          cb: (s: { isActive: boolean }) => void,466        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };467      }>("App");468      if (CapApp?.addListener) {469        const sub = CapApp.addListener(470          "appStateChange",471          ({ isActive }: { isActive: boolean }) => {472            if (!isActive) {473              backgroundedAt = Date.now();474              return;475            }476            if (backgroundedAt !== null && autoLockMinutes() > 0) {477              const elapsed = Date.now() - backgroundedAt;478              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();479            }480            backgroundedAt = null;481          }482        );483        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.484        onCleanup(() => {485          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});486        });487      }488489      // L12/COR-011: foreground idle autolock. appStateChange only fires when490      // the OS backgrounds the app — if the user idles with the screen on,491      // chrome.alarms is no-op'd in Capacitor so the vault would stay open492      // indefinitely. Poll every 30s and lock if elapsed since last user493      // interaction exceeds autoLockMinutes.494      let lastUserActivityAt = Date.now();495      const bumpActivity = () => { lastUserActivityAt = Date.now(); };496      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;497      for (const ev of ACTIVITY_EVENTS) {498        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });499      }500      const idleLockInterval = setInterval(() => {501        const minutes = autoLockMinutes();502        if (!minutes || minutes <= 0) return;503        const elapsed = Date.now() - lastUserActivityAt;504        if (elapsed >= minutes * 60_000) {505          lastUserActivityAt = Date.now();506          handleHeaderLock();507        }508      }, 30_000);509      onCleanup(() => {510        clearInterval(idleLockInterval);511        for (const ev of ACTIVITY_EVENTS) {512          document.removeEventListener(ev, bumpActivity, { capture: true });513        }514      });515    }516517    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale518    // entries instead of waiting for the next GET_ENTRIES round-trip.519    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {520      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();521      if (msg?.type === "PRO_GATE_TRIGGERED") {522        setUpgradeHighlight(msg.payload?.feature ?? null);523        setSettingsInitialSection("license");524        setView("settings");525      }526    };527    chrome.runtime.onMessage.addListener(handleRuntimeMessage);528    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));529530    // Android hardware/gesture back. MainActivity fires peach:back; the popup531    // decides what "back" means per surface. Lock+no-vault is the common case532    // — return to onboarding rather than letting the OS dismiss the activity.533    const handlePeachBack = () => {534      // Notes mode captures back first535      if (showNotes()) {536        setShowNotes(false);537        setOpenNoteId(undefined);538        return;539      }540      const v = view();541      if (v === "lock" && !hasVault() && onboarded()) {542        setOnboarded(false);543        return;544      }545      if (v === "list") { setView("entry"); return; }546      if (v === "settings") {547        window.dispatchEvent(new Event("peach:settings-back"));548        return;549      }550      if (v === "import" || v === "health") { setView("settings"); return; }551      if (v === "export") { handleExportBack(); return; }552      if (v === "add") { handleBack(); return; }553      if (v === "chirp-sync") { setView("settings"); return; }554    };555    window.addEventListener("peach:back", handlePeachBack);556    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));557558    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that559    // peeks from the bottom (search bar handle visible) and drags up to fill560    // the screen. dragOffset is the LIVE finger offset during a drag, in px,561    // 0 when no drag in progress. The wrapper element computes transform =562    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.563    if (isNativePlatform()) {564      let touchStartY = 0;565      let touchStartX = 0;566      let lastY = 0;567      let lastT = 0;568      let dragging = false;569      let captured = false;570      const HORIZONTAL_TOLERANCE = 16;571      const ACTIVATION_DY = 8;572      const PEEK_PX = 60;573574      const onTouchStart = (e: TouchEvent) => {575        const t = e.touches[0];576        if (!t) return;577        const v = view();578        if (v !== "entry" && v !== "list") return;579        // Entry view: only intercept drags starting in the bottom 40%.580        // List view: intercept drags starting in the top 35% (the search/handle row).581        const inBand = v === "entry"582          ? t.clientY > window.innerHeight * 0.6583          : t.clientY < window.innerHeight * 0.35;584        if (!inBand) return;585        touchStartY = lastY = t.clientY;586        touchStartX = t.clientX;587        lastT = e.timeStamp;588        dragging = true;589        captured = false;590      };591592      const onTouchMove = (e: TouchEvent) => {593        if (!dragging) return;594        const t = e.touches[0];595        if (!t) return;596        const dy = t.clientY - touchStartY;597        const dx = Math.abs(t.clientX - touchStartX);598599        if (!captured) {600          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {601            // Looks like a horizontal swipe — release.602            dragging = false;603            return;604          }605          if (Math.abs(dy) < ACTIVATION_DY) return;606          captured = true;607        }608609        // Translate the sheet by dy from its rest (peek) position. Peek is610        // (viewport height - PEEK_PX). Open is 0.611        const v = view();612        const restClosed = window.innerHeight - PEEK_PX;613        const baseTranslate = v === "list" ? 0 : restClosed;614        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));615        setSheetTranslate(next);616        lastY = t.clientY;617        lastT = e.timeStamp;618      };619620      const onTouchEnd = (e: TouchEvent) => {621        if (!dragging) { return; }622        const t = e.changedTouches[0];623        const elapsed = Math.max(1, e.timeStamp - lastT);624        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms625        const wasCaptured = captured;626        dragging = false;627        captured = false;628        const v = view();629630        if (!wasCaptured) {631          // Tap in the peek strip while in entry view → open the vault list.632          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");633          setSheetTranslate(null);634          return;635        }636637        const restClosed = window.innerHeight - PEEK_PX;638        const current = sheetTranslate() ?? restClosed;639640        // Snap rules:641        //   - Strong upward velocity → open642        //   - Strong downward velocity → close643        //   - Otherwise snap to whichever rest is closer644        let nextOpen: boolean;645        if (velocity < -0.05) nextOpen = true;646        else if (velocity > 0.05) nextOpen = false;647        else nextOpen = current < restClosed * 0.5;648649        if (nextOpen && v !== "list") setView("list");650        if (!nextOpen && v !== "entry") setView("entry");651        // Release the live offset so CSS transition handles the snap.652        setSheetTranslate(null);653      };654655      document.addEventListener("touchstart", onTouchStart, { passive: true });656      document.addEventListener("touchmove",  onTouchMove,  { passive: true });657      document.addEventListener("touchend",   onTouchEnd,   { passive: true });658      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });659      onCleanup(() => {660        document.removeEventListener("touchstart", onTouchStart);661        document.removeEventListener("touchmove",  onTouchMove);662        document.removeEventListener("touchend",   onTouchEnd);663      });664    }665666    // Action handlers — keyed by ShortcutAction. The dispatcher below tests667    // each binding against the event and runs the matching handler. New668    // shortcuts only need an entry here; the binding is data, not code.669    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {670      copy_password: () => {671        const entry = selectedEntry();672        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });673      },674      copy_username: () => {675        const entry = selectedEntry();676        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });677      },678      copy_totp: () => {679        const entry = selectedEntry();680        if (!entry?.totp) return;681        try {682          const { code } = generateTOTP(entry.totp);683          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });684        } catch { /* invalid TOTP secret — silent */ }685      },686      new_entry: () => handleAdd(),687      edit_entry: () => {688        const entry = selectedEntry();689        // Passkey-only entries have nothing user-editable in the Add view; the690        // passkey credential itself is opaque. Skip the edit action for them.691        if (!entry || isPasskeyOnly(entry)) return;692        setEditEntry(entry);693        setView("add");694      },695      delete_entry: () => {696        if (selectedEntry()) void handleDelete();697      },698      lock_vault: () => { void handleHeaderLock(); },699      search: () => openList(),700      nav_prev: () => navigate(-1),701      nav_next: () => navigate(1),702      jump_vault: () => setView("entry"),703      jump_settings: () => setView("settings"),704      show_help: () => setShowShortcutsHelp(true),705    };706707    // Actions that are MEANINGFUL only on the entry-detail view. Outside708    // that scope the binding is dormant — pressing C while on Settings709    // does nothing rather than awkwardly copying from a now-stale entry.710    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([711      "copy_password", "copy_username", "copy_totp",712      "edit_entry", "delete_entry", "nav_prev", "nav_next",713    ]);714715    const handleGlobalKeydown = (e: KeyboardEvent) => {716      const v = view();717      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"718        || (e.target as HTMLElement)?.tagName === "TEXTAREA"719        || (e.target as HTMLElement)?.isContentEditable;720      const isPrintableSearchKey =721        e.key.length === 1 &&722        !e.ctrlKey &&723        !e.metaKey &&724        !e.altKey;725726      // No input during the pro celebration sequence727      if (v === "pro-celebration") return;728729      // Help dialog: Escape closes it; eat the keypress so it doesn't730      // also navigate away from the underlying view.731      if (showShortcutsHelp()) {732        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }733        return;734      }735736      // ── Escape — fixed binding (not user-customizable) ───────737      if (e.key === "Escape") {738        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }739        if (v === "list") { setView("entry"); return; }740        if (v === "settings" || v === "add") { handleBack(); return; }741        if (v === "import" || v === "health") { setView("settings"); return; }742        if (v === "export") { handleExportBack(); return; }743        if (v === "chirp-sync") { setView("settings"); return; }744      }745746      // Bindings-driven dispatch. Single-key letter bindings without747      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is748      // inside an input, so users can type into search/forms normally.749      const bindings = shortcutBindings();750      for (const action of Object.keys(bindings) as ShortcutAction[]) {751        const binding = bindings[action];752        if (!matchKeybinding(e, binding)) continue;753        // Single-key letter bindings need the input-focus guard. Bindings754        // with any modifier are safe — Ctrl+L doesn't conflict with typing.755        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;756        if (!hasMod && binding.key.length === 1 && inInput) return;757        if (ENTRY_SCOPED.has(action) && v !== "entry") return;758        e.preventDefault();759        SHORTCUT_HANDLERS[action]?.();760        return;761      }762763      // Type-to-search: in entry view, any printable key not consumed by a764      // shortcut above primes the list search seed and opens the list.765      // Kept outside the bindings table because it's a behavior, not a766      // discrete action — every printable character can trigger it.767      if (v === "entry" && !inInput && isPrintableSearchKey) {768        e.preventDefault();769        primeListSearch(e.key);770        return;771      }772    };773    window.addEventListener("keydown", handleGlobalKeydown);774    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));775776    const handleStorageChanged = (777      changes: Record<string, chrome.storage.StorageChange>,778      areaName: string779    ) => {780      if (areaName !== "session") return;781      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {782        return;783      }784      void refreshPendingPasskey();785    };786    chrome.storage.onChanged.addListener(handleStorageChanged);787    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));788  });789790  async function refreshCurrentTab() {791    try {792      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });793      const url = tab?.url ?? tab?.pendingUrl ?? "";794      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");795      // Skip extension/internal URLs — adding chrome://, about:, or796      // chrome-extension:// to a vault entry is never what the user wants.797      const isWebUrl = /^https?:\/\//i.test(url);798      setCurrentTabUrl(isWebUrl ? url : "");799    } catch {800      setCurrentTabDomain("");801      setCurrentTabUrl("");802    }803  }804805  async function refreshPendingPasskey() {806    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });807    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);808  }809810  async function refreshProStatus() {811    const res = await sendMessage({ type: "GET_LICENSE" });812    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;813    setProStatus(Boolean(data?.valid && data?.plan === "pro"));814  }815816  async function restoreSettings() {817    const res = await sendMessage({ type: "GET_SETTINGS" });818    const s = (res as { ok: boolean; data?: any }).data ?? {};819    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {820      setAccentColor(s.accentColor as AccentColorName);821    }822    setTheme(s.theme === "light" ? "light" : "dark");823    if (s.textSize === "small" || s.textSize === "large") {824      setTextSize(s.textSize);825    } else {826      setTextSize("medium");827    }828    setReduceMotion(s.reduceMotion === true);829    setLockOnClose(s.lockOnClose !== false);830    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);831    setBreachMonitoring(s.breachMonitoring !== false);832    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);833    setShortcutBindings(getActiveBindings(s.shortcuts));834  }835836  async function applyTrashRetention(days: number) {837    setTrashRetentionDays(days);838    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });839  }840841  function primeListSearch(seed: string) {842    setListSearchSeed(seed);843    setListSearchSeedNonce((value) => value + 1);844    openList();845  }846847  // Returns null when it detected a dead service worker and triggered handleLock().848  // Callers that need to abort (e.g. openVault) check for null rather than relying849  // on view() state, which may already be "lock" during normal startup flows.850  async function loadEntries(): Promise<VaultEntry[] | null> {851    const response = await sendMessage({ type: "GET_ENTRIES" });852    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };853854    // If the service worker was killed and restarted (MV3 workers sleep), the855    // vault will be locked again — or the worker may not respond at all.856    // In either case, send the user to the lock screen rather than silently857    // showing an empty vault (which looks like data loss).858    if (!res.ok) {859      if (860        res.error === "vault_locked" ||861        res.error === "SERVICE_WORKER_UNAVAILABLE" ||862        (typeof res.error === "string" && res.error.includes("locked"))863      ) {864        handleLock();865        return null; // signal emergency lock to callers866      }867      return [];868    }869870    const loadedEntries = res.data ?? [];871    setEntries(loadedEntries);872873    const currentId = selectedEntry()?.id;874    if (currentId) {875      setSelectedEntry(876        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null877      );878    }879880    return loadedEntries;881  }882883  async function openVault(preferredEntryId?: string, skipViewSet = false) {884    // Purge expired trash entries on each vault open885    const retDays = trashRetentionDays();886    if (retDays > 0) {887      void sendMessage({888        type: "PURGE_EXPIRED_TRASH",889        payload: { retentionMs: retDays * 86_400_000 },890      });891    }892893    const loadedEntries = await loadEntries();894895    // null means loadEntries() triggered an emergency lock (service worker died).896    // Don't override it by setting view back to "entry" with an empty vault.897    if (loadedEntries === null) return;898899    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry900    let nextSelectedEntry: VaultEntry | null = null;901    if (preferredEntryId) {902      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;903    }904    if (!nextSelectedEntry) {905      const tabDomain = currentTabDomain();906      if (tabDomain) {907        nextSelectedEntry = loadedEntries.find((e) => {908          if (e.type === "login") {909            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;910            for (const extra of e.additionalUrls ?? []) {911              if ((extractDomain(extra) ?? "") === tabDomain) return true;912            }913            return false;914          }915          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;916          return false;917        }) ?? null;918      }919    }920    nextSelectedEntry ??= loadedEntries[0] ?? null;921922    setSelectedEntry(nextSelectedEntry);923    setEditEntry(undefined);924    setContentTransitioning(false);925    setContentPhase("enter");926    queueContentIdle();927    if (!skipViewSet) setView("entry");928  }929930  async function handleUnlock() {931    // If the user previously created a vault but hadn't yet confirmed their932    // recovery words (and the browser was closed before they could), the933    // peach_recovery_pending flag is still set in storage.local. Re-route934    // back to the recovery surface so they finish the confirmation step935    // before reaching the entries view — the words can be re-derived now936    // that the vault is unlocked again.937    let recoveryPending = false;938    try {939      const out = await chrome.storage.local?.get("peach_recovery_pending");940      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";941    } catch { /* best-effort */ }942    if (recoveryPending) {943      setForceRecoveryWords(true);944      setView("lock");945      triggerPipPulse();946      await restoreSettings();947      return;948    }949    setHasVault(true);950    triggerPipPulse();951    await restoreSettings();952    const celebrating = pendingCelebration();953    if (celebrating) {954      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });955      setPendingCelebration(false);956    }957    await openVault(undefined, celebrating);958    if (celebrating) {959      setView("pro-celebration");960      window.setTimeout(() => setView("entry"), 2500);961    }962  }963964  function handleSelectEntry(entry: VaultEntry) {965    if (entry.type === "note") {966      setOpenNoteId(entry.id);967      setShowNotes(true);968      return;969    }970    setSelectedEntry(entry);971    setContentTransitioning(false);972    setContentPhase("enter");973    queueContentIdle();974    setView("entry");975  }976977  function handleAdd() {978    setEditEntry(undefined);979    setView("add");980  }981982  async function handleDelete() {983    const entry = selectedEntry();984    if (!entry) return;985    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });986    const loadedEntries = await loadEntries() ?? [];987    setSelectedEntry(loadedEntries[0] ?? null);988    setView("entry");989  }990991  async function handleDeleteMany(ids: string[]) {992    for (const id of ids) {993      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });994    }995    const loadedEntries = await loadEntries() ?? [];996    // If the currently selected entry was among the deleted, move to first997    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);998    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);999  }10001001  async function handleSave(savedEntry?: VaultEntry) {1002    await openVault(savedEntry?.id);1003  }10041005  function handleBack() {1006    const dest = editBackView();1007    setEditBackView("entry");1008    setEditEntry(undefined);1009    setView(dest);1010  }10111012  function handleExportBack() {1013    if (returnToPanic()) {1014      setReturnToPanic(false);1015      setView("panic");1016      return;1017    }1018    setView("settings");1019  }10201021  function handleLock() {1022    clearCanarySuppressions();1023    setEntries([]);1024    setSelectedEntry(null);1025    setEditEntry(undefined);1026    setContentPhase("idle");1027    setView("lock");1028  }10291030  function handleHeaderLock() {1031    // Lock the UI immediately — do not wait for the service worker. If the SW1032    // is dead or slow, the 5s sendMessage timeout would create a dead-click1033    // window. The SW will lock on its next wake regardless.1034    handleLock();1035    void sendMessage({ type: "LOCK" });1036  }10371038  function navigate(dir: number) {1039    const allEntries = entries();1040    if (allEntries.length === 0) return;1041    const currentIndex = selectedIndex();1042    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1043    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1044    setSelectedEntry(allEntries[nextIndex]);1045    setContentPhase("enter");1046    queueContentIdle();1047  }10481049  function openList() {1050    setView("list");1051  }10521053  function openHealth() {1054    setEditEntry(undefined);1055    setView("health");1056  }10571058  function handleOpenFileImport() {1059    setRestoreView("file");1060  }10611062  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10631064  function handleFixEntry(entry: VaultEntry) {1065    setSelectedEntry(entry);1066    // Passkey-only entries have no editable surface — drop into view mode1067    // instead of opening the Add editor.1068    if (isPasskeyOnly(entry)) {1069      setView("entry");1070      return;1071    }1072    setEditBackView(view()); // preserve caller view so back returns here1073    setEditEntry(entry);1074    setView("add");1075  }10761077  const isLockedView = () => view() === "lock";10781079  async function handleApprovePendingPasskey() {1080    const pending = pendingPasskey();1081    if (!pending) return;1082    if (pending.browser === "firefox" && pending.type === "create") {1083      // Firefox path: popup itself runs navigator.credentials.create. The1084      // background never approved/rejected anything — it just stashed1085      // intent. After the popup-driven flow resolves (success or cancel),1086      // clear the pending key so the popup doesn't re-show this on next open.1087      const { createFirefoxPasskey } = await import("./firefox-passkey");1088      const result = await createFirefoxPasskey(pending);1089      if (!result.ok) {1090        console.warn("Peach Firefox passkey create failed:", result.error);1091      }1092      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1093      setPendingPasskey(null);1094      void loadEntries();1095      window.close();1096      return;1097    }1098    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1099    window.close();1100  }11011102  async function handleDenyPendingPasskey() {1103    const pending = pendingPasskey();1104    if (!pending) return;1105    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1106    window.close();1107  }11081109  function queueContentIdle(after?: () => void) {1110    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1111    contentPhaseTimer = window.setTimeout(() => {1112      setContentPhase("idle");1113      after?.();1114    }, ENTRY_TRANSITION_SETTLE_MS);1115  }11161117  return (1118    <div class="popup-root peach-theme">1119      <Show when={bootState() === "ready"}>1120        <Show1121          when={!pendingPasskey()}1122          fallback={1123            <PasskeyApprovalView1124              type={pendingPasskey()!.type}1125              rpName={pendingPasskey()!.rpName}1126              rpId={pendingPasskey()!.rpId}1127              userName={pendingPasskey()!.userName}1128              userDisplayName={pendingPasskey()!.userDisplayName}1129              onApprove={handleApprovePendingPasskey}1130              onDeny={handleDenyPendingPasskey}1131            />1132          }1133        >1134          <Show1135            when={!isLockedView()}1136            fallback={1137              <Show1138                when={onboarded() || hasVault()}1139                fallback={1140                  <Onboarding1141                    onComplete={() => { setOnboarded(true); }}1142                  />1143                }1144              >1145                <LockView1146                  hasVault={hasVault()}1147                  ready={bootState() === "ready"}1148                  isPro={proStatus()}1149                  forceRecoveryWords={forceRecoveryWords()}1150                  onUnlock={() => {1151                    // RecoveryWordDisplay clears the storage flag before1152                    // calling onDone, so handleUnlock will see no pending1153                    // confirmation and proceed through the normal path.1154                    if (forceRecoveryWords()) setForceRecoveryWords(false);1155                    return handleUnlock();1156                  }}1157                  onBackToOnboarding={1158                    !hasVault()1159                      ? () => setOnboarded(false)1160                      : undefined1161                  }1162                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1163                />1164              </Show>1165            }1166          >1167            <Show1168              when={view() !== "pro-celebration"}1169              fallback={<ProCelebration />}1170            >1171            <section1172              id="hd-shell"1173              class="peach-shell peach-theme"1174              data-surface="extension"1175            >1176            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1177              <PeachWordmark unlocked />1178              <div class="peach-chrome-actions">1179                <button1180                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1181                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1182                  aria-label="Notes"1183                  title="Notes"1184                >1185                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1186                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1187                    <line x1="4" y1="5" x2="10" y2="5" />1188                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1189                    <line x1="4" y1="10" x2="7" y2="10" />1190                  </svg>1191                </button>1192                <button1193                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1194                  onClick={() => setView("settings")}1195                  aria-label="Settings"1196                >1197                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1198                    <path1199                      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"1200                      stroke="currentColor"1201                      stroke-width="0.9"1202                    />1203                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1204                  </svg>1205                </button>1206                <button1207                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1208                  onClick={handleAdd}1209                  aria-label="New entry"1210                >1211                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1212                    <path d="M5.5 1v9M1 5.5h9" />1213                  </svg>1214                </button>1215                <button1216                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1217                  onClick={() => void handleHeaderLock()}1218                  aria-label="Lock vault"1219                >1220                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1221                    <path1222                      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"1223                      stroke="currentColor"1224                      stroke-width="1"1225                      stroke-linecap="round"1226                    />1227                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1228                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1229                  </svg>1230                </button>1231              </div>1232            </header>12331234            <Show when={pendingProNotice() !== null}>1235              <div class="peach-pro-notice-banner">1236                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1237                <button1238                  class="peach-pro-notice-link"1239                  onClick={() => {1240                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1241                    setSettingsInitialSection("license");1242                    setView("settings");1243                    setPendingProNotice(null);1244                  }}1245                >1246                  Learn more →1247                </button>1248                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1249              </div>1250            </Show>12511252            <div class="peach-shell-body">1253              <div class="peach-shell-veil"></div>1254              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1255                <EntryView1256                  entry={selectedEntry()}1257                  currentTabUrl={currentTabUrl()}1258                  entries={entries()}1259                  isPro={proStatus()}1260                  onDelete={handleDelete}1261                  onFieldSaved={() => void loadEntries()}1262                  onEscape={() => { setView("list"); }}1263                  onProGate={(feature) => {1264                    setUpgradeHighlight(feature);1265                    setSettingsInitialSection("license");1266                    setView("settings");1267                  }}1268                />1269              </div>12701271              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1272                <div class="peach-search-bar">1273                  <span class="peach-search-icon">1274                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1275                      <circle cx="5.5" cy="5.5" r="3.75" />1276                      <path d="M8.75 8.75L11.5 11.5" />1277                    </svg>1278                  </span>1279                  <input1280                    class="peach-search-input"1281                    placeholder="search vault..."1282                    autocomplete="off"1283                    aria-label="Search vault entries"1284                    onClick={openList}1285                    onFocus={openList}1286                    readOnly1287                  />1288                  <div class="peach-search-meta">1289                    <span class="peach-search-counter">1290                      {entries().length > 01291                        ? `${selectedIndex() + 1} / ${entries().length}`1292                        : "0 entries"}1293                    </span>1294                    <span class="peach-divider"></span>1295                    <button1296                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1297                      onClick={() => navigate(-1)}1298                      aria-label="Previous entry"1299                      disabled={entries().length === 0}1300                    >1301                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1302                        <path d="M5 1L1 5.5L5 10" />1303                      </svg>1304                    </button>1305                    <button1306                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1307                      onClick={() => navigate(1)}1308                      aria-label="Next entry"1309                      disabled={entries().length === 0}1310                    >1311                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1312                        <path d="M1 1L5 5.5L1 10" />1313                      </svg>1314                    </button>1315                  </div>1316                </div>1317              </section>1318            </div>13191320            {/* Desktop: shown on demand via Show. Native sheet is rendered1321                via Portal below at the document root so its position:fixed1322                isn't trapped by .peach-shell's transform-based animations. */}1323            <Show when={!isNativePlatform() && view() === "list"}>1324              <VaultView1325                entries={entries()}1326                selectedEntryId={selectedEntry()?.id}1327                currentTabDomain={currentTabDomain()}1328                sortOrder={sortOrder()}1329                searchSeed={listSearchSeed()}1330                searchSeedNonce={listSearchSeedNonce()}1331                onSelectEntry={handleSelectEntry}1332                onSortOrderChange={setSortOrder}1333                onAdd={handleAdd}1334                onClose={() => setView("entry")}1335                onOpenTrash={() => setView("trash")}1336                onDeleteMany={handleDeleteMany}1337              />1338            </Show>1339            <Show when={isNativePlatform() && hasVault()}>1340              <Portal>1341                <div1342                  class="peach-vault-sheet"1343                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1344                  style={(() => {1345                    const live = sheetTranslate();1346                    if (live === null) return undefined;1347                    return { transform: `translateY(${live}px)` };1348                  })()}1349                >1350                  <VaultView1351                    entries={entries()}1352                    selectedEntryId={selectedEntry()?.id}1353                    currentTabDomain={currentTabDomain()}1354                    sortOrder={sortOrder()}1355                    searchSeed={listSearchSeed()}1356                    searchSeedNonce={listSearchSeedNonce()}1357                    isNative={true}1358                    onSelectEntry={handleSelectEntry}1359                    onSortOrderChange={setSortOrder}1360                    onAdd={handleAdd}1361                    onClose={() => setView("entry")}1362                    onOpenTrash={() => setView("trash")}1363                    onDeleteMany={handleDeleteMany}1364                  />1365                </div>1366              </Portal>1367            </Show>1368            <Show when={view() === "settings" || settingsExiting()}>1369              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1370                <SettingsView1371                  entriesCount={entries().length}1372                  breachMonitoring={breachMonitoring()}1373                  lockOnClose={lockOnClose()}1374                  autoLockMinutes={autoLockMinutes()}1375                  trashRetentionDays={trashRetentionDays()}1376                  theme={theme()}1377                  accentColor={accentColor()}1378                  textSize={textSize()}1379                  reduceMotion={reduceMotion()}1380                  isPro={proStatus()}1381                  initialSection={settingsInitialSection()}1382                  upgradeHighlight={upgradeHighlight()}1383                  isExiting={settingsExiting()}1384                  onBreachMonitoringChange={applyBreachMonitoring}1385                  onLockOnCloseChange={applyLockOnClose}1386                  onAutoLockMinutesChange={applyAutoLockMinutes}1387                  onTrashRetentionChange={applyTrashRetention}1388                  onThemeChange={applyTheme}1389                  onAccentChange={applyAccentColor}1390                  onTextSizeChange={applyTextSize}1391                  onReduceMotionChange={applyReduceMotion}1392                  shortcuts={shortcutBindings()}1393                  onShortcutsChange={applyShortcuts}1394                  onLicenseChange={async () => {1395                    // After activation/deactivation: refresh Pro status,1396                    // re-load entries (defensive — signal state can drift if1397                    // the SW briefly restarts during the verify+save round-trip),1398                    // and replay the Pro celebration if this is the first time1399                    // a valid Pro license is seen on this device.1400                    await refreshProStatus();1401                    void loadEntries();1402                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1403                    if ((should as { ok: boolean; data?: boolean }).data === true) {1404                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1405                      // When activating from Settings, the in-deck fan animation1406                      // IS the celebration — skip the full-screen overlay so1407                      // Settings isn't unmounted mid-animation.1408                      if (view() !== "settings") {1409                        setView("pro-celebration");1410                        window.setTimeout(() => setView("settings"), 2500);1411                      }1412                    }1413                  }}1414                  onBack={() => {1415                    setSettingsExiting(true);1416                    window.setTimeout(() => {1417                      setSettingsExiting(false);1418                      setSettingsInitialSection(null);1419                      setUpgradeHighlight(null);1420                      handleBack();1421                    }, 200);1422                  }}1423                  onImport={() => setView("import")}1424                  onExport={() => setView("export")}1425                  onBreachCheckDone={loadEntries}1426                  onOpenHealth={openHealth}1427                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("chirp-sync"); }}1428                  onOpenFileImport={handleOpenFileImport}1429                  onOpenPanic={() => setView("panic")}1430                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1431                  onOpenCodexRestore={() => setView("codex-restore")}1432                  onCardChange={setSettingsActiveCard}1433                  onProGate={(feature) => {1434                    setUpgradeHighlight(feature);1435                    setSettingsInitialSection("license");1436                  }}1437                />1438              </Suspense>1439            </Show>1440            <Show when={view() === "codex-generate"}>1441              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1442                <CodexGenerateView1443                  isPro={proStatus()}1444                  onBack={() => setView("settings")}1445                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1446                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1447                  onVaultLocked={() => handleLock()}1448                />1449              </Suspense>1450            </Show>1451            <Show when={view() === "codex-restore"}>1452              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1453                <CodexRestoreView1454                  onBack={() => setView("lock")}1455                  onRestoreSuccess={async () => {1456                    // After restore the vault is unlocked; refresh entries1457                    // and route to the main vault list. handleUnlock is the1458                    // canonical post-unlock setup path.1459                    await handleUnlock();1460                  }}1461                />1462              </Suspense>1463            </Show>1464            <Show when={view() === "chirp-sync"}>1465              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1466                <ChirpSyncView1467                  isPro={proStatus()}1468                  onBack={() => setView("settings")}1469                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1470                />1471              </Suspense>1472            </Show>1473            <Show when={view() === "add"}>1474              <AddView1475                entry={editEntry()}1476                entries={entries()}1477                onBack={handleBack}1478                onSave={handleSave}1479              />1480            </Show>1481            <Show when={view() === "import"}>1482              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1483                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1484              </Suspense>1485            </Show>1486            <Show when={view() === "export"}>1487              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1488                <ExportView onBack={handleExportBack} />1489              </Suspense>1490            </Show>1491            <Show when={view() === "panic"}>1492              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1493                <PanicView1494                  onCancel={() => setView("settings")}1495                  onOpenExport={() => {1496                    setReturnToPanic(true);1497                    setView("export");1498                  }}1499                  onDestroyed={async () => {1500                    clearCanarySuppressions();1501                    setEntries([]);1502                    setSelectedEntry(null);1503                    setEditEntry(undefined);1504                    setHasVault(false);1505                    setOnboarded(false);1506                    setProStatus(false);1507                    setPendingPasskey(null);1508                    setUpgradeHighlight(null);1509                    setSettingsInitialSection(null);1510                    setPendingProNotice(null);1511                    setPendingCelebration(false);1512                    setReturnToPanic(false);1513                    setContentPhase("idle");1514                    setView("lock");1515                  }}1516                />1517              </Suspense>1518            </Show>1519            {/* Health stays mounted while editing an entry from it so1520                computeReused() doesn't rerun on every cancel/back. */}1521            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1522              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1523                <HealthView1524                  entries={entries()}1525                  isPro={proStatus()}1526                  onFixEntry={handleFixEntry}1527                  onBack={() => setView("settings")}1528                  onRefresh={loadEntries}1529                  hidden={view() !== "health"}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}