App.tsx

68.4 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageSet } from "../shared/storage";4import { sendMessage } from "../shared/bridge";5import { ACCENT_COLORS } from "../shared/types";6import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";7import type { IncomingPairingRequest } from "../shared/sync-types";8import { isPasskeyOnly } from "../shared/types";9import { LockView } from "./views/Lock";10import { Onboarding } from "./views/Onboarding";11import { NotesMode } from "./views/NotesMode";12import { ProCelebration } from "./views/ProCelebration";13import { VaultView, type SortOrder } from "./views/Vault";14import { EntryView } from "./views/Entry";15import { AddView } from "./views/Add";16import { PeachMark, PeachWordmark } from "./components/PeachMark";17import { PasskeyApprovalView } from "./views/PasskeyApproval";18import { extractDomain } from "../shared/domain";19import { popupCopy } from "./copy";20import {21  DEFAULT_BINDINGS,22  formatKeybinding,23  getActiveBindings,24  matchKeybinding,25  SHORTCUT_DESCRIPTORS,26  type Keybinding,27  type ShortcutAction,28} from "../shared/shortcuts";29import { generateTOTP } from "../crypto/totp";30import { isNativePlatform, nativePlugin } from "../shared/native";3132export { sendMessage } from "../shared/bridge";3334const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));35const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));36const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));37const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));38const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));39const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));40const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));41const AddDeviceView   = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.AddDeviceView })));42const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));43const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));4445type View =46  | "lock"47  | "pro-celebration"48  | "entry"49  | "list"50  | "add"51  | "settings"52  | "sync-pairing"53  | "sync-add-device"54  | "import"55  | "export"56  | "health"57  | "trash"58  | "panic"59  | "codex-generate"60  | "codex-restore";61type BootState = "loading" | "ready";6263const canarySuppressMap = new Map<string, boolean>();64let shellRingAnimation: Animation | null = null;6566export function isCanarySuppressed(entryId: string): boolean {67  return canarySuppressMap.get(entryId) ?? false;68}6970export function setCanarySuppressed(entryId: string, suppressed: boolean): void {71  canarySuppressMap.set(entryId, suppressed);72}7374export function clearCanarySuppressions(): void {75  canarySuppressMap.clear();76}7778export function triggerRing() {79  const shell = document.getElementById("hd-shell");80  if (!shell) return;8182  shellRingAnimation?.cancel();83  shell.dataset.glowing = "true";84  const animation = shell.animate(85    [86      { offset: 0, boxShadow: "var(--copy-shadow)" },87      {88        offset: 0.3,89        boxShadow:90          "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)",91      },92      { offset: 1, boxShadow: "var(--copy-shadow)" },93    ],94    {95      duration: 720,96      easing: "cubic-bezier(0.4, 0, 0.2, 1)",97      fill: "none",98    }99  );100  shellRingAnimation = animation;101  const clearGlow = () => {102    if (shellRingAnimation !== animation) return;103    shellRingAnimation = null;104    delete shell.dataset.glowing;105  };106  animation.onfinish = clearGlow;107  animation.oncancel = clearGlow;108}109110111export function triggerPipPulse() {112  const pip = document.querySelector(".peach-status-pip, .pip");113  if (pip) {114    pip.classList.remove("pulse");115    void (pip as HTMLElement).offsetWidth;116    pip.classList.add("pulse");117  }118}119120const ENTRY_TRANSITION_EXIT_MS = 95;121const ENTRY_TRANSITION_SETTLE_MS = 135;122123export default function App() {124  const [bootState, setBootState] = createSignal<BootState>("loading");125  const [view, setView] = createSignal<View>("lock");126  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,127  // CSS transition takes over for snap animation).128  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);129  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(130    "enter"131  );132  const [contentTransitioning, setContentTransitioning] = createSignal(false);133  const [hasVault, setHasVault] = createSignal(false);134  const [onboarded, setOnboarded] = createSignal(true);135  const [entries, setEntries] = createSignal<VaultEntry[]>([]);136  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);137  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);138  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");139  const [theme, setTheme] = createSignal<"dark" | "light">("dark");140  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");141  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");142  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);143  const [lockOnClose, setLockOnClose] = createSignal(true);144  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);145  const [breachMonitoring, setBreachMonitoring] = createSignal(true);146  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);147  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);148  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);149  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);150  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);151  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");152  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");153  // Cached Pro status — synchronous for render paths. Background's154  // GET_LICENSE is async, but render-time reads of isPro() must not block.155  // Refreshed at boot, after activate/deactivate, and whenever the popup156  // re-opens onto a stored license that has changed via another window.157  const [proStatus, setProStatus] = createSignal(false);158  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);159  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);160  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");161  const [listSearchSeed, setListSearchSeed] = createSignal("");162  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);163  const [pendingCelebration, setPendingCelebration] = createSignal(false);164  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);165  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);166  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);167  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);168  const [incomingPairTick, setIncomingPairTick] = createSignal(0);169  const incomingPairSecondsLeft = () => {170    void incomingPairTick();171    const req = incomingPair();172    if (!req) return 0;173    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));174  };175  // True while Panic Step 1 has bounced the user out to Export. When Export's176  // onBack fires we return to Panic instead of Settings so the user keeps the177  // destruction context they came from.178  const [returnToPanic, setReturnToPanic] = createSignal(false);179  const [showNotes, setShowNotes] = createSignal(false);180  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);181  // Set on popup boot when peach_recovery_pending flag is found in session182  // storage — instructs LockView to skip the unlock UI and open the recovery183  // words confirmation surface instead. Cleared via handleUnlock once the184  // user has typed the 3 confirmation words.185  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);186187  let contentPhaseTimer: number | undefined;188189  function applyAccent(name: AccentColorName) {190    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;191    const hex = color.hex;192    document.documentElement.style.setProperty("--peach-accent", hex);193    // Ambient surface variables — derived from the accent so surfaces shift194    // subtly toward the accent hue rather than staying fixed warm-brown.195    document.documentElement.style.setProperty("--peach-glow", hex + "2A");196    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");197    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");198  }199200  createEffect(() => {201    applyAccent(accentColor());202  });203204  createEffect(() => {205    document.documentElement.classList.toggle("light", theme() === "light");206    document.body.classList.toggle("light", theme() === "light");207  });208209  createEffect(() => {210    document.documentElement.setAttribute("data-display-font", displayFont());211  });212213  createEffect(() => {214    document.documentElement.setAttribute("data-text-size", textSize());215  });216217  createEffect(() => {218    if (reduceMotion()) {219      document.documentElement.setAttribute("data-motion", "reduce");220    } else {221      document.documentElement.removeAttribute("data-motion");222    }223  });224225  const selectedIndex = createMemo(() => {226    const currentId = selectedEntry()?.id;227    if (!currentId) return entries().length > 0 ? 0 : -1;228    return entries().findIndex((entry) => entry.id === currentId);229  });230231  async function applyAccentColor(name: AccentColorName) {232    applyAccent(name);233    setAccentColor(name);234    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });235  }236237  async function applyTheme(t: "dark" | "light") {238    setTheme(t);239    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });240  }241242  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {243    setDisplayFont(f);244    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });245  }246247  async function applyTextSize(size: "small" | "medium" | "large") {248    setTextSize(size);249    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });250  }251252  async function applyReduceMotion(enabled: boolean) {253    setReduceMotion(enabled);254    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });255  }256257  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload258  // small and lets future default updates land for actions the user hasn't259  // touched. Settings sends us the full active map; we filter and store.260  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {261    setShortcutBindings(active);262    const overrides: Record<string, Keybinding> = {};263    for (const action of Object.keys(active) as ShortcutAction[]) {264      const a = active[action];265      const d = DEFAULT_BINDINGS[action];266      const same = a.key === d.key267        && Boolean(a.ctrl)  === Boolean(d.ctrl)268        && Boolean(a.meta)  === Boolean(d.meta)269        && Boolean(a.shift) === Boolean(d.shift)270        && Boolean(a.alt)   === Boolean(d.alt);271      if (!same) overrides[action] = a;272    }273    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });274  }275276  async function applyLockOnClose(enabled: boolean) {277    setLockOnClose(enabled);278    await sendMessage({279      type: "UPDATE_SETTINGS",280      payload: { lockOnClose: enabled },281    });282  }283284  async function applyAutoLockMinutes(minutes: number) {285    setAutoLockMinutes(minutes);286    await sendMessage({287      type: "UPDATE_SETTINGS",288      payload: { autoLockMinutes: minutes },289    });290  }291292  async function applyBreachMonitoring(enabled: boolean) {293    setBreachMonitoring(enabled);294    await sendMessage({295      type: "UPDATE_SETTINGS",296      payload: { breachMonitoring: enabled },297    });298  }299300  onMount(async () => {301    // Resolve the active tab in parallel with the unlock/has-vault queries —302    // openVault()'s smart selection picks the entry matching currentTabDomain,303    // so it must be populated before openVault runs. Previously refreshCurrentTab304    // ran after openVault, leaving popups that booted already-unlocked falling305    // back to loadedEntries[0] instead of the domain match.306    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([307      sendMessage({ type: "IS_UNLOCKED" }),308      sendMessage({ type: "HAS_VAULT" }),309      refreshCurrentTab(),310      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),311    ]);312    const unlocked = Boolean(313      (unlockResponse as { ok: boolean; data?: boolean }).data314    );315    const vaultExists = Boolean(316      (vaultResponse as { ok: boolean; data?: boolean }).data317    );318    const shouldCelebrate = Boolean(319      (celebrationResponse as { ok: boolean; data?: boolean }).data320    );321    setHasVault(vaultExists);322    // Onboarding gate — show once on first install, never again. Existing323    // users (vaultExists) are auto-marked onboarded so they skip the flow324    // even on the very first popup open after this feature ships.325    try {326      const onboarded = await storageGet("peach_onboarded");327      const seen = onboarded === "true";328      if (vaultExists && !seen) {329        await storageSet("peach_onboarded", "true");330        setOnboarded(true);331      } else {332        setOnboarded(seen);333      }334    } catch {335      // storage unavailable — default to onboarded so we never block boot336      setOnboarded(true);337    }338    await Promise.all([restoreSettings(), refreshProStatus()]);339340    // Mark played before any animation so a crash mid-sequence never replays it341    if (shouldCelebrate) {342      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });343    }344345    // If the user created a vault but hasn't yet confirmed their recovery346    // words, route back to the recovery-words screen instead of opening the347    // entries view. The flag lives in chrome.storage.local so it survives348    // both popup close (SW suppresses lock-on-close) and full browser349    // restart (handleUnlock checks the same flag after a fresh password350    // unlock). Cleared when confirmation succeeds.351    let recoveryPending = false;352    try {353      const out = await chrome.storage.local?.get("peach_recovery_pending");354      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";355    } catch { /* best-effort */ }356357    // Native: closing the app before recovery-words confirmation means the358    // user didn't finish vault creation. Throw the partial vault away and359    // restart onboarding rather than asking them to unlock a vault they360    // never finished creating. Desktop keeps the existing "unlock to361    // resume" flow because closing the popup there is much more casual.362    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {363      try {364        await chrome.storage.local?.remove([365          "peach_vault_a",366          "peach_vault_b",367          "peach_recovery_pending",368          "peach_onboarded",369          "peach_vault_history",370        ]);371      } catch { /* best-effort */ }372      setHasVault(false);373      setOnboarded(false);374      setView("lock");375      setBootState("ready");376      document.getElementById("pre-lock")?.setAttribute("hidden", "true");377      return;378    }379380    if (recoveryPending && unlocked) {381      // forceRecoveryWords overrides LockView's hasVault gate so the382      // recovery surface renders even though the vault now exists.383      setForceRecoveryWords(true);384      setView("lock");385    } else if (unlocked && vaultExists) {386      await openVault(undefined, shouldCelebrate);387      if (shouldCelebrate) {388        setView("pro-celebration");389        window.setTimeout(() => setView("entry"), 2500);390      }391    } else if (shouldCelebrate) {392      setPendingCelebration(true);393    }394395    await refreshPendingPasskey();396    await refreshIncomingPairing();397    await consumeRecentPairing();398399    // Track tab changes so smart sort stays current400    const handleTabActivated = () => { void refreshCurrentTab(); };401    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {402      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();403    };404    try {405      chrome.tabs.onActivated.addListener(handleTabActivated);406      chrome.tabs.onUpdated.addListener(handleTabUpdated);407      onCleanup(() => {408        chrome.tabs.onActivated.removeListener(handleTabActivated);409        chrome.tabs.onUpdated.removeListener(handleTabUpdated);410      });411    } catch {412      // tabs permission may not be available in all contexts413    }414415    setBootState("ready");416    document.getElementById("pre-lock")?.setAttribute("hidden", "true");417418    // Check for pending session-storage notices from the background.419    if (chrome.storage.session) {420      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as421        Record<string, { feature?: string } | undefined>;422      if (session.pendingProGate?.feature) {423        await chrome.storage.session.remove("pendingProGate");424        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);425        setSettingsInitialSection("license");426        setView("settings");427      } else if (session.pendingProNotice?.feature) {428        await chrome.storage.session.remove("pendingProNotice");429        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });430      }431    }432433    // Warm the lazy-module cache so the Suspense fallback never shows for434    // locally-bundled extension views. Without this, the first navigation to435    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which436    // covers the shell and absorbs clicks on the header.437    void Promise.all([438      import("./views/Settings").catch(() => {}),439      import("./views/Import").catch(() => {}),440      import("./views/Export").catch(() => {}),441      import("./views/Health").catch(() => {}),442      import("./views/TrashView").catch(() => {}),443    ]);444445    // Lock-on-close via a persistent port. sendMessage in pagehide is446    // unreliable — the popup context tears down before the message lands.447    // The SW's onConnect listener locks when this port disconnects.448    let popupPort: chrome.runtime.Port | null = null;449    try {450      popupPort = chrome.runtime.connect({ name: "popup" });451    } catch { /* extension context invalidated — ignore */ }452    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });453454    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only455    // reliable signal is appStateChange — setTimeout is killed when the OS456    // backgrounds the app. We measure elapsed background time on resume.457    if (isNativePlatform()) {458      let backgroundedAt: number | null = null;459      let syncPollInterval: ReturnType<typeof setInterval> | null = null;460461      function startSyncPolling() {462        if (syncPollInterval) return;463        syncPollInterval = setInterval(async () => {464          const res = await sendMessage({ type: 'TRIGGER_SYNC' }).catch(() => null);465          const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;466          if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {467            await sendMessage({ type: 'GET_ENTRIES' }).catch(() => null);468          }469        }, 60_000);470      }471472      function stopSyncPolling() {473        if (syncPollInterval) { clearInterval(syncPollInterval); syncPollInterval = null; }474      }475476      const CapApp = nativePlugin<{477        addListener: (478          ev: string,479          cb: (s: { isActive: boolean }) => void,480        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };481      }>("App");482      if (CapApp?.addListener) {483        const sub = CapApp.addListener(484          "appStateChange",485          ({ isActive }: { isActive: boolean }) => {486            if (!isActive) {487              backgroundedAt = Date.now();488              stopSyncPolling();489              return;490            }491            if (backgroundedAt !== null && autoLockMinutes() > 0) {492              const elapsed = Date.now() - backgroundedAt;493              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();494            }495            backgroundedAt = null;496            // Resume polling when app comes to foreground (Pro only).497            if (proStatus()) startSyncPolling();498          }499        );500        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.501        onCleanup(() => {502          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});503          stopSyncPolling();504        });505      }506    }507508    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale509    // entries instead of waiting for the next GET_ENTRIES round-trip.510    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {511      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();512      if (msg?.type === "PRO_GATE_TRIGGERED") {513        setUpgradeHighlight(msg.payload?.feature ?? null);514        setSettingsInitialSection("license");515        setView("settings");516      }517    };518    chrome.runtime.onMessage.addListener(handleRuntimeMessage);519    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));520521    // Android hardware/gesture back. MainActivity fires peach:back; the popup522    // decides what "back" means per surface. Lock+no-vault is the common case523    // — return to onboarding rather than letting the OS dismiss the activity.524    const handlePeachBack = () => {525      // Notes mode captures back first526      if (showNotes()) {527        setShowNotes(false);528        setOpenNoteId(undefined);529        return;530      }531      const v = view();532      if (v === "lock" && !hasVault() && onboarded()) {533        setOnboarded(false);534        return;535      }536      if (v === "list") { setView("entry"); return; }537      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {538        handleBack();539        return;540      }541      if (v === "sync-pairing") { setView("settings"); return; }542    };543    window.addEventListener("peach:back", handlePeachBack);544    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));545546    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that547    // peeks from the bottom (search bar handle visible) and drags up to fill548    // the screen. dragOffset is the LIVE finger offset during a drag, in px,549    // 0 when no drag in progress. The wrapper element computes transform =550    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.551    if (isNativePlatform()) {552      let touchStartY = 0;553      let touchStartX = 0;554      let lastY = 0;555      let lastT = 0;556      let dragging = false;557      let captured = false;558      const HORIZONTAL_TOLERANCE = 16;559      const ACTIVATION_DY = 8;560      const PEEK_PX = 60;561562      const onTouchStart = (e: TouchEvent) => {563        const t = e.touches[0];564        if (!t) return;565        const v = view();566        if (v !== "entry" && v !== "list") return;567        // Entry view: only intercept drags starting in the bottom 40%.568        // List view: intercept drags starting in the top 35% (the search/handle row).569        const inBand = v === "entry"570          ? t.clientY > window.innerHeight * 0.6571          : t.clientY < window.innerHeight * 0.35;572        if (!inBand) return;573        touchStartY = lastY = t.clientY;574        touchStartX = t.clientX;575        lastT = e.timeStamp;576        dragging = true;577        captured = false;578      };579580      const onTouchMove = (e: TouchEvent) => {581        if (!dragging) return;582        const t = e.touches[0];583        if (!t) return;584        const dy = t.clientY - touchStartY;585        const dx = Math.abs(t.clientX - touchStartX);586587        if (!captured) {588          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {589            // Looks like a horizontal swipe — release.590            dragging = false;591            return;592          }593          if (Math.abs(dy) < ACTIVATION_DY) return;594          captured = true;595        }596597        // Translate the sheet by dy from its rest (peek) position. Peek is598        // (viewport height - PEEK_PX). Open is 0.599        const v = view();600        const restClosed = window.innerHeight - PEEK_PX;601        const baseTranslate = v === "list" ? 0 : restClosed;602        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));603        setSheetTranslate(next);604        lastY = t.clientY;605        lastT = e.timeStamp;606      };607608      const onTouchEnd = (e: TouchEvent) => {609        if (!dragging) { return; }610        const t = e.changedTouches[0];611        const elapsed = Math.max(1, e.timeStamp - lastT);612        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms613        const wasCaptured = captured;614        dragging = false;615        captured = false;616        const v = view();617618        if (!wasCaptured) {619          // Tap in the peek strip while in entry view → open the vault list.620          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");621          setSheetTranslate(null);622          return;623        }624625        const restClosed = window.innerHeight - PEEK_PX;626        const current = sheetTranslate() ?? restClosed;627628        // Snap rules:629        //   - Strong upward velocity → open630        //   - Strong downward velocity → close631        //   - Otherwise snap to whichever rest is closer632        let nextOpen: boolean;633        if (velocity < -0.05) nextOpen = true;634        else if (velocity > 0.05) nextOpen = false;635        else nextOpen = current < restClosed * 0.5;636637        if (nextOpen && v !== "list") setView("list");638        if (!nextOpen && v !== "entry") setView("entry");639        // Release the live offset so CSS transition handles the snap.640        setSheetTranslate(null);641      };642643      document.addEventListener("touchstart", onTouchStart, { passive: true });644      document.addEventListener("touchmove",  onTouchMove,  { passive: true });645      document.addEventListener("touchend",   onTouchEnd,   { passive: true });646      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });647      onCleanup(() => {648        document.removeEventListener("touchstart", onTouchStart);649        document.removeEventListener("touchmove",  onTouchMove);650        document.removeEventListener("touchend",   onTouchEnd);651      });652    }653654    // Action handlers — keyed by ShortcutAction. The dispatcher below tests655    // each binding against the event and runs the matching handler. New656    // shortcuts only need an entry here; the binding is data, not code.657    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {658      copy_password: () => {659        const entry = selectedEntry();660        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });661      },662      copy_username: () => {663        const entry = selectedEntry();664        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });665      },666      copy_totp: () => {667        const entry = selectedEntry();668        if (!entry?.totp) return;669        try {670          const { code } = generateTOTP(entry.totp);671          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });672        } catch { /* invalid TOTP secret — silent */ }673      },674      new_entry: () => handleAdd(),675      edit_entry: () => {676        const entry = selectedEntry();677        // Passkey-only entries have nothing user-editable in the Add view; the678        // passkey credential itself is opaque. Skip the edit action for them.679        if (!entry || isPasskeyOnly(entry)) return;680        setEditEntry(entry);681        setView("add");682      },683      delete_entry: () => {684        if (selectedEntry()) void handleDelete();685      },686      lock_vault: () => { void handleHeaderLock(); },687      search: () => openList(),688      nav_prev: () => navigate(-1),689      nav_next: () => navigate(1),690      jump_vault: () => setView("entry"),691      jump_settings: () => setView("settings"),692      show_help: () => setShowShortcutsHelp(true),693    };694695    // Actions that are MEANINGFUL only on the entry-detail view. Outside696    // that scope the binding is dormant — pressing C while on Settings697    // does nothing rather than awkwardly copying from a now-stale entry.698    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([699      "copy_password", "copy_username", "copy_totp",700      "edit_entry", "delete_entry", "nav_prev", "nav_next",701    ]);702703    const handleGlobalKeydown = (e: KeyboardEvent) => {704      const v = view();705      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"706        || (e.target as HTMLElement)?.tagName === "TEXTAREA"707        || (e.target as HTMLElement)?.isContentEditable;708      const isPrintableSearchKey =709        e.key.length === 1 &&710        !e.ctrlKey &&711        !e.metaKey &&712        !e.altKey;713714      // No input during the pro celebration sequence715      if (v === "pro-celebration") return;716717      // Help dialog: Escape closes it; eat the keypress so it doesn't718      // also navigate away from the underlying view.719      if (showShortcutsHelp()) {720        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }721        return;722      }723724      // ── Escape — fixed binding (not user-customizable) ───────725      if (e.key === "Escape") {726        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }727        if (v === "list") { setView("entry"); return; }728        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }729        if (v === "sync-pairing") { setView("settings"); return; }730        if (v === "sync-add-device") { setView("sync-pairing"); return; }731      }732733      // Bindings-driven dispatch. Single-key letter bindings without734      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is735      // inside an input, so users can type into search/forms normally.736      const bindings = shortcutBindings();737      for (const action of Object.keys(bindings) as ShortcutAction[]) {738        const binding = bindings[action];739        if (!matchKeybinding(e, binding)) continue;740        // Single-key letter bindings need the input-focus guard. Bindings741        // with any modifier are safe — Ctrl+L doesn't conflict with typing.742        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;743        if (!hasMod && binding.key.length === 1 && inInput) return;744        if (ENTRY_SCOPED.has(action) && v !== "entry") return;745        e.preventDefault();746        SHORTCUT_HANDLERS[action]?.();747        return;748      }749750      // Type-to-search: in entry view, any printable key not consumed by a751      // shortcut above primes the list search seed and opens the list.752      // Kept outside the bindings table because it's a behavior, not a753      // discrete action — every printable character can trigger it.754      if (v === "entry" && !inInput && isPrintableSearchKey) {755        e.preventDefault();756        primeListSearch(e.key);757        return;758      }759    };760    window.addEventListener("keydown", handleGlobalKeydown);761    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));762763    const handleStorageChanged = (764      changes: Record<string, chrome.storage.StorageChange>,765      areaName: string766    ) => {767      if (areaName !== "session") return;768      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {769        return;770      }771      void refreshPendingPasskey();772    };773    chrome.storage.onChanged.addListener(handleStorageChanged);774    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));775  });776777  async function refreshCurrentTab() {778    try {779      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });780      const url = tab?.url ?? tab?.pendingUrl ?? "";781      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");782      // Skip extension/internal URLs — adding chrome://, about:, or783      // chrome-extension:// to a vault entry is never what the user wants.784      const isWebUrl = /^https?:\/\//i.test(url);785      setCurrentTabUrl(isWebUrl ? url : "");786    } catch {787      setCurrentTabDomain("");788      setCurrentTabUrl("");789    }790  }791792  async function refreshPendingPasskey() {793    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });794    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);795  }796797  async function refreshIncomingPairing() {798    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });799    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;800    setIncomingPair(data);801  }802803  // Drains a single one-shot record left by the background when 6-digit804  // pairing succeeded while the popup was closed (or the SyncPairing view was805  // navigated away from before it could show its own success card).806  async function consumeRecentPairing() {807    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });808    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;809    if (data?.deviceName) {810      setRecentPairToast(data.deviceName);811      window.setTimeout(() => setRecentPairToast(null), 4000);812    }813  }814815  async function respondIncomingPairing(accept: boolean) {816    if (incomingPairResponding()) return;817    setIncomingPairResponding(true);818    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });819    setIncomingPair(null);820    setIncomingPairResponding(false);821  }822823  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a824  // request appears, ticks once per second, and clears the banner if the825  // request expires while the popup is open.826  createEffect(() => {827    const req = incomingPair();828    if (!req) return;829    const handle = window.setInterval(() => {830      setIncomingPairTick((tick) => tick + 1);831      if (Date.now() >= req.expiresAt) {832        setIncomingPair(null);833        window.clearInterval(handle);834      }835    }, 1000);836    onCleanup(() => window.clearInterval(handle));837  });838839  async function refreshProStatus() {840    const res = await sendMessage({ type: "GET_LICENSE" });841    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;842    setProStatus(Boolean(data?.valid && data?.plan === "pro"));843  }844845  async function restoreSettings() {846    const res = await sendMessage({ type: "GET_SETTINGS" });847    const s = (res as { ok: boolean; data?: any }).data ?? {};848    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {849      setAccentColor(s.accentColor as AccentColorName);850    }851    setTheme(s.theme === "light" ? "light" : "dark");852    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {853      setDisplayFont(s.displayFont);854    } else {855      setDisplayFont("cormorant-italic");856    }857    if (s.textSize === "small" || s.textSize === "large") {858      setTextSize(s.textSize);859    } else {860      setTextSize("medium");861    }862    setReduceMotion(s.reduceMotion === true);863    setLockOnClose(s.lockOnClose !== false);864    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);865    setBreachMonitoring(s.breachMonitoring !== false);866    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);867    setShortcutBindings(getActiveBindings(s.shortcuts));868  }869870  async function applyTrashRetention(days: number) {871    setTrashRetentionDays(days);872    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });873  }874875  function primeListSearch(seed: string) {876    setListSearchSeed(seed);877    setListSearchSeedNonce((value) => value + 1);878    openList();879  }880881  // Returns null when it detected a dead service worker and triggered handleLock().882  // Callers that need to abort (e.g. openVault) check for null rather than relying883  // on view() state, which may already be "lock" during normal startup flows.884  async function loadEntries(): Promise<VaultEntry[] | null> {885    const response = await sendMessage({ type: "GET_ENTRIES" });886    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };887888    // If the service worker was killed and restarted (MV3 workers sleep), the889    // vault will be locked again — or the worker may not respond at all.890    // In either case, send the user to the lock screen rather than silently891    // showing an empty vault (which looks like data loss).892    if (!res.ok) {893      if (894        res.error === "vault locked" ||895        res.error === "SERVICE_WORKER_UNAVAILABLE" ||896        (typeof res.error === "string" && res.error.includes("locked"))897      ) {898        handleLock();899        return null; // signal emergency lock to callers900      }901      return [];902    }903904    const loadedEntries = res.data ?? [];905    setEntries(loadedEntries);906907    const currentId = selectedEntry()?.id;908    if (currentId) {909      setSelectedEntry(910        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null911      );912    }913914    return loadedEntries;915  }916917  async function openVault(preferredEntryId?: string, skipViewSet = false) {918    // Desktop: fire-and-forget sync on every vault open (Pro only).919    // Never blocks popup load; refreshes entries if new data arrives.920    if (!isNativePlatform() && proStatus()) {921      void sendMessage({ type: 'TRIGGER_SYNC' }).then((res) => {922        const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;923        if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {924          void loadEntries();925        }926      }).catch(() => {});927    }928929    // Purge expired trash entries on each vault open930    const retDays = trashRetentionDays();931    if (retDays > 0) {932      void sendMessage({933        type: "PURGE_EXPIRED_TRASH",934        payload: { retentionMs: retDays * 86_400_000 },935      });936    }937938    const loadedEntries = await loadEntries();939940    // null means loadEntries() triggered an emergency lock (service worker died).941    // Don't override it by setting view back to "entry" with an empty vault.942    if (loadedEntries === null) return;943944    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry945    let nextSelectedEntry: VaultEntry | null = null;946    if (preferredEntryId) {947      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;948    }949    if (!nextSelectedEntry) {950      const tabDomain = currentTabDomain();951      if (tabDomain) {952        nextSelectedEntry = loadedEntries.find((e) => {953          if (e.type === "login") {954            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;955            for (const extra of e.additionalUrls ?? []) {956              if ((extractDomain(extra) ?? "") === tabDomain) return true;957            }958            return false;959          }960          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;961          return false;962        }) ?? null;963      }964    }965    nextSelectedEntry ??= loadedEntries[0] ?? null;966967    setSelectedEntry(nextSelectedEntry);968    setEditEntry(undefined);969    setContentTransitioning(false);970    setContentPhase("enter");971    queueContentIdle();972    if (!skipViewSet) setView("entry");973  }974975  async function handleUnlock() {976    // If the user previously created a vault but hadn't yet confirmed their977    // recovery words (and the browser was closed before they could), the978    // peach_recovery_pending flag is still set in storage.local. Re-route979    // back to the recovery surface so they finish the confirmation step980    // before reaching the entries view — the words can be re-derived now981    // that the vault is unlocked again.982    let recoveryPending = false;983    try {984      const out = await chrome.storage.local?.get("peach_recovery_pending");985      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";986    } catch { /* best-effort */ }987    if (recoveryPending) {988      setForceRecoveryWords(true);989      setView("lock");990      triggerPipPulse();991      await restoreSettings();992      return;993    }994    setHasVault(true);995    triggerPipPulse();996    await restoreSettings();997    const celebrating = pendingCelebration();998    if (celebrating) {999      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1000      setPendingCelebration(false);1001    }1002    await openVault(undefined, celebrating);1003    if (celebrating) {1004      setView("pro-celebration");1005      window.setTimeout(() => setView("entry"), 2500);1006    }1007  }10081009  function handleSelectEntry(entry: VaultEntry) {1010    if (entry.type === "note") {1011      setOpenNoteId(entry.id);1012      setShowNotes(true);1013      return;1014    }1015    setSelectedEntry(entry);1016    setContentTransitioning(false);1017    setContentPhase("enter");1018    queueContentIdle();1019    setView("entry");1020  }10211022  function handleAdd() {1023    setEditEntry(undefined);1024    setView("add");1025  }10261027  async function handleDelete() {1028    const entry = selectedEntry();1029    if (!entry) return;1030    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1031    const loadedEntries = await loadEntries() ?? [];1032    setSelectedEntry(loadedEntries[0] ?? null);1033    setView("entry");1034  }10351036  async function handleDeleteMany(ids: string[]) {1037    for (const id of ids) {1038      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1039    }1040    const loadedEntries = await loadEntries() ?? [];1041    // If the currently selected entry was among the deleted, move to first1042    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1043    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1044  }10451046  async function handleSave(savedEntry?: VaultEntry) {1047    await openVault(savedEntry?.id);1048  }10491050  function handleBack() {1051    setEditEntry(undefined);1052    setView("entry");1053  }10541055  function handleLock() {1056    clearCanarySuppressions();1057    setEntries([]);1058    setSelectedEntry(null);1059    setEditEntry(undefined);1060    setContentPhase("idle");1061    setView("lock");1062  }10631064  function handleHeaderLock() {1065    // Lock the UI immediately — do not wait for the service worker. If the SW1066    // is dead or slow, the 5s sendMessage timeout would create a dead-click1067    // window. The SW will lock on its next wake regardless.1068    handleLock();1069    void sendMessage({ type: "LOCK" });1070  }10711072  function navigate(dir: number) {1073    const allEntries = entries();1074    if (allEntries.length === 0) return;1075    const currentIndex = selectedIndex();1076    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1077    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1078    setSelectedEntry(allEntries[nextIndex]);1079    setContentPhase("enter");1080    queueContentIdle();1081  }10821083  function openList() {1084    setView("list");1085  }10861087  function openHealth() {1088    setEditEntry(undefined);1089    setView("health");1090  }10911092  function handleOpenFileImport() {1093    setRestoreView("file");1094  }10951096  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10971098  function handleFixEntry(entry: VaultEntry) {1099    // Passkey-only entries have no editable surface — drop into view mode1100    // instead of opening the Add editor.1101    if (isPasskeyOnly(entry)) {1102      setSelectedEntry(entry);1103      setView("entry");1104      return;1105    }1106    setEditEntry(entry);1107    setView("add");1108  }11091110  const isLockedView = () => view() === "lock";11111112  async function handleApprovePendingPasskey() {1113    const pending = pendingPasskey();1114    if (!pending) return;1115    if (pending.browser === "firefox" && pending.type === "create") {1116      // Firefox path: popup itself runs navigator.credentials.create. The1117      // background never approved/rejected anything — it just stashed1118      // intent. After the popup-driven flow resolves (success or cancel),1119      // clear the pending key so the popup doesn't re-show this on next open.1120      const { createFirefoxPasskey } = await import("./firefox-passkey");1121      const result = await createFirefoxPasskey(pending);1122      if (!result.ok) {1123        console.warn("Peach Firefox passkey create failed:", result.error);1124      }1125      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1126      setPendingPasskey(null);1127      void loadEntries();1128      window.close();1129      return;1130    }1131    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1132    window.close();1133  }11341135  async function handleDenyPendingPasskey() {1136    const pending = pendingPasskey();1137    if (!pending) return;1138    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1139    window.close();1140  }11411142  function queueContentIdle(after?: () => void) {1143    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1144    contentPhaseTimer = window.setTimeout(() => {1145      setContentPhase("idle");1146      after?.();1147    }, ENTRY_TRANSITION_SETTLE_MS);1148  }11491150  return (1151    <div class="popup-root peach-theme">1152      <Show when={bootState() === "ready"}>1153        <Show1154          when={!pendingPasskey()}1155          fallback={1156            <PasskeyApprovalView1157              type={pendingPasskey()!.type}1158              rpName={pendingPasskey()!.rpName}1159              rpId={pendingPasskey()!.rpId}1160              userName={pendingPasskey()!.userName}1161              userDisplayName={pendingPasskey()!.userDisplayName}1162              onApprove={handleApprovePendingPasskey}1163              onDeny={handleDenyPendingPasskey}1164            />1165          }1166        >1167          <Show1168            when={!isLockedView()}1169            fallback={1170              <Show1171                when={onboarded() || hasVault()}1172                fallback={1173                  <Onboarding1174                    onComplete={() => { setOnboarded(true); }}1175                  />1176                }1177              >1178                <LockView1179                  hasVault={hasVault()}1180                  ready={bootState() === "ready"}1181                  isPro={proStatus()}1182                  forceRecoveryWords={forceRecoveryWords()}1183                  onUnlock={() => {1184                    // RecoveryWordDisplay clears the storage flag before1185                    // calling onDone, so handleUnlock will see no pending1186                    // confirmation and proceed through the normal path.1187                    if (forceRecoveryWords()) setForceRecoveryWords(false);1188                    return handleUnlock();1189                  }}1190                  onBackToOnboarding={1191                    !hasVault()1192                      ? () => setOnboarded(false)1193                      : undefined1194                  }1195                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1196                />1197              </Show>1198            }1199          >1200            <Show1201              when={view() !== "pro-celebration"}1202              fallback={<ProCelebration />}1203            >1204            <section1205              id="hd-shell"1206              class="peach-shell peach-theme"1207              data-surface="extension"1208            >1209            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1210              <PeachWordmark unlocked />1211              <div class="peach-chrome-actions">1212                <button1213                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1214                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1215                  aria-label="Notes"1216                  title="Notes"1217                >1218                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1219                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1220                    <line x1="4" y1="5" x2="10" y2="5" />1221                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1222                    <line x1="4" y1="10" x2="7" y2="10" />1223                  </svg>1224                </button>1225                <button1226                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1227                  onClick={() => setView("settings")}1228                  aria-label="Settings"1229                >1230                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1231                    <path1232                      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"1233                      stroke="currentColor"1234                      stroke-width="0.9"1235                    />1236                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1237                  </svg>1238                </button>1239                <button1240                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1241                  onClick={handleAdd}1242                  aria-label="New entry"1243                >1244                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1245                    <path d="M5.5 1v9M1 5.5h9" />1246                  </svg>1247                </button>1248                <button1249                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1250                  onClick={() => void handleHeaderLock()}1251                  aria-label="Lock vault"1252                >1253                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1254                    <path1255                      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"1256                      stroke="currentColor"1257                      stroke-width="1"1258                      stroke-linecap="round"1259                    />1260                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1261                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1262                  </svg>1263                </button>1264              </div>1265            </header>12661267            <Show when={recentPairToast()}>1268              <div class="peach-pair-toast" role="status" aria-live="polite">1269                Paired with <strong>{recentPairToast()}</strong>1270              </div>1271            </Show>12721273            <Show when={incomingPair() !== null}>1274              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1275                <div class="peach-pair-request-header">1276                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1277                  <span class="peach-pair-request-title">Pairing request</span>1278                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1279                </div>1280                <p class="peach-pair-request-body">1281                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1282                </p>1283                <div class="peach-pair-request-actions">1284                  <button1285                    class="peach-btn peach-btn--ghost peach-btn--sm"1286                    onClick={() => void respondIncomingPairing(false)}1287                    disabled={incomingPairResponding()}1288                  >1289                    Reject1290                  </button>1291                  <button1292                    class="peach-btn peach-btn--accent peach-btn--sm"1293                    onClick={() => void respondIncomingPairing(true)}1294                    disabled={incomingPairResponding()}1295                  >1296                    Accept1297                  </button>1298                </div>1299              </div>1300            </Show>13011302            <Show when={pendingProNotice() !== null}>1303              <div class="peach-pro-notice-banner">1304                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1305                <button1306                  class="peach-pro-notice-link"1307                  onClick={() => {1308                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1309                    setSettingsInitialSection("license");1310                    setView("settings");1311                    setPendingProNotice(null);1312                  }}1313                >1314                  Learn more →1315                </button>1316                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1317              </div>1318            </Show>13191320            <div class="peach-shell-body">1321              <div class="peach-shell-veil"></div>1322              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1323                <EntryView1324                  entry={selectedEntry()}1325                  currentTabUrl={currentTabUrl()}1326                  entries={entries()}1327                  onDelete={handleDelete}1328                  onFieldSaved={() => void loadEntries()}1329                  onEscape={() => { setView("list"); }}1330                />1331              </div>13321333              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1334                <div class="peach-search-bar">1335                  <span class="peach-search-icon">1336                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1337                      <circle cx="5.5" cy="5.5" r="3.75" />1338                      <path d="M8.75 8.75L11.5 11.5" />1339                    </svg>1340                  </span>1341                  <input1342                    class="peach-search-input"1343                    placeholder="search vault..."1344                    autocomplete="off"1345                    aria-label="Search vault entries"1346                    onClick={openList}1347                    onFocus={openList}1348                    readOnly1349                  />1350                  <div class="peach-search-meta">1351                    <span class="peach-search-counter">1352                      {entries().length > 01353                        ? `${selectedIndex() + 1} / ${entries().length}`1354                        : "0 entries"}1355                    </span>1356                    <span class="peach-divider"></span>1357                    <button1358                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1359                      onClick={() => navigate(-1)}1360                      aria-label="Previous entry"1361                      disabled={entries().length === 0}1362                    >1363                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1364                        <path d="M5 1L1 5.5L5 10" />1365                      </svg>1366                    </button>1367                    <button1368                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1369                      onClick={() => navigate(1)}1370                      aria-label="Next entry"1371                      disabled={entries().length === 0}1372                    >1373                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1374                        <path d="M1 1L5 5.5L1 10" />1375                      </svg>1376                    </button>1377                  </div>1378                </div>1379              </section>1380            </div>13811382            {/* Desktop: shown on demand via Show. Native sheet is rendered1383                via Portal below at the document root so its position:fixed1384                isn't trapped by .peach-shell's transform-based animations. */}1385            <Show when={!isNativePlatform() && view() === "list"}>1386              <VaultView1387                entries={entries()}1388                selectedEntryId={selectedEntry()?.id}1389                currentTabDomain={currentTabDomain()}1390                sortOrder={sortOrder()}1391                searchSeed={listSearchSeed()}1392                searchSeedNonce={listSearchSeedNonce()}1393                onSelectEntry={handleSelectEntry}1394                onSortOrderChange={setSortOrder}1395                onAdd={handleAdd}1396                onClose={() => setView("entry")}1397                onOpenTrash={() => setView("trash")}1398                onDeleteMany={handleDeleteMany}1399              />1400            </Show>1401            <Show when={isNativePlatform() && hasVault()}>1402              <Portal>1403                <div1404                  class="peach-vault-sheet"1405                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1406                  style={(() => {1407                    const live = sheetTranslate();1408                    if (live === null) return undefined;1409                    return { transform: `translateY(${live}px)` };1410                  })()}1411                >1412                  <VaultView1413                    entries={entries()}1414                    selectedEntryId={selectedEntry()?.id}1415                    currentTabDomain={currentTabDomain()}1416                    sortOrder={sortOrder()}1417                    searchSeed={listSearchSeed()}1418                    searchSeedNonce={listSearchSeedNonce()}1419                    onSelectEntry={handleSelectEntry}1420                    onSortOrderChange={setSortOrder}1421                    onAdd={handleAdd}1422                    onClose={() => setView("entry")}1423                    onOpenTrash={() => setView("trash")}1424                    onDeleteMany={handleDeleteMany}1425                  />1426                </div>1427              </Portal>1428            </Show>1429            <Show when={view() === "settings"}>1430              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1431                <SettingsView1432                  entriesCount={entries().length}1433                  breachMonitoring={breachMonitoring()}1434                  lockOnClose={lockOnClose()}1435                  autoLockMinutes={autoLockMinutes()}1436                  trashRetentionDays={trashRetentionDays()}1437                  theme={theme()}1438                  accentColor={accentColor()}1439                  displayFont={displayFont()}1440                  textSize={textSize()}1441                  reduceMotion={reduceMotion()}1442                  isPro={proStatus()}1443                  initialSection={settingsInitialSection()}1444                  upgradeHighlight={upgradeHighlight()}1445                  onBreachMonitoringChange={applyBreachMonitoring}1446                  onLockOnCloseChange={applyLockOnClose}1447                  onAutoLockMinutesChange={applyAutoLockMinutes}1448                  onTrashRetentionChange={applyTrashRetention}1449                  onThemeChange={applyTheme}1450                  onAccentChange={applyAccentColor}1451                  onDisplayFontChange={applyDisplayFont}1452                  onTextSizeChange={applyTextSize}1453                  onReduceMotionChange={applyReduceMotion}1454                  shortcuts={shortcutBindings()}1455                  onShortcutsChange={applyShortcuts}1456                  onLicenseChange={async () => {1457                    // After activation/deactivation: refresh Pro status,1458                    // re-load entries (defensive — signal state can drift if1459                    // the SW briefly restarts during the verify+save round-trip),1460                    // and replay the Pro celebration if this is the first time1461                    // a valid Pro license is seen on this device.1462                    await refreshProStatus();1463                    void loadEntries();1464                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1465                    if ((should as { ok: boolean; data?: boolean }).data === true) {1466                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1467                      setView("pro-celebration");1468                      window.setTimeout(() => setView("settings"), 2500);1469                    }1470                  }}1471                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1472                  onImport={() => setView("import")}1473                  onExport={() => setView("export")}1474                  onBreachCheckDone={loadEntries}1475                  onOpenHealth={openHealth}1476                  onOpenSyncPairing={() => setView("sync-pairing")}1477                  onOpenFileImport={handleOpenFileImport}1478                  onOpenPanic={() => setView("panic")}1479                  onOpenCodexGenerate={() => setView("codex-generate")}1480                />1481              </Suspense>1482            </Show>1483            <Show when={view() === "codex-generate"}>1484              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1485                <CodexGenerateView1486                  isPro={proStatus()}1487                  onBack={() => setView("settings")}1488                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1489                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1490                />1491              </Suspense>1492            </Show>1493            <Show when={view() === "codex-restore"}>1494              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1495                <CodexRestoreView1496                  onBack={() => setView("lock")}1497                  onRestoreSuccess={async () => {1498                    // After restore the vault is unlocked; refresh entries1499                    // and route to the main vault list. handleUnlock is the1500                    // canonical post-unlock setup path.1501                    await handleUnlock();1502                  }}1503                />1504              </Suspense>1505            </Show>1506            <Show when={view() === "sync-pairing"}>1507              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1508                <SyncPairingView1509                  isPro={proStatus()}1510                  onAddDevice={() => setView("sync-add-device")}1511                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1512                  onBack={() => setView("settings")}1513                />1514              </Suspense>1515            </Show>1516            <Show when={view() === "sync-add-device"}>1517              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1518                <AddDeviceView1519                  onClose={() => setView("sync-pairing")}1520                  onPaired={() => setView("sync-pairing")}1521                />1522              </Suspense>1523            </Show>1524            <Show when={view() === "add"}>1525              <AddView1526                entry={editEntry()}1527                entries={entries()}1528                onBack={handleBack}1529                onSave={handleSave}1530              />1531            </Show>1532            <Show when={view() === "import"}>1533              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1534                <ImportView onBack={handleBack} onImport={handleSave} />1535              </Suspense>1536            </Show>1537            <Show when={view() === "export"}>1538              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1539                <ExportView1540                  onBack={() => {1541                    if (returnToPanic()) {1542                      setReturnToPanic(false);1543                      setView("panic");1544                    } else {1545                      handleBack();1546                    }1547                  }}1548                />1549              </Suspense>1550            </Show>1551            <Show when={view() === "panic"}>1552              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1553                <PanicView1554                  onCancel={() => setView("settings")}1555                  onOpenExport={() => {1556                    setReturnToPanic(true);1557                    setView("export");1558                  }}1559                  onDestroyed={async () => {1560                    clearCanarySuppressions();1561                    setEntries([]);1562                    setSelectedEntry(null);1563                    setEditEntry(undefined);1564                    setHasVault(false);1565                    setOnboarded(false);1566                    setProStatus(false);1567                    setPendingPasskey(null);1568                    setUpgradeHighlight(null);1569                    setSettingsInitialSection(null);1570                    setPendingProNotice(null);1571                    setPendingCelebration(false);1572                    setReturnToPanic(false);1573                    setContentPhase("idle");1574                    setView("lock");1575                  }}1576                />1577              </Suspense>1578            </Show>1579            <Show when={view() === "health"}>1580              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1581                <HealthView1582                  entries={entries()}1583                  isPro={proStatus()}1584                  onFixEntry={handleFixEntry}1585                  onBack={() => setView("settings")}1586                  onRefresh={loadEntries}1587                />1588              </Suspense>1589            </Show>1590            <Show when={view() === "trash"}>1591              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1592                <TrashView1593                  onBack={() => setView("list")}1594                  onRestored={() => void loadEntries()}1595                />1596              </Suspense>1597            </Show>1598            <Show when={showNotes()}>1599              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1600                <NotesMode1601                  notes={entries().filter((e) => e.type === "note")}1602                  initialNoteId={openNoteId()}1603                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1604                  onNoteListChanged={() => void loadEntries()}1605                />1606              </div>1607            </Show>1608            <Show when={restoreView() === "file"}>1609              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1610                <ImportView1611                  mode="onboarding"1612                  replacesExistingVault={true}1613                  onBack={() => setRestoreView(null)}1614                  onImport={async () => {1615                    setRestoreView(null);1616                    await handleUnlock();1617                  }}1618                />1619              </Suspense>1620            </Show>1621            </section>1622            </Show>1623          </Show>1624        </Show>1625      </Show>1626      <Show when={showShortcutsHelp()}>1627        <ShortcutsHelpOverlay1628          bindings={shortcutBindings()}1629          onClose={() => setShowShortcutsHelp(false)}1630        />1631      </Show>1632    </div>1633  );1634}16351636function ShortcutsHelpOverlay(props: {1637  bindings: Record<ShortcutAction, Keybinding>;1638  onClose: () => void;1639}) {1640  return (1641    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1642      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1643        <div class="peach-shortcuts-help-head">1644          <h3>Keyboard shortcuts</h3>1645          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1646        </div>1647        <div class="peach-shortcuts-help-body">1648          <p class="peach-settings-sub-label">ENTRY VIEW</p>1649          <ul>1650            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1651              <li>1652                <span>{d.label}</span>1653                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1654              </li>1655            ))}1656          </ul>1657          <p class="peach-settings-sub-label">ANYWHERE</p>1658          <ul>1659            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1660              <li>1661                <span>{d.label}</span>1662                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1663              </li>1664            ))}1665          </ul>1666        </div>1667      </div>1668    </div>1669  );1670}