App.tsx

77.9 KB · raw

1import { createEffect, createMemo, createSignal, For, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { storageGet, storageRemove, storageSet } from "../shared/storage";3import { sendMessage } from "../shared/bridge";4import { ACCENT_COLORS } from "../shared/types";5import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";6import { isPasskeyOnly } from "../shared/types";7import {8  hasCompletedInitialSync,9  INITIAL_SYNC_PENDING_DEVICE_KEY,10  type InitialSyncDevice,11} from "../shared/initial-sync";12import { LockView, RESTORE_SOURCE_STORAGE_KEY, type RestoreSource } from "./views/Lock";13import {14  ONBOARDING_CARD_STORAGE_KEY,15  ONBOARDING_LAST_CARD,16  Onboarding,17} from "./views/Onboarding";1819const ONBOARDING_EXIT_STORAGE_KEY = "peach_onboarding_exit";20import { NotesMode } from "./views/NotesMode";21import { ProCelebration } from "./views/ProCelebration";22import { InitialSyncView } from "./views/InitialSyncView";23import { VaultView, type SortOrder } from "./views/Vault";24import { EntryView } from "./views/Entry";25import { AddView } from "./views/Add";26import { PeachWordmark } from "./components/PeachMark";27import { PasskeyApprovalView } from "./views/PasskeyApproval";28import { extractDomain } from "../shared/domain";29import {30  syncIndicator,31  syncIndicatorLabel,32  type SyncOutcomeSummary,33} from "../shared/sync-outcome";34import { popupCopy } from "./copy";35import {36  DEFAULT_BINDINGS,37  formatKeybinding,38  getActiveBindings,39  matchKeybinding,40  SHORTCUT_DESCRIPTORS,41  type Keybinding,42  type ShortcutAction,43} from "../shared/shortcuts";44import { generateTOTP } from "../crypto/totp";4546export { sendMessage } from "../shared/bridge";4748const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));49const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));50const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));51const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));52const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));53const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));54const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));55const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));56const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));57const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));5859type View =60  | "lock"61  | "pro-celebration"62  | "entry"63  | "list"64  | "add"65  | "settings"66  | "pair-device"67  | "import"68  | "export"69  | "health"70  | "trash"71  | "panic"72  | "adopting"73  | "initial-sync"74  | "codex-generate"75  | "codex-restore";76type BootState = "loading" | "ready";7778const INITIAL_SYNC_POLL_MS = 500;79const INITIAL_SYNC_SLOW_MS = 15_000;8081let shellRingAnimation: Animation | null = null;8283export function triggerRing() {84  const shell = document.getElementById("hd-shell");85  if (!shell) return;8687  shellRingAnimation?.cancel();88  shell.dataset.glowing = "true";89  const animation = shell.animate(90    [91      { offset: 0, boxShadow: "var(--copy-shadow)" },92      {93        offset: 0.3,94        boxShadow:95          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",96      },97      { offset: 1, boxShadow: "var(--copy-shadow)" },98    ],99    {100      duration: 720,101      easing: "cubic-bezier(0.4, 0, 0.2, 1)",102      fill: "none",103    }104  );105  shellRingAnimation = animation;106  const clearGlow = () => {107    if (shellRingAnimation !== animation) return;108    shellRingAnimation = null;109    delete shell.dataset.glowing;110  };111  animation.onfinish = clearGlow;112  animation.oncancel = clearGlow;113}114115export function triggerPipPulse() {116  const pip = document.querySelector(".peach-status-pip, .pip");117  if (pip) {118    pip.classList.remove("pulse");119    void (pip as HTMLElement).offsetWidth;120    pip.classList.add("pulse");121  }122}123124const ENTRY_TRANSITION_SETTLE_MS = 135;125126export default function App() {127  const [bootState, setBootState] = createSignal<BootState>("loading");128  const [view, setView] = createSignal<View>("lock");129  const [contentPhase, setContentPhase] = createSignal<"enter" | "idle">("enter");130  const [hasVault, setHasVault] = createSignal(false);131  const [onboarded, setOnboarded] = createSignal(true);132  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);133  // The restore source picked before the popup closed (the OS file picker134  // kills it), so reopening resumes the same source form instead of the135  // picker. Read from RESTORE_SOURCE_STORAGE_KEY at boot.136  const [resumeRestoreSource, setResumeRestoreSource] = createSignal<RestoreSource | null>(null);137  // Onboarding remounts whenever it leaves (create/adopt/restore) and comes138  // back. Those flows all exit from the final card, so resume there — a fresh139  // install's first mount stays at 0.140  const [onboardingCardAtExit, setOnboardingCardAtExit] = createSignal(0);141  const [entries, setEntries] = createSignal<VaultEntry[]>([]);142  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);143  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);144145  // Rare device-trust alerts stay visible; routine entry sync is silent.146  interface SyncAlert {147    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";148    entryId: string;149    entryTitle: string;150    deviceName: string;151    timestamp: number;152  }153  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);154  // Per-group flip index: which alert within a type-group is currently shown.155  const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});156  async function loadSyncAlerts() {157    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {158      ok: boolean;159      data?: SyncAlert[];160    };161    if (r.ok && (r.data?.length ?? 0) > 0) {162      setSyncAlerts(r.data ?? []);163      // Acknowledge so a crash between read and render doesn't lose them —164      // they remain on screen until the user dismisses each.165      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });166    }167  }168  function dismissAlertGroup(type: string) {169    setSyncAlerts((arr) => arr.filter((a) => a.type !== type));170    setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });171  }172  function flipAlert(type: string, dir: 1 | -1) {173    const group = syncAlerts().filter((a) => a.type === type);174    if (group.length <= 1) return;175    setAlertFlipIdx((m) => {176      const cur = m[type] ?? 0;177      return { ...m, [type]: (cur + dir + group.length) % group.length };178    });179  }180  /** Grouped alert types in display order, each with its alerts. */181  const alertGroups = createMemo(() => {182    const map = new Map<string, SyncAlert[]>();183    for (const a of syncAlerts()) {184      const g = map.get(a.type);185      if (g) g.push(a); else map.set(a.type, [a]);186    }187    return [...map.entries()];188  });189  function syncAlertText(a: SyncAlert): string {190    if (a.type === "DEVICE_REVOKED") {191      return `${a.deviceName} revoked a paired device — review your devices in Settings`;192    }193    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;194  }195  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");196  const [theme, setTheme] = createSignal<"dark" | "light">("dark");197  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");198  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);199  const [lockOnClose, setLockOnClose] = createSignal(false);200  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);201  const [breachMonitoring, setBreachMonitoring] = createSignal(true);202  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);203  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);204  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);205  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);206  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);207  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");208  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");209  // Cached Pro status — synchronous for render paths. Background's210  // GET_LICENSE is async, but render-time reads of isPro() must not block.211  // Refreshed at boot, after activate/deactivate, and whenever the popup212  // re-opens onto a stored license that has changed via another window.213  const [proStatus, setProStatus] = createSignal(false);214  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);215  // When the sync card's pairing button opens the pairing view, deep-link216  // straight into that pairing path instead of the rest screen.217  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");218  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);219  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");220  const [listSearchSeed, setListSearchSeed] = createSignal("");221  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);222  const [pendingCelebration, setPendingCelebration] = createSignal(false);223  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);224  // True while Panic Step 1 has bounced the user out to Export. When Export's225  // onBack fires we return to Panic instead of Settings so the user keeps the226  // destruction context they came from.227  const [returnToPanic, setReturnToPanic] = createSignal(false);228  // The view to return to when the add/edit view is dismissed. Normally "entry"229  // but "health" when the user arrives via the fix-entry path from Vault Health.230  const [editBackView, setEditBackView] = createSignal<View>("entry");231  const [settingsExiting, setSettingsExiting] = createSignal(false);232  const [showNotes, setShowNotes] = createSignal(false);233  // Topbar sync affordance. Always present: gating it on having a paired device234  // meant it never appeared for the person trying to set pairing up, which is235  // exactly when you reach for it.236  const [syncBusy, setSyncBusy] = createSignal(false);237  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);238  // The indicator light + its spoken-word equivalent. Colour alone is not the239  // signal; the title/aria-label always carries the same claim in English.240  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});241  const [pairedCount, setPairedCount] = createSignal(0);242  const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);243  const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);244  let initialSyncWaitGeneration = 0;245  const syncLight = () =>246    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());247  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());248  async function loadSyncIndicator() {249    const [stateRes, devicesRes] = await Promise.all([250      sendMessage({ type: "GET_SYNC_STATE" }),251      sendMessage({ type: "LIST_PAIRED_DEVICES" }),252    ]);253    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };254    if (s.ok && s.data) setSyncSummary(s.data);255    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };256    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);257  }258259  interface InitialSyncPairedDevice extends InitialSyncDevice {260    pairedAt?: number;261  }262263  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {264    const response = (await sendMessage({265      type: "LIST_PAIRED_DEVICES",266    })) as {267      ok: boolean;268      data?: { devices?: InitialSyncPairedDevice[] };269    };270    return response.ok ? response.data?.devices ?? [] : [];271  }272273  async function resolveInitialSyncDeviceId(): Promise<string | null> {274    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(275      () => null,276    );277    const devices = await listInitialSyncDevices().catch(() => []);278    if (stored && devices.some((device) => device.deviceId === stored)) {279      return stored;280    }281282    // Fresh adoption has exactly one direct source, but choosing the newest row283    // also repairs the marker if storage failed after the pair itself committed.284    const newest = [...devices].sort(285      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),286    )[0];287    if (!newest) return stored;288    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(289      () => undefined,290    );291    return newest.deviceId;292  }293294  async function finishInitialSync(generation: number): Promise<void> {295    if (generation !== initialSyncWaitGeneration) return;296    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);297    setInitialSyncDeviceId(null);298    setInitialSyncSlow(false);299    await refreshProStatus();300301    // A license transferred during pairing intentionally leaves the one-shot302    // celebration pending. Consume it only now: sync readiness → celebration303    // → populated vault, never celebration → temporarily empty vault.304    const celebration = (await sendMessage({305      type: "SHOULD_PLAY_CELEBRATION",306    })) as { ok: boolean; data?: boolean };307    const shouldCelebrate = celebration.ok && celebration.data === true;308    if (shouldCelebrate) {309      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });310    }311312    const opened = await openVault(undefined, shouldCelebrate);313    if (!opened || generation !== initialSyncWaitGeneration) return;314    if (shouldCelebrate) {315      setView("pro-celebration");316      window.setTimeout(() => {317        if (generation === initialSyncWaitGeneration) setView("entry");318      }, 2500);319    }320  }321322  async function beginInitialSyncWait(deviceId: string): Promise<void> {323    const generation = ++initialSyncWaitGeneration;324    setInitialSyncDeviceId(deviceId);325    setInitialSyncSlow(false);326    setView("initial-sync");327    const startedAt = Date.now();328329    // Best effort: the pairing write already wakes the mesh listener, while330    // this trigger covers the key-order case where this receiver is the dialer.331    void sendMessage({332      type: "TRIGGER_SYNC",333      payload: { reason: "foreground" },334    }).catch(() => undefined);335336    while (337      generation === initialSyncWaitGeneration &&338      view() === "initial-sync"339    ) {340      try {341        const devices = await listInitialSyncDevices();342        if (hasCompletedInitialSync(devices, deviceId)) {343          await finishInitialSync(generation);344          return;345        }346      } catch {347        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.348      }349      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {350        setInitialSyncSlow(true);351      }352      await new Promise((resolve) =>353        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),354      );355    }356  }357358  async function retryInitialSync(): Promise<void> {359    const deviceId =360      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());361    if (deviceId) {362      await beginInitialSyncWait(deviceId);363    } else {364      setInitialSyncSlow(true);365    }366  }367368  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);369  // Set on popup boot when peach_recovery_pending flag is found in session370  // storage — instructs LockView to skip the unlock UI and open the recovery371  // words confirmation surface instead. Cleared via handleUnlock once the372  // user has typed the 3 confirmation words.373  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);374375  let contentPhaseTimer: number | undefined;376  // Set when the popup was opened from the inline "Open Peach to unlock" button.377  // handleUnlock() closes the popup after unlock so the user returns to the page.378  let openedForInlineUnlock = false;379380  onCleanup(() => {381    initialSyncWaitGeneration += 1;382  });383384  function applyAccent(name: AccentColorName) {385    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;386    const hex = color.hex;387    document.documentElement.style.setProperty("--peach-accent", hex);388    // Ambient variables derived from the selected accent.389    document.documentElement.style.setProperty("--peach-glow", hex + "2A");390    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");391  }392393  createEffect(() => {394    applyAccent(accentColor());395  });396397  createEffect(() => {398    document.documentElement.classList.toggle("light", theme() === "light");399    document.body.classList.toggle("light", theme() === "light");400  });401402  createEffect(() => {403    document.documentElement.setAttribute("data-text-size", textSize());404  });405406  createEffect(() => {407    if (reduceMotion()) {408      document.documentElement.setAttribute("data-motion", "reduce");409    } else {410      document.documentElement.removeAttribute("data-motion");411    }412  });413414  // Notes are not a destination of the Entry view; selecting a note opens the415  // notes surface instead (handleSelectEntry). Anything that walks or counts416  // the Entry view's neighbours (counter, prev/next, index) must use this417  // filtered list, otherwise the user can arrow into a note and is stuck —418  // the Entry view can't render a note and the prev/next buttons stop moving.419  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));420421  const selectedIndex = createMemo(() => {422    const currentId = selectedEntry()?.id;423    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;424    return nonNoteEntries().findIndex((entry) => entry.id === currentId);425  });426427  async function applyAccentColor(name: AccentColorName) {428    applyAccent(name);429    setAccentColor(name);430    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });431  }432433  async function applyTheme(t: "dark" | "light") {434    setTheme(t);435    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });436  }437438  async function applyTextSize(size: "small" | "medium" | "large") {439    setTextSize(size);440    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });441  }442443  async function applyReduceMotion(enabled: boolean) {444    setReduceMotion(enabled);445    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });446  }447448  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload449  // small and lets future default updates land for actions the user hasn't450  // touched. Settings sends us the full active map; we filter and store.451  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {452    setShortcutBindings(active);453    const overrides: Record<string, Keybinding> = {};454    for (const action of Object.keys(active) as ShortcutAction[]) {455      const a = active[action];456      const d = DEFAULT_BINDINGS[action];457      const same = a.key === d.key458        && Boolean(a.ctrl)  === Boolean(d.ctrl)459        && Boolean(a.meta)  === Boolean(d.meta)460        && Boolean(a.shift) === Boolean(d.shift)461        && Boolean(a.alt)   === Boolean(d.alt);462      if (!same) overrides[action] = a;463    }464    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });465  }466467  async function applyLockOnClose(enabled: boolean) {468    setLockOnClose(enabled);469    await sendMessage({470      type: "UPDATE_SETTINGS",471      payload: { lockOnClose: enabled },472    });473  }474475  async function applyAutoLockMinutes(minutes: number) {476    setAutoLockMinutes(minutes);477    await sendMessage({478      type: "UPDATE_SETTINGS",479      payload: { autoLockMinutes: minutes },480    });481  }482483  async function applyBreachMonitoring(enabled: boolean) {484    setBreachMonitoring(enabled);485    await sendMessage({486      type: "UPDATE_SETTINGS",487      payload: { breachMonitoring: enabled },488    });489  }490491  // Which onboarding exit flow the user is in (create-vault / restore /492  // adopt). Persisted so closing the popup on one of those screens resumes493  // it directly instead of rewinding to the last carousel card.494  function markOnboardingExit(flow: "create" | "restore" | "adopt") {495    setOnboardingCardAtExit(ONBOARDING_LAST_CARD);496    void storageSet(ONBOARDING_EXIT_STORAGE_KEY, flow).catch(() => {});497    // Backing out of the flow remounts the carousel at this card; keep the498    // persisted card in sync so a later popup close resumes consistently.499    void storageSet(ONBOARDING_CARD_STORAGE_KEY, String(ONBOARDING_LAST_CARD)).catch(() => {});500  }501  function clearOnboardingExit() {502    void storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});503    void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});504    setResumeRestoreSource(null);505  }506507  onMount(async () => {508    // Resolve the active tab in parallel with the unlock/has-vault queries —509    // openVault()'s smart selection picks the entry matching currentTabDomain,510    // so it must be populated before openVault runs. Previously refreshCurrentTab511    // ran after openVault, leaving popups that booted already-unlocked falling512    // back to loadedEntries[0] instead of the domain match.513    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([514      sendMessage({ type: "IS_UNLOCKED" }),515      sendMessage({ type: "HAS_VAULT" }),516      refreshCurrentTab(),517      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),518    ]);519    const unlocked = Boolean(520      (unlockResponse as { ok: boolean; data?: boolean }).data521    );522    const vaultExists = Boolean(523      (vaultResponse as { ok: boolean; data?: boolean }).data524    );525    const shouldCelebrate = Boolean(526      (celebrationResponse as { ok: boolean; data?: boolean }).data527    );528    setHasVault(vaultExists);529    // Onboarding gate — show once on first install, never again. Existing530    // users (vaultExists) are auto-marked onboarded so they skip the flow531    // even on the very first popup open after this feature ships.532    try {533      const onboarded = await storageGet("peach_onboarded");534      const seen = onboarded === "true";535      if (vaultExists && !seen) {536        await storageSet("peach_onboarded", "true");537        await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});538        await storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});539        await storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});540        setOnboarded(true);541      } else {542        setOnboarded(seen);543        if (!seen) {544          // A popup close while the user is in an exit flow (create-vault /545          // restore / adopt) resumes that flow directly — landing back on the546          // carousel one screen earlier reads as losing progress.547          const exit = await storageGet(ONBOARDING_EXIT_STORAGE_KEY).catch(() => null);548          if (exit === "create" || exit === "restore" || exit === "adopt") {549            setOnboardingCardAtExit(ONBOARDING_LAST_CARD);550            setOnboarded(true);551            setStartOnboardingRestore(exit === "restore");552            if (exit === "restore") {553              // The OS file picker kills the action popup mid-restore, so the554              // surface resumes on the source the user had already picked.555              const source = await storageGet(RESTORE_SOURCE_STORAGE_KEY).catch(() => null);556              if (source === "symbols" || source === "codex" || source === "csv") {557                setResumeRestoreSource(source);558              }559            }560            if (exit === "adopt") setView("adopting");561          } else {562            // Otherwise resume mid-onboarding where the user left off instead563            // of rewinding to the opening card.564            const stored = Number(565              await storageGet(ONBOARDING_CARD_STORAGE_KEY).catch(() => null),566            );567            if (568              Number.isInteger(stored) &&569              stored > 0 &&570              stored <= ONBOARDING_LAST_CARD571            ) {572              setOnboardingCardAtExit(stored);573            }574          }575        }576      }577    } catch {578      // storage unavailable — default to onboarded so we never block boot579      setOnboarded(true);580    }581582    // Deep-link: ?restore=peachscript|csv — the detached-window half of the583    // file-picker flow. The action popup dismisses when the OS dialog steals584    // focus, so LockView.detachForFilePicker() reopens this URL in a585    // standalone window that owns the dialog. Routing runs before first586    // render so LockView mounts straight onto the right source form.587    try {588      const restoreRoute = new URLSearchParams(window.location.search).get("restore");589      if (restoreRoute === "peachscript" || restoreRoute === "csv") {590        setOnboarded(true);591        setStartOnboardingRestore(true);592        setResumeRestoreSource(restoreRoute === "peachscript" ? "symbols" : "csv");593      }594    } catch {595      // location.search unavailable — ignore.596    }597598    await Promise.all([restoreSettings(), refreshProStatus()]);599600    const pendingInitialSyncMarker =601      unlocked && vaultExists602        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)603        : null;604    const pendingInitialSyncDeviceId = pendingInitialSyncMarker605      ? await resolveInitialSyncDeviceId()606      : null;607608    // Mark played before any animation so a crash mid-sequence never replays609    // it. A newly adopted receiver deliberately defers this until its first610    // real sync finishes, preserving initial sync → celebration → vault.611    if (shouldCelebrate && !pendingInitialSyncDeviceId) {612      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });613    }614615    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome616    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.617    if (unlocked && vaultExists) {618      void sendMessage({619        type: "TRIGGER_SYNC",620        payload: { reason: "foreground" },621      });622      void loadSyncIndicator();623      // Rare device-trust alerts only; routine entry sync stays quiet.624      void loadSyncAlerts();625    }626627    // If the user created a vault but hasn't yet confirmed their recovery628    // words, route back to the recovery-words screen instead of opening the629    // entries view. The flag lives in chrome.storage.local so it survives630    // popup close while the background owns the session-scoped confirmation631    // exemption. Cleared when confirmation succeeds.632    let recoveryPending = false;633    try {634      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });635      recoveryPending = out.ok === true && out.data === true;636    } catch { /* best-effort */ }637638    // If this popup was opened from the inline "Open Peach to unlock" button,639    // the background set a session flag. Read and clear it so handleUnlock()640    // can close the popup after unlock and return the user to the page.641    if (chrome.storage.session) {642      try {643        const s = await chrome.storage.session.get("peach_inline_unlock");644        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {645          openedForInlineUnlock = true;646          await chrome.storage.session.remove("peach_inline_unlock");647        }648      } catch { /* best-effort */ }649    }650651    if (recoveryPending && unlocked) {652      // forceRecoveryWords overrides LockView's hasVault gate so the653      // recovery surface renders even though the vault now exists.654      setForceRecoveryWords(true);655      setView("lock");656    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {657      void beginInitialSyncWait(pendingInitialSyncDeviceId);658    } else if (unlocked && vaultExists) {659      await openVault(undefined, shouldCelebrate);660      if (shouldCelebrate) {661        setView("pro-celebration");662        window.setTimeout(() => setView("entry"), 2500);663      }664    } else if (shouldCelebrate) {665      setPendingCelebration(true);666    }667668    await refreshPendingPasskey();669670    // Track tab changes so smart sort stays current671    const handleTabActivated = () => { void refreshCurrentTab(); };672    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {673      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();674    };675    try {676      chrome.tabs.onActivated.addListener(handleTabActivated);677      chrome.tabs.onUpdated.addListener(handleTabUpdated);678      onCleanup(() => {679        chrome.tabs.onActivated.removeListener(handleTabActivated);680        chrome.tabs.onUpdated.removeListener(handleTabUpdated);681      });682    } catch {683      // tabs permission may not be available in all contexts684    }685686    setBootState("ready");687688    // Deep-link: ?codex=pdf opens a detached window straight into the689    // Codex restore flow with auto-picked PDF. The action popup can't host690    // a file dialog without dismissing itself, so this is the only way the691    // PDF import path survives. See CodexRestoreView.openPdfPicker().692    try {693      const route = new URLSearchParams(window.location.search).get("codex");694      if (route === "pdf" || route === "restore") {695        setView("codex-restore");696      }697    } catch {698      // location.search unavailable — ignore.699    }700701    // Check for pending session-storage notices from the background.702    if (chrome.storage.session) {703      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as704        Record<string, { feature?: string } | undefined>;705      if (session.pendingProGate?.feature) {706        await chrome.storage.session.remove("pendingProGate");707        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);708        setSettingsInitialSection("license");709        setView("settings");710      } else if (session.pendingProNotice?.feature) {711        await chrome.storage.session.remove("pendingProNotice");712        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });713      }714    }715716    // Warm the lazy-module cache so the Suspense fallback never shows for717    // locally-bundled extension views. Without this, the first navigation to718    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which719    // covers the shell and absorbs clicks on the header.720    void Promise.all([721      import("./views/Settings").catch(() => {}),722      import("./views/Import").catch(() => {}),723      import("./views/Export").catch(() => {}),724      import("./views/Health").catch(() => {}),725      import("./views/TrashView").catch(() => {}),726    ]);727728    // Lock-on-close via a persistent port. sendMessage in pagehide is729    // unreliable — the popup context tears down before the message lands.730    // The SW's onConnect listener locks when this port disconnects.731    let popupPort: chrome.runtime.Port | null = null;732    try {733      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect734      // listener accepts the "popup-" prefix; the random suffix is defence in735      // depth against a port named exactly "popup" from anything but our popup.736      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });737    } catch { /* extension context invalidated — ignore */ }738    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });739740    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale741    // entries instead of waiting for the next GET_ENTRIES round-trip.742    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {743      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();744      if (msg?.type === "SYNC_STATE_CHANGED") {745        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);746      }747      if (msg?.type === "PRO_GATE_TRIGGERED") {748        setUpgradeHighlight(msg.payload?.feature ?? null);749        setSettingsInitialSection("license");750        setView("settings");751      }752    };753    chrome.runtime.onMessage.addListener(handleRuntimeMessage);754    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));755756    // Action handlers — keyed by ShortcutAction. The dispatcher below tests757    // each binding against the event and runs the matching handler. New758    // shortcuts only need an entry here; the binding is data, not code.759    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {760      copy_password: () => {761        const entry = selectedEntry();762        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });763      },764      copy_username: () => {765        const entry = selectedEntry();766        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });767      },768      copy_totp: () => {769        const entry = selectedEntry();770        if (!entry?.totp) return;771        try {772          const { code } = generateTOTP(773            entry.totp,774            entry.totpAlgorithm,775            entry.totpDigits,776            entry.totpPeriod,777          );778          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });779        } catch { /* invalid TOTP secret — silent */ }780      },781      new_entry: () => handleAdd(),782      edit_entry: () => {783        const entry = selectedEntry();784        // Passkey-only entries have nothing user-editable in the Add view; the785        // passkey credential itself is opaque. Skip the edit action for them.786        if (!entry || isPasskeyOnly(entry)) return;787        setEditEntry(entry);788        setView("add");789      },790      delete_entry: () => {791        if (selectedEntry()) void handleDelete();792      },793      lock_vault: () => { void handleHeaderLock(); },794      search: () => openList(),795      nav_prev: () => navigate(-1),796      nav_next: () => navigate(1),797      jump_vault: () => setView("entry"),798      jump_settings: () => setView("settings"),799      show_help: () => setShowShortcutsHelp(true),800    };801802    // Actions that are MEANINGFUL only on the entry-detail view. Outside803    // that scope the binding is dormant — pressing C while on Settings804    // does nothing rather than awkwardly copying from a now-stale entry.805    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([806      "copy_password", "copy_username", "copy_totp",807      "edit_entry", "delete_entry", "nav_prev", "nav_next",808    ]);809810    const handleGlobalKeydown = (e: KeyboardEvent) => {811      const v = view();812      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"813        || (e.target as HTMLElement)?.tagName === "TEXTAREA"814        || (e.target as HTMLElement)?.isContentEditable;815      const isPrintableSearchKey =816        e.key.length === 1 &&817        !e.ctrlKey &&818        !e.metaKey &&819        !e.altKey;820821      // No shortcuts while a full-screen surface owns the whole viewport:822      // the lock screen, the post-pairing readiness sequence, or the Pro823      // celebration. Without this the lock screen is at the mercy of whatever824      // single-key binding is active — e.g. typing "n" in a password that825      // slips out of focus triggers `new_entry` and escapes the lock screen.826      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;827828      // Help dialog: Escape closes it; eat the keypress so it doesn't829      // also navigate away from the underlying view.830      if (showShortcutsHelp()) {831        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }832        return;833      }834835      // ── Escape — fixed binding (not user-customizable) ───────836      if (e.key === "Escape") {837        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }838        if (v === "list") { setView("entry"); return; }839        if (v === "settings" || v === "add") { handleBack(); return; }840        if (v === "import" || v === "health") { setView("settings"); return; }841        if (v === "export") { handleExportBack(); return; }842        if (v === "pair-device") { setView("settings"); return; }843      }844845      // Bindings-driven dispatch. Single-key letter bindings without846      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is847      // inside an input, so users can type into search/forms normally.848      const bindings = shortcutBindings();849      for (const action of Object.keys(bindings) as ShortcutAction[]) {850        const binding = bindings[action];851        if (!matchKeybinding(e, binding)) continue;852        // Single-key letter bindings need the input-focus guard. Bindings853        // with any modifier are safe — Ctrl+L doesn't conflict with typing.854        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;855        if (!hasMod && binding.key.length === 1 && inInput) return;856        if (ENTRY_SCOPED.has(action) && v !== "entry") return;857        e.preventDefault();858        SHORTCUT_HANDLERS[action]?.();859        return;860      }861862      // Type-to-search: in entry view, any printable key not consumed by a863      // shortcut above primes the list search seed and opens the list.864      // Kept outside the bindings table because it's a behavior, not a865      // discrete action — every printable character can trigger it.866      if (v === "entry" && !inInput && isPrintableSearchKey) {867        e.preventDefault();868        primeListSearch(e.key);869        return;870      }871    };872    window.addEventListener("keydown", handleGlobalKeydown);873    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));874875    const handleStorageChanged = (876      changes: Record<string, chrome.storage.StorageChange>,877      areaName: string878    ) => {879      if (areaName !== "session") return;880      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {881        return;882      }883      void refreshPendingPasskey();884    };885    chrome.storage.onChanged.addListener(handleStorageChanged);886    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));887  });888889  async function refreshCurrentTab() {890    try {891      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });892      const url = tab?.url ?? tab?.pendingUrl ?? "";893      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");894      // Skip extension/internal URLs — adding chrome://, about:, or895      // chrome-extension:// to a vault entry is never what the user wants.896      const isWebUrl = /^https?:\/\//i.test(url);897      setCurrentTabUrl(isWebUrl ? url : "");898    } catch {899      setCurrentTabDomain("");900      setCurrentTabUrl("");901    }902  }903904  async function refreshPendingPasskey() {905    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });906    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);907  }908909  async function refreshProStatus() {910    const res = await sendMessage({ type: "GET_LICENSE" });911    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;912    setProStatus(Boolean(data?.valid && data?.plan === "pro"));913  }914915  async function restoreSettings() {916    const res = await sendMessage({ type: "GET_SETTINGS" });917    const s = (res as { ok: boolean; data?: any }).data ?? {};918    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {919      setAccentColor(s.accentColor as AccentColorName);920    }921    setTheme(s.theme === "light" ? "light" : "dark");922    if (s.textSize === "small" || s.textSize === "large") {923      setTextSize(s.textSize);924    } else {925      setTextSize("medium");926    }927    setReduceMotion(s.reduceMotion === true);928    setLockOnClose(s.lockOnClose === true);929    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);930    setBreachMonitoring(s.breachMonitoring !== false);931    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);932    setShortcutBindings(getActiveBindings(s.shortcuts));933  }934935  async function applyTrashRetention(days: number) {936    setTrashRetentionDays(days);937    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });938  }939940  function primeListSearch(seed: string) {941    setListSearchSeed(seed);942    setListSearchSeedNonce((value) => value + 1);943    openList();944  }945946  // Returns null when it detected a dead service worker and triggered handleLock().947  // Callers that need to abort (e.g. openVault) check for null rather than relying948  // on view() state, which may already be "lock" during normal startup flows.949  async function loadEntries(): Promise<VaultEntry[] | null> {950    const response = await sendMessage({ type: "GET_ENTRIES" });951    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };952953    // If the service worker was killed and restarted (MV3 workers sleep), the954    // vault will be locked again — or the worker may not respond at all.955    // In either case, send the user to the lock screen rather than silently956    // showing an empty vault (which looks like data loss).957    if (!res.ok) {958      if (959        res.error === "vault_locked" ||960        res.error === "SERVICE_WORKER_UNAVAILABLE" ||961        (typeof res.error === "string" && res.error.includes("locked"))962      ) {963        handleLock();964        return null; // signal emergency lock to callers965      }966      return [];967    }968969    const loadedEntries = res.data ?? [];970    setEntries(loadedEntries);971972    const currentId = selectedEntry()?.id;973    if (currentId) {974      setSelectedEntry(975        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)976      );977    }978979    return loadedEntries;980  }981982  async function openVault(preferredEntryId?: string, skipViewSet = false) {983    // Purge expired trash entries on each vault open984    const retDays = trashRetentionDays();985    if (retDays > 0) {986      void sendMessage({987        type: "PURGE_EXPIRED_TRASH",988        payload: { retentionMs: retDays * 86_400_000 },989      });990    }991992    const loadedEntries = await loadEntries();993994    // null means loadEntries() triggered an emergency lock (service worker died).995    // Don't override it by setting view back to "entry" with an empty vault.996    if (loadedEntries === null) return false;997998    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry999    let nextSelectedEntry: VaultEntry | null = null;1000    if (preferredEntryId) {1001      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1002    }1003    if (!nextSelectedEntry) {1004      const tabDomain = currentTabDomain();1005      if (tabDomain) {1006        nextSelectedEntry = loadedEntries.find((e) => {1007          if (e.type === "login") {1008            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1009            for (const extra of e.additionalUrls ?? []) {1010              if ((extractDomain(extra) ?? "") === tabDomain) return true;1011            }1012            return false;1013          }1014          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1015          return false;1016        }) ?? null;1017      }1018    }1019    nextSelectedEntry ??= pickNavigable(loadedEntries);10201021    setSelectedEntry(nextSelectedEntry);1022    setEditEntry(undefined);1023    setContentPhase("enter");1024    queueContentIdle();1025    if (!skipViewSet) setView("entry");1026    return true;1027  }10281029  async function handleUnlock() {1030    // If the user previously created a vault but hadn't yet confirmed their1031    // recovery words (and the browser was closed before they could), the1032    // the background-owned recovery-pending state is still set. Re-route1033    // back to the recovery surface so they finish the confirmation step1034    // before reaching the entries view — the words can be re-derived now1035    // that the vault is unlocked again.1036    let recoveryPending = false;1037    try {1038      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });1039      recoveryPending = out.ok === true && out.data === true;1040    } catch { /* best-effort */ }1041    if (recoveryPending) {1042      setForceRecoveryWords(true);1043      setView("lock");1044      triggerPipPulse();1045      await restoreSettings();1046      return;1047    }1048    setHasVault(true);1049    triggerPipPulse();1050    await restoreSettings();1051    const celebrating = pendingCelebration();1052    if (celebrating) {1053      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1054      setPendingCelebration(false);1055    }1056    await openVault(undefined, celebrating);1057    if (celebrating) {1058      setView("pro-celebration");1059      window.setTimeout(() => setView("entry"), 2500);1060    }1061    // Popup was opened from the inline "Open Peach to unlock" button — close it1062    // now so the user lands back on the page with the autofill selector ready.1063    if (openedForInlineUnlock) {1064      openedForInlineUnlock = false;1065      window.close();1066    }1067  }10681069  function handleSelectEntry(entry: VaultEntry) {1070    if (entry.type === "note") {1071      setOpenNoteId(entry.id);1072      setShowNotes(true);1073      return;1074    }1075    setSelectedEntry(entry);1076    setContentPhase("enter");1077    queueContentIdle();1078    setView("entry");1079  }10801081  function handleAdd() {1082    setEditEntry(undefined);1083    setView("add");1084  }10851086  async function handleDelete() {1087    const entry = selectedEntry();1088    if (!entry) return;1089    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1090    const loadedEntries = await loadEntries() ?? [];1091    setSelectedEntry(pickNavigable(loadedEntries));1092    setView("entry");1093  }10941095  async function handleDeleteMany(ids: string[]) {1096    for (const id of ids) {1097      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1098    }1099    const loadedEntries = await loadEntries() ?? [];1100    // If the currently selected entry was among the deleted, move to first1101    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1102    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1103  }11041105  async function handleSave(savedEntry?: VaultEntry) {1106    await openVault(savedEntry?.id);1107  }11081109  function handleBack() {1110    const dest = editBackView();1111    setEditBackView("entry");1112    setEditEntry(undefined);1113    setView(dest);1114  }11151116  function handleExportBack() {1117    if (returnToPanic()) {1118      setReturnToPanic(false);1119      setView("panic");1120      return;1121    }1122    setView("settings");1123  }11241125  function handleLock() {1126    setEntries([]);1127    setSelectedEntry(null);1128    setEditEntry(undefined);1129    setContentPhase("idle");1130    setView("lock");1131  }11321133  function handleHeaderLock() {1134    // Lock the UI immediately — do not wait for the service worker. If the SW1135    // is dead or slow, the 5s sendMessage timeout would create a dead-click1136    // window. The SW will lock on its next wake regardless.1137    handleLock();1138    void sendMessage({ type: "LOCK" });1139  }11401141  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1142  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1143  // the trigger's own reply.1144  async function handleHeaderSync(): Promise<void> {1145    if (syncBusy()) return;1146    setSyncBusy(true);1147    setSyncFlash(null);1148    try {1149      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1150      let state: SyncOutcomeSummary = { status: "syncing" };1151      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1152        await new Promise((r) => setTimeout(r, 250));1153        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1154          ok: boolean;1155          data?: SyncOutcomeSummary;1156        };1157        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1158      }1159      setSyncSummary(state);1160      setSyncFlash(state.status === "error" ? "error" : "ok");1161      await loadSyncAlerts();1162      await loadEntries();1163      await loadSyncIndicator();1164    } catch {1165      setSyncSummary({ status: "error", outcome: "run_failed" });1166      setSyncFlash("error");1167    } finally {1168      setSyncBusy(false);1169      setTimeout(() => setSyncFlash(null), 2_000);1170    }1171  }11721173  function navigate(dir: number) {1174    const navigable = nonNoteEntries();1175    if (navigable.length === 0) return;1176    const currentIndex = selectedIndex();1177    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1178    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1179    setSelectedEntry(navigable[nextIndex]);1180    setContentPhase("enter");1181    queueContentIdle();1182  }11831184  /**1185   * The Entry view's selection invariant: never select a note. Notes are a1186   * separate surface (handleSelectEntry opens the notes view), so any code path1187   * that picks a default — vault open, post-delete, refresh — must skip them1188   * and return null if the only entries are notes.1189   */1190  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1191    return list.find((e) => e.type !== "note") ?? null;1192  }11931194  function openList() {1195    setView("list");1196  }11971198  function openHealth() {1199    setEditEntry(undefined);1200    setView("health");1201  }12021203  function handleOpenFileImport() {1204    setRestoreView("file");1205  }12061207  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12081209  function handleFixEntry(entry: VaultEntry) {1210    setSelectedEntry(entry);1211    // Passkey-only entries have no editable surface — drop into view mode1212    // instead of opening the Add editor.1213    if (isPasskeyOnly(entry)) {1214      setView("entry");1215      return;1216    }1217    setEditBackView(view()); // preserve caller view so back returns here1218    setEditEntry(entry);1219    setView("add");1220  }12211222  const isLockedView = () => view() === "lock" || view() === "adopting";12231224  async function handleAdoptionDone() {1225    await storageSet("peach_onboarded", "true").catch(() => {});1226    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1227    clearOnboardingExit();1228    setOnboarded(true);1229    setHasVault(true);1230    setView("initial-sync");1231    // The background applies a Pro license and persists the source-device1232    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1233    // celebration pending until that exact peer records a completed sync.1234    await refreshProStatus();1235    const deviceId = await resolveInitialSyncDeviceId();1236    if (deviceId) {1237      void beginInitialSyncWait(deviceId);1238    } else {1239      // Pairing completion without a durable peer row should be impossible.1240      // Stay on the honest waiting surface and expose retry instead of falling1241      // through to an empty vault.1242      setInitialSyncSlow(true);1243    }1244  }12451246  async function handleApprovePendingPasskey() {1247    const pending = pendingPasskey();1248    if (!pending) return;1249    if (pending.browser === "firefox" && pending.type === "create") {1250      // Firefox path: popup itself runs navigator.credentials.create. The1251      // background never approved/rejected anything — it just stashed1252      // intent. After the popup-driven flow resolves (success or cancel),1253      // clear the pending key so the popup doesn't re-show this on next open.1254      const { createFirefoxPasskey } = await import("./firefox-passkey");1255      const result = await createFirefoxPasskey(pending);1256      if (!result.ok) {1257        console.warn("Peach Firefox passkey create failed:", result.error);1258      }1259      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1260      setPendingPasskey(null);1261      void loadEntries();1262      window.close();1263      return;1264    }1265    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1266    window.close();1267  }12681269  async function handleDenyPendingPasskey() {1270    const pending = pendingPasskey();1271    if (!pending) return;1272    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1273    window.close();1274  }12751276  function queueContentIdle(after?: () => void) {1277    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1278    contentPhaseTimer = window.setTimeout(() => {1279      setContentPhase("idle");1280      after?.();1281    }, ENTRY_TRANSITION_SETTLE_MS);1282  }12831284  return (1285    <div class="popup-root peach-theme">1286      <Show when={bootState() === "ready"}>1287        <Show1288          when={!pendingPasskey()}1289          fallback={1290            <PasskeyApprovalView1291              type={pendingPasskey()!.type}1292              rpName={pendingPasskey()!.rpName}1293              rpId={pendingPasskey()!.rpId}1294              userName={pendingPasskey()!.userName}1295              userDisplayName={pendingPasskey()!.userDisplayName}1296              onApprove={handleApprovePendingPasskey}1297              onDeny={handleDenyPendingPasskey}1298            />1299          }1300        >1301          <Show1302            when={!isLockedView()}1303            fallback={1304              <Show1305                when={view() !== "adopting"}1306                fallback={1307                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1308                    <AdoptVaultView1309                      onCancel={() => {1310                        clearOnboardingExit();1311                        setOnboarded(false);1312                        setView("lock");1313                      }}1314                      onDone={handleAdoptionDone}1315                    />1316                  </Suspense>1317                }1318              >1319                <Show1320                  when={onboarded() || hasVault()}1321                  fallback={1322                    <Onboarding1323                      initialCard={onboardingCardAtExit()}1324                      onComplete={() => {1325                        markOnboardingExit("create");1326                        setStartOnboardingRestore(false);1327                        setOnboarded(true);1328                      }}1329                      onRestore={() => {1330                        markOnboardingExit("restore");1331                        setStartOnboardingRestore(true);1332                        setOnboarded(true);1333                      }}1334                      onAdopt={() => {1335                        markOnboardingExit("adopt");1336                        setStartOnboardingRestore(false);1337                        setOnboarded(true);1338                        setView("adopting");1339                      }}1340                    />1341                  }1342                >1343                  <LockView1344                    hasVault={hasVault()}1345                    ready={bootState() === "ready"}1346                    isPro={proStatus()}1347                    forceRecoveryWords={forceRecoveryWords()}1348                    initialRestore={startOnboardingRestore()}1349                    initialRestoreSource={resumeRestoreSource() ?? undefined}1350                    onUnlock={() => {1351                      // RecoveryWordDisplay clears the storage flag before1352                      // calling onDone, so handleUnlock will see no pending1353                      // confirmation and proceed through the normal path.1354                      if (forceRecoveryWords()) setForceRecoveryWords(false);1355                      // The create/restore flow is done — a lock later in this1356                      // window must show the unlock screen, not re-enter the1357                      // onboarding restore surface.1358                      setStartOnboardingRestore(false);1359                      setResumeRestoreSource(null);1360                      void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1361                      return handleUnlock();1362                    }}1363                    onBackToOnboarding={1364                      !hasVault()1365                        ? () => {1366                            // Deliberately rewinding to the carousel — the exit1367                            // flow must not reclaim the next popup open.1368                            clearOnboardingExit();1369                            setStartOnboardingRestore(false);1370                            setOnboarded(false);1371                          }1372                        : undefined1373                    }1374                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1375                  />1376                </Show>1377              </Show>1378            }1379          >1380            <Show1381              when={1382                view() !== "pro-celebration" &&1383                view() !== "initial-sync"1384              }1385              fallback={1386                <Show1387                  when={view() === "initial-sync"}1388                  fallback={<ProCelebration />}1389                >1390                  <InitialSyncView1391                    slow={initialSyncSlow()}1392                    onRetry={() => void retryInitialSync()}1393                  />1394                </Show>1395              }1396            >1397            <section1398              id="hd-shell"1399              class="peach-shell peach-theme"1400              data-surface="extension"1401            >1402            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1403              <PeachWordmark unlocked />1404              <div class="peach-chrome-actions">1405                <button1406                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1407                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1408                  aria-label="Notes"1409                  title="Notes"1410                >1411                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1412                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1413                    <line x1="4" y1="5" x2="10" y2="5" />1414                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1415                    <line x1="4" y1="10" x2="7" y2="10" />1416                  </svg>1417                </button>1418                <button1419                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1420                    classList={{1421                      "is-syncing": syncBusy(),1422                      "is-ok": syncFlash() === "ok",1423                      "is-error": syncFlash() === "error",1424                    }}1425                    onClick={() => void handleHeaderSync()}1426                    disabled={syncBusy()}1427                    aria-label={`Sync now. ${syncLabel()}`}1428                    title={syncLabel()}1429                  >1430                    <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">1431                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1432                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1433                      <path d="M2.6 1v2.4h2.4" />1434                      <path d="M11.4 13v-2.4H9" />1435                    </svg>1436                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1437                  </button>1438                <button1439                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1440                  onClick={() => setView("settings")}1441                  aria-label="Settings"1442                >1443                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1444                    <path1445                      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"1446                      stroke="currentColor"1447                      stroke-width="0.9"1448                    />1449                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1450                  </svg>1451                </button>1452                <button1453                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1454                  onClick={handleAdd}1455                  aria-label="New entry"1456                >1457                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1458                    <path d="M5.5 1v9M1 5.5h9" />1459                  </svg>1460                </button>1461                <button1462                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1463                  onClick={() => void handleHeaderLock()}1464                  aria-label="Lock vault"1465                >1466                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1467                    <path1468                      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"1469                      stroke="currentColor"1470                      stroke-width="1"1471                      stroke-linecap="round"1472                    />1473                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1474                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1475                  </svg>1476                </button>1477              </div>1478            </header>14791480            <Show when={pendingProNotice() !== null}>1481              <div class="peach-pro-notice-banner">1482                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1483                <button1484                  class="peach-pro-notice-link"1485                  onClick={() => {1486                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1487                    setSettingsInitialSection("license");1488                    setView("settings");1489                    setPendingProNotice(null);1490                  }}1491                >1492                  Learn more →1493                </button>1494                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1495              </div>1496            </Show>14971498            <div class="peach-shell-body">1499              <div class="peach-shell-veil"></div>1500              <div class="peach-content-frame" data-content-phase={contentPhase()}>1501                <EntryView1502                  entry={selectedEntry()}1503                  currentTabUrl={currentTabUrl()}1504                  entries={entries()}1505                  isPro={proStatus()}1506                  onDelete={handleDelete}1507                  onFieldSaved={() => void loadEntries()}1508                  onEscape={() => { setView("list"); }}1509                  onProGate={(feature) => {1510                    setUpgradeHighlight(feature);1511                    setSettingsInitialSection("license");1512                    setView("settings");1513                  }}1514                />1515              </div>15161517              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1518                <div class="peach-search-bar">1519                  <span class="peach-search-icon">1520                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1521                      <circle cx="5.5" cy="5.5" r="3.75" />1522                      <path d="M8.75 8.75L11.5 11.5" />1523                    </svg>1524                  </span>1525                  <input1526                    class="peach-search-input"1527                    placeholder="search vault..."1528                    autocomplete="off"1529                    aria-label="Search vault entries"1530                    onClick={openList}1531                    onFocus={openList}1532                    readOnly1533                  />1534                  <div class="peach-search-meta">1535                    <span class="peach-search-counter">1536                      {nonNoteEntries().length > 01537                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1538                        : "0 entries"}1539                    </span>1540                    <span class="peach-divider"></span>1541                    <button1542                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1543                      onClick={() => navigate(-1)}1544                      aria-label="Previous entry"1545                      disabled={nonNoteEntries().length === 0}1546                    >1547                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1548                        <path d="M5 1L1 5.5L5 10" />1549                      </svg>1550                    </button>1551                    <button1552                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1553                      onClick={() => navigate(1)}1554                      aria-label="Next entry"1555                      disabled={nonNoteEntries().length === 0}1556                    >1557                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1558                        <path d="M1 1L5 5.5L1 10" />1559                      </svg>1560                    </button>1561                  </div>1562                </div>1563              </section>1564            </div>15651566            {/* Rare device-trust alerts; normal sync changes are silent. */}1567            <Show when={alertGroups().length > 0}>1568              <div class="peach-sync-alerts">1569                <For each={alertGroups()}>1570                  {([type, group]) => {1571                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1572                    return (1573                      <div class="peach-sync-alert">1574                        <Show when={group.length > 1}>1575                          <button1576                            class="peach-sync-alert-flip"1577                            type="button"1578                            aria-label="Previous"1579                            onClick={() => flipAlert(type, -1)}1580                          >‹</button>1581                        </Show>1582                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1583                        <Show when={group.length > 1}>1584                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1585                          <button1586                            class="peach-sync-alert-flip"1587                            type="button"1588                            aria-label="Next"1589                            onClick={() => flipAlert(type, 1)}1590                          >›</button>1591                        </Show>1592                        <button1593                          class="peach-sync-alert-dismiss"1594                          type="button"1595                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1596                          onClick={() => dismissAlertGroup(type)}1597                        >×</button>1598                      </div>1599                    );1600                  }}1601                </For>1602              </div>1603            </Show>16041605            <Show when={view() === "list"}>1606              <VaultView1607                entries={entries()}1608                selectedEntryId={selectedEntry()?.id}1609                currentTabDomain={currentTabDomain()}1610                sortOrder={sortOrder()}1611                searchSeed={listSearchSeed()}1612                searchSeedNonce={listSearchSeedNonce()}1613                onSelectEntry={handleSelectEntry}1614                onSortOrderChange={setSortOrder}1615                onAdd={handleAdd}1616                onClose={() => setView("entry")}1617                onOpenTrash={() => setView("trash")}1618                onDeleteMany={handleDeleteMany}1619              />1620            </Show>1621            <Show when={view() === "settings" || settingsExiting()}>1622              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1623                <SettingsView1624                  entriesCount={entries().length}1625                  breachMonitoring={breachMonitoring()}1626                  lockOnClose={lockOnClose()}1627                  autoLockMinutes={autoLockMinutes()}1628                  trashRetentionDays={trashRetentionDays()}1629                  theme={theme()}1630                  accentColor={accentColor()}1631                  textSize={textSize()}1632                  reduceMotion={reduceMotion()}1633                  isPro={proStatus()}1634                  initialSection={settingsInitialSection()}1635                  upgradeHighlight={upgradeHighlight()}1636                  isExiting={settingsExiting()}1637                  onBreachMonitoringChange={applyBreachMonitoring}1638                  onLockOnCloseChange={applyLockOnClose}1639                  onAutoLockMinutesChange={applyAutoLockMinutes}1640                  onTrashRetentionChange={applyTrashRetention}1641                  onThemeChange={applyTheme}1642                  onAccentChange={applyAccentColor}1643                  onTextSizeChange={applyTextSize}1644                  onReduceMotionChange={applyReduceMotion}1645                  shortcuts={shortcutBindings()}1646                  onShortcutsChange={applyShortcuts}1647                  onLicenseChange={async () => {1648                    // After activation/deactivation: refresh Pro status,1649                    // re-load entries (defensive — signal state can drift if1650                    // the SW briefly restarts during the verify+save round-trip),1651                    // and replay the Pro celebration if this is the first time1652                    // a valid Pro license is seen on this device.1653                    await refreshProStatus();1654                    void loadEntries();1655                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1656                    if ((should as { ok: boolean; data?: boolean }).data === true) {1657                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1658                      setView("pro-celebration");1659                      window.setTimeout(() => setView("settings"), 2500);1660                    }1661                  }}1662                  onBack={() => {1663                    setSettingsExiting(true);1664                    window.setTimeout(() => {1665                      setSettingsExiting(false);1666                      setSettingsInitialSection(null);1667                      setUpgradeHighlight(null);1668                      handleBack();1669                    }, 200);1670                  }}1671                  onImport={() => setView("import")}1672                  onExport={() => setView("export")}1673                  onBreachCheckDone={loadEntries}1674                  onOpenHealth={openHealth}1675                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1676                  onOpenFileImport={handleOpenFileImport}1677                  onOpenPanic={() => setView("panic")}1678                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1679                  onOpenCodexRestore={() => setView("codex-restore")}1680                  onCardChange={setSettingsActiveCard}1681                  onProGate={(feature) => {1682                    setUpgradeHighlight(feature);1683                    setSettingsInitialSection("license");1684                  }}1685                />1686              </Suspense>1687            </Show>1688            <Show when={view() === "codex-generate"}>1689              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1690                <CodexGenerateView1691                  isPro={proStatus()}1692                  onBack={() => setView("settings")}1693                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1694                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1695                  onVaultLocked={() => handleLock()}1696                />1697              </Suspense>1698            </Show>1699            <Show when={view() === "codex-restore"}>1700              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1701                <CodexRestoreView1702                  onBack={() => setView("lock")}1703                  onRestoreSuccess={async () => {1704                    // After restore the vault is unlocked; refresh entries1705                    // and route to the main vault list. handleUnlock is the1706                    // canonical post-unlock setup path.1707                    await handleUnlock();1708                  }}1709                />1710              </Suspense>1711            </Show>1712            <Show when={view() === "pair-device"}>1713              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1714                <PairDeviceView1715                  isPro={proStatus()}1716                  onProChanged={() => { void refreshProStatus(); }}1717                  onBack={() => setView("settings")}1718                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1719                />1720              </Suspense>1721            </Show>1722            <Show when={view() === "add"}>1723              <AddView1724                entry={editEntry()}1725                entries={entries()}1726                onBack={handleBack}1727                onSave={handleSave}1728              />1729            </Show>1730            <Show when={view() === "import"}>1731              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1732                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1733              </Suspense>1734            </Show>1735            <Show when={view() === "export"}>1736              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1737                <ExportView onBack={handleExportBack} />1738              </Suspense>1739            </Show>1740            <Show when={view() === "panic"}>1741              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1742                <PanicView1743                  onCancel={() => setView("settings")}1744                  onOpenExport={() => {1745                    setReturnToPanic(true);1746                    setView("export");1747                  }}1748                  onDestroyed={async () => {1749                    // Fresh onboarding start after a destroy — don't let the1750                    // resume markers land the user mid-carousel.1751                    setOnboardingCardAtExit(0);1752                    void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1753                    clearOnboardingExit();1754                    setEntries([]);1755                    setSelectedEntry(null);1756                    setEditEntry(undefined);1757                    setHasVault(false);1758                    setOnboarded(false);1759                    setProStatus(false);1760                    setPendingPasskey(null);1761                    setUpgradeHighlight(null);1762                    setSettingsInitialSection(null);1763                    setPendingProNotice(null);1764                    setPendingCelebration(false);1765                    setReturnToPanic(false);1766                    setContentPhase("idle");1767                    setView("lock");1768                  }}1769                />1770              </Suspense>1771            </Show>1772            {/* Health stays mounted while editing an entry from it so1773                computeReused() doesn't rerun on every cancel/back. */}1774            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1775              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1776                <HealthView1777                  entries={entries()}1778                  isPro={proStatus()}1779                  onFixEntry={handleFixEntry}1780                  onBack={() => setView("settings")}1781                  onRefresh={loadEntries}1782                  hidden={view() !== "health"}1783                />1784              </Suspense>1785            </Show>1786            <Show when={view() === "trash"}>1787              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1788                <TrashView1789                  onBack={() => setView("list")}1790                  onRestored={() => void loadEntries()}1791                />1792              </Suspense>1793            </Show>1794            <Show when={showNotes()}>1795              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1796                <NotesMode1797                  notes={entries().filter((e) => e.type === "note")}1798                  initialNoteId={openNoteId()}1799                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1800                  onNoteListChanged={() => void loadEntries()}1801                />1802              </div>1803            </Show>1804            <Show when={restoreView() === "file"}>1805              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1806                <ImportView1807                  mode="onboarding"1808                  replacesExistingVault={true}1809                  onBack={() => setRestoreView(null)}1810                  onImport={async () => {1811                    setRestoreView(null);1812                    await handleUnlock();1813                  }}1814                />1815              </Suspense>1816            </Show>1817            </section>1818            </Show>1819          </Show>1820        </Show>1821      </Show>1822      <Show when={showShortcutsHelp()}>1823        <ShortcutsHelpOverlay1824          bindings={shortcutBindings()}1825          onClose={() => setShowShortcutsHelp(false)}1826        />1827      </Show>1828    </div>1829  );1830}18311832function ShortcutsHelpOverlay(props: {1833  bindings: Record<ShortcutAction, Keybinding>;1834  onClose: () => void;1835}) {1836  return (1837    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1838      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1839        <div class="peach-shortcuts-help-head">1840          <h3>Keyboard shortcuts</h3>1841          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1842        </div>1843        <div class="peach-shortcuts-help-body">1844          <p class="peach-settings-sub-label">ENTRY VIEW</p>1845          <ul>1846            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1847              <li>1848                <span>{d.label}</span>1849                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1850              </li>1851            ))}1852          </ul>1853          <p class="peach-settings-sub-label">ANYWHERE</p>1854          <ul>1855            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1856              <li>1857                <span>{d.label}</span>1858                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1859              </li>1860            ))}1861          </ul>1862        </div>1863      </div>1864    </div>1865  );1866}