App.tsx

66.9 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageSet } from "../shared/storage";4import { sendMessage } from "../shared/bridge";5import { ACCENT_COLORS } from "../shared/types";6import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";7import { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { NotesMode } from "./views/NotesMode";11import { ProCelebration } from "./views/ProCelebration";12import { VaultView, type SortOrder } from "./views/Vault";13import { EntryView } from "./views/Entry";14import { AddView } from "./views/Add";15import { PeachWordmark } from "./components/PeachMark";16import { PasskeyApprovalView } from "./views/PasskeyApproval";17import { extractDomain } from "../shared/domain";18import { popupCopy } from "./copy";19import {20  DEFAULT_BINDINGS,21  formatKeybinding,22  getActiveBindings,23  matchKeybinding,24  SHORTCUT_DESCRIPTORS,25  type Keybinding,26  type ShortcutAction,27} from "../shared/shortcuts";28import { generateTOTP } from "../crypto/totp";29import { isNativePlatform, nativePlugin } from "../shared/native";3031export { sendMessage } from "../shared/bridge";3233const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));34const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));35const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));36const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));37const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));38const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));39const ChirpSyncView   = lazy(() => import("./views/ChirpSync").then(m => ({ default: m.ChirpSyncView })));40const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));41const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));4243type View =44  | "lock"45  | "pro-celebration"46  | "entry"47  | "list"48  | "add"49  | "settings"50  | "chirp-sync"51  | "import"52  | "export"53  | "health"54  | "trash"55  | "panic"56  | "codex-generate"57  | "codex-restore";58type BootState = "loading" | "ready";5960const canarySuppressMap = new Map<string, boolean>();61let shellRingAnimation: Animation | null = null;6263export function isCanarySuppressed(entryId: string): boolean {64  return canarySuppressMap.get(entryId) ?? false;65}6667export function setCanarySuppressed(entryId: string, suppressed: boolean): void {68  canarySuppressMap.set(entryId, suppressed);69}7071export function clearCanarySuppressions(): void {72  canarySuppressMap.clear();73}7475export function triggerRing() {76  const shell = document.getElementById("hd-shell");77  if (!shell) return;7879  shellRingAnimation?.cancel();80  shell.dataset.glowing = "true";81  const animation = shell.animate(82    [83      { offset: 0, boxShadow: "var(--copy-shadow)" },84      {85        offset: 0.3,86        boxShadow:87          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",88      },89      { offset: 1, boxShadow: "var(--copy-shadow)" },90    ],91    {92      duration: 720,93      easing: "cubic-bezier(0.4, 0, 0.2, 1)",94      fill: "none",95    }96  );97  shellRingAnimation = animation;98  const clearGlow = () => {99    if (shellRingAnimation !== animation) return;100    shellRingAnimation = null;101    delete shell.dataset.glowing;102  };103  animation.onfinish = clearGlow;104  animation.oncancel = clearGlow;105}106107108export function triggerPipPulse() {109  const pip = document.querySelector(".peach-status-pip, .pip");110  if (pip) {111    pip.classList.remove("pulse");112    void (pip as HTMLElement).offsetWidth;113    pip.classList.add("pulse");114  }115}116117const ENTRY_TRANSITION_SETTLE_MS = 135;118119export default function App() {120  const [bootState, setBootState] = createSignal<BootState>("loading");121  const [view, setView] = createSignal<View>("lock");122  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,123  // CSS transition takes over for snap animation).124  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);125  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(126    "enter"127  );128  const [contentTransitioning, setContentTransitioning] = createSignal(false);129  const [hasVault, setHasVault] = createSignal(false);130  const [onboarded, setOnboarded] = createSignal(true);131  const [entries, setEntries] = createSignal<VaultEntry[]>([]);132  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);133  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);134  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");135  const [theme, setTheme] = createSignal<"dark" | "light">("dark");136  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");137  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);138  const [lockOnClose, setLockOnClose] = createSignal(true);139  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);140  const [breachMonitoring, setBreachMonitoring] = createSignal(true);141  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);142  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);143  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);144  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);145  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);146  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");147  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");148  // Cached Pro status — synchronous for render paths. Background's149  // GET_LICENSE is async, but render-time reads of isPro() must not block.150  // Refreshed at boot, after activate/deactivate, and whenever the popup151  // re-opens onto a stored license that has changed via another window.152  const [proStatus, setProStatus] = createSignal(false);153  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);154  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");155  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);156  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");157  const [listSearchSeed, setListSearchSeed] = createSignal("");158  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);159  const [pendingCelebration, setPendingCelebration] = createSignal(false);160  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);161  // True while Panic Step 1 has bounced the user out to Export. When Export's162  // onBack fires we return to Panic instead of Settings so the user keeps the163  // destruction context they came from.164  const [returnToPanic, setReturnToPanic] = createSignal(false);165  // The view to return to when the add/edit view is dismissed. Normally "entry"166  // but "health" when the user arrives via the fix-entry path from Vault Health.167  const [editBackView, setEditBackView] = createSignal<View>("entry");168  const [settingsExiting, setSettingsExiting] = createSignal(false);169  const [showNotes, setShowNotes] = createSignal(false);170  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);171  // Set on popup boot when peach_recovery_pending flag is found in session172  // storage — instructs LockView to skip the unlock UI and open the recovery173  // words confirmation surface instead. Cleared via handleUnlock once the174  // user has typed the 3 confirmation words.175  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);176177  let contentPhaseTimer: number | undefined;178179  function applyAccent(name: AccentColorName) {180    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;181    const hex = color.hex;182    document.documentElement.style.setProperty("--peach-accent", hex);183    // Ambient surface variables — derived from the accent so surfaces shift184    // subtly toward the accent hue rather than staying fixed warm-brown.185    document.documentElement.style.setProperty("--peach-glow", hex + "2A");186    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");187    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");188  }189190  createEffect(() => {191    applyAccent(accentColor());192  });193194  createEffect(() => {195    document.documentElement.classList.toggle("light", theme() === "light");196    document.body.classList.toggle("light", theme() === "light");197  });198199  createEffect(() => {200    document.documentElement.setAttribute("data-text-size", textSize());201  });202203  createEffect(() => {204    if (reduceMotion()) {205      document.documentElement.setAttribute("data-motion", "reduce");206    } else {207      document.documentElement.removeAttribute("data-motion");208    }209  });210211  const selectedIndex = createMemo(() => {212    const currentId = selectedEntry()?.id;213    if (!currentId) return entries().length > 0 ? 0 : -1;214    return entries().findIndex((entry) => entry.id === currentId);215  });216217  async function applyAccentColor(name: AccentColorName) {218    applyAccent(name);219    setAccentColor(name);220    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });221  }222223  async function applyTheme(t: "dark" | "light") {224    setTheme(t);225    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });226  }227228  async function applyTextSize(size: "small" | "medium" | "large") {229    setTextSize(size);230    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });231  }232233  async function applyReduceMotion(enabled: boolean) {234    setReduceMotion(enabled);235    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });236  }237238  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload239  // small and lets future default updates land for actions the user hasn't240  // touched. Settings sends us the full active map; we filter and store.241  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {242    setShortcutBindings(active);243    const overrides: Record<string, Keybinding> = {};244    for (const action of Object.keys(active) as ShortcutAction[]) {245      const a = active[action];246      const d = DEFAULT_BINDINGS[action];247      const same = a.key === d.key248        && Boolean(a.ctrl)  === Boolean(d.ctrl)249        && Boolean(a.meta)  === Boolean(d.meta)250        && Boolean(a.shift) === Boolean(d.shift)251        && Boolean(a.alt)   === Boolean(d.alt);252      if (!same) overrides[action] = a;253    }254    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });255  }256257  async function applyLockOnClose(enabled: boolean) {258    setLockOnClose(enabled);259    await sendMessage({260      type: "UPDATE_SETTINGS",261      payload: { lockOnClose: enabled },262    });263  }264265  async function applyAutoLockMinutes(minutes: number) {266    setAutoLockMinutes(minutes);267    await sendMessage({268      type: "UPDATE_SETTINGS",269      payload: { autoLockMinutes: minutes },270    });271  }272273  async function applyBreachMonitoring(enabled: boolean) {274    setBreachMonitoring(enabled);275    await sendMessage({276      type: "UPDATE_SETTINGS",277      payload: { breachMonitoring: enabled },278    });279  }280281  onMount(async () => {282    // Resolve the active tab in parallel with the unlock/has-vault queries —283    // openVault()'s smart selection picks the entry matching currentTabDomain,284    // so it must be populated before openVault runs. Previously refreshCurrentTab285    // ran after openVault, leaving popups that booted already-unlocked falling286    // back to loadedEntries[0] instead of the domain match.287    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([288      sendMessage({ type: "IS_UNLOCKED" }),289      sendMessage({ type: "HAS_VAULT" }),290      refreshCurrentTab(),291      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),292    ]);293    const unlocked = Boolean(294      (unlockResponse as { ok: boolean; data?: boolean }).data295    );296    const vaultExists = Boolean(297      (vaultResponse as { ok: boolean; data?: boolean }).data298    );299    const shouldCelebrate = Boolean(300      (celebrationResponse as { ok: boolean; data?: boolean }).data301    );302    setHasVault(vaultExists);303    // Onboarding gate — show once on first install, never again. Existing304    // users (vaultExists) are auto-marked onboarded so they skip the flow305    // even on the very first popup open after this feature ships.306    try {307      const onboarded = await storageGet("peach_onboarded");308      const seen = onboarded === "true";309      if (vaultExists && !seen) {310        await storageSet("peach_onboarded", "true");311        setOnboarded(true);312      } else {313        setOnboarded(seen);314      }315    } catch {316      // storage unavailable — default to onboarded so we never block boot317      setOnboarded(true);318    }319    await Promise.all([restoreSettings(), refreshProStatus()]);320321    // Mark played before any animation so a crash mid-sequence never replays it322    if (shouldCelebrate) {323      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });324    }325326    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the327    // background ignores it when no mobile hosts are paired or while328    // another sync is already in flight.329    if (unlocked && vaultExists) {330      void sendMessage({331        type: "TRIGGER_SYNC",332        payload: { reason: "foreground" },333      });334    }335336    // If the user created a vault but hasn't yet confirmed their recovery337    // words, route back to the recovery-words screen instead of opening the338    // entries view. The flag lives in chrome.storage.local so it survives339    // both popup close (SW suppresses lock-on-close) and full browser340    // restart (handleUnlock checks the same flag after a fresh password341    // unlock). Cleared when confirmation succeeds.342    let recoveryPending = false;343    try {344      const out = await chrome.storage.local?.get("peach_recovery_pending");345      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";346    } catch { /* best-effort */ }347348    // Native: closing the app before recovery-words confirmation means the349    // user didn't finish vault creation. Throw the partial vault away and350    // restart onboarding rather than asking them to unlock a vault they351    // never finished creating. Desktop keeps the existing "unlock to352    // resume" flow because closing the popup there is much more casual.353    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {354      try {355        await chrome.storage.local?.remove([356          "peach_vault_a",357          "peach_vault_b",358          "peach_recovery_pending",359          "peach_onboarded",360          "peach_vault_history",361        ]);362      } catch { /* best-effort */ }363      setHasVault(false);364      setOnboarded(false);365      setView("lock");366      setBootState("ready");367      document.getElementById("pre-lock")?.setAttribute("hidden", "true");368      return;369    }370371    if (recoveryPending && unlocked) {372      // forceRecoveryWords overrides LockView's hasVault gate so the373      // recovery surface renders even though the vault now exists.374      setForceRecoveryWords(true);375      setView("lock");376    } else if (unlocked && vaultExists) {377      await openVault(undefined, shouldCelebrate);378      if (shouldCelebrate) {379        setView("pro-celebration");380        window.setTimeout(() => setView("entry"), 2500);381      }382    } else if (shouldCelebrate) {383      setPendingCelebration(true);384    }385386    await refreshPendingPasskey();387388    // Track tab changes so smart sort stays current389    const handleTabActivated = () => { void refreshCurrentTab(); };390    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {391      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();392    };393    try {394      chrome.tabs.onActivated.addListener(handleTabActivated);395      chrome.tabs.onUpdated.addListener(handleTabUpdated);396      onCleanup(() => {397        chrome.tabs.onActivated.removeListener(handleTabActivated);398        chrome.tabs.onUpdated.removeListener(handleTabUpdated);399      });400    } catch {401      // tabs permission may not be available in all contexts402    }403404    setBootState("ready");405    document.getElementById("pre-lock")?.setAttribute("hidden", "true");406407    // Deep-link: ?codex=pdf opens a detached window straight into the408    // Codex restore flow with auto-picked PDF. The action popup can't host409    // a file dialog without dismissing itself, so this is the only way the410    // PDF import path survives. See CodexRestoreView.openPdfPicker().411    try {412      const route = new URLSearchParams(window.location.search).get("codex");413      if (route === "pdf" || route === "restore") {414        setView("codex-restore");415      }416    } catch {417      // location.search unavailable — ignore.418    }419420    // Check for pending session-storage notices from the background.421    if (chrome.storage.session) {422      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as423        Record<string, { feature?: string } | undefined>;424      if (session.pendingProGate?.feature) {425        await chrome.storage.session.remove("pendingProGate");426        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);427        setSettingsInitialSection("license");428        setView("settings");429      } else if (session.pendingProNotice?.feature) {430        await chrome.storage.session.remove("pendingProNotice");431        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });432      }433    }434435    // Warm the lazy-module cache so the Suspense fallback never shows for436    // locally-bundled extension views. Without this, the first navigation to437    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which438    // covers the shell and absorbs clicks on the header.439    void Promise.all([440      import("./views/Settings").catch(() => {}),441      import("./views/Import").catch(() => {}),442      import("./views/Export").catch(() => {}),443      import("./views/Health").catch(() => {}),444      import("./views/TrashView").catch(() => {}),445    ]);446447    // Lock-on-close via a persistent port. sendMessage in pagehide is448    // unreliable — the popup context tears down before the message lands.449    // The SW's onConnect listener locks when this port disconnects.450    let popupPort: chrome.runtime.Port | null = null;451    try {452      popupPort = chrome.runtime.connect({ name: "popup" });453    } catch { /* extension context invalidated — ignore */ }454    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });455456    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only457    // reliable signal is appStateChange — setTimeout is killed when the OS458    // backgrounds the app. We measure elapsed background time on resume.459    if (isNativePlatform()) {460      let backgroundedAt: number | null = null;461462      const CapApp = nativePlugin<{463        addListener: (464          ev: string,465          cb: (s: { isActive: boolean }) => void,466        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };467      }>("App");468      if (CapApp?.addListener) {469        const sub = CapApp.addListener(470          "appStateChange",471          ({ isActive }: { isActive: boolean }) => {472            if (!isActive) {473              backgroundedAt = Date.now();474              return;475            }476            if (backgroundedAt !== null && autoLockMinutes() > 0) {477              const elapsed = Date.now() - backgroundedAt;478              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();479            }480            backgroundedAt = null;481          }482        );483        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.484        onCleanup(() => {485          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});486        });487      }488489      // L12/COR-011: foreground idle autolock. appStateChange only fires when490      // the OS backgrounds the app — if the user idles with the screen on,491      // chrome.alarms is no-op'd in Capacitor so the vault would stay open492      // indefinitely. Poll every 30s and lock if elapsed since last user493      // interaction exceeds autoLockMinutes.494      let lastUserActivityAt = Date.now();495      const bumpActivity = () => { lastUserActivityAt = Date.now(); };496      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;497      for (const ev of ACTIVITY_EVENTS) {498        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });499      }500      const idleLockInterval = setInterval(() => {501        const minutes = autoLockMinutes();502        if (!minutes || minutes <= 0) return;503        const elapsed = Date.now() - lastUserActivityAt;504        if (elapsed >= minutes * 60_000) {505          lastUserActivityAt = Date.now();506          handleHeaderLock();507        }508      }, 30_000);509      onCleanup(() => {510        clearInterval(idleLockInterval);511        for (const ev of ACTIVITY_EVENTS) {512          document.removeEventListener(ev, bumpActivity, { capture: true });513        }514      });515516      // mDNS peer-discovery trigger. Register onCleanup synchronously so517      // SolidJS captures it within the reactive owner — onCleanup inside a518      // .then() callback may miss the capture window and leak the listener.519      let stopMDNS: () => void = () => undefined;520      onCleanup(() => stopMDNS());521      if (isNativePlatform()) {522        // Android runs the background/sync dispatcher in-process with the523        // popup, so the production runner has to be registered from the524        // UI bootstrap path instead of the MV3 service-worker entry.525        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>526          import("../background/chirp-sync-runner").then(({ productionSyncRunner }) => {527            setSyncRunner(productionSyncRunner);528            void hydratePersistedSyncState();529          })530        );531      }532      void import("./chirp-pair-capacitor").then(({ startMDNSListener }) => {533        stopMDNS = startMDNSListener();534      });535    }536537    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale538    // entries instead of waiting for the next GET_ENTRIES round-trip.539    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {540      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();541      if (msg?.type === "PRO_GATE_TRIGGERED") {542        setUpgradeHighlight(msg.payload?.feature ?? null);543        setSettingsInitialSection("license");544        setView("settings");545      }546    };547    chrome.runtime.onMessage.addListener(handleRuntimeMessage);548    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));549550    // Android hardware/gesture back. MainActivity fires peach:back; the popup551    // decides what "back" means per surface. Lock+no-vault is the common case552    // — return to onboarding rather than letting the OS dismiss the activity.553    const handlePeachBack = () => {554      // Notes mode captures back first555      if (showNotes()) {556        setShowNotes(false);557        setOpenNoteId(undefined);558        return;559      }560      const v = view();561      if (v === "lock" && !hasVault() && onboarded()) {562        setOnboarded(false);563        return;564      }565      if (v === "list") { setView("entry"); return; }566      if (v === "settings") {567        window.dispatchEvent(new Event("peach:settings-back"));568        return;569      }570      if (v === "import" || v === "health") { setView("settings"); return; }571      if (v === "export") { handleExportBack(); return; }572      if (v === "add") { handleBack(); return; }573      if (v === "chirp-sync") { setView("settings"); return; }574    };575    window.addEventListener("peach:back", handlePeachBack);576    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));577578    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that579    // peeks from the bottom (search bar handle visible) and drags up to fill580    // the screen. dragOffset is the LIVE finger offset during a drag, in px,581    // 0 when no drag in progress. The wrapper element computes transform =582    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.583    if (isNativePlatform()) {584      let touchStartY = 0;585      let touchStartX = 0;586      let lastY = 0;587      let lastT = 0;588      let dragging = false;589      let captured = false;590      const HORIZONTAL_TOLERANCE = 16;591      const ACTIVATION_DY = 8;592      const PEEK_PX = 60;593594      const onTouchStart = (e: TouchEvent) => {595        const t = e.touches[0];596        if (!t) return;597        const v = view();598        if (v !== "entry" && v !== "list") return;599        // Entry view: only intercept drags starting in the bottom 40%.600        // List view: intercept drags starting in the top 35% (the search/handle row).601        const inBand = v === "entry"602          ? t.clientY > window.innerHeight * 0.6603          : t.clientY < window.innerHeight * 0.35;604        if (!inBand) return;605        touchStartY = lastY = t.clientY;606        touchStartX = t.clientX;607        lastT = e.timeStamp;608        dragging = true;609        captured = false;610      };611612      const onTouchMove = (e: TouchEvent) => {613        if (!dragging) return;614        const t = e.touches[0];615        if (!t) return;616        const dy = t.clientY - touchStartY;617        const dx = Math.abs(t.clientX - touchStartX);618619        if (!captured) {620          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {621            // Looks like a horizontal swipe — release.622            dragging = false;623            return;624          }625          if (Math.abs(dy) < ACTIVATION_DY) return;626          captured = true;627        }628629        // Translate the sheet by dy from its rest (peek) position. Peek is630        // (viewport height - PEEK_PX). Open is 0.631        const v = view();632        const restClosed = window.innerHeight - PEEK_PX;633        const baseTranslate = v === "list" ? 0 : restClosed;634        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));635        setSheetTranslate(next);636        lastY = t.clientY;637        lastT = e.timeStamp;638      };639640      const onTouchEnd = (e: TouchEvent) => {641        if (!dragging) { return; }642        const t = e.changedTouches[0];643        const elapsed = Math.max(1, e.timeStamp - lastT);644        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms645        const wasCaptured = captured;646        dragging = false;647        captured = false;648        const v = view();649650        if (!wasCaptured) {651          // Tap in the peek strip while in entry view → open the vault list.652          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");653          setSheetTranslate(null);654          return;655        }656657        const restClosed = window.innerHeight - PEEK_PX;658        const current = sheetTranslate() ?? restClosed;659660        // Snap rules:661        //   - Strong upward velocity → open662        //   - Strong downward velocity → close663        //   - Otherwise snap to whichever rest is closer664        let nextOpen: boolean;665        if (velocity < -0.05) nextOpen = true;666        else if (velocity > 0.05) nextOpen = false;667        else nextOpen = current < restClosed * 0.5;668669        if (nextOpen && v !== "list") setView("list");670        if (!nextOpen && v !== "entry") setView("entry");671        // Release the live offset so CSS transition handles the snap.672        setSheetTranslate(null);673      };674675      document.addEventListener("touchstart", onTouchStart, { passive: true });676      document.addEventListener("touchmove",  onTouchMove,  { passive: true });677      document.addEventListener("touchend",   onTouchEnd,   { passive: true });678      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });679      onCleanup(() => {680        document.removeEventListener("touchstart", onTouchStart);681        document.removeEventListener("touchmove",  onTouchMove);682        document.removeEventListener("touchend",   onTouchEnd);683      });684    }685686    // Action handlers — keyed by ShortcutAction. The dispatcher below tests687    // each binding against the event and runs the matching handler. New688    // shortcuts only need an entry here; the binding is data, not code.689    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {690      copy_password: () => {691        const entry = selectedEntry();692        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });693      },694      copy_username: () => {695        const entry = selectedEntry();696        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });697      },698      copy_totp: () => {699        const entry = selectedEntry();700        if (!entry?.totp) return;701        try {702          const { code } = generateTOTP(entry.totp);703          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });704        } catch { /* invalid TOTP secret — silent */ }705      },706      new_entry: () => handleAdd(),707      edit_entry: () => {708        const entry = selectedEntry();709        // Passkey-only entries have nothing user-editable in the Add view; the710        // passkey credential itself is opaque. Skip the edit action for them.711        if (!entry || isPasskeyOnly(entry)) return;712        setEditEntry(entry);713        setView("add");714      },715      delete_entry: () => {716        if (selectedEntry()) void handleDelete();717      },718      lock_vault: () => { void handleHeaderLock(); },719      search: () => openList(),720      nav_prev: () => navigate(-1),721      nav_next: () => navigate(1),722      jump_vault: () => setView("entry"),723      jump_settings: () => setView("settings"),724      show_help: () => setShowShortcutsHelp(true),725    };726727    // Actions that are MEANINGFUL only on the entry-detail view. Outside728    // that scope the binding is dormant — pressing C while on Settings729    // does nothing rather than awkwardly copying from a now-stale entry.730    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([731      "copy_password", "copy_username", "copy_totp",732      "edit_entry", "delete_entry", "nav_prev", "nav_next",733    ]);734735    const handleGlobalKeydown = (e: KeyboardEvent) => {736      const v = view();737      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"738        || (e.target as HTMLElement)?.tagName === "TEXTAREA"739        || (e.target as HTMLElement)?.isContentEditable;740      const isPrintableSearchKey =741        e.key.length === 1 &&742        !e.ctrlKey &&743        !e.metaKey &&744        !e.altKey;745746      // No input during the pro celebration sequence747      if (v === "pro-celebration") return;748749      // Help dialog: Escape closes it; eat the keypress so it doesn't750      // also navigate away from the underlying view.751      if (showShortcutsHelp()) {752        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }753        return;754      }755756      // ── Escape — fixed binding (not user-customizable) ───────757      if (e.key === "Escape") {758        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }759        if (v === "list") { setView("entry"); return; }760        if (v === "settings" || v === "add") { handleBack(); return; }761        if (v === "import" || v === "health") { setView("settings"); return; }762        if (v === "export") { handleExportBack(); return; }763        if (v === "chirp-sync") { setView("settings"); return; }764      }765766      // Bindings-driven dispatch. Single-key letter bindings without767      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is768      // inside an input, so users can type into search/forms normally.769      const bindings = shortcutBindings();770      for (const action of Object.keys(bindings) as ShortcutAction[]) {771        const binding = bindings[action];772        if (!matchKeybinding(e, binding)) continue;773        // Single-key letter bindings need the input-focus guard. Bindings774        // with any modifier are safe — Ctrl+L doesn't conflict with typing.775        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;776        if (!hasMod && binding.key.length === 1 && inInput) return;777        if (ENTRY_SCOPED.has(action) && v !== "entry") return;778        e.preventDefault();779        SHORTCUT_HANDLERS[action]?.();780        return;781      }782783      // Type-to-search: in entry view, any printable key not consumed by a784      // shortcut above primes the list search seed and opens the list.785      // Kept outside the bindings table because it's a behavior, not a786      // discrete action — every printable character can trigger it.787      if (v === "entry" && !inInput && isPrintableSearchKey) {788        e.preventDefault();789        primeListSearch(e.key);790        return;791      }792    };793    window.addEventListener("keydown", handleGlobalKeydown);794    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));795796    const handleStorageChanged = (797      changes: Record<string, chrome.storage.StorageChange>,798      areaName: string799    ) => {800      if (areaName !== "session") return;801      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {802        return;803      }804      void refreshPendingPasskey();805    };806    chrome.storage.onChanged.addListener(handleStorageChanged);807    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));808  });809810  async function refreshCurrentTab() {811    try {812      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });813      const url = tab?.url ?? tab?.pendingUrl ?? "";814      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");815      // Skip extension/internal URLs — adding chrome://, about:, or816      // chrome-extension:// to a vault entry is never what the user wants.817      const isWebUrl = /^https?:\/\//i.test(url);818      setCurrentTabUrl(isWebUrl ? url : "");819    } catch {820      setCurrentTabDomain("");821      setCurrentTabUrl("");822    }823  }824825  async function refreshPendingPasskey() {826    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });827    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);828  }829830  async function refreshProStatus() {831    const res = await sendMessage({ type: "GET_LICENSE" });832    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;833    setProStatus(Boolean(data?.valid && data?.plan === "pro"));834  }835836  async function restoreSettings() {837    const res = await sendMessage({ type: "GET_SETTINGS" });838    const s = (res as { ok: boolean; data?: any }).data ?? {};839    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {840      setAccentColor(s.accentColor as AccentColorName);841    }842    setTheme(s.theme === "light" ? "light" : "dark");843    if (s.textSize === "small" || s.textSize === "large") {844      setTextSize(s.textSize);845    } else {846      setTextSize("medium");847    }848    setReduceMotion(s.reduceMotion === true);849    setLockOnClose(s.lockOnClose !== false);850    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);851    setBreachMonitoring(s.breachMonitoring !== false);852    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);853    setShortcutBindings(getActiveBindings(s.shortcuts));854  }855856  async function applyTrashRetention(days: number) {857    setTrashRetentionDays(days);858    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });859  }860861  function primeListSearch(seed: string) {862    setListSearchSeed(seed);863    setListSearchSeedNonce((value) => value + 1);864    openList();865  }866867  // Returns null when it detected a dead service worker and triggered handleLock().868  // Callers that need to abort (e.g. openVault) check for null rather than relying869  // on view() state, which may already be "lock" during normal startup flows.870  async function loadEntries(): Promise<VaultEntry[] | null> {871    const response = await sendMessage({ type: "GET_ENTRIES" });872    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };873874    // If the service worker was killed and restarted (MV3 workers sleep), the875    // vault will be locked again — or the worker may not respond at all.876    // In either case, send the user to the lock screen rather than silently877    // showing an empty vault (which looks like data loss).878    if (!res.ok) {879      if (880        res.error === "vault_locked" ||881        res.error === "SERVICE_WORKER_UNAVAILABLE" ||882        (typeof res.error === "string" && res.error.includes("locked"))883      ) {884        handleLock();885        return null; // signal emergency lock to callers886      }887      return [];888    }889890    const loadedEntries = res.data ?? [];891    setEntries(loadedEntries);892893    const currentId = selectedEntry()?.id;894    if (currentId) {895      setSelectedEntry(896        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null897      );898    }899900    return loadedEntries;901  }902903  async function openVault(preferredEntryId?: string, skipViewSet = false) {904    // Purge expired trash entries on each vault open905    const retDays = trashRetentionDays();906    if (retDays > 0) {907      void sendMessage({908        type: "PURGE_EXPIRED_TRASH",909        payload: { retentionMs: retDays * 86_400_000 },910      });911    }912913    const loadedEntries = await loadEntries();914915    // null means loadEntries() triggered an emergency lock (service worker died).916    // Don't override it by setting view back to "entry" with an empty vault.917    if (loadedEntries === null) return;918919    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry920    let nextSelectedEntry: VaultEntry | null = null;921    if (preferredEntryId) {922      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;923    }924    if (!nextSelectedEntry) {925      const tabDomain = currentTabDomain();926      if (tabDomain) {927        nextSelectedEntry = loadedEntries.find((e) => {928          if (e.type === "login") {929            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;930            for (const extra of e.additionalUrls ?? []) {931              if ((extractDomain(extra) ?? "") === tabDomain) return true;932            }933            return false;934          }935          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;936          return false;937        }) ?? null;938      }939    }940    nextSelectedEntry ??= loadedEntries[0] ?? null;941942    setSelectedEntry(nextSelectedEntry);943    setEditEntry(undefined);944    setContentTransitioning(false);945    setContentPhase("enter");946    queueContentIdle();947    if (!skipViewSet) setView("entry");948  }949950  async function handleUnlock() {951    // If the user previously created a vault but hadn't yet confirmed their952    // recovery words (and the browser was closed before they could), the953    // peach_recovery_pending flag is still set in storage.local. Re-route954    // back to the recovery surface so they finish the confirmation step955    // before reaching the entries view — the words can be re-derived now956    // that the vault is unlocked again.957    let recoveryPending = false;958    try {959      const out = await chrome.storage.local?.get("peach_recovery_pending");960      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";961    } catch { /* best-effort */ }962    if (recoveryPending) {963      setForceRecoveryWords(true);964      setView("lock");965      triggerPipPulse();966      await restoreSettings();967      return;968    }969    setHasVault(true);970    triggerPipPulse();971    await restoreSettings();972    const celebrating = pendingCelebration();973    if (celebrating) {974      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });975      setPendingCelebration(false);976    }977    await openVault(undefined, celebrating);978    if (celebrating) {979      setView("pro-celebration");980      window.setTimeout(() => setView("entry"), 2500);981    }982  }983984  function handleSelectEntry(entry: VaultEntry) {985    if (entry.type === "note") {986      setOpenNoteId(entry.id);987      setShowNotes(true);988      return;989    }990    setSelectedEntry(entry);991    setContentTransitioning(false);992    setContentPhase("enter");993    queueContentIdle();994    setView("entry");995  }996997  function handleAdd() {998    setEditEntry(undefined);999    setView("add");1000  }10011002  async function handleDelete() {1003    const entry = selectedEntry();1004    if (!entry) return;1005    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1006    const loadedEntries = await loadEntries() ?? [];1007    setSelectedEntry(loadedEntries[0] ?? null);1008    setView("entry");1009  }10101011  async function handleDeleteMany(ids: string[]) {1012    for (const id of ids) {1013      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1014    }1015    const loadedEntries = await loadEntries() ?? [];1016    // If the currently selected entry was among the deleted, move to first1017    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1018    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1019  }10201021  async function handleSave(savedEntry?: VaultEntry) {1022    await openVault(savedEntry?.id);1023  }10241025  function handleBack() {1026    const dest = editBackView();1027    setEditBackView("entry");1028    setEditEntry(undefined);1029    setView(dest);1030  }10311032  function handleExportBack() {1033    if (returnToPanic()) {1034      setReturnToPanic(false);1035      setView("panic");1036      return;1037    }1038    setView("settings");1039  }10401041  function handleLock() {1042    clearCanarySuppressions();1043    setEntries([]);1044    setSelectedEntry(null);1045    setEditEntry(undefined);1046    setContentPhase("idle");1047    setView("lock");1048  }10491050  function handleHeaderLock() {1051    // Lock the UI immediately — do not wait for the service worker. If the SW1052    // is dead or slow, the 5s sendMessage timeout would create a dead-click1053    // window. The SW will lock on its next wake regardless.1054    handleLock();1055    void sendMessage({ type: "LOCK" });1056  }10571058  function navigate(dir: number) {1059    const allEntries = entries();1060    if (allEntries.length === 0) return;1061    const currentIndex = selectedIndex();1062    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1063    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1064    setSelectedEntry(allEntries[nextIndex]);1065    setContentPhase("enter");1066    queueContentIdle();1067  }10681069  function openList() {1070    setView("list");1071  }10721073  function openHealth() {1074    setEditEntry(undefined);1075    setView("health");1076  }10771078  function handleOpenFileImport() {1079    setRestoreView("file");1080  }10811082  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10831084  function handleFixEntry(entry: VaultEntry) {1085    setSelectedEntry(entry);1086    // Passkey-only entries have no editable surface — drop into view mode1087    // instead of opening the Add editor.1088    if (isPasskeyOnly(entry)) {1089      setView("entry");1090      return;1091    }1092    setEditBackView(view()); // preserve caller view so back returns here1093    setEditEntry(entry);1094    setView("add");1095  }10961097  const isLockedView = () => view() === "lock";10981099  async function handleApprovePendingPasskey() {1100    const pending = pendingPasskey();1101    if (!pending) return;1102    if (pending.browser === "firefox" && pending.type === "create") {1103      // Firefox path: popup itself runs navigator.credentials.create. The1104      // background never approved/rejected anything — it just stashed1105      // intent. After the popup-driven flow resolves (success or cancel),1106      // clear the pending key so the popup doesn't re-show this on next open.1107      const { createFirefoxPasskey } = await import("./firefox-passkey");1108      const result = await createFirefoxPasskey(pending);1109      if (!result.ok) {1110        console.warn("Peach Firefox passkey create failed:", result.error);1111      }1112      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1113      setPendingPasskey(null);1114      void loadEntries();1115      window.close();1116      return;1117    }1118    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1119    window.close();1120  }11211122  async function handleDenyPendingPasskey() {1123    const pending = pendingPasskey();1124    if (!pending) return;1125    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1126    window.close();1127  }11281129  function queueContentIdle(after?: () => void) {1130    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1131    contentPhaseTimer = window.setTimeout(() => {1132      setContentPhase("idle");1133      after?.();1134    }, ENTRY_TRANSITION_SETTLE_MS);1135  }11361137  return (1138    <div class="popup-root peach-theme">1139      <Show when={bootState() === "ready"}>1140        <Show1141          when={!pendingPasskey()}1142          fallback={1143            <PasskeyApprovalView1144              type={pendingPasskey()!.type}1145              rpName={pendingPasskey()!.rpName}1146              rpId={pendingPasskey()!.rpId}1147              userName={pendingPasskey()!.userName}1148              userDisplayName={pendingPasskey()!.userDisplayName}1149              onApprove={handleApprovePendingPasskey}1150              onDeny={handleDenyPendingPasskey}1151            />1152          }1153        >1154          <Show1155            when={!isLockedView()}1156            fallback={1157              <Show1158                when={onboarded() || hasVault()}1159                fallback={1160                  <Onboarding1161                    onComplete={() => { setOnboarded(true); }}1162                  />1163                }1164              >1165                <LockView1166                  hasVault={hasVault()}1167                  ready={bootState() === "ready"}1168                  isPro={proStatus()}1169                  forceRecoveryWords={forceRecoveryWords()}1170                  onUnlock={() => {1171                    // RecoveryWordDisplay clears the storage flag before1172                    // calling onDone, so handleUnlock will see no pending1173                    // confirmation and proceed through the normal path.1174                    if (forceRecoveryWords()) setForceRecoveryWords(false);1175                    return handleUnlock();1176                  }}1177                  onBackToOnboarding={1178                    !hasVault()1179                      ? () => setOnboarded(false)1180                      : undefined1181                  }1182                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1183                />1184              </Show>1185            }1186          >1187            <Show1188              when={view() !== "pro-celebration"}1189              fallback={<ProCelebration />}1190            >1191            <section1192              id="hd-shell"1193              class="peach-shell peach-theme"1194              data-surface="extension"1195            >1196            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1197              <PeachWordmark unlocked />1198              <div class="peach-chrome-actions">1199                <button1200                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1201                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1202                  aria-label="Notes"1203                  title="Notes"1204                >1205                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1206                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1207                    <line x1="4" y1="5" x2="10" y2="5" />1208                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1209                    <line x1="4" y1="10" x2="7" y2="10" />1210                  </svg>1211                </button>1212                <button1213                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1214                  onClick={() => setView("settings")}1215                  aria-label="Settings"1216                >1217                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1218                    <path1219                      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"1220                      stroke="currentColor"1221                      stroke-width="0.9"1222                    />1223                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1224                  </svg>1225                </button>1226                <button1227                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1228                  onClick={handleAdd}1229                  aria-label="New entry"1230                >1231                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1232                    <path d="M5.5 1v9M1 5.5h9" />1233                  </svg>1234                </button>1235                <button1236                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1237                  onClick={() => void handleHeaderLock()}1238                  aria-label="Lock vault"1239                >1240                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1241                    <path1242                      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"1243                      stroke="currentColor"1244                      stroke-width="1"1245                      stroke-linecap="round"1246                    />1247                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1248                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1249                  </svg>1250                </button>1251              </div>1252            </header>12531254            <Show when={pendingProNotice() !== null}>1255              <div class="peach-pro-notice-banner">1256                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1257                <button1258                  class="peach-pro-notice-link"1259                  onClick={() => {1260                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1261                    setSettingsInitialSection("license");1262                    setView("settings");1263                    setPendingProNotice(null);1264                  }}1265                >1266                  Learn more →1267                </button>1268                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1269              </div>1270            </Show>12711272            <div class="peach-shell-body">1273              <div class="peach-shell-veil"></div>1274              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1275                <EntryView1276                  entry={selectedEntry()}1277                  currentTabUrl={currentTabUrl()}1278                  entries={entries()}1279                  isPro={proStatus()}1280                  onDelete={handleDelete}1281                  onFieldSaved={() => void loadEntries()}1282                  onEscape={() => { setView("list"); }}1283                  onProGate={(feature) => {1284                    setUpgradeHighlight(feature);1285                    setSettingsInitialSection("license");1286                    setView("settings");1287                  }}1288                />1289              </div>12901291              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1292                <div class="peach-search-bar">1293                  <span class="peach-search-icon">1294                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1295                      <circle cx="5.5" cy="5.5" r="3.75" />1296                      <path d="M8.75 8.75L11.5 11.5" />1297                    </svg>1298                  </span>1299                  <input1300                    class="peach-search-input"1301                    placeholder="search vault..."1302                    autocomplete="off"1303                    aria-label="Search vault entries"1304                    onClick={openList}1305                    onFocus={openList}1306                    readOnly1307                  />1308                  <div class="peach-search-meta">1309                    <span class="peach-search-counter">1310                      {entries().length > 01311                        ? `${selectedIndex() + 1} / ${entries().length}`1312                        : "0 entries"}1313                    </span>1314                    <span class="peach-divider"></span>1315                    <button1316                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1317                      onClick={() => navigate(-1)}1318                      aria-label="Previous entry"1319                      disabled={entries().length === 0}1320                    >1321                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1322                        <path d="M5 1L1 5.5L5 10" />1323                      </svg>1324                    </button>1325                    <button1326                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1327                      onClick={() => navigate(1)}1328                      aria-label="Next entry"1329                      disabled={entries().length === 0}1330                    >1331                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1332                        <path d="M1 1L5 5.5L1 10" />1333                      </svg>1334                    </button>1335                  </div>1336                </div>1337              </section>1338            </div>13391340            {/* Desktop: shown on demand via Show. Native sheet is rendered1341                via Portal below at the document root so its position:fixed1342                isn't trapped by .peach-shell's transform-based animations. */}1343            <Show when={!isNativePlatform() && view() === "list"}>1344              <VaultView1345                entries={entries()}1346                selectedEntryId={selectedEntry()?.id}1347                currentTabDomain={currentTabDomain()}1348                sortOrder={sortOrder()}1349                searchSeed={listSearchSeed()}1350                searchSeedNonce={listSearchSeedNonce()}1351                onSelectEntry={handleSelectEntry}1352                onSortOrderChange={setSortOrder}1353                onAdd={handleAdd}1354                onClose={() => setView("entry")}1355                onOpenTrash={() => setView("trash")}1356                onDeleteMany={handleDeleteMany}1357              />1358            </Show>1359            <Show when={isNativePlatform() && hasVault()}>1360              <Portal>1361                <div1362                  class="peach-vault-sheet"1363                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1364                  style={(() => {1365                    const live = sheetTranslate();1366                    if (live === null) return undefined;1367                    return { transform: `translateY(${live}px)` };1368                  })()}1369                >1370                  <VaultView1371                    entries={entries()}1372                    selectedEntryId={selectedEntry()?.id}1373                    currentTabDomain={currentTabDomain()}1374                    sortOrder={sortOrder()}1375                    searchSeed={listSearchSeed()}1376                    searchSeedNonce={listSearchSeedNonce()}1377                    isNative={true}1378                    onSelectEntry={handleSelectEntry}1379                    onSortOrderChange={setSortOrder}1380                    onAdd={handleAdd}1381                    onClose={() => setView("entry")}1382                    onOpenTrash={() => setView("trash")}1383                    onDeleteMany={handleDeleteMany}1384                  />1385                </div>1386              </Portal>1387            </Show>1388            <Show when={view() === "settings" || settingsExiting()}>1389              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1390                <SettingsView1391                  entriesCount={entries().length}1392                  breachMonitoring={breachMonitoring()}1393                  lockOnClose={lockOnClose()}1394                  autoLockMinutes={autoLockMinutes()}1395                  trashRetentionDays={trashRetentionDays()}1396                  theme={theme()}1397                  accentColor={accentColor()}1398                  textSize={textSize()}1399                  reduceMotion={reduceMotion()}1400                  isPro={proStatus()}1401                  initialSection={settingsInitialSection()}1402                  upgradeHighlight={upgradeHighlight()}1403                  isExiting={settingsExiting()}1404                  onBreachMonitoringChange={applyBreachMonitoring}1405                  onLockOnCloseChange={applyLockOnClose}1406                  onAutoLockMinutesChange={applyAutoLockMinutes}1407                  onTrashRetentionChange={applyTrashRetention}1408                  onThemeChange={applyTheme}1409                  onAccentChange={applyAccentColor}1410                  onTextSizeChange={applyTextSize}1411                  onReduceMotionChange={applyReduceMotion}1412                  shortcuts={shortcutBindings()}1413                  onShortcutsChange={applyShortcuts}1414                  onLicenseChange={async () => {1415                    // After activation/deactivation: refresh Pro status,1416                    // re-load entries (defensive — signal state can drift if1417                    // the SW briefly restarts during the verify+save round-trip),1418                    // and replay the Pro celebration if this is the first time1419                    // a valid Pro license is seen on this device.1420                    await refreshProStatus();1421                    void loadEntries();1422                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1423                    if ((should as { ok: boolean; data?: boolean }).data === true) {1424                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1425                      setView("pro-celebration");1426                      window.setTimeout(() => setView("settings"), 2500);1427                    }1428                  }}1429                  onBack={() => {1430                    setSettingsExiting(true);1431                    window.setTimeout(() => {1432                      setSettingsExiting(false);1433                      setSettingsInitialSection(null);1434                      setUpgradeHighlight(null);1435                      handleBack();1436                    }, 200);1437                  }}1438                  onImport={() => setView("import")}1439                  onExport={() => setView("export")}1440                  onBreachCheckDone={loadEntries}1441                  onOpenHealth={openHealth}1442                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("chirp-sync"); }}1443                  onOpenFileImport={handleOpenFileImport}1444                  onOpenPanic={() => setView("panic")}1445                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1446                  onOpenCodexRestore={() => setView("codex-restore")}1447                  onCardChange={setSettingsActiveCard}1448                  onProGate={(feature) => {1449                    setUpgradeHighlight(feature);1450                    setSettingsInitialSection("license");1451                  }}1452                />1453              </Suspense>1454            </Show>1455            <Show when={view() === "codex-generate"}>1456              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1457                <CodexGenerateView1458                  isPro={proStatus()}1459                  onBack={() => setView("settings")}1460                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1461                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1462                  onVaultLocked={() => handleLock()}1463                />1464              </Suspense>1465            </Show>1466            <Show when={view() === "codex-restore"}>1467              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1468                <CodexRestoreView1469                  onBack={() => setView("lock")}1470                  onRestoreSuccess={async () => {1471                    // After restore the vault is unlocked; refresh entries1472                    // and route to the main vault list. handleUnlock is the1473                    // canonical post-unlock setup path.1474                    await handleUnlock();1475                  }}1476                />1477              </Suspense>1478            </Show>1479            <Show when={view() === "chirp-sync"}>1480              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1481                <ChirpSyncView1482                  isPro={proStatus()}1483                  onBack={() => setView("settings")}1484                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1485                />1486              </Suspense>1487            </Show>1488            <Show when={view() === "add"}>1489              <AddView1490                entry={editEntry()}1491                entries={entries()}1492                onBack={handleBack}1493                onSave={handleSave}1494              />1495            </Show>1496            <Show when={view() === "import"}>1497              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1498                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1499              </Suspense>1500            </Show>1501            <Show when={view() === "export"}>1502              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1503                <ExportView onBack={handleExportBack} />1504              </Suspense>1505            </Show>1506            <Show when={view() === "panic"}>1507              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1508                <PanicView1509                  onCancel={() => setView("settings")}1510                  onOpenExport={() => {1511                    setReturnToPanic(true);1512                    setView("export");1513                  }}1514                  onDestroyed={async () => {1515                    clearCanarySuppressions();1516                    setEntries([]);1517                    setSelectedEntry(null);1518                    setEditEntry(undefined);1519                    setHasVault(false);1520                    setOnboarded(false);1521                    setProStatus(false);1522                    setPendingPasskey(null);1523                    setUpgradeHighlight(null);1524                    setSettingsInitialSection(null);1525                    setPendingProNotice(null);1526                    setPendingCelebration(false);1527                    setReturnToPanic(false);1528                    setContentPhase("idle");1529                    setView("lock");1530                  }}1531                />1532              </Suspense>1533            </Show>1534            {/* Health stays mounted while editing an entry from it so1535                computeReused() doesn't rerun on every cancel/back. */}1536            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1537              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1538                <HealthView1539                  entries={entries()}1540                  isPro={proStatus()}1541                  onFixEntry={handleFixEntry}1542                  onBack={() => setView("settings")}1543                  onRefresh={loadEntries}1544                  hidden={view() !== "health"}1545                />1546              </Suspense>1547            </Show>1548            <Show when={view() === "trash"}>1549              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1550                <TrashView1551                  onBack={() => setView("list")}1552                  onRestored={() => void loadEntries()}1553                />1554              </Suspense>1555            </Show>1556            <Show when={showNotes()}>1557              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1558                <NotesMode1559                  notes={entries().filter((e) => e.type === "note")}1560                  initialNoteId={openNoteId()}1561                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1562                  onNoteListChanged={() => void loadEntries()}1563                />1564              </div>1565            </Show>1566            <Show when={restoreView() === "file"}>1567              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1568                <ImportView1569                  mode="onboarding"1570                  replacesExistingVault={true}1571                  onBack={() => setRestoreView(null)}1572                  onImport={async () => {1573                    setRestoreView(null);1574                    await handleUnlock();1575                  }}1576                />1577              </Suspense>1578            </Show>1579            </section>1580            </Show>1581          </Show>1582        </Show>1583      </Show>1584      <Show when={showShortcutsHelp()}>1585        <ShortcutsHelpOverlay1586          bindings={shortcutBindings()}1587          onClose={() => setShowShortcutsHelp(false)}1588        />1589      </Show>1590    </div>1591  );1592}15931594function ShortcutsHelpOverlay(props: {1595  bindings: Record<ShortcutAction, Keybinding>;1596  onClose: () => void;1597}) {1598  return (1599    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1600      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1601        <div class="peach-shortcuts-help-head">1602          <h3>Keyboard shortcuts</h3>1603          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1604        </div>1605        <div class="peach-shortcuts-help-body">1606          <p class="peach-settings-sub-label">ENTRY VIEW</p>1607          <ul>1608            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1609              <li>1610                <span>{d.label}</span>1611                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1612              </li>1613            ))}1614          </ul>1615          <p class="peach-settings-sub-label">ANYWHERE</p>1616          <ul>1617            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1618              <li>1619                <span>{d.label}</span>1620                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1621              </li>1622            ))}1623          </ul>1624        </div>1625      </div>1626    </div>1627  );1628}