App.tsx

77.8 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(entry.totp);773          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });774        } catch { /* invalid TOTP secret — silent */ }775      },776      new_entry: () => handleAdd(),777      edit_entry: () => {778        const entry = selectedEntry();779        // Passkey-only entries have nothing user-editable in the Add view; the780        // passkey credential itself is opaque. Skip the edit action for them.781        if (!entry || isPasskeyOnly(entry)) return;782        setEditEntry(entry);783        setView("add");784      },785      delete_entry: () => {786        if (selectedEntry()) void handleDelete();787      },788      lock_vault: () => { void handleHeaderLock(); },789      search: () => openList(),790      nav_prev: () => navigate(-1),791      nav_next: () => navigate(1),792      jump_vault: () => setView("entry"),793      jump_settings: () => setView("settings"),794      show_help: () => setShowShortcutsHelp(true),795    };796797    // Actions that are MEANINGFUL only on the entry-detail view. Outside798    // that scope the binding is dormant — pressing C while on Settings799    // does nothing rather than awkwardly copying from a now-stale entry.800    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([801      "copy_password", "copy_username", "copy_totp",802      "edit_entry", "delete_entry", "nav_prev", "nav_next",803    ]);804805    const handleGlobalKeydown = (e: KeyboardEvent) => {806      const v = view();807      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"808        || (e.target as HTMLElement)?.tagName === "TEXTAREA"809        || (e.target as HTMLElement)?.isContentEditable;810      const isPrintableSearchKey =811        e.key.length === 1 &&812        !e.ctrlKey &&813        !e.metaKey &&814        !e.altKey;815816      // No shortcuts while a full-screen surface owns the whole viewport:817      // the lock screen, the post-pairing readiness sequence, or the Pro818      // celebration. Without this the lock screen is at the mercy of whatever819      // single-key binding is active — e.g. typing "n" in a password that820      // slips out of focus triggers `new_entry` and escapes the lock screen.821      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;822823      // Help dialog: Escape closes it; eat the keypress so it doesn't824      // also navigate away from the underlying view.825      if (showShortcutsHelp()) {826        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }827        return;828      }829830      // ── Escape — fixed binding (not user-customizable) ───────831      if (e.key === "Escape") {832        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }833        if (v === "list") { setView("entry"); return; }834        if (v === "settings" || v === "add") { handleBack(); return; }835        if (v === "import" || v === "health") { setView("settings"); return; }836        if (v === "export") { handleExportBack(); return; }837        if (v === "pair-device") { setView("settings"); return; }838      }839840      // Bindings-driven dispatch. Single-key letter bindings without841      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is842      // inside an input, so users can type into search/forms normally.843      const bindings = shortcutBindings();844      for (const action of Object.keys(bindings) as ShortcutAction[]) {845        const binding = bindings[action];846        if (!matchKeybinding(e, binding)) continue;847        // Single-key letter bindings need the input-focus guard. Bindings848        // with any modifier are safe — Ctrl+L doesn't conflict with typing.849        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;850        if (!hasMod && binding.key.length === 1 && inInput) return;851        if (ENTRY_SCOPED.has(action) && v !== "entry") return;852        e.preventDefault();853        SHORTCUT_HANDLERS[action]?.();854        return;855      }856857      // Type-to-search: in entry view, any printable key not consumed by a858      // shortcut above primes the list search seed and opens the list.859      // Kept outside the bindings table because it's a behavior, not a860      // discrete action — every printable character can trigger it.861      if (v === "entry" && !inInput && isPrintableSearchKey) {862        e.preventDefault();863        primeListSearch(e.key);864        return;865      }866    };867    window.addEventListener("keydown", handleGlobalKeydown);868    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));869870    const handleStorageChanged = (871      changes: Record<string, chrome.storage.StorageChange>,872      areaName: string873    ) => {874      if (areaName !== "session") return;875      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {876        return;877      }878      void refreshPendingPasskey();879    };880    chrome.storage.onChanged.addListener(handleStorageChanged);881    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));882  });883884  async function refreshCurrentTab() {885    try {886      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });887      const url = tab?.url ?? tab?.pendingUrl ?? "";888      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");889      // Skip extension/internal URLs — adding chrome://, about:, or890      // chrome-extension:// to a vault entry is never what the user wants.891      const isWebUrl = /^https?:\/\//i.test(url);892      setCurrentTabUrl(isWebUrl ? url : "");893    } catch {894      setCurrentTabDomain("");895      setCurrentTabUrl("");896    }897  }898899  async function refreshPendingPasskey() {900    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });901    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);902  }903904  async function refreshProStatus() {905    const res = await sendMessage({ type: "GET_LICENSE" });906    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;907    setProStatus(Boolean(data?.valid && data?.plan === "pro"));908  }909910  async function restoreSettings() {911    const res = await sendMessage({ type: "GET_SETTINGS" });912    const s = (res as { ok: boolean; data?: any }).data ?? {};913    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {914      setAccentColor(s.accentColor as AccentColorName);915    }916    setTheme(s.theme === "light" ? "light" : "dark");917    if (s.textSize === "small" || s.textSize === "large") {918      setTextSize(s.textSize);919    } else {920      setTextSize("medium");921    }922    setReduceMotion(s.reduceMotion === true);923    setLockOnClose(s.lockOnClose === true);924    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);925    setBreachMonitoring(s.breachMonitoring !== false);926    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);927    setShortcutBindings(getActiveBindings(s.shortcuts));928  }929930  async function applyTrashRetention(days: number) {931    setTrashRetentionDays(days);932    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });933  }934935  function primeListSearch(seed: string) {936    setListSearchSeed(seed);937    setListSearchSeedNonce((value) => value + 1);938    openList();939  }940941  // Returns null when it detected a dead service worker and triggered handleLock().942  // Callers that need to abort (e.g. openVault) check for null rather than relying943  // on view() state, which may already be "lock" during normal startup flows.944  async function loadEntries(): Promise<VaultEntry[] | null> {945    const response = await sendMessage({ type: "GET_ENTRIES" });946    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };947948    // If the service worker was killed and restarted (MV3 workers sleep), the949    // vault will be locked again — or the worker may not respond at all.950    // In either case, send the user to the lock screen rather than silently951    // showing an empty vault (which looks like data loss).952    if (!res.ok) {953      if (954        res.error === "vault_locked" ||955        res.error === "SERVICE_WORKER_UNAVAILABLE" ||956        (typeof res.error === "string" && res.error.includes("locked"))957      ) {958        handleLock();959        return null; // signal emergency lock to callers960      }961      return [];962    }963964    const loadedEntries = res.data ?? [];965    setEntries(loadedEntries);966967    const currentId = selectedEntry()?.id;968    if (currentId) {969      setSelectedEntry(970        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)971      );972    }973974    return loadedEntries;975  }976977  async function openVault(preferredEntryId?: string, skipViewSet = false) {978    // Purge expired trash entries on each vault open979    const retDays = trashRetentionDays();980    if (retDays > 0) {981      void sendMessage({982        type: "PURGE_EXPIRED_TRASH",983        payload: { retentionMs: retDays * 86_400_000 },984      });985    }986987    const loadedEntries = await loadEntries();988989    // null means loadEntries() triggered an emergency lock (service worker died).990    // Don't override it by setting view back to "entry" with an empty vault.991    if (loadedEntries === null) return false;992993    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry994    let nextSelectedEntry: VaultEntry | null = null;995    if (preferredEntryId) {996      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;997    }998    if (!nextSelectedEntry) {999      const tabDomain = currentTabDomain();1000      if (tabDomain) {1001        nextSelectedEntry = loadedEntries.find((e) => {1002          if (e.type === "login") {1003            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1004            for (const extra of e.additionalUrls ?? []) {1005              if ((extractDomain(extra) ?? "") === tabDomain) return true;1006            }1007            return false;1008          }1009          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1010          return false;1011        }) ?? null;1012      }1013    }1014    nextSelectedEntry ??= pickNavigable(loadedEntries);10151016    setSelectedEntry(nextSelectedEntry);1017    setEditEntry(undefined);1018    setContentPhase("enter");1019    queueContentIdle();1020    if (!skipViewSet) setView("entry");1021    return true;1022  }10231024  async function handleUnlock() {1025    // If the user previously created a vault but hadn't yet confirmed their1026    // recovery words (and the browser was closed before they could), the1027    // the background-owned recovery-pending state is still set. Re-route1028    // back to the recovery surface so they finish the confirmation step1029    // before reaching the entries view — the words can be re-derived now1030    // that the vault is unlocked again.1031    let recoveryPending = false;1032    try {1033      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });1034      recoveryPending = out.ok === true && out.data === true;1035    } catch { /* best-effort */ }1036    if (recoveryPending) {1037      setForceRecoveryWords(true);1038      setView("lock");1039      triggerPipPulse();1040      await restoreSettings();1041      return;1042    }1043    setHasVault(true);1044    triggerPipPulse();1045    await restoreSettings();1046    const celebrating = pendingCelebration();1047    if (celebrating) {1048      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1049      setPendingCelebration(false);1050    }1051    await openVault(undefined, celebrating);1052    if (celebrating) {1053      setView("pro-celebration");1054      window.setTimeout(() => setView("entry"), 2500);1055    }1056    // Popup was opened from the inline "Open Peach to unlock" button — close it1057    // now so the user lands back on the page with the autofill selector ready.1058    if (openedForInlineUnlock) {1059      openedForInlineUnlock = false;1060      window.close();1061    }1062  }10631064  function handleSelectEntry(entry: VaultEntry) {1065    if (entry.type === "note") {1066      setOpenNoteId(entry.id);1067      setShowNotes(true);1068      return;1069    }1070    setSelectedEntry(entry);1071    setContentPhase("enter");1072    queueContentIdle();1073    setView("entry");1074  }10751076  function handleAdd() {1077    setEditEntry(undefined);1078    setView("add");1079  }10801081  async function handleDelete() {1082    const entry = selectedEntry();1083    if (!entry) return;1084    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1085    const loadedEntries = await loadEntries() ?? [];1086    setSelectedEntry(pickNavigable(loadedEntries));1087    setView("entry");1088  }10891090  async function handleDeleteMany(ids: string[]) {1091    for (const id of ids) {1092      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1093    }1094    const loadedEntries = await loadEntries() ?? [];1095    // If the currently selected entry was among the deleted, move to first1096    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1097    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1098  }10991100  async function handleSave(savedEntry?: VaultEntry) {1101    await openVault(savedEntry?.id);1102  }11031104  function handleBack() {1105    const dest = editBackView();1106    setEditBackView("entry");1107    setEditEntry(undefined);1108    setView(dest);1109  }11101111  function handleExportBack() {1112    if (returnToPanic()) {1113      setReturnToPanic(false);1114      setView("panic");1115      return;1116    }1117    setView("settings");1118  }11191120  function handleLock() {1121    setEntries([]);1122    setSelectedEntry(null);1123    setEditEntry(undefined);1124    setContentPhase("idle");1125    setView("lock");1126  }11271128  function handleHeaderLock() {1129    // Lock the UI immediately — do not wait for the service worker. If the SW1130    // is dead or slow, the 5s sendMessage timeout would create a dead-click1131    // window. The SW will lock on its next wake regardless.1132    handleLock();1133    void sendMessage({ type: "LOCK" });1134  }11351136  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1137  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1138  // the trigger's own reply.1139  async function handleHeaderSync(): Promise<void> {1140    if (syncBusy()) return;1141    setSyncBusy(true);1142    setSyncFlash(null);1143    try {1144      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1145      let state: SyncOutcomeSummary = { status: "syncing" };1146      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1147        await new Promise((r) => setTimeout(r, 250));1148        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1149          ok: boolean;1150          data?: SyncOutcomeSummary;1151        };1152        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1153      }1154      setSyncSummary(state);1155      setSyncFlash(state.status === "error" ? "error" : "ok");1156      await loadSyncAlerts();1157      await loadEntries();1158      await loadSyncIndicator();1159    } catch {1160      setSyncSummary({ status: "error", outcome: "run_failed" });1161      setSyncFlash("error");1162    } finally {1163      setSyncBusy(false);1164      setTimeout(() => setSyncFlash(null), 2_000);1165    }1166  }11671168  function navigate(dir: number) {1169    const navigable = nonNoteEntries();1170    if (navigable.length === 0) return;1171    const currentIndex = selectedIndex();1172    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1173    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1174    setSelectedEntry(navigable[nextIndex]);1175    setContentPhase("enter");1176    queueContentIdle();1177  }11781179  /**1180   * The Entry view's selection invariant: never select a note. Notes are a1181   * separate surface (handleSelectEntry opens the notes view), so any code path1182   * that picks a default — vault open, post-delete, refresh — must skip them1183   * and return null if the only entries are notes.1184   */1185  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1186    return list.find((e) => e.type !== "note") ?? null;1187  }11881189  function openList() {1190    setView("list");1191  }11921193  function openHealth() {1194    setEditEntry(undefined);1195    setView("health");1196  }11971198  function handleOpenFileImport() {1199    setRestoreView("file");1200  }12011202  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12031204  function handleFixEntry(entry: VaultEntry) {1205    setSelectedEntry(entry);1206    // Passkey-only entries have no editable surface — drop into view mode1207    // instead of opening the Add editor.1208    if (isPasskeyOnly(entry)) {1209      setView("entry");1210      return;1211    }1212    setEditBackView(view()); // preserve caller view so back returns here1213    setEditEntry(entry);1214    setView("add");1215  }12161217  const isLockedView = () => view() === "lock" || view() === "adopting";12181219  async function handleAdoptionDone() {1220    await storageSet("peach_onboarded", "true").catch(() => {});1221    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1222    clearOnboardingExit();1223    setOnboarded(true);1224    setHasVault(true);1225    setView("initial-sync");1226    // The background applies a Pro license and persists the source-device1227    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1228    // celebration pending until that exact peer records a completed sync.1229    await refreshProStatus();1230    const deviceId = await resolveInitialSyncDeviceId();1231    if (deviceId) {1232      void beginInitialSyncWait(deviceId);1233    } else {1234      // Pairing completion without a durable peer row should be impossible.1235      // Stay on the honest waiting surface and expose retry instead of falling1236      // through to an empty vault.1237      setInitialSyncSlow(true);1238    }1239  }12401241  async function handleApprovePendingPasskey() {1242    const pending = pendingPasskey();1243    if (!pending) return;1244    if (pending.browser === "firefox" && pending.type === "create") {1245      // Firefox path: popup itself runs navigator.credentials.create. The1246      // background never approved/rejected anything — it just stashed1247      // intent. After the popup-driven flow resolves (success or cancel),1248      // clear the pending key so the popup doesn't re-show this on next open.1249      const { createFirefoxPasskey } = await import("./firefox-passkey");1250      const result = await createFirefoxPasskey(pending);1251      if (!result.ok) {1252        console.warn("Peach Firefox passkey create failed:", result.error);1253      }1254      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1255      setPendingPasskey(null);1256      void loadEntries();1257      window.close();1258      return;1259    }1260    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1261    window.close();1262  }12631264  async function handleDenyPendingPasskey() {1265    const pending = pendingPasskey();1266    if (!pending) return;1267    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1268    window.close();1269  }12701271  function queueContentIdle(after?: () => void) {1272    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1273    contentPhaseTimer = window.setTimeout(() => {1274      setContentPhase("idle");1275      after?.();1276    }, ENTRY_TRANSITION_SETTLE_MS);1277  }12781279  return (1280    <div class="popup-root peach-theme">1281      <Show when={bootState() === "ready"}>1282        <Show1283          when={!pendingPasskey()}1284          fallback={1285            <PasskeyApprovalView1286              type={pendingPasskey()!.type}1287              rpName={pendingPasskey()!.rpName}1288              rpId={pendingPasskey()!.rpId}1289              userName={pendingPasskey()!.userName}1290              userDisplayName={pendingPasskey()!.userDisplayName}1291              onApprove={handleApprovePendingPasskey}1292              onDeny={handleDenyPendingPasskey}1293            />1294          }1295        >1296          <Show1297            when={!isLockedView()}1298            fallback={1299              <Show1300                when={view() !== "adopting"}1301                fallback={1302                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1303                    <AdoptVaultView1304                      onCancel={() => {1305                        clearOnboardingExit();1306                        setOnboarded(false);1307                        setView("lock");1308                      }}1309                      onDone={handleAdoptionDone}1310                    />1311                  </Suspense>1312                }1313              >1314                <Show1315                  when={onboarded() || hasVault()}1316                  fallback={1317                    <Onboarding1318                      initialCard={onboardingCardAtExit()}1319                      onComplete={() => {1320                        markOnboardingExit("create");1321                        setStartOnboardingRestore(false);1322                        setOnboarded(true);1323                      }}1324                      onRestore={() => {1325                        markOnboardingExit("restore");1326                        setStartOnboardingRestore(true);1327                        setOnboarded(true);1328                      }}1329                      onAdopt={() => {1330                        markOnboardingExit("adopt");1331                        setStartOnboardingRestore(false);1332                        setOnboarded(true);1333                        setView("adopting");1334                      }}1335                    />1336                  }1337                >1338                  <LockView1339                    hasVault={hasVault()}1340                    ready={bootState() === "ready"}1341                    isPro={proStatus()}1342                    forceRecoveryWords={forceRecoveryWords()}1343                    initialRestore={startOnboardingRestore()}1344                    initialRestoreSource={resumeRestoreSource() ?? undefined}1345                    onUnlock={() => {1346                      // RecoveryWordDisplay clears the storage flag before1347                      // calling onDone, so handleUnlock will see no pending1348                      // confirmation and proceed through the normal path.1349                      if (forceRecoveryWords()) setForceRecoveryWords(false);1350                      // The create/restore flow is done — a lock later in this1351                      // window must show the unlock screen, not re-enter the1352                      // onboarding restore surface.1353                      setStartOnboardingRestore(false);1354                      setResumeRestoreSource(null);1355                      void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1356                      return handleUnlock();1357                    }}1358                    onBackToOnboarding={1359                      !hasVault()1360                        ? () => {1361                            // Deliberately rewinding to the carousel — the exit1362                            // flow must not reclaim the next popup open.1363                            clearOnboardingExit();1364                            setStartOnboardingRestore(false);1365                            setOnboarded(false);1366                          }1367                        : undefined1368                    }1369                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1370                  />1371                </Show>1372              </Show>1373            }1374          >1375            <Show1376              when={1377                view() !== "pro-celebration" &&1378                view() !== "initial-sync"1379              }1380              fallback={1381                <Show1382                  when={view() === "initial-sync"}1383                  fallback={<ProCelebration />}1384                >1385                  <InitialSyncView1386                    slow={initialSyncSlow()}1387                    onRetry={() => void retryInitialSync()}1388                  />1389                </Show>1390              }1391            >1392            <section1393              id="hd-shell"1394              class="peach-shell peach-theme"1395              data-surface="extension"1396            >1397            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1398              <PeachWordmark unlocked />1399              <div class="peach-chrome-actions">1400                <button1401                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1402                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1403                  aria-label="Notes"1404                  title="Notes"1405                >1406                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1407                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1408                    <line x1="4" y1="5" x2="10" y2="5" />1409                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1410                    <line x1="4" y1="10" x2="7" y2="10" />1411                  </svg>1412                </button>1413                <button1414                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1415                    classList={{1416                      "is-syncing": syncBusy(),1417                      "is-ok": syncFlash() === "ok",1418                      "is-error": syncFlash() === "error",1419                    }}1420                    onClick={() => void handleHeaderSync()}1421                    disabled={syncBusy()}1422                    aria-label={`Sync now. ${syncLabel()}`}1423                    title={syncLabel()}1424                  >1425                    <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">1426                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1427                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1428                      <path d="M2.6 1v2.4h2.4" />1429                      <path d="M11.4 13v-2.4H9" />1430                    </svg>1431                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1432                  </button>1433                <button1434                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1435                  onClick={() => setView("settings")}1436                  aria-label="Settings"1437                >1438                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1439                    <path1440                      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"1441                      stroke="currentColor"1442                      stroke-width="0.9"1443                    />1444                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1445                  </svg>1446                </button>1447                <button1448                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1449                  onClick={handleAdd}1450                  aria-label="New entry"1451                >1452                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1453                    <path d="M5.5 1v9M1 5.5h9" />1454                  </svg>1455                </button>1456                <button1457                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1458                  onClick={() => void handleHeaderLock()}1459                  aria-label="Lock vault"1460                >1461                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1462                    <path1463                      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"1464                      stroke="currentColor"1465                      stroke-width="1"1466                      stroke-linecap="round"1467                    />1468                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1469                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1470                  </svg>1471                </button>1472              </div>1473            </header>14741475            <Show when={pendingProNotice() !== null}>1476              <div class="peach-pro-notice-banner">1477                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1478                <button1479                  class="peach-pro-notice-link"1480                  onClick={() => {1481                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1482                    setSettingsInitialSection("license");1483                    setView("settings");1484                    setPendingProNotice(null);1485                  }}1486                >1487                  Learn more →1488                </button>1489                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1490              </div>1491            </Show>14921493            <div class="peach-shell-body">1494              <div class="peach-shell-veil"></div>1495              <div class="peach-content-frame" data-content-phase={contentPhase()}>1496                <EntryView1497                  entry={selectedEntry()}1498                  currentTabUrl={currentTabUrl()}1499                  entries={entries()}1500                  isPro={proStatus()}1501                  onDelete={handleDelete}1502                  onFieldSaved={() => void loadEntries()}1503                  onEscape={() => { setView("list"); }}1504                  onProGate={(feature) => {1505                    setUpgradeHighlight(feature);1506                    setSettingsInitialSection("license");1507                    setView("settings");1508                  }}1509                />1510              </div>15111512              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1513                <div class="peach-search-bar">1514                  <span class="peach-search-icon">1515                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1516                      <circle cx="5.5" cy="5.5" r="3.75" />1517                      <path d="M8.75 8.75L11.5 11.5" />1518                    </svg>1519                  </span>1520                  <input1521                    class="peach-search-input"1522                    placeholder="search vault..."1523                    autocomplete="off"1524                    aria-label="Search vault entries"1525                    onClick={openList}1526                    onFocus={openList}1527                    readOnly1528                  />1529                  <div class="peach-search-meta">1530                    <span class="peach-search-counter">1531                      {nonNoteEntries().length > 01532                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1533                        : "0 entries"}1534                    </span>1535                    <span class="peach-divider"></span>1536                    <button1537                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1538                      onClick={() => navigate(-1)}1539                      aria-label="Previous entry"1540                      disabled={nonNoteEntries().length === 0}1541                    >1542                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1543                        <path d="M5 1L1 5.5L5 10" />1544                      </svg>1545                    </button>1546                    <button1547                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1548                      onClick={() => navigate(1)}1549                      aria-label="Next entry"1550                      disabled={nonNoteEntries().length === 0}1551                    >1552                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1553                        <path d="M1 1L5 5.5L1 10" />1554                      </svg>1555                    </button>1556                  </div>1557                </div>1558              </section>1559            </div>15601561            {/* Rare device-trust alerts; normal sync changes are silent. */}1562            <Show when={alertGroups().length > 0}>1563              <div class="peach-sync-alerts">1564                <For each={alertGroups()}>1565                  {([type, group]) => {1566                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1567                    return (1568                      <div class="peach-sync-alert">1569                        <Show when={group.length > 1}>1570                          <button1571                            class="peach-sync-alert-flip"1572                            type="button"1573                            aria-label="Previous"1574                            onClick={() => flipAlert(type, -1)}1575                          >‹</button>1576                        </Show>1577                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1578                        <Show when={group.length > 1}>1579                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1580                          <button1581                            class="peach-sync-alert-flip"1582                            type="button"1583                            aria-label="Next"1584                            onClick={() => flipAlert(type, 1)}1585                          >›</button>1586                        </Show>1587                        <button1588                          class="peach-sync-alert-dismiss"1589                          type="button"1590                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1591                          onClick={() => dismissAlertGroup(type)}1592                        >×</button>1593                      </div>1594                    );1595                  }}1596                </For>1597              </div>1598            </Show>15991600            <Show when={view() === "list"}>1601              <VaultView1602                entries={entries()}1603                selectedEntryId={selectedEntry()?.id}1604                currentTabDomain={currentTabDomain()}1605                sortOrder={sortOrder()}1606                searchSeed={listSearchSeed()}1607                searchSeedNonce={listSearchSeedNonce()}1608                onSelectEntry={handleSelectEntry}1609                onSortOrderChange={setSortOrder}1610                onAdd={handleAdd}1611                onClose={() => setView("entry")}1612                onOpenTrash={() => setView("trash")}1613                onDeleteMany={handleDeleteMany}1614              />1615            </Show>1616            <Show when={view() === "settings" || settingsExiting()}>1617              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1618                <SettingsView1619                  entriesCount={entries().length}1620                  breachMonitoring={breachMonitoring()}1621                  lockOnClose={lockOnClose()}1622                  autoLockMinutes={autoLockMinutes()}1623                  trashRetentionDays={trashRetentionDays()}1624                  theme={theme()}1625                  accentColor={accentColor()}1626                  textSize={textSize()}1627                  reduceMotion={reduceMotion()}1628                  isPro={proStatus()}1629                  initialSection={settingsInitialSection()}1630                  upgradeHighlight={upgradeHighlight()}1631                  isExiting={settingsExiting()}1632                  onBreachMonitoringChange={applyBreachMonitoring}1633                  onLockOnCloseChange={applyLockOnClose}1634                  onAutoLockMinutesChange={applyAutoLockMinutes}1635                  onTrashRetentionChange={applyTrashRetention}1636                  onThemeChange={applyTheme}1637                  onAccentChange={applyAccentColor}1638                  onTextSizeChange={applyTextSize}1639                  onReduceMotionChange={applyReduceMotion}1640                  shortcuts={shortcutBindings()}1641                  onShortcutsChange={applyShortcuts}1642                  onLicenseChange={async () => {1643                    // After activation/deactivation: refresh Pro status,1644                    // re-load entries (defensive — signal state can drift if1645                    // the SW briefly restarts during the verify+save round-trip),1646                    // and replay the Pro celebration if this is the first time1647                    // a valid Pro license is seen on this device.1648                    await refreshProStatus();1649                    void loadEntries();1650                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1651                    if ((should as { ok: boolean; data?: boolean }).data === true) {1652                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1653                      setView("pro-celebration");1654                      window.setTimeout(() => setView("settings"), 2500);1655                    }1656                  }}1657                  onBack={() => {1658                    setSettingsExiting(true);1659                    window.setTimeout(() => {1660                      setSettingsExiting(false);1661                      setSettingsInitialSection(null);1662                      setUpgradeHighlight(null);1663                      handleBack();1664                    }, 200);1665                  }}1666                  onImport={() => setView("import")}1667                  onExport={() => setView("export")}1668                  onBreachCheckDone={loadEntries}1669                  onOpenHealth={openHealth}1670                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1671                  onOpenFileImport={handleOpenFileImport}1672                  onOpenPanic={() => setView("panic")}1673                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1674                  onOpenCodexRestore={() => setView("codex-restore")}1675                  onCardChange={setSettingsActiveCard}1676                  onProGate={(feature) => {1677                    setUpgradeHighlight(feature);1678                    setSettingsInitialSection("license");1679                  }}1680                />1681              </Suspense>1682            </Show>1683            <Show when={view() === "codex-generate"}>1684              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1685                <CodexGenerateView1686                  isPro={proStatus()}1687                  onBack={() => setView("settings")}1688                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1689                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1690                  onVaultLocked={() => handleLock()}1691                />1692              </Suspense>1693            </Show>1694            <Show when={view() === "codex-restore"}>1695              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1696                <CodexRestoreView1697                  onBack={() => setView("lock")}1698                  onRestoreSuccess={async () => {1699                    // After restore the vault is unlocked; refresh entries1700                    // and route to the main vault list. handleUnlock is the1701                    // canonical post-unlock setup path.1702                    await handleUnlock();1703                  }}1704                />1705              </Suspense>1706            </Show>1707            <Show when={view() === "pair-device"}>1708              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1709                <PairDeviceView1710                  isPro={proStatus()}1711                  onProChanged={() => { void refreshProStatus(); }}1712                  onBack={() => setView("settings")}1713                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1714                />1715              </Suspense>1716            </Show>1717            <Show when={view() === "add"}>1718              <AddView1719                entry={editEntry()}1720                entries={entries()}1721                onBack={handleBack}1722                onSave={handleSave}1723              />1724            </Show>1725            <Show when={view() === "import"}>1726              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1727                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1728              </Suspense>1729            </Show>1730            <Show when={view() === "export"}>1731              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1732                <ExportView onBack={handleExportBack} />1733              </Suspense>1734            </Show>1735            <Show when={view() === "panic"}>1736              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1737                <PanicView1738                  onCancel={() => setView("settings")}1739                  onOpenExport={() => {1740                    setReturnToPanic(true);1741                    setView("export");1742                  }}1743                  onDestroyed={async () => {1744                    // Fresh onboarding start after a destroy — don't let the1745                    // resume markers land the user mid-carousel.1746                    setOnboardingCardAtExit(0);1747                    void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1748                    clearOnboardingExit();1749                    setEntries([]);1750                    setSelectedEntry(null);1751                    setEditEntry(undefined);1752                    setHasVault(false);1753                    setOnboarded(false);1754                    setProStatus(false);1755                    setPendingPasskey(null);1756                    setUpgradeHighlight(null);1757                    setSettingsInitialSection(null);1758                    setPendingProNotice(null);1759                    setPendingCelebration(false);1760                    setReturnToPanic(false);1761                    setContentPhase("idle");1762                    setView("lock");1763                  }}1764                />1765              </Suspense>1766            </Show>1767            {/* Health stays mounted while editing an entry from it so1768                computeReused() doesn't rerun on every cancel/back. */}1769            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1770              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1771                <HealthView1772                  entries={entries()}1773                  isPro={proStatus()}1774                  onFixEntry={handleFixEntry}1775                  onBack={() => setView("settings")}1776                  onRefresh={loadEntries}1777                  hidden={view() !== "health"}1778                />1779              </Suspense>1780            </Show>1781            <Show when={view() === "trash"}>1782              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1783                <TrashView1784                  onBack={() => setView("list")}1785                  onRestored={() => void loadEntries()}1786                />1787              </Suspense>1788            </Show>1789            <Show when={showNotes()}>1790              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1791                <NotesMode1792                  notes={entries().filter((e) => e.type === "note")}1793                  initialNoteId={openNoteId()}1794                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1795                  onNoteListChanged={() => void loadEntries()}1796                />1797              </div>1798            </Show>1799            <Show when={restoreView() === "file"}>1800              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1801                <ImportView1802                  mode="onboarding"1803                  replacesExistingVault={true}1804                  onBack={() => setRestoreView(null)}1805                  onImport={async () => {1806                    setRestoreView(null);1807                    await handleUnlock();1808                  }}1809                />1810              </Suspense>1811            </Show>1812            </section>1813            </Show>1814          </Show>1815        </Show>1816      </Show>1817      <Show when={showShortcutsHelp()}>1818        <ShortcutsHelpOverlay1819          bindings={shortcutBindings()}1820          onClose={() => setShowShortcutsHelp(false)}1821        />1822      </Show>1823    </div>1824  );1825}18261827function ShortcutsHelpOverlay(props: {1828  bindings: Record<ShortcutAction, Keybinding>;1829  onClose: () => void;1830}) {1831  return (1832    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1833      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1834        <div class="peach-shortcuts-help-head">1835          <h3>Keyboard shortcuts</h3>1836          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1837        </div>1838        <div class="peach-shortcuts-help-body">1839          <p class="peach-settings-sub-label">ENTRY VIEW</p>1840          <ul>1841            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1842              <li>1843                <span>{d.label}</span>1844                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1845              </li>1846            ))}1847          </ul>1848          <p class="peach-settings-sub-label">ANYWHERE</p>1849          <ul>1850            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1851              <li>1852                <span>{d.label}</span>1853                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1854              </li>1855            ))}1856          </ul>1857        </div>1858      </div>1859    </div>1860  );1861}