App.tsx

80.6 KB · raw

1import { createEffect, createMemo, createSignal, For, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { storageGet, storageRemove, storageSet } from "../shared/storage";3import { sendMessage } from "../shared/bridge";4import { ACCENT_COLORS } from "../shared/types";5import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";6import { isPasskeyOnly } from "../shared/types";7import {8  hasCompletedInitialSync,9  INITIAL_SYNC_PENDING_DEVICE_KEY,10  type InitialSyncDevice,11} from "../shared/initial-sync";12import { LockView, RESTORE_SOURCE_STORAGE_KEY, type RestoreSource } from "./views/Lock";13import {14  ONBOARDING_CARD_STORAGE_KEY,15  ONBOARDING_LAST_CARD,16  Onboarding,17} from "./views/Onboarding";1819const ONBOARDING_EXIT_STORAGE_KEY = "peach_onboarding_exit";20import { NotesMode } from "./views/NotesMode";21import { ProCelebration } from "./views/ProCelebration";22import { InitialSyncView } from "./views/InitialSyncView";23import { VaultView, type SortOrder } from "./views/Vault";24import { EntryView } from "./views/Entry";25import { AddView } from "./views/Add";26import { PeachWordmark } from "./components/PeachMark";27import { PasskeyApprovalView } from "./views/PasskeyApproval";28import { extractDomain } from "../shared/domain";29import {30  syncIndicator,31  syncIndicatorLabel,32  type SyncOutcomeSummary,33} from "../shared/sync-outcome";34import { popupCopy } from "./copy";35import {36  DEFAULT_BINDINGS,37  formatKeybinding,38  getActiveBindings,39  matchKeybinding,40  SHORTCUT_DESCRIPTORS,41  type Keybinding,42  type ShortcutAction,43} from "../shared/shortcuts";44import { generateTOTP } from "../crypto/totp";4546export { sendMessage } from "../shared/bridge";4748const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));49const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));50const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));51const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));52const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));53const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));54const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));55const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));56const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));57const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));5859type View =60  | "lock"61  | "pro-celebration"62  | "entry"63  | "list"64  | "add"65  | "settings"66  | "pair-device"67  | "import"68  | "export"69  | "health"70  | "trash"71  | "panic"72  | "adopting"73  | "initial-sync"74  | "codex-generate"75  | "codex-restore";76type BootState = "loading" | "ready";7778const INITIAL_SYNC_POLL_MS = 500;79const INITIAL_SYNC_SLOW_MS = 15_000;8081let shellRingAnimation: Animation | null = null;8283export function triggerRing() {84  const shell = document.getElementById("hd-shell");85  if (!shell) return;8687  shellRingAnimation?.cancel();88  shell.dataset.glowing = "true";89  const animation = shell.animate(90    [91      { offset: 0, boxShadow: "var(--copy-shadow)" },92      {93        offset: 0.3,94        boxShadow:95          "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)",96      },97      { offset: 1, boxShadow: "var(--copy-shadow)" },98    ],99    {100      duration: 720,101      easing: "cubic-bezier(0.4, 0, 0.2, 1)",102      fill: "none",103    }104  );105  shellRingAnimation = animation;106  const clearGlow = () => {107    if (shellRingAnimation !== animation) return;108    shellRingAnimation = null;109    delete shell.dataset.glowing;110  };111  animation.onfinish = clearGlow;112  animation.oncancel = clearGlow;113}114115export 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}123124const ENTRY_TRANSITION_SETTLE_MS = 135;125126export default function App() {127  const [bootState, setBootState] = createSignal<BootState>("loading");128  const [view, setView] = createSignal<View>("lock");129  const [contentPhase, setContentPhase] = createSignal<"enter" | "idle">("enter");130  const [hasVault, setHasVault] = createSignal(false);131  const [onboarded, setOnboarded] = createSignal(true);132  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);133  // The restore source picked before the popup closed (the OS file picker134  // kills it), so reopening resumes the same source form instead of the135  // picker. Read from RESTORE_SOURCE_STORAGE_KEY at boot.136  const [resumeRestoreSource, setResumeRestoreSource] = createSignal<RestoreSource | null>(null);137  // Onboarding remounts whenever it leaves (create/adopt/restore) and comes138  // back. Those flows all exit from the final card, so resume there — a fresh139  // install's first mount stays at 0.140  const [onboardingCardAtExit, setOnboardingCardAtExit] = createSignal(0);141  const [entries, setEntries] = createSignal<VaultEntry[]>([]);142  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);143  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);144145  // Rare device-trust alerts stay visible; routine entry sync is silent.146  interface SyncAlert {147    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";148    entryId: string;149    entryTitle: string;150    deviceName: string;151    timestamp: number;152  }153  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);154  // Per-group flip index: which alert within a type-group is currently shown.155  const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});156  async function loadSyncAlerts() {157    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {158      ok: boolean;159      data?: SyncAlert[];160    };161    if (r.ok && (r.data?.length ?? 0) > 0) {162      setSyncAlerts(r.data ?? []);163      // Acknowledge so a crash between read and render doesn't lose them —164      // they remain on screen until the user dismisses each.165      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });166    }167  }168  function dismissAlertGroup(type: string) {169    setSyncAlerts((arr) => arr.filter((a) => a.type !== type));170    setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });171  }172  function flipAlert(type: string, dir: 1 | -1) {173    const group = syncAlerts().filter((a) => a.type === type);174    if (group.length <= 1) return;175    setAlertFlipIdx((m) => {176      const cur = m[type] ?? 0;177      return { ...m, [type]: (cur + dir + group.length) % group.length };178    });179  }180  /** Grouped alert types in display order, each with its alerts. */181  const alertGroups = createMemo(() => {182    const map = new Map<string, SyncAlert[]>();183    for (const a of syncAlerts()) {184      const g = map.get(a.type);185      if (g) g.push(a); else map.set(a.type, [a]);186    }187    return [...map.entries()];188  });189  function syncAlertText(a: SyncAlert): string {190    if (a.type === "DEVICE_REVOKED") {191      return `${a.deviceName} revoked a paired device — review your devices in Settings`;192    }193    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;194  }195  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");196  const [theme, setTheme] = createSignal<"dark" | "light">("dark");197  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");198  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);199  const [lockOnClose, setLockOnClose] = createSignal(false);200  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);201  const [breachMonitoring, setBreachMonitoring] = createSignal(true);202  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);203  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);204  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);205  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);206  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);207  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");208  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");209  // Cached Pro status — synchronous for render paths. Background's210  // GET_LICENSE is async, but render-time reads of isPro() must not block.211  // Refreshed at boot, after activate/deactivate, and whenever the popup212  // re-opens onto a stored license that has changed via another window.213  const [proStatus, setProStatus] = createSignal(false);214  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);215  // When the sync card's pairing button opens the pairing view, deep-link216  // straight into that pairing path instead of the rest screen.217  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");218  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);219  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");220  const [listSearchSeed, setListSearchSeed] = createSignal("");221  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);222  const [pendingCelebration, setPendingCelebration] = createSignal(false);223  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);224  // A page asked to be remembered for an entry it did not match. Pages cannot225  // grow an entry's domain set themselves (PB-26-106), so the background queues226  // the request here and this banner is the confirmation gate.227  const [pendingRememberSite, setPendingRememberSite] = createSignal<{228    entryId: string;229    url: string;230    title: string;231  } | null>(null);232  // True while Panic Step 1 has bounced the user out to Export. When Export's233  // onBack fires we return to Panic instead of Settings so the user keeps the234  // destruction context they came from.235  const [returnToPanic, setReturnToPanic] = createSignal(false);236  // The view to return to when the add/edit view is dismissed. Normally "entry"237  // but "health" when the user arrives via the fix-entry path from Vault Health.238  const [editBackView, setEditBackView] = createSignal<View>("entry");239  const [settingsExiting, setSettingsExiting] = createSignal(false);240  const [showNotes, setShowNotes] = createSignal(false);241  // Topbar sync affordance. Always present: gating it on having a paired device242  // meant it never appeared for the person trying to set pairing up, which is243  // exactly when you reach for it.244  const [syncBusy, setSyncBusy] = createSignal(false);245  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);246  // The indicator light + its spoken-word equivalent. Colour alone is not the247  // signal; the title/aria-label always carries the same claim in English.248  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});249  const [pairedCount, setPairedCount] = createSignal(0);250  const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);251  const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);252  let initialSyncWaitGeneration = 0;253  const syncLight = () =>254    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());255  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());256  async function loadSyncIndicator() {257    const [stateRes, devicesRes] = await Promise.all([258      sendMessage({ type: "GET_SYNC_STATE" }),259      sendMessage({ type: "LIST_PAIRED_DEVICES" }),260    ]);261    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };262    if (s.ok && s.data) setSyncSummary(s.data);263    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };264    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);265  }266267  interface InitialSyncPairedDevice extends InitialSyncDevice {268    pairedAt?: number;269  }270271  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {272    const response = (await sendMessage({273      type: "LIST_PAIRED_DEVICES",274    })) as {275      ok: boolean;276      data?: { devices?: InitialSyncPairedDevice[] };277    };278    return response.ok ? response.data?.devices ?? [] : [];279  }280281  async function resolveInitialSyncDeviceId(): Promise<string | null> {282    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(283      () => null,284    );285    const devices = await listInitialSyncDevices().catch(() => []);286    if (stored && devices.some((device) => device.deviceId === stored)) {287      return stored;288    }289290    // Fresh adoption has exactly one direct source, but choosing the newest row291    // also repairs the marker if storage failed after the pair itself committed.292    const newest = [...devices].sort(293      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),294    )[0];295    if (!newest) return stored;296    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(297      () => undefined,298    );299    return newest.deviceId;300  }301302  async function finishInitialSync(generation: number): Promise<void> {303    if (generation !== initialSyncWaitGeneration) return;304    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);305    setInitialSyncDeviceId(null);306    setInitialSyncSlow(false);307    await refreshProStatus();308309    // A license transferred during pairing intentionally leaves the one-shot310    // celebration pending. Consume it only now: sync readiness → celebration311    // → populated vault, never celebration → temporarily empty vault.312    const celebration = (await sendMessage({313      type: "SHOULD_PLAY_CELEBRATION",314    })) as { ok: boolean; data?: boolean };315    const shouldCelebrate = celebration.ok && celebration.data === true;316    if (shouldCelebrate) {317      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });318    }319320    const opened = await openVault(undefined, shouldCelebrate);321    if (!opened || generation !== initialSyncWaitGeneration) return;322    if (shouldCelebrate) {323      setView("pro-celebration");324      window.setTimeout(() => {325        if (generation === initialSyncWaitGeneration) setView("entry");326      }, 2500);327    }328  }329330  async function beginInitialSyncWait(deviceId: string): Promise<void> {331    const generation = ++initialSyncWaitGeneration;332    setInitialSyncDeviceId(deviceId);333    setInitialSyncSlow(false);334    setView("initial-sync");335    const startedAt = Date.now();336337    // Best effort: the pairing write already wakes the mesh listener, while338    // this trigger covers the key-order case where this receiver is the dialer.339    void sendMessage({340      type: "TRIGGER_SYNC",341      payload: { reason: "foreground" },342    }).catch(() => undefined);343344    while (345      generation === initialSyncWaitGeneration &&346      view() === "initial-sync"347    ) {348      try {349        const devices = await listInitialSyncDevices();350        if (hasCompletedInitialSync(devices, deviceId)) {351          await finishInitialSync(generation);352          return;353        }354      } catch {355        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.356      }357      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {358        setInitialSyncSlow(true);359      }360      await new Promise((resolve) =>361        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),362      );363    }364  }365366  async function retryInitialSync(): Promise<void> {367    const deviceId =368      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());369    if (deviceId) {370      await beginInitialSyncWait(deviceId);371    } else {372      setInitialSyncSlow(true);373    }374  }375376  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);377  // Set on popup boot when peach_recovery_pending flag is found in session378  // storage — instructs LockView to skip the unlock UI and open the recovery379  // words confirmation surface instead. Cleared via handleUnlock once the380  // user has typed the 3 confirmation words.381  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);382383  let contentPhaseTimer: number | undefined;384  // Set when the popup was opened from the inline "Open Peach to unlock" button.385  // handleUnlock() closes the popup after unlock so the user returns to the page.386  let openedForInlineUnlock = false;387388  onCleanup(() => {389    initialSyncWaitGeneration += 1;390  });391392  function applyAccent(name: AccentColorName) {393    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;394    const hex = color.hex;395    document.documentElement.style.setProperty("--peach-accent", hex);396    // Ambient variables derived from the selected accent.397    document.documentElement.style.setProperty("--peach-glow", hex + "2A");398    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");399  }400401  createEffect(() => {402    applyAccent(accentColor());403  });404405  createEffect(() => {406    document.documentElement.classList.toggle("light", theme() === "light");407    document.body.classList.toggle("light", theme() === "light");408  });409410  createEffect(() => {411    document.documentElement.setAttribute("data-text-size", textSize());412  });413414  createEffect(() => {415    if (reduceMotion()) {416      document.documentElement.setAttribute("data-motion", "reduce");417    } else {418      document.documentElement.removeAttribute("data-motion");419    }420  });421422  // Notes are not a destination of the Entry view; selecting a note opens the423  // notes surface instead (handleSelectEntry). Anything that walks or counts424  // the Entry view's neighbours (counter, prev/next, index) must use this425  // filtered list, otherwise the user can arrow into a note and is stuck —426  // the Entry view can't render a note and the prev/next buttons stop moving.427  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));428429  const selectedIndex = createMemo(() => {430    const currentId = selectedEntry()?.id;431    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;432    return nonNoteEntries().findIndex((entry) => entry.id === currentId);433  });434435  async function applyAccentColor(name: AccentColorName) {436    applyAccent(name);437    setAccentColor(name);438    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });439  }440441  async function applyTheme(t: "dark" | "light") {442    setTheme(t);443    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });444  }445446  async function applyTextSize(size: "small" | "medium" | "large") {447    setTextSize(size);448    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });449  }450451  async function applyReduceMotion(enabled: boolean) {452    setReduceMotion(enabled);453    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });454  }455456  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload457  // small and lets future default updates land for actions the user hasn't458  // touched. Settings sends us the full active map; we filter and store.459  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {460    setShortcutBindings(active);461    const overrides: Record<string, Keybinding> = {};462    for (const action of Object.keys(active) as ShortcutAction[]) {463      const a = active[action];464      const d = DEFAULT_BINDINGS[action];465      const same = a.key === d.key466        && Boolean(a.ctrl)  === Boolean(d.ctrl)467        && Boolean(a.meta)  === Boolean(d.meta)468        && Boolean(a.shift) === Boolean(d.shift)469        && Boolean(a.alt)   === Boolean(d.alt);470      if (!same) overrides[action] = a;471    }472    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });473  }474475  async function applyLockOnClose(enabled: boolean) {476    setLockOnClose(enabled);477    await sendMessage({478      type: "UPDATE_SETTINGS",479      payload: { lockOnClose: enabled },480    });481  }482483  async function applyAutoLockMinutes(minutes: number) {484    setAutoLockMinutes(minutes);485    await sendMessage({486      type: "UPDATE_SETTINGS",487      payload: { autoLockMinutes: minutes },488    });489  }490491  async function applyBreachMonitoring(enabled: boolean) {492    setBreachMonitoring(enabled);493    await sendMessage({494      type: "UPDATE_SETTINGS",495      payload: { breachMonitoring: enabled },496    });497  }498499  // Which onboarding exit flow the user is in (create-vault / restore /500  // adopt). Persisted so closing the popup on one of those screens resumes501  // it directly instead of rewinding to the last carousel card.502  function markOnboardingExit(flow: "create" | "restore" | "adopt") {503    setOnboardingCardAtExit(ONBOARDING_LAST_CARD);504    void storageSet(ONBOARDING_EXIT_STORAGE_KEY, flow).catch(() => {});505    // Backing out of the flow remounts the carousel at this card; keep the506    // persisted card in sync so a later popup close resumes consistently.507    void storageSet(ONBOARDING_CARD_STORAGE_KEY, String(ONBOARDING_LAST_CARD)).catch(() => {});508  }509  function clearOnboardingExit() {510    void storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});511    void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});512    setResumeRestoreSource(null);513  }514515  onMount(async () => {516    // Resolve the active tab in parallel with the unlock/has-vault queries —517    // openVault()'s smart selection picks the entry matching currentTabDomain,518    // so it must be populated before openVault runs. Previously refreshCurrentTab519    // ran after openVault, leaving popups that booted already-unlocked falling520    // back to loadedEntries[0] instead of the domain match.521    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([522      sendMessage({ type: "IS_UNLOCKED" }),523      sendMessage({ type: "HAS_VAULT" }),524      refreshCurrentTab(),525      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),526    ]);527    const unlocked = Boolean(528      (unlockResponse as { ok: boolean; data?: boolean }).data529    );530    const vaultExists = Boolean(531      (vaultResponse as { ok: boolean; data?: boolean }).data532    );533    const shouldCelebrate = Boolean(534      (celebrationResponse as { ok: boolean; data?: boolean }).data535    );536    setHasVault(vaultExists);537    // Onboarding gate — show once on first install, never again. Existing538    // users (vaultExists) are auto-marked onboarded so they skip the flow539    // even on the very first popup open after this feature ships.540    try {541      const onboarded = await storageGet("peach_onboarded");542      const seen = onboarded === "true";543      if (vaultExists && !seen) {544        await storageSet("peach_onboarded", "true");545        await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});546        await storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});547        await storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});548        setOnboarded(true);549      } else {550        setOnboarded(seen);551        if (!seen) {552          // A popup close while the user is in an exit flow (create-vault /553          // restore / adopt) resumes that flow directly — landing back on the554          // carousel one screen earlier reads as losing progress.555          const exit = await storageGet(ONBOARDING_EXIT_STORAGE_KEY).catch(() => null);556          if (exit === "create" || exit === "restore" || exit === "adopt") {557            setOnboardingCardAtExit(ONBOARDING_LAST_CARD);558            setOnboarded(true);559            setStartOnboardingRestore(exit === "restore");560            if (exit === "restore") {561              // The OS file picker kills the action popup mid-restore, so the562              // surface resumes on the source the user had already picked.563              const source = await storageGet(RESTORE_SOURCE_STORAGE_KEY).catch(() => null);564              if (source === "symbols" || source === "codex" || source === "csv") {565                setResumeRestoreSource(source);566              }567            }568            if (exit === "adopt") setView("adopting");569          } else {570            // Otherwise resume mid-onboarding where the user left off instead571            // of rewinding to the opening card.572            const stored = Number(573              await storageGet(ONBOARDING_CARD_STORAGE_KEY).catch(() => null),574            );575            if (576              Number.isInteger(stored) &&577              stored > 0 &&578              stored <= ONBOARDING_LAST_CARD579            ) {580              setOnboardingCardAtExit(stored);581            }582          }583        }584      }585    } catch {586      // storage unavailable — default to onboarded so we never block boot587      setOnboarded(true);588    }589590    // Deep-link: ?restore=peachscript|csv — the detached-window half of the591    // file-picker flow. The action popup dismisses when the OS dialog steals592    // focus, so LockView.detachForFilePicker() reopens this URL in a593    // standalone window that owns the dialog. Routing runs before first594    // render so LockView mounts straight onto the right source form.595    try {596      const restoreRoute = new URLSearchParams(window.location.search).get("restore");597      if (restoreRoute === "peachscript" || restoreRoute === "csv") {598        setOnboarded(true);599        setStartOnboardingRestore(true);600        setResumeRestoreSource(restoreRoute === "peachscript" ? "symbols" : "csv");601      }602    } catch {603      // location.search unavailable — ignore.604    }605606    await Promise.all([restoreSettings(), refreshProStatus()]);607608    const pendingInitialSyncMarker =609      unlocked && vaultExists610        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)611        : null;612    const pendingInitialSyncDeviceId = pendingInitialSyncMarker613      ? await resolveInitialSyncDeviceId()614      : null;615616    // Mark played before any animation so a crash mid-sequence never replays617    // it. A newly adopted receiver deliberately defers this until its first618    // real sync finishes, preserving initial sync → celebration → vault.619    if (shouldCelebrate && !pendingInitialSyncDeviceId) {620      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });621    }622623    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome624    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.625    if (unlocked && vaultExists) {626      void sendMessage({627        type: "TRIGGER_SYNC",628        payload: { reason: "foreground" },629      });630      void loadSyncIndicator();631      // Rare device-trust alerts only; routine entry sync stays quiet.632      void loadSyncAlerts();633    }634635    // If the user created a vault but hasn't yet confirmed their recovery636    // words, route back to the recovery-words screen instead of opening the637    // entries view. The flag lives in chrome.storage.local so it survives638    // popup close while the background owns the session-scoped confirmation639    // exemption. Cleared when confirmation succeeds.640    let recoveryPending = false;641    try {642      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });643      recoveryPending = out.ok === true && out.data === true;644    } catch { /* best-effort */ }645646    // If this popup was opened from the inline "Open Peach to unlock" button,647    // the background set a session flag. Read and clear it so handleUnlock()648    // can close the popup after unlock and return the user to the page.649    if (chrome.storage.session) {650      try {651        const s = await chrome.storage.session.get("peach_inline_unlock");652        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {653          openedForInlineUnlock = true;654          await chrome.storage.session.remove("peach_inline_unlock");655        }656      } catch { /* best-effort */ }657    }658659    if (recoveryPending && unlocked) {660      // forceRecoveryWords overrides LockView's hasVault gate so the661      // recovery surface renders even though the vault now exists.662      setForceRecoveryWords(true);663      setView("lock");664    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {665      void beginInitialSyncWait(pendingInitialSyncDeviceId);666    } else if (unlocked && vaultExists) {667      await openVault(undefined, shouldCelebrate);668      if (shouldCelebrate) {669        setView("pro-celebration");670        window.setTimeout(() => setView("entry"), 2500);671      }672    } else if (shouldCelebrate) {673      setPendingCelebration(true);674    }675676    await refreshPendingPasskey();677678    // Track tab changes so smart sort stays current679    const handleTabActivated = () => { void refreshCurrentTab(); };680    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {681      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();682    };683    try {684      chrome.tabs.onActivated.addListener(handleTabActivated);685      chrome.tabs.onUpdated.addListener(handleTabUpdated);686      onCleanup(() => {687        chrome.tabs.onActivated.removeListener(handleTabActivated);688        chrome.tabs.onUpdated.removeListener(handleTabUpdated);689      });690    } catch {691      // tabs permission may not be available in all contexts692    }693694    setBootState("ready");695696    // Deep-link: ?codex=pdf opens a detached window straight into the697    // Codex restore flow with auto-picked PDF. The action popup can't host698    // a file dialog without dismissing itself, so this is the only way the699    // PDF import path survives. See CodexRestoreView.openPdfPicker().700    try {701      const route = new URLSearchParams(window.location.search).get("codex");702      if (route === "pdf" || route === "restore") {703        setView("codex-restore");704      }705    } catch {706      // location.search unavailable — ignore.707    }708709    // Check for pending session-storage notices from the background.710    if (chrome.storage.session) {711      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as712        Record<string, { feature?: string } | undefined>;713      if (session.pendingProGate?.feature) {714        await chrome.storage.session.remove("pendingProGate");715        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);716        setSettingsInitialSection("license");717        setView("settings");718      } else if (session.pendingProNotice?.feature) {719        await chrome.storage.session.remove("pendingProNotice");720        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });721      }722      const remembered = (await chrome.storage.session.get("pendingRememberSite")) as {723        pendingRememberSite?: { entryId?: unknown; url?: unknown };724      };725      const request = remembered.pendingRememberSite;726      if (727        typeof request?.entryId === "string" &&728        typeof request.url === "string"729      ) {730        const entry = await sendMessage({ type: "GET_ENTRIES" });731        const match = entry.ok732          ? (entry.data as Array<{ id: string; title?: string }> | undefined)?.find(733              (candidate) => candidate.id === request.entryId,734            )735          : undefined;736        if (match) {737          let host = request.url;738          try { host = new URL(request.url).hostname; } catch { /* keep raw */ }739          setPendingRememberSite({ entryId: request.entryId, url: request.url, title: match.title ?? host });740        } else {741          await chrome.storage.session.remove("pendingRememberSite");742        }743      }744    }745746    // Warm the lazy-module cache so the Suspense fallback never shows for747    // locally-bundled extension views. Without this, the first navigation to748    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which749    // covers the shell and absorbs clicks on the header.750    void Promise.all([751      import("./views/Settings").catch(() => {}),752      import("./views/Import").catch(() => {}),753      import("./views/Export").catch(() => {}),754      import("./views/Health").catch(() => {}),755      import("./views/TrashView").catch(() => {}),756    ]);757758    // Lock-on-close via a persistent port. sendMessage in pagehide is759    // unreliable — the popup context tears down before the message lands.760    // The SW's onConnect listener locks when this port disconnects.761    let popupPort: chrome.runtime.Port | null = null;762    try {763      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect764      // listener accepts the "popup-" prefix; the random suffix is defence in765      // depth against a port named exactly "popup" from anything but our popup.766      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });767    } catch { /* extension context invalidated — ignore */ }768    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });769770    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale771    // entries instead of waiting for the next GET_ENTRIES round-trip.772    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {773      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();774      if (msg?.type === "SYNC_STATE_CHANGED") {775        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);776      }777      if (msg?.type === "PRO_GATE_TRIGGERED") {778        setUpgradeHighlight(msg.payload?.feature ?? null);779        setSettingsInitialSection("license");780        setView("settings");781      }782    };783    chrome.runtime.onMessage.addListener(handleRuntimeMessage);784    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));785786    // Action handlers — keyed by ShortcutAction. The dispatcher below tests787    // each binding against the event and runs the matching handler. New788    // shortcuts only need an entry here; the binding is data, not code.789    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {790      copy_password: () => {791        const entry = selectedEntry();792        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });793      },794      copy_username: () => {795        const entry = selectedEntry();796        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });797      },798      copy_totp: () => {799        const entry = selectedEntry();800        if (!entry?.totp) return;801        try {802          const { code } = generateTOTP(803            entry.totp,804            entry.totpAlgorithm,805            entry.totpDigits,806            entry.totpPeriod,807          );808          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });809        } catch { /* invalid TOTP secret — silent */ }810      },811      new_entry: () => handleAdd(),812      edit_entry: () => {813        const entry = selectedEntry();814        // Passkey-only entries have nothing user-editable in the Add view; the815        // passkey credential itself is opaque. Skip the edit action for them.816        if (!entry || isPasskeyOnly(entry)) return;817        setEditEntry(entry);818        setView("add");819      },820      delete_entry: () => {821        if (selectedEntry()) void handleDelete();822      },823      lock_vault: () => { void handleHeaderLock(); },824      search: () => openList(),825      nav_prev: () => navigate(-1),826      nav_next: () => navigate(1),827      jump_vault: () => setView("entry"),828      jump_settings: () => setView("settings"),829      show_help: () => setShowShortcutsHelp(true),830    };831832    // Actions that are MEANINGFUL only on the entry-detail view. Outside833    // that scope the binding is dormant — pressing C while on Settings834    // does nothing rather than awkwardly copying from a now-stale entry.835    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([836      "copy_password", "copy_username", "copy_totp",837      "edit_entry", "delete_entry", "nav_prev", "nav_next",838    ]);839840    const handleGlobalKeydown = (e: KeyboardEvent) => {841      const v = view();842      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"843        || (e.target as HTMLElement)?.tagName === "TEXTAREA"844        || (e.target as HTMLElement)?.isContentEditable;845      const isPrintableSearchKey =846        e.key.length === 1 &&847        !e.ctrlKey &&848        !e.metaKey &&849        !e.altKey;850851      // No shortcuts while a full-screen surface owns the whole viewport:852      // the lock screen, the post-pairing readiness sequence, or the Pro853      // celebration. Without this the lock screen is at the mercy of whatever854      // single-key binding is active — e.g. typing "n" in a password that855      // slips out of focus triggers `new_entry` and escapes the lock screen.856      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;857858      // Help dialog: Escape closes it; eat the keypress so it doesn't859      // also navigate away from the underlying view.860      if (showShortcutsHelp()) {861        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }862        return;863      }864865      // ── Escape — fixed binding (not user-customizable) ───────866      if (e.key === "Escape") {867        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }868        if (v === "list") { setView("entry"); return; }869        if (v === "settings" || v === "add") { handleBack(); return; }870        if (v === "import" || v === "health") { setView("settings"); return; }871        if (v === "export") { handleExportBack(); return; }872        if (v === "pair-device") { setView("settings"); return; }873      }874875      // Bindings-driven dispatch. Single-key letter bindings without876      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is877      // inside an input, so users can type into search/forms normally.878      const bindings = shortcutBindings();879      for (const action of Object.keys(bindings) as ShortcutAction[]) {880        const binding = bindings[action];881        if (!matchKeybinding(e, binding)) continue;882        // Single-key letter bindings need the input-focus guard. Bindings883        // with any modifier are safe — Ctrl+L doesn't conflict with typing.884        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;885        if (!hasMod && binding.key.length === 1 && inInput) return;886        if (ENTRY_SCOPED.has(action) && v !== "entry") return;887        e.preventDefault();888        SHORTCUT_HANDLERS[action]?.();889        return;890      }891892      // Type-to-search: in entry view, any printable key not consumed by a893      // shortcut above primes the list search seed and opens the list.894      // Kept outside the bindings table because it's a behavior, not a895      // discrete action — every printable character can trigger it.896      if (v === "entry" && !inInput && isPrintableSearchKey) {897        e.preventDefault();898        primeListSearch(e.key);899        return;900      }901    };902    window.addEventListener("keydown", handleGlobalKeydown);903    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));904905    const handleStorageChanged = (906      changes: Record<string, chrome.storage.StorageChange>,907      areaName: string908    ) => {909      if (areaName !== "session") return;910      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {911        return;912      }913      void refreshPendingPasskey();914    };915    chrome.storage.onChanged.addListener(handleStorageChanged);916    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));917  });918919  async function refreshCurrentTab() {920    try {921      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });922      const url = tab?.url ?? tab?.pendingUrl ?? "";923      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");924      // Skip extension/internal URLs — adding chrome://, about:, or925      // chrome-extension:// to a vault entry is never what the user wants.926      const isWebUrl = /^https?:\/\//i.test(url);927      setCurrentTabUrl(isWebUrl ? url : "");928    } catch {929      setCurrentTabDomain("");930      setCurrentTabUrl("");931    }932  }933934  async function refreshPendingPasskey() {935    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });936    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);937  }938939  async function refreshProStatus() {940    const res = await sendMessage({ type: "GET_LICENSE" });941    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;942    setProStatus(Boolean(data?.valid && data?.plan === "pro"));943  }944945  async function restoreSettings() {946    const res = await sendMessage({ type: "GET_SETTINGS" });947    const s = (res as { ok: boolean; data?: any }).data ?? {};948    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {949      setAccentColor(s.accentColor as AccentColorName);950    }951    setTheme(s.theme === "light" ? "light" : "dark");952    if (s.textSize === "small" || s.textSize === "large") {953      setTextSize(s.textSize);954    } else {955      setTextSize("medium");956    }957    setReduceMotion(s.reduceMotion === true);958    setLockOnClose(s.lockOnClose === true);959    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);960    setBreachMonitoring(s.breachMonitoring !== false);961    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);962    setShortcutBindings(getActiveBindings(s.shortcuts));963  }964965  async function applyTrashRetention(days: number) {966    setTrashRetentionDays(days);967    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });968  }969970  function primeListSearch(seed: string) {971    setListSearchSeed(seed);972    setListSearchSeedNonce((value) => value + 1);973    openList();974  }975976  // Returns null when it detected a dead service worker and triggered handleLock().977  // Callers that need to abort (e.g. openVault) check for null rather than relying978  // on view() state, which may already be "lock" during normal startup flows.979  async function loadEntries(): Promise<VaultEntry[] | null> {980    const response = await sendMessage({ type: "GET_ENTRIES" });981    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };982983    // If the service worker was killed and restarted (MV3 workers sleep), the984    // vault will be locked again — or the worker may not respond at all.985    // In either case, send the user to the lock screen rather than silently986    // showing an empty vault (which looks like data loss).987    if (!res.ok) {988      if (989        res.error === "vault_locked" ||990        res.error === "SERVICE_WORKER_UNAVAILABLE" ||991        (typeof res.error === "string" && res.error.includes("locked"))992      ) {993        handleLock();994        return null; // signal emergency lock to callers995      }996      return [];997    }998999    const loadedEntries = res.data ?? [];1000    setEntries(loadedEntries);10011002    const currentId = selectedEntry()?.id;1003    if (currentId) {1004      setSelectedEntry(1005        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1006      );1007    }10081009    return loadedEntries;1010  }10111012  async function openVault(preferredEntryId?: string, skipViewSet = false) {1013    // Purge expired trash entries on each vault open1014    const retDays = trashRetentionDays();1015    if (retDays > 0) {1016      void sendMessage({1017        type: "PURGE_EXPIRED_TRASH",1018        payload: { retentionMs: retDays * 86_400_000 },1019      });1020    }10211022    const loadedEntries = await loadEntries();10231024    // null means loadEntries() triggered an emergency lock (service worker died).1025    // Don't override it by setting view back to "entry" with an empty vault.1026    if (loadedEntries === null) return false;10271028    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1029    let nextSelectedEntry: VaultEntry | null = null;1030    if (preferredEntryId) {1031      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1032    }1033    if (!nextSelectedEntry) {1034      const tabDomain = currentTabDomain();1035      if (tabDomain) {1036        nextSelectedEntry = loadedEntries.find((e) => {1037          if (e.type === "login") {1038            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1039            for (const extra of e.additionalUrls ?? []) {1040              if ((extractDomain(extra) ?? "") === tabDomain) return true;1041            }1042            return false;1043          }1044          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1045          return false;1046        }) ?? null;1047      }1048    }1049    nextSelectedEntry ??= pickNavigable(loadedEntries);10501051    setSelectedEntry(nextSelectedEntry);1052    setEditEntry(undefined);1053    setContentPhase("enter");1054    queueContentIdle();1055    if (!skipViewSet) setView("entry");1056    return true;1057  }10581059  async function handleUnlock() {1060    // If the user previously created a vault but hadn't yet confirmed their1061    // recovery words (and the browser was closed before they could), the1062    // the background-owned recovery-pending state is still set. Re-route1063    // back to the recovery surface so they finish the confirmation step1064    // before reaching the entries view — the words can be re-derived now1065    // that the vault is unlocked again.1066    let recoveryPending = false;1067    try {1068      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });1069      recoveryPending = out.ok === true && out.data === true;1070    } catch { /* best-effort */ }1071    if (recoveryPending) {1072      setForceRecoveryWords(true);1073      setView("lock");1074      triggerPipPulse();1075      await restoreSettings();1076      return;1077    }1078    setHasVault(true);1079    triggerPipPulse();1080    await restoreSettings();1081    const celebrating = pendingCelebration();1082    if (celebrating) {1083      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1084      setPendingCelebration(false);1085    }1086    await openVault(undefined, celebrating);1087    if (celebrating) {1088      setView("pro-celebration");1089      window.setTimeout(() => setView("entry"), 2500);1090    }1091    // Popup was opened from the inline "Open Peach to unlock" button — close it1092    // now so the user lands back on the page with the autofill selector ready.1093    if (openedForInlineUnlock) {1094      openedForInlineUnlock = false;1095      window.close();1096    }1097  }10981099  function handleSelectEntry(entry: VaultEntry) {1100    if (entry.type === "note") {1101      setOpenNoteId(entry.id);1102      setShowNotes(true);1103      return;1104    }1105    setSelectedEntry(entry);1106    setContentPhase("enter");1107    queueContentIdle();1108    setView("entry");1109  }11101111  function handleAdd() {1112    setEditEntry(undefined);1113    setView("add");1114  }11151116  async function handleDelete() {1117    const entry = selectedEntry();1118    if (!entry) return;1119    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1120    const loadedEntries = await loadEntries() ?? [];1121    setSelectedEntry(pickNavigable(loadedEntries));1122    setView("entry");1123  }11241125  async function handleDeleteMany(ids: string[]) {1126    for (const id of ids) {1127      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1128    }1129    const loadedEntries = await loadEntries() ?? [];1130    // If the currently selected entry was among the deleted, move to first1131    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1132    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1133  }11341135  async function handleSave(savedEntry?: VaultEntry) {1136    await openVault(savedEntry?.id);1137  }11381139  function handleBack() {1140    const dest = editBackView();1141    setEditBackView("entry");1142    setEditEntry(undefined);1143    setView(dest);1144  }11451146  function handleExportBack() {1147    if (returnToPanic()) {1148      setReturnToPanic(false);1149      setView("panic");1150      return;1151    }1152    setView("settings");1153  }11541155  function handleLock() {1156    setEntries([]);1157    setSelectedEntry(null);1158    setEditEntry(undefined);1159    setContentPhase("idle");1160    setView("lock");1161  }11621163  function handleHeaderLock() {1164    // Lock the UI immediately — do not wait for the service worker. If the SW1165    // is dead or slow, the 5s sendMessage timeout would create a dead-click1166    // window. The SW will lock on its next wake regardless.1167    handleLock();1168    void sendMessage({ type: "LOCK" });1169  }11701171  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1172  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1173  // the trigger's own reply.1174  async function handleHeaderSync(): Promise<void> {1175    if (syncBusy()) return;1176    setSyncBusy(true);1177    setSyncFlash(null);1178    try {1179      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1180      let state: SyncOutcomeSummary = { status: "syncing" };1181      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1182        await new Promise((r) => setTimeout(r, 250));1183        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1184          ok: boolean;1185          data?: SyncOutcomeSummary;1186        };1187        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1188      }1189      setSyncSummary(state);1190      setSyncFlash(state.status === "error" ? "error" : "ok");1191      await loadSyncAlerts();1192      await loadEntries();1193      await loadSyncIndicator();1194    } catch {1195      setSyncSummary({ status: "error", outcome: "run_failed" });1196      setSyncFlash("error");1197    } finally {1198      setSyncBusy(false);1199      setTimeout(() => setSyncFlash(null), 2_000);1200    }1201  }12021203  function navigate(dir: number) {1204    const navigable = nonNoteEntries();1205    if (navigable.length === 0) return;1206    const currentIndex = selectedIndex();1207    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1208    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1209    setSelectedEntry(navigable[nextIndex]);1210    setContentPhase("enter");1211    queueContentIdle();1212  }12131214  /**1215   * The Entry view's selection invariant: never select a note. Notes are a1216   * separate surface (handleSelectEntry opens the notes view), so any code path1217   * that picks a default — vault open, post-delete, refresh — must skip them1218   * and return null if the only entries are notes.1219   */1220  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1221    return list.find((e) => e.type !== "note") ?? null;1222  }12231224  function openList() {1225    setView("list");1226  }12271228  function openHealth() {1229    setEditEntry(undefined);1230    setView("health");1231  }12321233  function handleOpenFileImport() {1234    setRestoreView("file");1235  }12361237  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12381239  function handleFixEntry(entry: VaultEntry) {1240    setSelectedEntry(entry);1241    // Passkey-only entries have no editable surface — drop into view mode1242    // instead of opening the Add editor.1243    if (isPasskeyOnly(entry)) {1244      setView("entry");1245      return;1246    }1247    setEditBackView(view()); // preserve caller view so back returns here1248    setEditEntry(entry);1249    setView("add");1250  }12511252  const isLockedView = () => view() === "lock" || view() === "adopting";12531254  async function handleAdoptionDone() {1255    await storageSet("peach_onboarded", "true").catch(() => {});1256    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1257    clearOnboardingExit();1258    setOnboarded(true);1259    setHasVault(true);1260    setView("initial-sync");1261    // The background applies a Pro license and persists the source-device1262    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1263    // celebration pending until that exact peer records a completed sync.1264    await refreshProStatus();1265    const deviceId = await resolveInitialSyncDeviceId();1266    if (deviceId) {1267      void beginInitialSyncWait(deviceId);1268    } else {1269      // Pairing completion without a durable peer row should be impossible.1270      // Stay on the honest waiting surface and expose retry instead of falling1271      // through to an empty vault.1272      setInitialSyncSlow(true);1273    }1274  }12751276  async function handleApprovePendingPasskey() {1277    const pending = pendingPasskey();1278    if (!pending) return;1279    if (pending.browser === "firefox" && pending.type === "create") {1280      // Firefox path: popup itself runs navigator.credentials.create. The1281      // background never approved/rejected anything — it just stashed1282      // intent. After the popup-driven flow resolves (success or cancel),1283      // clear the pending key so the popup doesn't re-show this on next open.1284      const { createFirefoxPasskey } = await import("./firefox-passkey");1285      const result = await createFirefoxPasskey(pending);1286      if (!result.ok) {1287        console.warn("Peach Firefox passkey create failed:", result.error);1288      }1289      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1290      setPendingPasskey(null);1291      void loadEntries();1292      window.close();1293      return;1294    }1295    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1296    window.close();1297  }12981299  async function handleDenyPendingPasskey() {1300    const pending = pendingPasskey();1301    if (!pending) return;1302    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1303    window.close();1304  }13051306  function queueContentIdle(after?: () => void) {1307    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1308    contentPhaseTimer = window.setTimeout(() => {1309      setContentPhase("idle");1310      after?.();1311    }, ENTRY_TRANSITION_SETTLE_MS);1312  }13131314  return (1315    <div class="popup-root peach-theme">1316      <Show when={bootState() === "ready"}>1317        <Show1318          when={!pendingPasskey()}1319          fallback={1320            <PasskeyApprovalView1321              type={pendingPasskey()!.type}1322              rpName={pendingPasskey()!.rpName}1323              rpId={pendingPasskey()!.rpId}1324              userName={pendingPasskey()!.userName}1325              userDisplayName={pendingPasskey()!.userDisplayName}1326              onApprove={handleApprovePendingPasskey}1327              onDeny={handleDenyPendingPasskey}1328            />1329          }1330        >1331          <Show1332            when={!isLockedView()}1333            fallback={1334              <Show1335                when={view() !== "adopting"}1336                fallback={1337                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1338                    <AdoptVaultView1339                      onCancel={() => {1340                        clearOnboardingExit();1341                        setOnboarded(false);1342                        setView("lock");1343                      }}1344                      onDone={handleAdoptionDone}1345                    />1346                  </Suspense>1347                }1348              >1349                <Show1350                  when={onboarded() || hasVault()}1351                  fallback={1352                    <Onboarding1353                      initialCard={onboardingCardAtExit()}1354                      onComplete={() => {1355                        markOnboardingExit("create");1356                        setStartOnboardingRestore(false);1357                        setOnboarded(true);1358                      }}1359                      onRestore={() => {1360                        markOnboardingExit("restore");1361                        setStartOnboardingRestore(true);1362                        setOnboarded(true);1363                      }}1364                      onAdopt={() => {1365                        markOnboardingExit("adopt");1366                        setStartOnboardingRestore(false);1367                        setOnboarded(true);1368                        setView("adopting");1369                      }}1370                    />1371                  }1372                >1373                  <LockView1374                    hasVault={hasVault()}1375                    ready={bootState() === "ready"}1376                    isPro={proStatus()}1377                    forceRecoveryWords={forceRecoveryWords()}1378                    initialRestore={startOnboardingRestore()}1379                    initialRestoreSource={resumeRestoreSource() ?? undefined}1380                    onUnlock={() => {1381                      // RecoveryWordDisplay clears the storage flag before1382                      // calling onDone, so handleUnlock will see no pending1383                      // confirmation and proceed through the normal path.1384                      if (forceRecoveryWords()) setForceRecoveryWords(false);1385                      // The create/restore flow is done — a lock later in this1386                      // window must show the unlock screen, not re-enter the1387                      // onboarding restore surface.1388                      setStartOnboardingRestore(false);1389                      setResumeRestoreSource(null);1390                      void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1391                      return handleUnlock();1392                    }}1393                    onBackToOnboarding={1394                      !hasVault()1395                        ? () => {1396                            // Deliberately rewinding to the carousel — the exit1397                            // flow must not reclaim the next popup open.1398                            clearOnboardingExit();1399                            setStartOnboardingRestore(false);1400                            setOnboarded(false);1401                          }1402                        : undefined1403                    }1404                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1405                  />1406                </Show>1407              </Show>1408            }1409          >1410            <Show1411              when={1412                view() !== "pro-celebration" &&1413                view() !== "initial-sync"1414              }1415              fallback={1416                <Show1417                  when={view() === "initial-sync"}1418                  fallback={<ProCelebration />}1419                >1420                  <InitialSyncView1421                    slow={initialSyncSlow()}1422                    onRetry={() => void retryInitialSync()}1423                  />1424                </Show>1425              }1426            >1427            <section1428              id="hd-shell"1429              class="peach-shell peach-theme"1430              data-surface="extension"1431            >1432            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1433              <PeachWordmark unlocked />1434              <div class="peach-chrome-actions">1435                <button1436                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1437                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1438                  aria-label="Notes"1439                  title="Notes"1440                >1441                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1442                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1443                    <line x1="4" y1="5" x2="10" y2="5" />1444                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1445                    <line x1="4" y1="10" x2="7" y2="10" />1446                  </svg>1447                </button>1448                <button1449                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1450                    classList={{1451                      "is-syncing": syncBusy(),1452                      "is-ok": syncFlash() === "ok",1453                      "is-error": syncFlash() === "error",1454                    }}1455                    onClick={() => void handleHeaderSync()}1456                    disabled={syncBusy()}1457                    aria-label={`Sync now. ${syncLabel()}`}1458                    title={syncLabel()}1459                  >1460                    <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">1461                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1462                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1463                      <path d="M2.6 1v2.4h2.4" />1464                      <path d="M11.4 13v-2.4H9" />1465                    </svg>1466                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1467                  </button>1468                <button1469                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1470                  onClick={() => setView("settings")}1471                  aria-label="Settings"1472                >1473                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1474                    <path1475                      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"1476                      stroke="currentColor"1477                      stroke-width="0.9"1478                    />1479                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1480                  </svg>1481                </button>1482                <button1483                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1484                  onClick={handleAdd}1485                  aria-label="New entry"1486                >1487                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1488                    <path d="M5.5 1v9M1 5.5h9" />1489                  </svg>1490                </button>1491                <button1492                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1493                  onClick={() => void handleHeaderLock()}1494                  aria-label="Lock vault"1495                >1496                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1497                    <path1498                      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"1499                      stroke="currentColor"1500                      stroke-width="1"1501                      stroke-linecap="round"1502                    />1503                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1504                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1505                  </svg>1506                </button>1507              </div>1508            </header>15091510            <Show when={pendingProNotice() !== null}>1511              <div class="peach-pro-notice-banner">1512                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1513                <button1514                  class="peach-pro-notice-link"1515                  onClick={() => {1516                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1517                    setSettingsInitialSection("license");1518                    setView("settings");1519                    setPendingProNotice(null);1520                  }}1521                >1522                  Learn more →1523                </button>1524                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1525              </div>1526            </Show>15271528            <Show when={pendingRememberSite()}>1529              {(request) => {1530                let host = request().url;1531                try { host = new URL(request().url).hostname; } catch { /* keep raw */ }1532                return (1533                  <div class="peach-pro-notice-banner">1534                    <span>Also use “{request().title}” on {host}?</span>1535                    <button1536                      class="peach-pro-notice-link"1537                      onClick={async () => {1538                        await sendMessage({1539                          type: "ADD_ADDITIONAL_URL",1540                          payload: { id: request().entryId, url: request().url },1541                        });1542                        await chrome.storage.session.remove("pendingRememberSite");1543                        setPendingRememberSite(null);1544                      }}1545                    >1546                      Add1547                    </button>1548                    <button1549                      class="peach-pro-notice-close"1550                      onClick={async () => {1551                        await chrome.storage.session.remove("pendingRememberSite");1552                        setPendingRememberSite(null);1553                      }}1554                      aria-label="Dismiss"1555                    >1556                      ✕1557                    </button>1558                  </div>1559                );1560              }}1561            </Show>15621563            <div class="peach-shell-body">1564              <div class="peach-shell-veil"></div>1565              <div class="peach-content-frame" data-content-phase={contentPhase()}>1566                <EntryView1567                  entry={selectedEntry()}1568                  currentTabUrl={currentTabUrl()}1569                  entries={entries()}1570                  isPro={proStatus()}1571                  onDelete={handleDelete}1572                  onFieldSaved={() => void loadEntries()}1573                  onEscape={() => { setView("list"); }}1574                  onProGate={(feature) => {1575                    setUpgradeHighlight(feature);1576                    setSettingsInitialSection("license");1577                    setView("settings");1578                  }}1579                />1580              </div>15811582              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1583                <div class="peach-search-bar">1584                  <span class="peach-search-icon">1585                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1586                      <circle cx="5.5" cy="5.5" r="3.75" />1587                      <path d="M8.75 8.75L11.5 11.5" />1588                    </svg>1589                  </span>1590                  <input1591                    class="peach-search-input"1592                    placeholder="search vault..."1593                    autocomplete="off"1594                    aria-label="Search vault entries"1595                    onClick={openList}1596                    onFocus={openList}1597                    readOnly1598                  />1599                  <div class="peach-search-meta">1600                    <span class="peach-search-counter">1601                      {nonNoteEntries().length > 01602                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1603                        : "0 entries"}1604                    </span>1605                    <span class="peach-divider"></span>1606                    <button1607                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1608                      onClick={() => navigate(-1)}1609                      aria-label="Previous entry"1610                      disabled={nonNoteEntries().length === 0}1611                    >1612                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1613                        <path d="M5 1L1 5.5L5 10" />1614                      </svg>1615                    </button>1616                    <button1617                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1618                      onClick={() => navigate(1)}1619                      aria-label="Next entry"1620                      disabled={nonNoteEntries().length === 0}1621                    >1622                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1623                        <path d="M1 1L5 5.5L1 10" />1624                      </svg>1625                    </button>1626                  </div>1627                </div>1628              </section>1629            </div>16301631            {/* Rare device-trust alerts; normal sync changes are silent. */}1632            <Show when={alertGroups().length > 0}>1633              <div class="peach-sync-alerts">1634                <For each={alertGroups()}>1635                  {([type, group]) => {1636                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1637                    return (1638                      <div class="peach-sync-alert">1639                        <Show when={group.length > 1}>1640                          <button1641                            class="peach-sync-alert-flip"1642                            type="button"1643                            aria-label="Previous"1644                            onClick={() => flipAlert(type, -1)}1645                          >‹</button>1646                        </Show>1647                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1648                        <Show when={group.length > 1}>1649                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1650                          <button1651                            class="peach-sync-alert-flip"1652                            type="button"1653                            aria-label="Next"1654                            onClick={() => flipAlert(type, 1)}1655                          >›</button>1656                        </Show>1657                        <button1658                          class="peach-sync-alert-dismiss"1659                          type="button"1660                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1661                          onClick={() => dismissAlertGroup(type)}1662                        >×</button>1663                      </div>1664                    );1665                  }}1666                </For>1667              </div>1668            </Show>16691670            <Show when={view() === "list"}>1671              <VaultView1672                entries={entries()}1673                selectedEntryId={selectedEntry()?.id}1674                currentTabDomain={currentTabDomain()}1675                sortOrder={sortOrder()}1676                searchSeed={listSearchSeed()}1677                searchSeedNonce={listSearchSeedNonce()}1678                onSelectEntry={handleSelectEntry}1679                onSortOrderChange={setSortOrder}1680                onAdd={handleAdd}1681                onClose={() => setView("entry")}1682                onOpenTrash={() => setView("trash")}1683                onDeleteMany={handleDeleteMany}1684              />1685            </Show>1686            <Show when={view() === "settings" || settingsExiting()}>1687              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1688                <SettingsView1689                  entriesCount={entries().length}1690                  breachMonitoring={breachMonitoring()}1691                  lockOnClose={lockOnClose()}1692                  autoLockMinutes={autoLockMinutes()}1693                  trashRetentionDays={trashRetentionDays()}1694                  theme={theme()}1695                  accentColor={accentColor()}1696                  textSize={textSize()}1697                  reduceMotion={reduceMotion()}1698                  isPro={proStatus()}1699                  initialSection={settingsInitialSection()}1700                  upgradeHighlight={upgradeHighlight()}1701                  isExiting={settingsExiting()}1702                  onBreachMonitoringChange={applyBreachMonitoring}1703                  onLockOnCloseChange={applyLockOnClose}1704                  onAutoLockMinutesChange={applyAutoLockMinutes}1705                  onTrashRetentionChange={applyTrashRetention}1706                  onThemeChange={applyTheme}1707                  onAccentChange={applyAccentColor}1708                  onTextSizeChange={applyTextSize}1709                  onReduceMotionChange={applyReduceMotion}1710                  shortcuts={shortcutBindings()}1711                  onShortcutsChange={applyShortcuts}1712                  onLicenseChange={async () => {1713                    // After activation/deactivation: refresh Pro status,1714                    // re-load entries (defensive — signal state can drift if1715                    // the SW briefly restarts during the verify+save round-trip),1716                    // and replay the Pro celebration if this is the first time1717                    // a valid Pro license is seen on this device.1718                    await refreshProStatus();1719                    void loadEntries();1720                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1721                    if ((should as { ok: boolean; data?: boolean }).data === true) {1722                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1723                      setView("pro-celebration");1724                      window.setTimeout(() => setView("settings"), 2500);1725                    }1726                  }}1727                  onBack={() => {1728                    setSettingsExiting(true);1729                    window.setTimeout(() => {1730                      setSettingsExiting(false);1731                      setSettingsInitialSection(null);1732                      setUpgradeHighlight(null);1733                      handleBack();1734                    }, 200);1735                  }}1736                  onImport={() => setView("import")}1737                  onExport={() => setView("export")}1738                  onBreachCheckDone={loadEntries}1739                  onOpenHealth={openHealth}1740                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1741                  onOpenFileImport={handleOpenFileImport}1742                  onOpenPanic={() => setView("panic")}1743                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1744                  onOpenCodexRestore={() => setView("codex-restore")}1745                  onCardChange={setSettingsActiveCard}1746                  onProGate={(feature) => {1747                    setUpgradeHighlight(feature);1748                    setSettingsInitialSection("license");1749                  }}1750                />1751              </Suspense>1752            </Show>1753            <Show when={view() === "codex-generate"}>1754              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1755                <CodexGenerateView1756                  isPro={proStatus()}1757                  onBack={() => setView("settings")}1758                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1759                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1760                  onVaultLocked={() => handleLock()}1761                />1762              </Suspense>1763            </Show>1764            <Show when={view() === "codex-restore"}>1765              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1766                <CodexRestoreView1767                  onBack={() => setView("lock")}1768                  onRestoreSuccess={async () => {1769                    // After restore the vault is unlocked; refresh entries1770                    // and route to the main vault list. handleUnlock is the1771                    // canonical post-unlock setup path.1772                    await handleUnlock();1773                  }}1774                />1775              </Suspense>1776            </Show>1777            <Show when={view() === "pair-device"}>1778              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1779                <PairDeviceView1780                  isPro={proStatus()}1781                  onProChanged={() => { void refreshProStatus(); }}1782                  onBack={() => setView("settings")}1783                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1784                />1785              </Suspense>1786            </Show>1787            <Show when={view() === "add"}>1788              <AddView1789                entry={editEntry()}1790                entries={entries()}1791                onBack={handleBack}1792                onSave={handleSave}1793              />1794            </Show>1795            <Show when={view() === "import"}>1796              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1797                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1798              </Suspense>1799            </Show>1800            <Show when={view() === "export"}>1801              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1802                <ExportView onBack={handleExportBack} />1803              </Suspense>1804            </Show>1805            <Show when={view() === "panic"}>1806              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1807                <PanicView1808                  onCancel={() => setView("settings")}1809                  onOpenExport={() => {1810                    setReturnToPanic(true);1811                    setView("export");1812                  }}1813                  onDestroyed={async () => {1814                    // Fresh onboarding start after a destroy — don't let the1815                    // resume markers land the user mid-carousel.1816                    setOnboardingCardAtExit(0);1817                    void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1818                    clearOnboardingExit();1819                    setEntries([]);1820                    setSelectedEntry(null);1821                    setEditEntry(undefined);1822                    setHasVault(false);1823                    setOnboarded(false);1824                    setProStatus(false);1825                    setPendingPasskey(null);1826                    setUpgradeHighlight(null);1827                    setSettingsInitialSection(null);1828                    setPendingProNotice(null);1829                    setPendingCelebration(false);1830                    setReturnToPanic(false);1831                    setContentPhase("idle");1832                    setView("lock");1833                  }}1834                />1835              </Suspense>1836            </Show>1837            {/* Health stays mounted while editing an entry from it so1838                computeReused() doesn't rerun on every cancel/back. */}1839            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1840              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1841                <HealthView1842                  entries={entries()}1843                  isPro={proStatus()}1844                  onFixEntry={handleFixEntry}1845                  onBack={() => setView("settings")}1846                  onRefresh={loadEntries}1847                  hidden={view() !== "health"}1848                />1849              </Suspense>1850            </Show>1851            <Show when={view() === "trash"}>1852              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1853                <TrashView1854                  onBack={() => setView("list")}1855                  onRestored={() => void loadEntries()}1856                />1857              </Suspense>1858            </Show>1859            <Show when={showNotes()}>1860              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1861                <NotesMode1862                  notes={entries().filter((e) => e.type === "note")}1863                  initialNoteId={openNoteId()}1864                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1865                  onNoteListChanged={() => void loadEntries()}1866                />1867              </div>1868            </Show>1869            <Show when={restoreView() === "file"}>1870              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1871                <ImportView1872                  mode="onboarding"1873                  replacesExistingVault={true}1874                  onBack={() => setRestoreView(null)}1875                  onImport={async () => {1876                    setRestoreView(null);1877                    await handleUnlock();1878                  }}1879                />1880              </Suspense>1881            </Show>1882            </section>1883            </Show>1884          </Show>1885        </Show>1886      </Show>1887      <Show when={showShortcutsHelp()}>1888        <ShortcutsHelpOverlay1889          bindings={shortcutBindings()}1890          onClose={() => setShowShortcutsHelp(false)}1891        />1892      </Show>1893    </div>1894  );1895}18961897function ShortcutsHelpOverlay(props: {1898  bindings: Record<ShortcutAction, Keybinding>;1899  onClose: () => void;1900}) {1901  return (1902    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1903      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1904        <div class="peach-shortcuts-help-head">1905          <h3>Keyboard shortcuts</h3>1906          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1907        </div>1908        <div class="peach-shortcuts-help-body">1909          <p class="peach-settings-sub-label">ENTRY VIEW</p>1910          <ul>1911            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1912              <li>1913                <span>{d.label}</span>1914                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1915              </li>1916            ))}1917          </ul>1918          <p class="peach-settings-sub-label">ANYWHERE</p>1919          <ul>1920            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1921              <li>1922                <span>{d.label}</span>1923                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1924              </li>1925            ))}1926          </ul>1927        </div>1928      </div>1929    </div>1930  );1931}