App.tsx

69.6 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_SETTLE_MS = 135;121122export default function App() {123  const [bootState, setBootState] = createSignal<BootState>("loading");124  const [view, setView] = createSignal<View>("lock");125  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,126  // CSS transition takes over for snap animation).127  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);128  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(129    "enter"130  );131  const [contentTransitioning, setContentTransitioning] = createSignal(false);132  const [hasVault, setHasVault] = createSignal(false);133  const [onboarded, setOnboarded] = createSignal(true);134  const [entries, setEntries] = createSignal<VaultEntry[]>([]);135  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);136  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);137  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");138  const [theme, setTheme] = createSignal<"dark" | "light">("dark");139  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");140  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");141  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);142  const [lockOnClose, setLockOnClose] = createSignal(true);143  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);144  const [breachMonitoring, setBreachMonitoring] = createSignal(true);145  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);146  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);147  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);148  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);149  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);150  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");151  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");152  // Cached Pro status — synchronous for render paths. Background's153  // GET_LICENSE is async, but render-time reads of isPro() must not block.154  // Refreshed at boot, after activate/deactivate, and whenever the popup155  // re-opens onto a stored license that has changed via another window.156  const [proStatus, setProStatus] = createSignal(false);157  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);158  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);159  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");160  const [listSearchSeed, setListSearchSeed] = createSignal("");161  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);162  const [pendingCelebration, setPendingCelebration] = createSignal(false);163  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);164  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);165  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);166  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);167  const [incomingPairTick, setIncomingPairTick] = createSignal(0);168  const incomingPairSecondsLeft = () => {169    void incomingPairTick();170    const req = incomingPair();171    if (!req) return 0;172    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));173  };174  // True while Panic Step 1 has bounced the user out to Export. When Export's175  // onBack fires we return to Panic instead of Settings so the user keeps the176  // destruction context they came from.177  const [returnToPanic, setReturnToPanic] = createSignal(false);178  const [showNotes, setShowNotes] = createSignal(false);179  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);180  // Set on popup boot when peach_recovery_pending flag is found in session181  // storage — instructs LockView to skip the unlock UI and open the recovery182  // words confirmation surface instead. Cleared via handleUnlock once the183  // user has typed the 3 confirmation words.184  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);185186  let contentPhaseTimer: number | undefined;187188  function applyAccent(name: AccentColorName) {189    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;190    const hex = color.hex;191    document.documentElement.style.setProperty("--peach-accent", hex);192    // Ambient surface variables — derived from the accent so surfaces shift193    // subtly toward the accent hue rather than staying fixed warm-brown.194    document.documentElement.style.setProperty("--peach-glow", hex + "2A");195    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");196    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");197  }198199  createEffect(() => {200    applyAccent(accentColor());201  });202203  createEffect(() => {204    document.documentElement.classList.toggle("light", theme() === "light");205    document.body.classList.toggle("light", theme() === "light");206  });207208  createEffect(() => {209    document.documentElement.setAttribute("data-display-font", displayFont());210  });211212  createEffect(() => {213    document.documentElement.setAttribute("data-text-size", textSize());214  });215216  createEffect(() => {217    if (reduceMotion()) {218      document.documentElement.setAttribute("data-motion", "reduce");219    } else {220      document.documentElement.removeAttribute("data-motion");221    }222  });223224  const selectedIndex = createMemo(() => {225    const currentId = selectedEntry()?.id;226    if (!currentId) return entries().length > 0 ? 0 : -1;227    return entries().findIndex((entry) => entry.id === currentId);228  });229230  async function applyAccentColor(name: AccentColorName) {231    applyAccent(name);232    setAccentColor(name);233    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });234  }235236  async function applyTheme(t: "dark" | "light") {237    setTheme(t);238    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });239  }240241  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {242    setDisplayFont(f);243    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });244  }245246  async function applyTextSize(size: "small" | "medium" | "large") {247    setTextSize(size);248    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });249  }250251  async function applyReduceMotion(enabled: boolean) {252    setReduceMotion(enabled);253    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });254  }255256  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload257  // small and lets future default updates land for actions the user hasn't258  // touched. Settings sends us the full active map; we filter and store.259  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {260    setShortcutBindings(active);261    const overrides: Record<string, Keybinding> = {};262    for (const action of Object.keys(active) as ShortcutAction[]) {263      const a = active[action];264      const d = DEFAULT_BINDINGS[action];265      const same = a.key === d.key266        && Boolean(a.ctrl)  === Boolean(d.ctrl)267        && Boolean(a.meta)  === Boolean(d.meta)268        && Boolean(a.shift) === Boolean(d.shift)269        && Boolean(a.alt)   === Boolean(d.alt);270      if (!same) overrides[action] = a;271    }272    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });273  }274275  async function applyLockOnClose(enabled: boolean) {276    setLockOnClose(enabled);277    await sendMessage({278      type: "UPDATE_SETTINGS",279      payload: { lockOnClose: enabled },280    });281  }282283  async function applyAutoLockMinutes(minutes: number) {284    setAutoLockMinutes(minutes);285    await sendMessage({286      type: "UPDATE_SETTINGS",287      payload: { autoLockMinutes: minutes },288    });289  }290291  async function applyBreachMonitoring(enabled: boolean) {292    setBreachMonitoring(enabled);293    await sendMessage({294      type: "UPDATE_SETTINGS",295      payload: { breachMonitoring: enabled },296    });297  }298299  onMount(async () => {300    // Resolve the active tab in parallel with the unlock/has-vault queries —301    // openVault()'s smart selection picks the entry matching currentTabDomain,302    // so it must be populated before openVault runs. Previously refreshCurrentTab303    // ran after openVault, leaving popups that booted already-unlocked falling304    // back to loadedEntries[0] instead of the domain match.305    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([306      sendMessage({ type: "IS_UNLOCKED" }),307      sendMessage({ type: "HAS_VAULT" }),308      refreshCurrentTab(),309      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),310    ]);311    const unlocked = Boolean(312      (unlockResponse as { ok: boolean; data?: boolean }).data313    );314    const vaultExists = Boolean(315      (vaultResponse as { ok: boolean; data?: boolean }).data316    );317    const shouldCelebrate = Boolean(318      (celebrationResponse as { ok: boolean; data?: boolean }).data319    );320    setHasVault(vaultExists);321    // Onboarding gate — show once on first install, never again. Existing322    // users (vaultExists) are auto-marked onboarded so they skip the flow323    // even on the very first popup open after this feature ships.324    try {325      const onboarded = await storageGet("peach_onboarded");326      const seen = onboarded === "true";327      if (vaultExists && !seen) {328        await storageSet("peach_onboarded", "true");329        setOnboarded(true);330      } else {331        setOnboarded(seen);332      }333    } catch {334      // storage unavailable — default to onboarded so we never block boot335      setOnboarded(true);336    }337    await Promise.all([restoreSettings(), refreshProStatus()]);338339    // Mark played before any animation so a crash mid-sequence never replays it340    if (shouldCelebrate) {341      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });342    }343344    // If the user created a vault but hasn't yet confirmed their recovery345    // words, route back to the recovery-words screen instead of opening the346    // entries view. The flag lives in chrome.storage.local so it survives347    // both popup close (SW suppresses lock-on-close) and full browser348    // restart (handleUnlock checks the same flag after a fresh password349    // unlock). Cleared when confirmation succeeds.350    let recoveryPending = false;351    try {352      const out = await chrome.storage.local?.get("peach_recovery_pending");353      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";354    } catch { /* best-effort */ }355356    // Native: closing the app before recovery-words confirmation means the357    // user didn't finish vault creation. Throw the partial vault away and358    // restart onboarding rather than asking them to unlock a vault they359    // never finished creating. Desktop keeps the existing "unlock to360    // resume" flow because closing the popup there is much more casual.361    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {362      try {363        await chrome.storage.local?.remove([364          "peach_vault_a",365          "peach_vault_b",366          "peach_recovery_pending",367          "peach_onboarded",368          "peach_vault_history",369        ]);370      } catch { /* best-effort */ }371      setHasVault(false);372      setOnboarded(false);373      setView("lock");374      setBootState("ready");375      document.getElementById("pre-lock")?.setAttribute("hidden", "true");376      return;377    }378379    if (recoveryPending && unlocked) {380      // forceRecoveryWords overrides LockView's hasVault gate so the381      // recovery surface renders even though the vault now exists.382      setForceRecoveryWords(true);383      setView("lock");384    } else if (unlocked && vaultExists) {385      await openVault(undefined, shouldCelebrate);386      if (shouldCelebrate) {387        setView("pro-celebration");388        window.setTimeout(() => setView("entry"), 2500);389      }390    } else if (shouldCelebrate) {391      setPendingCelebration(true);392    }393394    await refreshPendingPasskey();395    await refreshIncomingPairing();396    await consumeRecentPairing();397398    // Track tab changes so smart sort stays current399    const handleTabActivated = () => { void refreshCurrentTab(); };400    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {401      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();402    };403    try {404      chrome.tabs.onActivated.addListener(handleTabActivated);405      chrome.tabs.onUpdated.addListener(handleTabUpdated);406      onCleanup(() => {407        chrome.tabs.onActivated.removeListener(handleTabActivated);408        chrome.tabs.onUpdated.removeListener(handleTabUpdated);409      });410    } catch {411      // tabs permission may not be available in all contexts412    }413414    setBootState("ready");415    document.getElementById("pre-lock")?.setAttribute("hidden", "true");416417    // Check for pending session-storage notices from the background.418    if (chrome.storage.session) {419      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as420        Record<string, { feature?: string } | undefined>;421      if (session.pendingProGate?.feature) {422        await chrome.storage.session.remove("pendingProGate");423        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);424        setSettingsInitialSection("license");425        setView("settings");426      } else if (session.pendingProNotice?.feature) {427        await chrome.storage.session.remove("pendingProNotice");428        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });429      }430    }431432    // Warm the lazy-module cache so the Suspense fallback never shows for433    // locally-bundled extension views. Without this, the first navigation to434    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which435    // covers the shell and absorbs clicks on the header.436    void Promise.all([437      import("./views/Settings").catch(() => {}),438      import("./views/Import").catch(() => {}),439      import("./views/Export").catch(() => {}),440      import("./views/Health").catch(() => {}),441      import("./views/TrashView").catch(() => {}),442    ]);443444    // Lock-on-close via a persistent port. sendMessage in pagehide is445    // unreliable — the popup context tears down before the message lands.446    // The SW's onConnect listener locks when this port disconnects.447    let popupPort: chrome.runtime.Port | null = null;448    try {449      popupPort = chrome.runtime.connect({ name: "popup" });450    } catch { /* extension context invalidated — ignore */ }451    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });452453    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only454    // reliable signal is appStateChange — setTimeout is killed when the OS455    // backgrounds the app. We measure elapsed background time on resume.456    if (isNativePlatform()) {457      let backgroundedAt: number | null = null;458      let syncPollInterval: ReturnType<typeof setInterval> | null = null;459460      function startSyncPolling() {461        if (syncPollInterval) return;462        syncPollInterval = setInterval(async () => {463          const res = await sendMessage({ type: 'TRIGGER_SYNC' }).catch(() => null);464          const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;465          if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {466            await sendMessage({ type: 'GET_ENTRIES' }).catch(() => null);467          }468        }, 60_000);469      }470471      function stopSyncPolling() {472        if (syncPollInterval) { clearInterval(syncPollInterval); syncPollInterval = null; }473      }474475      const CapApp = nativePlugin<{476        addListener: (477          ev: string,478          cb: (s: { isActive: boolean }) => void,479        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };480      }>("App");481      if (CapApp?.addListener) {482        const sub = CapApp.addListener(483          "appStateChange",484          ({ isActive }: { isActive: boolean }) => {485            if (!isActive) {486              backgroundedAt = Date.now();487              stopSyncPolling();488              return;489            }490            if (backgroundedAt !== null && autoLockMinutes() > 0) {491              const elapsed = Date.now() - backgroundedAt;492              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();493            }494            backgroundedAt = null;495            // Resume polling when app comes to foreground (Pro only).496            if (proStatus()) startSyncPolling();497          }498        );499        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.500        onCleanup(() => {501          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});502          stopSyncPolling();503        });504      }505506      // L12/COR-011: foreground idle autolock. appStateChange only fires when507      // the OS backgrounds the app — if the user idles with the screen on,508      // chrome.alarms is no-op'd in Capacitor so the vault would stay open509      // indefinitely. Poll every 30s and lock if elapsed since last user510      // interaction exceeds autoLockMinutes.511      let lastUserActivityAt = Date.now();512      const bumpActivity = () => { lastUserActivityAt = Date.now(); };513      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;514      for (const ev of ACTIVITY_EVENTS) {515        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });516      }517      const idleLockInterval = setInterval(() => {518        const minutes = autoLockMinutes();519        if (!minutes || minutes <= 0) return;520        const elapsed = Date.now() - lastUserActivityAt;521        if (elapsed >= minutes * 60_000) {522          lastUserActivityAt = Date.now();523          handleHeaderLock();524        }525      }, 30_000);526      onCleanup(() => {527        clearInterval(idleLockInterval);528        for (const ev of ACTIVITY_EVENTS) {529          document.removeEventListener(ev, bumpActivity, { capture: true });530        }531      });532    }533534    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale535    // entries instead of waiting for the next GET_ENTRIES round-trip.536    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {537      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();538      if (msg?.type === "PRO_GATE_TRIGGERED") {539        setUpgradeHighlight(msg.payload?.feature ?? null);540        setSettingsInitialSection("license");541        setView("settings");542      }543    };544    chrome.runtime.onMessage.addListener(handleRuntimeMessage);545    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));546547    // Android hardware/gesture back. MainActivity fires peach:back; the popup548    // decides what "back" means per surface. Lock+no-vault is the common case549    // — return to onboarding rather than letting the OS dismiss the activity.550    const handlePeachBack = () => {551      // Notes mode captures back first552      if (showNotes()) {553        setShowNotes(false);554        setOpenNoteId(undefined);555        return;556      }557      const v = view();558      if (v === "lock" && !hasVault() && onboarded()) {559        setOnboarded(false);560        return;561      }562      if (v === "list") { setView("entry"); return; }563      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {564        handleBack();565        return;566      }567      if (v === "sync-pairing") { setView("settings"); return; }568    };569    window.addEventListener("peach:back", handlePeachBack);570    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));571572    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that573    // peeks from the bottom (search bar handle visible) and drags up to fill574    // the screen. dragOffset is the LIVE finger offset during a drag, in px,575    // 0 when no drag in progress. The wrapper element computes transform =576    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.577    if (isNativePlatform()) {578      let touchStartY = 0;579      let touchStartX = 0;580      let lastY = 0;581      let lastT = 0;582      let dragging = false;583      let captured = false;584      const HORIZONTAL_TOLERANCE = 16;585      const ACTIVATION_DY = 8;586      const PEEK_PX = 60;587588      const onTouchStart = (e: TouchEvent) => {589        const t = e.touches[0];590        if (!t) return;591        const v = view();592        if (v !== "entry" && v !== "list") return;593        // Entry view: only intercept drags starting in the bottom 40%.594        // List view: intercept drags starting in the top 35% (the search/handle row).595        const inBand = v === "entry"596          ? t.clientY > window.innerHeight * 0.6597          : t.clientY < window.innerHeight * 0.35;598        if (!inBand) return;599        touchStartY = lastY = t.clientY;600        touchStartX = t.clientX;601        lastT = e.timeStamp;602        dragging = true;603        captured = false;604      };605606      const onTouchMove = (e: TouchEvent) => {607        if (!dragging) return;608        const t = e.touches[0];609        if (!t) return;610        const dy = t.clientY - touchStartY;611        const dx = Math.abs(t.clientX - touchStartX);612613        if (!captured) {614          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {615            // Looks like a horizontal swipe — release.616            dragging = false;617            return;618          }619          if (Math.abs(dy) < ACTIVATION_DY) return;620          captured = true;621        }622623        // Translate the sheet by dy from its rest (peek) position. Peek is624        // (viewport height - PEEK_PX). Open is 0.625        const v = view();626        const restClosed = window.innerHeight - PEEK_PX;627        const baseTranslate = v === "list" ? 0 : restClosed;628        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));629        setSheetTranslate(next);630        lastY = t.clientY;631        lastT = e.timeStamp;632      };633634      const onTouchEnd = (e: TouchEvent) => {635        if (!dragging) { return; }636        const t = e.changedTouches[0];637        const elapsed = Math.max(1, e.timeStamp - lastT);638        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms639        const wasCaptured = captured;640        dragging = false;641        captured = false;642        const v = view();643644        if (!wasCaptured) {645          // Tap in the peek strip while in entry view → open the vault list.646          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");647          setSheetTranslate(null);648          return;649        }650651        const restClosed = window.innerHeight - PEEK_PX;652        const current = sheetTranslate() ?? restClosed;653654        // Snap rules:655        //   - Strong upward velocity → open656        //   - Strong downward velocity → close657        //   - Otherwise snap to whichever rest is closer658        let nextOpen: boolean;659        if (velocity < -0.05) nextOpen = true;660        else if (velocity > 0.05) nextOpen = false;661        else nextOpen = current < restClosed * 0.5;662663        if (nextOpen && v !== "list") setView("list");664        if (!nextOpen && v !== "entry") setView("entry");665        // Release the live offset so CSS transition handles the snap.666        setSheetTranslate(null);667      };668669      document.addEventListener("touchstart", onTouchStart, { passive: true });670      document.addEventListener("touchmove",  onTouchMove,  { passive: true });671      document.addEventListener("touchend",   onTouchEnd,   { passive: true });672      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });673      onCleanup(() => {674        document.removeEventListener("touchstart", onTouchStart);675        document.removeEventListener("touchmove",  onTouchMove);676        document.removeEventListener("touchend",   onTouchEnd);677      });678    }679680    // Action handlers — keyed by ShortcutAction. The dispatcher below tests681    // each binding against the event and runs the matching handler. New682    // shortcuts only need an entry here; the binding is data, not code.683    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {684      copy_password: () => {685        const entry = selectedEntry();686        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });687      },688      copy_username: () => {689        const entry = selectedEntry();690        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });691      },692      copy_totp: () => {693        const entry = selectedEntry();694        if (!entry?.totp) return;695        try {696          const { code } = generateTOTP(entry.totp);697          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });698        } catch { /* invalid TOTP secret — silent */ }699      },700      new_entry: () => handleAdd(),701      edit_entry: () => {702        const entry = selectedEntry();703        // Passkey-only entries have nothing user-editable in the Add view; the704        // passkey credential itself is opaque. Skip the edit action for them.705        if (!entry || isPasskeyOnly(entry)) return;706        setEditEntry(entry);707        setView("add");708      },709      delete_entry: () => {710        if (selectedEntry()) void handleDelete();711      },712      lock_vault: () => { void handleHeaderLock(); },713      search: () => openList(),714      nav_prev: () => navigate(-1),715      nav_next: () => navigate(1),716      jump_vault: () => setView("entry"),717      jump_settings: () => setView("settings"),718      show_help: () => setShowShortcutsHelp(true),719    };720721    // Actions that are MEANINGFUL only on the entry-detail view. Outside722    // that scope the binding is dormant — pressing C while on Settings723    // does nothing rather than awkwardly copying from a now-stale entry.724    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([725      "copy_password", "copy_username", "copy_totp",726      "edit_entry", "delete_entry", "nav_prev", "nav_next",727    ]);728729    const handleGlobalKeydown = (e: KeyboardEvent) => {730      const v = view();731      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"732        || (e.target as HTMLElement)?.tagName === "TEXTAREA"733        || (e.target as HTMLElement)?.isContentEditable;734      const isPrintableSearchKey =735        e.key.length === 1 &&736        !e.ctrlKey &&737        !e.metaKey &&738        !e.altKey;739740      // No input during the pro celebration sequence741      if (v === "pro-celebration") return;742743      // Help dialog: Escape closes it; eat the keypress so it doesn't744      // also navigate away from the underlying view.745      if (showShortcutsHelp()) {746        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }747        return;748      }749750      // ── Escape — fixed binding (not user-customizable) ───────751      if (e.key === "Escape") {752        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }753        if (v === "list") { setView("entry"); return; }754        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }755        if (v === "sync-pairing") { setView("settings"); return; }756        if (v === "sync-add-device") { setView("sync-pairing"); return; }757      }758759      // Bindings-driven dispatch. Single-key letter bindings without760      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is761      // inside an input, so users can type into search/forms normally.762      const bindings = shortcutBindings();763      for (const action of Object.keys(bindings) as ShortcutAction[]) {764        const binding = bindings[action];765        if (!matchKeybinding(e, binding)) continue;766        // Single-key letter bindings need the input-focus guard. Bindings767        // with any modifier are safe — Ctrl+L doesn't conflict with typing.768        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;769        if (!hasMod && binding.key.length === 1 && inInput) return;770        if (ENTRY_SCOPED.has(action) && v !== "entry") return;771        e.preventDefault();772        SHORTCUT_HANDLERS[action]?.();773        return;774      }775776      // Type-to-search: in entry view, any printable key not consumed by a777      // shortcut above primes the list search seed and opens the list.778      // Kept outside the bindings table because it's a behavior, not a779      // discrete action — every printable character can trigger it.780      if (v === "entry" && !inInput && isPrintableSearchKey) {781        e.preventDefault();782        primeListSearch(e.key);783        return;784      }785    };786    window.addEventListener("keydown", handleGlobalKeydown);787    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));788789    const handleStorageChanged = (790      changes: Record<string, chrome.storage.StorageChange>,791      areaName: string792    ) => {793      if (areaName !== "session") return;794      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {795        return;796      }797      void refreshPendingPasskey();798    };799    chrome.storage.onChanged.addListener(handleStorageChanged);800    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));801  });802803  async function refreshCurrentTab() {804    try {805      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });806      const url = tab?.url ?? tab?.pendingUrl ?? "";807      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");808      // Skip extension/internal URLs — adding chrome://, about:, or809      // chrome-extension:// to a vault entry is never what the user wants.810      const isWebUrl = /^https?:\/\//i.test(url);811      setCurrentTabUrl(isWebUrl ? url : "");812    } catch {813      setCurrentTabDomain("");814      setCurrentTabUrl("");815    }816  }817818  async function refreshPendingPasskey() {819    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });820    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);821  }822823  async function refreshIncomingPairing() {824    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });825    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;826    setIncomingPair(data);827  }828829  // Drains a single one-shot record left by the background when 6-digit830  // pairing succeeded while the popup was closed (or the SyncPairing view was831  // navigated away from before it could show its own success card).832  async function consumeRecentPairing() {833    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });834    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;835    if (data?.deviceName) {836      setRecentPairToast(data.deviceName);837      window.setTimeout(() => setRecentPairToast(null), 4000);838    }839  }840841  async function respondIncomingPairing(accept: boolean) {842    if (incomingPairResponding()) return;843    setIncomingPairResponding(true);844    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });845    setIncomingPair(null);846    setIncomingPairResponding(false);847  }848849  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a850  // request appears, ticks once per second, and clears the banner if the851  // request expires while the popup is open.852  createEffect(() => {853    const req = incomingPair();854    if (!req) return;855    const handle = window.setInterval(() => {856      setIncomingPairTick((tick) => tick + 1);857      if (Date.now() >= req.expiresAt) {858        setIncomingPair(null);859        window.clearInterval(handle);860      }861    }, 1000);862    onCleanup(() => window.clearInterval(handle));863  });864865  async function refreshProStatus() {866    const res = await sendMessage({ type: "GET_LICENSE" });867    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;868    setProStatus(Boolean(data?.valid && data?.plan === "pro"));869  }870871  async function restoreSettings() {872    const res = await sendMessage({ type: "GET_SETTINGS" });873    const s = (res as { ok: boolean; data?: any }).data ?? {};874    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {875      setAccentColor(s.accentColor as AccentColorName);876    }877    setTheme(s.theme === "light" ? "light" : "dark");878    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {879      setDisplayFont(s.displayFont);880    } else {881      setDisplayFont("cormorant-italic");882    }883    if (s.textSize === "small" || s.textSize === "large") {884      setTextSize(s.textSize);885    } else {886      setTextSize("medium");887    }888    setReduceMotion(s.reduceMotion === true);889    setLockOnClose(s.lockOnClose !== false);890    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);891    setBreachMonitoring(s.breachMonitoring !== false);892    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);893    setShortcutBindings(getActiveBindings(s.shortcuts));894  }895896  async function applyTrashRetention(days: number) {897    setTrashRetentionDays(days);898    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });899  }900901  function primeListSearch(seed: string) {902    setListSearchSeed(seed);903    setListSearchSeedNonce((value) => value + 1);904    openList();905  }906907  // Returns null when it detected a dead service worker and triggered handleLock().908  // Callers that need to abort (e.g. openVault) check for null rather than relying909  // on view() state, which may already be "lock" during normal startup flows.910  async function loadEntries(): Promise<VaultEntry[] | null> {911    const response = await sendMessage({ type: "GET_ENTRIES" });912    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };913914    // If the service worker was killed and restarted (MV3 workers sleep), the915    // vault will be locked again — or the worker may not respond at all.916    // In either case, send the user to the lock screen rather than silently917    // showing an empty vault (which looks like data loss).918    if (!res.ok) {919      if (920        res.error === "vault_locked" ||921        res.error === "SERVICE_WORKER_UNAVAILABLE" ||922        (typeof res.error === "string" && res.error.includes("locked"))923      ) {924        handleLock();925        return null; // signal emergency lock to callers926      }927      return [];928    }929930    const loadedEntries = res.data ?? [];931    setEntries(loadedEntries);932933    const currentId = selectedEntry()?.id;934    if (currentId) {935      setSelectedEntry(936        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null937      );938    }939940    return loadedEntries;941  }942943  async function openVault(preferredEntryId?: string, skipViewSet = false) {944    // Desktop: fire-and-forget sync on every vault open (Pro only).945    // Never blocks popup load; refreshes entries if new data arrives.946    if (!isNativePlatform() && proStatus()) {947      void sendMessage({ type: 'TRIGGER_SYNC' }).then((res) => {948        const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;949        if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {950          void loadEntries();951        }952      }).catch(() => {});953    }954955    // Purge expired trash entries on each vault open956    const retDays = trashRetentionDays();957    if (retDays > 0) {958      void sendMessage({959        type: "PURGE_EXPIRED_TRASH",960        payload: { retentionMs: retDays * 86_400_000 },961      });962    }963964    const loadedEntries = await loadEntries();965966    // null means loadEntries() triggered an emergency lock (service worker died).967    // Don't override it by setting view back to "entry" with an empty vault.968    if (loadedEntries === null) return;969970    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry971    let nextSelectedEntry: VaultEntry | null = null;972    if (preferredEntryId) {973      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;974    }975    if (!nextSelectedEntry) {976      const tabDomain = currentTabDomain();977      if (tabDomain) {978        nextSelectedEntry = loadedEntries.find((e) => {979          if (e.type === "login") {980            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;981            for (const extra of e.additionalUrls ?? []) {982              if ((extractDomain(extra) ?? "") === tabDomain) return true;983            }984            return false;985          }986          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;987          return false;988        }) ?? null;989      }990    }991    nextSelectedEntry ??= loadedEntries[0] ?? null;992993    setSelectedEntry(nextSelectedEntry);994    setEditEntry(undefined);995    setContentTransitioning(false);996    setContentPhase("enter");997    queueContentIdle();998    if (!skipViewSet) setView("entry");999  }10001001  async function handleUnlock() {1002    // If the user previously created a vault but hadn't yet confirmed their1003    // recovery words (and the browser was closed before they could), the1004    // peach_recovery_pending flag is still set in storage.local. Re-route1005    // back to the recovery surface so they finish the confirmation step1006    // before reaching the entries view — the words can be re-derived now1007    // that the vault is unlocked again.1008    let recoveryPending = false;1009    try {1010      const out = await chrome.storage.local?.get("peach_recovery_pending");1011      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1012    } catch { /* best-effort */ }1013    if (recoveryPending) {1014      setForceRecoveryWords(true);1015      setView("lock");1016      triggerPipPulse();1017      await restoreSettings();1018      return;1019    }1020    setHasVault(true);1021    triggerPipPulse();1022    await restoreSettings();1023    const celebrating = pendingCelebration();1024    if (celebrating) {1025      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1026      setPendingCelebration(false);1027    }1028    await openVault(undefined, celebrating);1029    if (celebrating) {1030      setView("pro-celebration");1031      window.setTimeout(() => setView("entry"), 2500);1032    }1033  }10341035  function handleSelectEntry(entry: VaultEntry) {1036    if (entry.type === "note") {1037      setOpenNoteId(entry.id);1038      setShowNotes(true);1039      return;1040    }1041    setSelectedEntry(entry);1042    setContentTransitioning(false);1043    setContentPhase("enter");1044    queueContentIdle();1045    setView("entry");1046  }10471048  function handleAdd() {1049    setEditEntry(undefined);1050    setView("add");1051  }10521053  async function handleDelete() {1054    const entry = selectedEntry();1055    if (!entry) return;1056    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1057    const loadedEntries = await loadEntries() ?? [];1058    setSelectedEntry(loadedEntries[0] ?? null);1059    setView("entry");1060  }10611062  async function handleDeleteMany(ids: string[]) {1063    for (const id of ids) {1064      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1065    }1066    const loadedEntries = await loadEntries() ?? [];1067    // If the currently selected entry was among the deleted, move to first1068    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1069    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1070  }10711072  async function handleSave(savedEntry?: VaultEntry) {1073    await openVault(savedEntry?.id);1074  }10751076  function handleBack() {1077    setEditEntry(undefined);1078    setView("entry");1079  }10801081  function handleLock() {1082    clearCanarySuppressions();1083    setEntries([]);1084    setSelectedEntry(null);1085    setEditEntry(undefined);1086    setContentPhase("idle");1087    setView("lock");1088  }10891090  function handleHeaderLock() {1091    // Lock the UI immediately — do not wait for the service worker. If the SW1092    // is dead or slow, the 5s sendMessage timeout would create a dead-click1093    // window. The SW will lock on its next wake regardless.1094    handleLock();1095    void sendMessage({ type: "LOCK" });1096  }10971098  function navigate(dir: number) {1099    const allEntries = entries();1100    if (allEntries.length === 0) return;1101    const currentIndex = selectedIndex();1102    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1103    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1104    setSelectedEntry(allEntries[nextIndex]);1105    setContentPhase("enter");1106    queueContentIdle();1107  }11081109  function openList() {1110    setView("list");1111  }11121113  function openHealth() {1114    setEditEntry(undefined);1115    setView("health");1116  }11171118  function handleOpenFileImport() {1119    setRestoreView("file");1120  }11211122  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11231124  function handleFixEntry(entry: VaultEntry) {1125    // Passkey-only entries have no editable surface — drop into view mode1126    // instead of opening the Add editor.1127    if (isPasskeyOnly(entry)) {1128      setSelectedEntry(entry);1129      setView("entry");1130      return;1131    }1132    setEditEntry(entry);1133    setView("add");1134  }11351136  const isLockedView = () => view() === "lock";11371138  async function handleApprovePendingPasskey() {1139    const pending = pendingPasskey();1140    if (!pending) return;1141    if (pending.browser === "firefox" && pending.type === "create") {1142      // Firefox path: popup itself runs navigator.credentials.create. The1143      // background never approved/rejected anything — it just stashed1144      // intent. After the popup-driven flow resolves (success or cancel),1145      // clear the pending key so the popup doesn't re-show this on next open.1146      const { createFirefoxPasskey } = await import("./firefox-passkey");1147      const result = await createFirefoxPasskey(pending);1148      if (!result.ok) {1149        console.warn("Peach Firefox passkey create failed:", result.error);1150      }1151      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1152      setPendingPasskey(null);1153      void loadEntries();1154      window.close();1155      return;1156    }1157    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1158    window.close();1159  }11601161  async function handleDenyPendingPasskey() {1162    const pending = pendingPasskey();1163    if (!pending) return;1164    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1165    window.close();1166  }11671168  function queueContentIdle(after?: () => void) {1169    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1170    contentPhaseTimer = window.setTimeout(() => {1171      setContentPhase("idle");1172      after?.();1173    }, ENTRY_TRANSITION_SETTLE_MS);1174  }11751176  return (1177    <div class="popup-root peach-theme">1178      <Show when={bootState() === "ready"}>1179        <Show1180          when={!pendingPasskey()}1181          fallback={1182            <PasskeyApprovalView1183              type={pendingPasskey()!.type}1184              rpName={pendingPasskey()!.rpName}1185              rpId={pendingPasskey()!.rpId}1186              userName={pendingPasskey()!.userName}1187              userDisplayName={pendingPasskey()!.userDisplayName}1188              onApprove={handleApprovePendingPasskey}1189              onDeny={handleDenyPendingPasskey}1190            />1191          }1192        >1193          <Show1194            when={!isLockedView()}1195            fallback={1196              <Show1197                when={onboarded() || hasVault()}1198                fallback={1199                  <Onboarding1200                    onComplete={() => { setOnboarded(true); }}1201                  />1202                }1203              >1204                <LockView1205                  hasVault={hasVault()}1206                  ready={bootState() === "ready"}1207                  isPro={proStatus()}1208                  forceRecoveryWords={forceRecoveryWords()}1209                  onUnlock={() => {1210                    // RecoveryWordDisplay clears the storage flag before1211                    // calling onDone, so handleUnlock will see no pending1212                    // confirmation and proceed through the normal path.1213                    if (forceRecoveryWords()) setForceRecoveryWords(false);1214                    return handleUnlock();1215                  }}1216                  onBackToOnboarding={1217                    !hasVault()1218                      ? () => setOnboarded(false)1219                      : undefined1220                  }1221                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1222                />1223              </Show>1224            }1225          >1226            <Show1227              when={view() !== "pro-celebration"}1228              fallback={<ProCelebration />}1229            >1230            <section1231              id="hd-shell"1232              class="peach-shell peach-theme"1233              data-surface="extension"1234            >1235            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1236              <PeachWordmark unlocked />1237              <div class="peach-chrome-actions">1238                <button1239                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1240                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1241                  aria-label="Notes"1242                  title="Notes"1243                >1244                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1245                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1246                    <line x1="4" y1="5" x2="10" y2="5" />1247                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1248                    <line x1="4" y1="10" x2="7" y2="10" />1249                  </svg>1250                </button>1251                <button1252                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1253                  onClick={() => setView("settings")}1254                  aria-label="Settings"1255                >1256                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1257                    <path1258                      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"1259                      stroke="currentColor"1260                      stroke-width="0.9"1261                    />1262                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1263                  </svg>1264                </button>1265                <button1266                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1267                  onClick={handleAdd}1268                  aria-label="New entry"1269                >1270                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1271                    <path d="M5.5 1v9M1 5.5h9" />1272                  </svg>1273                </button>1274                <button1275                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1276                  onClick={() => void handleHeaderLock()}1277                  aria-label="Lock vault"1278                >1279                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1280                    <path1281                      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"1282                      stroke="currentColor"1283                      stroke-width="1"1284                      stroke-linecap="round"1285                    />1286                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1287                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1288                  </svg>1289                </button>1290              </div>1291            </header>12921293            <Show when={recentPairToast()}>1294              <div class="peach-pair-toast" role="status" aria-live="polite">1295                Paired with <strong>{recentPairToast()}</strong>1296              </div>1297            </Show>12981299            <Show when={incomingPair() !== null}>1300              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1301                <div class="peach-pair-request-header">1302                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1303                  <span class="peach-pair-request-title">Pairing request</span>1304                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1305                </div>1306                <p class="peach-pair-request-body">1307                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1308                </p>1309                <div class="peach-pair-request-actions">1310                  <button1311                    class="peach-btn peach-btn--ghost peach-btn--sm"1312                    onClick={() => void respondIncomingPairing(false)}1313                    disabled={incomingPairResponding()}1314                  >1315                    Reject1316                  </button>1317                  <button1318                    class="peach-btn peach-btn--accent peach-btn--sm"1319                    onClick={() => void respondIncomingPairing(true)}1320                    disabled={incomingPairResponding()}1321                  >1322                    Accept1323                  </button>1324                </div>1325              </div>1326            </Show>13271328            <Show when={pendingProNotice() !== null}>1329              <div class="peach-pro-notice-banner">1330                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1331                <button1332                  class="peach-pro-notice-link"1333                  onClick={() => {1334                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1335                    setSettingsInitialSection("license");1336                    setView("settings");1337                    setPendingProNotice(null);1338                  }}1339                >1340                  Learn more →1341                </button>1342                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1343              </div>1344            </Show>13451346            <div class="peach-shell-body">1347              <div class="peach-shell-veil"></div>1348              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1349                <EntryView1350                  entry={selectedEntry()}1351                  currentTabUrl={currentTabUrl()}1352                  entries={entries()}1353                  onDelete={handleDelete}1354                  onFieldSaved={() => void loadEntries()}1355                  onEscape={() => { setView("list"); }}1356                />1357              </div>13581359              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1360                <div class="peach-search-bar">1361                  <span class="peach-search-icon">1362                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1363                      <circle cx="5.5" cy="5.5" r="3.75" />1364                      <path d="M8.75 8.75L11.5 11.5" />1365                    </svg>1366                  </span>1367                  <input1368                    class="peach-search-input"1369                    placeholder="search vault..."1370                    autocomplete="off"1371                    aria-label="Search vault entries"1372                    onClick={openList}1373                    onFocus={openList}1374                    readOnly1375                  />1376                  <div class="peach-search-meta">1377                    <span class="peach-search-counter">1378                      {entries().length > 01379                        ? `${selectedIndex() + 1} / ${entries().length}`1380                        : "0 entries"}1381                    </span>1382                    <span class="peach-divider"></span>1383                    <button1384                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1385                      onClick={() => navigate(-1)}1386                      aria-label="Previous entry"1387                      disabled={entries().length === 0}1388                    >1389                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1390                        <path d="M5 1L1 5.5L5 10" />1391                      </svg>1392                    </button>1393                    <button1394                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1395                      onClick={() => navigate(1)}1396                      aria-label="Next entry"1397                      disabled={entries().length === 0}1398                    >1399                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1400                        <path d="M1 1L5 5.5L1 10" />1401                      </svg>1402                    </button>1403                  </div>1404                </div>1405              </section>1406            </div>14071408            {/* Desktop: shown on demand via Show. Native sheet is rendered1409                via Portal below at the document root so its position:fixed1410                isn't trapped by .peach-shell's transform-based animations. */}1411            <Show when={!isNativePlatform() && view() === "list"}>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            </Show>1427            <Show when={isNativePlatform() && hasVault()}>1428              <Portal>1429                <div1430                  class="peach-vault-sheet"1431                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1432                  style={(() => {1433                    const live = sheetTranslate();1434                    if (live === null) return undefined;1435                    return { transform: `translateY(${live}px)` };1436                  })()}1437                >1438                  <VaultView1439                    entries={entries()}1440                    selectedEntryId={selectedEntry()?.id}1441                    currentTabDomain={currentTabDomain()}1442                    sortOrder={sortOrder()}1443                    searchSeed={listSearchSeed()}1444                    searchSeedNonce={listSearchSeedNonce()}1445                    onSelectEntry={handleSelectEntry}1446                    onSortOrderChange={setSortOrder}1447                    onAdd={handleAdd}1448                    onClose={() => setView("entry")}1449                    onOpenTrash={() => setView("trash")}1450                    onDeleteMany={handleDeleteMany}1451                  />1452                </div>1453              </Portal>1454            </Show>1455            <Show when={view() === "settings"}>1456              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1457                <SettingsView1458                  entriesCount={entries().length}1459                  breachMonitoring={breachMonitoring()}1460                  lockOnClose={lockOnClose()}1461                  autoLockMinutes={autoLockMinutes()}1462                  trashRetentionDays={trashRetentionDays()}1463                  theme={theme()}1464                  accentColor={accentColor()}1465                  displayFont={displayFont()}1466                  textSize={textSize()}1467                  reduceMotion={reduceMotion()}1468                  isPro={proStatus()}1469                  initialSection={settingsInitialSection()}1470                  upgradeHighlight={upgradeHighlight()}1471                  onBreachMonitoringChange={applyBreachMonitoring}1472                  onLockOnCloseChange={applyLockOnClose}1473                  onAutoLockMinutesChange={applyAutoLockMinutes}1474                  onTrashRetentionChange={applyTrashRetention}1475                  onThemeChange={applyTheme}1476                  onAccentChange={applyAccentColor}1477                  onDisplayFontChange={applyDisplayFont}1478                  onTextSizeChange={applyTextSize}1479                  onReduceMotionChange={applyReduceMotion}1480                  shortcuts={shortcutBindings()}1481                  onShortcutsChange={applyShortcuts}1482                  onLicenseChange={async () => {1483                    // After activation/deactivation: refresh Pro status,1484                    // re-load entries (defensive — signal state can drift if1485                    // the SW briefly restarts during the verify+save round-trip),1486                    // and replay the Pro celebration if this is the first time1487                    // a valid Pro license is seen on this device.1488                    await refreshProStatus();1489                    void loadEntries();1490                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1491                    if ((should as { ok: boolean; data?: boolean }).data === true) {1492                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1493                      setView("pro-celebration");1494                      window.setTimeout(() => setView("settings"), 2500);1495                    }1496                  }}1497                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1498                  onImport={() => setView("import")}1499                  onExport={() => setView("export")}1500                  onBreachCheckDone={loadEntries}1501                  onOpenHealth={openHealth}1502                  onOpenSyncPairing={() => setView("sync-pairing")}1503                  onOpenFileImport={handleOpenFileImport}1504                  onOpenPanic={() => setView("panic")}1505                  onOpenCodexGenerate={() => setView("codex-generate")}1506                  onOpenCodexRestore={() => setView("codex-restore")}1507                />1508              </Suspense>1509            </Show>1510            <Show when={view() === "codex-generate"}>1511              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1512                <CodexGenerateView1513                  isPro={proStatus()}1514                  onBack={() => setView("settings")}1515                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1516                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1517                />1518              </Suspense>1519            </Show>1520            <Show when={view() === "codex-restore"}>1521              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1522                <CodexRestoreView1523                  onBack={() => setView("lock")}1524                  onRestoreSuccess={async () => {1525                    // After restore the vault is unlocked; refresh entries1526                    // and route to the main vault list. handleUnlock is the1527                    // canonical post-unlock setup path.1528                    await handleUnlock();1529                  }}1530                />1531              </Suspense>1532            </Show>1533            <Show when={view() === "sync-pairing"}>1534              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1535                <SyncPairingView1536                  isPro={proStatus()}1537                  onAddDevice={() => setView("sync-add-device")}1538                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1539                  onBack={() => setView("settings")}1540                />1541              </Suspense>1542            </Show>1543            <Show when={view() === "sync-add-device"}>1544              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1545                <AddDeviceView1546                  onClose={() => setView("sync-pairing")}1547                  onPaired={() => setView("sync-pairing")}1548                />1549              </Suspense>1550            </Show>1551            <Show when={view() === "add"}>1552              <AddView1553                entry={editEntry()}1554                entries={entries()}1555                onBack={handleBack}1556                onSave={handleSave}1557              />1558            </Show>1559            <Show when={view() === "import"}>1560              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1561                <ImportView onBack={handleBack} onImport={handleSave} />1562              </Suspense>1563            </Show>1564            <Show when={view() === "export"}>1565              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1566                <ExportView1567                  onBack={() => {1568                    if (returnToPanic()) {1569                      setReturnToPanic(false);1570                      setView("panic");1571                    } else {1572                      handleBack();1573                    }1574                  }}1575                />1576              </Suspense>1577            </Show>1578            <Show when={view() === "panic"}>1579              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1580                <PanicView1581                  onCancel={() => setView("settings")}1582                  onOpenExport={() => {1583                    setReturnToPanic(true);1584                    setView("export");1585                  }}1586                  onDestroyed={async () => {1587                    clearCanarySuppressions();1588                    setEntries([]);1589                    setSelectedEntry(null);1590                    setEditEntry(undefined);1591                    setHasVault(false);1592                    setOnboarded(false);1593                    setProStatus(false);1594                    setPendingPasskey(null);1595                    setUpgradeHighlight(null);1596                    setSettingsInitialSection(null);1597                    setPendingProNotice(null);1598                    setPendingCelebration(false);1599                    setReturnToPanic(false);1600                    setContentPhase("idle");1601                    setView("lock");1602                  }}1603                />1604              </Suspense>1605            </Show>1606            <Show when={view() === "health"}>1607              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1608                <HealthView1609                  entries={entries()}1610                  isPro={proStatus()}1611                  onFixEntry={handleFixEntry}1612                  onBack={() => setView("settings")}1613                  onRefresh={loadEntries}1614                />1615              </Suspense>1616            </Show>1617            <Show when={view() === "trash"}>1618              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1619                <TrashView1620                  onBack={() => setView("list")}1621                  onRestored={() => void loadEntries()}1622                />1623              </Suspense>1624            </Show>1625            <Show when={showNotes()}>1626              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1627                <NotesMode1628                  notes={entries().filter((e) => e.type === "note")}1629                  initialNoteId={openNoteId()}1630                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1631                  onNoteListChanged={() => void loadEntries()}1632                />1633              </div>1634            </Show>1635            <Show when={restoreView() === "file"}>1636              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1637                <ImportView1638                  mode="onboarding"1639                  replacesExistingVault={true}1640                  onBack={() => setRestoreView(null)}1641                  onImport={async () => {1642                    setRestoreView(null);1643                    await handleUnlock();1644                  }}1645                />1646              </Suspense>1647            </Show>1648            </section>1649            </Show>1650          </Show>1651        </Show>1652      </Show>1653      <Show when={showShortcutsHelp()}>1654        <ShortcutsHelpOverlay1655          bindings={shortcutBindings()}1656          onClose={() => setShowShortcutsHelp(false)}1657        />1658      </Show>1659    </div>1660  );1661}16621663function ShortcutsHelpOverlay(props: {1664  bindings: Record<ShortcutAction, Keybinding>;1665  onClose: () => void;1666}) {1667  return (1668    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1669      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1670        <div class="peach-shortcuts-help-head">1671          <h3>Keyboard shortcuts</h3>1672          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1673        </div>1674        <div class="peach-shortcuts-help-body">1675          <p class="peach-settings-sub-label">ENTRY VIEW</p>1676          <ul>1677            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1678              <li>1679                <span>{d.label}</span>1680                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1681              </li>1682            ))}1683          </ul>1684          <p class="peach-settings-sub-label">ANYWHERE</p>1685          <ul>1686            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1687              <li>1688                <span>{d.label}</span>1689                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1690              </li>1691            ))}1692          </ul>1693        </div>1694      </div>1695    </div>1696  );1697}