App.tsx

82.4 KB · raw

1import { createEffect, createMemo, createSignal, For, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageRemove, storageSet } from "../shared/storage";4import { sendMessage } from "../shared/bridge";5import { ACCENT_COLORS } from "../shared/types";6import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";7import { isPasskeyOnly } from "../shared/types";8import {9  hasCompletedInitialSync,10  INITIAL_SYNC_PENDING_DEVICE_KEY,11  type InitialSyncDevice,12} from "../shared/initial-sync";13import { LockView } from "./views/Lock";14import { Onboarding } from "./views/Onboarding";15import { NotesMode } from "./views/NotesMode";16import { ProCelebration } from "./views/ProCelebration";17import { InitialSyncView } from "./views/InitialSyncView";18import { VaultView, type SortOrder } from "./views/Vault";19import { EntryView } from "./views/Entry";20import { AddView } from "./views/Add";21import { PeachWordmark } from "./components/PeachMark";22import { PasskeyApprovalView } from "./views/PasskeyApproval";23import { extractDomain } from "../shared/domain";24import {25  syncIndicator,26  syncIndicatorLabel,27  type SyncOutcomeSummary,28} from "../shared/sync-outcome";29import { popupCopy } from "./copy";30import {31  DEFAULT_BINDINGS,32  formatKeybinding,33  getActiveBindings,34  matchKeybinding,35  SHORTCUT_DESCRIPTORS,36  type Keybinding,37  type ShortcutAction,38} from "../shared/shortcuts";39import { generateTOTP } from "../crypto/totp";40import { isNativePlatform, nativePlugin } from "../shared/native";4142export { sendMessage } from "../shared/bridge";4344const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));45const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));46const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));47const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));48const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));49const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));50const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));51const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));52const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));53const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));5455type View =56  | "lock"57  | "pro-celebration"58  | "entry"59  | "list"60  | "add"61  | "settings"62  | "pair-device"63  | "import"64  | "export"65  | "health"66  | "trash"67  | "panic"68  | "adopting"69  | "initial-sync"70  | "codex-generate"71  | "codex-restore";72type BootState = "loading" | "ready";7374const INITIAL_SYNC_POLL_MS = 500;75const INITIAL_SYNC_SLOW_MS = 15_000;7677const canarySuppressMap = new Map<string, boolean>();78let shellRingAnimation: Animation | null = null;7980export function isCanarySuppressed(entryId: string): boolean {81  return canarySuppressMap.get(entryId) ?? false;82}8384export function setCanarySuppressed(entryId: string, suppressed: boolean): void {85  canarySuppressMap.set(entryId, suppressed);86}8788export function clearCanarySuppressions(): void {89  canarySuppressMap.clear();90}9192export function triggerRing() {93  const shell = document.getElementById("hd-shell");94  if (!shell) return;9596  shellRingAnimation?.cancel();97  shell.dataset.glowing = "true";98  const animation = shell.animate(99    [100      { offset: 0, boxShadow: "var(--copy-shadow)" },101      {102        offset: 0.3,103        boxShadow:104          "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)",105      },106      { offset: 1, boxShadow: "var(--copy-shadow)" },107    ],108    {109      duration: 720,110      easing: "cubic-bezier(0.4, 0, 0.2, 1)",111      fill: "none",112    }113  );114  shellRingAnimation = animation;115  const clearGlow = () => {116    if (shellRingAnimation !== animation) return;117    shellRingAnimation = null;118    delete shell.dataset.glowing;119  };120  animation.onfinish = clearGlow;121  animation.oncancel = clearGlow;122}123124125export function triggerPipPulse() {126  const pip = document.querySelector(".peach-status-pip, .pip");127  if (pip) {128    pip.classList.remove("pulse");129    void (pip as HTMLElement).offsetWidth;130    pip.classList.add("pulse");131  }132}133134const ENTRY_TRANSITION_SETTLE_MS = 135;135136export default function App() {137  const [bootState, setBootState] = createSignal<BootState>("loading");138  const [view, setView] = createSignal<View>("lock");139  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,140  // CSS transition takes over for snap animation).141  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);142  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(143    "enter"144  );145  const [contentTransitioning, setContentTransitioning] = createSignal(false);146  const [hasVault, setHasVault] = createSignal(false);147  const [onboarded, setOnboarded] = createSignal(true);148  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);149  const [entries, setEntries] = createSignal<VaultEntry[]>([]);150  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);151  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);152153  // Rare device-trust alerts stay visible; routine entry sync is silent.154  interface SyncAlert {155    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";156    entryId: string;157    entryTitle: string;158    deviceName: string;159    timestamp: number;160  }161  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);162  async function loadSyncAlerts() {163    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {164      ok: boolean;165      data?: SyncAlert[];166    };167    if (r.ok && (r.data?.length ?? 0) > 0) {168      setSyncAlerts(r.data ?? []);169      // Acknowledge so a crash between read and render doesn't lose them —170      // they remain on screen until the user dismisses each.171      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });172    }173  }174  function dismissSyncAlert(index: number) {175    setSyncAlerts((arr) => arr.filter((_, i) => i !== index));176  }177  function syncAlertText(a: SyncAlert): string {178    if (a.type === "DEVICE_REVOKED") {179      return `${a.deviceName} revoked a paired device — review your devices in Settings`;180    }181    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;182  }183  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");184  const [theme, setTheme] = createSignal<"dark" | "light">("dark");185  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");186  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);187  const [lockOnClose, setLockOnClose] = createSignal(true);188  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);189  const [breachMonitoring, setBreachMonitoring] = createSignal(true);190  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);191  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);192  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);193  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);194  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);195  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");196  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");197  // Cached Pro status — synchronous for render paths. Background's198  // GET_LICENSE is async, but render-time reads of isPro() must not block.199  // Refreshed at boot, after activate/deactivate, and whenever the popup200  // re-opens onto a stored license that has changed via another window.201  const [proStatus, setProStatus] = createSignal(false);202  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);203  // When the sync card's pairing button opens the pairing view, deep-link204  // straight into that pairing path instead of the rest screen.205  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");206  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);207  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");208  const [listSearchSeed, setListSearchSeed] = createSignal("");209  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);210  const [pendingCelebration, setPendingCelebration] = createSignal(false);211  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);212  // True while Panic Step 1 has bounced the user out to Export. When Export's213  // onBack fires we return to Panic instead of Settings so the user keeps the214  // destruction context they came from.215  const [returnToPanic, setReturnToPanic] = createSignal(false);216  // The view to return to when the add/edit view is dismissed. Normally "entry"217  // but "health" when the user arrives via the fix-entry path from Vault Health.218  const [editBackView, setEditBackView] = createSignal<View>("entry");219  const [settingsExiting, setSettingsExiting] = createSignal(false);220  const [showNotes, setShowNotes] = createSignal(false);221  // Topbar sync affordance. Always present: gating it on having a paired device222  // meant it never appeared for the person trying to set pairing up, which is223  // exactly when you reach for it.224  const [syncBusy, setSyncBusy] = createSignal(false);225  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);226  // The indicator light + its spoken-word equivalent. Colour alone is not the227  // signal; the title/aria-label always carries the same claim in English.228  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});229  const [pairedCount, setPairedCount] = createSignal(0);230  const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);231  const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);232  let initialSyncWaitGeneration = 0;233  const syncLight = () =>234    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());235  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());236  async function loadSyncIndicator() {237    const [stateRes, devicesRes] = await Promise.all([238      sendMessage({ type: "GET_SYNC_STATE" }),239      sendMessage({ type: "LIST_PAIRED_DEVICES" }),240    ]);241    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };242    if (s.ok && s.data) setSyncSummary(s.data);243    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };244    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);245  }246247  interface InitialSyncPairedDevice extends InitialSyncDevice {248    pairedAt?: number;249  }250251  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {252    const response = (await sendMessage({253      type: "LIST_PAIRED_DEVICES",254    })) as {255      ok: boolean;256      data?: { devices?: InitialSyncPairedDevice[] };257    };258    return response.ok ? response.data?.devices ?? [] : [];259  }260261  async function resolveInitialSyncDeviceId(): Promise<string | null> {262    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(263      () => null,264    );265    const devices = await listInitialSyncDevices().catch(() => []);266    if (stored && devices.some((device) => device.deviceId === stored)) {267      return stored;268    }269270    // Fresh adoption has exactly one direct source, but choosing the newest row271    // also repairs the marker if storage failed after the pair itself committed.272    const newest = [...devices].sort(273      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),274    )[0];275    if (!newest) return stored;276    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(277      () => undefined,278    );279    return newest.deviceId;280  }281282  async function finishInitialSync(generation: number): Promise<void> {283    if (generation !== initialSyncWaitGeneration) return;284    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);285    setInitialSyncDeviceId(null);286    setInitialSyncSlow(false);287    await refreshProStatus();288289    // A license transferred during pairing intentionally leaves the one-shot290    // celebration pending. Consume it only now: sync readiness → celebration291    // → populated vault, never celebration → temporarily empty vault.292    const celebration = (await sendMessage({293      type: "SHOULD_PLAY_CELEBRATION",294    })) as { ok: boolean; data?: boolean };295    const shouldCelebrate = celebration.ok && celebration.data === true;296    if (shouldCelebrate) {297      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });298    }299300    const opened = await openVault(undefined, shouldCelebrate);301    if (!opened || generation !== initialSyncWaitGeneration) return;302    if (shouldCelebrate) {303      setView("pro-celebration");304      window.setTimeout(() => {305        if (generation === initialSyncWaitGeneration) setView("entry");306      }, 2500);307    }308  }309310  async function beginInitialSyncWait(deviceId: string): Promise<void> {311    const generation = ++initialSyncWaitGeneration;312    setInitialSyncDeviceId(deviceId);313    setInitialSyncSlow(false);314    setView("initial-sync");315    const startedAt = Date.now();316317    // Best effort: the pairing write already wakes the mesh listener, while318    // this trigger covers the key-order case where this receiver is the dialer.319    void sendMessage({320      type: "TRIGGER_SYNC",321      payload: { reason: "foreground" },322    }).catch(() => undefined);323324    while (325      generation === initialSyncWaitGeneration &&326      view() === "initial-sync"327    ) {328      try {329        const devices = await listInitialSyncDevices();330        if (hasCompletedInitialSync(devices, deviceId)) {331          await finishInitialSync(generation);332          return;333        }334      } catch {335        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.336      }337      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {338        setInitialSyncSlow(true);339      }340      await new Promise((resolve) =>341        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),342      );343    }344  }345346  async function retryInitialSync(): Promise<void> {347    const deviceId =348      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());349    if (deviceId) {350      await beginInitialSyncWait(deviceId);351    } else {352      setInitialSyncSlow(true);353    }354  }355356  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);357  // Set on popup boot when peach_recovery_pending flag is found in session358  // storage — instructs LockView to skip the unlock UI and open the recovery359  // words confirmation surface instead. Cleared via handleUnlock once the360  // user has typed the 3 confirmation words.361  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);362363  let contentPhaseTimer: number | undefined;364  // Set when the popup was opened from the inline "Open Peach to unlock" button.365  // handleUnlock() closes the popup after unlock so the user returns to the page.366  let openedForInlineUnlock = false;367368  onCleanup(() => {369    initialSyncWaitGeneration += 1;370  });371372  function applyAccent(name: AccentColorName) {373    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;374    const hex = color.hex;375    document.documentElement.style.setProperty("--peach-accent", hex);376    // Ambient surface variables — derived from the accent so surfaces shift377    // subtly toward the accent hue rather than staying fixed warm-brown.378    document.documentElement.style.setProperty("--peach-glow", hex + "2A");379    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");380    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");381  }382383  createEffect(() => {384    applyAccent(accentColor());385  });386387  createEffect(() => {388    document.documentElement.classList.toggle("light", theme() === "light");389    document.body.classList.toggle("light", theme() === "light");390  });391392  createEffect(() => {393    document.documentElement.setAttribute("data-text-size", textSize());394  });395396  createEffect(() => {397    if (reduceMotion()) {398      document.documentElement.setAttribute("data-motion", "reduce");399    } else {400      document.documentElement.removeAttribute("data-motion");401    }402  });403404  // Notes are not a destination of the Entry view; selecting a note opens the405  // notes surface instead (handleSelectEntry). Anything that walks or counts406  // the Entry view's neighbours (counter, prev/next, index) must use this407  // filtered list, otherwise the user can arrow into a note and is stuck —408  // the Entry view can't render a note and the prev/next buttons stop moving.409  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));410411  const selectedIndex = createMemo(() => {412    const currentId = selectedEntry()?.id;413    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;414    return nonNoteEntries().findIndex((entry) => entry.id === currentId);415  });416417  async function applyAccentColor(name: AccentColorName) {418    applyAccent(name);419    setAccentColor(name);420    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });421  }422423  async function applyTheme(t: "dark" | "light") {424    setTheme(t);425    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });426  }427428  async function applyTextSize(size: "small" | "medium" | "large") {429    setTextSize(size);430    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });431  }432433  async function applyReduceMotion(enabled: boolean) {434    setReduceMotion(enabled);435    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });436  }437438  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload439  // small and lets future default updates land for actions the user hasn't440  // touched. Settings sends us the full active map; we filter and store.441  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {442    setShortcutBindings(active);443    const overrides: Record<string, Keybinding> = {};444    for (const action of Object.keys(active) as ShortcutAction[]) {445      const a = active[action];446      const d = DEFAULT_BINDINGS[action];447      const same = a.key === d.key448        && Boolean(a.ctrl)  === Boolean(d.ctrl)449        && Boolean(a.meta)  === Boolean(d.meta)450        && Boolean(a.shift) === Boolean(d.shift)451        && Boolean(a.alt)   === Boolean(d.alt);452      if (!same) overrides[action] = a;453    }454    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });455  }456457  async function applyLockOnClose(enabled: boolean) {458    setLockOnClose(enabled);459    await sendMessage({460      type: "UPDATE_SETTINGS",461      payload: { lockOnClose: enabled },462    });463  }464465  async function applyAutoLockMinutes(minutes: number) {466    setAutoLockMinutes(minutes);467    await sendMessage({468      type: "UPDATE_SETTINGS",469      payload: { autoLockMinutes: minutes },470    });471  }472473  async function applyBreachMonitoring(enabled: boolean) {474    setBreachMonitoring(enabled);475    await sendMessage({476      type: "UPDATE_SETTINGS",477      payload: { breachMonitoring: enabled },478    });479  }480481  onMount(async () => {482    // Resolve the active tab in parallel with the unlock/has-vault queries —483    // openVault()'s smart selection picks the entry matching currentTabDomain,484    // so it must be populated before openVault runs. Previously refreshCurrentTab485    // ran after openVault, leaving popups that booted already-unlocked falling486    // back to loadedEntries[0] instead of the domain match.487    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([488      sendMessage({ type: "IS_UNLOCKED" }),489      sendMessage({ type: "HAS_VAULT" }),490      refreshCurrentTab(),491      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),492    ]);493    const unlocked = Boolean(494      (unlockResponse as { ok: boolean; data?: boolean }).data495    );496    const vaultExists = Boolean(497      (vaultResponse as { ok: boolean; data?: boolean }).data498    );499    const shouldCelebrate = Boolean(500      (celebrationResponse as { ok: boolean; data?: boolean }).data501    );502    setHasVault(vaultExists);503    // Onboarding gate — show once on first install, never again. Existing504    // users (vaultExists) are auto-marked onboarded so they skip the flow505    // even on the very first popup open after this feature ships.506    try {507      const onboarded = await storageGet("peach_onboarded");508      const seen = onboarded === "true";509      if (vaultExists && !seen) {510        await storageSet("peach_onboarded", "true");511        setOnboarded(true);512      } else {513        setOnboarded(seen);514      }515    } catch {516      // storage unavailable — default to onboarded so we never block boot517      setOnboarded(true);518    }519    await Promise.all([restoreSettings(), refreshProStatus()]);520521    const pendingInitialSyncMarker =522      unlocked && vaultExists523        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)524        : null;525    const pendingInitialSyncDeviceId = pendingInitialSyncMarker526      ? await resolveInitialSyncDeviceId()527      : null;528529    // Mark played before any animation so a crash mid-sequence never replays530    // it. A newly adopted receiver deliberately defers this until its first531    // real sync finishes, preserving initial sync → celebration → vault.532    if (shouldCelebrate && !pendingInitialSyncDeviceId) {533      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });534    }535536    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome537    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.538    if (unlocked && vaultExists) {539      void sendMessage({540        type: "TRIGGER_SYNC",541        payload: { reason: "foreground" },542      });543      void loadSyncIndicator();544      // Rare device-trust alerts only; routine entry sync stays quiet.545      void loadSyncAlerts();546    }547548    // If the user created a vault but hasn't yet confirmed their recovery549    // words, route back to the recovery-words screen instead of opening the550    // entries view. The flag lives in chrome.storage.local so it survives551    // both popup close (SW suppresses lock-on-close) and full browser552    // restart (handleUnlock checks the same flag after a fresh password553    // unlock). Cleared when confirmation succeeds.554    let recoveryPending = false;555    try {556      const out = await chrome.storage.local?.get("peach_recovery_pending");557      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";558    } catch { /* best-effort */ }559560    // If this popup was opened from the inline "Open Peach to unlock" button,561    // the background set a session flag. Read and clear it so handleUnlock()562    // can close the popup after unlock and return the user to the page.563    if (chrome.storage.session) {564      try {565        const s = await chrome.storage.session.get("peach_inline_unlock");566        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {567          openedForInlineUnlock = true;568          await chrome.storage.session.remove("peach_inline_unlock");569        }570      } catch { /* best-effort */ }571    }572573    // Native: closing the app before recovery-words confirmation means the574    // user didn't finish vault creation. Throw the partial vault away and575    // restart onboarding rather than asking them to unlock a vault they576    // never finished creating. Desktop keeps the existing "unlock to577    // resume" flow because closing the popup there is much more casual.578    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {579      try {580        await chrome.storage.local?.remove([581          "peach_vault_a",582          "peach_vault_b",583          "peach_recovery_pending",584          "peach_onboarded",585          "peach_vault_history",586        ]);587      } catch { /* best-effort */ }588      setHasVault(false);589      setOnboarded(false);590      setView("lock");591      setBootState("ready");592      return;593    }594595    if (recoveryPending && unlocked) {596      // forceRecoveryWords overrides LockView's hasVault gate so the597      // recovery surface renders even though the vault now exists.598      setForceRecoveryWords(true);599      setView("lock");600    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {601      void beginInitialSyncWait(pendingInitialSyncDeviceId);602    } else if (unlocked && vaultExists) {603      await openVault(undefined, shouldCelebrate);604      if (shouldCelebrate) {605        setView("pro-celebration");606        window.setTimeout(() => setView("entry"), 2500);607      }608    } else if (shouldCelebrate) {609      setPendingCelebration(true);610    }611612    await refreshPendingPasskey();613614    // Track tab changes so smart sort stays current615    const handleTabActivated = () => { void refreshCurrentTab(); };616    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {617      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();618    };619    try {620      chrome.tabs.onActivated.addListener(handleTabActivated);621      chrome.tabs.onUpdated.addListener(handleTabUpdated);622      onCleanup(() => {623        chrome.tabs.onActivated.removeListener(handleTabActivated);624        chrome.tabs.onUpdated.removeListener(handleTabUpdated);625      });626    } catch {627      // tabs permission may not be available in all contexts628    }629630    setBootState("ready");631632    // Deep-link: ?codex=pdf opens a detached window straight into the633    // Codex restore flow with auto-picked PDF. The action popup can't host634    // a file dialog without dismissing itself, so this is the only way the635    // PDF import path survives. See CodexRestoreView.openPdfPicker().636    try {637      const route = new URLSearchParams(window.location.search).get("codex");638      if (route === "pdf" || route === "restore") {639        setView("codex-restore");640      }641    } catch {642      // location.search unavailable — ignore.643    }644645    // Check for pending session-storage notices from the background.646    if (chrome.storage.session) {647      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as648        Record<string, { feature?: string } | undefined>;649      if (session.pendingProGate?.feature) {650        await chrome.storage.session.remove("pendingProGate");651        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);652        setSettingsInitialSection("license");653        setView("settings");654      } else if (session.pendingProNotice?.feature) {655        await chrome.storage.session.remove("pendingProNotice");656        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });657      }658    }659660    // Warm the lazy-module cache so the Suspense fallback never shows for661    // locally-bundled extension views. Without this, the first navigation to662    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which663    // covers the shell and absorbs clicks on the header.664    void Promise.all([665      import("./views/Settings").catch(() => {}),666      import("./views/Import").catch(() => {}),667      import("./views/Export").catch(() => {}),668      import("./views/Health").catch(() => {}),669      import("./views/TrashView").catch(() => {}),670    ]);671672    // Lock-on-close via a persistent port. sendMessage in pagehide is673    // unreliable — the popup context tears down before the message lands.674    // The SW's onConnect listener locks when this port disconnects.675    let popupPort: chrome.runtime.Port | null = null;676    try {677      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect678      // listener accepts the "popup-" prefix; the random suffix is defence in679      // depth against a port named exactly "popup" from anything but our popup.680      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });681    } catch { /* extension context invalidated — ignore */ }682    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });683684    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only685    // reliable signal is appStateChange — setTimeout is killed when the OS686    // backgrounds the app. We measure elapsed background time on resume.687    if (isNativePlatform()) {688      let backgroundedAt: number | null = null;689690      const CapApp = nativePlugin<{691        addListener: (692          ev: string,693          cb: (s: { isActive: boolean }) => void,694        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };695      }>("App");696      if (CapApp?.addListener) {697        const sub = CapApp.addListener(698          "appStateChange",699          ({ isActive }: { isActive: boolean }) => {700            if (!isActive) {701              backgroundedAt = Date.now();702              return;703            }704            if (backgroundedAt !== null && autoLockMinutes() > 0) {705              const elapsed = Date.now() - backgroundedAt;706              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();707            }708            backgroundedAt = null;709          }710        );711        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.712        onCleanup(() => {713          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});714        });715      }716717      // L12/COR-011: foreground idle autolock. appStateChange only fires when718      // the OS backgrounds the app — if the user idles with the screen on,719      // chrome.alarms is no-op'd in Capacitor so the vault would stay open720      // indefinitely. Poll every 30s and lock if elapsed since last user721      // interaction exceeds autoLockMinutes.722      let lastUserActivityAt = Date.now();723      const bumpActivity = () => { lastUserActivityAt = Date.now(); };724      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;725      for (const ev of ACTIVITY_EVENTS) {726        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });727      }728      const idleLockInterval = setInterval(() => {729        const minutes = autoLockMinutes();730        if (!minutes || minutes <= 0) return;731        const elapsed = Date.now() - lastUserActivityAt;732        if (elapsed >= minutes * 60_000) {733          lastUserActivityAt = Date.now();734          handleHeaderLock();735        }736      }, 30_000);737      onCleanup(() => {738        clearInterval(idleLockInterval);739        for (const ev of ACTIVITY_EVENTS) {740          document.removeEventListener(ev, bumpActivity, { capture: true });741        }742      });743744      // The retired native peer-discovery trigger went with the old Capacitor745      // pairing plugin. Reconnection is address-cache first, subnet probe second746      // (sync-runner.ts); relocating a peer that changed networks is an747      // Android-side discovery concern now.748      if (isNativePlatform()) {749        // Android runs the background/sync dispatcher in-process with the750        // popup, so the production runner has to be registered from the751        // UI bootstrap path instead of the MV3 service-worker entry.752        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>753          import("../background/sync-runner").then(({ productionSyncRunner }) => {754            setSyncRunner(productionSyncRunner);755            void hydratePersistedSyncState();756          })757        );758      }759    }760761    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale762    // entries instead of waiting for the next GET_ENTRIES round-trip.763    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {764      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();765      if (msg?.type === "SYNC_STATE_CHANGED") {766        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);767      }768      if (msg?.type === "PRO_GATE_TRIGGERED") {769        setUpgradeHighlight(msg.payload?.feature ?? null);770        setSettingsInitialSection("license");771        setView("settings");772      }773    };774    chrome.runtime.onMessage.addListener(handleRuntimeMessage);775    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));776777    // Android hardware/gesture back. MainActivity fires peach:back; the popup778    // decides what "back" means per surface. Lock+no-vault is the common case779    // — return to onboarding rather than letting the OS dismiss the activity.780    const handlePeachBack = () => {781      // Notes mode captures back first782      if (showNotes()) {783        setShowNotes(false);784        setOpenNoteId(undefined);785        return;786      }787      const v = view();788      if (v === "lock" && !hasVault() && onboarded()) {789        setOnboarded(false);790        return;791      }792      if (v === "list") { setView("entry"); return; }793      if (v === "settings") {794        window.dispatchEvent(new Event("peach:settings-back"));795        return;796      }797      if (v === "import" || v === "health") { setView("settings"); return; }798      if (v === "export") { handleExportBack(); return; }799      if (v === "add") { handleBack(); return; }800      if (v === "pair-device") { setView("settings"); return; }801    };802    window.addEventListener("peach:back", handlePeachBack);803    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));804805    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that806    // peeks from the bottom (search bar handle visible) and drags up to fill807    // the screen. dragOffset is the LIVE finger offset during a drag, in px,808    // 0 when no drag in progress. The wrapper element computes transform =809    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.810    if (isNativePlatform()) {811      let touchStartY = 0;812      let touchStartX = 0;813      let lastY = 0;814      let lastT = 0;815      let dragging = false;816      let captured = false;817      const HORIZONTAL_TOLERANCE = 16;818      const ACTIVATION_DY = 8;819      const PEEK_PX = 60;820821      const onTouchStart = (e: TouchEvent) => {822        const t = e.touches[0];823        if (!t) return;824        const v = view();825        if (v !== "entry" && v !== "list") return;826        // Entry view: only intercept drags starting in the bottom 40%.827        // List view: intercept drags starting in the top 35% (the search/handle row).828        const inBand = v === "entry"829          ? t.clientY > window.innerHeight * 0.6830          : t.clientY < window.innerHeight * 0.35;831        if (!inBand) return;832        touchStartY = lastY = t.clientY;833        touchStartX = t.clientX;834        lastT = e.timeStamp;835        dragging = true;836        captured = false;837      };838839      const onTouchMove = (e: TouchEvent) => {840        if (!dragging) return;841        const t = e.touches[0];842        if (!t) return;843        const dy = t.clientY - touchStartY;844        const dx = Math.abs(t.clientX - touchStartX);845846        if (!captured) {847          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {848            // Looks like a horizontal swipe — release.849            dragging = false;850            return;851          }852          if (Math.abs(dy) < ACTIVATION_DY) return;853          captured = true;854        }855856        // Translate the sheet by dy from its rest (peek) position. Peek is857        // (viewport height - PEEK_PX). Open is 0.858        const v = view();859        const restClosed = window.innerHeight - PEEK_PX;860        const baseTranslate = v === "list" ? 0 : restClosed;861        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));862        setSheetTranslate(next);863        lastY = t.clientY;864        lastT = e.timeStamp;865      };866867      const onTouchEnd = (e: TouchEvent) => {868        if (!dragging) { return; }869        const t = e.changedTouches[0];870        const elapsed = Math.max(1, e.timeStamp - lastT);871        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms872        const wasCaptured = captured;873        dragging = false;874        captured = false;875        const v = view();876877        if (!wasCaptured) {878          // Tap in the peek strip while in entry view → open the vault list.879          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");880          setSheetTranslate(null);881          return;882        }883884        const restClosed = window.innerHeight - PEEK_PX;885        const current = sheetTranslate() ?? restClosed;886887        // Snap rules:888        //   - Strong upward velocity → open889        //   - Strong downward velocity → close890        //   - Otherwise snap to whichever rest is closer891        let nextOpen: boolean;892        if (velocity < -0.05) nextOpen = true;893        else if (velocity > 0.05) nextOpen = false;894        else nextOpen = current < restClosed * 0.5;895896        if (nextOpen && v !== "list") setView("list");897        if (!nextOpen && v !== "entry") setView("entry");898        // Release the live offset so CSS transition handles the snap.899        setSheetTranslate(null);900      };901902      document.addEventListener("touchstart", onTouchStart, { passive: true });903      document.addEventListener("touchmove",  onTouchMove,  { passive: true });904      document.addEventListener("touchend",   onTouchEnd,   { passive: true });905      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });906      onCleanup(() => {907        document.removeEventListener("touchstart", onTouchStart);908        document.removeEventListener("touchmove",  onTouchMove);909        document.removeEventListener("touchend",   onTouchEnd);910      });911    }912913    // Action handlers — keyed by ShortcutAction. The dispatcher below tests914    // each binding against the event and runs the matching handler. New915    // shortcuts only need an entry here; the binding is data, not code.916    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {917      copy_password: () => {918        const entry = selectedEntry();919        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });920      },921      copy_username: () => {922        const entry = selectedEntry();923        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });924      },925      copy_totp: () => {926        const entry = selectedEntry();927        if (!entry?.totp) return;928        try {929          const { code } = generateTOTP(entry.totp);930          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });931        } catch { /* invalid TOTP secret — silent */ }932      },933      new_entry: () => handleAdd(),934      edit_entry: () => {935        const entry = selectedEntry();936        // Passkey-only entries have nothing user-editable in the Add view; the937        // passkey credential itself is opaque. Skip the edit action for them.938        if (!entry || isPasskeyOnly(entry)) return;939        setEditEntry(entry);940        setView("add");941      },942      delete_entry: () => {943        if (selectedEntry()) void handleDelete();944      },945      lock_vault: () => { void handleHeaderLock(); },946      search: () => openList(),947      nav_prev: () => navigate(-1),948      nav_next: () => navigate(1),949      jump_vault: () => setView("entry"),950      jump_settings: () => setView("settings"),951      show_help: () => setShowShortcutsHelp(true),952    };953954    // Actions that are MEANINGFUL only on the entry-detail view. Outside955    // that scope the binding is dormant — pressing C while on Settings956    // does nothing rather than awkwardly copying from a now-stale entry.957    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([958      "copy_password", "copy_username", "copy_totp",959      "edit_entry", "delete_entry", "nav_prev", "nav_next",960    ]);961962    const handleGlobalKeydown = (e: KeyboardEvent) => {963      const v = view();964      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"965        || (e.target as HTMLElement)?.tagName === "TEXTAREA"966        || (e.target as HTMLElement)?.isContentEditable;967      const isPrintableSearchKey =968        e.key.length === 1 &&969        !e.ctrlKey &&970        !e.metaKey &&971        !e.altKey;972973      // No navigation shortcuts while the post-pairing readiness sequence or974      // Pro celebration owns the whole surface.975      if (v === "pro-celebration" || v === "initial-sync") return;976977      // Help dialog: Escape closes it; eat the keypress so it doesn't978      // also navigate away from the underlying view.979      if (showShortcutsHelp()) {980        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }981        return;982      }983984      // ── Escape — fixed binding (not user-customizable) ───────985      if (e.key === "Escape") {986        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }987        if (v === "list") { setView("entry"); return; }988        if (v === "settings" || v === "add") { handleBack(); return; }989        if (v === "import" || v === "health") { setView("settings"); return; }990        if (v === "export") { handleExportBack(); return; }991        if (v === "pair-device") { setView("settings"); return; }992      }993994      // Bindings-driven dispatch. Single-key letter bindings without995      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is996      // inside an input, so users can type into search/forms normally.997      const bindings = shortcutBindings();998      for (const action of Object.keys(bindings) as ShortcutAction[]) {999        const binding = bindings[action];1000        if (!matchKeybinding(e, binding)) continue;1001        // Single-key letter bindings need the input-focus guard. Bindings1002        // with any modifier are safe — Ctrl+L doesn't conflict with typing.1003        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;1004        if (!hasMod && binding.key.length === 1 && inInput) return;1005        if (ENTRY_SCOPED.has(action) && v !== "entry") return;1006        e.preventDefault();1007        SHORTCUT_HANDLERS[action]?.();1008        return;1009      }10101011      // Type-to-search: in entry view, any printable key not consumed by a1012      // shortcut above primes the list search seed and opens the list.1013      // Kept outside the bindings table because it's a behavior, not a1014      // discrete action — every printable character can trigger it.1015      if (v === "entry" && !inInput && isPrintableSearchKey) {1016        e.preventDefault();1017        primeListSearch(e.key);1018        return;1019      }1020    };1021    window.addEventListener("keydown", handleGlobalKeydown);1022    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));10231024    const handleStorageChanged = (1025      changes: Record<string, chrome.storage.StorageChange>,1026      areaName: string1027    ) => {1028      if (areaName !== "session") return;1029      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {1030        return;1031      }1032      void refreshPendingPasskey();1033    };1034    chrome.storage.onChanged.addListener(handleStorageChanged);1035    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));1036  });10371038  async function refreshCurrentTab() {1039    try {1040      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1041      const url = tab?.url ?? tab?.pendingUrl ?? "";1042      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");1043      // Skip extension/internal URLs — adding chrome://, about:, or1044      // chrome-extension:// to a vault entry is never what the user wants.1045      const isWebUrl = /^https?:\/\//i.test(url);1046      setCurrentTabUrl(isWebUrl ? url : "");1047    } catch {1048      setCurrentTabDomain("");1049      setCurrentTabUrl("");1050    }1051  }10521053  async function refreshPendingPasskey() {1054    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });1055    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);1056  }10571058  async function refreshProStatus() {1059    const res = await sendMessage({ type: "GET_LICENSE" });1060    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;1061    setProStatus(Boolean(data?.valid && data?.plan === "pro"));1062  }10631064  async function restoreSettings() {1065    const res = await sendMessage({ type: "GET_SETTINGS" });1066    const s = (res as { ok: boolean; data?: any }).data ?? {};1067    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {1068      setAccentColor(s.accentColor as AccentColorName);1069    }1070    setTheme(s.theme === "light" ? "light" : "dark");1071    if (s.textSize === "small" || s.textSize === "large") {1072      setTextSize(s.textSize);1073    } else {1074      setTextSize("medium");1075    }1076    setReduceMotion(s.reduceMotion === true);1077    setLockOnClose(s.lockOnClose !== false);1078    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);1079    setBreachMonitoring(s.breachMonitoring !== false);1080    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);1081    setShortcutBindings(getActiveBindings(s.shortcuts));1082  }10831084  async function applyTrashRetention(days: number) {1085    setTrashRetentionDays(days);1086    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });1087  }10881089  function primeListSearch(seed: string) {1090    setListSearchSeed(seed);1091    setListSearchSeedNonce((value) => value + 1);1092    openList();1093  }10941095  // Returns null when it detected a dead service worker and triggered handleLock().1096  // Callers that need to abort (e.g. openVault) check for null rather than relying1097  // on view() state, which may already be "lock" during normal startup flows.1098  async function loadEntries(): Promise<VaultEntry[] | null> {1099    const response = await sendMessage({ type: "GET_ENTRIES" });1100    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };11011102    // If the service worker was killed and restarted (MV3 workers sleep), the1103    // vault will be locked again — or the worker may not respond at all.1104    // In either case, send the user to the lock screen rather than silently1105    // showing an empty vault (which looks like data loss).1106    if (!res.ok) {1107      if (1108        res.error === "vault_locked" ||1109        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1110        (typeof res.error === "string" && res.error.includes("locked"))1111      ) {1112        handleLock();1113        return null; // signal emergency lock to callers1114      }1115      return [];1116    }11171118    const loadedEntries = res.data ?? [];1119    setEntries(loadedEntries);11201121    const currentId = selectedEntry()?.id;1122    if (currentId) {1123      setSelectedEntry(1124        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1125      );1126    }11271128    return loadedEntries;1129  }11301131  async function openVault(preferredEntryId?: string, skipViewSet = false) {1132    // Purge expired trash entries on each vault open1133    const retDays = trashRetentionDays();1134    if (retDays > 0) {1135      void sendMessage({1136        type: "PURGE_EXPIRED_TRASH",1137        payload: { retentionMs: retDays * 86_400_000 },1138      });1139    }11401141    const loadedEntries = await loadEntries();11421143    // null means loadEntries() triggered an emergency lock (service worker died).1144    // Don't override it by setting view back to "entry" with an empty vault.1145    if (loadedEntries === null) return false;11461147    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1148    let nextSelectedEntry: VaultEntry | null = null;1149    if (preferredEntryId) {1150      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1151    }1152    if (!nextSelectedEntry) {1153      const tabDomain = currentTabDomain();1154      if (tabDomain) {1155        nextSelectedEntry = loadedEntries.find((e) => {1156          if (e.type === "login") {1157            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1158            for (const extra of e.additionalUrls ?? []) {1159              if ((extractDomain(extra) ?? "") === tabDomain) return true;1160            }1161            return false;1162          }1163          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1164          return false;1165        }) ?? null;1166      }1167    }1168    nextSelectedEntry ??= pickNavigable(loadedEntries);11691170    setSelectedEntry(nextSelectedEntry);1171    setEditEntry(undefined);1172    setContentTransitioning(false);1173    setContentPhase("enter");1174    queueContentIdle();1175    if (!skipViewSet) setView("entry");1176    return true;1177  }11781179  async function handleUnlock() {1180    // If the user previously created a vault but hadn't yet confirmed their1181    // recovery words (and the browser was closed before they could), the1182    // peach_recovery_pending flag is still set in storage.local. Re-route1183    // back to the recovery surface so they finish the confirmation step1184    // before reaching the entries view — the words can be re-derived now1185    // that the vault is unlocked again.1186    let recoveryPending = false;1187    try {1188      const out = await chrome.storage.local?.get("peach_recovery_pending");1189      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1190    } catch { /* best-effort */ }1191    if (recoveryPending) {1192      setForceRecoveryWords(true);1193      setView("lock");1194      triggerPipPulse();1195      await restoreSettings();1196      return;1197    }1198    setHasVault(true);1199    triggerPipPulse();1200    await restoreSettings();1201    const celebrating = pendingCelebration();1202    if (celebrating) {1203      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1204      setPendingCelebration(false);1205    }1206    await openVault(undefined, celebrating);1207    if (celebrating) {1208      setView("pro-celebration");1209      window.setTimeout(() => setView("entry"), 2500);1210    }1211    // Popup was opened from the inline "Open Peach to unlock" button — close it1212    // now so the user lands back on the page with the autofill selector ready.1213    if (openedForInlineUnlock) {1214      openedForInlineUnlock = false;1215      window.close();1216    }1217  }12181219  function handleSelectEntry(entry: VaultEntry) {1220    if (entry.type === "note") {1221      setOpenNoteId(entry.id);1222      setShowNotes(true);1223      return;1224    }1225    setSelectedEntry(entry);1226    setContentTransitioning(false);1227    setContentPhase("enter");1228    queueContentIdle();1229    setView("entry");1230  }12311232  function handleAdd() {1233    setEditEntry(undefined);1234    setView("add");1235  }12361237  async function handleDelete() {1238    const entry = selectedEntry();1239    if (!entry) return;1240    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1241    const loadedEntries = await loadEntries() ?? [];1242    setSelectedEntry(pickNavigable(loadedEntries));1243    setView("entry");1244  }12451246  async function handleDeleteMany(ids: string[]) {1247    for (const id of ids) {1248      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1249    }1250    const loadedEntries = await loadEntries() ?? [];1251    // If the currently selected entry was among the deleted, move to first1252    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1253    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1254  }12551256  async function handleSave(savedEntry?: VaultEntry) {1257    await openVault(savedEntry?.id);1258  }12591260  function handleBack() {1261    const dest = editBackView();1262    setEditBackView("entry");1263    setEditEntry(undefined);1264    setView(dest);1265  }12661267  function handleExportBack() {1268    if (returnToPanic()) {1269      setReturnToPanic(false);1270      setView("panic");1271      return;1272    }1273    setView("settings");1274  }12751276  function handleLock() {1277    clearCanarySuppressions();1278    setEntries([]);1279    setSelectedEntry(null);1280    setEditEntry(undefined);1281    setContentPhase("idle");1282    setView("lock");1283  }12841285  function handleHeaderLock() {1286    // Lock the UI immediately — do not wait for the service worker. If the SW1287    // is dead or slow, the 5s sendMessage timeout would create a dead-click1288    // window. The SW will lock on its next wake regardless.1289    handleLock();1290    void sendMessage({ type: "LOCK" });1291  }12921293  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1294  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1295  // the trigger's own reply.1296  async function handleHeaderSync(): Promise<void> {1297    if (syncBusy()) return;1298    setSyncBusy(true);1299    setSyncFlash(null);1300    try {1301      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1302      let state: SyncOutcomeSummary = { status: "syncing" };1303      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1304        await new Promise((r) => setTimeout(r, 250));1305        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1306          ok: boolean;1307          data?: SyncOutcomeSummary;1308        };1309        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1310      }1311      setSyncSummary(state);1312      setSyncFlash(state.status === "error" ? "error" : "ok");1313      await loadSyncAlerts();1314      await loadEntries();1315      await loadSyncIndicator();1316    } catch {1317      setSyncSummary({ status: "error", outcome: "run_failed" });1318      setSyncFlash("error");1319    } finally {1320      setSyncBusy(false);1321      setTimeout(() => setSyncFlash(null), 2_000);1322    }1323  }13241325  function navigate(dir: number) {1326    const navigable = nonNoteEntries();1327    if (navigable.length === 0) return;1328    const currentIndex = selectedIndex();1329    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1330    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1331    setSelectedEntry(navigable[nextIndex]);1332    setContentPhase("enter");1333    queueContentIdle();1334  }13351336  /**1337   * The Entry view's selection invariant: never select a note. Notes are a1338   * separate surface (handleSelectEntry opens the notes view), so any code path1339   * that picks a default — vault open, post-delete, refresh — must skip them1340   * and return null if the only entries are notes.1341   */1342  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1343    return list.find((e) => e.type !== "note") ?? null;1344  }13451346  function openList() {1347    setView("list");1348  }13491350  function openHealth() {1351    setEditEntry(undefined);1352    setView("health");1353  }13541355  function handleOpenFileImport() {1356    setRestoreView("file");1357  }13581359  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;13601361  function handleFixEntry(entry: VaultEntry) {1362    setSelectedEntry(entry);1363    // Passkey-only entries have no editable surface — drop into view mode1364    // instead of opening the Add editor.1365    if (isPasskeyOnly(entry)) {1366      setView("entry");1367      return;1368    }1369    setEditBackView(view()); // preserve caller view so back returns here1370    setEditEntry(entry);1371    setView("add");1372  }13731374  const isLockedView = () => view() === "lock" || view() === "adopting";13751376  async function handleAdoptionDone() {1377    await storageSet("peach_onboarded", "true").catch(() => {});1378    setOnboarded(true);1379    setHasVault(true);1380    setView("initial-sync");1381    // The background applies a Pro license and persists the source-device1382    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1383    // celebration pending until that exact peer records a completed sync.1384    await refreshProStatus();1385    const deviceId = await resolveInitialSyncDeviceId();1386    if (deviceId) {1387      void beginInitialSyncWait(deviceId);1388    } else {1389      // Pairing completion without a durable peer row should be impossible.1390      // Stay on the honest waiting surface and expose retry instead of falling1391      // through to an empty vault.1392      setInitialSyncSlow(true);1393    }1394  }13951396  async function handleApprovePendingPasskey() {1397    const pending = pendingPasskey();1398    if (!pending) return;1399    if (pending.browser === "firefox" && pending.type === "create") {1400      // Firefox path: popup itself runs navigator.credentials.create. The1401      // background never approved/rejected anything — it just stashed1402      // intent. After the popup-driven flow resolves (success or cancel),1403      // clear the pending key so the popup doesn't re-show this on next open.1404      const { createFirefoxPasskey } = await import("./firefox-passkey");1405      const result = await createFirefoxPasskey(pending);1406      if (!result.ok) {1407        console.warn("Peach Firefox passkey create failed:", result.error);1408      }1409      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1410      setPendingPasskey(null);1411      void loadEntries();1412      window.close();1413      return;1414    }1415    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1416    window.close();1417  }14181419  async function handleDenyPendingPasskey() {1420    const pending = pendingPasskey();1421    if (!pending) return;1422    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1423    window.close();1424  }14251426  function queueContentIdle(after?: () => void) {1427    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1428    contentPhaseTimer = window.setTimeout(() => {1429      setContentPhase("idle");1430      after?.();1431    }, ENTRY_TRANSITION_SETTLE_MS);1432  }14331434  return (1435    <div class="popup-root peach-theme">1436      <Show when={bootState() === "ready"}>1437        <Show1438          when={!pendingPasskey()}1439          fallback={1440            <PasskeyApprovalView1441              type={pendingPasskey()!.type}1442              rpName={pendingPasskey()!.rpName}1443              rpId={pendingPasskey()!.rpId}1444              userName={pendingPasskey()!.userName}1445              userDisplayName={pendingPasskey()!.userDisplayName}1446              onApprove={handleApprovePendingPasskey}1447              onDeny={handleDenyPendingPasskey}1448            />1449          }1450        >1451          <Show1452            when={!isLockedView()}1453            fallback={1454              <Show1455                when={view() !== "adopting"}1456                fallback={1457                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1458                    <AdoptVaultView1459                      onCancel={() => {1460                        setOnboarded(false);1461                        setView("lock");1462                      }}1463                      onDone={handleAdoptionDone}1464                    />1465                  </Suspense>1466                }1467              >1468                <Show1469                  when={onboarded() || hasVault()}1470                  fallback={1471                    <Onboarding1472                      onComplete={() => {1473                        setStartOnboardingRestore(false);1474                        setOnboarded(true);1475                      }}1476                      onRestore={() => {1477                        setStartOnboardingRestore(true);1478                        setOnboarded(true);1479                      }}1480                      onAdopt={() => {1481                        setStartOnboardingRestore(false);1482                        setOnboarded(true);1483                        setView("adopting");1484                      }}1485                    />1486                  }1487                >1488                  <LockView1489                    hasVault={hasVault()}1490                    ready={bootState() === "ready"}1491                    isPro={proStatus()}1492                    forceRecoveryWords={forceRecoveryWords()}1493                    initialRestore={startOnboardingRestore()}1494                    onUnlock={() => {1495                      // RecoveryWordDisplay clears the storage flag before1496                      // calling onDone, so handleUnlock will see no pending1497                      // confirmation and proceed through the normal path.1498                      if (forceRecoveryWords()) setForceRecoveryWords(false);1499                      return handleUnlock();1500                    }}1501                    onBackToOnboarding={1502                      !hasVault()1503                        ? () => {1504                            setStartOnboardingRestore(false);1505                            setOnboarded(false);1506                          }1507                        : undefined1508                    }1509                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1510                  />1511                </Show>1512              </Show>1513            }1514          >1515            <Show1516              when={1517                view() !== "pro-celebration" &&1518                view() !== "initial-sync"1519              }1520              fallback={1521                <Show1522                  when={view() === "initial-sync"}1523                  fallback={<ProCelebration />}1524                >1525                  <InitialSyncView1526                    slow={initialSyncSlow()}1527                    onRetry={() => void retryInitialSync()}1528                  />1529                </Show>1530              }1531            >1532            <section1533              id="hd-shell"1534              class="peach-shell peach-theme"1535              data-surface="extension"1536            >1537            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1538              <PeachWordmark unlocked />1539              <div class="peach-chrome-actions">1540                <button1541                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1542                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1543                  aria-label="Notes"1544                  title="Notes"1545                >1546                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1547                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1548                    <line x1="4" y1="5" x2="10" y2="5" />1549                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1550                    <line x1="4" y1="10" x2="7" y2="10" />1551                  </svg>1552                </button>1553                <button1554                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1555                    classList={{1556                      "is-syncing": syncBusy(),1557                      "is-ok": syncFlash() === "ok",1558                      "is-error": syncFlash() === "error",1559                    }}1560                    onClick={() => void handleHeaderSync()}1561                    disabled={syncBusy()}1562                    aria-label={`Sync now. ${syncLabel()}`}1563                    title={syncLabel()}1564                  >1565                    <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">1566                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1567                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1568                      <path d="M2.6 1v2.4h2.4" />1569                      <path d="M11.4 13v-2.4H9" />1570                    </svg>1571                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1572                  </button>1573                <button1574                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1575                  onClick={() => setView("settings")}1576                  aria-label="Settings"1577                >1578                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1579                    <path1580                      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"1581                      stroke="currentColor"1582                      stroke-width="0.9"1583                    />1584                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1585                  </svg>1586                </button>1587                <button1588                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1589                  onClick={handleAdd}1590                  aria-label="New entry"1591                >1592                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1593                    <path d="M5.5 1v9M1 5.5h9" />1594                  </svg>1595                </button>1596                <button1597                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1598                  onClick={() => void handleHeaderLock()}1599                  aria-label="Lock vault"1600                >1601                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1602                    <path1603                      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"1604                      stroke="currentColor"1605                      stroke-width="1"1606                      stroke-linecap="round"1607                    />1608                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1609                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1610                  </svg>1611                </button>1612              </div>1613            </header>16141615            <Show when={pendingProNotice() !== null}>1616              <div class="peach-pro-notice-banner">1617                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1618                <button1619                  class="peach-pro-notice-link"1620                  onClick={() => {1621                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1622                    setSettingsInitialSection("license");1623                    setView("settings");1624                    setPendingProNotice(null);1625                  }}1626                >1627                  Learn more →1628                </button>1629                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1630              </div>1631            </Show>16321633            <div class="peach-shell-body">1634              <div class="peach-shell-veil"></div>1635              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1636                <EntryView1637                  entry={selectedEntry()}1638                  currentTabUrl={currentTabUrl()}1639                  entries={entries()}1640                  isPro={proStatus()}1641                  onDelete={handleDelete}1642                  onFieldSaved={() => void loadEntries()}1643                  onEscape={() => { setView("list"); }}1644                  onProGate={(feature) => {1645                    setUpgradeHighlight(feature);1646                    setSettingsInitialSection("license");1647                    setView("settings");1648                  }}1649                />1650              </div>16511652              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1653                <div class="peach-search-bar">1654                  <span class="peach-search-icon">1655                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1656                      <circle cx="5.5" cy="5.5" r="3.75" />1657                      <path d="M8.75 8.75L11.5 11.5" />1658                    </svg>1659                  </span>1660                  <input1661                    class="peach-search-input"1662                    placeholder="search vault..."1663                    autocomplete="off"1664                    aria-label="Search vault entries"1665                    onClick={openList}1666                    onFocus={openList}1667                    readOnly1668                  />1669                  <div class="peach-search-meta">1670                    <span class="peach-search-counter">1671                      {nonNoteEntries().length > 01672                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1673                        : "0 entries"}1674                    </span>1675                    <span class="peach-divider"></span>1676                    <button1677                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1678                      onClick={() => navigate(-1)}1679                      aria-label="Previous entry"1680                      disabled={nonNoteEntries().length === 0}1681                    >1682                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1683                        <path d="M5 1L1 5.5L5 10" />1684                      </svg>1685                    </button>1686                    <button1687                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1688                      onClick={() => navigate(1)}1689                      aria-label="Next entry"1690                      disabled={nonNoteEntries().length === 0}1691                    >1692                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1693                        <path d="M1 1L5 5.5L1 10" />1694                      </svg>1695                    </button>1696                  </div>1697                </div>1698              </section>1699            </div>17001701            {/* Desktop: shown on demand via Show. Native sheet is rendered1702                via Portal below at the document root so its position:fixed1703                isn't trapped by .peach-shell's transform-based animations. */}1704            {/* Rare device-trust alerts; normal sync changes are silent. */}1705            <Show when={syncAlerts().length > 0}>1706              <div class="peach-sync-alerts">1707                <For each={syncAlerts()}>1708                  {(alert, i) => (1709                    <div class="peach-sync-alert">1710                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1711                      <button1712                        class="peach-sync-alert-dismiss"1713                        type="button"1714                        aria-label="Dismiss"1715                        onClick={() => dismissSyncAlert(i())}1716                      >×</button>1717                    </div>1718                  )}1719                </For>1720              </div>1721            </Show>17221723            <Show when={!isNativePlatform() && view() === "list"}>1724              <VaultView1725                entries={entries()}1726                selectedEntryId={selectedEntry()?.id}1727                currentTabDomain={currentTabDomain()}1728                sortOrder={sortOrder()}1729                searchSeed={listSearchSeed()}1730                searchSeedNonce={listSearchSeedNonce()}1731                onSelectEntry={handleSelectEntry}1732                onSortOrderChange={setSortOrder}1733                onAdd={handleAdd}1734                onClose={() => setView("entry")}1735                onOpenTrash={() => setView("trash")}1736                onDeleteMany={handleDeleteMany}1737              />1738            </Show>1739            <Show when={isNativePlatform() && hasVault()}>1740              <Portal>1741                <div1742                  class="peach-vault-sheet"1743                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1744                  style={(() => {1745                    const live = sheetTranslate();1746                    if (live === null) return undefined;1747                    return { transform: `translateY(${live}px)` };1748                  })()}1749                >1750                  <VaultView1751                    entries={entries()}1752                    selectedEntryId={selectedEntry()?.id}1753                    currentTabDomain={currentTabDomain()}1754                    sortOrder={sortOrder()}1755                    searchSeed={listSearchSeed()}1756                    searchSeedNonce={listSearchSeedNonce()}1757                    isNative={true}1758                    onSelectEntry={handleSelectEntry}1759                    onSortOrderChange={setSortOrder}1760                    onAdd={handleAdd}1761                    onClose={() => setView("entry")}1762                    onOpenTrash={() => setView("trash")}1763                    onDeleteMany={handleDeleteMany}1764                  />1765                </div>1766              </Portal>1767            </Show>1768            <Show when={view() === "settings" || settingsExiting()}>1769              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1770                <SettingsView1771                  entriesCount={entries().length}1772                  breachMonitoring={breachMonitoring()}1773                  lockOnClose={lockOnClose()}1774                  autoLockMinutes={autoLockMinutes()}1775                  trashRetentionDays={trashRetentionDays()}1776                  theme={theme()}1777                  accentColor={accentColor()}1778                  textSize={textSize()}1779                  reduceMotion={reduceMotion()}1780                  isPro={proStatus()}1781                  initialSection={settingsInitialSection()}1782                  upgradeHighlight={upgradeHighlight()}1783                  isExiting={settingsExiting()}1784                  onBreachMonitoringChange={applyBreachMonitoring}1785                  onLockOnCloseChange={applyLockOnClose}1786                  onAutoLockMinutesChange={applyAutoLockMinutes}1787                  onTrashRetentionChange={applyTrashRetention}1788                  onThemeChange={applyTheme}1789                  onAccentChange={applyAccentColor}1790                  onTextSizeChange={applyTextSize}1791                  onReduceMotionChange={applyReduceMotion}1792                  shortcuts={shortcutBindings()}1793                  onShortcutsChange={applyShortcuts}1794                  onLicenseChange={async () => {1795                    // After activation/deactivation: refresh Pro status,1796                    // re-load entries (defensive — signal state can drift if1797                    // the SW briefly restarts during the verify+save round-trip),1798                    // and replay the Pro celebration if this is the first time1799                    // a valid Pro license is seen on this device.1800                    await refreshProStatus();1801                    void loadEntries();1802                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1803                    if ((should as { ok: boolean; data?: boolean }).data === true) {1804                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1805                      setView("pro-celebration");1806                      window.setTimeout(() => setView("settings"), 2500);1807                    }1808                  }}1809                  onBack={() => {1810                    setSettingsExiting(true);1811                    window.setTimeout(() => {1812                      setSettingsExiting(false);1813                      setSettingsInitialSection(null);1814                      setUpgradeHighlight(null);1815                      handleBack();1816                    }, 200);1817                  }}1818                  onImport={() => setView("import")}1819                  onExport={() => setView("export")}1820                  onBreachCheckDone={loadEntries}1821                  onOpenHealth={openHealth}1822                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1823                  onOpenFileImport={handleOpenFileImport}1824                  onOpenPanic={() => setView("panic")}1825                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1826                  onOpenCodexRestore={() => setView("codex-restore")}1827                  onCardChange={setSettingsActiveCard}1828                  onProGate={(feature) => {1829                    setUpgradeHighlight(feature);1830                    setSettingsInitialSection("license");1831                  }}1832                />1833              </Suspense>1834            </Show>1835            <Show when={view() === "codex-generate"}>1836              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1837                <CodexGenerateView1838                  isPro={proStatus()}1839                  onBack={() => setView("settings")}1840                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1841                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1842                  onVaultLocked={() => handleLock()}1843                />1844              </Suspense>1845            </Show>1846            <Show when={view() === "codex-restore"}>1847              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1848                <CodexRestoreView1849                  onBack={() => setView("lock")}1850                  onRestoreSuccess={async () => {1851                    // After restore the vault is unlocked; refresh entries1852                    // and route to the main vault list. handleUnlock is the1853                    // canonical post-unlock setup path.1854                    await handleUnlock();1855                  }}1856                />1857              </Suspense>1858            </Show>1859            <Show when={view() === "pair-device"}>1860              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1861                <PairDeviceView1862                  isPro={proStatus()}1863                  onProChanged={() => { void refreshProStatus(); }}1864                  onBack={() => setView("settings")}1865                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1866                />1867              </Suspense>1868            </Show>1869            <Show when={view() === "add"}>1870              <AddView1871                entry={editEntry()}1872                entries={entries()}1873                onBack={handleBack}1874                onSave={handleSave}1875              />1876            </Show>1877            <Show when={view() === "import"}>1878              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1879                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1880              </Suspense>1881            </Show>1882            <Show when={view() === "export"}>1883              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1884                <ExportView onBack={handleExportBack} />1885              </Suspense>1886            </Show>1887            <Show when={view() === "panic"}>1888              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1889                <PanicView1890                  onCancel={() => setView("settings")}1891                  onOpenExport={() => {1892                    setReturnToPanic(true);1893                    setView("export");1894                  }}1895                  onDestroyed={async () => {1896                    clearCanarySuppressions();1897                    setEntries([]);1898                    setSelectedEntry(null);1899                    setEditEntry(undefined);1900                    setHasVault(false);1901                    setOnboarded(false);1902                    setProStatus(false);1903                    setPendingPasskey(null);1904                    setUpgradeHighlight(null);1905                    setSettingsInitialSection(null);1906                    setPendingProNotice(null);1907                    setPendingCelebration(false);1908                    setReturnToPanic(false);1909                    setContentPhase("idle");1910                    setView("lock");1911                  }}1912                />1913              </Suspense>1914            </Show>1915            {/* Health stays mounted while editing an entry from it so1916                computeReused() doesn't rerun on every cancel/back. */}1917            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1918              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1919                <HealthView1920                  entries={entries()}1921                  isPro={proStatus()}1922                  onFixEntry={handleFixEntry}1923                  onBack={() => setView("settings")}1924                  onRefresh={loadEntries}1925                  hidden={view() !== "health"}1926                />1927              </Suspense>1928            </Show>1929            <Show when={view() === "trash"}>1930              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1931                <TrashView1932                  onBack={() => setView("list")}1933                  onRestored={() => void loadEntries()}1934                />1935              </Suspense>1936            </Show>1937            <Show when={showNotes()}>1938              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1939                <NotesMode1940                  notes={entries().filter((e) => e.type === "note")}1941                  initialNoteId={openNoteId()}1942                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1943                  onNoteListChanged={() => void loadEntries()}1944                />1945              </div>1946            </Show>1947            <Show when={restoreView() === "file"}>1948              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1949                <ImportView1950                  mode="onboarding"1951                  replacesExistingVault={true}1952                  onBack={() => setRestoreView(null)}1953                  onImport={async () => {1954                    setRestoreView(null);1955                    await handleUnlock();1956                  }}1957                />1958              </Suspense>1959            </Show>1960            </section>1961            </Show>1962          </Show>1963        </Show>1964      </Show>1965      <Show when={showShortcutsHelp()}>1966        <ShortcutsHelpOverlay1967          bindings={shortcutBindings()}1968          onClose={() => setShowShortcutsHelp(false)}1969        />1970      </Show>1971    </div>1972  );1973}19741975function ShortcutsHelpOverlay(props: {1976  bindings: Record<ShortcutAction, Keybinding>;1977  onClose: () => void;1978}) {1979  return (1980    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1981      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1982        <div class="peach-shortcuts-help-head">1983          <h3>Keyboard shortcuts</h3>1984          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1985        </div>1986        <div class="peach-shortcuts-help-body">1987          <p class="peach-settings-sub-label">ENTRY VIEW</p>1988          <ul>1989            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1990              <li>1991                <span>{d.label}</span>1992                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1993              </li>1994            ))}1995          </ul>1996          <p class="peach-settings-sub-label">ANYWHERE</p>1997          <ul>1998            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1999              <li>2000                <span>{d.label}</span>2001                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2002              </li>2003            ))}2004          </ul>2005        </div>2006      </div>2007    </div>2008  );2009}