App.tsx

85.1 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_LAST_CARD, 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  // Onboarding remounts whenever it leaves (create/adopt/restore) and comes150  // back. Those flows all exit from the final card, so resume there — a fresh151  // install's first mount stays at 0.152  const [onboardingCardAtExit, setOnboardingCardAtExit] = createSignal(0);153  const [entries, setEntries] = createSignal<VaultEntry[]>([]);154  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);155  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);156157  // Rare device-trust alerts stay visible; routine entry sync is silent.158  interface SyncAlert {159    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";160    entryId: string;161    entryTitle: string;162    deviceName: string;163    timestamp: number;164  }165  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);166  // Per-group flip index: which alert within a type-group is currently shown.167  const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});168  async function loadSyncAlerts() {169    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {170      ok: boolean;171      data?: SyncAlert[];172    };173    if (r.ok && (r.data?.length ?? 0) > 0) {174      setSyncAlerts(r.data ?? []);175      // Acknowledge so a crash between read and render doesn't lose them —176      // they remain on screen until the user dismisses each.177      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });178    }179  }180  function dismissAlertGroup(type: string) {181    setSyncAlerts((arr) => arr.filter((a) => a.type !== type));182    setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });183  }184  function flipAlert(type: string, dir: 1 | -1) {185    const group = syncAlerts().filter((a) => a.type === type);186    if (group.length <= 1) return;187    setAlertFlipIdx((m) => {188      const cur = m[type] ?? 0;189      return { ...m, [type]: (cur + dir + group.length) % group.length };190    });191  }192  /** Grouped alert types in display order, each with its alerts. */193  const alertGroups = createMemo(() => {194    const map = new Map<string, SyncAlert[]>();195    for (const a of syncAlerts()) {196      const g = map.get(a.type);197      if (g) g.push(a); else map.set(a.type, [a]);198    }199    return [...map.entries()];200  });201  function syncAlertText(a: SyncAlert): string {202    if (a.type === "DEVICE_REVOKED") {203      return `${a.deviceName} revoked a paired device — review your devices in Settings`;204    }205    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;206  }207  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");208  const [theme, setTheme] = createSignal<"dark" | "light">("dark");209  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");210  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);211  const [lockOnClose, setLockOnClose] = createSignal(false);212  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);213  const [breachMonitoring, setBreachMonitoring] = createSignal(true);214  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);215  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);216  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);217  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);218  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);219  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");220  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");221  // Cached Pro status — synchronous for render paths. Background's222  // GET_LICENSE is async, but render-time reads of isPro() must not block.223  // Refreshed at boot, after activate/deactivate, and whenever the popup224  // re-opens onto a stored license that has changed via another window.225  const [proStatus, setProStatus] = createSignal(false);226  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);227  // When the sync card's pairing button opens the pairing view, deep-link228  // straight into that pairing path instead of the rest screen.229  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");230  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);231  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");232  const [listSearchSeed, setListSearchSeed] = createSignal("");233  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);234  const [pendingCelebration, setPendingCelebration] = createSignal(false);235  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | 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; data?: { devices?: unknown[] } };268    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);269  }270271  interface InitialSyncPairedDevice extends InitialSyncDevice {272    pairedAt?: number;273  }274275  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {276    const response = (await sendMessage({277      type: "LIST_PAIRED_DEVICES",278    })) as {279      ok: boolean;280      data?: { devices?: InitialSyncPairedDevice[] };281    };282    return response.ok ? response.data?.devices ?? [] : [];283  }284285  async function resolveInitialSyncDeviceId(): Promise<string | null> {286    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(287      () => null,288    );289    const devices = await listInitialSyncDevices().catch(() => []);290    if (stored && devices.some((device) => device.deviceId === stored)) {291      return stored;292    }293294    // Fresh adoption has exactly one direct source, but choosing the newest row295    // also repairs the marker if storage failed after the pair itself committed.296    const newest = [...devices].sort(297      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),298    )[0];299    if (!newest) return stored;300    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(301      () => undefined,302    );303    return newest.deviceId;304  }305306  async function finishInitialSync(generation: number): Promise<void> {307    if (generation !== initialSyncWaitGeneration) return;308    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);309    setInitialSyncDeviceId(null);310    setInitialSyncSlow(false);311    await refreshProStatus();312313    // A license transferred during pairing intentionally leaves the one-shot314    // celebration pending. Consume it only now: sync readiness → celebration315    // → populated vault, never celebration → temporarily empty vault.316    const celebration = (await sendMessage({317      type: "SHOULD_PLAY_CELEBRATION",318    })) as { ok: boolean; data?: boolean };319    const shouldCelebrate = celebration.ok && celebration.data === true;320    if (shouldCelebrate) {321      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });322    }323324    const opened = await openVault(undefined, shouldCelebrate);325    if (!opened || generation !== initialSyncWaitGeneration) return;326    if (shouldCelebrate) {327      setView("pro-celebration");328      window.setTimeout(() => {329        if (generation === initialSyncWaitGeneration) setView("entry");330      }, 2500);331    }332  }333334  async function beginInitialSyncWait(deviceId: string): Promise<void> {335    const generation = ++initialSyncWaitGeneration;336    setInitialSyncDeviceId(deviceId);337    setInitialSyncSlow(false);338    setView("initial-sync");339    const startedAt = Date.now();340341    // Best effort: the pairing write already wakes the mesh listener, while342    // this trigger covers the key-order case where this receiver is the dialer.343    void sendMessage({344      type: "TRIGGER_SYNC",345      payload: { reason: "foreground" },346    }).catch(() => undefined);347348    while (349      generation === initialSyncWaitGeneration &&350      view() === "initial-sync"351    ) {352      try {353        const devices = await listInitialSyncDevices();354        if (hasCompletedInitialSync(devices, deviceId)) {355          await finishInitialSync(generation);356          return;357        }358      } catch {359        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.360      }361      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {362        setInitialSyncSlow(true);363      }364      await new Promise((resolve) =>365        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),366      );367    }368  }369370  async function retryInitialSync(): Promise<void> {371    const deviceId =372      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());373    if (deviceId) {374      await beginInitialSyncWait(deviceId);375    } else {376      setInitialSyncSlow(true);377    }378  }379380  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);381  // Set on popup boot when peach_recovery_pending flag is found in session382  // storage — instructs LockView to skip the unlock UI and open the recovery383  // words confirmation surface instead. Cleared via handleUnlock once the384  // user has typed the 3 confirmation words.385  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);386387  let contentPhaseTimer: number | undefined;388  // Set when the popup was opened from the inline "Open Peach to unlock" button.389  // handleUnlock() closes the popup after unlock so the user returns to the page.390  let openedForInlineUnlock = false;391392  onCleanup(() => {393    initialSyncWaitGeneration += 1;394  });395396  function applyAccent(name: AccentColorName) {397    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;398    const hex = color.hex;399    document.documentElement.style.setProperty("--peach-accent", hex);400    // Ambient surface variables — derived from the accent so surfaces shift401    // subtly toward the accent hue rather than staying fixed warm-brown.402    document.documentElement.style.setProperty("--peach-glow", hex + "2A");403    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");404    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");405  }406407  createEffect(() => {408    applyAccent(accentColor());409  });410411  createEffect(() => {412    document.documentElement.classList.toggle("light", theme() === "light");413    document.body.classList.toggle("light", theme() === "light");414  });415416  createEffect(() => {417    document.documentElement.setAttribute("data-text-size", textSize());418  });419420  createEffect(() => {421    if (reduceMotion()) {422      document.documentElement.setAttribute("data-motion", "reduce");423    } else {424      document.documentElement.removeAttribute("data-motion");425    }426  });427428  // Notes are not a destination of the Entry view; selecting a note opens the429  // notes surface instead (handleSelectEntry). Anything that walks or counts430  // the Entry view's neighbours (counter, prev/next, index) must use this431  // filtered list, otherwise the user can arrow into a note and is stuck —432  // the Entry view can't render a note and the prev/next buttons stop moving.433  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));434435  const selectedIndex = createMemo(() => {436    const currentId = selectedEntry()?.id;437    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;438    return nonNoteEntries().findIndex((entry) => entry.id === currentId);439  });440441  async function applyAccentColor(name: AccentColorName) {442    applyAccent(name);443    setAccentColor(name);444    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });445  }446447  async function applyTheme(t: "dark" | "light") {448    setTheme(t);449    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });450  }451452  async function applyTextSize(size: "small" | "medium" | "large") {453    setTextSize(size);454    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });455  }456457  async function applyReduceMotion(enabled: boolean) {458    setReduceMotion(enabled);459    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });460  }461462  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload463  // small and lets future default updates land for actions the user hasn't464  // touched. Settings sends us the full active map; we filter and store.465  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {466    setShortcutBindings(active);467    const overrides: Record<string, Keybinding> = {};468    for (const action of Object.keys(active) as ShortcutAction[]) {469      const a = active[action];470      const d = DEFAULT_BINDINGS[action];471      const same = a.key === d.key472        && Boolean(a.ctrl)  === Boolean(d.ctrl)473        && Boolean(a.meta)  === Boolean(d.meta)474        && Boolean(a.shift) === Boolean(d.shift)475        && Boolean(a.alt)   === Boolean(d.alt);476      if (!same) overrides[action] = a;477    }478    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });479  }480481  async function applyLockOnClose(enabled: boolean) {482    setLockOnClose(enabled);483    await sendMessage({484      type: "UPDATE_SETTINGS",485      payload: { lockOnClose: enabled },486    });487  }488489  async function applyAutoLockMinutes(minutes: number) {490    setAutoLockMinutes(minutes);491    await sendMessage({492      type: "UPDATE_SETTINGS",493      payload: { autoLockMinutes: minutes },494    });495  }496497  async function applyBreachMonitoring(enabled: boolean) {498    setBreachMonitoring(enabled);499    await sendMessage({500      type: "UPDATE_SETTINGS",501      payload: { breachMonitoring: enabled },502    });503  }504505  onMount(async () => {506    // Resolve the active tab in parallel with the unlock/has-vault queries —507    // openVault()'s smart selection picks the entry matching currentTabDomain,508    // so it must be populated before openVault runs. Previously refreshCurrentTab509    // ran after openVault, leaving popups that booted already-unlocked falling510    // back to loadedEntries[0] instead of the domain match.511    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([512      sendMessage({ type: "IS_UNLOCKED" }),513      sendMessage({ type: "HAS_VAULT" }),514      refreshCurrentTab(),515      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),516    ]);517    const unlocked = Boolean(518      (unlockResponse as { ok: boolean; data?: boolean }).data519    );520    const vaultExists = Boolean(521      (vaultResponse as { ok: boolean; data?: boolean }).data522    );523    const shouldCelebrate = Boolean(524      (celebrationResponse as { ok: boolean; data?: boolean }).data525    );526    setHasVault(vaultExists);527    // Onboarding gate — show once on first install, never again. Existing528    // users (vaultExists) are auto-marked onboarded so they skip the flow529    // even on the very first popup open after this feature ships.530    try {531      const onboarded = await storageGet("peach_onboarded");532      const seen = onboarded === "true";533      if (vaultExists && !seen) {534        await storageSet("peach_onboarded", "true");535        setOnboarded(true);536      } else {537        setOnboarded(seen);538      }539    } catch {540      // storage unavailable — default to onboarded so we never block boot541      setOnboarded(true);542    }543    await Promise.all([restoreSettings(), refreshProStatus()]);544545    const pendingInitialSyncMarker =546      unlocked && vaultExists547        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)548        : null;549    const pendingInitialSyncDeviceId = pendingInitialSyncMarker550      ? await resolveInitialSyncDeviceId()551      : null;552553    // Mark played before any animation so a crash mid-sequence never replays554    // it. A newly adopted receiver deliberately defers this until its first555    // real sync finishes, preserving initial sync → celebration → vault.556    if (shouldCelebrate && !pendingInitialSyncDeviceId) {557      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });558    }559560    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome561    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.562    if (unlocked && vaultExists) {563      void sendMessage({564        type: "TRIGGER_SYNC",565        payload: { reason: "foreground" },566      });567      void loadSyncIndicator();568      // Rare device-trust alerts only; routine entry sync stays quiet.569      void loadSyncAlerts();570    }571572    // If the user created a vault but hasn't yet confirmed their recovery573    // words, route back to the recovery-words screen instead of opening the574    // entries view. The flag lives in chrome.storage.local so it survives575    // both popup close (SW suppresses lock-on-close) and full browser576    // restart (handleUnlock checks the same flag after a fresh password577    // unlock). Cleared when confirmation succeeds.578    let recoveryPending = false;579    try {580      const out = await chrome.storage.local?.get("peach_recovery_pending");581      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";582    } catch { /* best-effort */ }583584    // If this popup was opened from the inline "Open Peach to unlock" button,585    // the background set a session flag. Read and clear it so handleUnlock()586    // can close the popup after unlock and return the user to the page.587    if (chrome.storage.session) {588      try {589        const s = await chrome.storage.session.get("peach_inline_unlock");590        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {591          openedForInlineUnlock = true;592          await chrome.storage.session.remove("peach_inline_unlock");593        }594      } catch { /* best-effort */ }595    }596597    // Native: closing the app before recovery-words confirmation means the598    // user didn't finish vault creation. Throw the partial vault away and599    // restart onboarding rather than asking them to unlock a vault they600    // never finished creating. Desktop keeps the existing "unlock to601    // resume" flow because closing the popup there is much more casual.602    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {603      try {604        await chrome.storage.local?.remove([605          "peach_vault_a",606          "peach_vault_b",607          "peach_recovery_pending",608          "peach_onboarded",609          "peach_vault_history",610        ]);611      } catch { /* best-effort */ }612      setHasVault(false);613      setOnboarded(false);614      setView("lock");615      setBootState("ready");616      return;617    }618619    if (recoveryPending && unlocked) {620      // forceRecoveryWords overrides LockView's hasVault gate so the621      // recovery surface renders even though the vault now exists.622      setForceRecoveryWords(true);623      setView("lock");624    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {625      void beginInitialSyncWait(pendingInitialSyncDeviceId);626    } else if (unlocked && vaultExists) {627      await openVault(undefined, shouldCelebrate);628      if (shouldCelebrate) {629        setView("pro-celebration");630        window.setTimeout(() => setView("entry"), 2500);631      }632    } else if (shouldCelebrate) {633      setPendingCelebration(true);634    }635636    await refreshPendingPasskey();637638    // Track tab changes so smart sort stays current639    const handleTabActivated = () => { void refreshCurrentTab(); };640    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {641      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();642    };643    try {644      chrome.tabs.onActivated.addListener(handleTabActivated);645      chrome.tabs.onUpdated.addListener(handleTabUpdated);646      onCleanup(() => {647        chrome.tabs.onActivated.removeListener(handleTabActivated);648        chrome.tabs.onUpdated.removeListener(handleTabUpdated);649      });650    } catch {651      // tabs permission may not be available in all contexts652    }653654    setBootState("ready");655656    // Deep-link: ?codex=pdf opens a detached window straight into the657    // Codex restore flow with auto-picked PDF. The action popup can't host658    // a file dialog without dismissing itself, so this is the only way the659    // PDF import path survives. See CodexRestoreView.openPdfPicker().660    try {661      const route = new URLSearchParams(window.location.search).get("codex");662      if (route === "pdf" || route === "restore") {663        setView("codex-restore");664      }665    } catch {666      // location.search unavailable — ignore.667    }668669    // Check for pending session-storage notices from the background.670    if (chrome.storage.session) {671      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as672        Record<string, { feature?: string } | undefined>;673      if (session.pendingProGate?.feature) {674        await chrome.storage.session.remove("pendingProGate");675        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);676        setSettingsInitialSection("license");677        setView("settings");678      } else if (session.pendingProNotice?.feature) {679        await chrome.storage.session.remove("pendingProNotice");680        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });681      }682    }683684    // Warm the lazy-module cache so the Suspense fallback never shows for685    // locally-bundled extension views. Without this, the first navigation to686    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which687    // covers the shell and absorbs clicks on the header.688    void Promise.all([689      import("./views/Settings").catch(() => {}),690      import("./views/Import").catch(() => {}),691      import("./views/Export").catch(() => {}),692      import("./views/Health").catch(() => {}),693      import("./views/TrashView").catch(() => {}),694    ]);695696    // Lock-on-close via a persistent port. sendMessage in pagehide is697    // unreliable — the popup context tears down before the message lands.698    // The SW's onConnect listener locks when this port disconnects.699    let popupPort: chrome.runtime.Port | null = null;700    try {701      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect702      // listener accepts the "popup-" prefix; the random suffix is defence in703      // depth against a port named exactly "popup" from anything but our popup.704      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });705    } catch { /* extension context invalidated — ignore */ }706    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });707708    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only709    // reliable signal is appStateChange — setTimeout is killed when the OS710    // backgrounds the app. We measure elapsed background time on resume.711    if (isNativePlatform()) {712      let backgroundedAt: number | null = null;713714      const CapApp = nativePlugin<{715        addListener: (716          ev: string,717          cb: (s: { isActive: boolean }) => void,718        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };719      }>("App");720      if (CapApp?.addListener) {721        const sub = CapApp.addListener(722          "appStateChange",723          ({ isActive }: { isActive: boolean }) => {724            if (!isActive) {725              backgroundedAt = Date.now();726              return;727            }728            if (backgroundedAt !== null && autoLockMinutes() > 0) {729              const elapsed = Date.now() - backgroundedAt;730              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();731            }732            backgroundedAt = null;733          }734        );735        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.736        onCleanup(() => {737          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});738        });739      }740741      // L12/COR-011: foreground idle autolock. appStateChange only fires when742      // the OS backgrounds the app — if the user idles with the screen on,743      // chrome.alarms is no-op'd in Capacitor so the vault would stay open744      // indefinitely. Poll every 30s and lock if elapsed since last user745      // interaction exceeds autoLockMinutes.746      let lastUserActivityAt = Date.now();747      const bumpActivity = () => { lastUserActivityAt = Date.now(); };748      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;749      for (const ev of ACTIVITY_EVENTS) {750        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });751      }752      const idleLockInterval = setInterval(() => {753        const minutes = autoLockMinutes();754        if (!minutes || minutes <= 0) return;755        const elapsed = Date.now() - lastUserActivityAt;756        if (elapsed >= minutes * 60_000) {757          lastUserActivityAt = Date.now();758          handleHeaderLock();759        }760      }, 30_000);761      onCleanup(() => {762        clearInterval(idleLockInterval);763        for (const ev of ACTIVITY_EVENTS) {764          document.removeEventListener(ev, bumpActivity, { capture: true });765        }766      });767768      // The retired native peer-discovery trigger went with the old Capacitor769      // pairing plugin. Reconnection is address-cache first, subnet probe second770      // (sync-runner.ts); relocating a peer that changed networks is an771      // Android-side discovery concern now.772      if (isNativePlatform()) {773        // Android runs the background/sync dispatcher in-process with the774        // popup, so the production runner has to be registered from the775        // UI bootstrap path instead of the MV3 service-worker entry.776        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>777          import("../background/sync-runner").then(({ productionSyncRunner }) => {778            setSyncRunner(productionSyncRunner);779            void hydratePersistedSyncState();780          })781        );782      }783    }784785    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale786    // entries instead of waiting for the next GET_ENTRIES round-trip.787    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {788      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();789      if (msg?.type === "SYNC_STATE_CHANGED") {790        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);791      }792      if (msg?.type === "PRO_GATE_TRIGGERED") {793        setUpgradeHighlight(msg.payload?.feature ?? null);794        setSettingsInitialSection("license");795        setView("settings");796      }797    };798    chrome.runtime.onMessage.addListener(handleRuntimeMessage);799    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));800801    // Android hardware/gesture back. MainActivity fires peach:back; the popup802    // decides what "back" means per surface. Lock+no-vault is the common case803    // — return to onboarding rather than letting the OS dismiss the activity.804    const handlePeachBack = () => {805      // Notes mode captures back first806      if (showNotes()) {807        setShowNotes(false);808        setOpenNoteId(undefined);809        return;810      }811      const v = view();812      if (v === "lock" && !hasVault() && onboarded()) {813        setOnboarded(false);814        return;815      }816      if (v === "list") { setView("entry"); return; }817      if (v === "settings") {818        window.dispatchEvent(new Event("peach:settings-back"));819        return;820      }821      if (v === "import" || v === "health") { setView("settings"); return; }822      if (v === "export") { handleExportBack(); return; }823      if (v === "add") { handleBack(); return; }824      if (v === "pair-device") { setView("settings"); return; }825    };826    window.addEventListener("peach:back", handlePeachBack);827    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));828829    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that830    // peeks from the bottom (search bar handle visible) and drags up to fill831    // the screen. dragOffset is the LIVE finger offset during a drag, in px,832    // 0 when no drag in progress. The wrapper element computes transform =833    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.834    if (isNativePlatform()) {835      let touchStartY = 0;836      let touchStartX = 0;837      let lastY = 0;838      let lastT = 0;839      let dragging = false;840      let captured = false;841      const HORIZONTAL_TOLERANCE = 16;842      const ACTIVATION_DY = 8;843      const PEEK_PX = 60;844845      const onTouchStart = (e: TouchEvent) => {846        const t = e.touches[0];847        if (!t) return;848        const v = view();849        if (v !== "entry" && v !== "list") return;850        // Entry view: only intercept drags starting in the bottom 40%.851        // List view: intercept drags starting in the top 35% (the search/handle row).852        const inBand = v === "entry"853          ? t.clientY > window.innerHeight * 0.6854          : t.clientY < window.innerHeight * 0.35;855        if (!inBand) return;856        touchStartY = lastY = t.clientY;857        touchStartX = t.clientX;858        lastT = e.timeStamp;859        dragging = true;860        captured = false;861      };862863      const onTouchMove = (e: TouchEvent) => {864        if (!dragging) return;865        const t = e.touches[0];866        if (!t) return;867        const dy = t.clientY - touchStartY;868        const dx = Math.abs(t.clientX - touchStartX);869870        if (!captured) {871          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {872            // Looks like a horizontal swipe — release.873            dragging = false;874            return;875          }876          if (Math.abs(dy) < ACTIVATION_DY) return;877          captured = true;878        }879880        // Translate the sheet by dy from its rest (peek) position. Peek is881        // (viewport height - PEEK_PX). Open is 0.882        const v = view();883        const restClosed = window.innerHeight - PEEK_PX;884        const baseTranslate = v === "list" ? 0 : restClosed;885        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));886        setSheetTranslate(next);887        lastY = t.clientY;888        lastT = e.timeStamp;889      };890891      const onTouchEnd = (e: TouchEvent) => {892        if (!dragging) { return; }893        const t = e.changedTouches[0];894        const elapsed = Math.max(1, e.timeStamp - lastT);895        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms896        const wasCaptured = captured;897        dragging = false;898        captured = false;899        const v = view();900901        if (!wasCaptured) {902          // Tap in the peek strip while in entry view → open the vault list.903          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");904          setSheetTranslate(null);905          return;906        }907908        const restClosed = window.innerHeight - PEEK_PX;909        const current = sheetTranslate() ?? restClosed;910911        // Snap rules:912        //   - Strong upward velocity → open913        //   - Strong downward velocity → close914        //   - Otherwise snap to whichever rest is closer915        let nextOpen: boolean;916        if (velocity < -0.05) nextOpen = true;917        else if (velocity > 0.05) nextOpen = false;918        else nextOpen = current < restClosed * 0.5;919920        if (nextOpen && v !== "list") setView("list");921        if (!nextOpen && v !== "entry") setView("entry");922        // Release the live offset so CSS transition handles the snap.923        setSheetTranslate(null);924      };925926      document.addEventListener("touchstart", onTouchStart, { passive: true });927      document.addEventListener("touchmove",  onTouchMove,  { passive: true });928      document.addEventListener("touchend",   onTouchEnd,   { passive: true });929      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });930      onCleanup(() => {931        document.removeEventListener("touchstart", onTouchStart);932        document.removeEventListener("touchmove",  onTouchMove);933        document.removeEventListener("touchend",   onTouchEnd);934      });935    }936937    // Action handlers — keyed by ShortcutAction. The dispatcher below tests938    // each binding against the event and runs the matching handler. New939    // shortcuts only need an entry here; the binding is data, not code.940    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {941      copy_password: () => {942        const entry = selectedEntry();943        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });944      },945      copy_username: () => {946        const entry = selectedEntry();947        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });948      },949      copy_totp: () => {950        const entry = selectedEntry();951        if (!entry?.totp) return;952        try {953          const { code } = generateTOTP(entry.totp);954          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });955        } catch { /* invalid TOTP secret — silent */ }956      },957      new_entry: () => handleAdd(),958      edit_entry: () => {959        const entry = selectedEntry();960        // Passkey-only entries have nothing user-editable in the Add view; the961        // passkey credential itself is opaque. Skip the edit action for them.962        if (!entry || isPasskeyOnly(entry)) return;963        setEditEntry(entry);964        setView("add");965      },966      delete_entry: () => {967        if (selectedEntry()) void handleDelete();968      },969      lock_vault: () => { void handleHeaderLock(); },970      search: () => openList(),971      nav_prev: () => navigate(-1),972      nav_next: () => navigate(1),973      jump_vault: () => setView("entry"),974      jump_settings: () => setView("settings"),975      show_help: () => setShowShortcutsHelp(true),976    };977978    // Actions that are MEANINGFUL only on the entry-detail view. Outside979    // that scope the binding is dormant — pressing C while on Settings980    // does nothing rather than awkwardly copying from a now-stale entry.981    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([982      "copy_password", "copy_username", "copy_totp",983      "edit_entry", "delete_entry", "nav_prev", "nav_next",984    ]);985986    const handleGlobalKeydown = (e: KeyboardEvent) => {987      const v = view();988      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"989        || (e.target as HTMLElement)?.tagName === "TEXTAREA"990        || (e.target as HTMLElement)?.isContentEditable;991      const isPrintableSearchKey =992        e.key.length === 1 &&993        !e.ctrlKey &&994        !e.metaKey &&995        !e.altKey;996997      // No shortcuts while a full-screen surface owns the whole viewport:998      // the lock screen, the post-pairing readiness sequence, or the Pro999      // celebration. Without this the lock screen is at the mercy of whatever1000      // single-key binding is active — e.g. typing "n" in a password that1001      // slips out of focus triggers `new_entry` and escapes the lock screen.1002      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;10031004      // Help dialog: Escape closes it; eat the keypress so it doesn't1005      // also navigate away from the underlying view.1006      if (showShortcutsHelp()) {1007        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }1008        return;1009      }10101011      // ── Escape — fixed binding (not user-customizable) ───────1012      if (e.key === "Escape") {1013        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }1014        if (v === "list") { setView("entry"); return; }1015        if (v === "settings" || v === "add") { handleBack(); return; }1016        if (v === "import" || v === "health") { setView("settings"); return; }1017        if (v === "export") { handleExportBack(); return; }1018        if (v === "pair-device") { setView("settings"); return; }1019      }10201021      // Bindings-driven dispatch. Single-key letter bindings without1022      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is1023      // inside an input, so users can type into search/forms normally.1024      const bindings = shortcutBindings();1025      for (const action of Object.keys(bindings) as ShortcutAction[]) {1026        const binding = bindings[action];1027        if (!matchKeybinding(e, binding)) continue;1028        // Single-key letter bindings need the input-focus guard. Bindings1029        // with any modifier are safe — Ctrl+L doesn't conflict with typing.1030        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;1031        if (!hasMod && binding.key.length === 1 && inInput) return;1032        if (ENTRY_SCOPED.has(action) && v !== "entry") return;1033        e.preventDefault();1034        SHORTCUT_HANDLERS[action]?.();1035        return;1036      }10371038      // Type-to-search: in entry view, any printable key not consumed by a1039      // shortcut above primes the list search seed and opens the list.1040      // Kept outside the bindings table because it's a behavior, not a1041      // discrete action — every printable character can trigger it.1042      if (v === "entry" && !inInput && isPrintableSearchKey) {1043        e.preventDefault();1044        primeListSearch(e.key);1045        return;1046      }1047    };1048    window.addEventListener("keydown", handleGlobalKeydown);1049    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));10501051    const handleStorageChanged = (1052      changes: Record<string, chrome.storage.StorageChange>,1053      areaName: string1054    ) => {1055      if (areaName !== "session") return;1056      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {1057        return;1058      }1059      void refreshPendingPasskey();1060    };1061    chrome.storage.onChanged.addListener(handleStorageChanged);1062    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));1063  });10641065  async function refreshCurrentTab() {1066    try {1067      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1068      const url = tab?.url ?? tab?.pendingUrl ?? "";1069      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");1070      // Skip extension/internal URLs — adding chrome://, about:, or1071      // chrome-extension:// to a vault entry is never what the user wants.1072      const isWebUrl = /^https?:\/\//i.test(url);1073      setCurrentTabUrl(isWebUrl ? url : "");1074    } catch {1075      setCurrentTabDomain("");1076      setCurrentTabUrl("");1077    }1078  }10791080  async function refreshPendingPasskey() {1081    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });1082    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);1083  }10841085  async function refreshProStatus() {1086    const res = await sendMessage({ type: "GET_LICENSE" });1087    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;1088    setProStatus(Boolean(data?.valid && data?.plan === "pro"));1089  }10901091  async function restoreSettings() {1092    const res = await sendMessage({ type: "GET_SETTINGS" });1093    const s = (res as { ok: boolean; data?: any }).data ?? {};1094    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {1095      setAccentColor(s.accentColor as AccentColorName);1096    }1097    setTheme(s.theme === "light" ? "light" : "dark");1098    if (s.textSize === "small" || s.textSize === "large") {1099      setTextSize(s.textSize);1100    } else {1101      setTextSize("medium");1102    }1103    setReduceMotion(s.reduceMotion === true);1104    setLockOnClose(s.lockOnClose === true);1105    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);1106    setBreachMonitoring(s.breachMonitoring !== false);1107    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);1108    setShortcutBindings(getActiveBindings(s.shortcuts));1109  }11101111  async function applyTrashRetention(days: number) {1112    setTrashRetentionDays(days);1113    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });1114  }11151116  function primeListSearch(seed: string) {1117    setListSearchSeed(seed);1118    setListSearchSeedNonce((value) => value + 1);1119    openList();1120  }11211122  // Returns null when it detected a dead service worker and triggered handleLock().1123  // Callers that need to abort (e.g. openVault) check for null rather than relying1124  // on view() state, which may already be "lock" during normal startup flows.1125  async function loadEntries(): Promise<VaultEntry[] | null> {1126    const response = await sendMessage({ type: "GET_ENTRIES" });1127    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };11281129    // If the service worker was killed and restarted (MV3 workers sleep), the1130    // vault will be locked again — or the worker may not respond at all.1131    // In either case, send the user to the lock screen rather than silently1132    // showing an empty vault (which looks like data loss).1133    if (!res.ok) {1134      if (1135        res.error === "vault_locked" ||1136        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1137        (typeof res.error === "string" && res.error.includes("locked"))1138      ) {1139        handleLock();1140        return null; // signal emergency lock to callers1141      }1142      return [];1143    }11441145    const loadedEntries = res.data ?? [];1146    setEntries(loadedEntries);11471148    const currentId = selectedEntry()?.id;1149    if (currentId) {1150      setSelectedEntry(1151        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1152      );1153    }11541155    return loadedEntries;1156  }11571158  async function openVault(preferredEntryId?: string, skipViewSet = false) {1159    // Purge expired trash entries on each vault open1160    const retDays = trashRetentionDays();1161    if (retDays > 0) {1162      void sendMessage({1163        type: "PURGE_EXPIRED_TRASH",1164        payload: { retentionMs: retDays * 86_400_000 },1165      });1166    }11671168    const loadedEntries = await loadEntries();11691170    // null means loadEntries() triggered an emergency lock (service worker died).1171    // Don't override it by setting view back to "entry" with an empty vault.1172    if (loadedEntries === null) return false;11731174    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1175    let nextSelectedEntry: VaultEntry | null = null;1176    if (preferredEntryId) {1177      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1178    }1179    if (!nextSelectedEntry) {1180      const tabDomain = currentTabDomain();1181      if (tabDomain) {1182        nextSelectedEntry = loadedEntries.find((e) => {1183          if (e.type === "login") {1184            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1185            for (const extra of e.additionalUrls ?? []) {1186              if ((extractDomain(extra) ?? "") === tabDomain) return true;1187            }1188            return false;1189          }1190          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1191          return false;1192        }) ?? null;1193      }1194    }1195    nextSelectedEntry ??= pickNavigable(loadedEntries);11961197    setSelectedEntry(nextSelectedEntry);1198    setEditEntry(undefined);1199    setContentTransitioning(false);1200    setContentPhase("enter");1201    queueContentIdle();1202    if (!skipViewSet) setView("entry");1203    return true;1204  }12051206  async function handleUnlock() {1207    // If the user previously created a vault but hadn't yet confirmed their1208    // recovery words (and the browser was closed before they could), the1209    // peach_recovery_pending flag is still set in storage.local. Re-route1210    // back to the recovery surface so they finish the confirmation step1211    // before reaching the entries view — the words can be re-derived now1212    // that the vault is unlocked again.1213    let recoveryPending = false;1214    try {1215      const out = await chrome.storage.local?.get("peach_recovery_pending");1216      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1217    } catch { /* best-effort */ }1218    if (recoveryPending) {1219      setForceRecoveryWords(true);1220      setView("lock");1221      triggerPipPulse();1222      await restoreSettings();1223      return;1224    }1225    setHasVault(true);1226    triggerPipPulse();1227    await restoreSettings();1228    const celebrating = pendingCelebration();1229    if (celebrating) {1230      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1231      setPendingCelebration(false);1232    }1233    await openVault(undefined, celebrating);1234    if (celebrating) {1235      setView("pro-celebration");1236      window.setTimeout(() => setView("entry"), 2500);1237    }1238    // Popup was opened from the inline "Open Peach to unlock" button — close it1239    // now so the user lands back on the page with the autofill selector ready.1240    if (openedForInlineUnlock) {1241      openedForInlineUnlock = false;1242      window.close();1243    }1244  }12451246  function handleSelectEntry(entry: VaultEntry) {1247    if (entry.type === "note") {1248      setOpenNoteId(entry.id);1249      setShowNotes(true);1250      return;1251    }1252    setSelectedEntry(entry);1253    setContentTransitioning(false);1254    setContentPhase("enter");1255    queueContentIdle();1256    setView("entry");1257  }12581259  function handleAdd() {1260    setEditEntry(undefined);1261    setView("add");1262  }12631264  async function handleDelete() {1265    const entry = selectedEntry();1266    if (!entry) return;1267    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1268    const loadedEntries = await loadEntries() ?? [];1269    setSelectedEntry(pickNavigable(loadedEntries));1270    setView("entry");1271  }12721273  async function handleDeleteMany(ids: string[]) {1274    for (const id of ids) {1275      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1276    }1277    const loadedEntries = await loadEntries() ?? [];1278    // If the currently selected entry was among the deleted, move to first1279    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1280    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1281  }12821283  async function handleSave(savedEntry?: VaultEntry) {1284    await openVault(savedEntry?.id);1285  }12861287  function handleBack() {1288    const dest = editBackView();1289    setEditBackView("entry");1290    setEditEntry(undefined);1291    setView(dest);1292  }12931294  function handleExportBack() {1295    if (returnToPanic()) {1296      setReturnToPanic(false);1297      setView("panic");1298      return;1299    }1300    setView("settings");1301  }13021303  function handleLock() {1304    clearCanarySuppressions();1305    setEntries([]);1306    setSelectedEntry(null);1307    setEditEntry(undefined);1308    setContentPhase("idle");1309    setView("lock");1310  }13111312  function handleHeaderLock() {1313    // Lock the UI immediately — do not wait for the service worker. If the SW1314    // is dead or slow, the 5s sendMessage timeout would create a dead-click1315    // window. The SW will lock on its next wake regardless.1316    handleLock();1317    void sendMessage({ type: "LOCK" });1318  }13191320  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1321  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1322  // the trigger's own reply.1323  async function handleHeaderSync(): Promise<void> {1324    if (syncBusy()) return;1325    setSyncBusy(true);1326    setSyncFlash(null);1327    try {1328      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1329      let state: SyncOutcomeSummary = { status: "syncing" };1330      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1331        await new Promise((r) => setTimeout(r, 250));1332        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1333          ok: boolean;1334          data?: SyncOutcomeSummary;1335        };1336        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1337      }1338      setSyncSummary(state);1339      setSyncFlash(state.status === "error" ? "error" : "ok");1340      await loadSyncAlerts();1341      await loadEntries();1342      await loadSyncIndicator();1343    } catch {1344      setSyncSummary({ status: "error", outcome: "run_failed" });1345      setSyncFlash("error");1346    } finally {1347      setSyncBusy(false);1348      setTimeout(() => setSyncFlash(null), 2_000);1349    }1350  }13511352  function navigate(dir: number) {1353    const navigable = nonNoteEntries();1354    if (navigable.length === 0) return;1355    const currentIndex = selectedIndex();1356    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1357    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1358    setSelectedEntry(navigable[nextIndex]);1359    setContentPhase("enter");1360    queueContentIdle();1361  }13621363  /**1364   * The Entry view's selection invariant: never select a note. Notes are a1365   * separate surface (handleSelectEntry opens the notes view), so any code path1366   * that picks a default — vault open, post-delete, refresh — must skip them1367   * and return null if the only entries are notes.1368   */1369  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1370    return list.find((e) => e.type !== "note") ?? null;1371  }13721373  function openList() {1374    setView("list");1375  }13761377  function openHealth() {1378    setEditEntry(undefined);1379    setView("health");1380  }13811382  function handleOpenFileImport() {1383    setRestoreView("file");1384  }13851386  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;13871388  function handleFixEntry(entry: VaultEntry) {1389    setSelectedEntry(entry);1390    // Passkey-only entries have no editable surface — drop into view mode1391    // instead of opening the Add editor.1392    if (isPasskeyOnly(entry)) {1393      setView("entry");1394      return;1395    }1396    setEditBackView(view()); // preserve caller view so back returns here1397    setEditEntry(entry);1398    setView("add");1399  }14001401  const isLockedView = () => view() === "lock" || view() === "adopting";14021403  async function handleAdoptionDone() {1404    await storageSet("peach_onboarded", "true").catch(() => {});1405    setOnboarded(true);1406    setHasVault(true);1407    setView("initial-sync");1408    // The background applies a Pro license and persists the source-device1409    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1410    // celebration pending until that exact peer records a completed sync.1411    await refreshProStatus();1412    const deviceId = await resolveInitialSyncDeviceId();1413    if (deviceId) {1414      void beginInitialSyncWait(deviceId);1415    } else {1416      // Pairing completion without a durable peer row should be impossible.1417      // Stay on the honest waiting surface and expose retry instead of falling1418      // through to an empty vault.1419      setInitialSyncSlow(true);1420    }1421  }14221423  async function handleApprovePendingPasskey() {1424    const pending = pendingPasskey();1425    if (!pending) return;1426    if (pending.browser === "firefox" && pending.type === "create") {1427      // Firefox path: popup itself runs navigator.credentials.create. The1428      // background never approved/rejected anything — it just stashed1429      // intent. After the popup-driven flow resolves (success or cancel),1430      // clear the pending key so the popup doesn't re-show this on next open.1431      const { createFirefoxPasskey } = await import("./firefox-passkey");1432      const result = await createFirefoxPasskey(pending);1433      if (!result.ok) {1434        console.warn("Peach Firefox passkey create failed:", result.error);1435      }1436      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1437      setPendingPasskey(null);1438      void loadEntries();1439      window.close();1440      return;1441    }1442    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1443    window.close();1444  }14451446  async function handleDenyPendingPasskey() {1447    const pending = pendingPasskey();1448    if (!pending) return;1449    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1450    window.close();1451  }14521453  function queueContentIdle(after?: () => void) {1454    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1455    contentPhaseTimer = window.setTimeout(() => {1456      setContentPhase("idle");1457      after?.();1458    }, ENTRY_TRANSITION_SETTLE_MS);1459  }14601461  return (1462    <div class="popup-root peach-theme">1463      <Show when={bootState() === "ready"}>1464        <Show1465          when={!pendingPasskey()}1466          fallback={1467            <PasskeyApprovalView1468              type={pendingPasskey()!.type}1469              rpName={pendingPasskey()!.rpName}1470              rpId={pendingPasskey()!.rpId}1471              userName={pendingPasskey()!.userName}1472              userDisplayName={pendingPasskey()!.userDisplayName}1473              onApprove={handleApprovePendingPasskey}1474              onDeny={handleDenyPendingPasskey}1475            />1476          }1477        >1478          <Show1479            when={!isLockedView()}1480            fallback={1481              <Show1482                when={view() !== "adopting"}1483                fallback={1484                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1485                    <AdoptVaultView1486                      onCancel={() => {1487                        setOnboarded(false);1488                        setView("lock");1489                      }}1490                      onDone={handleAdoptionDone}1491                    />1492                  </Suspense>1493                }1494              >1495                <Show1496                  when={onboarded() || hasVault()}1497                  fallback={1498                    <Onboarding1499                      initialCard={onboardingCardAtExit()}1500                      onComplete={() => {1501                        setOnboardingCardAtExit(ONBOARDING_LAST_CARD);1502                        setStartOnboardingRestore(false);1503                        setOnboarded(true);1504                      }}1505                      onRestore={() => {1506                        setOnboardingCardAtExit(ONBOARDING_LAST_CARD);1507                        setStartOnboardingRestore(true);1508                        setOnboarded(true);1509                      }}1510                      onAdopt={() => {1511                        setOnboardingCardAtExit(ONBOARDING_LAST_CARD);1512                        setStartOnboardingRestore(false);1513                        setOnboarded(true);1514                        setView("adopting");1515                      }}1516                    />1517                  }1518                >1519                  <LockView1520                    hasVault={hasVault()}1521                    ready={bootState() === "ready"}1522                    isPro={proStatus()}1523                    forceRecoveryWords={forceRecoveryWords()}1524                    initialRestore={startOnboardingRestore()}1525                    onUnlock={() => {1526                      // RecoveryWordDisplay clears the storage flag before1527                      // calling onDone, so handleUnlock will see no pending1528                      // confirmation and proceed through the normal path.1529                      if (forceRecoveryWords()) setForceRecoveryWords(false);1530                      return handleUnlock();1531                    }}1532                    onBackToOnboarding={1533                      !hasVault()1534                        ? () => {1535                            setStartOnboardingRestore(false);1536                            setOnboarded(false);1537                          }1538                        : undefined1539                    }1540                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1541                  />1542                </Show>1543              </Show>1544            }1545          >1546            <Show1547              when={1548                view() !== "pro-celebration" &&1549                view() !== "initial-sync"1550              }1551              fallback={1552                <Show1553                  when={view() === "initial-sync"}1554                  fallback={<ProCelebration />}1555                >1556                  <InitialSyncView1557                    slow={initialSyncSlow()}1558                    onRetry={() => void retryInitialSync()}1559                  />1560                </Show>1561              }1562            >1563            <section1564              id="hd-shell"1565              class="peach-shell peach-theme"1566              data-surface="extension"1567            >1568            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1569              <PeachWordmark unlocked />1570              <div class="peach-chrome-actions">1571                <button1572                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1573                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1574                  aria-label="Notes"1575                  title="Notes"1576                >1577                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1578                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1579                    <line x1="4" y1="5" x2="10" y2="5" />1580                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1581                    <line x1="4" y1="10" x2="7" y2="10" />1582                  </svg>1583                </button>1584                <button1585                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1586                    classList={{1587                      "is-syncing": syncBusy(),1588                      "is-ok": syncFlash() === "ok",1589                      "is-error": syncFlash() === "error",1590                    }}1591                    onClick={() => void handleHeaderSync()}1592                    disabled={syncBusy()}1593                    aria-label={`Sync now. ${syncLabel()}`}1594                    title={syncLabel()}1595                  >1596                    <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">1597                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1598                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1599                      <path d="M2.6 1v2.4h2.4" />1600                      <path d="M11.4 13v-2.4H9" />1601                    </svg>1602                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1603                  </button>1604                <button1605                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1606                  onClick={() => setView("settings")}1607                  aria-label="Settings"1608                >1609                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1610                    <path1611                      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"1612                      stroke="currentColor"1613                      stroke-width="0.9"1614                    />1615                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1616                  </svg>1617                </button>1618                <button1619                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1620                  onClick={handleAdd}1621                  aria-label="New entry"1622                >1623                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1624                    <path d="M5.5 1v9M1 5.5h9" />1625                  </svg>1626                </button>1627                <button1628                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1629                  onClick={() => void handleHeaderLock()}1630                  aria-label="Lock vault"1631                >1632                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1633                    <path1634                      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"1635                      stroke="currentColor"1636                      stroke-width="1"1637                      stroke-linecap="round"1638                    />1639                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1640                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1641                  </svg>1642                </button>1643              </div>1644            </header>16451646            <Show when={pendingProNotice() !== null}>1647              <div class="peach-pro-notice-banner">1648                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1649                <button1650                  class="peach-pro-notice-link"1651                  onClick={() => {1652                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1653                    setSettingsInitialSection("license");1654                    setView("settings");1655                    setPendingProNotice(null);1656                  }}1657                >1658                  Learn more →1659                </button>1660                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1661              </div>1662            </Show>16631664            <div class="peach-shell-body">1665              <div class="peach-shell-veil"></div>1666              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1667                <EntryView1668                  entry={selectedEntry()}1669                  currentTabUrl={currentTabUrl()}1670                  entries={entries()}1671                  isPro={proStatus()}1672                  onDelete={handleDelete}1673                  onFieldSaved={() => void loadEntries()}1674                  onEscape={() => { setView("list"); }}1675                  onProGate={(feature) => {1676                    setUpgradeHighlight(feature);1677                    setSettingsInitialSection("license");1678                    setView("settings");1679                  }}1680                />1681              </div>16821683              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1684                <div class="peach-search-bar">1685                  <span class="peach-search-icon">1686                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1687                      <circle cx="5.5" cy="5.5" r="3.75" />1688                      <path d="M8.75 8.75L11.5 11.5" />1689                    </svg>1690                  </span>1691                  <input1692                    class="peach-search-input"1693                    placeholder="search vault..."1694                    autocomplete="off"1695                    aria-label="Search vault entries"1696                    onClick={openList}1697                    onFocus={openList}1698                    readOnly1699                  />1700                  <div class="peach-search-meta">1701                    <span class="peach-search-counter">1702                      {nonNoteEntries().length > 01703                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1704                        : "0 entries"}1705                    </span>1706                    <span class="peach-divider"></span>1707                    <button1708                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1709                      onClick={() => navigate(-1)}1710                      aria-label="Previous entry"1711                      disabled={nonNoteEntries().length === 0}1712                    >1713                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1714                        <path d="M5 1L1 5.5L5 10" />1715                      </svg>1716                    </button>1717                    <button1718                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1719                      onClick={() => navigate(1)}1720                      aria-label="Next entry"1721                      disabled={nonNoteEntries().length === 0}1722                    >1723                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1724                        <path d="M1 1L5 5.5L1 10" />1725                      </svg>1726                    </button>1727                  </div>1728                </div>1729              </section>1730            </div>17311732            {/* Desktop: shown on demand via Show. Native sheet is rendered1733                via Portal below at the document root so its position:fixed1734                isn't trapped by .peach-shell's transform-based animations. */}1735            {/* Rare device-trust alerts; normal sync changes are silent. */}1736            <Show when={alertGroups().length > 0}>1737              <div class="peach-sync-alerts">1738                <For each={alertGroups()}>1739                  {([type, group]) => {1740                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1741                    return (1742                      <div class="peach-sync-alert">1743                        <Show when={group.length > 1}>1744                          <button1745                            class="peach-sync-alert-flip"1746                            type="button"1747                            aria-label="Previous"1748                            onClick={() => flipAlert(type, -1)}1749                          >‹</button>1750                        </Show>1751                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1752                        <Show when={group.length > 1}>1753                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1754                          <button1755                            class="peach-sync-alert-flip"1756                            type="button"1757                            aria-label="Next"1758                            onClick={() => flipAlert(type, 1)}1759                          >›</button>1760                        </Show>1761                        <button1762                          class="peach-sync-alert-dismiss"1763                          type="button"1764                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1765                          onClick={() => dismissAlertGroup(type)}1766                        >×</button>1767                      </div>1768                    );1769                  }}1770                </For>1771              </div>1772            </Show>17731774            <Show when={!isNativePlatform() && view() === "list"}>1775              <VaultView1776                entries={entries()}1777                selectedEntryId={selectedEntry()?.id}1778                currentTabDomain={currentTabDomain()}1779                sortOrder={sortOrder()}1780                searchSeed={listSearchSeed()}1781                searchSeedNonce={listSearchSeedNonce()}1782                onSelectEntry={handleSelectEntry}1783                onSortOrderChange={setSortOrder}1784                onAdd={handleAdd}1785                onClose={() => setView("entry")}1786                onOpenTrash={() => setView("trash")}1787                onDeleteMany={handleDeleteMany}1788              />1789            </Show>1790            <Show when={isNativePlatform() && hasVault()}>1791              <Portal>1792                <div1793                  class="peach-vault-sheet"1794                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1795                  style={(() => {1796                    const live = sheetTranslate();1797                    if (live === null) return undefined;1798                    return { transform: `translateY(${live}px)` };1799                  })()}1800                >1801                  <VaultView1802                    entries={entries()}1803                    selectedEntryId={selectedEntry()?.id}1804                    currentTabDomain={currentTabDomain()}1805                    sortOrder={sortOrder()}1806                    searchSeed={listSearchSeed()}1807                    searchSeedNonce={listSearchSeedNonce()}1808                    isNative={true}1809                    onSelectEntry={handleSelectEntry}1810                    onSortOrderChange={setSortOrder}1811                    onAdd={handleAdd}1812                    onClose={() => setView("entry")}1813                    onOpenTrash={() => setView("trash")}1814                    onDeleteMany={handleDeleteMany}1815                  />1816                </div>1817              </Portal>1818            </Show>1819            <Show when={view() === "settings" || settingsExiting()}>1820              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1821                <SettingsView1822                  entriesCount={entries().length}1823                  breachMonitoring={breachMonitoring()}1824                  lockOnClose={lockOnClose()}1825                  autoLockMinutes={autoLockMinutes()}1826                  trashRetentionDays={trashRetentionDays()}1827                  theme={theme()}1828                  accentColor={accentColor()}1829                  textSize={textSize()}1830                  reduceMotion={reduceMotion()}1831                  isPro={proStatus()}1832                  initialSection={settingsInitialSection()}1833                  upgradeHighlight={upgradeHighlight()}1834                  isExiting={settingsExiting()}1835                  onBreachMonitoringChange={applyBreachMonitoring}1836                  onLockOnCloseChange={applyLockOnClose}1837                  onAutoLockMinutesChange={applyAutoLockMinutes}1838                  onTrashRetentionChange={applyTrashRetention}1839                  onThemeChange={applyTheme}1840                  onAccentChange={applyAccentColor}1841                  onTextSizeChange={applyTextSize}1842                  onReduceMotionChange={applyReduceMotion}1843                  shortcuts={shortcutBindings()}1844                  onShortcutsChange={applyShortcuts}1845                  onLicenseChange={async () => {1846                    // After activation/deactivation: refresh Pro status,1847                    // re-load entries (defensive — signal state can drift if1848                    // the SW briefly restarts during the verify+save round-trip),1849                    // and replay the Pro celebration if this is the first time1850                    // a valid Pro license is seen on this device.1851                    await refreshProStatus();1852                    void loadEntries();1853                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1854                    if ((should as { ok: boolean; data?: boolean }).data === true) {1855                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1856                      setView("pro-celebration");1857                      window.setTimeout(() => setView("settings"), 2500);1858                    }1859                  }}1860                  onBack={() => {1861                    setSettingsExiting(true);1862                    window.setTimeout(() => {1863                      setSettingsExiting(false);1864                      setSettingsInitialSection(null);1865                      setUpgradeHighlight(null);1866                      handleBack();1867                    }, 200);1868                  }}1869                  onImport={() => setView("import")}1870                  onExport={() => setView("export")}1871                  onBreachCheckDone={loadEntries}1872                  onOpenHealth={openHealth}1873                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1874                  onOpenFileImport={handleOpenFileImport}1875                  onOpenPanic={() => setView("panic")}1876                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1877                  onOpenCodexRestore={() => setView("codex-restore")}1878                  onCardChange={setSettingsActiveCard}1879                  onProGate={(feature) => {1880                    setUpgradeHighlight(feature);1881                    setSettingsInitialSection("license");1882                  }}1883                />1884              </Suspense>1885            </Show>1886            <Show when={view() === "codex-generate"}>1887              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1888                <CodexGenerateView1889                  isPro={proStatus()}1890                  onBack={() => setView("settings")}1891                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1892                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1893                  onVaultLocked={() => handleLock()}1894                />1895              </Suspense>1896            </Show>1897            <Show when={view() === "codex-restore"}>1898              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1899                <CodexRestoreView1900                  onBack={() => setView("lock")}1901                  onRestoreSuccess={async () => {1902                    // After restore the vault is unlocked; refresh entries1903                    // and route to the main vault list. handleUnlock is the1904                    // canonical post-unlock setup path.1905                    await handleUnlock();1906                  }}1907                />1908              </Suspense>1909            </Show>1910            <Show when={view() === "pair-device"}>1911              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1912                <PairDeviceView1913                  isPro={proStatus()}1914                  onProChanged={() => { void refreshProStatus(); }}1915                  onBack={() => setView("settings")}1916                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1917                />1918              </Suspense>1919            </Show>1920            <Show when={view() === "add"}>1921              <AddView1922                entry={editEntry()}1923                entries={entries()}1924                onBack={handleBack}1925                onSave={handleSave}1926              />1927            </Show>1928            <Show when={view() === "import"}>1929              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1930                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1931              </Suspense>1932            </Show>1933            <Show when={view() === "export"}>1934              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1935                <ExportView onBack={handleExportBack} />1936              </Suspense>1937            </Show>1938            <Show when={view() === "panic"}>1939              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1940                <PanicView1941                  onCancel={() => setView("settings")}1942                  onOpenExport={() => {1943                    setReturnToPanic(true);1944                    setView("export");1945                  }}1946                  onDestroyed={async () => {1947                    clearCanarySuppressions();1948                    setEntries([]);1949                    setSelectedEntry(null);1950                    setEditEntry(undefined);1951                    setHasVault(false);1952                    setOnboarded(false);1953                    setProStatus(false);1954                    setPendingPasskey(null);1955                    setUpgradeHighlight(null);1956                    setSettingsInitialSection(null);1957                    setPendingProNotice(null);1958                    setPendingCelebration(false);1959                    setReturnToPanic(false);1960                    setContentPhase("idle");1961                    setView("lock");1962                  }}1963                />1964              </Suspense>1965            </Show>1966            {/* Health stays mounted while editing an entry from it so1967                computeReused() doesn't rerun on every cancel/back. */}1968            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1969              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1970                <HealthView1971                  entries={entries()}1972                  isPro={proStatus()}1973                  onFixEntry={handleFixEntry}1974                  onBack={() => setView("settings")}1975                  onRefresh={loadEntries}1976                  hidden={view() !== "health"}1977                />1978              </Suspense>1979            </Show>1980            <Show when={view() === "trash"}>1981              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1982                <TrashView1983                  onBack={() => setView("list")}1984                  onRestored={() => void loadEntries()}1985                />1986              </Suspense>1987            </Show>1988            <Show when={showNotes()}>1989              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1990                <NotesMode1991                  notes={entries().filter((e) => e.type === "note")}1992                  initialNoteId={openNoteId()}1993                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1994                  onNoteListChanged={() => void loadEntries()}1995                />1996              </div>1997            </Show>1998            <Show when={restoreView() === "file"}>1999              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2000                <ImportView2001                  mode="onboarding"2002                  replacesExistingVault={true}2003                  onBack={() => setRestoreView(null)}2004                  onImport={async () => {2005                    setRestoreView(null);2006                    await handleUnlock();2007                  }}2008                />2009              </Suspense>2010            </Show>2011            </section>2012            </Show>2013          </Show>2014        </Show>2015      </Show>2016      <Show when={showShortcutsHelp()}>2017        <ShortcutsHelpOverlay2018          bindings={shortcutBindings()}2019          onClose={() => setShowShortcutsHelp(false)}2020        />2021      </Show>2022    </div>2023  );2024}20252026function ShortcutsHelpOverlay(props: {2027  bindings: Record<ShortcutAction, Keybinding>;2028  onClose: () => void;2029}) {2030  return (2031    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>2032      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>2033        <div class="peach-shortcuts-help-head">2034          <h3>Keyboard shortcuts</h3>2035          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>2036        </div>2037        <div class="peach-shortcuts-help-body">2038          <p class="peach-settings-sub-label">ENTRY VIEW</p>2039          <ul>2040            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (2041              <li>2042                <span>{d.label}</span>2043                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2044              </li>2045            ))}2046          </ul>2047          <p class="peach-settings-sub-label">ANYWHERE</p>2048          <ul>2049            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (2050              <li>2051                <span>{d.label}</span>2052                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2053              </li>2054            ))}2055          </ul>2056        </div>2057      </div>2058    </div>2059  );2060}