App.tsx

81.1 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    // Content UI can ask the background to open this trusted popup either for647    // unlock or at a specific entry. Consume both session-scoped handoffs once.648    let pendingOpenEntryId: string | undefined;649    if (chrome.storage.session) {650      try {651        const s = await chrome.storage.session.get(["peach_inline_unlock", "peach_open_entry"]);652        const pending = s as { peach_inline_unlock?: boolean; peach_open_entry?: string };653        if (pending.peach_inline_unlock) {654          openedForInlineUnlock = true;655        }656        if (typeof pending.peach_open_entry === "string") pendingOpenEntryId = pending.peach_open_entry;657        await chrome.storage.session.remove(["peach_inline_unlock", "peach_open_entry"]);658      } catch { /* best-effort */ }659    }660661    if (recoveryPending && unlocked) {662      // forceRecoveryWords overrides LockView's hasVault gate so the663      // recovery surface renders even though the vault now exists.664      setForceRecoveryWords(true);665      setView("lock");666    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {667      void beginInitialSyncWait(pendingInitialSyncDeviceId);668    } else if (unlocked && vaultExists) {669      await openVault(pendingOpenEntryId, shouldCelebrate);670      if (shouldCelebrate) {671        setView("pro-celebration");672        window.setTimeout(() => setView("entry"), 2500);673      }674    } else if (shouldCelebrate) {675      setPendingCelebration(true);676    }677678    await refreshPendingPasskey();679680    // Track tab changes so smart sort stays current681    const handleTabActivated = () => { void refreshCurrentTab(); };682    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {683      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();684    };685    try {686      chrome.tabs.onActivated.addListener(handleTabActivated);687      chrome.tabs.onUpdated.addListener(handleTabUpdated);688      onCleanup(() => {689        chrome.tabs.onActivated.removeListener(handleTabActivated);690        chrome.tabs.onUpdated.removeListener(handleTabUpdated);691      });692    } catch {693      // tabs permission may not be available in all contexts694    }695696    setBootState("ready");697698    // Deep-link: ?codex=pdf opens a detached window straight into the699    // Codex restore flow with auto-picked PDF. The action popup can't host700    // a file dialog without dismissing itself, so this is the only way the701    // PDF import path survives. See CodexRestoreView.openPdfPicker().702    try {703      const route = new URLSearchParams(window.location.search).get("codex");704      if (route === "pdf" || route === "restore") {705        setView("codex-restore");706      }707    } catch {708      // location.search unavailable — ignore.709    }710711    // Check for pending session-storage notices from the background.712    if (chrome.storage.session) {713      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as714        Record<string, { feature?: string } | undefined>;715      if (session.pendingProGate?.feature) {716        await chrome.storage.session.remove("pendingProGate");717        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);718        setSettingsInitialSection("license");719        setView("settings");720      } else if (session.pendingProNotice?.feature) {721        await chrome.storage.session.remove("pendingProNotice");722        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });723      }724      const remembered = (await chrome.storage.session.get("pendingRememberSite")) as {725        pendingRememberSite?: { entryId?: unknown; url?: unknown };726      };727      const request = remembered.pendingRememberSite;728      if (729        typeof request?.entryId === "string" &&730        typeof request.url === "string"731      ) {732        const entry = await sendMessage({ type: "GET_ENTRIES" });733        const match = entry.ok734          ? (entry.data as Array<{ id: string; title?: string }> | undefined)?.find(735              (candidate) => candidate.id === request.entryId,736            )737          : undefined;738        if (match) {739          let host = request.url;740          try { host = new URL(request.url).hostname; } catch { /* keep raw */ }741          setPendingRememberSite({ entryId: request.entryId, url: request.url, title: match.title ?? host });742        } else {743          await chrome.storage.session.remove("pendingRememberSite");744        }745      }746    }747748    // Warm the lazy-module cache so the Suspense fallback never shows for749    // locally-bundled extension views. Without this, the first navigation to750    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which751    // covers the shell and absorbs clicks on the header.752    void Promise.all([753      import("./views/Settings").catch(() => {}),754      import("./views/Import").catch(() => {}),755      import("./views/Export").catch(() => {}),756      import("./views/Health").catch(() => {}),757      import("./views/TrashView").catch(() => {}),758    ]);759760    // Lock-on-close via a persistent port. sendMessage in pagehide is761    // unreliable — the popup context tears down before the message lands.762    // The SW's onConnect listener locks when this port disconnects.763    let popupPort: chrome.runtime.Port | null = null;764    try {765      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect766      // listener accepts the "popup-" prefix; the random suffix is defence in767      // depth against a port named exactly "popup" from anything but our popup.768      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });769    } catch { /* extension context invalidated — ignore */ }770    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });771772    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale773    // entries instead of waiting for the next GET_ENTRIES round-trip.774    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {775      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();776      if (msg?.type === "SYNC_STATE_CHANGED") {777        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);778      }779      if (msg?.type === "PRO_GATE_TRIGGERED") {780        setUpgradeHighlight(msg.payload?.feature ?? null);781        setSettingsInitialSection("license");782        setView("settings");783      }784    };785    chrome.runtime.onMessage.addListener(handleRuntimeMessage);786    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));787788    // Action handlers — keyed by ShortcutAction. The dispatcher below tests789    // each binding against the event and runs the matching handler. New790    // shortcuts only need an entry here; the binding is data, not code.791    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {792      copy_password: () => {793        const entry = selectedEntry();794        if (entry?.password) void popupCopy(795          entry.password,796          "Password",797          entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,798        ).then((ok) => { if (ok) triggerRing(); });799      },800      copy_username: () => {801        const entry = selectedEntry();802        if (entry?.username) void popupCopy(803          entry.username,804          "Username",805          entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,806        ).then((ok) => { if (ok) triggerRing(); });807      },808      copy_totp: () => {809        const entry = selectedEntry();810        if (!entry?.totp) return;811        try {812          const { code } = generateTOTP(813            entry.totp,814            entry.totpAlgorithm,815            entry.totpDigits,816            entry.totpPeriod,817          );818          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });819        } catch { /* invalid TOTP secret — silent */ }820      },821      new_entry: () => handleAdd(),822      edit_entry: () => {823        const entry = selectedEntry();824        // Passkey-only entries have nothing user-editable in the Add view; the825        // passkey credential itself is opaque. Skip the edit action for them.826        if (!entry || isPasskeyOnly(entry)) return;827        setEditEntry(entry);828        setView("add");829      },830      delete_entry: () => {831        if (selectedEntry()) void handleDelete();832      },833      lock_vault: () => { void handleHeaderLock(); },834      search: () => openList(),835      nav_prev: () => navigate(-1),836      nav_next: () => navigate(1),837      jump_vault: () => setView("entry"),838      jump_settings: () => setView("settings"),839      show_help: () => setShowShortcutsHelp(true),840    };841842    // Actions that are MEANINGFUL only on the entry-detail view. Outside843    // that scope the binding is dormant — pressing C while on Settings844    // does nothing rather than awkwardly copying from a now-stale entry.845    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([846      "copy_password", "copy_username", "copy_totp",847      "edit_entry", "delete_entry", "nav_prev", "nav_next",848    ]);849850    const handleGlobalKeydown = (e: KeyboardEvent) => {851      const v = view();852      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"853        || (e.target as HTMLElement)?.tagName === "TEXTAREA"854        || (e.target as HTMLElement)?.isContentEditable;855      const isPrintableSearchKey =856        e.key.length === 1 &&857        !e.ctrlKey &&858        !e.metaKey &&859        !e.altKey;860861      // No shortcuts while a full-screen surface owns the whole viewport:862      // the lock screen, the post-pairing readiness sequence, or the Pro863      // celebration. Without this the lock screen is at the mercy of whatever864      // single-key binding is active — e.g. typing "n" in a password that865      // slips out of focus triggers `new_entry` and escapes the lock screen.866      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;867868      // Help dialog: Escape closes it; eat the keypress so it doesn't869      // also navigate away from the underlying view.870      if (showShortcutsHelp()) {871        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }872        return;873      }874875      // ── Escape — fixed binding (not user-customizable) ───────876      if (e.key === "Escape") {877        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }878        if (v === "list") { setView("entry"); return; }879        if (v === "settings" || v === "add") { handleBack(); return; }880        if (v === "import" || v === "health") { setView("settings"); return; }881        if (v === "export") { handleExportBack(); return; }882        if (v === "pair-device") { setView("settings"); return; }883      }884885      // Bindings-driven dispatch. Single-key letter bindings without886      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is887      // inside an input, so users can type into search/forms normally.888      const bindings = shortcutBindings();889      for (const action of Object.keys(bindings) as ShortcutAction[]) {890        const binding = bindings[action];891        if (!matchKeybinding(e, binding)) continue;892        // Single-key letter bindings need the input-focus guard. Bindings893        // with any modifier are safe — Ctrl+L doesn't conflict with typing.894        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;895        if (!hasMod && binding.key.length === 1 && inInput) return;896        if (ENTRY_SCOPED.has(action) && v !== "entry") return;897        e.preventDefault();898        SHORTCUT_HANDLERS[action]?.();899        return;900      }901902      // Type-to-search: in entry view, any printable key not consumed by a903      // shortcut above primes the list search seed and opens the list.904      // Kept outside the bindings table because it's a behavior, not a905      // discrete action — every printable character can trigger it.906      if (v === "entry" && !inInput && isPrintableSearchKey) {907        e.preventDefault();908        primeListSearch(e.key);909        return;910      }911    };912    window.addEventListener("keydown", handleGlobalKeydown);913    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));914915    const handleStorageChanged = (916      changes: Record<string, chrome.storage.StorageChange>,917      areaName: string918    ) => {919      if (areaName !== "session") return;920      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {921        return;922      }923      void refreshPendingPasskey();924    };925    chrome.storage.onChanged.addListener(handleStorageChanged);926    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));927  });928929  async function refreshCurrentTab() {930    try {931      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });932      const url = tab?.url ?? tab?.pendingUrl ?? "";933      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");934      // Skip extension/internal URLs — adding chrome://, about:, or935      // chrome-extension:// to a vault entry is never what the user wants.936      const isWebUrl = /^https?:\/\//i.test(url);937      setCurrentTabUrl(isWebUrl ? url : "");938    } catch {939      setCurrentTabDomain("");940      setCurrentTabUrl("");941    }942  }943944  async function refreshPendingPasskey() {945    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });946    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);947  }948949  async function refreshProStatus() {950    const res = await sendMessage({ type: "GET_LICENSE" });951    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;952    setProStatus(Boolean(data?.valid && data?.plan === "pro"));953  }954955  async function restoreSettings() {956    const res = await sendMessage({ type: "GET_SETTINGS" });957    const s = (res as { ok: boolean; data?: any }).data ?? {};958    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {959      setAccentColor(s.accentColor as AccentColorName);960    }961    setTheme(s.theme === "light" ? "light" : "dark");962    if (s.textSize === "small" || s.textSize === "large") {963      setTextSize(s.textSize);964    } else {965      setTextSize("medium");966    }967    setReduceMotion(s.reduceMotion === true);968    setLockOnClose(s.lockOnClose === true);969    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);970    setBreachMonitoring(s.breachMonitoring !== false);971    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);972    setShortcutBindings(getActiveBindings(s.shortcuts));973  }974975  async function applyTrashRetention(days: number) {976    setTrashRetentionDays(days);977    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });978  }979980  function primeListSearch(seed: string) {981    setListSearchSeed(seed);982    setListSearchSeedNonce((value) => value + 1);983    openList();984  }985986  // Returns null when it detected a dead service worker and triggered handleLock().987  // Callers that need to abort (e.g. openVault) check for null rather than relying988  // on view() state, which may already be "lock" during normal startup flows.989  async function loadEntries(): Promise<VaultEntry[] | null> {990    const response = await sendMessage({ type: "GET_ENTRIES" });991    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };992993    // If the service worker was killed and restarted (MV3 workers sleep), the994    // vault will be locked again — or the worker may not respond at all.995    // In either case, send the user to the lock screen rather than silently996    // showing an empty vault (which looks like data loss).997    if (!res.ok) {998      if (999        res.error === "vault_locked" ||1000        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1001        (typeof res.error === "string" && res.error.includes("locked"))1002      ) {1003        handleLock();1004        return null; // signal emergency lock to callers1005      }1006      return [];1007    }10081009    const loadedEntries = res.data ?? [];1010    setEntries(loadedEntries);10111012    const currentId = selectedEntry()?.id;1013    if (currentId) {1014      setSelectedEntry(1015        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1016      );1017    }10181019    return loadedEntries;1020  }10211022  async function openVault(preferredEntryId?: string, skipViewSet = false) {1023    // Purge expired trash entries on each vault open1024    const retDays = trashRetentionDays();1025    if (retDays > 0) {1026      void sendMessage({1027        type: "PURGE_EXPIRED_TRASH",1028        payload: { retentionMs: retDays * 86_400_000 },1029      });1030    }10311032    const loadedEntries = await loadEntries();10331034    // null means loadEntries() triggered an emergency lock (service worker died).1035    // Don't override it by setting view back to "entry" with an empty vault.1036    if (loadedEntries === null) return false;10371038    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1039    let nextSelectedEntry: VaultEntry | null = null;1040    if (preferredEntryId) {1041      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1042    }1043    if (!nextSelectedEntry) {1044      const tabDomain = currentTabDomain();1045      if (tabDomain) {1046        nextSelectedEntry = loadedEntries.find((e) => {1047          if (e.type === "login") {1048            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1049            for (const extra of e.additionalUrls ?? []) {1050              if ((extractDomain(extra) ?? "") === tabDomain) return true;1051            }1052            return false;1053          }1054          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1055          return false;1056        }) ?? null;1057      }1058    }1059    nextSelectedEntry ??= pickNavigable(loadedEntries);10601061    setSelectedEntry(nextSelectedEntry);1062    setEditEntry(undefined);1063    setContentPhase("enter");1064    queueContentIdle();1065    if (!skipViewSet) setView("entry");1066    return true;1067  }10681069  async function handleUnlock() {1070    // If the user previously created a vault but hadn't yet confirmed their1071    // recovery words (and the browser was closed before they could), the1072    // the background-owned recovery-pending state is still set. Re-route1073    // back to the recovery surface so they finish the confirmation step1074    // before reaching the entries view — the words can be re-derived now1075    // that the vault is unlocked again.1076    let recoveryPending = false;1077    try {1078      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });1079      recoveryPending = out.ok === true && out.data === true;1080    } catch { /* best-effort */ }1081    if (recoveryPending) {1082      setForceRecoveryWords(true);1083      setView("lock");1084      triggerPipPulse();1085      await restoreSettings();1086      return;1087    }1088    setHasVault(true);1089    triggerPipPulse();1090    await restoreSettings();1091    const celebrating = pendingCelebration();1092    if (celebrating) {1093      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1094      setPendingCelebration(false);1095    }1096    await openVault(undefined, celebrating);1097    if (celebrating) {1098      setView("pro-celebration");1099      window.setTimeout(() => setView("entry"), 2500);1100    }1101    // Popup was opened from the inline "Open Peach to unlock" button — close it1102    // now so the user lands back on the page with the autofill selector ready.1103    if (openedForInlineUnlock) {1104      openedForInlineUnlock = false;1105      window.close();1106    }1107  }11081109  function handleSelectEntry(entry: VaultEntry) {1110    if (entry.type === "note") {1111      setOpenNoteId(entry.id);1112      setShowNotes(true);1113      return;1114    }1115    setSelectedEntry(entry);1116    setContentPhase("enter");1117    queueContentIdle();1118    setView("entry");1119  }11201121  function handleAdd() {1122    setEditEntry(undefined);1123    setView("add");1124  }11251126  async function handleDelete() {1127    const entry = selectedEntry();1128    if (!entry) return;1129    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1130    const loadedEntries = await loadEntries() ?? [];1131    setSelectedEntry(pickNavigable(loadedEntries));1132    setView("entry");1133  }11341135  async function handleDeleteMany(ids: string[]) {1136    for (const id of ids) {1137      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1138    }1139    const loadedEntries = await loadEntries() ?? [];1140    // If the currently selected entry was among the deleted, move to first1141    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1142    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1143  }11441145  async function handleSave(savedEntry?: VaultEntry) {1146    await openVault(savedEntry?.id);1147  }11481149  function handleBack() {1150    const dest = editBackView();1151    setEditBackView("entry");1152    setEditEntry(undefined);1153    setView(dest);1154  }11551156  function handleExportBack() {1157    if (returnToPanic()) {1158      setReturnToPanic(false);1159      setView("panic");1160      return;1161    }1162    setView("settings");1163  }11641165  function handleLock() {1166    setEntries([]);1167    setSelectedEntry(null);1168    setEditEntry(undefined);1169    setContentPhase("idle");1170    setView("lock");1171  }11721173  function handleHeaderLock() {1174    // Lock the UI immediately — do not wait for the service worker. If the SW1175    // is dead or slow, the 5s sendMessage timeout would create a dead-click1176    // window. The SW will lock on its next wake regardless.1177    handleLock();1178    void sendMessage({ type: "LOCK" });1179  }11801181  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1182  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1183  // the trigger's own reply.1184  async function handleHeaderSync(): Promise<void> {1185    if (syncBusy()) return;1186    setSyncBusy(true);1187    setSyncFlash(null);1188    try {1189      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1190      let state: SyncOutcomeSummary = { status: "syncing" };1191      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1192        await new Promise((r) => setTimeout(r, 250));1193        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1194          ok: boolean;1195          data?: SyncOutcomeSummary;1196        };1197        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1198      }1199      setSyncSummary(state);1200      setSyncFlash(state.status === "error" ? "error" : "ok");1201      await loadSyncAlerts();1202      await loadEntries();1203      await loadSyncIndicator();1204    } catch {1205      setSyncSummary({ status: "error", outcome: "run_failed" });1206      setSyncFlash("error");1207    } finally {1208      setSyncBusy(false);1209      setTimeout(() => setSyncFlash(null), 2_000);1210    }1211  }12121213  function navigate(dir: number) {1214    const navigable = nonNoteEntries();1215    if (navigable.length === 0) return;1216    const currentIndex = selectedIndex();1217    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1218    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1219    setSelectedEntry(navigable[nextIndex]);1220    setContentPhase("enter");1221    queueContentIdle();1222  }12231224  /**1225   * The Entry view's selection invariant: never select a note. Notes are a1226   * separate surface (handleSelectEntry opens the notes view), so any code path1227   * that picks a default — vault open, post-delete, refresh — must skip them1228   * and return null if the only entries are notes.1229   */1230  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1231    return list.find((e) => e.type !== "note") ?? null;1232  }12331234  function openList() {1235    setView("list");1236  }12371238  function openHealth() {1239    setEditEntry(undefined);1240    setView("health");1241  }12421243  function handleOpenFileImport() {1244    setRestoreView("file");1245  }12461247  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12481249  function handleFixEntry(entry: VaultEntry) {1250    setSelectedEntry(entry);1251    // Passkey-only entries have no editable surface — drop into view mode1252    // instead of opening the Add editor.1253    if (isPasskeyOnly(entry)) {1254      setView("entry");1255      return;1256    }1257    setEditBackView(view()); // preserve caller view so back returns here1258    setEditEntry(entry);1259    setView("add");1260  }12611262  const isLockedView = () => view() === "lock" || view() === "adopting";12631264  async function handleAdoptionDone() {1265    await storageSet("peach_onboarded", "true").catch(() => {});1266    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1267    clearOnboardingExit();1268    setOnboarded(true);1269    setHasVault(true);1270    setView("initial-sync");1271    // The background applies a Pro license and persists the source-device1272    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1273    // celebration pending until that exact peer records a completed sync.1274    await refreshProStatus();1275    const deviceId = await resolveInitialSyncDeviceId();1276    if (deviceId) {1277      void beginInitialSyncWait(deviceId);1278    } else {1279      // Pairing completion without a durable peer row should be impossible.1280      // Stay on the honest waiting surface and expose retry instead of falling1281      // through to an empty vault.1282      setInitialSyncSlow(true);1283    }1284  }12851286  async function handleApprovePendingPasskey() {1287    const pending = pendingPasskey();1288    if (!pending) return;1289    if (pending.browser === "firefox" && pending.type === "create") {1290      // Firefox path: popup itself runs navigator.credentials.create. The1291      // background never approved/rejected anything — it just stashed1292      // intent. After the popup-driven flow resolves (success or cancel),1293      // clear the pending key so the popup doesn't re-show this on next open.1294      const { createFirefoxPasskey } = await import("./firefox-passkey");1295      const result = await createFirefoxPasskey(pending);1296      if (!result.ok) {1297        console.warn("Peach Firefox passkey create failed:", result.error);1298      }1299      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1300      setPendingPasskey(null);1301      void loadEntries();1302      window.close();1303      return;1304    }1305    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1306    window.close();1307  }13081309  async function handleDenyPendingPasskey() {1310    const pending = pendingPasskey();1311    if (!pending) return;1312    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1313    window.close();1314  }13151316  function queueContentIdle(after?: () => void) {1317    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1318    contentPhaseTimer = window.setTimeout(() => {1319      setContentPhase("idle");1320      after?.();1321    }, ENTRY_TRANSITION_SETTLE_MS);1322  }13231324  return (1325    <div class="popup-root peach-theme">1326      <Show when={bootState() === "ready"}>1327        <Show1328          when={!pendingPasskey()}1329          fallback={1330            <PasskeyApprovalView1331              type={pendingPasskey()!.type}1332              rpName={pendingPasskey()!.rpName}1333              rpId={pendingPasskey()!.rpId}1334              userName={pendingPasskey()!.userName}1335              userDisplayName={pendingPasskey()!.userDisplayName}1336              onApprove={handleApprovePendingPasskey}1337              onDeny={handleDenyPendingPasskey}1338            />1339          }1340        >1341          <Show1342            when={!isLockedView()}1343            fallback={1344              <Show1345                when={view() !== "adopting"}1346                fallback={1347                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1348                    <AdoptVaultView1349                      onCancel={() => {1350                        clearOnboardingExit();1351                        setOnboarded(false);1352                        setView("lock");1353                      }}1354                      onDone={handleAdoptionDone}1355                    />1356                  </Suspense>1357                }1358              >1359                <Show1360                  when={onboarded() || hasVault()}1361                  fallback={1362                    <Onboarding1363                      initialCard={onboardingCardAtExit()}1364                      onComplete={() => {1365                        markOnboardingExit("create");1366                        setStartOnboardingRestore(false);1367                        setOnboarded(true);1368                      }}1369                      onRestore={() => {1370                        markOnboardingExit("restore");1371                        setStartOnboardingRestore(true);1372                        setOnboarded(true);1373                      }}1374                      onAdopt={() => {1375                        markOnboardingExit("adopt");1376                        setStartOnboardingRestore(false);1377                        setOnboarded(true);1378                        setView("adopting");1379                      }}1380                    />1381                  }1382                >1383                  <LockView1384                    hasVault={hasVault()}1385                    ready={bootState() === "ready"}1386                    isPro={proStatus()}1387                    forceRecoveryWords={forceRecoveryWords()}1388                    initialRestore={startOnboardingRestore()}1389                    initialRestoreSource={resumeRestoreSource() ?? undefined}1390                    onUnlock={() => {1391                      // RecoveryWordDisplay clears the storage flag before1392                      // calling onDone, so handleUnlock will see no pending1393                      // confirmation and proceed through the normal path.1394                      if (forceRecoveryWords()) setForceRecoveryWords(false);1395                      // The create/restore flow is done — a lock later in this1396                      // window must show the unlock screen, not re-enter the1397                      // onboarding restore surface.1398                      setStartOnboardingRestore(false);1399                      setResumeRestoreSource(null);1400                      void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1401                      return handleUnlock();1402                    }}1403                    onBackToOnboarding={1404                      !hasVault()1405                        ? () => {1406                            // Deliberately rewinding to the carousel — the exit1407                            // flow must not reclaim the next popup open.1408                            clearOnboardingExit();1409                            setStartOnboardingRestore(false);1410                            setOnboarded(false);1411                          }1412                        : undefined1413                    }1414                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1415                  />1416                </Show>1417              </Show>1418            }1419          >1420            <Show1421              when={1422                view() !== "pro-celebration" &&1423                view() !== "initial-sync"1424              }1425              fallback={1426                <Show1427                  when={view() === "initial-sync"}1428                  fallback={<ProCelebration />}1429                >1430                  <InitialSyncView1431                    slow={initialSyncSlow()}1432                    onRetry={() => void retryInitialSync()}1433                  />1434                </Show>1435              }1436            >1437            <section1438              id="hd-shell"1439              class="peach-shell peach-theme"1440              data-surface="extension"1441            >1442            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1443              <PeachWordmark unlocked />1444              <div class="peach-chrome-actions">1445                <button1446                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1447                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1448                  aria-label="Notes"1449                  title="Notes"1450                >1451                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1452                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1453                    <line x1="4" y1="5" x2="10" y2="5" />1454                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1455                    <line x1="4" y1="10" x2="7" y2="10" />1456                  </svg>1457                </button>1458                <button1459                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1460                    classList={{1461                      "is-syncing": syncBusy(),1462                      "is-ok": syncFlash() === "ok",1463                      "is-error": syncFlash() === "error",1464                    }}1465                    onClick={() => void handleHeaderSync()}1466                    disabled={syncBusy()}1467                    aria-label={`Sync now. ${syncLabel()}`}1468                    title={syncLabel()}1469                  >1470                    <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">1471                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1472                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1473                      <path d="M2.6 1v2.4h2.4" />1474                      <path d="M11.4 13v-2.4H9" />1475                    </svg>1476                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1477                  </button>1478                <button1479                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1480                  onClick={() => setView("settings")}1481                  aria-label="Settings"1482                >1483                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1484                    <path1485                      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"1486                      stroke="currentColor"1487                      stroke-width="0.9"1488                    />1489                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1490                  </svg>1491                </button>1492                <button1493                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1494                  onClick={handleAdd}1495                  aria-label="New entry"1496                >1497                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1498                    <path d="M5.5 1v9M1 5.5h9" />1499                  </svg>1500                </button>1501                <button1502                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1503                  onClick={() => void handleHeaderLock()}1504                  aria-label="Lock vault"1505                >1506                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1507                    <path1508                      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"1509                      stroke="currentColor"1510                      stroke-width="1"1511                      stroke-linecap="round"1512                    />1513                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1514                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1515                  </svg>1516                </button>1517              </div>1518            </header>15191520            <Show when={pendingProNotice() !== null}>1521              <div class="peach-pro-notice-banner">1522                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1523                <button1524                  class="peach-pro-notice-link"1525                  onClick={() => {1526                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1527                    setSettingsInitialSection("license");1528                    setView("settings");1529                    setPendingProNotice(null);1530                  }}1531                >1532                  Learn more →1533                </button>1534                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1535              </div>1536            </Show>15371538            <Show when={pendingRememberSite()}>1539              {(request) => {1540                let host = request().url;1541                try { host = new URL(request().url).hostname; } catch { /* keep raw */ }1542                return (1543                  <div class="peach-pro-notice-banner">1544                    <span>Also use “{request().title}” on {host}?</span>1545                    <button1546                      class="peach-pro-notice-link"1547                      onClick={async () => {1548                        await sendMessage({1549                          type: "ADD_ADDITIONAL_URL",1550                          payload: { id: request().entryId, url: request().url },1551                        });1552                        await chrome.storage.session.remove("pendingRememberSite");1553                        setPendingRememberSite(null);1554                      }}1555                    >1556                      Add1557                    </button>1558                    <button1559                      class="peach-pro-notice-close"1560                      onClick={async () => {1561                        await chrome.storage.session.remove("pendingRememberSite");1562                        setPendingRememberSite(null);1563                      }}1564                      aria-label="Dismiss"1565                    >1566                      ✕1567                    </button>1568                  </div>1569                );1570              }}1571            </Show>15721573            <div class="peach-shell-body">1574              <div class="peach-shell-veil"></div>1575              <div class="peach-content-frame" data-content-phase={contentPhase()}>1576                <EntryView1577                  entry={selectedEntry()}1578                  currentTabUrl={currentTabUrl()}1579                  entries={entries()}1580                  isPro={proStatus()}1581                  onDelete={handleDelete}1582                  onFieldSaved={() => void loadEntries()}1583                  onEscape={() => { setView("list"); }}1584                  onProGate={(feature) => {1585                    setUpgradeHighlight(feature);1586                    setSettingsInitialSection("license");1587                    setView("settings");1588                  }}1589                />1590              </div>15911592              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1593                <div class="peach-search-bar">1594                  <span class="peach-search-icon">1595                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1596                      <circle cx="5.5" cy="5.5" r="3.75" />1597                      <path d="M8.75 8.75L11.5 11.5" />1598                    </svg>1599                  </span>1600                  <input1601                    class="peach-search-input"1602                    placeholder="search vault..."1603                    autocomplete="off"1604                    aria-label="Search vault entries"1605                    onClick={openList}1606                    onFocus={openList}1607                    readOnly1608                  />1609                  <div class="peach-search-meta">1610                    <span class="peach-search-counter">1611                      {nonNoteEntries().length > 01612                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1613                        : "0 entries"}1614                    </span>1615                    <span class="peach-divider"></span>1616                    <button1617                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1618                      onClick={() => navigate(-1)}1619                      aria-label="Previous 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="M5 1L1 5.5L5 10" />1624                      </svg>1625                    </button>1626                    <button1627                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1628                      onClick={() => navigate(1)}1629                      aria-label="Next entry"1630                      disabled={nonNoteEntries().length === 0}1631                    >1632                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1633                        <path d="M1 1L5 5.5L1 10" />1634                      </svg>1635                    </button>1636                  </div>1637                </div>1638              </section>1639            </div>16401641            {/* Rare device-trust alerts; normal sync changes are silent. */}1642            <Show when={alertGroups().length > 0}>1643              <div class="peach-sync-alerts">1644                <For each={alertGroups()}>1645                  {([type, group]) => {1646                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1647                    return (1648                      <div class="peach-sync-alert">1649                        <Show when={group.length > 1}>1650                          <button1651                            class="peach-sync-alert-flip"1652                            type="button"1653                            aria-label="Previous"1654                            onClick={() => flipAlert(type, -1)}1655                          >‹</button>1656                        </Show>1657                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1658                        <Show when={group.length > 1}>1659                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1660                          <button1661                            class="peach-sync-alert-flip"1662                            type="button"1663                            aria-label="Next"1664                            onClick={() => flipAlert(type, 1)}1665                          >›</button>1666                        </Show>1667                        <button1668                          class="peach-sync-alert-dismiss"1669                          type="button"1670                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1671                          onClick={() => dismissAlertGroup(type)}1672                        >×</button>1673                      </div>1674                    );1675                  }}1676                </For>1677              </div>1678            </Show>16791680            <Show when={view() === "list"}>1681              <VaultView1682                entries={entries()}1683                selectedEntryId={selectedEntry()?.id}1684                currentTabDomain={currentTabDomain()}1685                sortOrder={sortOrder()}1686                searchSeed={listSearchSeed()}1687                searchSeedNonce={listSearchSeedNonce()}1688                onSelectEntry={handleSelectEntry}1689                onSortOrderChange={setSortOrder}1690                onAdd={handleAdd}1691                onClose={() => setView("entry")}1692                onOpenTrash={() => setView("trash")}1693                onDeleteMany={handleDeleteMany}1694              />1695            </Show>1696            <Show when={view() === "settings" || settingsExiting()}>1697              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1698                <SettingsView1699                  entriesCount={entries().length}1700                  breachMonitoring={breachMonitoring()}1701                  lockOnClose={lockOnClose()}1702                  autoLockMinutes={autoLockMinutes()}1703                  trashRetentionDays={trashRetentionDays()}1704                  theme={theme()}1705                  accentColor={accentColor()}1706                  textSize={textSize()}1707                  reduceMotion={reduceMotion()}1708                  isPro={proStatus()}1709                  initialSection={settingsInitialSection()}1710                  upgradeHighlight={upgradeHighlight()}1711                  isExiting={settingsExiting()}1712                  onBreachMonitoringChange={applyBreachMonitoring}1713                  onLockOnCloseChange={applyLockOnClose}1714                  onAutoLockMinutesChange={applyAutoLockMinutes}1715                  onTrashRetentionChange={applyTrashRetention}1716                  onThemeChange={applyTheme}1717                  onAccentChange={applyAccentColor}1718                  onTextSizeChange={applyTextSize}1719                  onReduceMotionChange={applyReduceMotion}1720                  shortcuts={shortcutBindings()}1721                  onShortcutsChange={applyShortcuts}1722                  onLicenseChange={async () => {1723                    // After activation/deactivation: refresh Pro status,1724                    // re-load entries (defensive — signal state can drift if1725                    // the SW briefly restarts during the verify+save round-trip),1726                    // and replay the Pro celebration if this is the first time1727                    // a valid Pro license is seen on this device.1728                    await refreshProStatus();1729                    void loadEntries();1730                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1731                    if ((should as { ok: boolean; data?: boolean }).data === true) {1732                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1733                      setView("pro-celebration");1734                      window.setTimeout(() => setView("settings"), 2500);1735                    }1736                  }}1737                  onBack={() => {1738                    setSettingsExiting(true);1739                    window.setTimeout(() => {1740                      setSettingsExiting(false);1741                      setSettingsInitialSection(null);1742                      setUpgradeHighlight(null);1743                      handleBack();1744                    }, 200);1745                  }}1746                  onImport={() => setView("import")}1747                  onExport={() => setView("export")}1748                  onBreachCheckDone={loadEntries}1749                  onOpenHealth={openHealth}1750                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1751                  onOpenFileImport={handleOpenFileImport}1752                  onOpenPanic={() => setView("panic")}1753                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1754                  onOpenCodexRestore={() => setView("codex-restore")}1755                  onCardChange={setSettingsActiveCard}1756                  onProGate={(feature) => {1757                    setUpgradeHighlight(feature);1758                    setSettingsInitialSection("license");1759                  }}1760                />1761              </Suspense>1762            </Show>1763            <Show when={view() === "codex-generate"}>1764              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1765                <CodexGenerateView1766                  isPro={proStatus()}1767                  onBack={() => setView("settings")}1768                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1769                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1770                  onVaultLocked={() => handleLock()}1771                />1772              </Suspense>1773            </Show>1774            <Show when={view() === "codex-restore"}>1775              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1776                <CodexRestoreView1777                  onBack={() => setView("lock")}1778                  onRestoreSuccess={async () => {1779                    // After restore the vault is unlocked; refresh entries1780                    // and route to the main vault list. handleUnlock is the1781                    // canonical post-unlock setup path.1782                    await handleUnlock();1783                  }}1784                />1785              </Suspense>1786            </Show>1787            <Show when={view() === "pair-device"}>1788              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1789                <PairDeviceView1790                  isPro={proStatus()}1791                  onProChanged={() => { void refreshProStatus(); }}1792                  onBack={() => setView("settings")}1793                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1794                />1795              </Suspense>1796            </Show>1797            <Show when={view() === "add"}>1798              <AddView1799                entry={editEntry()}1800                entries={entries()}1801                onBack={handleBack}1802                onSave={handleSave}1803              />1804            </Show>1805            <Show when={view() === "import"}>1806              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1807                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1808              </Suspense>1809            </Show>1810            <Show when={view() === "export"}>1811              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1812                <ExportView onBack={handleExportBack} />1813              </Suspense>1814            </Show>1815            <Show when={view() === "panic"}>1816              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1817                <PanicView1818                  onCancel={() => setView("settings")}1819                  onOpenExport={() => {1820                    setReturnToPanic(true);1821                    setView("export");1822                  }}1823                  onDestroyed={async () => {1824                    // Fresh onboarding start after a destroy — don't let the1825                    // resume markers land the user mid-carousel.1826                    setOnboardingCardAtExit(0);1827                    void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1828                    clearOnboardingExit();1829                    setEntries([]);1830                    setSelectedEntry(null);1831                    setEditEntry(undefined);1832                    setHasVault(false);1833                    setOnboarded(false);1834                    setProStatus(false);1835                    setPendingPasskey(null);1836                    setUpgradeHighlight(null);1837                    setSettingsInitialSection(null);1838                    setPendingProNotice(null);1839                    setPendingCelebration(false);1840                    setReturnToPanic(false);1841                    setContentPhase("idle");1842                    setView("lock");1843                  }}1844                />1845              </Suspense>1846            </Show>1847            {/* Health stays mounted while editing an entry from it so1848                computeReused() doesn't rerun on every cancel/back. */}1849            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1850              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1851                <HealthView1852                  entries={entries()}1853                  isPro={proStatus()}1854                  onFixEntry={handleFixEntry}1855                  onBack={() => setView("settings")}1856                  onRefresh={loadEntries}1857                  hidden={view() !== "health"}1858                />1859              </Suspense>1860            </Show>1861            <Show when={view() === "trash"}>1862              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1863                <TrashView1864                  onBack={() => setView("list")}1865                  onRestored={() => void loadEntries()}1866                />1867              </Suspense>1868            </Show>1869            <Show when={showNotes()}>1870              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1871                <NotesMode1872                  notes={entries().filter((e) => e.type === "note")}1873                  initialNoteId={openNoteId()}1874                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1875                  onNoteListChanged={() => void loadEntries()}1876                />1877              </div>1878            </Show>1879            <Show when={restoreView() === "file"}>1880              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1881                <ImportView1882                  mode="onboarding"1883                  replacesExistingVault={true}1884                  onBack={() => setRestoreView(null)}1885                  onImport={async () => {1886                    setRestoreView(null);1887                    await handleUnlock();1888                  }}1889                />1890              </Suspense>1891            </Show>1892            </section>1893            </Show>1894          </Show>1895        </Show>1896      </Show>1897      <Show when={showShortcutsHelp()}>1898        <ShortcutsHelpOverlay1899          bindings={shortcutBindings()}1900          onClose={() => setShowShortcutsHelp(false)}1901        />1902      </Show>1903    </div>1904  );1905}19061907function ShortcutsHelpOverlay(props: {1908  bindings: Record<ShortcutAction, Keybinding>;1909  onClose: () => void;1910}) {1911  return (1912    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1913      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1914        <div class="peach-shortcuts-help-head">1915          <h3>Keyboard shortcuts</h3>1916          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1917        </div>1918        <div class="peach-shortcuts-help-body">1919          <p class="peach-settings-sub-label">ENTRY VIEW</p>1920          <ul>1921            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1922              <li>1923                <span>{d.label}</span>1924                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1925              </li>1926            ))}1927          </ul>1928          <p class="peach-settings-sub-label">ANYWHERE</p>1929          <ul>1930            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1931              <li>1932                <span>{d.label}</span>1933                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1934              </li>1935            ))}1936          </ul>1937        </div>1938      </div>1939    </div>1940  );1941}