App.tsx

81.7 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 { WhatsNewView } from "./views/WhatsNew";14import { shouldShowWhatsNew } from "../shared/release-notes";15import {16  ONBOARDING_CARD_STORAGE_KEY,17  ONBOARDING_LAST_CARD,18  Onboarding,19} from "./views/Onboarding";2021const ONBOARDING_EXIT_STORAGE_KEY = "peach_onboarding_exit";22import { NotesMode } from "./views/NotesMode";23import { ProCelebration } from "./views/ProCelebration";24import { InitialSyncView } from "./views/InitialSyncView";25import { VaultView, type SortOrder } from "./views/Vault";26import { EntryView } from "./views/Entry";27import { AddView } from "./views/Add";28import { PeachWordmark } from "./components/PeachMark";29import { PasskeyApprovalView } from "./views/PasskeyApproval";30import { detectHomograph, extractDomain, getSecurityOriginDisplay } from "../shared/domain";31import {32  syncIndicator,33  syncIndicatorLabel,34  type SyncOutcomeSummary,35} from "../shared/sync-outcome";36import { popupCopy } from "./copy";37import {38  DEFAULT_BINDINGS,39  formatKeybinding,40  getActiveBindings,41  matchKeybinding,42  SHORTCUT_DESCRIPTORS,43  type Keybinding,44  type ShortcutAction,45} from "../shared/shortcuts";46import { generateTOTP } from "../crypto/totp";4748export { sendMessage } from "../shared/bridge";4950const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));51const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));52const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));53const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));54const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));55const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));56const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));57const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));58const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));59const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));6061type View =62  | "lock"63  | "pro-celebration"64  | "whats-new"65  | "entry"66  | "list"67  | "add"68  | "settings"69  | "pair-device"70  | "import"71  | "export"72  | "health"73  | "trash"74  | "panic"75  | "adopting"76  | "initial-sync"77  | "codex-generate"78  | "codex-restore";79type BootState = "loading" | "ready";8081const INITIAL_SYNC_POLL_MS = 500;82const INITIAL_SYNC_SLOW_MS = 15_000;8384let shellRingAnimation: Animation | null = null;8586export function triggerRing() {87  const shell = document.getElementById("hd-shell");88  if (!shell) return;8990  shellRingAnimation?.cancel();91  shell.dataset.glowing = "true";92  const animation = shell.animate(93    [94      { offset: 0, boxShadow: "var(--copy-shadow)" },95      {96        offset: 0.3,97        boxShadow:98          "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)",99      },100      { offset: 1, boxShadow: "var(--copy-shadow)" },101    ],102    {103      duration: 720,104      easing: "cubic-bezier(0.4, 0, 0.2, 1)",105      fill: "none",106    }107  );108  shellRingAnimation = animation;109  const clearGlow = () => {110    if (shellRingAnimation !== animation) return;111    shellRingAnimation = null;112    delete shell.dataset.glowing;113  };114  animation.onfinish = clearGlow;115  animation.oncancel = clearGlow;116}117118export function triggerPipPulse() {119  const pip = document.querySelector(".peach-status-pip, .pip");120  if (pip) {121    pip.classList.remove("pulse");122    void (pip as HTMLElement).offsetWidth;123    pip.classList.add("pulse");124  }125}126127const ENTRY_TRANSITION_SETTLE_MS = 135;128129export default function App() {130  const [bootState, setBootState] = createSignal<BootState>("loading");131  const [view, setView] = createSignal<View>("lock");132  const [contentPhase, setContentPhase] = createSignal<"enter" | "idle">("enter");133  const [hasVault, setHasVault] = createSignal(false);134  const [onboarded, setOnboarded] = createSignal(true);135  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);136  // The restore source picked before the popup closed (the OS file picker137  // kills it), so reopening resumes the same source form instead of the138  // picker. Read from RESTORE_SOURCE_STORAGE_KEY at boot.139  const [resumeRestoreSource, setResumeRestoreSource] = createSignal<RestoreSource | null>(null);140  // Onboarding remounts whenever it leaves (create/adopt/restore) and comes141  // back. Those flows all exit from the final card, so resume there — a fresh142  // install's first mount stays at 0.143  const [onboardingCardAtExit, setOnboardingCardAtExit] = createSignal(0);144  const [entries, setEntries] = createSignal<VaultEntry[]>([]);145  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);146  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);147148  // Rare device-trust alerts stay visible; routine entry sync is silent.149  interface SyncAlert {150    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";151    entryId: string;152    entryTitle: string;153    deviceName: string;154    timestamp: number;155  }156  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);157  // Per-group flip index: which alert within a type-group is currently shown.158  const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});159  async function loadSyncAlerts() {160    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {161      ok: boolean;162      data?: SyncAlert[];163    };164    if (r.ok && (r.data?.length ?? 0) > 0) {165      setSyncAlerts(r.data ?? []);166      // Acknowledge so a crash between read and render doesn't lose them —167      // they remain on screen until the user dismisses each.168      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });169    }170  }171  function dismissAlertGroup(type: string) {172    setSyncAlerts((arr) => arr.filter((a) => a.type !== type));173    setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });174  }175  function flipAlert(type: string, dir: 1 | -1) {176    const group = syncAlerts().filter((a) => a.type === type);177    if (group.length <= 1) return;178    setAlertFlipIdx((m) => {179      const cur = m[type] ?? 0;180      return { ...m, [type]: (cur + dir + group.length) % group.length };181    });182  }183  /** Grouped alert types in display order, each with its alerts. */184  const alertGroups = createMemo(() => {185    const map = new Map<string, SyncAlert[]>();186    for (const a of syncAlerts()) {187      const g = map.get(a.type);188      if (g) g.push(a); else map.set(a.type, [a]);189    }190    return [...map.entries()];191  });192  function syncAlertText(a: SyncAlert): string {193    if (a.type === "DEVICE_REVOKED") {194      return `${a.deviceName} revoked a paired device — review your devices in Settings`;195    }196    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;197  }198  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");199  const [theme, setTheme] = createSignal<"dark" | "light">("dark");200  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");201  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);202  const [lockOnClose, setLockOnClose] = createSignal(false);203  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);204  const [breachMonitoring, setBreachMonitoring] = createSignal(true);205  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);206  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);207  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);208  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);209  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);210  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");211  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");212  // Cached Pro status — synchronous for render paths. Background's213  // GET_LICENSE is async, but render-time reads of isPro() must not block.214  // Refreshed at boot, after activate/deactivate, and whenever the popup215  // re-opens onto a stored license that has changed via another window.216  const [proStatus, setProStatus] = createSignal(false);217  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);218  // When the sync card's pairing button opens the pairing view, deep-link219  // straight into that pairing path instead of the rest screen.220  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");221  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);222  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");223  const [listSearchSeed, setListSearchSeed] = createSignal("");224  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);225  const [pendingCelebration, setPendingCelebration] = createSignal(false);226  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);227  // A page asked to be remembered for an entry it did not match. Pages cannot228  // grow an entry's domain set themselves (PB-26-106), so the background queues229  // the request here and this banner is the confirmation gate.230  const [pendingRememberSite, setPendingRememberSite] = createSignal<{231    entryId: string;232    url: string;233    title: string;234  } | null>(null);235  // True while Panic Step 1 has bounced the user out to Export. When Export's236  // onBack fires we return to Panic instead of Settings so the user keeps the237  // destruction context they came from.238  const [returnToPanic, setReturnToPanic] = createSignal(false);239  // The view to return to when the add/edit view is dismissed. Normally "entry"240  // but "health" when the user arrives via the fix-entry path from Vault Health.241  const [editBackView, setEditBackView] = createSignal<View>("entry");242  const [settingsExiting, setSettingsExiting] = createSignal(false);243  const [showNotes, setShowNotes] = createSignal(false);244  // Topbar sync affordance. Always present: gating it on having a paired device245  // meant it never appeared for the person trying to set pairing up, which is246  // exactly when you reach for it.247  const [syncBusy, setSyncBusy] = createSignal(false);248  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);249  // The indicator light + its spoken-word equivalent. Colour alone is not the250  // signal; the title/aria-label always carries the same claim in English.251  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});252  const [pairedCount, setPairedCount] = createSignal(0);253  const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);254  const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);255  let initialSyncWaitGeneration = 0;256  const syncLight = () =>257    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());258  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());259  async function loadSyncIndicator() {260    const [stateRes, devicesRes] = await Promise.all([261      sendMessage({ type: "GET_SYNC_STATE" }),262      sendMessage({ type: "LIST_PAIRED_DEVICES" }),263    ]);264    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };265    if (s.ok && s.data) setSyncSummary(s.data);266    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };267    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);268  }269270  interface InitialSyncPairedDevice extends InitialSyncDevice {271    pairedAt?: number;272  }273274  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {275    const response = (await sendMessage({276      type: "LIST_PAIRED_DEVICES",277    })) as {278      ok: boolean;279      data?: { devices?: InitialSyncPairedDevice[] };280    };281    return response.ok ? response.data?.devices ?? [] : [];282  }283284  async function resolveInitialSyncDeviceId(): Promise<string | null> {285    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(286      () => null,287    );288    const devices = await listInitialSyncDevices().catch(() => []);289    if (stored && devices.some((device) => device.deviceId === stored)) {290      return stored;291    }292293    // Fresh adoption has exactly one direct source, but choosing the newest row294    // also repairs the marker if storage failed after the pair itself committed.295    const newest = [...devices].sort(296      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),297    )[0];298    if (!newest) return stored;299    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(300      () => undefined,301    );302    return newest.deviceId;303  }304305  async function finishInitialSync(generation: number): Promise<void> {306    if (generation !== initialSyncWaitGeneration) return;307    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);308    setInitialSyncDeviceId(null);309    setInitialSyncSlow(false);310    await refreshProStatus();311312    // A license transferred during pairing intentionally leaves the one-shot313    // celebration pending. Consume it only now: sync readiness → celebration314    // → populated vault, never celebration → temporarily empty vault.315    const celebration = (await sendMessage({316      type: "SHOULD_PLAY_CELEBRATION",317    })) as { ok: boolean; data?: boolean };318    const shouldCelebrate = celebration.ok && celebration.data === true;319    if (shouldCelebrate) {320      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });321    }322323    const opened = await openVault(undefined, shouldCelebrate);324    if (!opened || generation !== initialSyncWaitGeneration) return;325    if (shouldCelebrate) {326      setView("pro-celebration");327      window.setTimeout(() => {328        if (generation === initialSyncWaitGeneration) setView("entry");329      }, 2500);330    }331  }332333  async function beginInitialSyncWait(deviceId: string): Promise<void> {334    const generation = ++initialSyncWaitGeneration;335    setInitialSyncDeviceId(deviceId);336    setInitialSyncSlow(false);337    setView("initial-sync");338    const startedAt = Date.now();339340    // Best effort: the pairing write already wakes the mesh listener, while341    // this trigger covers the key-order case where this receiver is the dialer.342    void sendMessage({343      type: "TRIGGER_SYNC",344      payload: { reason: "foreground" },345    }).catch(() => undefined);346347    while (348      generation === initialSyncWaitGeneration &&349      view() === "initial-sync"350    ) {351      try {352        const devices = await listInitialSyncDevices();353        if (hasCompletedInitialSync(devices, deviceId)) {354          await finishInitialSync(generation);355          return;356        }357      } catch {358        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.359      }360      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {361        setInitialSyncSlow(true);362      }363      await new Promise((resolve) =>364        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),365      );366    }367  }368369  async function retryInitialSync(): Promise<void> {370    const deviceId =371      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());372    if (deviceId) {373      await beginInitialSyncWait(deviceId);374    } else {375      setInitialSyncSlow(true);376    }377  }378379  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);380  // Set on popup boot when peach_recovery_pending flag is found in session381  // storage — instructs LockView to skip the unlock UI and open the recovery382  // words confirmation surface instead. Cleared via handleUnlock once the383  // user has typed the 3 confirmation words.384  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);385386  let contentPhaseTimer: number | undefined;387  // Set when the popup was opened from the inline "Open Peach to unlock" button.388  // handleUnlock() closes the popup after unlock so the user returns to the page.389  let openedForInlineUnlock = false;390391  onCleanup(() => {392    initialSyncWaitGeneration += 1;393  });394395  function applyAccent(name: AccentColorName) {396    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;397    const hex = color.hex;398    document.documentElement.style.setProperty("--peach-accent", hex);399    // Ambient variables derived from the selected accent.400    document.documentElement.style.setProperty("--peach-glow", hex + "2A");401    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");402  }403404  createEffect(() => {405    applyAccent(accentColor());406  });407408  createEffect(() => {409    document.documentElement.classList.toggle("light", theme() === "light");410    document.body.classList.toggle("light", theme() === "light");411  });412413  createEffect(() => {414    document.documentElement.setAttribute("data-text-size", textSize());415  });416417  createEffect(() => {418    if (reduceMotion()) {419      document.documentElement.setAttribute("data-motion", "reduce");420    } else {421      document.documentElement.removeAttribute("data-motion");422    }423  });424425  // Notes are not a destination of the Entry view; selecting a note opens the426  // notes surface instead (handleSelectEntry). Anything that walks or counts427  // the Entry view's neighbours (counter, prev/next, index) must use this428  // filtered list, otherwise the user can arrow into a note and is stuck —429  // the Entry view can't render a note and the prev/next buttons stop moving.430  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));431432  const selectedIndex = createMemo(() => {433    const currentId = selectedEntry()?.id;434    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;435    return nonNoteEntries().findIndex((entry) => entry.id === currentId);436  });437438  async function applyAccentColor(name: AccentColorName) {439    applyAccent(name);440    setAccentColor(name);441    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });442  }443444  async function applyTheme(t: "dark" | "light") {445    setTheme(t);446    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });447  }448449  async function applyTextSize(size: "small" | "medium" | "large") {450    setTextSize(size);451    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });452  }453454  async function applyReduceMotion(enabled: boolean) {455    setReduceMotion(enabled);456    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });457  }458459  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload460  // small and lets future default updates land for actions the user hasn't461  // touched. Settings sends us the full active map; we filter and store.462  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {463    setShortcutBindings(active);464    const overrides: Record<string, Keybinding> = {};465    for (const action of Object.keys(active) as ShortcutAction[]) {466      const a = active[action];467      const d = DEFAULT_BINDINGS[action];468      const same = a.key === d.key469        && Boolean(a.ctrl)  === Boolean(d.ctrl)470        && Boolean(a.meta)  === Boolean(d.meta)471        && Boolean(a.shift) === Boolean(d.shift)472        && Boolean(a.alt)   === Boolean(d.alt);473      if (!same) overrides[action] = a;474    }475    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });476  }477478  async function applyLockOnClose(enabled: boolean) {479    setLockOnClose(enabled);480    await sendMessage({481      type: "UPDATE_SETTINGS",482      payload: { lockOnClose: enabled },483    });484  }485486  async function applyAutoLockMinutes(minutes: number) {487    setAutoLockMinutes(minutes);488    await sendMessage({489      type: "UPDATE_SETTINGS",490      payload: { autoLockMinutes: minutes },491    });492  }493494  async function applyBreachMonitoring(enabled: boolean) {495    setBreachMonitoring(enabled);496    await sendMessage({497      type: "UPDATE_SETTINGS",498      payload: { breachMonitoring: enabled },499    });500  }501502  // Which onboarding exit flow the user is in (create-vault / restore /503  // adopt). Persisted so closing the popup on one of those screens resumes504  // it directly instead of rewinding to the last carousel card.505  function markOnboardingExit(flow: "create" | "restore" | "adopt") {506    setOnboardingCardAtExit(ONBOARDING_LAST_CARD);507    void storageSet(ONBOARDING_EXIT_STORAGE_KEY, flow).catch(() => {});508    // Backing out of the flow remounts the carousel at this card; keep the509    // persisted card in sync so a later popup close resumes consistently.510    void storageSet(ONBOARDING_CARD_STORAGE_KEY, String(ONBOARDING_LAST_CARD)).catch(() => {});511  }512  function clearOnboardingExit() {513    void storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});514    void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});515    setResumeRestoreSource(null);516  }517518  onMount(async () => {519    // Resolve the active tab in parallel with the unlock/has-vault queries —520    // openVault()'s smart selection picks the entry matching currentTabDomain,521    // so it must be populated before openVault runs. Previously refreshCurrentTab522    // ran after openVault, leaving popups that booted already-unlocked falling523    // back to loadedEntries[0] instead of the domain match.524    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([525      sendMessage({ type: "IS_UNLOCKED" }),526      sendMessage({ type: "HAS_VAULT" }),527      refreshCurrentTab(),528      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),529    ]);530    const unlocked = Boolean(531      (unlockResponse as { ok: boolean; data?: boolean }).data532    );533    const vaultExists = Boolean(534      (vaultResponse as { ok: boolean; data?: boolean }).data535    );536    const shouldCelebrate = Boolean(537      (celebrationResponse as { ok: boolean; data?: boolean }).data538    );539    setHasVault(vaultExists);540    // Onboarding gate — show once on first install, never again. Existing541    // users (vaultExists) are auto-marked onboarded so they skip the flow542    // even on the very first popup open after this feature ships.543    try {544      const onboarded = await storageGet("peach_onboarded");545      const seen = onboarded === "true";546      if (vaultExists && !seen) {547        await storageSet("peach_onboarded", "true");548        await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});549        await storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});550        await storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});551        setOnboarded(true);552      } else {553        setOnboarded(seen);554        if (!seen) {555          // A popup close while the user is in an exit flow (create-vault /556          // restore / adopt) resumes that flow directly — landing back on the557          // carousel one screen earlier reads as losing progress.558          const exit = await storageGet(ONBOARDING_EXIT_STORAGE_KEY).catch(() => null);559          if (exit === "create" || exit === "restore" || exit === "adopt") {560            setOnboardingCardAtExit(ONBOARDING_LAST_CARD);561            setOnboarded(true);562            setStartOnboardingRestore(exit === "restore");563            if (exit === "restore") {564              // The OS file picker kills the action popup mid-restore, so the565              // surface resumes on the source the user had already picked.566              const source = await storageGet(RESTORE_SOURCE_STORAGE_KEY).catch(() => null);567              if (source === "symbols" || source === "codex" || source === "csv") {568                setResumeRestoreSource(source);569              }570            }571            if (exit === "adopt") setView("adopting");572          } else {573            // Otherwise resume mid-onboarding where the user left off instead574            // of rewinding to the opening card.575            const stored = Number(576              await storageGet(ONBOARDING_CARD_STORAGE_KEY).catch(() => null),577            );578            if (579              Number.isInteger(stored) &&580              stored > 0 &&581              stored <= ONBOARDING_LAST_CARD582            ) {583              setOnboardingCardAtExit(stored);584            }585          }586        }587      }588    } catch {589      // storage unavailable — default to onboarded so we never block boot590      setOnboarded(true);591    }592593    // Deep-link: ?restore=peachscript|csv — the detached-window half of the594    // file-picker flow. The action popup dismisses when the OS dialog steals595    // focus, so LockView.detachForFilePicker() reopens this URL in a596    // standalone window that owns the dialog. Routing runs before first597    // render so LockView mounts straight onto the right source form.598    try {599      const restoreRoute = new URLSearchParams(window.location.search).get("restore");600      if (restoreRoute === "peachscript" || restoreRoute === "csv") {601        setOnboarded(true);602        setStartOnboardingRestore(true);603        setResumeRestoreSource(restoreRoute === "peachscript" ? "symbols" : "csv");604      }605    } catch {606      // location.search unavailable — ignore.607    }608609    await Promise.all([restoreSettings(), refreshProStatus()]);610611    const pendingInitialSyncMarker =612      unlocked && vaultExists613        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)614        : null;615    const pendingInitialSyncDeviceId = pendingInitialSyncMarker616      ? await resolveInitialSyncDeviceId()617      : null;618619    // Mark played before any animation so a crash mid-sequence never replays620    // it. A newly adopted receiver deliberately defers this until its first621    // real sync finishes, preserving initial sync → celebration → vault.622    if (shouldCelebrate && !pendingInitialSyncDeviceId) {623      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });624    }625626    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome627    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.628    if (unlocked && vaultExists) {629      void sendMessage({630        type: "TRIGGER_SYNC",631        payload: { reason: "foreground" },632      });633      void loadSyncIndicator();634      // Rare device-trust alerts only; routine entry sync stays quiet.635      void loadSyncAlerts();636    }637638    // If the user created a vault but hasn't yet confirmed their recovery639    // words, route back to the recovery-words screen instead of opening the640    // entries view. The flag lives in chrome.storage.local so it survives641    // popup close while the background owns the session-scoped confirmation642    // exemption. Cleared when confirmation succeeds.643    let recoveryPending = false;644    try {645      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });646      recoveryPending = out.ok === true && out.data === true;647    } catch { /* best-effort */ }648649    // Content UI can ask the background to open this trusted popup either for650    // unlock or at a specific entry. Consume both session-scoped handoffs once.651    let pendingOpenEntryId: string | undefined;652    if (chrome.storage.session) {653      try {654        const s = await chrome.storage.session.get(["peach_inline_unlock", "peach_open_entry"]);655        const pending = s as { peach_inline_unlock?: boolean; peach_open_entry?: string };656        if (pending.peach_inline_unlock) {657          openedForInlineUnlock = true;658        }659        if (typeof pending.peach_open_entry === "string") pendingOpenEntryId = pending.peach_open_entry;660        await chrome.storage.session.remove(["peach_inline_unlock", "peach_open_entry"]);661      } catch { /* best-effort */ }662    }663664    if (recoveryPending && unlocked) {665      // forceRecoveryWords overrides LockView's hasVault gate so the666      // recovery surface renders even though the vault now exists.667      setForceRecoveryWords(true);668      setView("lock");669    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {670      void beginInitialSyncWait(pendingInitialSyncDeviceId);671    } else if (unlocked && vaultExists) {672      await openVault(pendingOpenEntryId, shouldCelebrate);673      if (shouldCelebrate) {674        setView("pro-celebration");675        window.setTimeout(() => setView("entry"), 2500);676      } else if (await shouldShowWhatsNew()) {677        setView("whats-new");678      }679    } else if (shouldCelebrate) {680      setPendingCelebration(true);681    }682683    await refreshPendingPasskey();684685    // Track tab changes so smart sort stays current686    const handleTabActivated = () => { void refreshCurrentTab(); };687    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {688      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();689    };690    try {691      chrome.tabs.onActivated.addListener(handleTabActivated);692      chrome.tabs.onUpdated.addListener(handleTabUpdated);693      onCleanup(() => {694        chrome.tabs.onActivated.removeListener(handleTabActivated);695        chrome.tabs.onUpdated.removeListener(handleTabUpdated);696      });697    } catch {698      // tabs permission may not be available in all contexts699    }700701    setBootState("ready");702703    // Deep-link: ?codex=pdf opens a detached window straight into the704    // Codex restore flow with auto-picked PDF. The action popup can't host705    // a file dialog without dismissing itself, so this is the only way the706    // PDF import path survives. See CodexRestoreView.openPdfPicker().707    try {708      const route = new URLSearchParams(window.location.search).get("codex");709      if (route === "pdf" || route === "restore") {710        setView("codex-restore");711      }712    } catch {713      // location.search unavailable — ignore.714    }715716    // Check for pending session-storage notices from the background.717    if (chrome.storage.session) {718      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as719        Record<string, { feature?: string } | undefined>;720      if (session.pendingProGate?.feature) {721        await chrome.storage.session.remove("pendingProGate");722        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);723        setSettingsInitialSection("license");724        setView("settings");725      } else if (session.pendingProNotice?.feature) {726        await chrome.storage.session.remove("pendingProNotice");727        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });728      }729      const remembered = (await chrome.storage.session.get("pendingRememberSite")) as {730        pendingRememberSite?: { entryId?: unknown; url?: unknown };731      };732      const request = remembered.pendingRememberSite;733      if (734        typeof request?.entryId === "string" &&735        typeof request.url === "string"736      ) {737        const entry = await sendMessage({ type: "GET_ENTRIES" });738        const match = entry.ok739          ? (entry.data as Array<{ id: string; title?: string }> | undefined)?.find(740              (candidate) => candidate.id === request.entryId,741            )742          : undefined;743        if (match) {744          let host = request.url;745          try { host = new URL(request.url).hostname; } catch { /* keep raw */ }746          setPendingRememberSite({ entryId: request.entryId, url: request.url, title: match.title ?? host });747        } else {748          await chrome.storage.session.remove("pendingRememberSite");749        }750      }751    }752753    // Warm the lazy-module cache so the Suspense fallback never shows for754    // locally-bundled extension views. Without this, the first navigation to755    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which756    // covers the shell and absorbs clicks on the header.757    void Promise.all([758      import("./views/Settings").catch(() => {}),759      import("./views/Import").catch(() => {}),760      import("./views/Export").catch(() => {}),761      import("./views/Health").catch(() => {}),762      import("./views/TrashView").catch(() => {}),763    ]);764765    // Lock-on-close via a persistent port. sendMessage in pagehide is766    // unreliable — the popup context tears down before the message lands.767    // The SW's onConnect listener locks when this port disconnects.768    let popupPort: chrome.runtime.Port | null = null;769    try {770      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect771      // listener accepts the "popup-" prefix; the random suffix is defence in772      // depth against a port named exactly "popup" from anything but our popup.773      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });774    } catch { /* extension context invalidated — ignore */ }775    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });776777    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale778    // entries instead of waiting for the next GET_ENTRIES round-trip.779    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {780      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();781      if (msg?.type === "SYNC_STATE_CHANGED") {782        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);783      }784      if (msg?.type === "PRO_GATE_TRIGGERED") {785        setUpgradeHighlight(msg.payload?.feature ?? null);786        setSettingsInitialSection("license");787        setView("settings");788      }789    };790    chrome.runtime.onMessage.addListener(handleRuntimeMessage);791    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));792793    // Action handlers — keyed by ShortcutAction. The dispatcher below tests794    // each binding against the event and runs the matching handler. New795    // shortcuts only need an entry here; the binding is data, not code.796    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {797      copy_password: () => {798        const entry = selectedEntry();799        if (entry?.password) void popupCopy(800          entry.password,801          "Password",802          entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,803        ).then((ok) => { if (ok) triggerRing(); });804      },805      copy_username: () => {806        const entry = selectedEntry();807        if (entry?.username) void popupCopy(808          entry.username,809          "Username",810          entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,811        ).then((ok) => { if (ok) triggerRing(); });812      },813      copy_totp: () => {814        const entry = selectedEntry();815        if (!entry?.totp) return;816        try {817          const { code } = generateTOTP(818            entry.totp,819            entry.totpAlgorithm,820            entry.totpDigits,821            entry.totpPeriod,822          );823          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });824        } catch { /* invalid TOTP secret — silent */ }825      },826      new_entry: () => handleAdd(),827      edit_entry: () => {828        const entry = selectedEntry();829        // Passkey-only entries have nothing user-editable in the Add view; the830        // passkey credential itself is opaque. Skip the edit action for them.831        if (!entry || isPasskeyOnly(entry)) return;832        setEditEntry(entry);833        setView("add");834      },835      delete_entry: () => {836        if (selectedEntry()) void handleDelete();837      },838      lock_vault: () => { void handleHeaderLock(); },839      search: () => openList(),840      nav_prev: () => navigate(-1),841      nav_next: () => navigate(1),842      jump_vault: () => setView("entry"),843      jump_settings: () => setView("settings"),844      show_help: () => setShowShortcutsHelp(true),845    };846847    // Actions that are MEANINGFUL only on the entry-detail view. Outside848    // that scope the binding is dormant — pressing C while on Settings849    // does nothing rather than awkwardly copying from a now-stale entry.850    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([851      "copy_password", "copy_username", "copy_totp",852      "edit_entry", "delete_entry", "nav_prev", "nav_next",853    ]);854855    const handleGlobalKeydown = (e: KeyboardEvent) => {856      const v = view();857      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"858        || (e.target as HTMLElement)?.tagName === "TEXTAREA"859        || (e.target as HTMLElement)?.isContentEditable;860      const isPrintableSearchKey =861        e.key.length === 1 &&862        !e.ctrlKey &&863        !e.metaKey &&864        !e.altKey;865866      // No shortcuts while a full-screen surface owns the whole viewport:867      // the lock screen, the post-pairing readiness sequence, or the Pro868      // celebration. Without this the lock screen is at the mercy of whatever869      // single-key binding is active — e.g. typing "n" in a password that870      // slips out of focus triggers `new_entry` and escapes the lock screen.871      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;872873      // Help dialog: Escape closes it; eat the keypress so it doesn't874      // also navigate away from the underlying view.875      if (showShortcutsHelp()) {876        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }877        return;878      }879880      // ── Escape — fixed binding (not user-customizable) ───────881      if (e.key === "Escape") {882        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }883        if (v === "list") { setView("entry"); return; }884        if (v === "settings" || v === "add") { handleBack(); return; }885        if (v === "import" || v === "health") { setView("settings"); return; }886        if (v === "export") { handleExportBack(); return; }887        if (v === "pair-device") { setView("settings"); return; }888      }889890      // Bindings-driven dispatch. Single-key letter bindings without891      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is892      // inside an input, so users can type into search/forms normally.893      const bindings = shortcutBindings();894      for (const action of Object.keys(bindings) as ShortcutAction[]) {895        const binding = bindings[action];896        if (!matchKeybinding(e, binding)) continue;897        // Single-key letter bindings need the input-focus guard. Bindings898        // with any modifier are safe — Ctrl+L doesn't conflict with typing.899        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;900        if (!hasMod && binding.key.length === 1 && inInput) return;901        if (ENTRY_SCOPED.has(action) && v !== "entry") return;902        e.preventDefault();903        SHORTCUT_HANDLERS[action]?.();904        return;905      }906907      // Type-to-search: in entry view, any printable key not consumed by a908      // shortcut above primes the list search seed and opens the list.909      // Kept outside the bindings table because it's a behavior, not a910      // discrete action — every printable character can trigger it.911      if (v === "entry" && !inInput && isPrintableSearchKey) {912        e.preventDefault();913        primeListSearch(e.key);914        return;915      }916    };917    window.addEventListener("keydown", handleGlobalKeydown);918    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));919920    const handleStorageChanged = (921      changes: Record<string, chrome.storage.StorageChange>,922      areaName: string923    ) => {924      if (areaName !== "session") return;925      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {926        return;927      }928      void refreshPendingPasskey();929    };930    chrome.storage.onChanged.addListener(handleStorageChanged);931    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));932  });933934  async function refreshCurrentTab() {935    try {936      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });937      const url = tab?.url ?? tab?.pendingUrl ?? "";938      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");939      // Skip extension/internal URLs — adding chrome://, about:, or940      // chrome-extension:// to a vault entry is never what the user wants.941      const isWebUrl = /^https?:\/\//i.test(url);942      setCurrentTabUrl(isWebUrl ? url : "");943    } catch {944      setCurrentTabDomain("");945      setCurrentTabUrl("");946    }947  }948949  async function refreshPendingPasskey() {950    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });951    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);952  }953954  async function refreshProStatus() {955    const res = await sendMessage({ type: "GET_LICENSE" });956    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;957    setProStatus(Boolean(data?.valid && data?.plan === "pro"));958  }959960  async function restoreSettings() {961    const res = await sendMessage({ type: "GET_SETTINGS" });962    const s = (res as { ok: boolean; data?: any }).data ?? {};963    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {964      setAccentColor(s.accentColor as AccentColorName);965    }966    setTheme(s.theme === "light" ? "light" : "dark");967    if (s.textSize === "small" || s.textSize === "large") {968      setTextSize(s.textSize);969    } else {970      setTextSize("medium");971    }972    setReduceMotion(s.reduceMotion === true);973    setLockOnClose(s.lockOnClose === true);974    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);975    setBreachMonitoring(s.breachMonitoring !== false);976    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);977    setShortcutBindings(getActiveBindings(s.shortcuts));978  }979980  async function applyTrashRetention(days: number) {981    setTrashRetentionDays(days);982    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });983  }984985  function primeListSearch(seed: string) {986    setListSearchSeed(seed);987    setListSearchSeedNonce((value) => value + 1);988    openList();989  }990991  // Returns null when it detected a dead service worker and triggered handleLock().992  // Callers that need to abort (e.g. openVault) check for null rather than relying993  // on view() state, which may already be "lock" during normal startup flows.994  async function loadEntries(): Promise<VaultEntry[] | null> {995    const response = await sendMessage({ type: "GET_ENTRIES" });996    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };997998    // If the service worker was killed and restarted (MV3 workers sleep), the999    // vault will be locked again — or the worker may not respond at all.1000    // In either case, send the user to the lock screen rather than silently1001    // showing an empty vault (which looks like data loss).1002    if (!res.ok) {1003      if (1004        res.error === "vault_locked" ||1005        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1006        (typeof res.error === "string" && res.error.includes("locked"))1007      ) {1008        handleLock();1009        return null; // signal emergency lock to callers1010      }1011      return [];1012    }10131014    const loadedEntries = res.data ?? [];1015    setEntries(loadedEntries);10161017    const currentId = selectedEntry()?.id;1018    if (currentId) {1019      setSelectedEntry(1020        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1021      );1022    }10231024    return loadedEntries;1025  }10261027  async function openVault(preferredEntryId?: string, skipViewSet = false) {1028    // Purge expired trash entries on each vault open1029    const retDays = trashRetentionDays();1030    if (retDays > 0) {1031      void sendMessage({1032        type: "PURGE_EXPIRED_TRASH",1033        payload: { retentionMs: retDays * 86_400_000 },1034      });1035    }10361037    const loadedEntries = await loadEntries();10381039    // null means loadEntries() triggered an emergency lock (service worker died).1040    // Don't override it by setting view back to "entry" with an empty vault.1041    if (loadedEntries === null) return false;10421043    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1044    let nextSelectedEntry: VaultEntry | null = null;1045    if (preferredEntryId) {1046      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1047    }1048    if (!nextSelectedEntry) {1049      const tabDomain = currentTabDomain();1050      if (tabDomain) {1051        nextSelectedEntry = loadedEntries.find((e) => {1052          if (e.type === "login") {1053            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1054            for (const extra of e.additionalUrls ?? []) {1055              if ((extractDomain(extra) ?? "") === tabDomain) return true;1056            }1057            return false;1058          }1059          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1060          return false;1061        }) ?? null;1062      }1063    }1064    nextSelectedEntry ??= pickNavigable(loadedEntries);10651066    setSelectedEntry(nextSelectedEntry);1067    setEditEntry(undefined);1068    setContentPhase("enter");1069    queueContentIdle();1070    if (!skipViewSet) setView("entry");1071    return true;1072  }10731074  async function handleUnlock() {1075    // If the user previously created a vault but hadn't yet confirmed their1076    // recovery words (and the browser was closed before they could), the1077    // the background-owned recovery-pending state is still set. Re-route1078    // back to the recovery surface so they finish the confirmation step1079    // before reaching the entries view — the words can be re-derived now1080    // that the vault is unlocked again.1081    let recoveryPending = false;1082    try {1083      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });1084      recoveryPending = out.ok === true && out.data === true;1085    } catch { /* best-effort */ }1086    if (recoveryPending) {1087      setForceRecoveryWords(true);1088      setView("lock");1089      triggerPipPulse();1090      await restoreSettings();1091      return;1092    }1093    setHasVault(true);1094    triggerPipPulse();1095    await restoreSettings();1096    const celebrating = pendingCelebration();1097    if (celebrating) {1098      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1099      setPendingCelebration(false);1100    }1101    await openVault(undefined, celebrating);1102    if (celebrating) {1103      setView("pro-celebration");1104      window.setTimeout(() => setView("entry"), 2500);1105    } else if (!openedForInlineUnlock && await shouldShowWhatsNew()) {1106      setView("whats-new");1107    }1108    // Popup was opened from the inline "Open Peach to unlock" button — close it1109    // now so the user lands back on the page with the autofill selector ready.1110    if (openedForInlineUnlock) {1111      openedForInlineUnlock = false;1112      window.close();1113    }1114  }11151116  function handleSelectEntry(entry: VaultEntry) {1117    if (entry.type === "note") {1118      setOpenNoteId(entry.id);1119      setShowNotes(true);1120      return;1121    }1122    setSelectedEntry(entry);1123    setContentPhase("enter");1124    queueContentIdle();1125    setView("entry");1126  }11271128  function handleAdd() {1129    setEditEntry(undefined);1130    setView("add");1131  }11321133  async function handleDelete() {1134    const entry = selectedEntry();1135    if (!entry) return;1136    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1137    const loadedEntries = await loadEntries() ?? [];1138    setSelectedEntry(pickNavigable(loadedEntries));1139    setView("entry");1140  }11411142  async function handleDeleteMany(ids: string[]) {1143    for (const id of ids) {1144      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1145    }1146    const loadedEntries = await loadEntries() ?? [];1147    // If the currently selected entry was among the deleted, move to first1148    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1149    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1150  }11511152  async function handleSave(savedEntry?: VaultEntry) {1153    await openVault(savedEntry?.id);1154  }11551156  function handleBack() {1157    const dest = editBackView();1158    setEditBackView("entry");1159    setEditEntry(undefined);1160    setView(dest);1161  }11621163  function handleExportBack() {1164    if (returnToPanic()) {1165      setReturnToPanic(false);1166      setView("panic");1167      return;1168    }1169    setView("settings");1170  }11711172  function handleLock() {1173    setEntries([]);1174    setSelectedEntry(null);1175    setEditEntry(undefined);1176    setContentPhase("idle");1177    setView("lock");1178  }11791180  function handleHeaderLock() {1181    // Lock the UI immediately — do not wait for the service worker. If the SW1182    // is dead or slow, the 5s sendMessage timeout would create a dead-click1183    // window. The SW will lock on its next wake regardless.1184    handleLock();1185    void sendMessage({ type: "LOCK" });1186  }11871188  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1189  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1190  // the trigger's own reply.1191  async function handleHeaderSync(): Promise<void> {1192    if (syncBusy()) return;1193    setSyncBusy(true);1194    setSyncFlash(null);1195    try {1196      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1197      let state: SyncOutcomeSummary = { status: "syncing" };1198      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1199        await new Promise((r) => setTimeout(r, 250));1200        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1201          ok: boolean;1202          data?: SyncOutcomeSummary;1203        };1204        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1205      }1206      setSyncSummary(state);1207      setSyncFlash(state.status === "error" ? "error" : "ok");1208      await loadSyncAlerts();1209      await loadEntries();1210      await loadSyncIndicator();1211    } catch {1212      setSyncSummary({ status: "error", outcome: "run_failed" });1213      setSyncFlash("error");1214    } finally {1215      setSyncBusy(false);1216      setTimeout(() => setSyncFlash(null), 2_000);1217    }1218  }12191220  function navigate(dir: number) {1221    const navigable = nonNoteEntries();1222    if (navigable.length === 0) return;1223    const currentIndex = selectedIndex();1224    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1225    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1226    setSelectedEntry(navigable[nextIndex]);1227    setContentPhase("enter");1228    queueContentIdle();1229  }12301231  /**1232   * The Entry view's selection invariant: never select a note. Notes are a1233   * separate surface (handleSelectEntry opens the notes view), so any code path1234   * that picks a default — vault open, post-delete, refresh — must skip them1235   * and return null if the only entries are notes.1236   */1237  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1238    return list.find((e) => e.type !== "note") ?? null;1239  }12401241  function openList() {1242    setView("list");1243  }12441245  function openHealth() {1246    setEditEntry(undefined);1247    setView("health");1248  }12491250  function handleOpenFileImport() {1251    setRestoreView("file");1252  }12531254  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12551256  function handleFixEntry(entry: VaultEntry) {1257    setSelectedEntry(entry);1258    // Passkey-only entries have no editable surface — drop into view mode1259    // instead of opening the Add editor.1260    if (isPasskeyOnly(entry)) {1261      setView("entry");1262      return;1263    }1264    setEditBackView(view()); // preserve caller view so back returns here1265    setEditEntry(entry);1266    setView("add");1267  }12681269  const isLockedView = () => view() === "lock" || view() === "adopting";12701271  async function handleAdoptionDone() {1272    await storageSet("peach_onboarded", "true").catch(() => {});1273    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1274    clearOnboardingExit();1275    setOnboarded(true);1276    setHasVault(true);1277    setView("initial-sync");1278    // The background applies a Pro license and persists the source-device1279    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1280    // celebration pending until that exact peer records a completed sync.1281    await refreshProStatus();1282    const deviceId = await resolveInitialSyncDeviceId();1283    if (deviceId) {1284      void beginInitialSyncWait(deviceId);1285    } else {1286      // Pairing completion without a durable peer row should be impossible.1287      // Stay on the honest waiting surface and expose retry instead of falling1288      // through to an empty vault.1289      setInitialSyncSlow(true);1290    }1291  }12921293  async function handleApprovePendingPasskey() {1294    const pending = pendingPasskey();1295    if (!pending) return;1296    if (pending.browser === "firefox" && pending.type === "create") {1297      // Firefox path: popup itself runs navigator.credentials.create. The1298      // background never approved/rejected anything — it just stashed1299      // intent. After the popup-driven flow resolves (success or cancel),1300      // clear the pending key so the popup doesn't re-show this on next open.1301      const { createFirefoxPasskey } = await import("./firefox-passkey");1302      const result = await createFirefoxPasskey(pending);1303      if (!result.ok) {1304        console.warn("Peach Firefox passkey create failed:", result.error);1305      }1306      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1307      setPendingPasskey(null);1308      void loadEntries();1309      window.close();1310      return;1311    }1312    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1313    window.close();1314  }13151316  async function handleDenyPendingPasskey() {1317    const pending = pendingPasskey();1318    if (!pending) return;1319    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1320    window.close();1321  }13221323  function queueContentIdle(after?: () => void) {1324    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1325    contentPhaseTimer = window.setTimeout(() => {1326      setContentPhase("idle");1327      after?.();1328    }, ENTRY_TRANSITION_SETTLE_MS);1329  }13301331  return (1332    <div class="popup-root peach-theme">1333      <Show when={bootState() === "ready"}>1334        <Show1335          when={!pendingPasskey()}1336          fallback={1337            <PasskeyApprovalView1338              type={pendingPasskey()!.type}1339              rpName={pendingPasskey()!.rpName}1340              rpId={pendingPasskey()!.rpId}1341              userName={pendingPasskey()!.userName}1342              userDisplayName={pendingPasskey()!.userDisplayName}1343              onApprove={handleApprovePendingPasskey}1344              onDeny={handleDenyPendingPasskey}1345            />1346          }1347        >1348          <Show1349            when={!isLockedView()}1350            fallback={1351              <Show1352                when={view() !== "adopting"}1353                fallback={1354                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1355                    <AdoptVaultView1356                      onCancel={() => {1357                        clearOnboardingExit();1358                        setOnboarded(false);1359                        setView("lock");1360                      }}1361                      onDone={handleAdoptionDone}1362                    />1363                  </Suspense>1364                }1365              >1366                <Show1367                  when={onboarded() || hasVault()}1368                  fallback={1369                    <Onboarding1370                      initialCard={onboardingCardAtExit()}1371                      onComplete={() => {1372                        markOnboardingExit("create");1373                        setStartOnboardingRestore(false);1374                        setOnboarded(true);1375                      }}1376                      onRestore={() => {1377                        markOnboardingExit("restore");1378                        setStartOnboardingRestore(true);1379                        setOnboarded(true);1380                      }}1381                      onAdopt={() => {1382                        markOnboardingExit("adopt");1383                        setStartOnboardingRestore(false);1384                        setOnboarded(true);1385                        setView("adopting");1386                      }}1387                    />1388                  }1389                >1390                  <LockView1391                    hasVault={hasVault()}1392                    ready={bootState() === "ready"}1393                    isPro={proStatus()}1394                    forceRecoveryWords={forceRecoveryWords()}1395                    initialRestore={startOnboardingRestore()}1396                    initialRestoreSource={resumeRestoreSource() ?? undefined}1397                    onUnlock={() => {1398                      // RecoveryWordDisplay clears the storage flag before1399                      // calling onDone, so handleUnlock will see no pending1400                      // confirmation and proceed through the normal path.1401                      if (forceRecoveryWords()) setForceRecoveryWords(false);1402                      // The create/restore flow is done — a lock later in this1403                      // window must show the unlock screen, not re-enter the1404                      // onboarding restore surface.1405                      setStartOnboardingRestore(false);1406                      setResumeRestoreSource(null);1407                      void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1408                      return handleUnlock();1409                    }}1410                    onBackToOnboarding={1411                      !hasVault()1412                        ? () => {1413                            // Deliberately rewinding to the carousel — the exit1414                            // flow must not reclaim the next popup open.1415                            clearOnboardingExit();1416                            setStartOnboardingRestore(false);1417                            setOnboarded(false);1418                          }1419                        : undefined1420                    }1421                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1422                  />1423                </Show>1424              </Show>1425            }1426          >1427            <Show1428              when={1429                view() !== "pro-celebration" &&1430                view() !== "initial-sync" &&1431                view() !== "whats-new"1432              }1433              fallback={1434                <Show1435                  when={view() === "initial-sync"}1436                  fallback={1437                    <Show1438                      when={view() === "whats-new"}1439                      fallback={<ProCelebration />}1440                    >1441                      <WhatsNewView onContinue={() => setView("entry")} />1442                    </Show>1443                  }1444                >1445                  <InitialSyncView1446                    slow={initialSyncSlow()}1447                    onRetry={() => void retryInitialSync()}1448                  />1449                </Show>1450              }1451            >1452            <section1453              id="hd-shell"1454              class="peach-shell peach-theme"1455              data-surface="extension"1456            >1457            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1458              <PeachWordmark unlocked />1459              <div class="peach-chrome-actions">1460                <button1461                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1462                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1463                  aria-label="Notes"1464                  title="Notes"1465                >1466                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1467                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1468                    <line x1="4" y1="5" x2="10" y2="5" />1469                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1470                    <line x1="4" y1="10" x2="7" y2="10" />1471                  </svg>1472                </button>1473                <button1474                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1475                    classList={{1476                      "is-syncing": syncBusy(),1477                      "is-ok": syncFlash() === "ok",1478                      "is-error": syncFlash() === "error",1479                    }}1480                    onClick={() => void handleHeaderSync()}1481                    disabled={syncBusy()}1482                    aria-label={`Sync now. ${syncLabel()}`}1483                    title={syncLabel()}1484                  >1485                    <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">1486                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1487                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1488                      <path d="M2.6 1v2.4h2.4" />1489                      <path d="M11.4 13v-2.4H9" />1490                    </svg>1491                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1492                  </button>1493                <button1494                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1495                  onClick={() => setView("settings")}1496                  aria-label="Settings"1497                >1498                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1499                    <path1500                      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"1501                      stroke="currentColor"1502                      stroke-width="0.9"1503                    />1504                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1505                  </svg>1506                </button>1507                <button1508                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1509                  onClick={handleAdd}1510                  aria-label="New entry"1511                >1512                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1513                    <path d="M5.5 1v9M1 5.5h9" />1514                  </svg>1515                </button>1516                <button1517                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1518                  onClick={() => void handleHeaderLock()}1519                  aria-label="Lock vault"1520                >1521                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1522                    <path1523                      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"1524                      stroke="currentColor"1525                      stroke-width="1"1526                      stroke-linecap="round"1527                    />1528                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1529                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1530                  </svg>1531                </button>1532              </div>1533            </header>15341535            <Show when={pendingProNotice() !== null}>1536              <div class="peach-pro-notice-banner">1537                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1538                <button1539                  class="peach-pro-notice-link"1540                  onClick={() => {1541                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1542                    setSettingsInitialSection("license");1543                    setView("settings");1544                    setPendingProNotice(null);1545                  }}1546                >1547                  Learn more →1548                </button>1549                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1550              </div>1551            </Show>15521553            <Show when={pendingRememberSite()}>1554              {(request) => {1555                const origin = getSecurityOriginDisplay(request().url);1556                const originLabel = detectHomograph(origin) ? `⚠ ${origin}` : origin;1557                return (1558                  <div class="peach-pro-notice-banner">1559                    <span>Also use “{request().title}” on {originLabel}?</span>1560                    <button1561                      class="peach-pro-notice-link"1562                      onClick={async () => {1563                        await sendMessage({1564                          type: "ADD_ADDITIONAL_URL",1565                          payload: { id: request().entryId, url: request().url },1566                        });1567                        await chrome.storage.session.remove("pendingRememberSite");1568                        setPendingRememberSite(null);1569                      }}1570                    >1571                      Add1572                    </button>1573                    <button1574                      class="peach-pro-notice-close"1575                      onClick={async () => {1576                        await chrome.storage.session.remove("pendingRememberSite");1577                        setPendingRememberSite(null);1578                      }}1579                      aria-label="Dismiss"1580                    >1581                      ✕1582                    </button>1583                  </div>1584                );1585              }}1586            </Show>15871588            <div class="peach-shell-body">1589              <div class="peach-shell-veil"></div>1590              <div class="peach-content-frame" data-content-phase={contentPhase()}>1591                <EntryView1592                  entry={selectedEntry()}1593                  currentTabUrl={currentTabUrl()}1594                  entries={entries()}1595                  isPro={proStatus()}1596                  onDelete={handleDelete}1597                  onFieldSaved={() => void loadEntries()}1598                  onEscape={() => { setView("list"); }}1599                  onProGate={(feature) => {1600                    setUpgradeHighlight(feature);1601                    setSettingsInitialSection("license");1602                    setView("settings");1603                  }}1604                />1605              </div>16061607              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1608                <div class="peach-search-bar">1609                  <span class="peach-search-icon">1610                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1611                      <circle cx="5.5" cy="5.5" r="3.75" />1612                      <path d="M8.75 8.75L11.5 11.5" />1613                    </svg>1614                  </span>1615                  <input1616                    class="peach-search-input"1617                    placeholder="search vault..."1618                    autocomplete="off"1619                    aria-label="Search vault entries"1620                    onClick={openList}1621                    onFocus={openList}1622                    readOnly1623                  />1624                  <div class="peach-search-meta">1625                    <span class="peach-search-counter">1626                      {nonNoteEntries().length > 01627                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1628                        : "0 entries"}1629                    </span>1630                    <span class="peach-divider"></span>1631                    <button1632                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1633                      onClick={() => navigate(-1)}1634                      aria-label="Previous entry"1635                      disabled={nonNoteEntries().length === 0}1636                    >1637                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1638                        <path d="M5 1L1 5.5L5 10" />1639                      </svg>1640                    </button>1641                    <button1642                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1643                      onClick={() => navigate(1)}1644                      aria-label="Next entry"1645                      disabled={nonNoteEntries().length === 0}1646                    >1647                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1648                        <path d="M1 1L5 5.5L1 10" />1649                      </svg>1650                    </button>1651                  </div>1652                </div>1653              </section>1654            </div>16551656            {/* Rare device-trust alerts; normal sync changes are silent. */}1657            <Show when={alertGroups().length > 0}>1658              <div class="peach-sync-alerts">1659                <For each={alertGroups()}>1660                  {([type, group]) => {1661                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1662                    return (1663                      <div class="peach-sync-alert">1664                        <Show when={group.length > 1}>1665                          <button1666                            class="peach-sync-alert-flip"1667                            type="button"1668                            aria-label="Previous"1669                            onClick={() => flipAlert(type, -1)}1670                          >‹</button>1671                        </Show>1672                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1673                        <Show when={group.length > 1}>1674                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1675                          <button1676                            class="peach-sync-alert-flip"1677                            type="button"1678                            aria-label="Next"1679                            onClick={() => flipAlert(type, 1)}1680                          >›</button>1681                        </Show>1682                        <button1683                          class="peach-sync-alert-dismiss"1684                          type="button"1685                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1686                          onClick={() => dismissAlertGroup(type)}1687                        >×</button>1688                      </div>1689                    );1690                  }}1691                </For>1692              </div>1693            </Show>16941695            <Show when={view() === "list"}>1696              <VaultView1697                entries={entries()}1698                selectedEntryId={selectedEntry()?.id}1699                currentTabDomain={currentTabDomain()}1700                sortOrder={sortOrder()}1701                searchSeed={listSearchSeed()}1702                searchSeedNonce={listSearchSeedNonce()}1703                onSelectEntry={handleSelectEntry}1704                onSortOrderChange={setSortOrder}1705                onAdd={handleAdd}1706                onClose={() => setView("entry")}1707                onOpenTrash={() => setView("trash")}1708                onDeleteMany={handleDeleteMany}1709              />1710            </Show>1711            <Show when={view() === "settings" || settingsExiting()}>1712              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1713                <SettingsView1714                  entriesCount={entries().length}1715                  breachMonitoring={breachMonitoring()}1716                  lockOnClose={lockOnClose()}1717                  autoLockMinutes={autoLockMinutes()}1718                  trashRetentionDays={trashRetentionDays()}1719                  theme={theme()}1720                  accentColor={accentColor()}1721                  textSize={textSize()}1722                  reduceMotion={reduceMotion()}1723                  isPro={proStatus()}1724                  initialSection={settingsInitialSection()}1725                  upgradeHighlight={upgradeHighlight()}1726                  isExiting={settingsExiting()}1727                  onBreachMonitoringChange={applyBreachMonitoring}1728                  onLockOnCloseChange={applyLockOnClose}1729                  onAutoLockMinutesChange={applyAutoLockMinutes}1730                  onTrashRetentionChange={applyTrashRetention}1731                  onThemeChange={applyTheme}1732                  onAccentChange={applyAccentColor}1733                  onTextSizeChange={applyTextSize}1734                  onReduceMotionChange={applyReduceMotion}1735                  shortcuts={shortcutBindings()}1736                  onShortcutsChange={applyShortcuts}1737                  onLicenseChange={async () => {1738                    // After activation/deactivation: refresh Pro status,1739                    // re-load entries (defensive — signal state can drift if1740                    // the SW briefly restarts during the verify+save round-trip),1741                    // and replay the Pro celebration if this is the first time1742                    // a valid Pro license is seen on this device.1743                    await refreshProStatus();1744                    void loadEntries();1745                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1746                    if ((should as { ok: boolean; data?: boolean }).data === true) {1747                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1748                      setView("pro-celebration");1749                      window.setTimeout(() => setView("settings"), 2500);1750                    }1751                  }}1752                  onBack={() => {1753                    setSettingsExiting(true);1754                    window.setTimeout(() => {1755                      setSettingsExiting(false);1756                      setSettingsInitialSection(null);1757                      setUpgradeHighlight(null);1758                      handleBack();1759                    }, 200);1760                  }}1761                  onImport={() => setView("import")}1762                  onExport={() => setView("export")}1763                  onBreachCheckDone={loadEntries}1764                  onOpenHealth={openHealth}1765                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1766                  onOpenFileImport={handleOpenFileImport}1767                  onOpenPanic={() => setView("panic")}1768                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1769                  onOpenCodexRestore={() => setView("codex-restore")}1770                  onCardChange={setSettingsActiveCard}1771                  onProGate={(feature) => {1772                    setUpgradeHighlight(feature);1773                    setSettingsInitialSection("license");1774                  }}1775                />1776              </Suspense>1777            </Show>1778            <Show when={view() === "codex-generate"}>1779              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1780                <CodexGenerateView1781                  isPro={proStatus()}1782                  onBack={() => setView("settings")}1783                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1784                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1785                  onVaultLocked={() => handleLock()}1786                />1787              </Suspense>1788            </Show>1789            <Show when={view() === "codex-restore"}>1790              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1791                <CodexRestoreView1792                  onBack={() => setView("lock")}1793                  onRestoreSuccess={async () => {1794                    // After restore the vault is unlocked; refresh entries1795                    // and route to the main vault list. handleUnlock is the1796                    // canonical post-unlock setup path.1797                    await handleUnlock();1798                  }}1799                />1800              </Suspense>1801            </Show>1802            <Show when={view() === "pair-device"}>1803              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1804                <PairDeviceView1805                  isPro={proStatus()}1806                  onProChanged={() => { void refreshProStatus(); }}1807                  onBack={() => setView("settings")}1808                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1809                />1810              </Suspense>1811            </Show>1812            <Show when={view() === "add"}>1813              <AddView1814                entry={editEntry()}1815                entries={entries()}1816                onBack={handleBack}1817                onSave={handleSave}1818              />1819            </Show>1820            <Show when={view() === "import"}>1821              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1822                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1823              </Suspense>1824            </Show>1825            <Show when={view() === "export"}>1826              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1827                <ExportView onBack={handleExportBack} />1828              </Suspense>1829            </Show>1830            <Show when={view() === "panic"}>1831              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1832                <PanicView1833                  onCancel={() => setView("settings")}1834                  onOpenExport={() => {1835                    setReturnToPanic(true);1836                    setView("export");1837                  }}1838                  onDestroyed={async () => {1839                    // Fresh onboarding start after a destroy — don't let the1840                    // resume markers land the user mid-carousel.1841                    setOnboardingCardAtExit(0);1842                    void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1843                    clearOnboardingExit();1844                    setEntries([]);1845                    setSelectedEntry(null);1846                    setEditEntry(undefined);1847                    setHasVault(false);1848                    setOnboarded(false);1849                    setProStatus(false);1850                    setPendingPasskey(null);1851                    setUpgradeHighlight(null);1852                    setSettingsInitialSection(null);1853                    setPendingProNotice(null);1854                    setPendingCelebration(false);1855                    setReturnToPanic(false);1856                    setContentPhase("idle");1857                    setView("lock");1858                  }}1859                />1860              </Suspense>1861            </Show>1862            {/* Health stays mounted while editing an entry from it so1863                computeReused() doesn't rerun on every cancel/back. */}1864            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1865              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1866                <HealthView1867                  entries={entries()}1868                  isPro={proStatus()}1869                  onFixEntry={handleFixEntry}1870                  onBack={() => setView("settings")}1871                  onRefresh={loadEntries}1872                  hidden={view() !== "health"}1873                />1874              </Suspense>1875            </Show>1876            <Show when={view() === "trash"}>1877              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1878                <TrashView1879                  onBack={() => setView("list")}1880                  onRestored={() => void loadEntries()}1881                />1882              </Suspense>1883            </Show>1884            <Show when={showNotes()}>1885              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1886                <NotesMode1887                  notes={entries().filter((e) => e.type === "note")}1888                  initialNoteId={openNoteId()}1889                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1890                  onNoteListChanged={() => void loadEntries()}1891                />1892              </div>1893            </Show>1894            <Show when={restoreView() === "file"}>1895              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1896                <ImportView1897                  mode="onboarding"1898                  replacesExistingVault={true}1899                  onBack={() => setRestoreView(null)}1900                  onImport={async () => {1901                    setRestoreView(null);1902                    await handleUnlock();1903                  }}1904                />1905              </Suspense>1906            </Show>1907            </section>1908            </Show>1909          </Show>1910        </Show>1911      </Show>1912      <Show when={showShortcutsHelp()}>1913        <ShortcutsHelpOverlay1914          bindings={shortcutBindings()}1915          onClose={() => setShowShortcutsHelp(false)}1916        />1917      </Show>1918    </div>1919  );1920}19211922function ShortcutsHelpOverlay(props: {1923  bindings: Record<ShortcutAction, Keybinding>;1924  onClose: () => void;1925}) {1926  return (1927    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1928      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1929        <div class="peach-shortcuts-help-head">1930          <h3>Keyboard shortcuts</h3>1931          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1932        </div>1933        <div class="peach-shortcuts-help-body">1934          <p class="peach-settings-sub-label">ENTRY VIEW</p>1935          <ul>1936            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1937              <li>1938                <span>{d.label}</span>1939                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1940              </li>1941            ))}1942          </ul>1943          <p class="peach-settings-sub-label">ANYWHERE</p>1944          <ul>1945            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1946              <li>1947                <span>{d.label}</span>1948                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1949              </li>1950            ))}1951          </ul>1952        </div>1953      </div>1954    </div>1955  );1956}