App.tsx

85.3 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 { ProNudgeView } from "./views/ProNudge";16import { claimProNudge } from "../shared/pro-nudge";17import {18  ONBOARDING_CARD_STORAGE_KEY,19  ONBOARDING_LAST_CARD,20  Onboarding,21} from "./views/Onboarding";2223const ONBOARDING_EXIT_STORAGE_KEY = "peach_onboarding_exit";24import { NotesMode } from "./views/NotesMode";25import { ProCelebration } from "./views/ProCelebration";26import { InitialSyncView } from "./views/InitialSyncView";27import { VaultView, type SortOrder } from "./views/Vault";28import { EntryView } from "./views/Entry";29import { AddView } from "./views/Add";30import { PeachWordmark } from "./components/PeachMark";31import { PasskeyApprovalView } from "./views/PasskeyApproval";32import { detectHomograph, extractDomain, getSecurityOriginDisplay } from "../shared/domain";33import {34  isManualSyncPending,35  syncIndicator,36  syncIndicatorLabel,37  type SyncOutcomeSummary,38} from "../shared/sync-outcome";39import { popupCopy } from "./copy";40import {41  DEFAULT_BINDINGS,42  formatKeybinding,43  getActiveBindings,44  matchKeybinding,45  SHORTCUT_DESCRIPTORS,46  type Keybinding,47  type ShortcutAction,48} from "../shared/shortcuts";49import { generateTOTP } from "../crypto/totp";5051export { sendMessage } from "../shared/bridge";5253const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));54const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));55const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));56const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));57const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));58const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));59const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));60const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));61const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));62const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));6364type View =65  | "lock"66  | "pro-celebration"67  | "whats-new"68  | "pro-nudge"69  | "entry"70  | "list"71  | "add"72  | "settings"73  | "pair-device"74  | "import"75  | "export"76  | "health"77  | "trash"78  | "panic"79  | "adopting"80  | "initial-sync"81  | "codex-generate"82  | "codex-restore";83type BootState = "loading" | "ready" | "error";8485const INITIAL_SYNC_POLL_MS = 500;86const INITIAL_SYNC_SLOW_MS = 15_000;8788let shellRingAnimation: Animation | null = null;8990export function triggerRing() {91  const shell = document.getElementById("hd-shell");92  if (!shell) return;9394  shellRingAnimation?.cancel();95  shell.dataset.glowing = "true";96  const animation = shell.animate(97    [98      { offset: 0, boxShadow: "var(--copy-shadow)" },99      {100        offset: 0.3,101        boxShadow:102          "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)",103      },104      { offset: 1, boxShadow: "var(--copy-shadow)" },105    ],106    {107      duration: 720,108      easing: "cubic-bezier(0.4, 0, 0.2, 1)",109      fill: "none",110    }111  );112  shellRingAnimation = animation;113  const clearGlow = () => {114    if (shellRingAnimation !== animation) return;115    shellRingAnimation = null;116    delete shell.dataset.glowing;117  };118  animation.onfinish = clearGlow;119  animation.oncancel = clearGlow;120}121122export function triggerPipPulse() {123  const pip = document.querySelector(".peach-status-pip, .pip");124  if (pip) {125    pip.classList.remove("pulse");126    void (pip as HTMLElement).offsetWidth;127    pip.classList.add("pulse");128  }129}130131const ENTRY_TRANSITION_SETTLE_MS = 135;132const ALL_SITES: chrome.permissions.Permissions = { origins: ["<all_urls>"] };133134export default function App() {135  const [bootState, setBootState] = createSignal<BootState>("loading");136  const [view, setView] = createSignal<View>("lock");137  const [contentPhase, setContentPhase] = createSignal<"enter" | "idle">("enter");138  const [hasVault, setHasVault] = createSignal(false);139  const [onboarded, setOnboarded] = createSignal(true);140  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);141  // The restore source picked before the popup closed (the OS file picker142  // kills it), so reopening resumes the same source form instead of the143  // picker. Read from RESTORE_SOURCE_STORAGE_KEY at boot.144  const [resumeRestoreSource, setResumeRestoreSource] = createSignal<RestoreSource | null>(null);145  // Onboarding remounts whenever it leaves (create/adopt/restore) and comes146  // back. Those flows all exit from the final card, so resume there — a fresh147  // install's first mount stays at 0.148  const [onboardingCardAtExit, setOnboardingCardAtExit] = createSignal(0);149  const [entries, setEntries] = createSignal<VaultEntry[]>([]);150  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);151  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);152153  // Rare device-trust alerts stay visible; routine entry sync is silent.154  interface SyncAlert {155    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";156    entryId: string;157    entryTitle: string;158    deviceName: string;159    timestamp: number;160  }161  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);162  // Per-group flip index: which alert within a type-group is currently shown.163  const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});164  async function loadSyncAlerts() {165    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {166      ok: boolean;167      data?: SyncAlert[];168    };169    if (r.ok) setSyncAlerts(r.data ?? []);170  }171  async function dismissAlertGroup(type: SyncAlert["type"]) {172    const result = (await sendMessage({173      type: "DISMISS_SYNC_ALERTS",174      payload: { type },175    })) as { ok: boolean };176    if (!result.ok) return;177    setSyncAlerts((arr) => arr.filter((a) => a.type !== type));178    setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });179  }180  function flipAlert(type: string, dir: 1 | -1) {181    const group = syncAlerts().filter((a) => a.type === type);182    if (group.length <= 1) return;183    setAlertFlipIdx((m) => {184      const cur = m[type] ?? 0;185      return { ...m, [type]: (cur + dir + group.length) % group.length };186    });187  }188  /** Grouped alert types in display order, each with its alerts. */189  const alertGroups = createMemo(() => {190    const map = new Map<string, SyncAlert[]>();191    for (const a of syncAlerts()) {192      const g = map.get(a.type);193      if (g) g.push(a); else map.set(a.type, [a]);194    }195    return [...map.entries()];196  });197  function syncAlertText(a: SyncAlert): string {198    if (a.type === "DEVICE_REVOKED") {199      return `${a.deviceName} revoked a paired device — review your devices in Settings`;200    }201    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;202  }203  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");204  const [theme, setTheme] = createSignal<"dark" | "light">("dark");205  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");206  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);207  const [lockOnClose, setLockOnClose] = createSignal(false);208  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);209  const [lockedSyncRequiresUnlock, setLockedSyncRequiresUnlock] = createSignal(false);210  const [breachMonitoring, setBreachMonitoring] = createSignal(true);211  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);212  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);213  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);214  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);215  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);216  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");217  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");218  // Cached Pro status — synchronous for render paths. Background's219  // GET_LICENSE is async, but render-time reads of isPro() must not block.220  // Refreshed at boot, after activate/deactivate, and whenever the popup221  // re-opens onto a stored license that has changed via another window.222  const [proStatus, setProStatus] = createSignal(false);223  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);224  // When the sync card's pairing button opens the pairing view, deep-link225  // straight into that pairing path instead of the rest screen.226  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");227  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);228  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");229  const [listSearchSeed, setListSearchSeed] = createSignal("");230  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);231  const [pendingCelebration, setPendingCelebration] = createSignal(false);232  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);233  // A page asked to be remembered for an entry it did not match. Pages cannot234  // grow an entry's domain set themselves (PB-26-106), so the background queues235  // the request here and this banner is the confirmation gate.236  const [pendingRememberSite, setPendingRememberSite] = createSignal<{237    entryId: string;238    url: string;239    title: string;240  } | null>(null);241  // Firefox MV3 lets users withhold <all_urls>; without it no content script242  // loads until a toolbar click grants activeTab for that one tab.243  const [siteAccessMissing, setSiteAccessMissing] = createSignal(false);244  // True while Panic Step 1 has bounced the user out to Export. When Export's245  // onBack fires we return to Panic instead of Settings so the user keeps the246  // destruction context they came from.247  const [returnToPanic, setReturnToPanic] = createSignal(false);248  // The view to return to when the add/edit view is dismissed. Normally "entry"249  // but "health" when the user arrives via the fix-entry path from Vault Health.250  const [editBackView, setEditBackView] = createSignal<View>("entry");251  const [settingsExiting, setSettingsExiting] = createSignal(false);252  const [showNotes, setShowNotes] = createSignal(false);253  // Topbar sync affordance. Always present: gating it on having a paired device254  // meant it never appeared for the person trying to set pairing up, which is255  // exactly when you reach for it.256  const [syncBusy, setSyncBusy] = createSignal(false);257  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);258  // The indicator light + its spoken-word equivalent. Colour alone is not the259  // signal; the title/aria-label always carries the same claim in English.260  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});261  const [pairedCount, setPairedCount] = createSignal(0);262  const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);263  const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);264  let initialSyncWaitGeneration = 0;265  const syncLight = () =>266    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());267  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());268  async function loadSyncIndicator() {269    const [stateRes, devicesRes] = await Promise.all([270      sendMessage({ type: "GET_SYNC_STATE" }),271      sendMessage({ type: "LIST_PAIRED_DEVICES" }),272    ]);273    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };274    if (s.ok && s.data) setSyncSummary(s.data);275    const d = devicesRes as { ok: boolean; error?: string; data?: { devices?: unknown[] } };276    if (d.ok) {277      setPairedCount(d.data?.devices?.length ?? 0);278    } else if (d.error === "trust_data_corrupted") {279      setPairedCount(0);280      setSyncSummary({ status: "error", outcome: "trust_data_corrupted" });281    }282  }283284  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {285    const response = (await sendMessage({286      type: "LIST_PAIRED_DEVICES",287    })) as {288      ok: boolean;289      error?: string;290      data?: { devices?: InitialSyncPairedDevice[] };291    };292    if (response.ok) return response.data?.devices ?? [];293    if (response.error === "trust_data_corrupted") throw new Error("trust_data_corrupted");294    throw new Error(response.error ?? "list_paired_devices_failed");295  }296  interface InitialSyncPairedDevice extends InitialSyncDevice {297    pairedAt?: number;298  }299300301  async function resolveInitialSyncDeviceId(): Promise<string | null> {302    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(303      () => null,304    );305    const devices = await listInitialSyncDevices().catch(() => []);306    if (stored && devices.some((device) => device.deviceId === stored)) {307      return stored;308    }309310    // Fresh adoption has exactly one direct source, but choosing the newest row311    // also repairs the marker if storage failed after the pair itself committed.312    const newest = [...devices].sort(313      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),314    )[0];315    if (!newest) return stored;316    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(317      () => undefined,318    );319    return newest.deviceId;320  }321322  async function finishInitialSync(generation: number): Promise<void> {323    if (generation !== initialSyncWaitGeneration) return;324    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);325    setInitialSyncDeviceId(null);326    setInitialSyncSlow(false);327    await refreshProStatus();328329    // A license transferred during pairing intentionally leaves the one-shot330    // celebration pending. Consume it only now: sync readiness → celebration331    // → populated vault, never celebration → temporarily empty vault.332    const celebration = (await sendMessage({333      type: "SHOULD_PLAY_CELEBRATION",334    })) as { ok: boolean; data?: boolean };335    const shouldCelebrate = celebration.ok && celebration.data === true;336    if (shouldCelebrate) {337      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });338    }339340    const opened = await openVault(undefined, shouldCelebrate);341    if (!opened || generation !== initialSyncWaitGeneration) return;342    if (shouldCelebrate) {343      setView("pro-celebration");344      window.setTimeout(() => {345        if (generation === initialSyncWaitGeneration) setView("entry");346      }, 2500);347    }348  }349350  async function beginInitialSyncWait(deviceId: string): Promise<void> {351    const generation = ++initialSyncWaitGeneration;352    setInitialSyncDeviceId(deviceId);353    setInitialSyncSlow(false);354    setView("initial-sync");355    const startedAt = Date.now();356357    // Best effort: the pairing write already wakes the mesh listener, while358    // this trigger covers the key-order case where this receiver is the dialer.359    void sendMessage({360      type: "TRIGGER_SYNC",361      payload: { reason: "foreground" },362    }).catch(() => undefined);363364    while (365      generation === initialSyncWaitGeneration &&366      view() === "initial-sync"367    ) {368      try {369        const devices = await listInitialSyncDevices();370        if (hasCompletedInitialSync(devices, deviceId)) {371          await finishInitialSync(generation);372          return;373        }374      } catch {375        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.376      }377      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {378        setInitialSyncSlow(true);379      }380      await new Promise((resolve) =>381        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),382      );383    }384  }385386  async function retryInitialSync(): Promise<void> {387    const deviceId =388      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());389    if (deviceId) {390      await beginInitialSyncWait(deviceId);391    } else {392      setInitialSyncSlow(true);393    }394  }395396  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);397  // Set on popup boot when peach_recovery_pending flag is found in session398  // storage — instructs LockView to skip the unlock UI and open the recovery399  // words confirmation surface instead. Cleared via handleUnlock once the400  // user has typed the 3 confirmation words.401  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);402403  let contentPhaseTimer: number | undefined;404  // Set when the popup was opened from the inline "Open Peach to unlock" button.405  // handleUnlock() closes the popup after unlock so the user returns to the page.406  let openedForInlineUnlock = false;407408  onCleanup(() => {409    initialSyncWaitGeneration += 1;410  });411412  function applyAccent(name: AccentColorName) {413    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;414    const hex = color.hex;415    document.documentElement.style.setProperty("--peach-accent", hex);416    // Ambient variables derived from the selected accent.417    document.documentElement.style.setProperty("--peach-glow", hex + "2A");418    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");419  }420421  createEffect(() => {422    applyAccent(accentColor());423  });424425  createEffect(() => {426    document.documentElement.classList.toggle("light", theme() === "light");427    document.body.classList.toggle("light", theme() === "light");428  });429430  createEffect(() => {431    document.documentElement.setAttribute("data-text-size", textSize());432  });433434  createEffect(() => {435    if (reduceMotion()) {436      document.documentElement.setAttribute("data-motion", "reduce");437    } else {438      document.documentElement.removeAttribute("data-motion");439    }440  });441442  // Notes are not a destination of the Entry view; selecting a note opens the443  // notes surface instead (handleSelectEntry). Anything that walks or counts444  // the Entry view's neighbours (counter, prev/next, index) must use this445  // filtered list, otherwise the user can arrow into a note and is stuck —446  // the Entry view can't render a note and the prev/next buttons stop moving.447  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));448449  const selectedIndex = createMemo(() => {450    const currentId = selectedEntry()?.id;451    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;452    return nonNoteEntries().findIndex((entry) => entry.id === currentId);453  });454455  async function applyAccentColor(name: AccentColorName) {456    applyAccent(name);457    setAccentColor(name);458    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });459  }460461  async function applyTheme(t: "dark" | "light") {462    setTheme(t);463    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });464  }465466  async function applyTextSize(size: "small" | "medium" | "large") {467    setTextSize(size);468    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });469  }470471  async function applyReduceMotion(enabled: boolean) {472    setReduceMotion(enabled);473    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });474  }475476  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload477  // small and lets future default updates land for actions the user hasn't478  // touched. Settings sends us the full active map; we filter and store.479  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {480    setShortcutBindings(active);481    const overrides: Record<string, Keybinding> = {};482    for (const action of Object.keys(active) as ShortcutAction[]) {483      const a = active[action];484      const d = DEFAULT_BINDINGS[action];485      const same = a.key === d.key486        && Boolean(a.ctrl)  === Boolean(d.ctrl)487        && Boolean(a.meta)  === Boolean(d.meta)488        && Boolean(a.shift) === Boolean(d.shift)489        && Boolean(a.alt)   === Boolean(d.alt);490      if (!same) overrides[action] = a;491    }492    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });493  }494495  async function applyLockOnClose(enabled: boolean) {496    setLockOnClose(enabled);497    await sendMessage({498      type: "UPDATE_SETTINGS",499      payload: { lockOnClose: enabled },500    });501  }502503  async function applyAutoLockMinutes(minutes: number) {504    setAutoLockMinutes(minutes);505    await sendMessage({506      type: "UPDATE_SETTINGS",507      payload: { autoLockMinutes: minutes },508    });509  }510  async function applyLockedSyncRequiresUnlock(enabled: boolean) {511    setLockedSyncRequiresUnlock(enabled);512    await sendMessage({ type: "UPDATE_SETTINGS", payload: { lockedSyncRequiresUnlock: enabled } });513  }514515  async function applyBreachMonitoring(enabled: boolean) {516    setBreachMonitoring(enabled);517    await sendMessage({518      type: "UPDATE_SETTINGS",519      payload: { breachMonitoring: enabled },520    });521  }522523  // Which onboarding exit flow the user is in (create-vault / restore /524  // adopt). Persisted so closing the popup on one of those screens resumes525  // it directly instead of rewinding to the last carousel card.526  function markOnboardingExit(flow: "create" | "restore" | "adopt") {527    setOnboardingCardAtExit(ONBOARDING_LAST_CARD);528    void storageSet(ONBOARDING_EXIT_STORAGE_KEY, flow).catch(() => {});529    // Backing out of the flow remounts the carousel at this card; keep the530    // persisted card in sync so a later popup close resumes consistently.531    void storageSet(ONBOARDING_CARD_STORAGE_KEY, String(ONBOARDING_LAST_CARD)).catch(() => {});532  }533  function clearOnboardingExit() {534    void storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});535    void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});536    setResumeRestoreSource(null);537  }538539  onMount(() => {540    void chrome.permissions.contains(ALL_SITES).then((granted) => setSiteAccessMissing(!granted));541  });542543  async function boot() {544    setBootState("loading");545    try {546    // Resolve the active tab in parallel with the unlock/has-vault queries —547    // openVault()'s smart selection picks the entry matching currentTabDomain,548    // so it must be populated before openVault runs. Previously refreshCurrentTab549    // ran after openVault, leaving popups that booted already-unlocked falling550    // back to loadedEntries[0] instead of the domain match.551    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([552      sendMessage({ type: "IS_UNLOCKED" }),553      sendMessage({ type: "HAS_VAULT" }),554      refreshCurrentTab(),555      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),556    ]);557    if (!unlockResponse || unlockResponse.ok !== true || typeof unlockResponse.data !== "boolean" ||558        !vaultResponse || vaultResponse.ok !== true || typeof vaultResponse.data !== "boolean") {559      setBootState("error");560      return;561    }562    const unlocked = unlockResponse.data;563    const vaultExists = vaultResponse.data;564    const shouldCelebrate = Boolean(565      celebrationResponse?.ok === true && celebrationResponse.data === true566    );567    setHasVault(vaultExists);568    // Onboarding gate — show once on first install, never again. Existing569    // users (vaultExists) are auto-marked onboarded so they skip the flow570    // even on the very first popup open after this feature ships.571    try {572      const onboarded = await storageGet("peach_onboarded");573      const seen = onboarded === "true";574      if (vaultExists && !seen) {575        await storageSet("peach_onboarded", "true");576        await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});577        await storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});578        await storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});579        setOnboarded(true);580      } else {581        setOnboarded(seen);582        if (!seen) {583          // A popup close while the user is in an exit flow (create-vault /584          // restore / adopt) resumes that flow directly — landing back on the585          // carousel one screen earlier reads as losing progress.586          const exit = await storageGet(ONBOARDING_EXIT_STORAGE_KEY).catch(() => null);587          if (exit === "create" || exit === "restore" || exit === "adopt") {588            setOnboardingCardAtExit(ONBOARDING_LAST_CARD);589            setOnboarded(true);590            setStartOnboardingRestore(exit === "restore");591            if (exit === "restore") {592              // The OS file picker kills the action popup mid-restore, so the593              // surface resumes on the source the user had already picked.594              const source = await storageGet(RESTORE_SOURCE_STORAGE_KEY).catch(() => null);595              if (source === "symbols" || source === "codex" || source === "csv") {596                setResumeRestoreSource(source);597              }598            }599            if (exit === "adopt") setView("adopting");600          } else {601            // Otherwise resume mid-onboarding where the user left off instead602            // of rewinding to the opening card.603            const stored = Number(604              await storageGet(ONBOARDING_CARD_STORAGE_KEY).catch(() => null),605            );606            if (607              Number.isInteger(stored) &&608              stored > 0 &&609              stored <= ONBOARDING_LAST_CARD610            ) {611              setOnboardingCardAtExit(stored);612            }613          }614        }615      }616    } catch {617      // storage unavailable — default to onboarded so we never block boot618      setOnboarded(true);619    }620621    // Deep-link: ?restore=peachscript|csv — the detached-window half of the622    // file-picker flow. The action popup dismisses when the OS dialog steals623    // focus, so LockView.detachForFilePicker() reopens this URL in a624    // standalone window that owns the dialog. Routing runs before first625    // render so LockView mounts straight onto the right source form.626    try {627      const restoreRoute = new URLSearchParams(window.location.search).get("restore");628      if (restoreRoute === "peachscript" || restoreRoute === "csv") {629        setOnboarded(true);630        setStartOnboardingRestore(true);631        setResumeRestoreSource(restoreRoute === "peachscript" ? "symbols" : "csv");632      }633    } catch {634      // location.search unavailable — ignore.635    }636637    await Promise.all([restoreSettings(), refreshProStatus()]);638639    const pendingInitialSyncMarker =640      unlocked && vaultExists641        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)642        : null;643    const pendingInitialSyncDeviceId = pendingInitialSyncMarker644      ? await resolveInitialSyncDeviceId()645      : null;646647    // Mark played before any animation so a crash mid-sequence never replays648    // it. A newly adopted receiver deliberately defers this until its first649    // real sync finishes, preserving initial sync → celebration → vault.650    if (shouldCelebrate && !pendingInitialSyncDeviceId) {651      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });652    }653654    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome655    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.656    if (unlocked && vaultExists) {657      void sendMessage({658        type: "TRIGGER_SYNC",659        payload: { reason: "foreground" },660      });661      void loadSyncIndicator();662      // Rare device-trust alerts only; routine entry sync stays quiet.663      void loadSyncAlerts();664    }665666    // If the user created a vault but hasn't yet confirmed their recovery667    // words, route back to the recovery-words screen instead of opening the668    // entries view. The flag lives in chrome.storage.local so it survives669    // popup close while the background owns the session-scoped confirmation670    // exemption. Cleared when confirmation succeeds.671    let recoveryPending = false;672    try {673      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });674      recoveryPending = out.ok === true && out.data === true;675    } catch { /* best-effort */ }676677    // Content UI can ask the background to open this trusted popup either for678    // unlock or at a specific entry. Consume both session-scoped handoffs once.679    let pendingOpenEntryId: string | undefined;680    if (chrome.storage.session) {681      try {682        const s = await chrome.storage.session.get(["peach_inline_unlock", "peach_open_entry"]);683        const pending = s as { peach_inline_unlock?: boolean; peach_open_entry?: string };684        if (pending.peach_inline_unlock) {685          openedForInlineUnlock = true;686        }687        if (typeof pending.peach_open_entry === "string") pendingOpenEntryId = pending.peach_open_entry;688        await chrome.storage.session.remove(["peach_inline_unlock", "peach_open_entry"]);689      } catch { /* best-effort */ }690    }691692    if (recoveryPending && unlocked) {693      // forceRecoveryWords overrides LockView's hasVault gate so the694      // recovery surface renders even though the vault now exists.695      setForceRecoveryWords(true);696      setView("lock");697    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {698      void beginInitialSyncWait(pendingInitialSyncDeviceId);699    } else if (unlocked && vaultExists) {700      await openVault(pendingOpenEntryId, shouldCelebrate);701      if (shouldCelebrate) {702        setView("pro-celebration");703        window.setTimeout(() => setView("entry"), 2500);704      } else if (await shouldShowWhatsNew()) {705        setView("whats-new");706      } else if (!proStatus() && await claimProNudge()) {707        setView("pro-nudge");708      }709    } else if (shouldCelebrate) {710      setPendingCelebration(true);711    }712713    await refreshPendingPasskey();714715    // Track tab changes so smart sort stays current716    const handleTabActivated = () => { void refreshCurrentTab(); };717    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {718      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();719    };720    try {721      chrome.tabs.onActivated.addListener(handleTabActivated);722      chrome.tabs.onUpdated.addListener(handleTabUpdated);723      onCleanup(() => {724        chrome.tabs.onActivated.removeListener(handleTabActivated);725        chrome.tabs.onUpdated.removeListener(handleTabUpdated);726      });727    } catch {728      // tabs permission may not be available in all contexts729    }730731    setBootState("ready");732733    // Deep-link: ?codex=pdf opens a detached window straight into the734    // Codex restore flow with auto-picked PDF. The action popup can't host735    // a file dialog without dismissing itself, so this is the only way the736    // PDF import path survives. See CodexRestoreView.openPdfPicker().737    try {738      const route = new URLSearchParams(window.location.search).get("codex");739      if (route === "pdf" || route === "restore") {740        setView("codex-restore");741      }742    } catch {743      // location.search unavailable — ignore.744    }745746    // Check for pending session-storage notices from the background.747    if (chrome.storage.session) {748      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as749        Record<string, { feature?: string } | undefined>;750      if (session.pendingProGate?.feature) {751        await chrome.storage.session.remove("pendingProGate");752        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);753        setSettingsInitialSection("license");754        setView("settings");755      } else if (session.pendingProNotice?.feature) {756        await chrome.storage.session.remove("pendingProNotice");757        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });758      }759      const remembered = (await chrome.storage.session.get("pendingRememberSite")) as {760        pendingRememberSite?: { entryId?: unknown; url?: unknown };761      };762      const request = remembered.pendingRememberSite;763      if (764        typeof request?.entryId === "string" &&765        typeof request.url === "string"766      ) {767        const entry = await sendMessage({ type: "GET_ENTRIES" });768        const match = entry.ok769          ? (entry.data as Array<{ id: string; title?: string }> | undefined)?.find(770              (candidate) => candidate.id === request.entryId,771            )772          : undefined;773        if (match) {774          let host = request.url;775          try { host = new URL(request.url).hostname; } catch { /* keep raw */ }776          setPendingRememberSite({ entryId: request.entryId, url: request.url, title: match.title ?? host });777        } else {778          await chrome.storage.session.remove("pendingRememberSite");779        }780      }781    }782783    // Warm the lazy-module cache so the Suspense fallback never shows for784    // locally-bundled extension views. Without this, the first navigation to785    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which786    // covers the shell and absorbs clicks on the header.787    void Promise.all([788      import("./views/Settings").catch(() => {}),789      import("./views/Import").catch(() => {}),790      import("./views/Export").catch(() => {}),791      import("./views/Health").catch(() => {}),792      import("./views/TrashView").catch(() => {}),793    ]);794795    // Lock-on-close via a persistent port. sendMessage in pagehide is796    // unreliable — the popup context tears down before the message lands.797    // The SW's onConnect listener locks when this port disconnects.798    let popupPort: chrome.runtime.Port | null = null;799    try {800      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect801      // listener accepts the "popup-" prefix; the random suffix is defence in802      // depth against a port named exactly "popup" from anything but our popup.803      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });804    } catch { /* extension context invalidated — ignore */ }805    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });806807    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale808    // entries instead of waiting for the next GET_ENTRIES round-trip.809    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {810      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();811      if (msg?.type === "SYNC_STATE_CHANGED") {812        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);813      }814      // A background sync merged entries the user never asked for (a peer's815      // push, or the periodic dial). Pull the fresh list so the vault view is816      // not stale — loadEntries() preserves the current selection by id.817      if (msg?.type === "VAULT_ENTRIES_CHANGED" && view() !== "lock") {818        void loadEntries();819      }820      if (msg?.type === "PRO_GATE_TRIGGERED") {821        setUpgradeHighlight(msg.payload?.feature ?? null);822        setSettingsInitialSection("license");823        setView("settings");824      }825    };826    chrome.runtime.onMessage.addListener(handleRuntimeMessage);827    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));828829    // Action handlers — keyed by ShortcutAction. The dispatcher below tests830    // each binding against the event and runs the matching handler. New831    // shortcuts only need an entry here; the binding is data, not code.832    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {833      copy_password: () => {834        const entry = selectedEntry();835        if (entry?.password) void popupCopy(836          entry.password,837          "Password",838          entry.id,839        ).then((ok) => { if (ok) triggerRing(); });840      },841      copy_username: () => {842        const entry = selectedEntry();843        if (entry?.username) void popupCopy(844          entry.username,845          "Username",846          entry.id,847        ).then((ok) => { if (ok) triggerRing(); });848      },849      copy_totp: () => {850        const entry = selectedEntry();851        if (!entry?.totp) return;852        try {853          const { code } = generateTOTP(854            entry.totp,855            entry.totpAlgorithm,856            entry.totpDigits,857            entry.totpPeriod,858          );859          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });860        } catch { /* invalid TOTP secret — silent */ }861      },862      new_entry: () => handleAdd(),863      edit_entry: () => {864        const entry = selectedEntry();865        // Passkey-only entries have nothing user-editable in the Add view; the866        // passkey credential itself is opaque. Skip the edit action for them.867        if (!entry || isPasskeyOnly(entry)) return;868        setEditEntry(entry);869        setView("add");870      },871      delete_entry: () => {872        if (selectedEntry()) void handleDelete();873      },874      lock_vault: () => { void handleHeaderLock(); },875      search: () => openList(),876      nav_prev: () => navigate(-1),877      nav_next: () => navigate(1),878      jump_vault: () => setView("entry"),879      jump_settings: () => setView("settings"),880      show_help: () => setShowShortcutsHelp(true),881    };882883    // Actions that are MEANINGFUL only on the entry-detail view. Outside884    // that scope the binding is dormant — pressing C while on Settings885    // does nothing rather than awkwardly copying from a now-stale entry.886    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([887      "copy_password", "copy_username", "copy_totp",888      "edit_entry", "delete_entry", "nav_prev", "nav_next",889    ]);890891    const handleGlobalKeydown = (e: KeyboardEvent) => {892      const v = view();893      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"894        || (e.target as HTMLElement)?.tagName === "TEXTAREA"895        || (e.target as HTMLElement)?.isContentEditable;896      const isPrintableSearchKey =897        e.key.length === 1 &&898        !e.ctrlKey &&899        !e.metaKey &&900        !e.altKey;901902      // No shortcuts while a full-screen surface owns the whole viewport:903      // the lock screen, the post-pairing readiness sequence, or the Pro904      // celebration. Without this the lock screen is at the mercy of whatever905      // single-key binding is active — e.g. typing "n" in a password that906      // slips out of focus triggers `new_entry` and escapes the lock screen.907      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;908909      // Help dialog: Escape closes it; eat the keypress so it doesn't910      // also navigate away from the underlying view.911      if (showShortcutsHelp()) {912        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }913        return;914      }915916      // ── Escape — fixed binding (not user-customizable) ───────917      if (e.key === "Escape") {918        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }919        if (v === "list") { setView("entry"); return; }920        if (v === "settings" || v === "add") { handleBack(); return; }921        if (v === "import" || v === "health") { setView("settings"); return; }922        if (v === "export") { handleExportBack(); return; }923        if (v === "pair-device") { setView("settings"); return; }924      }925926      // Bindings-driven dispatch. Single-key letter bindings without927      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is928      // inside an input, so users can type into search/forms normally.929      const bindings = shortcutBindings();930      for (const action of Object.keys(bindings) as ShortcutAction[]) {931        const binding = bindings[action];932        if (!matchKeybinding(e, binding)) continue;933        // Single-key letter bindings need the input-focus guard. Bindings934        // with any modifier are safe — Ctrl+L doesn't conflict with typing.935        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;936        if (!hasMod && binding.key.length === 1 && inInput) return;937        if (ENTRY_SCOPED.has(action) && v !== "entry") return;938        e.preventDefault();939        SHORTCUT_HANDLERS[action]?.();940        return;941      }942943      // Type-to-search: in entry view, any printable key not consumed by a944      // shortcut above primes the list search seed and opens the list.945      // Kept outside the bindings table because it's a behavior, not a946      // discrete action — every printable character can trigger it.947      if (v === "entry" && !inInput && isPrintableSearchKey) {948        e.preventDefault();949        primeListSearch(e.key);950        return;951      }952    };953    window.addEventListener("keydown", handleGlobalKeydown);954    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));955956    const handleStorageChanged = (957      changes: Record<string, chrome.storage.StorageChange>,958      areaName: string959    ) => {960      if (areaName !== "session") return;961      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {962        return;963      }964      void refreshPendingPasskey();965    };966    chrome.storage.onChanged.addListener(handleStorageChanged);967    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));968    } catch (error) {969      if (bootState() === "ready") console.warn("[Peach] popup setup failed:", error);970      else setBootState("error");971    }972  }973974  onMount(() => { void boot(); });975976  async function refreshCurrentTab() {977    try {978      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });979      const url = tab?.url ?? tab?.pendingUrl ?? "";980      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");981      // Skip extension/internal URLs — adding chrome://, about:, or982      // chrome-extension:// to a vault entry is never what the user wants.983      const isWebUrl = /^https?:\/\//i.test(url);984      setCurrentTabUrl(isWebUrl ? url : "");985    } catch {986      setCurrentTabDomain("");987      setCurrentTabUrl("");988    }989  }990991  async function refreshPendingPasskey() {992    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });993    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);994  }995996  async function refreshProStatus() {997    const res = await sendMessage({ type: "GET_LICENSE" });998    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;999    setProStatus(Boolean(data?.valid && data?.plan === "pro"));1000  }10011002  async function restoreSettings() {1003    const res = await sendMessage({ type: "GET_SETTINGS" });1004    const s = (res as { ok: boolean; data?: any }).data ?? {};1005    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {1006      setAccentColor(s.accentColor as AccentColorName);1007    }1008    setTheme(s.theme === "light" ? "light" : "dark");1009    if (s.textSize === "small" || s.textSize === "large") {1010      setTextSize(s.textSize);1011    } else {1012      setTextSize("medium");1013    }1014    setReduceMotion(s.reduceMotion === true);1015    setLockOnClose(s.lockOnClose === true);1016    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);1017    setLockedSyncRequiresUnlock(s.lockedSyncRequiresUnlock === true);1018    setBreachMonitoring(s.breachMonitoring !== false);1019    setShortcutBindings(getActiveBindings(s.shortcuts));1020  }10211022  async function applyTrashRetention(days: number) {1023    setTrashRetentionDays(days);1024    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });1025  }10261027  function primeListSearch(seed: string) {1028    setListSearchSeed(seed);1029    setListSearchSeedNonce((value) => value + 1);1030    openList();1031  }10321033  // Returns null when it detected a dead service worker and triggered handleLock().1034  // Callers that need to abort (e.g. openVault) check for null rather than relying1035  // on view() state, which may already be "lock" during normal startup flows.1036  async function loadEntries(): Promise<VaultEntry[] | null> {1037    const response = await sendMessage({ type: "GET_ENTRIES" });1038    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };10391040    // If the service worker was killed and restarted (MV3 workers sleep), the1041    // vault will be locked again — or the worker may not respond at all.1042    // In either case, send the user to the lock screen rather than silently1043    // showing an empty vault (which looks like data loss).1044    if (!res.ok) {1045      if (1046        res.error === "vault_locked" ||1047        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1048        (typeof res.error === "string" && res.error.includes("locked"))1049      ) {1050        handleLock();1051        return null; // signal emergency lock to callers1052      }1053      return [];1054    }10551056    const loadedEntries = res.data ?? [];1057    setEntries(loadedEntries);10581059    const currentId = selectedEntry()?.id;1060    if (currentId) {1061      setSelectedEntry(1062        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1063      );1064    }10651066    return loadedEntries;1067  }10681069  async function openVault(preferredEntryId?: string, skipViewSet = false) {1070    // Purge expired trash entries on each vault open1071    const retDays = trashRetentionDays();1072    if (retDays > 0) {1073      void sendMessage({1074        type: "PURGE_EXPIRED_TRASH",1075        payload: { retentionMs: retDays * 86_400_000 },1076      });1077    }10781079    const loadedEntries = await loadEntries();10801081    // null means loadEntries() triggered an emergency lock (service worker died).1082    // Don't override it by setting view back to "entry" with an empty vault.1083    if (loadedEntries === null) return false;10841085    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1086    let nextSelectedEntry: VaultEntry | null = null;1087    if (preferredEntryId) {1088      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1089    }1090    if (!nextSelectedEntry) {1091      const tabDomain = currentTabDomain();1092      if (tabDomain) {1093        nextSelectedEntry = loadedEntries.find((e) => {1094          if (e.type === "login") {1095            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1096            for (const extra of e.additionalUrls ?? []) {1097              if ((extractDomain(extra) ?? "") === tabDomain) return true;1098            }1099            return false;1100          }1101          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1102          return false;1103        }) ?? null;1104      }1105    }1106    nextSelectedEntry ??= pickNavigable(loadedEntries);11071108    setSelectedEntry(nextSelectedEntry);1109    setEditEntry(undefined);1110    setContentPhase("enter");1111    queueContentIdle();1112    if (!skipViewSet) setView("entry");1113    return true;1114  }11151116  async function handleUnlock() {1117    // If the user previously created a vault but hadn't yet confirmed their1118    // recovery words (and the browser was closed before they could), the1119    // the background-owned recovery-pending state is still set. Re-route1120    // back to the recovery surface so they finish the confirmation step1121    // before reaching the entries view — the words can be re-derived now1122    // that the vault is unlocked again.1123    let recoveryPending = false;1124    try {1125      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });1126      recoveryPending = out.ok === true && out.data === true;1127    } catch { /* best-effort */ }1128    if (recoveryPending) {1129      setForceRecoveryWords(true);1130      setView("lock");1131      triggerPipPulse();1132      await restoreSettings();1133      return;1134    }1135    setHasVault(true);1136    triggerPipPulse();1137    await restoreSettings();1138    const celebrating = pendingCelebration();1139    if (celebrating) {1140      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1141      setPendingCelebration(false);1142    }1143    await openVault(undefined, celebrating);1144    if (celebrating) {1145      setView("pro-celebration");1146      window.setTimeout(() => setView("entry"), 2500);1147    } else if (!openedForInlineUnlock && await shouldShowWhatsNew()) {1148      setView("whats-new");1149    } else if (!openedForInlineUnlock && !proStatus() && await claimProNudge()) {1150      setView("pro-nudge");1151    }1152    // Popup was opened from the inline "Open Peach to unlock" button — close it1153    // now so the user lands back on the page with the autofill selector ready.1154    if (openedForInlineUnlock) {1155      openedForInlineUnlock = false;1156      window.close();1157    }1158  }11591160  function handleSelectEntry(entry: VaultEntry) {1161    if (entry.type === "note") {1162      setOpenNoteId(entry.id);1163      setShowNotes(true);1164      return;1165    }1166    setSelectedEntry(entry);1167    setContentPhase("enter");1168    queueContentIdle();1169    setView("entry");1170  }11711172  function handleAdd() {1173    setEditEntry(undefined);1174    setView("add");1175  }11761177  async function handleDelete() {1178    const entry = selectedEntry();1179    if (!entry) return;1180    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1181    const loadedEntries = await loadEntries() ?? [];1182    setSelectedEntry(pickNavigable(loadedEntries));1183    setView("entry");1184  }11851186  async function handleDeleteMany(ids: string[]) {1187    for (const id of ids) {1188      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1189    }1190    const loadedEntries = await loadEntries() ?? [];1191    // If the currently selected entry was among the deleted, move to first1192    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1193    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1194  }11951196  async function handleSave(savedEntry?: VaultEntry) {1197    await openVault(savedEntry?.id);1198  }11991200  function handleBack() {1201    const dest = editBackView();1202    setEditBackView("entry");1203    setEditEntry(undefined);1204    setView(dest);1205  }12061207  function handleExportBack() {1208    if (returnToPanic()) {1209      setReturnToPanic(false);1210      setView("panic");1211      return;1212    }1213    setView("settings");1214  }12151216  function handleLock() {1217    setEntries([]);1218    setSelectedEntry(null);1219    setEditEntry(undefined);1220    setContentPhase("idle");1221    setView("lock");1222  }12231224  function handleHeaderLock() {1225    // Lock the UI immediately — do not wait for the service worker. If the SW1226    // is dead or slow, the 5s sendMessage timeout would create a dead-click1227    // window. The SW will lock on its next wake regardless.1228    handleLock();1229    void sendMessage({ type: "LOCK" });1230  }12311232  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1233  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1234  // the trigger's own reply.1235  async function handleHeaderSync(): Promise<void> {1236    if (syncBusy()) return;1237    setSyncBusy(true);1238    setSyncFlash(null);1239    try {1240      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1241      let state: SyncOutcomeSummary = { status: "syncing" };1242      for (let i = 0; i < 360 && isManualSyncPending(state); i++) {1243        await new Promise((r) => setTimeout(r, 250));1244        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1245          ok: boolean;1246          data?: SyncOutcomeSummary;1247        };1248        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1249      }1250      setSyncSummary(state);1251      setSyncFlash(state.status === "error" ? "error" : "ok");1252      await loadSyncAlerts();1253      await loadEntries();1254      await loadSyncIndicator();1255    } catch {1256      setSyncSummary({ status: "error", outcome: "run_failed" });1257      setSyncFlash("error");1258    } finally {1259      setSyncBusy(false);1260      setTimeout(() => setSyncFlash(null), 2_000);1261    }1262  }12631264  function navigate(dir: number) {1265    const navigable = nonNoteEntries();1266    if (navigable.length === 0) return;1267    const currentIndex = selectedIndex();1268    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1269    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1270    setSelectedEntry(navigable[nextIndex]);1271    setContentPhase("enter");1272    queueContentIdle();1273  }12741275  /**1276   * The Entry view's selection invariant: never select a note. Notes are a1277   * separate surface (handleSelectEntry opens the notes view), so any code path1278   * that picks a default — vault open, post-delete, refresh — must skip them1279   * and return null if the only entries are notes.1280   */1281  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1282    return list.find((e) => e.type !== "note") ?? null;1283  }12841285  function openList() {1286    setView("list");1287  }12881289  function openHealth() {1290    setEditEntry(undefined);1291    setView("health");1292  }12931294  function handleOpenFileImport() {1295    setRestoreView("file");1296  }12971298  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12991300  function handleFixEntry(entry: VaultEntry) {1301    setSelectedEntry(entry);1302    // Passkey-only entries have no editable surface — drop into view mode1303    // instead of opening the Add editor.1304    if (isPasskeyOnly(entry)) {1305      setView("entry");1306      return;1307    }1308    setEditBackView(view()); // preserve caller view so back returns here1309    setEditEntry(entry);1310    setView("add");1311  }13121313  const isLockedView = () => view() === "lock" || view() === "adopting";13141315  async function handleAdoptionDone() {1316    await storageSet("peach_onboarded", "true").catch(() => {});1317    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1318    clearOnboardingExit();1319    setOnboarded(true);1320    setHasVault(true);1321    setView("initial-sync");1322    // The background applies a Pro license and persists the source-device1323    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1324    // celebration pending until that exact peer records a completed sync.1325    await refreshProStatus();1326    const deviceId = await resolveInitialSyncDeviceId();1327    if (deviceId) {1328      void beginInitialSyncWait(deviceId);1329    } else {1330      // Pairing completion without a durable peer row should be impossible.1331      // Stay on the honest waiting surface and expose retry instead of falling1332      // through to an empty vault.1333      setInitialSyncSlow(true);1334    }1335  }13361337  async function handleApprovePendingPasskey() {1338    const pending = pendingPasskey();1339    if (!pending) return;1340    if (pending.browser === "firefox" && pending.type === "create") {1341      // Firefox path: popup itself runs navigator.credentials.create. The1342      // background never approved/rejected anything — it just stashed1343      // intent. After the popup-driven flow resolves (success or cancel),1344      // clear the pending key so the popup doesn't re-show this on next open.1345      const { createFirefoxPasskey } = await import("./firefox-passkey");1346      const result = await createFirefoxPasskey(pending);1347      if (!result.ok) {1348        console.warn("Peach Firefox passkey create failed:", result.error);1349      }1350      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1351      setPendingPasskey(null);1352      void loadEntries();1353      window.close();1354      return;1355    }1356    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1357    window.close();1358  }13591360  async function handleDenyPendingPasskey() {1361    const pending = pendingPasskey();1362    if (!pending) return;1363    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1364    window.close();1365  }13661367  function queueContentIdle(after?: () => void) {1368    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1369    contentPhaseTimer = window.setTimeout(() => {1370      setContentPhase("idle");1371      after?.();1372    }, ENTRY_TRANSITION_SETTLE_MS);1373  }13741375  return (1376    <div class="popup-root peach-theme">1377      <Show when={siteAccessMissing()}>1378        <div class="peach-pro-notice-banner peach-site-access-banner" role="alert">1379          <span>Peach can't fill on websites until you allow site access.</span>1380          <button1381            class="peach-pro-notice-link"1382            onClick={() => {1383              // Called synchronously from the click: Firefox requires a user gesture.1384              chrome.permissions.request(ALL_SITES).then(1385                (granted) => setSiteAccessMissing(!granted),1386                (error: unknown) => console.warn("Peach site access request failed:", error),1387              );1388            }}1389          >1390            Allow1391          </button>1392        </div>1393      </Show>1394      <Show when={bootState() === "error"}>1395        <div class="peach-loading peach-boot-error" role="alert">1396          <p>Peach couldn’t check your vault. Try again.</p>1397          <button class="peach-btn peach-btn--accent peach-btn--md" onClick={() => void boot()}>Retry</button>1398        </div>1399      </Show>1400      <Show when={bootState() === "ready"}>1401        <Show1402          when={!pendingPasskey()}1403          fallback={1404            <PasskeyApprovalView1405              type={pendingPasskey()!.type}1406              rpName={pendingPasskey()!.rpName}1407              rpId={pendingPasskey()!.rpId}1408              origin={pendingPasskey()!.origin}1409              crossOrigin={pendingPasskey()!.crossOrigin}1410              userName={pendingPasskey()!.userName}1411              userDisplayName={pendingPasskey()!.userDisplayName}1412              onApprove={handleApprovePendingPasskey}1413              onDeny={handleDenyPendingPasskey}1414            />1415          }1416        >1417          <Show1418            when={!isLockedView()}1419            fallback={1420              <Show1421                when={view() !== "adopting"}1422                fallback={1423                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1424                    <AdoptVaultView1425                      onCancel={() => {1426                        clearOnboardingExit();1427                        setOnboarded(false);1428                        setView("lock");1429                      }}1430                      onDone={handleAdoptionDone}1431                    />1432                  </Suspense>1433                }1434              >1435                <Show1436                  when={onboarded() || hasVault()}1437                  fallback={1438                    <Onboarding1439                      initialCard={onboardingCardAtExit()}1440                      onComplete={() => {1441                        markOnboardingExit("create");1442                        setStartOnboardingRestore(false);1443                        setOnboarded(true);1444                      }}1445                      onRestore={() => {1446                        markOnboardingExit("restore");1447                        setStartOnboardingRestore(true);1448                        setOnboarded(true);1449                      }}1450                      onAdopt={() => {1451                        markOnboardingExit("adopt");1452                        setStartOnboardingRestore(false);1453                        setOnboarded(true);1454                        setView("adopting");1455                      }}1456                    />1457                  }1458                >1459                  <LockView1460                    hasVault={hasVault()}1461                    ready={bootState() === "ready"}1462                    isPro={proStatus()}1463                    forceRecoveryWords={forceRecoveryWords()}1464                    initialRestore={startOnboardingRestore()}1465                    initialRestoreSource={resumeRestoreSource() ?? undefined}1466                    onUnlock={() => {1467                      // RecoveryWordDisplay clears the storage flag before1468                      // calling onDone, so handleUnlock will see no pending1469                      // confirmation and proceed through the normal path.1470                      if (forceRecoveryWords()) setForceRecoveryWords(false);1471                      // The create/restore flow is done — a lock later in this1472                      // window must show the unlock screen, not re-enter the1473                      // onboarding restore surface.1474                      setStartOnboardingRestore(false);1475                      setResumeRestoreSource(null);1476                      void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1477                      return handleUnlock();1478                    }}1479                    onBackToOnboarding={1480                      !hasVault()1481                        ? () => {1482                            // Deliberately rewinding to the carousel — the exit1483                            // flow must not reclaim the next popup open.1484                            clearOnboardingExit();1485                            setStartOnboardingRestore(false);1486                            setOnboarded(false);1487                          }1488                        : undefined1489                    }1490                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1491                  />1492                </Show>1493              </Show>1494            }1495          >1496            <Show1497              when={1498                view() !== "pro-celebration" &&1499                view() !== "initial-sync" &&1500                view() !== "whats-new" &&1501                view() !== "pro-nudge"1502              }1503              fallback={1504                <Show1505                  when={view() === "initial-sync"}1506                  fallback={1507                    <Show1508                      when={view() === "whats-new"}1509                      fallback={1510                        <Show when={view() === "pro-nudge"} fallback={<ProCelebration />}>1511                          <ProNudgeView1512                            onSeePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1513                            onDismiss={() => setView("entry")}1514                          />1515                        </Show>1516                      }1517                    >1518                      <WhatsNewView onContinue={() => setView("entry")} />1519                    </Show>1520                  }1521                >1522                  <InitialSyncView1523                    slow={initialSyncSlow()}1524                    onRetry={() => void retryInitialSync()}1525                  />1526                </Show>1527              }1528            >1529            <section1530              id="hd-shell"1531              class="peach-shell peach-theme"1532              data-surface="extension"1533            >1534            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1535              <PeachWordmark unlocked />1536              <div class="peach-chrome-actions">1537                <button1538                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1539                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1540                  aria-label="Notes"1541                  title="Notes"1542                >1543                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1544                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1545                    <line x1="4" y1="5" x2="10" y2="5" />1546                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1547                    <line x1="4" y1="10" x2="7" y2="10" />1548                  </svg>1549                </button>1550                <button1551                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1552                    classList={{1553                      "is-syncing": syncBusy(),1554                      "is-ok": syncFlash() === "ok",1555                      "is-error": syncFlash() === "error",1556                    }}1557                    onClick={() => void handleHeaderSync()}1558                    disabled={syncBusy()}1559                    aria-label={`Sync now. ${syncLabel()}`}1560                    title={syncLabel()}1561                  >1562                    <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">1563                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1564                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1565                      <path d="M2.6 1v2.4h2.4" />1566                      <path d="M11.4 13v-2.4H9" />1567                    </svg>1568                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1569                  </button>1570                <button1571                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1572                  onClick={() => setView("settings")}1573                  aria-label="Settings"1574                >1575                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1576                    <path1577                      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"1578                      stroke="currentColor"1579                      stroke-width="0.9"1580                    />1581                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1582                  </svg>1583                </button>1584                <button1585                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1586                  onClick={handleAdd}1587                  aria-label="New entry"1588                >1589                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1590                    <path d="M5.5 1v9M1 5.5h9" />1591                  </svg>1592                </button>1593                <button1594                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1595                  onClick={() => void handleHeaderLock()}1596                  aria-label="Lock vault"1597                >1598                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1599                    <path1600                      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"1601                      stroke="currentColor"1602                      stroke-width="1"1603                      stroke-linecap="round"1604                    />1605                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1606                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1607                  </svg>1608                </button>1609              </div>1610            </header>16111612            <Show when={pendingProNotice() !== null}>1613              <div class="peach-pro-notice-banner">1614                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1615                <button1616                  class="peach-pro-notice-link"1617                  onClick={() => {1618                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1619                    setSettingsInitialSection("license");1620                    setView("settings");1621                    setPendingProNotice(null);1622                  }}1623                >1624                  Learn more →1625                </button>1626                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1627              </div>1628            </Show>16291630            <Show when={pendingRememberSite()}>1631              {(request) => {1632                const origin = getSecurityOriginDisplay(request().url);1633                const originLabel = detectHomograph(origin) ? `⚠ ${origin}` : origin;1634                return (1635                  <div class="peach-pro-notice-banner">1636                    <span>Also use “{request().title}” on {originLabel}?</span>1637                    <button1638                      class="peach-pro-notice-link"1639                      onClick={async () => {1640                        await sendMessage({1641                          type: "ADD_ADDITIONAL_URL",1642                          payload: { id: request().entryId, url: request().url },1643                        });1644                        await chrome.storage.session.remove("pendingRememberSite");1645                        setPendingRememberSite(null);1646                      }}1647                    >1648                      Add1649                    </button>1650                    <button1651                      class="peach-pro-notice-close"1652                      onClick={async () => {1653                        await chrome.storage.session.remove("pendingRememberSite");1654                        setPendingRememberSite(null);1655                      }}1656                      aria-label="Dismiss"1657                    >1658                      ✕1659                    </button>1660                  </div>1661                );1662              }}1663            </Show>16641665            <div class="peach-shell-body">1666              <div class="peach-shell-veil"></div>1667              <div class="peach-content-frame" data-content-phase={contentPhase()}>1668                <EntryView1669                  keyboardEnabled={view() === "entry"}1670                  entry={selectedEntry()}1671                  currentTabUrl={currentTabUrl()}1672                  entries={entries()}1673                  isPro={proStatus()}1674                  onDelete={handleDelete}1675                  onFieldSaved={() => void loadEntries()}1676                  onEscape={() => { setView("list"); }}1677                  onProGate={(feature) => {1678                    setUpgradeHighlight(feature);1679                    setSettingsInitialSection("license");1680                    setView("settings");1681                  }}1682                />1683              </div>16841685              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1686                <div class="peach-search-bar">1687                  <span class="peach-search-icon">1688                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1689                      <circle cx="5.5" cy="5.5" r="3.75" />1690                      <path d="M8.75 8.75L11.5 11.5" />1691                    </svg>1692                  </span>1693                  <input1694                    class="peach-search-input"1695                    placeholder="search vault..."1696                    autocomplete="off"1697                    aria-label="Search vault entries"1698                    onClick={openList}1699                    onFocus={openList}1700                    readOnly1701                  />1702                  <div class="peach-search-meta">1703                    <span class="peach-search-counter">1704                      {nonNoteEntries().length > 01705                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1706                        : "0 entries"}1707                    </span>1708                    <span class="peach-divider"></span>1709                    <button1710                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1711                      onClick={() => navigate(-1)}1712                      aria-label="Previous entry"1713                      disabled={nonNoteEntries().length === 0}1714                    >1715                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1716                        <path d="M5 1L1 5.5L5 10" />1717                      </svg>1718                    </button>1719                    <button1720                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1721                      onClick={() => navigate(1)}1722                      aria-label="Next entry"1723                      disabled={nonNoteEntries().length === 0}1724                    >1725                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1726                        <path d="M1 1L5 5.5L1 10" />1727                      </svg>1728                    </button>1729                  </div>1730                </div>1731              </section>1732            </div>17331734            {/* Rare device-trust alerts; normal sync changes are silent. */}1735            <Show when={alertGroups().length > 0}>1736              <div class="peach-sync-alerts">1737                <For each={alertGroups()}>1738                  {([type, group]) => {1739                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1740                    return (1741                      <div class="peach-sync-alert">1742                        <Show when={group.length > 1}>1743                          <button1744                            class="peach-sync-alert-flip"1745                            type="button"1746                            aria-label="Previous"1747                            onClick={() => flipAlert(type, -1)}1748                          >‹</button>1749                        </Show>1750                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1751                        <Show when={group.length > 1}>1752                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1753                          <button1754                            class="peach-sync-alert-flip"1755                            type="button"1756                            aria-label="Next"1757                            onClick={() => flipAlert(type, 1)}1758                          >›</button>1759                        </Show>1760                        <button1761                          class="peach-sync-alert-dismiss"1762                          type="button"1763                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1764                          onClick={() => void dismissAlertGroup(type as SyncAlert["type"])}1765                        >×</button>1766                      </div>1767                    );1768                  }}1769                </For>1770              </div>1771            </Show>17721773            <Show when={view() === "list"}>1774              <VaultView1775                entries={entries()}1776                selectedEntryId={selectedEntry()?.id}1777                currentTabDomain={currentTabDomain()}1778                sortOrder={sortOrder()}1779                searchSeed={listSearchSeed()}1780                searchSeedNonce={listSearchSeedNonce()}1781                onSelectEntry={handleSelectEntry}1782                onSortOrderChange={setSortOrder}1783                onAdd={handleAdd}1784                onClose={() => setView("entry")}1785                onOpenTrash={() => setView("trash")}1786                onDeleteMany={handleDeleteMany}1787              />1788            </Show>1789            <Show when={view() === "settings" || settingsExiting()}>1790              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1791                <SettingsView1792                  entriesCount={entries().length}1793                  breachMonitoring={breachMonitoring()}1794                  lockOnClose={lockOnClose()}1795                  autoLockMinutes={autoLockMinutes()}1796                  trashRetentionDays={trashRetentionDays()}1797                  lockedSyncRequiresUnlock={lockedSyncRequiresUnlock()}1798                  theme={theme()}1799                  accentColor={accentColor()}1800                  textSize={textSize()}1801                  reduceMotion={reduceMotion()}1802                  isPro={proStatus()}1803                  initialSection={settingsInitialSection()}1804                  upgradeHighlight={upgradeHighlight()}1805                  isExiting={settingsExiting()}1806                  onBreachMonitoringChange={applyBreachMonitoring}1807                  onLockOnCloseChange={applyLockOnClose}1808                  onLockedSyncRequiresUnlockChange={applyLockedSyncRequiresUnlock}1809                  onAutoLockMinutesChange={applyAutoLockMinutes}1810                  onTrashRetentionChange={applyTrashRetention}1811                  onThemeChange={applyTheme}1812                  onAccentChange={applyAccentColor}1813                  onTextSizeChange={applyTextSize}1814                  onReduceMotionChange={applyReduceMotion}1815                  shortcuts={shortcutBindings()}1816                  onShortcutsChange={applyShortcuts}1817                  onLicenseChange={async () => {1818                    // After activation/deactivation: refresh Pro status,1819                    // re-load entries (defensive — signal state can drift if1820                    // the SW briefly restarts during the verify+save round-trip),1821                    // and replay the Pro celebration if this is the first time1822                    // a valid Pro license is seen on this device.1823                    await refreshProStatus();1824                    void loadEntries();1825                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1826                    if ((should as { ok: boolean; data?: boolean }).data === true) {1827                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1828                      setView("pro-celebration");1829                      window.setTimeout(() => setView("settings"), 2500);1830                    }1831                  }}1832                  onBack={() => {1833                    setSettingsExiting(true);1834                    window.setTimeout(() => {1835                      setSettingsExiting(false);1836                      setSettingsInitialSection(null);1837                      setUpgradeHighlight(null);1838                      handleBack();1839                    }, 200);1840                  }}1841                  onImport={() => setView("import")}1842                  onExport={() => setView("export")}1843                  onBreachCheckDone={loadEntries}1844                  onOpenHealth={openHealth}1845                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1846                  onOpenFileImport={handleOpenFileImport}1847                  onOpenPanic={() => setView("panic")}1848                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1849                  onOpenCodexRestore={() => setView("codex-restore")}1850                  onCardChange={setSettingsActiveCard}1851                  onProGate={(feature) => {1852                    setUpgradeHighlight(feature);1853                    setSettingsInitialSection("license");1854                  }}1855                />1856              </Suspense>1857            </Show>1858            <Show when={view() === "codex-generate"}>1859              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1860                <CodexGenerateView1861                  isPro={proStatus()}1862                  onBack={() => setView("settings")}1863                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1864                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1865                  onVaultLocked={() => handleLock()}1866                />1867              </Suspense>1868            </Show>1869            <Show when={view() === "codex-restore"}>1870              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1871                <CodexRestoreView1872                  onBack={() => setView("lock")}1873                  onRestoreSuccess={async () => {1874                    // After restore the vault is unlocked; refresh entries1875                    // and route to the main vault list. handleUnlock is the1876                    // canonical post-unlock setup path.1877                    await handleUnlock();1878                  }}1879                />1880              </Suspense>1881            </Show>1882            <Show when={view() === "pair-device"}>1883              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1884                <PairDeviceView1885                  isPro={proStatus()}1886                  onProChanged={() => { void refreshProStatus(); }}1887                  onBack={() => setView("settings")}1888                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1889                />1890              </Suspense>1891            </Show>1892            <Show when={view() === "add"}>1893              <AddView1894                entry={editEntry()}1895                entries={entries()}1896                onBack={handleBack}1897                onSave={handleSave}1898              />1899            </Show>1900            <Show when={view() === "import"}>1901              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1902                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1903              </Suspense>1904            </Show>1905            <Show when={view() === "export"}>1906              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1907                <ExportView onBack={handleExportBack} />1908              </Suspense>1909            </Show>1910            <Show when={view() === "panic"}>1911              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1912                <PanicView1913                  onCancel={() => setView("settings")}1914                  onOpenExport={() => {1915                    setReturnToPanic(true);1916                    setView("export");1917                  }}1918                  onDestroyed={async () => {1919                    // Fresh onboarding start after a destroy — don't let the1920                    // resume markers land the user mid-carousel.1921                    setOnboardingCardAtExit(0);1922                    void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1923                    clearOnboardingExit();1924                    setEntries([]);1925                    setSelectedEntry(null);1926                    setEditEntry(undefined);1927                    setHasVault(false);1928                    setOnboarded(false);1929                    setProStatus(false);1930                    setPendingPasskey(null);1931                    setUpgradeHighlight(null);1932                    setSettingsInitialSection(null);1933                    setPendingProNotice(null);1934                    setPendingCelebration(false);1935                    setReturnToPanic(false);1936                    setContentPhase("idle");1937                    setView("lock");1938                  }}1939                />1940              </Suspense>1941            </Show>1942            {/* Health stays mounted while editing an entry from it so1943                computeReused() doesn't rerun on every cancel/back. */}1944            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1945              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1946                <HealthView1947                  entries={entries()}1948                  isPro={proStatus()}1949                  onFixEntry={handleFixEntry}1950                  onBack={() => setView("settings")}1951                  onRefresh={loadEntries}1952                  hidden={view() !== "health"}1953                />1954              </Suspense>1955            </Show>1956            <Show when={view() === "trash"}>1957              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1958                <TrashView1959                  onBack={() => setView("list")}1960                  onRestored={() => void loadEntries()}1961                />1962              </Suspense>1963            </Show>1964            <Show when={showNotes()}>1965              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1966                <NotesMode1967                  notes={entries().filter((e) => e.type === "note")}1968                  initialNoteId={openNoteId()}1969                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1970                  onNoteListChanged={() => void loadEntries()}1971                />1972              </div>1973            </Show>1974            <Show when={restoreView() === "file"}>1975              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1976                <ImportView1977                  mode="onboarding"1978                  replacesExistingVault={true}1979                  onBack={() => setRestoreView(null)}1980                  onImport={async () => {1981                    setRestoreView(null);1982                    await handleUnlock();1983                  }}1984                />1985              </Suspense>1986            </Show>1987            </section>1988            </Show>1989          </Show>1990        </Show>1991      </Show>1992      <Show when={showShortcutsHelp()}>1993        <ShortcutsHelpOverlay1994          bindings={shortcutBindings()}1995          onClose={() => setShowShortcutsHelp(false)}1996        />1997      </Show>1998    </div>1999  );2000}20012002function ShortcutsHelpOverlay(props: {2003  bindings: Record<ShortcutAction, Keybinding>;2004  onClose: () => void;2005}) {2006  return (2007    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>2008      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>2009        <div class="peach-shortcuts-help-head">2010          <h3>Keyboard shortcuts</h3>2011          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>2012        </div>2013        <div class="peach-shortcuts-help-body">2014          <p class="peach-settings-sub-label">ENTRY VIEW</p>2015          <ul>2016            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (2017              <li>2018                <span>{d.label}</span>2019                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2020              </li>2021            ))}2022          </ul>2023          <p class="peach-settings-sub-label">ANYWHERE</p>2024          <ul>2025            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (2026              <li>2027                <span>{d.label}</span>2028                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2029              </li>2030            ))}2031          </ul>2032        </div>2033      </div>2034    </div>2035  );2036}