App.tsx

80.2 KB · raw

1import { createEffect, createMemo, createSignal, For, 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 {19  syncIndicator,20  syncIndicatorLabel,21  type SyncOutcomeSummary,22} from "../shared/sync-outcome";23import { popupCopy } from "./copy";24import {25  DEFAULT_BINDINGS,26  formatKeybinding,27  getActiveBindings,28  matchKeybinding,29  SHORTCUT_DESCRIPTORS,30  type Keybinding,31  type ShortcutAction,32} from "../shared/shortcuts";33import { generateTOTP } from "../crypto/totp";34import { isNativePlatform, nativePlugin } from "../shared/native";3536export { sendMessage } from "../shared/bridge";3738const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));39const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));40const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));41const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));42const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));43const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));44const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));45const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));46const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));47const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));4849type View =50  | "lock"51  | "pro-celebration"52  | "entry"53  | "list"54  | "add"55  | "settings"56  | "pair-device"57  | "import"58  | "export"59  | "health"60  | "trash"61  | "panic"62  | "adopting"63  | "codex-generate"64  | "codex-restore";65type BootState = "loading" | "ready";6667const canarySuppressMap = new Map<string, boolean>();68let shellRingAnimation: Animation | null = null;6970export function isCanarySuppressed(entryId: string): boolean {71  return canarySuppressMap.get(entryId) ?? false;72}7374export function setCanarySuppressed(entryId: string, suppressed: boolean): void {75  canarySuppressMap.set(entryId, suppressed);76}7778export function clearCanarySuppressions(): void {79  canarySuppressMap.clear();80}8182export function triggerRing() {83  const shell = document.getElementById("hd-shell");84  if (!shell) return;8586  shellRingAnimation?.cancel();87  shell.dataset.glowing = "true";88  const animation = shell.animate(89    [90      { offset: 0, boxShadow: "var(--copy-shadow)" },91      {92        offset: 0.3,93        boxShadow:94          "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)",95      },96      { offset: 1, boxShadow: "var(--copy-shadow)" },97    ],98    {99      duration: 720,100      easing: "cubic-bezier(0.4, 0, 0.2, 1)",101      fill: "none",102    }103  );104  shellRingAnimation = animation;105  const clearGlow = () => {106    if (shellRingAnimation !== animation) return;107    shellRingAnimation = null;108    delete shell.dataset.glowing;109  };110  animation.onfinish = clearGlow;111  animation.oncancel = clearGlow;112}113114115export function triggerPipPulse() {116  const pip = document.querySelector(".peach-status-pip, .pip");117  if (pip) {118    pip.classList.remove("pulse");119    void (pip as HTMLElement).offsetWidth;120    pip.classList.add("pulse");121  }122}123124function defaultAdoptionDeviceName(): string {125  const ua = (typeof navigator !== "undefined" ? navigator.userAgent : "") || "";126  if (/Firefox/i.test(ua)) return "Firefox";127  if (/Edg\//i.test(ua)) return "Edge";128  if (/Chrome/i.test(ua)) return "Chrome";129  if (/Safari/i.test(ua)) return "Safari";130  return "Peach";131}132133const ENTRY_TRANSITION_SETTLE_MS = 135;134135export default function App() {136  const [bootState, setBootState] = createSignal<BootState>("loading");137  const [view, setView] = createSignal<View>("lock");138  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,139  // CSS transition takes over for snap animation).140  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);141  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(142    "enter"143  );144  const [contentTransitioning, setContentTransitioning] = createSignal(false);145  const [hasVault, setHasVault] = createSignal(false);146  const [onboarded, setOnboarded] = createSignal(true);147  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);148  const [entries, setEntries] = createSignal<VaultEntry[]>([]);149  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);150  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);151152  // Rare device-trust alerts stay visible; routine entry sync is silent.153  interface SyncAlert {154    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";155    entryId: string;156    entryTitle: string;157    deviceName: string;158    timestamp: number;159  }160  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);161  async function loadSyncAlerts() {162    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {163      ok: boolean;164      data?: SyncAlert[];165    };166    if (r.ok && (r.data?.length ?? 0) > 0) {167      setSyncAlerts(r.data ?? []);168      // Acknowledge so a crash between read and render doesn't lose them —169      // they remain on screen until the user dismisses each.170      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });171    }172  }173  function dismissSyncAlert(index: number) {174    setSyncAlerts((arr) => arr.filter((_, i) => i !== index));175  }176  function syncAlertText(a: SyncAlert): string {177    if (a.type === "DEVICE_REVOKED") {178      return `${a.deviceName} revoked a paired device — review your devices in Settings`;179    }180    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;181  }182  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");183  const [theme, setTheme] = createSignal<"dark" | "light">("dark");184  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");185  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);186  const [lockOnClose, setLockOnClose] = createSignal(true);187  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);188  const [breachMonitoring, setBreachMonitoring] = createSignal(true);189  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);190  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);191  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);192  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);193  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);194  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");195  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");196  // Cached Pro status — synchronous for render paths. Background's197  // GET_LICENSE is async, but render-time reads of isPro() must not block.198  // Refreshed at boot, after activate/deactivate, and whenever the popup199  // re-opens onto a stored license that has changed via another window.200  const [proStatus, setProStatus] = createSignal(false);201  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);202  // When the sync card's pairing button opens the pairing view, deep-link203  // straight into that pairing path instead of the rest screen.204  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");205  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);206  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");207  const [listSearchSeed, setListSearchSeed] = createSignal("");208  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);209  const [pendingCelebration, setPendingCelebration] = createSignal(false);210  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);211  // True while Panic Step 1 has bounced the user out to Export. When Export's212  // onBack fires we return to Panic instead of Settings so the user keeps the213  // destruction context they came from.214  const [returnToPanic, setReturnToPanic] = createSignal(false);215  // The view to return to when the add/edit view is dismissed. Normally "entry"216  // but "health" when the user arrives via the fix-entry path from Vault Health.217  const [editBackView, setEditBackView] = createSignal<View>("entry");218  const [settingsExiting, setSettingsExiting] = createSignal(false);219  const [showNotes, setShowNotes] = createSignal(false);220  // Topbar sync affordance. Always present: gating it on having a paired device221  // meant it never appeared for the person trying to set pairing up, which is222  // exactly when you reach for it.223  const [syncBusy, setSyncBusy] = createSignal(false);224  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);225  // The indicator light + its spoken-word equivalent. Colour alone is not the226  // signal; the title/aria-label always carries the same claim in English.227  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});228  const [pairedCount, setPairedCount] = createSignal(0);229  const syncLight = () =>230    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());231  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());232  async function loadSyncIndicator() {233    const [stateRes, devicesRes] = await Promise.all([234      sendMessage({ type: "GET_SYNC_STATE" }),235      sendMessage({ type: "LIST_PAIRED_DEVICES" }),236    ]);237    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };238    if (s.ok && s.data) setSyncSummary(s.data);239    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };240    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);241  }242  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);243  // Set on popup boot when peach_recovery_pending flag is found in session244  // storage — instructs LockView to skip the unlock UI and open the recovery245  // words confirmation surface instead. Cleared via handleUnlock once the246  // user has typed the 3 confirmation words.247  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);248249  let contentPhaseTimer: number | undefined;250  // Set when the popup was opened from the inline "Open Peach to unlock" button.251  // handleUnlock() closes the popup after unlock so the user returns to the page.252  let openedForInlineUnlock = false;253254  function applyAccent(name: AccentColorName) {255    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;256    const hex = color.hex;257    document.documentElement.style.setProperty("--peach-accent", hex);258    // Ambient surface variables — derived from the accent so surfaces shift259    // subtly toward the accent hue rather than staying fixed warm-brown.260    document.documentElement.style.setProperty("--peach-glow", hex + "2A");261    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");262    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");263  }264265  createEffect(() => {266    applyAccent(accentColor());267  });268269  createEffect(() => {270    document.documentElement.classList.toggle("light", theme() === "light");271    document.body.classList.toggle("light", theme() === "light");272  });273274  createEffect(() => {275    document.documentElement.setAttribute("data-text-size", textSize());276  });277278  createEffect(() => {279    if (reduceMotion()) {280      document.documentElement.setAttribute("data-motion", "reduce");281    } else {282      document.documentElement.removeAttribute("data-motion");283    }284  });285286  // Notes are not a destination of the Entry view; selecting a note opens the287  // notes surface instead (handleSelectEntry). Anything that walks or counts288  // the Entry view's neighbours (counter, prev/next, index) must use this289  // filtered list, otherwise the user can arrow into a note and is stuck —290  // the Entry view can't render a note and the prev/next buttons stop moving.291  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));292293  const selectedIndex = createMemo(() => {294    const currentId = selectedEntry()?.id;295    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;296    return nonNoteEntries().findIndex((entry) => entry.id === currentId);297  });298299  async function applyAccentColor(name: AccentColorName) {300    applyAccent(name);301    setAccentColor(name);302    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });303  }304305  async function applyTheme(t: "dark" | "light") {306    setTheme(t);307    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });308  }309310  async function applyTextSize(size: "small" | "medium" | "large") {311    setTextSize(size);312    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });313  }314315  async function applyReduceMotion(enabled: boolean) {316    setReduceMotion(enabled);317    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });318  }319320  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload321  // small and lets future default updates land for actions the user hasn't322  // touched. Settings sends us the full active map; we filter and store.323  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {324    setShortcutBindings(active);325    const overrides: Record<string, Keybinding> = {};326    for (const action of Object.keys(active) as ShortcutAction[]) {327      const a = active[action];328      const d = DEFAULT_BINDINGS[action];329      const same = a.key === d.key330        && Boolean(a.ctrl)  === Boolean(d.ctrl)331        && Boolean(a.meta)  === Boolean(d.meta)332        && Boolean(a.shift) === Boolean(d.shift)333        && Boolean(a.alt)   === Boolean(d.alt);334      if (!same) overrides[action] = a;335    }336    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });337  }338339  async function applyLockOnClose(enabled: boolean) {340    setLockOnClose(enabled);341    await sendMessage({342      type: "UPDATE_SETTINGS",343      payload: { lockOnClose: enabled },344    });345  }346347  async function applyAutoLockMinutes(minutes: number) {348    setAutoLockMinutes(minutes);349    await sendMessage({350      type: "UPDATE_SETTINGS",351      payload: { autoLockMinutes: minutes },352    });353  }354355  async function applyBreachMonitoring(enabled: boolean) {356    setBreachMonitoring(enabled);357    await sendMessage({358      type: "UPDATE_SETTINGS",359      payload: { breachMonitoring: enabled },360    });361  }362363  onMount(async () => {364    // Resolve the active tab in parallel with the unlock/has-vault queries —365    // openVault()'s smart selection picks the entry matching currentTabDomain,366    // so it must be populated before openVault runs. Previously refreshCurrentTab367    // ran after openVault, leaving popups that booted already-unlocked falling368    // back to loadedEntries[0] instead of the domain match.369    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([370      sendMessage({ type: "IS_UNLOCKED" }),371      sendMessage({ type: "HAS_VAULT" }),372      refreshCurrentTab(),373      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),374    ]);375    const unlocked = Boolean(376      (unlockResponse as { ok: boolean; data?: boolean }).data377    );378    const vaultExists = Boolean(379      (vaultResponse as { ok: boolean; data?: boolean }).data380    );381    const shouldCelebrate = Boolean(382      (celebrationResponse as { ok: boolean; data?: boolean }).data383    );384    setHasVault(vaultExists);385    // Onboarding gate — show once on first install, never again. Existing386    // users (vaultExists) are auto-marked onboarded so they skip the flow387    // even on the very first popup open after this feature ships.388    try {389      const onboarded = await storageGet("peach_onboarded");390      const seen = onboarded === "true";391      if (vaultExists && !seen) {392        await storageSet("peach_onboarded", "true");393        setOnboarded(true);394      } else {395        setOnboarded(seen);396      }397    } catch {398      // storage unavailable — default to onboarded so we never block boot399      setOnboarded(true);400    }401    await Promise.all([restoreSettings(), refreshProStatus()]);402403    // Mark played before any animation so a crash mid-sequence never replays it404    if (shouldCelebrate) {405      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });406    }407408    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome409    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.410    if (unlocked && vaultExists) {411      void sendMessage({412        type: "TRIGGER_SYNC",413        payload: { reason: "foreground" },414      });415      void loadSyncIndicator();416      // Rare device-trust alerts only; routine entry sync stays quiet.417      void loadSyncAlerts();418    }419420    // If the user created a vault but hasn't yet confirmed their recovery421    // words, route back to the recovery-words screen instead of opening the422    // entries view. The flag lives in chrome.storage.local so it survives423    // both popup close (SW suppresses lock-on-close) and full browser424    // restart (handleUnlock checks the same flag after a fresh password425    // unlock). Cleared when confirmation succeeds.426    let recoveryPending = false;427    try {428      const out = await chrome.storage.local?.get("peach_recovery_pending");429      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";430    } catch { /* best-effort */ }431432    // If this popup was opened from the inline "Open Peach to unlock" button,433    // the background set a session flag. Read and clear it so handleUnlock()434    // can close the popup after unlock and return the user to the page.435    if (chrome.storage.session) {436      try {437        const s = await chrome.storage.session.get("peach_inline_unlock");438        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {439          openedForInlineUnlock = true;440          await chrome.storage.session.remove("peach_inline_unlock");441        }442      } catch { /* best-effort */ }443    }444445    // Native: closing the app before recovery-words confirmation means the446    // user didn't finish vault creation. Throw the partial vault away and447    // restart onboarding rather than asking them to unlock a vault they448    // never finished creating. Desktop keeps the existing "unlock to449    // resume" flow because closing the popup there is much more casual.450    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {451      try {452        await chrome.storage.local?.remove([453          "peach_vault_a",454          "peach_vault_b",455          "peach_recovery_pending",456          "peach_onboarded",457          "peach_vault_history",458        ]);459      } catch { /* best-effort */ }460      setHasVault(false);461      setOnboarded(false);462      setView("lock");463      setBootState("ready");464      return;465    }466467    if (recoveryPending && unlocked) {468      // forceRecoveryWords overrides LockView's hasVault gate so the469      // recovery surface renders even though the vault now exists.470      setForceRecoveryWords(true);471      setView("lock");472    } else if (unlocked && vaultExists) {473      await openVault(undefined, shouldCelebrate);474      if (shouldCelebrate) {475        setView("pro-celebration");476        window.setTimeout(() => setView("entry"), 2500);477      }478    } else if (shouldCelebrate) {479      setPendingCelebration(true);480    }481482    await refreshPendingPasskey();483484    // Track tab changes so smart sort stays current485    const handleTabActivated = () => { void refreshCurrentTab(); };486    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {487      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();488    };489    try {490      chrome.tabs.onActivated.addListener(handleTabActivated);491      chrome.tabs.onUpdated.addListener(handleTabUpdated);492      onCleanup(() => {493        chrome.tabs.onActivated.removeListener(handleTabActivated);494        chrome.tabs.onUpdated.removeListener(handleTabUpdated);495      });496    } catch {497      // tabs permission may not be available in all contexts498    }499500    setBootState("ready");501502    // Deep-link: ?codex=pdf opens a detached window straight into the503    // Codex restore flow with auto-picked PDF. The action popup can't host504    // a file dialog without dismissing itself, so this is the only way the505    // PDF import path survives. See CodexRestoreView.openPdfPicker().506    try {507      const route = new URLSearchParams(window.location.search).get("codex");508      if (route === "pdf" || route === "restore") {509        setView("codex-restore");510      }511    } catch {512      // location.search unavailable — ignore.513    }514515    // Check for pending session-storage notices from the background.516    if (chrome.storage.session) {517      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as518        Record<string, { feature?: string } | undefined>;519      if (session.pendingProGate?.feature) {520        await chrome.storage.session.remove("pendingProGate");521        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);522        setSettingsInitialSection("license");523        setView("settings");524      } else if (session.pendingProNotice?.feature) {525        await chrome.storage.session.remove("pendingProNotice");526        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });527      }528    }529530    // Warm the lazy-module cache so the Suspense fallback never shows for531    // locally-bundled extension views. Without this, the first navigation to532    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which533    // covers the shell and absorbs clicks on the header.534    void Promise.all([535      import("./views/Settings").catch(() => {}),536      import("./views/Import").catch(() => {}),537      import("./views/Export").catch(() => {}),538      import("./views/Health").catch(() => {}),539      import("./views/TrashView").catch(() => {}),540    ]);541542    // Lock-on-close via a persistent port. sendMessage in pagehide is543    // unreliable — the popup context tears down before the message lands.544    // The SW's onConnect listener locks when this port disconnects.545    let popupPort: chrome.runtime.Port | null = null;546    try {547      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect548      // listener accepts the "popup-" prefix; the random suffix is defence in549      // depth against a port named exactly "popup" from anything but our popup.550      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });551    } catch { /* extension context invalidated — ignore */ }552    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });553554    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only555    // reliable signal is appStateChange — setTimeout is killed when the OS556    // backgrounds the app. We measure elapsed background time on resume.557    if (isNativePlatform()) {558      let backgroundedAt: number | null = null;559560      const CapApp = nativePlugin<{561        addListener: (562          ev: string,563          cb: (s: { isActive: boolean }) => void,564        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };565      }>("App");566      if (CapApp?.addListener) {567        const sub = CapApp.addListener(568          "appStateChange",569          ({ isActive }: { isActive: boolean }) => {570            if (!isActive) {571              backgroundedAt = Date.now();572              return;573            }574            if (backgroundedAt !== null && autoLockMinutes() > 0) {575              const elapsed = Date.now() - backgroundedAt;576              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();577            }578            backgroundedAt = null;579          }580        );581        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.582        onCleanup(() => {583          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});584        });585      }586587      // L12/COR-011: foreground idle autolock. appStateChange only fires when588      // the OS backgrounds the app — if the user idles with the screen on,589      // chrome.alarms is no-op'd in Capacitor so the vault would stay open590      // indefinitely. Poll every 30s and lock if elapsed since last user591      // interaction exceeds autoLockMinutes.592      let lastUserActivityAt = Date.now();593      const bumpActivity = () => { lastUserActivityAt = Date.now(); };594      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;595      for (const ev of ACTIVITY_EVENTS) {596        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });597      }598      const idleLockInterval = setInterval(() => {599        const minutes = autoLockMinutes();600        if (!minutes || minutes <= 0) return;601        const elapsed = Date.now() - lastUserActivityAt;602        if (elapsed >= minutes * 60_000) {603          lastUserActivityAt = Date.now();604          handleHeaderLock();605        }606      }, 30_000);607      onCleanup(() => {608        clearInterval(idleLockInterval);609        for (const ev of ACTIVITY_EVENTS) {610          document.removeEventListener(ev, bumpActivity, { capture: true });611        }612      });613614      // The retired native peer-discovery trigger went with the old Capacitor615      // pairing plugin. Reconnection is address-cache first, subnet probe second616      // (sync-runner.ts); relocating a peer that changed networks is an617      // Android-side discovery concern now.618      if (isNativePlatform()) {619        // Android runs the background/sync dispatcher in-process with the620        // popup, so the production runner has to be registered from the621        // UI bootstrap path instead of the MV3 service-worker entry.622        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>623          import("../background/sync-runner").then(({ productionSyncRunner }) => {624            setSyncRunner(productionSyncRunner);625            void hydratePersistedSyncState();626          })627        );628      }629    }630631    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale632    // entries instead of waiting for the next GET_ENTRIES round-trip.633    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {634      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();635      if (msg?.type === "SYNC_STATE_CHANGED") {636        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);637      }638      if (msg?.type === "PRO_GATE_TRIGGERED") {639        setUpgradeHighlight(msg.payload?.feature ?? null);640        setSettingsInitialSection("license");641        setView("settings");642      }643    };644    chrome.runtime.onMessage.addListener(handleRuntimeMessage);645    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));646647    // Android hardware/gesture back. MainActivity fires peach:back; the popup648    // decides what "back" means per surface. Lock+no-vault is the common case649    // — return to onboarding rather than letting the OS dismiss the activity.650    const handlePeachBack = () => {651      // Notes mode captures back first652      if (showNotes()) {653        setShowNotes(false);654        setOpenNoteId(undefined);655        return;656      }657      const v = view();658      if (v === "lock" && !hasVault() && onboarded()) {659        setOnboarded(false);660        return;661      }662      if (v === "list") { setView("entry"); return; }663      if (v === "settings") {664        window.dispatchEvent(new Event("peach:settings-back"));665        return;666      }667      if (v === "import" || v === "health") { setView("settings"); return; }668      if (v === "export") { handleExportBack(); return; }669      if (v === "add") { handleBack(); return; }670      if (v === "pair-device") { setView("settings"); return; }671    };672    window.addEventListener("peach:back", handlePeachBack);673    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));674675    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that676    // peeks from the bottom (search bar handle visible) and drags up to fill677    // the screen. dragOffset is the LIVE finger offset during a drag, in px,678    // 0 when no drag in progress. The wrapper element computes transform =679    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.680    if (isNativePlatform()) {681      let touchStartY = 0;682      let touchStartX = 0;683      let lastY = 0;684      let lastT = 0;685      let dragging = false;686      let captured = false;687      const HORIZONTAL_TOLERANCE = 16;688      const ACTIVATION_DY = 8;689      const PEEK_PX = 60;690691      const onTouchStart = (e: TouchEvent) => {692        const t = e.touches[0];693        if (!t) return;694        const v = view();695        if (v !== "entry" && v !== "list") return;696        // Entry view: only intercept drags starting in the bottom 40%.697        // List view: intercept drags starting in the top 35% (the search/handle row).698        const inBand = v === "entry"699          ? t.clientY > window.innerHeight * 0.6700          : t.clientY < window.innerHeight * 0.35;701        if (!inBand) return;702        touchStartY = lastY = t.clientY;703        touchStartX = t.clientX;704        lastT = e.timeStamp;705        dragging = true;706        captured = false;707      };708709      const onTouchMove = (e: TouchEvent) => {710        if (!dragging) return;711        const t = e.touches[0];712        if (!t) return;713        const dy = t.clientY - touchStartY;714        const dx = Math.abs(t.clientX - touchStartX);715716        if (!captured) {717          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {718            // Looks like a horizontal swipe — release.719            dragging = false;720            return;721          }722          if (Math.abs(dy) < ACTIVATION_DY) return;723          captured = true;724        }725726        // Translate the sheet by dy from its rest (peek) position. Peek is727        // (viewport height - PEEK_PX). Open is 0.728        const v = view();729        const restClosed = window.innerHeight - PEEK_PX;730        const baseTranslate = v === "list" ? 0 : restClosed;731        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));732        setSheetTranslate(next);733        lastY = t.clientY;734        lastT = e.timeStamp;735      };736737      const onTouchEnd = (e: TouchEvent) => {738        if (!dragging) { return; }739        const t = e.changedTouches[0];740        const elapsed = Math.max(1, e.timeStamp - lastT);741        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms742        const wasCaptured = captured;743        dragging = false;744        captured = false;745        const v = view();746747        if (!wasCaptured) {748          // Tap in the peek strip while in entry view → open the vault list.749          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");750          setSheetTranslate(null);751          return;752        }753754        const restClosed = window.innerHeight - PEEK_PX;755        const current = sheetTranslate() ?? restClosed;756757        // Snap rules:758        //   - Strong upward velocity → open759        //   - Strong downward velocity → close760        //   - Otherwise snap to whichever rest is closer761        let nextOpen: boolean;762        if (velocity < -0.05) nextOpen = true;763        else if (velocity > 0.05) nextOpen = false;764        else nextOpen = current < restClosed * 0.5;765766        if (nextOpen && v !== "list") setView("list");767        if (!nextOpen && v !== "entry") setView("entry");768        // Release the live offset so CSS transition handles the snap.769        setSheetTranslate(null);770      };771772      document.addEventListener("touchstart", onTouchStart, { passive: true });773      document.addEventListener("touchmove",  onTouchMove,  { passive: true });774      document.addEventListener("touchend",   onTouchEnd,   { passive: true });775      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });776      onCleanup(() => {777        document.removeEventListener("touchstart", onTouchStart);778        document.removeEventListener("touchmove",  onTouchMove);779        document.removeEventListener("touchend",   onTouchEnd);780      });781    }782783    // Action handlers — keyed by ShortcutAction. The dispatcher below tests784    // each binding against the event and runs the matching handler. New785    // shortcuts only need an entry here; the binding is data, not code.786    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {787      copy_password: () => {788        const entry = selectedEntry();789        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });790      },791      copy_username: () => {792        const entry = selectedEntry();793        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });794      },795      copy_totp: () => {796        const entry = selectedEntry();797        if (!entry?.totp) return;798        try {799          const { code } = generateTOTP(entry.totp);800          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });801        } catch { /* invalid TOTP secret — silent */ }802      },803      new_entry: () => handleAdd(),804      edit_entry: () => {805        const entry = selectedEntry();806        // Passkey-only entries have nothing user-editable in the Add view; the807        // passkey credential itself is opaque. Skip the edit action for them.808        if (!entry || isPasskeyOnly(entry)) return;809        setEditEntry(entry);810        setView("add");811      },812      delete_entry: () => {813        if (selectedEntry()) void handleDelete();814      },815      lock_vault: () => { void handleHeaderLock(); },816      search: () => openList(),817      nav_prev: () => navigate(-1),818      nav_next: () => navigate(1),819      jump_vault: () => setView("entry"),820      jump_settings: () => setView("settings"),821      show_help: () => setShowShortcutsHelp(true),822    };823824    // Actions that are MEANINGFUL only on the entry-detail view. Outside825    // that scope the binding is dormant — pressing C while on Settings826    // does nothing rather than awkwardly copying from a now-stale entry.827    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([828      "copy_password", "copy_username", "copy_totp",829      "edit_entry", "delete_entry", "nav_prev", "nav_next",830    ]);831832    const handleGlobalKeydown = (e: KeyboardEvent) => {833      const v = view();834      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"835        || (e.target as HTMLElement)?.tagName === "TEXTAREA"836        || (e.target as HTMLElement)?.isContentEditable;837      const isPrintableSearchKey =838        e.key.length === 1 &&839        !e.ctrlKey &&840        !e.metaKey &&841        !e.altKey;842843      // No input during the pro celebration sequence844      if (v === "pro-celebration") return;845846      // Help dialog: Escape closes it; eat the keypress so it doesn't847      // also navigate away from the underlying view.848      if (showShortcutsHelp()) {849        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }850        return;851      }852853      // ── Escape — fixed binding (not user-customizable) ───────854      if (e.key === "Escape") {855        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }856        if (v === "list") { setView("entry"); return; }857        if (v === "settings" || v === "add") { handleBack(); return; }858        if (v === "import" || v === "health") { setView("settings"); return; }859        if (v === "export") { handleExportBack(); return; }860        if (v === "pair-device") { setView("settings"); return; }861      }862863      // Bindings-driven dispatch. Single-key letter bindings without864      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is865      // inside an input, so users can type into search/forms normally.866      const bindings = shortcutBindings();867      for (const action of Object.keys(bindings) as ShortcutAction[]) {868        const binding = bindings[action];869        if (!matchKeybinding(e, binding)) continue;870        // Single-key letter bindings need the input-focus guard. Bindings871        // with any modifier are safe — Ctrl+L doesn't conflict with typing.872        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;873        if (!hasMod && binding.key.length === 1 && inInput) return;874        if (ENTRY_SCOPED.has(action) && v !== "entry") return;875        e.preventDefault();876        SHORTCUT_HANDLERS[action]?.();877        return;878      }879880      // Type-to-search: in entry view, any printable key not consumed by a881      // shortcut above primes the list search seed and opens the list.882      // Kept outside the bindings table because it's a behavior, not a883      // discrete action — every printable character can trigger it.884      if (v === "entry" && !inInput && isPrintableSearchKey) {885        e.preventDefault();886        primeListSearch(e.key);887        return;888      }889    };890    window.addEventListener("keydown", handleGlobalKeydown);891    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));892893    const handleStorageChanged = (894      changes: Record<string, chrome.storage.StorageChange>,895      areaName: string896    ) => {897      if (areaName !== "session") return;898      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {899        return;900      }901      void refreshPendingPasskey();902    };903    chrome.storage.onChanged.addListener(handleStorageChanged);904    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));905  });906907  async function refreshCurrentTab() {908    try {909      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });910      const url = tab?.url ?? tab?.pendingUrl ?? "";911      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");912      // Skip extension/internal URLs — adding chrome://, about:, or913      // chrome-extension:// to a vault entry is never what the user wants.914      const isWebUrl = /^https?:\/\//i.test(url);915      setCurrentTabUrl(isWebUrl ? url : "");916    } catch {917      setCurrentTabDomain("");918      setCurrentTabUrl("");919    }920  }921922  async function refreshPendingPasskey() {923    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });924    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);925  }926927  async function refreshProStatus() {928    const res = await sendMessage({ type: "GET_LICENSE" });929    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;930    setProStatus(Boolean(data?.valid && data?.plan === "pro"));931  }932933  async function restoreSettings() {934    const res = await sendMessage({ type: "GET_SETTINGS" });935    const s = (res as { ok: boolean; data?: any }).data ?? {};936    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {937      setAccentColor(s.accentColor as AccentColorName);938    }939    setTheme(s.theme === "light" ? "light" : "dark");940    if (s.textSize === "small" || s.textSize === "large") {941      setTextSize(s.textSize);942    } else {943      setTextSize("medium");944    }945    setReduceMotion(s.reduceMotion === true);946    setLockOnClose(s.lockOnClose !== false);947    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);948    setBreachMonitoring(s.breachMonitoring !== false);949    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);950    setShortcutBindings(getActiveBindings(s.shortcuts));951  }952953  async function applyTrashRetention(days: number) {954    setTrashRetentionDays(days);955    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });956  }957958  function primeListSearch(seed: string) {959    setListSearchSeed(seed);960    setListSearchSeedNonce((value) => value + 1);961    openList();962  }963964  // Returns null when it detected a dead service worker and triggered handleLock().965  // Callers that need to abort (e.g. openVault) check for null rather than relying966  // on view() state, which may already be "lock" during normal startup flows.967  async function loadEntries(): Promise<VaultEntry[] | null> {968    const response = await sendMessage({ type: "GET_ENTRIES" });969    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };970971    // If the service worker was killed and restarted (MV3 workers sleep), the972    // vault will be locked again — or the worker may not respond at all.973    // In either case, send the user to the lock screen rather than silently974    // showing an empty vault (which looks like data loss).975    if (!res.ok) {976      if (977        res.error === "vault_locked" ||978        res.error === "SERVICE_WORKER_UNAVAILABLE" ||979        (typeof res.error === "string" && res.error.includes("locked"))980      ) {981        handleLock();982        return null; // signal emergency lock to callers983      }984      return [];985    }986987    const loadedEntries = res.data ?? [];988    setEntries(loadedEntries);989990    const currentId = selectedEntry()?.id;991    if (currentId) {992      setSelectedEntry(993        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)994      );995    }996997    return loadedEntries;998  }9991000  async function openVault(preferredEntryId?: string, skipViewSet = false) {1001    // Purge expired trash entries on each vault open1002    const retDays = trashRetentionDays();1003    if (retDays > 0) {1004      void sendMessage({1005        type: "PURGE_EXPIRED_TRASH",1006        payload: { retentionMs: retDays * 86_400_000 },1007      });1008    }10091010    const loadedEntries = await loadEntries();10111012    // null means loadEntries() triggered an emergency lock (service worker died).1013    // Don't override it by setting view back to "entry" with an empty vault.1014    if (loadedEntries === null) return;10151016    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1017    let nextSelectedEntry: VaultEntry | null = null;1018    if (preferredEntryId) {1019      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1020    }1021    if (!nextSelectedEntry) {1022      const tabDomain = currentTabDomain();1023      if (tabDomain) {1024        nextSelectedEntry = loadedEntries.find((e) => {1025          if (e.type === "login") {1026            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1027            for (const extra of e.additionalUrls ?? []) {1028              if ((extractDomain(extra) ?? "") === tabDomain) return true;1029            }1030            return false;1031          }1032          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1033          return false;1034        }) ?? null;1035      }1036    }1037    nextSelectedEntry ??= pickNavigable(loadedEntries);10381039    setSelectedEntry(nextSelectedEntry);1040    setEditEntry(undefined);1041    setContentTransitioning(false);1042    setContentPhase("enter");1043    queueContentIdle();1044    if (!skipViewSet) setView("entry");1045  }10461047  async function handleUnlock() {1048    // If the user previously created a vault but hadn't yet confirmed their1049    // recovery words (and the browser was closed before they could), the1050    // peach_recovery_pending flag is still set in storage.local. Re-route1051    // back to the recovery surface so they finish the confirmation step1052    // before reaching the entries view — the words can be re-derived now1053    // that the vault is unlocked again.1054    let recoveryPending = false;1055    try {1056      const out = await chrome.storage.local?.get("peach_recovery_pending");1057      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1058    } catch { /* best-effort */ }1059    if (recoveryPending) {1060      setForceRecoveryWords(true);1061      setView("lock");1062      triggerPipPulse();1063      await restoreSettings();1064      return;1065    }1066    setHasVault(true);1067    triggerPipPulse();1068    await restoreSettings();1069    const celebrating = pendingCelebration();1070    if (celebrating) {1071      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1072      setPendingCelebration(false);1073    }1074    await openVault(undefined, celebrating);1075    if (celebrating) {1076      setView("pro-celebration");1077      window.setTimeout(() => setView("entry"), 2500);1078    }1079    // Popup was opened from the inline "Open Peach to unlock" button — close it1080    // now so the user lands back on the page with the autofill selector ready.1081    if (openedForInlineUnlock) {1082      openedForInlineUnlock = false;1083      window.close();1084    }1085  }10861087  function handleSelectEntry(entry: VaultEntry) {1088    if (entry.type === "note") {1089      setOpenNoteId(entry.id);1090      setShowNotes(true);1091      return;1092    }1093    setSelectedEntry(entry);1094    setContentTransitioning(false);1095    setContentPhase("enter");1096    queueContentIdle();1097    setView("entry");1098  }10991100  function handleAdd() {1101    setEditEntry(undefined);1102    setView("add");1103  }11041105  async function handleDelete() {1106    const entry = selectedEntry();1107    if (!entry) return;1108    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1109    const loadedEntries = await loadEntries() ?? [];1110    setSelectedEntry(pickNavigable(loadedEntries));1111    setView("entry");1112  }11131114  async function handleDeleteMany(ids: string[]) {1115    for (const id of ids) {1116      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1117    }1118    const loadedEntries = await loadEntries() ?? [];1119    // If the currently selected entry was among the deleted, move to first1120    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1121    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1122  }11231124  async function handleSave(savedEntry?: VaultEntry) {1125    await openVault(savedEntry?.id);1126  }11271128  function handleBack() {1129    const dest = editBackView();1130    setEditBackView("entry");1131    setEditEntry(undefined);1132    setView(dest);1133  }11341135  function handleExportBack() {1136    if (returnToPanic()) {1137      setReturnToPanic(false);1138      setView("panic");1139      return;1140    }1141    setView("settings");1142  }11431144  function handleLock() {1145    clearCanarySuppressions();1146    setEntries([]);1147    setSelectedEntry(null);1148    setEditEntry(undefined);1149    setContentPhase("idle");1150    setView("lock");1151  }11521153  function handleHeaderLock() {1154    // Lock the UI immediately — do not wait for the service worker. If the SW1155    // is dead or slow, the 5s sendMessage timeout would create a dead-click1156    // window. The SW will lock on its next wake regardless.1157    handleLock();1158    void sendMessage({ type: "LOCK" });1159  }11601161  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1162  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1163  // the trigger's own reply.1164  async function handleHeaderSync(): Promise<void> {1165    if (syncBusy()) return;1166    setSyncBusy(true);1167    setSyncFlash(null);1168    try {1169      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1170      let state: SyncOutcomeSummary = { status: "syncing" };1171      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1172        await new Promise((r) => setTimeout(r, 250));1173        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1174          ok: boolean;1175          data?: SyncOutcomeSummary;1176        };1177        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1178      }1179      setSyncSummary(state);1180      setSyncFlash(state.status === "error" ? "error" : "ok");1181      await loadSyncAlerts();1182      await loadEntries();1183      await loadSyncIndicator();1184    } catch {1185      setSyncSummary({ status: "error", outcome: "run_failed" });1186      setSyncFlash("error");1187    } finally {1188      setSyncBusy(false);1189      setTimeout(() => setSyncFlash(null), 2_000);1190    }1191  }11921193  function navigate(dir: number) {1194    const navigable = nonNoteEntries();1195    if (navigable.length === 0) return;1196    const currentIndex = selectedIndex();1197    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1198    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1199    setSelectedEntry(navigable[nextIndex]);1200    setContentPhase("enter");1201    queueContentIdle();1202  }12031204  /**1205   * The Entry view's selection invariant: never select a note. Notes are a1206   * separate surface (handleSelectEntry opens the notes view), so any code path1207   * that picks a default — vault open, post-delete, refresh — must skip them1208   * and return null if the only entries are notes.1209   */1210  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1211    return list.find((e) => e.type !== "note") ?? null;1212  }12131214  function openList() {1215    setView("list");1216  }12171218  function openHealth() {1219    setEditEntry(undefined);1220    setView("health");1221  }12221223  function handleOpenFileImport() {1224    setRestoreView("file");1225  }12261227  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12281229  function handleFixEntry(entry: VaultEntry) {1230    setSelectedEntry(entry);1231    // Passkey-only entries have no editable surface — drop into view mode1232    // instead of opening the Add editor.1233    if (isPasskeyOnly(entry)) {1234      setView("entry");1235      return;1236    }1237    setEditBackView(view()); // preserve caller view so back returns here1238    setEditEntry(entry);1239    setView("add");1240  }12411242  const isLockedView = () => view() === "lock" || view() === "adopting";12431244  async function handleAdoptionDone() {1245    await storageSet("peach_onboarded", "true").catch(() => {});1246    setOnboarded(true);1247    setHasVault(true);1248    await handleUnlock();1249    void sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "foreground" } });1250  }12511252  /**1253   * Join an existing vault from a brand-new install.1254   *1255   * This used to require the receiver to LISTEN for the other device (a1256   * Capacitor pairing server), which a browser extension structurally cannot1257   * do — so on every real browser build it threw before doing anything. Over a1258   * pairing code the receiver is the DIALLER instead, which is the only shape1259   * that works here: dial the code, confirm the SAS, then ask for the vault.1260   *1261   * The vault does not exist yet at dial time, so nothing in this path may1262   * touch the vault before `createVaultFromRootKey` runs.1263   */1264  async function startVaultAdoption(args: {1265    password: string;1266    connection: { invitation: string };1267    confirmSAS(sas: string): Promise<boolean>;1268    createVault(rootKeyHex: string): Promise<{ vaultId: string }>;1269  }) {1270    const [{ dialRelayPairingChannel, openRelayPairingSocket }, { requestAdoption }] =1271      await Promise.all([1272        import("../shared/pairing-dial"),1273        import("../shared/vault-adopt"),1274      ]);12751276    const dial = await dialRelayPairingChannel(args.connection.invitation, {1277      openSocket: openRelayPairingSocket,1278    });1279    if (!dial.ok) throw new Error(dial.error);1280    const { channel, sas, socket, relayUrl, rendezvousSecretHex } = dial.dialled;12811282    try {1283      const source = await requestAdoption(channel, {1284        deviceName: defaultAdoptionDeviceName(),1285        generateDeviceId: () => crypto.randomUUID(),1286        // requestAdoption writes ADOPT_CONFIRM and refuses to read a root-key1287        // grant until this local SAS decision is true.1288        confirmSas: () => args.confirmSAS(sas),1289        pairState: { rendezvousSecretHex, relayUrl },1290        createVaultFromRootKey: args.createVault,1291        deriveLocalIdentity: async () => {1292          const res = await sendMessage({ type: "GET_LOCAL_IDENTITY" });1293          const r = res as { ok: boolean; data?: unknown; error?: string };1294          if (!r.ok || !r.data) throw new Error(r.error ?? "identity_unavailable");1295          return r.data as Awaited<ReturnType<Parameters<typeof requestAdoption>[1]["deriveLocalIdentity"]>>;1296        },1297        upsertPairedDevice: async (paired) => {1298          const res = await sendMessage({ type: "COMPLETE_PAIRING", payload: { paired } });1299          const r = res as { ok: boolean; error?: string };1300          if (!r.ok) throw new Error(r.error ?? "complete_pairing_failed");1301        },1302        applyLicense: async (license) => {1303          const res = (await sendMessage({1304            type: "ACTIVATE_LICENSE",1305            payload: { key: license },1306          })) as { ok: boolean; data?: { valid?: boolean; plan?: string } };1307          if (res.ok && res.data?.valid && res.data?.plan === "pro") await refreshProStatus();1308        },1309        onError(error) {1310          throw new Error(1311            error === "ADOPT_SAS_REJECTED" ? "sas_rejected" : error,1312          );1313        },1314      });1315      if (!source) throw new Error("adoption_rejected");1316      if (relayUrl) {1317        // Adopt the source's relay so this device dials the same rendezvous.1318        const setting = (await sendMessage({1319          type: "SET_SYNC_SETTINGS",1320          payload: { relayUrl },1321        })) as { ok: boolean; error?: string };1322        if (!setting.ok) throw new Error(setting.error ?? "relay_settings_failed");1323      }1324    } finally {1325      socket.close();1326    }1327  }13281329  async function handleApprovePendingPasskey() {1330    const pending = pendingPasskey();1331    if (!pending) return;1332    if (pending.browser === "firefox" && pending.type === "create") {1333      // Firefox path: popup itself runs navigator.credentials.create. The1334      // background never approved/rejected anything — it just stashed1335      // intent. After the popup-driven flow resolves (success or cancel),1336      // clear the pending key so the popup doesn't re-show this on next open.1337      const { createFirefoxPasskey } = await import("./firefox-passkey");1338      const result = await createFirefoxPasskey(pending);1339      if (!result.ok) {1340        console.warn("Peach Firefox passkey create failed:", result.error);1341      }1342      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1343      setPendingPasskey(null);1344      void loadEntries();1345      window.close();1346      return;1347    }1348    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1349    window.close();1350  }13511352  async function handleDenyPendingPasskey() {1353    const pending = pendingPasskey();1354    if (!pending) return;1355    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1356    window.close();1357  }13581359  function queueContentIdle(after?: () => void) {1360    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1361    contentPhaseTimer = window.setTimeout(() => {1362      setContentPhase("idle");1363      after?.();1364    }, ENTRY_TRANSITION_SETTLE_MS);1365  }13661367  return (1368    <div class="popup-root peach-theme">1369      <Show when={bootState() === "ready"}>1370        <Show1371          when={!pendingPasskey()}1372          fallback={1373            <PasskeyApprovalView1374              type={pendingPasskey()!.type}1375              rpName={pendingPasskey()!.rpName}1376              rpId={pendingPasskey()!.rpId}1377              userName={pendingPasskey()!.userName}1378              userDisplayName={pendingPasskey()!.userDisplayName}1379              onApprove={handleApprovePendingPasskey}1380              onDeny={handleDenyPendingPasskey}1381            />1382          }1383        >1384          <Show1385            when={!isLockedView()}1386            fallback={1387              <Show1388                when={view() !== "adopting"}1389                fallback={1390                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1391                    <AdoptVaultView1392                      onCancel={() => {1393                        setOnboarded(false);1394                        setView("lock");1395                      }}1396                      onDone={handleAdoptionDone}1397                      startAdoption={startVaultAdoption}1398                    />1399                  </Suspense>1400                }1401              >1402                <Show1403                  when={onboarded() || hasVault()}1404                  fallback={1405                    <Onboarding1406                      onComplete={() => {1407                        setStartOnboardingRestore(false);1408                        setOnboarded(true);1409                      }}1410                      onRestore={() => {1411                        setStartOnboardingRestore(true);1412                        setOnboarded(true);1413                      }}1414                      onAdopt={() => {1415                        setStartOnboardingRestore(false);1416                        setOnboarded(true);1417                        setView("adopting");1418                      }}1419                    />1420                  }1421                >1422                  <LockView1423                    hasVault={hasVault()}1424                    ready={bootState() === "ready"}1425                    isPro={proStatus()}1426                    forceRecoveryWords={forceRecoveryWords()}1427                    initialRestore={startOnboardingRestore()}1428                    onUnlock={() => {1429                      // RecoveryWordDisplay clears the storage flag before1430                      // calling onDone, so handleUnlock will see no pending1431                      // confirmation and proceed through the normal path.1432                      if (forceRecoveryWords()) setForceRecoveryWords(false);1433                      return handleUnlock();1434                    }}1435                    onBackToOnboarding={1436                      !hasVault()1437                        ? () => {1438                            setStartOnboardingRestore(false);1439                            setOnboarded(false);1440                          }1441                        : undefined1442                    }1443                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1444                  />1445                </Show>1446              </Show>1447            }1448          >1449            <Show1450              when={view() !== "pro-celebration"}1451              fallback={<ProCelebration />}1452            >1453            <section1454              id="hd-shell"1455              class="peach-shell peach-theme"1456              data-surface="extension"1457            >1458            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1459              <PeachWordmark unlocked />1460              <div class="peach-chrome-actions">1461                <button1462                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1463                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1464                  aria-label="Notes"1465                  title="Notes"1466                >1467                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1468                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1469                    <line x1="4" y1="5" x2="10" y2="5" />1470                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1471                    <line x1="4" y1="10" x2="7" y2="10" />1472                  </svg>1473                </button>1474                <button1475                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1476                    classList={{1477                      "is-syncing": syncBusy(),1478                      "is-ok": syncFlash() === "ok",1479                      "is-error": syncFlash() === "error",1480                    }}1481                    onClick={() => void handleHeaderSync()}1482                    disabled={syncBusy()}1483                    aria-label={`Sync now. ${syncLabel()}`}1484                    title={syncLabel()}1485                  >1486                    <svg class="peach-sync-icon" width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1487                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1488                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1489                      <path d="M2.6 1v2.4h2.4" />1490                      <path d="M11.4 13v-2.4H9" />1491                    </svg>1492                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1493                  </button>1494                <button1495                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1496                  onClick={() => setView("settings")}1497                  aria-label="Settings"1498                >1499                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1500                    <path1501                      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"1502                      stroke="currentColor"1503                      stroke-width="0.9"1504                    />1505                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1506                  </svg>1507                </button>1508                <button1509                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1510                  onClick={handleAdd}1511                  aria-label="New entry"1512                >1513                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1514                    <path d="M5.5 1v9M1 5.5h9" />1515                  </svg>1516                </button>1517                <button1518                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1519                  onClick={() => void handleHeaderLock()}1520                  aria-label="Lock vault"1521                >1522                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1523                    <path1524                      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"1525                      stroke="currentColor"1526                      stroke-width="1"1527                      stroke-linecap="round"1528                    />1529                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1530                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1531                  </svg>1532                </button>1533              </div>1534            </header>15351536            <Show when={pendingProNotice() !== null}>1537              <div class="peach-pro-notice-banner">1538                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1539                <button1540                  class="peach-pro-notice-link"1541                  onClick={() => {1542                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1543                    setSettingsInitialSection("license");1544                    setView("settings");1545                    setPendingProNotice(null);1546                  }}1547                >1548                  Learn more →1549                </button>1550                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1551              </div>1552            </Show>15531554            <div class="peach-shell-body">1555              <div class="peach-shell-veil"></div>1556              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1557                <EntryView1558                  entry={selectedEntry()}1559                  currentTabUrl={currentTabUrl()}1560                  entries={entries()}1561                  isPro={proStatus()}1562                  onDelete={handleDelete}1563                  onFieldSaved={() => void loadEntries()}1564                  onEscape={() => { setView("list"); }}1565                  onProGate={(feature) => {1566                    setUpgradeHighlight(feature);1567                    setSettingsInitialSection("license");1568                    setView("settings");1569                  }}1570                />1571              </div>15721573              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1574                <div class="peach-search-bar">1575                  <span class="peach-search-icon">1576                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1577                      <circle cx="5.5" cy="5.5" r="3.75" />1578                      <path d="M8.75 8.75L11.5 11.5" />1579                    </svg>1580                  </span>1581                  <input1582                    class="peach-search-input"1583                    placeholder="search vault..."1584                    autocomplete="off"1585                    aria-label="Search vault entries"1586                    onClick={openList}1587                    onFocus={openList}1588                    readOnly1589                  />1590                  <div class="peach-search-meta">1591                    <span class="peach-search-counter">1592                      {nonNoteEntries().length > 01593                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1594                        : "0 entries"}1595                    </span>1596                    <span class="peach-divider"></span>1597                    <button1598                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1599                      onClick={() => navigate(-1)}1600                      aria-label="Previous entry"1601                      disabled={nonNoteEntries().length === 0}1602                    >1603                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1604                        <path d="M5 1L1 5.5L5 10" />1605                      </svg>1606                    </button>1607                    <button1608                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1609                      onClick={() => navigate(1)}1610                      aria-label="Next entry"1611                      disabled={nonNoteEntries().length === 0}1612                    >1613                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1614                        <path d="M1 1L5 5.5L1 10" />1615                      </svg>1616                    </button>1617                  </div>1618                </div>1619              </section>1620            </div>16211622            {/* Desktop: shown on demand via Show. Native sheet is rendered1623                via Portal below at the document root so its position:fixed1624                isn't trapped by .peach-shell's transform-based animations. */}1625            {/* Rare device-trust alerts; normal sync changes are silent. */}1626            <Show when={syncAlerts().length > 0}>1627              <div class="peach-sync-alerts">1628                <For each={syncAlerts()}>1629                  {(alert, i) => (1630                    <div class="peach-sync-alert">1631                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1632                      <button1633                        class="peach-sync-alert-dismiss"1634                        type="button"1635                        aria-label="Dismiss"1636                        onClick={() => dismissSyncAlert(i())}1637                      >×</button>1638                    </div>1639                  )}1640                </For>1641              </div>1642            </Show>16431644            <Show when={!isNativePlatform() && view() === "list"}>1645              <VaultView1646                entries={entries()}1647                selectedEntryId={selectedEntry()?.id}1648                currentTabDomain={currentTabDomain()}1649                sortOrder={sortOrder()}1650                searchSeed={listSearchSeed()}1651                searchSeedNonce={listSearchSeedNonce()}1652                onSelectEntry={handleSelectEntry}1653                onSortOrderChange={setSortOrder}1654                onAdd={handleAdd}1655                onClose={() => setView("entry")}1656                onOpenTrash={() => setView("trash")}1657                onDeleteMany={handleDeleteMany}1658              />1659            </Show>1660            <Show when={isNativePlatform() && hasVault()}>1661              <Portal>1662                <div1663                  class="peach-vault-sheet"1664                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1665                  style={(() => {1666                    const live = sheetTranslate();1667                    if (live === null) return undefined;1668                    return { transform: `translateY(${live}px)` };1669                  })()}1670                >1671                  <VaultView1672                    entries={entries()}1673                    selectedEntryId={selectedEntry()?.id}1674                    currentTabDomain={currentTabDomain()}1675                    sortOrder={sortOrder()}1676                    searchSeed={listSearchSeed()}1677                    searchSeedNonce={listSearchSeedNonce()}1678                    isNative={true}1679                    onSelectEntry={handleSelectEntry}1680                    onSortOrderChange={setSortOrder}1681                    onAdd={handleAdd}1682                    onClose={() => setView("entry")}1683                    onOpenTrash={() => setView("trash")}1684                    onDeleteMany={handleDeleteMany}1685                  />1686                </div>1687              </Portal>1688            </Show>1689            <Show when={view() === "settings" || settingsExiting()}>1690              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1691                <SettingsView1692                  entriesCount={entries().length}1693                  breachMonitoring={breachMonitoring()}1694                  lockOnClose={lockOnClose()}1695                  autoLockMinutes={autoLockMinutes()}1696                  trashRetentionDays={trashRetentionDays()}1697                  theme={theme()}1698                  accentColor={accentColor()}1699                  textSize={textSize()}1700                  reduceMotion={reduceMotion()}1701                  isPro={proStatus()}1702                  initialSection={settingsInitialSection()}1703                  upgradeHighlight={upgradeHighlight()}1704                  isExiting={settingsExiting()}1705                  onBreachMonitoringChange={applyBreachMonitoring}1706                  onLockOnCloseChange={applyLockOnClose}1707                  onAutoLockMinutesChange={applyAutoLockMinutes}1708                  onTrashRetentionChange={applyTrashRetention}1709                  onThemeChange={applyTheme}1710                  onAccentChange={applyAccentColor}1711                  onTextSizeChange={applyTextSize}1712                  onReduceMotionChange={applyReduceMotion}1713                  shortcuts={shortcutBindings()}1714                  onShortcutsChange={applyShortcuts}1715                  onLicenseChange={async () => {1716                    // After activation/deactivation: refresh Pro status,1717                    // re-load entries (defensive — signal state can drift if1718                    // the SW briefly restarts during the verify+save round-trip),1719                    // and replay the Pro celebration if this is the first time1720                    // a valid Pro license is seen on this device.1721                    await refreshProStatus();1722                    void loadEntries();1723                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1724                    if ((should as { ok: boolean; data?: boolean }).data === true) {1725                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1726                      setView("pro-celebration");1727                      window.setTimeout(() => setView("settings"), 2500);1728                    }1729                  }}1730                  onBack={() => {1731                    setSettingsExiting(true);1732                    window.setTimeout(() => {1733                      setSettingsExiting(false);1734                      setSettingsInitialSection(null);1735                      setUpgradeHighlight(null);1736                      handleBack();1737                    }, 200);1738                  }}1739                  onImport={() => setView("import")}1740                  onExport={() => setView("export")}1741                  onBreachCheckDone={loadEntries}1742                  onOpenHealth={openHealth}1743                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1744                  onOpenFileImport={handleOpenFileImport}1745                  onOpenPanic={() => setView("panic")}1746                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1747                  onOpenCodexRestore={() => setView("codex-restore")}1748                  onCardChange={setSettingsActiveCard}1749                  onProGate={(feature) => {1750                    setUpgradeHighlight(feature);1751                    setSettingsInitialSection("license");1752                  }}1753                />1754              </Suspense>1755            </Show>1756            <Show when={view() === "codex-generate"}>1757              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1758                <CodexGenerateView1759                  isPro={proStatus()}1760                  onBack={() => setView("settings")}1761                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1762                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1763                  onVaultLocked={() => handleLock()}1764                />1765              </Suspense>1766            </Show>1767            <Show when={view() === "codex-restore"}>1768              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1769                <CodexRestoreView1770                  onBack={() => setView("lock")}1771                  onRestoreSuccess={async () => {1772                    // After restore the vault is unlocked; refresh entries1773                    // and route to the main vault list. handleUnlock is the1774                    // canonical post-unlock setup path.1775                    await handleUnlock();1776                  }}1777                />1778              </Suspense>1779            </Show>1780            <Show when={view() === "pair-device"}>1781              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1782                <PairDeviceView1783                  isPro={proStatus()}1784                  onProChanged={() => { void refreshProStatus(); }}1785                  onBack={() => setView("settings")}1786                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1787                />1788              </Suspense>1789            </Show>1790            <Show when={view() === "add"}>1791              <AddView1792                entry={editEntry()}1793                entries={entries()}1794                onBack={handleBack}1795                onSave={handleSave}1796              />1797            </Show>1798            <Show when={view() === "import"}>1799              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1800                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1801              </Suspense>1802            </Show>1803            <Show when={view() === "export"}>1804              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1805                <ExportView onBack={handleExportBack} />1806              </Suspense>1807            </Show>1808            <Show when={view() === "panic"}>1809              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1810                <PanicView1811                  onCancel={() => setView("settings")}1812                  onOpenExport={() => {1813                    setReturnToPanic(true);1814                    setView("export");1815                  }}1816                  onDestroyed={async () => {1817                    clearCanarySuppressions();1818                    setEntries([]);1819                    setSelectedEntry(null);1820                    setEditEntry(undefined);1821                    setHasVault(false);1822                    setOnboarded(false);1823                    setProStatus(false);1824                    setPendingPasskey(null);1825                    setUpgradeHighlight(null);1826                    setSettingsInitialSection(null);1827                    setPendingProNotice(null);1828                    setPendingCelebration(false);1829                    setReturnToPanic(false);1830                    setContentPhase("idle");1831                    setView("lock");1832                  }}1833                />1834              </Suspense>1835            </Show>1836            {/* Health stays mounted while editing an entry from it so1837                computeReused() doesn't rerun on every cancel/back. */}1838            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1839              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1840                <HealthView1841                  entries={entries()}1842                  isPro={proStatus()}1843                  onFixEntry={handleFixEntry}1844                  onBack={() => setView("settings")}1845                  onRefresh={loadEntries}1846                  hidden={view() !== "health"}1847                />1848              </Suspense>1849            </Show>1850            <Show when={view() === "trash"}>1851              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1852                <TrashView1853                  onBack={() => setView("list")}1854                  onRestored={() => void loadEntries()}1855                />1856              </Suspense>1857            </Show>1858            <Show when={showNotes()}>1859              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1860                <NotesMode1861                  notes={entries().filter((e) => e.type === "note")}1862                  initialNoteId={openNoteId()}1863                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1864                  onNoteListChanged={() => void loadEntries()}1865                />1866              </div>1867            </Show>1868            <Show when={restoreView() === "file"}>1869              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1870                <ImportView1871                  mode="onboarding"1872                  replacesExistingVault={true}1873                  onBack={() => setRestoreView(null)}1874                  onImport={async () => {1875                    setRestoreView(null);1876                    await handleUnlock();1877                  }}1878                />1879              </Suspense>1880            </Show>1881            </section>1882            </Show>1883          </Show>1884        </Show>1885      </Show>1886      <Show when={showShortcutsHelp()}>1887        <ShortcutsHelpOverlay1888          bindings={shortcutBindings()}1889          onClose={() => setShowShortcutsHelp(false)}1890        />1891      </Show>1892    </div>1893  );1894}18951896function ShortcutsHelpOverlay(props: {1897  bindings: Record<ShortcutAction, Keybinding>;1898  onClose: () => void;1899}) {1900  return (1901    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1902      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1903        <div class="peach-shortcuts-help-head">1904          <h3>Keyboard shortcuts</h3>1905          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1906        </div>1907        <div class="peach-shortcuts-help-body">1908          <p class="peach-settings-sub-label">ENTRY VIEW</p>1909          <ul>1910            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1911              <li>1912                <span>{d.label}</span>1913                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1914              </li>1915            ))}1916          </ul>1917          <p class="peach-settings-sub-label">ANYWHERE</p>1918          <ul>1919            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1920              <li>1921                <span>{d.label}</span>1922                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1923              </li>1924            ))}1925          </ul>1926        </div>1927      </div>1928    </div>1929  );1930}