App.tsx

82.5 KB · raw

1import { createEffect, createMemo, createSignal, For, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { storageGet, storageRemove, storageSet } from "../shared/storage";3import { sendMessage } from "../shared/bridge";4import { ACCENT_COLORS } from "../shared/types";5import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";6import { isPasskeyOnly } from "../shared/types";7import {8  hasCompletedInitialSync,9  INITIAL_SYNC_PENDING_DEVICE_KEY,10  type InitialSyncDevice,11} from "../shared/initial-sync";12import { LockView, RESTORE_SOURCE_STORAGE_KEY, type RestoreSource } from "./views/Lock";13import { WhatsNewView } from "./views/WhatsNew";14import { shouldShowWhatsNew } from "../shared/release-notes";15import {16  ONBOARDING_CARD_STORAGE_KEY,17  ONBOARDING_LAST_CARD,18  Onboarding,19} from "./views/Onboarding";2021const ONBOARDING_EXIT_STORAGE_KEY = "peach_onboarding_exit";22import { NotesMode } from "./views/NotesMode";23import { ProCelebration } from "./views/ProCelebration";24import { InitialSyncView } from "./views/InitialSyncView";25import { VaultView, type SortOrder } from "./views/Vault";26import { EntryView } from "./views/Entry";27import { AddView } from "./views/Add";28import { PeachWordmark } from "./components/PeachMark";29import { PasskeyApprovalView } from "./views/PasskeyApproval";30import { detectHomograph, extractDomain, getSecurityOriginDisplay } from "../shared/domain";31import {32  syncIndicator,33  syncIndicatorLabel,34  type SyncOutcomeSummary,35} from "../shared/sync-outcome";36import { popupCopy } from "./copy";37import {38  DEFAULT_BINDINGS,39  formatKeybinding,40  getActiveBindings,41  matchKeybinding,42  SHORTCUT_DESCRIPTORS,43  type Keybinding,44  type ShortcutAction,45} from "../shared/shortcuts";46import { generateTOTP } from "../crypto/totp";4748export { sendMessage } from "../shared/bridge";4950const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));51const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));52const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));53const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));54const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));55const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));56const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));57const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));58const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));59const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));6061type View =62  | "lock"63  | "pro-celebration"64  | "whats-new"65  | "entry"66  | "list"67  | "add"68  | "settings"69  | "pair-device"70  | "import"71  | "export"72  | "health"73  | "trash"74  | "panic"75  | "adopting"76  | "initial-sync"77  | "codex-generate"78  | "codex-restore";79type BootState = "loading" | "ready";8081const INITIAL_SYNC_POLL_MS = 500;82const INITIAL_SYNC_SLOW_MS = 15_000;8384let shellRingAnimation: Animation | null = null;8586export function triggerRing() {87  const shell = document.getElementById("hd-shell");88  if (!shell) return;8990  shellRingAnimation?.cancel();91  shell.dataset.glowing = "true";92  const animation = shell.animate(93    [94      { offset: 0, boxShadow: "var(--copy-shadow)" },95      {96        offset: 0.3,97        boxShadow:98          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",99      },100      { offset: 1, boxShadow: "var(--copy-shadow)" },101    ],102    {103      duration: 720,104      easing: "cubic-bezier(0.4, 0, 0.2, 1)",105      fill: "none",106    }107  );108  shellRingAnimation = animation;109  const clearGlow = () => {110    if (shellRingAnimation !== animation) return;111    shellRingAnimation = null;112    delete shell.dataset.glowing;113  };114  animation.onfinish = clearGlow;115  animation.oncancel = clearGlow;116}117118export function triggerPipPulse() {119  const pip = document.querySelector(".peach-status-pip, .pip");120  if (pip) {121    pip.classList.remove("pulse");122    void (pip as HTMLElement).offsetWidth;123    pip.classList.add("pulse");124  }125}126127const ENTRY_TRANSITION_SETTLE_MS = 135;128129export default function App() {130  const [bootState, setBootState] = createSignal<BootState>("loading");131  const [view, setView] = createSignal<View>("lock");132  const [contentPhase, setContentPhase] = createSignal<"enter" | "idle">("enter");133  const [hasVault, setHasVault] = createSignal(false);134  const [onboarded, setOnboarded] = createSignal(true);135  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);136  // The restore source picked before the popup closed (the OS file picker137  // kills it), so reopening resumes the same source form instead of the138  // picker. Read from RESTORE_SOURCE_STORAGE_KEY at boot.139  const [resumeRestoreSource, setResumeRestoreSource] = createSignal<RestoreSource | null>(null);140  // Onboarding remounts whenever it leaves (create/adopt/restore) and comes141  // back. Those flows all exit from the final card, so resume there — a fresh142  // install's first mount stays at 0.143  const [onboardingCardAtExit, setOnboardingCardAtExit] = createSignal(0);144  const [entries, setEntries] = createSignal<VaultEntry[]>([]);145  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);146  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);147148  // Rare device-trust alerts stay visible; routine entry sync is silent.149  interface SyncAlert {150    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";151    entryId: string;152    entryTitle: string;153    deviceName: string;154    timestamp: number;155  }156  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);157  // Per-group flip index: which alert within a type-group is currently shown.158  const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});159  async function loadSyncAlerts() {160    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {161      ok: boolean;162      data?: SyncAlert[];163    };164    if (r.ok) setSyncAlerts(r.data ?? []);165  }166  async function dismissAlertGroup(type: SyncAlert["type"]) {167    const result = (await sendMessage({168      type: "DISMISS_SYNC_ALERTS",169      payload: { type },170    })) as { ok: boolean };171    if (!result.ok) return;172    setSyncAlerts((arr) => arr.filter((a) => a.type !== type));173    setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });174  }175  function flipAlert(type: string, dir: 1 | -1) {176    const group = syncAlerts().filter((a) => a.type === type);177    if (group.length <= 1) return;178    setAlertFlipIdx((m) => {179      const cur = m[type] ?? 0;180      return { ...m, [type]: (cur + dir + group.length) % group.length };181    });182  }183  /** Grouped alert types in display order, each with its alerts. */184  const alertGroups = createMemo(() => {185    const map = new Map<string, SyncAlert[]>();186    for (const a of syncAlerts()) {187      const g = map.get(a.type);188      if (g) g.push(a); else map.set(a.type, [a]);189    }190    return [...map.entries()];191  });192  function syncAlertText(a: SyncAlert): string {193    if (a.type === "DEVICE_REVOKED") {194      return `${a.deviceName} revoked a paired device — review your devices in Settings`;195    }196    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;197  }198  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");199  const [theme, setTheme] = createSignal<"dark" | "light">("dark");200  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");201  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);202  const [lockOnClose, setLockOnClose] = createSignal(false);203  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);204  const [lockedSyncRequiresUnlock, setLockedSyncRequiresUnlock] = createSignal(false);205  const [breachMonitoring, setBreachMonitoring] = createSignal(true);206  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);207  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);208  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);209  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);210  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);211  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");212  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");213  // Cached Pro status — synchronous for render paths. Background's214  // GET_LICENSE is async, but render-time reads of isPro() must not block.215  // Refreshed at boot, after activate/deactivate, and whenever the popup216  // re-opens onto a stored license that has changed via another window.217  const [proStatus, setProStatus] = createSignal(false);218  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);219  // When the sync card's pairing button opens the pairing view, deep-link220  // straight into that pairing path instead of the rest screen.221  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");222  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);223  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");224  const [listSearchSeed, setListSearchSeed] = createSignal("");225  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);226  const [pendingCelebration, setPendingCelebration] = createSignal(false);227  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);228  // A page asked to be remembered for an entry it did not match. Pages cannot229  // grow an entry's domain set themselves (PB-26-106), so the background queues230  // the request here and this banner is the confirmation gate.231  const [pendingRememberSite, setPendingRememberSite] = createSignal<{232    entryId: string;233    url: string;234    title: string;235  } | null>(null);236  // True while Panic Step 1 has bounced the user out to Export. When Export's237  // onBack fires we return to Panic instead of Settings so the user keeps the238  // destruction context they came from.239  const [returnToPanic, setReturnToPanic] = createSignal(false);240  // The view to return to when the add/edit view is dismissed. Normally "entry"241  // but "health" when the user arrives via the fix-entry path from Vault Health.242  const [editBackView, setEditBackView] = createSignal<View>("entry");243  const [settingsExiting, setSettingsExiting] = createSignal(false);244  const [showNotes, setShowNotes] = createSignal(false);245  // Topbar sync affordance. Always present: gating it on having a paired device246  // meant it never appeared for the person trying to set pairing up, which is247  // exactly when you reach for it.248  const [syncBusy, setSyncBusy] = createSignal(false);249  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);250  // The indicator light + its spoken-word equivalent. Colour alone is not the251  // signal; the title/aria-label always carries the same claim in English.252  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});253  const [pairedCount, setPairedCount] = createSignal(0);254  const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);255  const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);256  let initialSyncWaitGeneration = 0;257  const syncLight = () =>258    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());259  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());260  async function loadSyncIndicator() {261    const [stateRes, devicesRes] = await Promise.all([262      sendMessage({ type: "GET_SYNC_STATE" }),263      sendMessage({ type: "LIST_PAIRED_DEVICES" }),264    ]);265    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };266    if (s.ok && s.data) setSyncSummary(s.data);267    const d = devicesRes as { ok: boolean; error?: string; data?: { devices?: unknown[] } };268    if (d.ok) {269      setPairedCount(d.data?.devices?.length ?? 0);270    } else if (d.error === "trust_data_corrupted") {271      setPairedCount(0);272      setSyncSummary({ status: "error", outcome: "trust_data_corrupted" });273    }274  }275276  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {277    const response = (await sendMessage({278      type: "LIST_PAIRED_DEVICES",279    })) as {280      ok: boolean;281      error?: string;282      data?: { devices?: InitialSyncPairedDevice[] };283    };284    if (response.ok) return response.data?.devices ?? [];285    if (response.error === "trust_data_corrupted") throw new Error("trust_data_corrupted");286    throw new Error(response.error ?? "list_paired_devices_failed");287  }288  interface InitialSyncPairedDevice extends InitialSyncDevice {289    pairedAt?: number;290  }291292293  async function resolveInitialSyncDeviceId(): Promise<string | null> {294    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(295      () => null,296    );297    const devices = await listInitialSyncDevices().catch(() => []);298    if (stored && devices.some((device) => device.deviceId === stored)) {299      return stored;300    }301302    // Fresh adoption has exactly one direct source, but choosing the newest row303    // also repairs the marker if storage failed after the pair itself committed.304    const newest = [...devices].sort(305      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),306    )[0];307    if (!newest) return stored;308    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(309      () => undefined,310    );311    return newest.deviceId;312  }313314  async function finishInitialSync(generation: number): Promise<void> {315    if (generation !== initialSyncWaitGeneration) return;316    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);317    setInitialSyncDeviceId(null);318    setInitialSyncSlow(false);319    await refreshProStatus();320321    // A license transferred during pairing intentionally leaves the one-shot322    // celebration pending. Consume it only now: sync readiness → celebration323    // → populated vault, never celebration → temporarily empty vault.324    const celebration = (await sendMessage({325      type: "SHOULD_PLAY_CELEBRATION",326    })) as { ok: boolean; data?: boolean };327    const shouldCelebrate = celebration.ok && celebration.data === true;328    if (shouldCelebrate) {329      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });330    }331332    const opened = await openVault(undefined, shouldCelebrate);333    if (!opened || generation !== initialSyncWaitGeneration) return;334    if (shouldCelebrate) {335      setView("pro-celebration");336      window.setTimeout(() => {337        if (generation === initialSyncWaitGeneration) setView("entry");338      }, 2500);339    }340  }341342  async function beginInitialSyncWait(deviceId: string): Promise<void> {343    const generation = ++initialSyncWaitGeneration;344    setInitialSyncDeviceId(deviceId);345    setInitialSyncSlow(false);346    setView("initial-sync");347    const startedAt = Date.now();348349    // Best effort: the pairing write already wakes the mesh listener, while350    // this trigger covers the key-order case where this receiver is the dialer.351    void sendMessage({352      type: "TRIGGER_SYNC",353      payload: { reason: "foreground" },354    }).catch(() => undefined);355356    while (357      generation === initialSyncWaitGeneration &&358      view() === "initial-sync"359    ) {360      try {361        const devices = await listInitialSyncDevices();362        if (hasCompletedInitialSync(devices, deviceId)) {363          await finishInitialSync(generation);364          return;365        }366      } catch {367        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.368      }369      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {370        setInitialSyncSlow(true);371      }372      await new Promise((resolve) =>373        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),374      );375    }376  }377378  async function retryInitialSync(): Promise<void> {379    const deviceId =380      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());381    if (deviceId) {382      await beginInitialSyncWait(deviceId);383    } else {384      setInitialSyncSlow(true);385    }386  }387388  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);389  // Set on popup boot when peach_recovery_pending flag is found in session390  // storage — instructs LockView to skip the unlock UI and open the recovery391  // words confirmation surface instead. Cleared via handleUnlock once the392  // user has typed the 3 confirmation words.393  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);394395  let contentPhaseTimer: number | undefined;396  // Set when the popup was opened from the inline "Open Peach to unlock" button.397  // handleUnlock() closes the popup after unlock so the user returns to the page.398  let openedForInlineUnlock = false;399400  onCleanup(() => {401    initialSyncWaitGeneration += 1;402  });403404  function applyAccent(name: AccentColorName) {405    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;406    const hex = color.hex;407    document.documentElement.style.setProperty("--peach-accent", hex);408    // Ambient variables derived from the selected accent.409    document.documentElement.style.setProperty("--peach-glow", hex + "2A");410    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");411  }412413  createEffect(() => {414    applyAccent(accentColor());415  });416417  createEffect(() => {418    document.documentElement.classList.toggle("light", theme() === "light");419    document.body.classList.toggle("light", theme() === "light");420  });421422  createEffect(() => {423    document.documentElement.setAttribute("data-text-size", textSize());424  });425426  createEffect(() => {427    if (reduceMotion()) {428      document.documentElement.setAttribute("data-motion", "reduce");429    } else {430      document.documentElement.removeAttribute("data-motion");431    }432  });433434  // Notes are not a destination of the Entry view; selecting a note opens the435  // notes surface instead (handleSelectEntry). Anything that walks or counts436  // the Entry view's neighbours (counter, prev/next, index) must use this437  // filtered list, otherwise the user can arrow into a note and is stuck —438  // the Entry view can't render a note and the prev/next buttons stop moving.439  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));440441  const selectedIndex = createMemo(() => {442    const currentId = selectedEntry()?.id;443    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;444    return nonNoteEntries().findIndex((entry) => entry.id === currentId);445  });446447  async function applyAccentColor(name: AccentColorName) {448    applyAccent(name);449    setAccentColor(name);450    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });451  }452453  async function applyTheme(t: "dark" | "light") {454    setTheme(t);455    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });456  }457458  async function applyTextSize(size: "small" | "medium" | "large") {459    setTextSize(size);460    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });461  }462463  async function applyReduceMotion(enabled: boolean) {464    setReduceMotion(enabled);465    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });466  }467468  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload469  // small and lets future default updates land for actions the user hasn't470  // touched. Settings sends us the full active map; we filter and store.471  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {472    setShortcutBindings(active);473    const overrides: Record<string, Keybinding> = {};474    for (const action of Object.keys(active) as ShortcutAction[]) {475      const a = active[action];476      const d = DEFAULT_BINDINGS[action];477      const same = a.key === d.key478        && Boolean(a.ctrl)  === Boolean(d.ctrl)479        && Boolean(a.meta)  === Boolean(d.meta)480        && Boolean(a.shift) === Boolean(d.shift)481        && Boolean(a.alt)   === Boolean(d.alt);482      if (!same) overrides[action] = a;483    }484    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });485  }486487  async function applyLockOnClose(enabled: boolean) {488    setLockOnClose(enabled);489    await sendMessage({490      type: "UPDATE_SETTINGS",491      payload: { lockOnClose: enabled },492    });493  }494495  async function applyAutoLockMinutes(minutes: number) {496    setAutoLockMinutes(minutes);497    await sendMessage({498      type: "UPDATE_SETTINGS",499      payload: { autoLockMinutes: minutes },500    });501  }502  async function applyLockedSyncRequiresUnlock(enabled: boolean) {503    setLockedSyncRequiresUnlock(enabled);504    await sendMessage({ type: "UPDATE_SETTINGS", payload: { lockedSyncRequiresUnlock: enabled } });505  }506507  async function applyBreachMonitoring(enabled: boolean) {508    setBreachMonitoring(enabled);509    await sendMessage({510      type: "UPDATE_SETTINGS",511      payload: { breachMonitoring: enabled },512    });513  }514515  // Which onboarding exit flow the user is in (create-vault / restore /516  // adopt). Persisted so closing the popup on one of those screens resumes517  // it directly instead of rewinding to the last carousel card.518  function markOnboardingExit(flow: "create" | "restore" | "adopt") {519    setOnboardingCardAtExit(ONBOARDING_LAST_CARD);520    void storageSet(ONBOARDING_EXIT_STORAGE_KEY, flow).catch(() => {});521    // Backing out of the flow remounts the carousel at this card; keep the522    // persisted card in sync so a later popup close resumes consistently.523    void storageSet(ONBOARDING_CARD_STORAGE_KEY, String(ONBOARDING_LAST_CARD)).catch(() => {});524  }525  function clearOnboardingExit() {526    void storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});527    void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});528    setResumeRestoreSource(null);529  }530531  onMount(async () => {532    // Resolve the active tab in parallel with the unlock/has-vault queries —533    // openVault()'s smart selection picks the entry matching currentTabDomain,534    // so it must be populated before openVault runs. Previously refreshCurrentTab535    // ran after openVault, leaving popups that booted already-unlocked falling536    // back to loadedEntries[0] instead of the domain match.537    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([538      sendMessage({ type: "IS_UNLOCKED" }),539      sendMessage({ type: "HAS_VAULT" }),540      refreshCurrentTab(),541      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),542    ]);543    const unlocked = Boolean(544      (unlockResponse as { ok: boolean; data?: boolean }).data545    );546    const vaultExists = Boolean(547      (vaultResponse as { ok: boolean; data?: boolean }).data548    );549    const shouldCelebrate = Boolean(550      (celebrationResponse as { ok: boolean; data?: boolean }).data551    );552    setHasVault(vaultExists);553    // Onboarding gate — show once on first install, never again. Existing554    // users (vaultExists) are auto-marked onboarded so they skip the flow555    // even on the very first popup open after this feature ships.556    try {557      const onboarded = await storageGet("peach_onboarded");558      const seen = onboarded === "true";559      if (vaultExists && !seen) {560        await storageSet("peach_onboarded", "true");561        await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});562        await storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});563        await storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});564        setOnboarded(true);565      } else {566        setOnboarded(seen);567        if (!seen) {568          // A popup close while the user is in an exit flow (create-vault /569          // restore / adopt) resumes that flow directly — landing back on the570          // carousel one screen earlier reads as losing progress.571          const exit = await storageGet(ONBOARDING_EXIT_STORAGE_KEY).catch(() => null);572          if (exit === "create" || exit === "restore" || exit === "adopt") {573            setOnboardingCardAtExit(ONBOARDING_LAST_CARD);574            setOnboarded(true);575            setStartOnboardingRestore(exit === "restore");576            if (exit === "restore") {577              // The OS file picker kills the action popup mid-restore, so the578              // surface resumes on the source the user had already picked.579              const source = await storageGet(RESTORE_SOURCE_STORAGE_KEY).catch(() => null);580              if (source === "symbols" || source === "codex" || source === "csv") {581                setResumeRestoreSource(source);582              }583            }584            if (exit === "adopt") setView("adopting");585          } else {586            // Otherwise resume mid-onboarding where the user left off instead587            // of rewinding to the opening card.588            const stored = Number(589              await storageGet(ONBOARDING_CARD_STORAGE_KEY).catch(() => null),590            );591            if (592              Number.isInteger(stored) &&593              stored > 0 &&594              stored <= ONBOARDING_LAST_CARD595            ) {596              setOnboardingCardAtExit(stored);597            }598          }599        }600      }601    } catch {602      // storage unavailable — default to onboarded so we never block boot603      setOnboarded(true);604    }605606    // Deep-link: ?restore=peachscript|csv — the detached-window half of the607    // file-picker flow. The action popup dismisses when the OS dialog steals608    // focus, so LockView.detachForFilePicker() reopens this URL in a609    // standalone window that owns the dialog. Routing runs before first610    // render so LockView mounts straight onto the right source form.611    try {612      const restoreRoute = new URLSearchParams(window.location.search).get("restore");613      if (restoreRoute === "peachscript" || restoreRoute === "csv") {614        setOnboarded(true);615        setStartOnboardingRestore(true);616        setResumeRestoreSource(restoreRoute === "peachscript" ? "symbols" : "csv");617      }618    } catch {619      // location.search unavailable — ignore.620    }621622    await Promise.all([restoreSettings(), refreshProStatus()]);623624    const pendingInitialSyncMarker =625      unlocked && vaultExists626        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)627        : null;628    const pendingInitialSyncDeviceId = pendingInitialSyncMarker629      ? await resolveInitialSyncDeviceId()630      : null;631632    // Mark played before any animation so a crash mid-sequence never replays633    // it. A newly adopted receiver deliberately defers this until its first634    // real sync finishes, preserving initial sync → celebration → vault.635    if (shouldCelebrate && !pendingInitialSyncDeviceId) {636      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });637    }638639    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome640    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.641    if (unlocked && vaultExists) {642      void sendMessage({643        type: "TRIGGER_SYNC",644        payload: { reason: "foreground" },645      });646      void loadSyncIndicator();647      // Rare device-trust alerts only; routine entry sync stays quiet.648      void loadSyncAlerts();649    }650651    // If the user created a vault but hasn't yet confirmed their recovery652    // words, route back to the recovery-words screen instead of opening the653    // entries view. The flag lives in chrome.storage.local so it survives654    // popup close while the background owns the session-scoped confirmation655    // exemption. Cleared when confirmation succeeds.656    let recoveryPending = false;657    try {658      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });659      recoveryPending = out.ok === true && out.data === true;660    } catch { /* best-effort */ }661662    // Content UI can ask the background to open this trusted popup either for663    // unlock or at a specific entry. Consume both session-scoped handoffs once.664    let pendingOpenEntryId: string | undefined;665    if (chrome.storage.session) {666      try {667        const s = await chrome.storage.session.get(["peach_inline_unlock", "peach_open_entry"]);668        const pending = s as { peach_inline_unlock?: boolean; peach_open_entry?: string };669        if (pending.peach_inline_unlock) {670          openedForInlineUnlock = true;671        }672        if (typeof pending.peach_open_entry === "string") pendingOpenEntryId = pending.peach_open_entry;673        await chrome.storage.session.remove(["peach_inline_unlock", "peach_open_entry"]);674      } catch { /* best-effort */ }675    }676677    if (recoveryPending && unlocked) {678      // forceRecoveryWords overrides LockView's hasVault gate so the679      // recovery surface renders even though the vault now exists.680      setForceRecoveryWords(true);681      setView("lock");682    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {683      void beginInitialSyncWait(pendingInitialSyncDeviceId);684    } else if (unlocked && vaultExists) {685      await openVault(pendingOpenEntryId, shouldCelebrate);686      if (shouldCelebrate) {687        setView("pro-celebration");688        window.setTimeout(() => setView("entry"), 2500);689      } else if (await shouldShowWhatsNew()) {690        setView("whats-new");691      }692    } else if (shouldCelebrate) {693      setPendingCelebration(true);694    }695696    await refreshPendingPasskey();697698    // Track tab changes so smart sort stays current699    const handleTabActivated = () => { void refreshCurrentTab(); };700    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {701      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();702    };703    try {704      chrome.tabs.onActivated.addListener(handleTabActivated);705      chrome.tabs.onUpdated.addListener(handleTabUpdated);706      onCleanup(() => {707        chrome.tabs.onActivated.removeListener(handleTabActivated);708        chrome.tabs.onUpdated.removeListener(handleTabUpdated);709      });710    } catch {711      // tabs permission may not be available in all contexts712    }713714    setBootState("ready");715716    // Deep-link: ?codex=pdf opens a detached window straight into the717    // Codex restore flow with auto-picked PDF. The action popup can't host718    // a file dialog without dismissing itself, so this is the only way the719    // PDF import path survives. See CodexRestoreView.openPdfPicker().720    try {721      const route = new URLSearchParams(window.location.search).get("codex");722      if (route === "pdf" || route === "restore") {723        setView("codex-restore");724      }725    } catch {726      // location.search unavailable — ignore.727    }728729    // Check for pending session-storage notices from the background.730    if (chrome.storage.session) {731      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as732        Record<string, { feature?: string } | undefined>;733      if (session.pendingProGate?.feature) {734        await chrome.storage.session.remove("pendingProGate");735        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);736        setSettingsInitialSection("license");737        setView("settings");738      } else if (session.pendingProNotice?.feature) {739        await chrome.storage.session.remove("pendingProNotice");740        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });741      }742      const remembered = (await chrome.storage.session.get("pendingRememberSite")) as {743        pendingRememberSite?: { entryId?: unknown; url?: unknown };744      };745      const request = remembered.pendingRememberSite;746      if (747        typeof request?.entryId === "string" &&748        typeof request.url === "string"749      ) {750        const entry = await sendMessage({ type: "GET_ENTRIES" });751        const match = entry.ok752          ? (entry.data as Array<{ id: string; title?: string }> | undefined)?.find(753              (candidate) => candidate.id === request.entryId,754            )755          : undefined;756        if (match) {757          let host = request.url;758          try { host = new URL(request.url).hostname; } catch { /* keep raw */ }759          setPendingRememberSite({ entryId: request.entryId, url: request.url, title: match.title ?? host });760        } else {761          await chrome.storage.session.remove("pendingRememberSite");762        }763      }764    }765766    // Warm the lazy-module cache so the Suspense fallback never shows for767    // locally-bundled extension views. Without this, the first navigation to768    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which769    // covers the shell and absorbs clicks on the header.770    void Promise.all([771      import("./views/Settings").catch(() => {}),772      import("./views/Import").catch(() => {}),773      import("./views/Export").catch(() => {}),774      import("./views/Health").catch(() => {}),775      import("./views/TrashView").catch(() => {}),776    ]);777778    // Lock-on-close via a persistent port. sendMessage in pagehide is779    // unreliable — the popup context tears down before the message lands.780    // The SW's onConnect listener locks when this port disconnects.781    let popupPort: chrome.runtime.Port | null = null;782    try {783      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect784      // listener accepts the "popup-" prefix; the random suffix is defence in785      // depth against a port named exactly "popup" from anything but our popup.786      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });787    } catch { /* extension context invalidated — ignore */ }788    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });789790    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale791    // entries instead of waiting for the next GET_ENTRIES round-trip.792    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {793      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();794      if (msg?.type === "SYNC_STATE_CHANGED") {795        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);796      }797      if (msg?.type === "PRO_GATE_TRIGGERED") {798        setUpgradeHighlight(msg.payload?.feature ?? null);799        setSettingsInitialSection("license");800        setView("settings");801      }802    };803    chrome.runtime.onMessage.addListener(handleRuntimeMessage);804    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));805806    // Action handlers — keyed by ShortcutAction. The dispatcher below tests807    // each binding against the event and runs the matching handler. New808    // shortcuts only need an entry here; the binding is data, not code.809    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {810      copy_password: () => {811        const entry = selectedEntry();812        if (entry?.password) void popupCopy(813          entry.password,814          "Password",815          entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,816        ).then((ok) => { if (ok) triggerRing(); });817      },818      copy_username: () => {819        const entry = selectedEntry();820        if (entry?.username) void popupCopy(821          entry.username,822          "Username",823          entry.canary?.webhookUrl ? { webhookUrl: entry.canary.webhookUrl, entryTitle: entry.title } : undefined,824        ).then((ok) => { if (ok) triggerRing(); });825      },826      copy_totp: () => {827        const entry = selectedEntry();828        if (!entry?.totp) return;829        try {830          const { code } = generateTOTP(831            entry.totp,832            entry.totpAlgorithm,833            entry.totpDigits,834            entry.totpPeriod,835          );836          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });837        } catch { /* invalid TOTP secret — silent */ }838      },839      new_entry: () => handleAdd(),840      edit_entry: () => {841        const entry = selectedEntry();842        // Passkey-only entries have nothing user-editable in the Add view; the843        // passkey credential itself is opaque. Skip the edit action for them.844        if (!entry || isPasskeyOnly(entry)) return;845        setEditEntry(entry);846        setView("add");847      },848      delete_entry: () => {849        if (selectedEntry()) void handleDelete();850      },851      lock_vault: () => { void handleHeaderLock(); },852      search: () => openList(),853      nav_prev: () => navigate(-1),854      nav_next: () => navigate(1),855      jump_vault: () => setView("entry"),856      jump_settings: () => setView("settings"),857      show_help: () => setShowShortcutsHelp(true),858    };859860    // Actions that are MEANINGFUL only on the entry-detail view. Outside861    // that scope the binding is dormant — pressing C while on Settings862    // does nothing rather than awkwardly copying from a now-stale entry.863    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([864      "copy_password", "copy_username", "copy_totp",865      "edit_entry", "delete_entry", "nav_prev", "nav_next",866    ]);867868    const handleGlobalKeydown = (e: KeyboardEvent) => {869      const v = view();870      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"871        || (e.target as HTMLElement)?.tagName === "TEXTAREA"872        || (e.target as HTMLElement)?.isContentEditable;873      const isPrintableSearchKey =874        e.key.length === 1 &&875        !e.ctrlKey &&876        !e.metaKey &&877        !e.altKey;878879      // No shortcuts while a full-screen surface owns the whole viewport:880      // the lock screen, the post-pairing readiness sequence, or the Pro881      // celebration. Without this the lock screen is at the mercy of whatever882      // single-key binding is active — e.g. typing "n" in a password that883      // slips out of focus triggers `new_entry` and escapes the lock screen.884      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;885886      // Help dialog: Escape closes it; eat the keypress so it doesn't887      // also navigate away from the underlying view.888      if (showShortcutsHelp()) {889        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }890        return;891      }892893      // ── Escape — fixed binding (not user-customizable) ───────894      if (e.key === "Escape") {895        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }896        if (v === "list") { setView("entry"); return; }897        if (v === "settings" || v === "add") { handleBack(); return; }898        if (v === "import" || v === "health") { setView("settings"); return; }899        if (v === "export") { handleExportBack(); return; }900        if (v === "pair-device") { setView("settings"); return; }901      }902903      // Bindings-driven dispatch. Single-key letter bindings without904      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is905      // inside an input, so users can type into search/forms normally.906      const bindings = shortcutBindings();907      for (const action of Object.keys(bindings) as ShortcutAction[]) {908        const binding = bindings[action];909        if (!matchKeybinding(e, binding)) continue;910        // Single-key letter bindings need the input-focus guard. Bindings911        // with any modifier are safe — Ctrl+L doesn't conflict with typing.912        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;913        if (!hasMod && binding.key.length === 1 && inInput) return;914        if (ENTRY_SCOPED.has(action) && v !== "entry") return;915        e.preventDefault();916        SHORTCUT_HANDLERS[action]?.();917        return;918      }919920      // Type-to-search: in entry view, any printable key not consumed by a921      // shortcut above primes the list search seed and opens the list.922      // Kept outside the bindings table because it's a behavior, not a923      // discrete action — every printable character can trigger it.924      if (v === "entry" && !inInput && isPrintableSearchKey) {925        e.preventDefault();926        primeListSearch(e.key);927        return;928      }929    };930    window.addEventListener("keydown", handleGlobalKeydown);931    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));932933    const handleStorageChanged = (934      changes: Record<string, chrome.storage.StorageChange>,935      areaName: string936    ) => {937      if (areaName !== "session") return;938      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {939        return;940      }941      void refreshPendingPasskey();942    };943    chrome.storage.onChanged.addListener(handleStorageChanged);944    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));945  });946947  async function refreshCurrentTab() {948    try {949      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });950      const url = tab?.url ?? tab?.pendingUrl ?? "";951      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");952      // Skip extension/internal URLs — adding chrome://, about:, or953      // chrome-extension:// to a vault entry is never what the user wants.954      const isWebUrl = /^https?:\/\//i.test(url);955      setCurrentTabUrl(isWebUrl ? url : "");956    } catch {957      setCurrentTabDomain("");958      setCurrentTabUrl("");959    }960  }961962  async function refreshPendingPasskey() {963    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });964    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);965  }966967  async function refreshProStatus() {968    const res = await sendMessage({ type: "GET_LICENSE" });969    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;970    setProStatus(Boolean(data?.valid && data?.plan === "pro"));971  }972973  async function restoreSettings() {974    const res = await sendMessage({ type: "GET_SETTINGS" });975    const s = (res as { ok: boolean; data?: any }).data ?? {};976    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {977      setAccentColor(s.accentColor as AccentColorName);978    }979    setTheme(s.theme === "light" ? "light" : "dark");980    if (s.textSize === "small" || s.textSize === "large") {981      setTextSize(s.textSize);982    } else {983      setTextSize("medium");984    }985    setReduceMotion(s.reduceMotion === true);986    setLockOnClose(s.lockOnClose === true);987    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);988    setLockedSyncRequiresUnlock(s.lockedSyncRequiresUnlock === true);989    setBreachMonitoring(s.breachMonitoring !== false);990    setShortcutBindings(getActiveBindings(s.shortcuts));991  }992993  async function applyTrashRetention(days: number) {994    setTrashRetentionDays(days);995    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });996  }997998  function primeListSearch(seed: string) {999    setListSearchSeed(seed);1000    setListSearchSeedNonce((value) => value + 1);1001    openList();1002  }10031004  // Returns null when it detected a dead service worker and triggered handleLock().1005  // Callers that need to abort (e.g. openVault) check for null rather than relying1006  // on view() state, which may already be "lock" during normal startup flows.1007  async function loadEntries(): Promise<VaultEntry[] | null> {1008    const response = await sendMessage({ type: "GET_ENTRIES" });1009    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };10101011    // If the service worker was killed and restarted (MV3 workers sleep), the1012    // vault will be locked again — or the worker may not respond at all.1013    // In either case, send the user to the lock screen rather than silently1014    // showing an empty vault (which looks like data loss).1015    if (!res.ok) {1016      if (1017        res.error === "vault_locked" ||1018        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1019        (typeof res.error === "string" && res.error.includes("locked"))1020      ) {1021        handleLock();1022        return null; // signal emergency lock to callers1023      }1024      return [];1025    }10261027    const loadedEntries = res.data ?? [];1028    setEntries(loadedEntries);10291030    const currentId = selectedEntry()?.id;1031    if (currentId) {1032      setSelectedEntry(1033        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1034      );1035    }10361037    return loadedEntries;1038  }10391040  async function openVault(preferredEntryId?: string, skipViewSet = false) {1041    // Purge expired trash entries on each vault open1042    const retDays = trashRetentionDays();1043    if (retDays > 0) {1044      void sendMessage({1045        type: "PURGE_EXPIRED_TRASH",1046        payload: { retentionMs: retDays * 86_400_000 },1047      });1048    }10491050    const loadedEntries = await loadEntries();10511052    // null means loadEntries() triggered an emergency lock (service worker died).1053    // Don't override it by setting view back to "entry" with an empty vault.1054    if (loadedEntries === null) return false;10551056    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1057    let nextSelectedEntry: VaultEntry | null = null;1058    if (preferredEntryId) {1059      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1060    }1061    if (!nextSelectedEntry) {1062      const tabDomain = currentTabDomain();1063      if (tabDomain) {1064        nextSelectedEntry = loadedEntries.find((e) => {1065          if (e.type === "login") {1066            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1067            for (const extra of e.additionalUrls ?? []) {1068              if ((extractDomain(extra) ?? "") === tabDomain) return true;1069            }1070            return false;1071          }1072          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1073          return false;1074        }) ?? null;1075      }1076    }1077    nextSelectedEntry ??= pickNavigable(loadedEntries);10781079    setSelectedEntry(nextSelectedEntry);1080    setEditEntry(undefined);1081    setContentPhase("enter");1082    queueContentIdle();1083    if (!skipViewSet) setView("entry");1084    return true;1085  }10861087  async function handleUnlock() {1088    // If the user previously created a vault but hadn't yet confirmed their1089    // recovery words (and the browser was closed before they could), the1090    // the background-owned recovery-pending state is still set. Re-route1091    // back to the recovery surface so they finish the confirmation step1092    // before reaching the entries view — the words can be re-derived now1093    // that the vault is unlocked again.1094    let recoveryPending = false;1095    try {1096      const out = await sendMessage({ type: "GET_RECOVERY_CONFIRM_PENDING" });1097      recoveryPending = out.ok === true && out.data === true;1098    } catch { /* best-effort */ }1099    if (recoveryPending) {1100      setForceRecoveryWords(true);1101      setView("lock");1102      triggerPipPulse();1103      await restoreSettings();1104      return;1105    }1106    setHasVault(true);1107    triggerPipPulse();1108    await restoreSettings();1109    const celebrating = pendingCelebration();1110    if (celebrating) {1111      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1112      setPendingCelebration(false);1113    }1114    await openVault(undefined, celebrating);1115    if (celebrating) {1116      setView("pro-celebration");1117      window.setTimeout(() => setView("entry"), 2500);1118    } else if (!openedForInlineUnlock && await shouldShowWhatsNew()) {1119      setView("whats-new");1120    }1121    // Popup was opened from the inline "Open Peach to unlock" button — close it1122    // now so the user lands back on the page with the autofill selector ready.1123    if (openedForInlineUnlock) {1124      openedForInlineUnlock = false;1125      window.close();1126    }1127  }11281129  function handleSelectEntry(entry: VaultEntry) {1130    if (entry.type === "note") {1131      setOpenNoteId(entry.id);1132      setShowNotes(true);1133      return;1134    }1135    setSelectedEntry(entry);1136    setContentPhase("enter");1137    queueContentIdle();1138    setView("entry");1139  }11401141  function handleAdd() {1142    setEditEntry(undefined);1143    setView("add");1144  }11451146  async function handleDelete() {1147    const entry = selectedEntry();1148    if (!entry) return;1149    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1150    const loadedEntries = await loadEntries() ?? [];1151    setSelectedEntry(pickNavigable(loadedEntries));1152    setView("entry");1153  }11541155  async function handleDeleteMany(ids: string[]) {1156    for (const id of ids) {1157      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1158    }1159    const loadedEntries = await loadEntries() ?? [];1160    // If the currently selected entry was among the deleted, move to first1161    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1162    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1163  }11641165  async function handleSave(savedEntry?: VaultEntry) {1166    await openVault(savedEntry?.id);1167  }11681169  function handleBack() {1170    const dest = editBackView();1171    setEditBackView("entry");1172    setEditEntry(undefined);1173    setView(dest);1174  }11751176  function handleExportBack() {1177    if (returnToPanic()) {1178      setReturnToPanic(false);1179      setView("panic");1180      return;1181    }1182    setView("settings");1183  }11841185  function handleLock() {1186    setEntries([]);1187    setSelectedEntry(null);1188    setEditEntry(undefined);1189    setContentPhase("idle");1190    setView("lock");1191  }11921193  function handleHeaderLock() {1194    // Lock the UI immediately — do not wait for the service worker. If the SW1195    // is dead or slow, the 5s sendMessage timeout would create a dead-click1196    // window. The SW will lock on its next wake regardless.1197    handleLock();1198    void sendMessage({ type: "LOCK" });1199  }12001201  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1202  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1203  // the trigger's own reply.1204  async function handleHeaderSync(): Promise<void> {1205    if (syncBusy()) return;1206    setSyncBusy(true);1207    setSyncFlash(null);1208    try {1209      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1210      let state: SyncOutcomeSummary = { status: "syncing" };1211      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1212        await new Promise((r) => setTimeout(r, 250));1213        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1214          ok: boolean;1215          data?: SyncOutcomeSummary;1216        };1217        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1218      }1219      setSyncSummary(state);1220      setSyncFlash(state.status === "error" ? "error" : "ok");1221      await loadSyncAlerts();1222      await loadEntries();1223      await loadSyncIndicator();1224    } catch {1225      setSyncSummary({ status: "error", outcome: "run_failed" });1226      setSyncFlash("error");1227    } finally {1228      setSyncBusy(false);1229      setTimeout(() => setSyncFlash(null), 2_000);1230    }1231  }12321233  function navigate(dir: number) {1234    const navigable = nonNoteEntries();1235    if (navigable.length === 0) return;1236    const currentIndex = selectedIndex();1237    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1238    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1239    setSelectedEntry(navigable[nextIndex]);1240    setContentPhase("enter");1241    queueContentIdle();1242  }12431244  /**1245   * The Entry view's selection invariant: never select a note. Notes are a1246   * separate surface (handleSelectEntry opens the notes view), so any code path1247   * that picks a default — vault open, post-delete, refresh — must skip them1248   * and return null if the only entries are notes.1249   */1250  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1251    return list.find((e) => e.type !== "note") ?? null;1252  }12531254  function openList() {1255    setView("list");1256  }12571258  function openHealth() {1259    setEditEntry(undefined);1260    setView("health");1261  }12621263  function handleOpenFileImport() {1264    setRestoreView("file");1265  }12661267  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12681269  function handleFixEntry(entry: VaultEntry) {1270    setSelectedEntry(entry);1271    // Passkey-only entries have no editable surface — drop into view mode1272    // instead of opening the Add editor.1273    if (isPasskeyOnly(entry)) {1274      setView("entry");1275      return;1276    }1277    setEditBackView(view()); // preserve caller view so back returns here1278    setEditEntry(entry);1279    setView("add");1280  }12811282  const isLockedView = () => view() === "lock" || view() === "adopting";12831284  async function handleAdoptionDone() {1285    await storageSet("peach_onboarded", "true").catch(() => {});1286    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1287    clearOnboardingExit();1288    setOnboarded(true);1289    setHasVault(true);1290    setView("initial-sync");1291    // The background applies a Pro license and persists the source-device1292    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1293    // celebration pending until that exact peer records a completed sync.1294    await refreshProStatus();1295    const deviceId = await resolveInitialSyncDeviceId();1296    if (deviceId) {1297      void beginInitialSyncWait(deviceId);1298    } else {1299      // Pairing completion without a durable peer row should be impossible.1300      // Stay on the honest waiting surface and expose retry instead of falling1301      // through to an empty vault.1302      setInitialSyncSlow(true);1303    }1304  }13051306  async function handleApprovePendingPasskey() {1307    const pending = pendingPasskey();1308    if (!pending) return;1309    if (pending.browser === "firefox" && pending.type === "create") {1310      // Firefox path: popup itself runs navigator.credentials.create. The1311      // background never approved/rejected anything — it just stashed1312      // intent. After the popup-driven flow resolves (success or cancel),1313      // clear the pending key so the popup doesn't re-show this on next open.1314      const { createFirefoxPasskey } = await import("./firefox-passkey");1315      const result = await createFirefoxPasskey(pending);1316      if (!result.ok) {1317        console.warn("Peach Firefox passkey create failed:", result.error);1318      }1319      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1320      setPendingPasskey(null);1321      void loadEntries();1322      window.close();1323      return;1324    }1325    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1326    window.close();1327  }13281329  async function handleDenyPendingPasskey() {1330    const pending = pendingPasskey();1331    if (!pending) return;1332    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1333    window.close();1334  }13351336  function queueContentIdle(after?: () => void) {1337    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1338    contentPhaseTimer = window.setTimeout(() => {1339      setContentPhase("idle");1340      after?.();1341    }, ENTRY_TRANSITION_SETTLE_MS);1342  }13431344  return (1345    <div class="popup-root peach-theme">1346      <Show when={bootState() === "ready"}>1347        <Show1348          when={!pendingPasskey()}1349          fallback={1350            <PasskeyApprovalView1351              type={pendingPasskey()!.type}1352              rpName={pendingPasskey()!.rpName}1353              rpId={pendingPasskey()!.rpId}1354              userName={pendingPasskey()!.userName}1355              userDisplayName={pendingPasskey()!.userDisplayName}1356              onApprove={handleApprovePendingPasskey}1357              onDeny={handleDenyPendingPasskey}1358            />1359          }1360        >1361          <Show1362            when={!isLockedView()}1363            fallback={1364              <Show1365                when={view() !== "adopting"}1366                fallback={1367                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1368                    <AdoptVaultView1369                      onCancel={() => {1370                        clearOnboardingExit();1371                        setOnboarded(false);1372                        setView("lock");1373                      }}1374                      onDone={handleAdoptionDone}1375                    />1376                  </Suspense>1377                }1378              >1379                <Show1380                  when={onboarded() || hasVault()}1381                  fallback={1382                    <Onboarding1383                      initialCard={onboardingCardAtExit()}1384                      onComplete={() => {1385                        markOnboardingExit("create");1386                        setStartOnboardingRestore(false);1387                        setOnboarded(true);1388                      }}1389                      onRestore={() => {1390                        markOnboardingExit("restore");1391                        setStartOnboardingRestore(true);1392                        setOnboarded(true);1393                      }}1394                      onAdopt={() => {1395                        markOnboardingExit("adopt");1396                        setStartOnboardingRestore(false);1397                        setOnboarded(true);1398                        setView("adopting");1399                      }}1400                    />1401                  }1402                >1403                  <LockView1404                    hasVault={hasVault()}1405                    ready={bootState() === "ready"}1406                    isPro={proStatus()}1407                    forceRecoveryWords={forceRecoveryWords()}1408                    initialRestore={startOnboardingRestore()}1409                    initialRestoreSource={resumeRestoreSource() ?? undefined}1410                    onUnlock={() => {1411                      // RecoveryWordDisplay clears the storage flag before1412                      // calling onDone, so handleUnlock will see no pending1413                      // confirmation and proceed through the normal path.1414                      if (forceRecoveryWords()) setForceRecoveryWords(false);1415                      // The create/restore flow is done — a lock later in this1416                      // window must show the unlock screen, not re-enter the1417                      // onboarding restore surface.1418                      setStartOnboardingRestore(false);1419                      setResumeRestoreSource(null);1420                      void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1421                      return handleUnlock();1422                    }}1423                    onBackToOnboarding={1424                      !hasVault()1425                        ? () => {1426                            // Deliberately rewinding to the carousel — the exit1427                            // flow must not reclaim the next popup open.1428                            clearOnboardingExit();1429                            setStartOnboardingRestore(false);1430                            setOnboarded(false);1431                          }1432                        : undefined1433                    }1434                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1435                  />1436                </Show>1437              </Show>1438            }1439          >1440            <Show1441              when={1442                view() !== "pro-celebration" &&1443                view() !== "initial-sync" &&1444                view() !== "whats-new"1445              }1446              fallback={1447                <Show1448                  when={view() === "initial-sync"}1449                  fallback={1450                    <Show1451                      when={view() === "whats-new"}1452                      fallback={<ProCelebration />}1453                    >1454                      <WhatsNewView onContinue={() => setView("entry")} />1455                    </Show>1456                  }1457                >1458                  <InitialSyncView1459                    slow={initialSyncSlow()}1460                    onRetry={() => void retryInitialSync()}1461                  />1462                </Show>1463              }1464            >1465            <section1466              id="hd-shell"1467              class="peach-shell peach-theme"1468              data-surface="extension"1469            >1470            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1471              <PeachWordmark unlocked />1472              <div class="peach-chrome-actions">1473                <button1474                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1475                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1476                  aria-label="Notes"1477                  title="Notes"1478                >1479                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1480                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1481                    <line x1="4" y1="5" x2="10" y2="5" />1482                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1483                    <line x1="4" y1="10" x2="7" y2="10" />1484                  </svg>1485                </button>1486                <button1487                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1488                    classList={{1489                      "is-syncing": syncBusy(),1490                      "is-ok": syncFlash() === "ok",1491                      "is-error": syncFlash() === "error",1492                    }}1493                    onClick={() => void handleHeaderSync()}1494                    disabled={syncBusy()}1495                    aria-label={`Sync now. ${syncLabel()}`}1496                    title={syncLabel()}1497                  >1498                    <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">1499                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1500                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1501                      <path d="M2.6 1v2.4h2.4" />1502                      <path d="M11.4 13v-2.4H9" />1503                    </svg>1504                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1505                  </button>1506                <button1507                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1508                  onClick={() => setView("settings")}1509                  aria-label="Settings"1510                >1511                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1512                    <path1513                      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"1514                      stroke="currentColor"1515                      stroke-width="0.9"1516                    />1517                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1518                  </svg>1519                </button>1520                <button1521                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1522                  onClick={handleAdd}1523                  aria-label="New entry"1524                >1525                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1526                    <path d="M5.5 1v9M1 5.5h9" />1527                  </svg>1528                </button>1529                <button1530                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1531                  onClick={() => void handleHeaderLock()}1532                  aria-label="Lock vault"1533                >1534                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1535                    <path1536                      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"1537                      stroke="currentColor"1538                      stroke-width="1"1539                      stroke-linecap="round"1540                    />1541                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1542                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1543                  </svg>1544                </button>1545              </div>1546            </header>15471548            <Show when={pendingProNotice() !== null}>1549              <div class="peach-pro-notice-banner">1550                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1551                <button1552                  class="peach-pro-notice-link"1553                  onClick={() => {1554                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1555                    setSettingsInitialSection("license");1556                    setView("settings");1557                    setPendingProNotice(null);1558                  }}1559                >1560                  Learn more →1561                </button>1562                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1563              </div>1564            </Show>15651566            <Show when={pendingRememberSite()}>1567              {(request) => {1568                const origin = getSecurityOriginDisplay(request().url);1569                const originLabel = detectHomograph(origin) ? `⚠ ${origin}` : origin;1570                return (1571                  <div class="peach-pro-notice-banner">1572                    <span>Also use “{request().title}” on {originLabel}?</span>1573                    <button1574                      class="peach-pro-notice-link"1575                      onClick={async () => {1576                        await sendMessage({1577                          type: "ADD_ADDITIONAL_URL",1578                          payload: { id: request().entryId, url: request().url },1579                        });1580                        await chrome.storage.session.remove("pendingRememberSite");1581                        setPendingRememberSite(null);1582                      }}1583                    >1584                      Add1585                    </button>1586                    <button1587                      class="peach-pro-notice-close"1588                      onClick={async () => {1589                        await chrome.storage.session.remove("pendingRememberSite");1590                        setPendingRememberSite(null);1591                      }}1592                      aria-label="Dismiss"1593                    >1594                      ✕1595                    </button>1596                  </div>1597                );1598              }}1599            </Show>16001601            <div class="peach-shell-body">1602              <div class="peach-shell-veil"></div>1603              <div class="peach-content-frame" data-content-phase={contentPhase()}>1604                <EntryView1605                  keyboardEnabled={view() === "entry"}1606                  entry={selectedEntry()}1607                  currentTabUrl={currentTabUrl()}1608                  entries={entries()}1609                  isPro={proStatus()}1610                  onDelete={handleDelete}1611                  onFieldSaved={() => void loadEntries()}1612                  onEscape={() => { setView("list"); }}1613                  onProGate={(feature) => {1614                    setUpgradeHighlight(feature);1615                    setSettingsInitialSection("license");1616                    setView("settings");1617                  }}1618                />1619              </div>16201621              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1622                <div class="peach-search-bar">1623                  <span class="peach-search-icon">1624                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1625                      <circle cx="5.5" cy="5.5" r="3.75" />1626                      <path d="M8.75 8.75L11.5 11.5" />1627                    </svg>1628                  </span>1629                  <input1630                    class="peach-search-input"1631                    placeholder="search vault..."1632                    autocomplete="off"1633                    aria-label="Search vault entries"1634                    onClick={openList}1635                    onFocus={openList}1636                    readOnly1637                  />1638                  <div class="peach-search-meta">1639                    <span class="peach-search-counter">1640                      {nonNoteEntries().length > 01641                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1642                        : "0 entries"}1643                    </span>1644                    <span class="peach-divider"></span>1645                    <button1646                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1647                      onClick={() => navigate(-1)}1648                      aria-label="Previous entry"1649                      disabled={nonNoteEntries().length === 0}1650                    >1651                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1652                        <path d="M5 1L1 5.5L5 10" />1653                      </svg>1654                    </button>1655                    <button1656                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1657                      onClick={() => navigate(1)}1658                      aria-label="Next entry"1659                      disabled={nonNoteEntries().length === 0}1660                    >1661                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1662                        <path d="M1 1L5 5.5L1 10" />1663                      </svg>1664                    </button>1665                  </div>1666                </div>1667              </section>1668            </div>16691670            {/* Rare device-trust alerts; normal sync changes are silent. */}1671            <Show when={alertGroups().length > 0}>1672              <div class="peach-sync-alerts">1673                <For each={alertGroups()}>1674                  {([type, group]) => {1675                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1676                    return (1677                      <div class="peach-sync-alert">1678                        <Show when={group.length > 1}>1679                          <button1680                            class="peach-sync-alert-flip"1681                            type="button"1682                            aria-label="Previous"1683                            onClick={() => flipAlert(type, -1)}1684                          >‹</button>1685                        </Show>1686                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1687                        <Show when={group.length > 1}>1688                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1689                          <button1690                            class="peach-sync-alert-flip"1691                            type="button"1692                            aria-label="Next"1693                            onClick={() => flipAlert(type, 1)}1694                          >›</button>1695                        </Show>1696                        <button1697                          class="peach-sync-alert-dismiss"1698                          type="button"1699                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1700                          onClick={() => void dismissAlertGroup(type as SyncAlert["type"])}1701                        >×</button>1702                      </div>1703                    );1704                  }}1705                </For>1706              </div>1707            </Show>17081709            <Show when={view() === "list"}>1710              <VaultView1711                entries={entries()}1712                selectedEntryId={selectedEntry()?.id}1713                currentTabDomain={currentTabDomain()}1714                sortOrder={sortOrder()}1715                searchSeed={listSearchSeed()}1716                searchSeedNonce={listSearchSeedNonce()}1717                onSelectEntry={handleSelectEntry}1718                onSortOrderChange={setSortOrder}1719                onAdd={handleAdd}1720                onClose={() => setView("entry")}1721                onOpenTrash={() => setView("trash")}1722                onDeleteMany={handleDeleteMany}1723              />1724            </Show>1725            <Show when={view() === "settings" || settingsExiting()}>1726              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1727                <SettingsView1728                  entriesCount={entries().length}1729                  breachMonitoring={breachMonitoring()}1730                  lockOnClose={lockOnClose()}1731                  autoLockMinutes={autoLockMinutes()}1732                  trashRetentionDays={trashRetentionDays()}1733                  lockedSyncRequiresUnlock={lockedSyncRequiresUnlock()}1734                  theme={theme()}1735                  accentColor={accentColor()}1736                  textSize={textSize()}1737                  reduceMotion={reduceMotion()}1738                  isPro={proStatus()}1739                  initialSection={settingsInitialSection()}1740                  upgradeHighlight={upgradeHighlight()}1741                  isExiting={settingsExiting()}1742                  onBreachMonitoringChange={applyBreachMonitoring}1743                  onLockOnCloseChange={applyLockOnClose}1744                  onLockedSyncRequiresUnlockChange={applyLockedSyncRequiresUnlock}1745                  onAutoLockMinutesChange={applyAutoLockMinutes}1746                  onTrashRetentionChange={applyTrashRetention}1747                  onThemeChange={applyTheme}1748                  onAccentChange={applyAccentColor}1749                  onTextSizeChange={applyTextSize}1750                  onReduceMotionChange={applyReduceMotion}1751                  shortcuts={shortcutBindings()}1752                  onShortcutsChange={applyShortcuts}1753                  onLicenseChange={async () => {1754                    // After activation/deactivation: refresh Pro status,1755                    // re-load entries (defensive — signal state can drift if1756                    // the SW briefly restarts during the verify+save round-trip),1757                    // and replay the Pro celebration if this is the first time1758                    // a valid Pro license is seen on this device.1759                    await refreshProStatus();1760                    void loadEntries();1761                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1762                    if ((should as { ok: boolean; data?: boolean }).data === true) {1763                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1764                      setView("pro-celebration");1765                      window.setTimeout(() => setView("settings"), 2500);1766                    }1767                  }}1768                  onBack={() => {1769                    setSettingsExiting(true);1770                    window.setTimeout(() => {1771                      setSettingsExiting(false);1772                      setSettingsInitialSection(null);1773                      setUpgradeHighlight(null);1774                      handleBack();1775                    }, 200);1776                  }}1777                  onImport={() => setView("import")}1778                  onExport={() => setView("export")}1779                  onBreachCheckDone={loadEntries}1780                  onOpenHealth={openHealth}1781                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1782                  onOpenFileImport={handleOpenFileImport}1783                  onOpenPanic={() => setView("panic")}1784                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1785                  onOpenCodexRestore={() => setView("codex-restore")}1786                  onCardChange={setSettingsActiveCard}1787                  onProGate={(feature) => {1788                    setUpgradeHighlight(feature);1789                    setSettingsInitialSection("license");1790                  }}1791                />1792              </Suspense>1793            </Show>1794            <Show when={view() === "codex-generate"}>1795              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1796                <CodexGenerateView1797                  isPro={proStatus()}1798                  onBack={() => setView("settings")}1799                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1800                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1801                  onVaultLocked={() => handleLock()}1802                />1803              </Suspense>1804            </Show>1805            <Show when={view() === "codex-restore"}>1806              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1807                <CodexRestoreView1808                  onBack={() => setView("lock")}1809                  onRestoreSuccess={async () => {1810                    // After restore the vault is unlocked; refresh entries1811                    // and route to the main vault list. handleUnlock is the1812                    // canonical post-unlock setup path.1813                    await handleUnlock();1814                  }}1815                />1816              </Suspense>1817            </Show>1818            <Show when={view() === "pair-device"}>1819              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1820                <PairDeviceView1821                  isPro={proStatus()}1822                  onProChanged={() => { void refreshProStatus(); }}1823                  onBack={() => setView("settings")}1824                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1825                />1826              </Suspense>1827            </Show>1828            <Show when={view() === "add"}>1829              <AddView1830                entry={editEntry()}1831                entries={entries()}1832                onBack={handleBack}1833                onSave={handleSave}1834              />1835            </Show>1836            <Show when={view() === "import"}>1837              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1838                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1839              </Suspense>1840            </Show>1841            <Show when={view() === "export"}>1842              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1843                <ExportView onBack={handleExportBack} />1844              </Suspense>1845            </Show>1846            <Show when={view() === "panic"}>1847              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1848                <PanicView1849                  onCancel={() => setView("settings")}1850                  onOpenExport={() => {1851                    setReturnToPanic(true);1852                    setView("export");1853                  }}1854                  onDestroyed={async () => {1855                    // Fresh onboarding start after a destroy — don't let the1856                    // resume markers land the user mid-carousel.1857                    setOnboardingCardAtExit(0);1858                    void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1859                    clearOnboardingExit();1860                    setEntries([]);1861                    setSelectedEntry(null);1862                    setEditEntry(undefined);1863                    setHasVault(false);1864                    setOnboarded(false);1865                    setProStatus(false);1866                    setPendingPasskey(null);1867                    setUpgradeHighlight(null);1868                    setSettingsInitialSection(null);1869                    setPendingProNotice(null);1870                    setPendingCelebration(false);1871                    setReturnToPanic(false);1872                    setContentPhase("idle");1873                    setView("lock");1874                  }}1875                />1876              </Suspense>1877            </Show>1878            {/* Health stays mounted while editing an entry from it so1879                computeReused() doesn't rerun on every cancel/back. */}1880            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1881              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1882                <HealthView1883                  entries={entries()}1884                  isPro={proStatus()}1885                  onFixEntry={handleFixEntry}1886                  onBack={() => setView("settings")}1887                  onRefresh={loadEntries}1888                  hidden={view() !== "health"}1889                />1890              </Suspense>1891            </Show>1892            <Show when={view() === "trash"}>1893              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1894                <TrashView1895                  onBack={() => setView("list")}1896                  onRestored={() => void loadEntries()}1897                />1898              </Suspense>1899            </Show>1900            <Show when={showNotes()}>1901              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1902                <NotesMode1903                  notes={entries().filter((e) => e.type === "note")}1904                  initialNoteId={openNoteId()}1905                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1906                  onNoteListChanged={() => void loadEntries()}1907                />1908              </div>1909            </Show>1910            <Show when={restoreView() === "file"}>1911              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1912                <ImportView1913                  mode="onboarding"1914                  replacesExistingVault={true}1915                  onBack={() => setRestoreView(null)}1916                  onImport={async () => {1917                    setRestoreView(null);1918                    await handleUnlock();1919                  }}1920                />1921              </Suspense>1922            </Show>1923            </section>1924            </Show>1925          </Show>1926        </Show>1927      </Show>1928      <Show when={showShortcutsHelp()}>1929        <ShortcutsHelpOverlay1930          bindings={shortcutBindings()}1931          onClose={() => setShowShortcutsHelp(false)}1932        />1933      </Show>1934    </div>1935  );1936}19371938function ShortcutsHelpOverlay(props: {1939  bindings: Record<ShortcutAction, Keybinding>;1940  onClose: () => void;1941}) {1942  return (1943    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1944      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1945        <div class="peach-shortcuts-help-head">1946          <h3>Keyboard shortcuts</h3>1947          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1948        </div>1949        <div class="peach-shortcuts-help-body">1950          <p class="peach-settings-sub-label">ENTRY VIEW</p>1951          <ul>1952            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1953              <li>1954                <span>{d.label}</span>1955                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1956              </li>1957            ))}1958          </ul>1959          <p class="peach-settings-sub-label">ANYWHERE</p>1960          <ul>1961            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1962              <li>1963                <span>{d.label}</span>1964                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1965              </li>1966            ))}1967          </ul>1968        </div>1969      </div>1970    </div>1971  );1972}