App.tsx

89.3 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, RESTORE_SOURCE_STORAGE_KEY, type RestoreSource } from "./views/Lock";14import {15  ONBOARDING_CARD_STORAGE_KEY,16  ONBOARDING_LAST_CARD,17  Onboarding,18} from "./views/Onboarding";1920const ONBOARDING_EXIT_STORAGE_KEY = "peach_onboarding_exit";21import { NotesMode } from "./views/NotesMode";22import { ProCelebration } from "./views/ProCelebration";23import { InitialSyncView } from "./views/InitialSyncView";24import { VaultView, type SortOrder } from "./views/Vault";25import { EntryView } from "./views/Entry";26import { AddView } from "./views/Add";27import { PeachWordmark } from "./components/PeachMark";28import { PasskeyApprovalView } from "./views/PasskeyApproval";29import { extractDomain } from "../shared/domain";30import {31  syncIndicator,32  syncIndicatorLabel,33  type SyncOutcomeSummary,34} from "../shared/sync-outcome";35import { popupCopy } from "./copy";36import {37  DEFAULT_BINDINGS,38  formatKeybinding,39  getActiveBindings,40  matchKeybinding,41  SHORTCUT_DESCRIPTORS,42  type Keybinding,43  type ShortcutAction,44} from "../shared/shortcuts";45import { generateTOTP } from "../crypto/totp";46import { isNativePlatform, nativePlugin } from "../shared/native";4748export { sendMessage } from "../shared/bridge";4950const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));51const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));52const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));53const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));54const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));55const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));56const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));57const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));58const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));59const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));6061type View =62  | "lock"63  | "pro-celebration"64  | "entry"65  | "list"66  | "add"67  | "settings"68  | "pair-device"69  | "import"70  | "export"71  | "health"72  | "trash"73  | "panic"74  | "adopting"75  | "initial-sync"76  | "codex-generate"77  | "codex-restore";78type BootState = "loading" | "ready";7980const INITIAL_SYNC_POLL_MS = 500;81const INITIAL_SYNC_SLOW_MS = 15_000;8283const canarySuppressMap = new Map<string, boolean>();84let shellRingAnimation: Animation | null = null;8586export function isCanarySuppressed(entryId: string): boolean {87  return canarySuppressMap.get(entryId) ?? false;88}8990export function setCanarySuppressed(entryId: string, suppressed: boolean): void {91  canarySuppressMap.set(entryId, suppressed);92}9394export function clearCanarySuppressions(): void {95  canarySuppressMap.clear();96}9798export function triggerRing() {99  const shell = document.getElementById("hd-shell");100  if (!shell) return;101102  shellRingAnimation?.cancel();103  shell.dataset.glowing = "true";104  const animation = shell.animate(105    [106      { offset: 0, boxShadow: "var(--copy-shadow)" },107      {108        offset: 0.3,109        boxShadow:110          "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)",111      },112      { offset: 1, boxShadow: "var(--copy-shadow)" },113    ],114    {115      duration: 720,116      easing: "cubic-bezier(0.4, 0, 0.2, 1)",117      fill: "none",118    }119  );120  shellRingAnimation = animation;121  const clearGlow = () => {122    if (shellRingAnimation !== animation) return;123    shellRingAnimation = null;124    delete shell.dataset.glowing;125  };126  animation.onfinish = clearGlow;127  animation.oncancel = clearGlow;128}129130131export function triggerPipPulse() {132  const pip = document.querySelector(".peach-status-pip, .pip");133  if (pip) {134    pip.classList.remove("pulse");135    void (pip as HTMLElement).offsetWidth;136    pip.classList.add("pulse");137  }138}139140const ENTRY_TRANSITION_SETTLE_MS = 135;141142export default function App() {143  const [bootState, setBootState] = createSignal<BootState>("loading");144  const [view, setView] = createSignal<View>("lock");145  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,146  // CSS transition takes over for snap animation).147  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);148  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(149    "enter"150  );151  const [contentTransitioning, setContentTransitioning] = createSignal(false);152  const [hasVault, setHasVault] = createSignal(false);153  const [onboarded, setOnboarded] = createSignal(true);154  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);155  // The restore source picked before the popup closed (the OS file picker156  // kills it), so reopening resumes the same source form instead of the157  // picker. Read from RESTORE_SOURCE_STORAGE_KEY at boot.158  const [resumeRestoreSource, setResumeRestoreSource] = createSignal<RestoreSource | null>(null);159  // Onboarding remounts whenever it leaves (create/adopt/restore) and comes160  // back. Those flows all exit from the final card, so resume there — a fresh161  // install's first mount stays at 0.162  const [onboardingCardAtExit, setOnboardingCardAtExit] = createSignal(0);163  const [entries, setEntries] = createSignal<VaultEntry[]>([]);164  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);165  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);166167  // Rare device-trust alerts stay visible; routine entry sync is silent.168  interface SyncAlert {169    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";170    entryId: string;171    entryTitle: string;172    deviceName: string;173    timestamp: number;174  }175  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);176  // Per-group flip index: which alert within a type-group is currently shown.177  const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});178  async function loadSyncAlerts() {179    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {180      ok: boolean;181      data?: SyncAlert[];182    };183    if (r.ok && (r.data?.length ?? 0) > 0) {184      setSyncAlerts(r.data ?? []);185      // Acknowledge so a crash between read and render doesn't lose them —186      // they remain on screen until the user dismisses each.187      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });188    }189  }190  function dismissAlertGroup(type: string) {191    setSyncAlerts((arr) => arr.filter((a) => a.type !== type));192    setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });193  }194  function flipAlert(type: string, dir: 1 | -1) {195    const group = syncAlerts().filter((a) => a.type === type);196    if (group.length <= 1) return;197    setAlertFlipIdx((m) => {198      const cur = m[type] ?? 0;199      return { ...m, [type]: (cur + dir + group.length) % group.length };200    });201  }202  /** Grouped alert types in display order, each with its alerts. */203  const alertGroups = createMemo(() => {204    const map = new Map<string, SyncAlert[]>();205    for (const a of syncAlerts()) {206      const g = map.get(a.type);207      if (g) g.push(a); else map.set(a.type, [a]);208    }209    return [...map.entries()];210  });211  function syncAlertText(a: SyncAlert): string {212    if (a.type === "DEVICE_REVOKED") {213      return `${a.deviceName} revoked a paired device — review your devices in Settings`;214    }215    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;216  }217  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");218  const [theme, setTheme] = createSignal<"dark" | "light">("dark");219  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");220  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);221  const [lockOnClose, setLockOnClose] = createSignal(false);222  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);223  const [breachMonitoring, setBreachMonitoring] = createSignal(true);224  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);225  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);226  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);227  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);228  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);229  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");230  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");231  // Cached Pro status — synchronous for render paths. Background's232  // GET_LICENSE is async, but render-time reads of isPro() must not block.233  // Refreshed at boot, after activate/deactivate, and whenever the popup234  // re-opens onto a stored license that has changed via another window.235  const [proStatus, setProStatus] = createSignal(false);236  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);237  // When the sync card's pairing button opens the pairing view, deep-link238  // straight into that pairing path instead of the rest screen.239  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");240  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);241  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");242  const [listSearchSeed, setListSearchSeed] = createSignal("");243  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);244  const [pendingCelebration, setPendingCelebration] = createSignal(false);245  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);246  // True while Panic Step 1 has bounced the user out to Export. When Export's247  // onBack fires we return to Panic instead of Settings so the user keeps the248  // destruction context they came from.249  const [returnToPanic, setReturnToPanic] = createSignal(false);250  // The view to return to when the add/edit view is dismissed. Normally "entry"251  // but "health" when the user arrives via the fix-entry path from Vault Health.252  const [editBackView, setEditBackView] = createSignal<View>("entry");253  const [settingsExiting, setSettingsExiting] = createSignal(false);254  const [showNotes, setShowNotes] = createSignal(false);255  // Topbar sync affordance. Always present: gating it on having a paired device256  // meant it never appeared for the person trying to set pairing up, which is257  // exactly when you reach for it.258  const [syncBusy, setSyncBusy] = createSignal(false);259  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);260  // The indicator light + its spoken-word equivalent. Colour alone is not the261  // signal; the title/aria-label always carries the same claim in English.262  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});263  const [pairedCount, setPairedCount] = createSignal(0);264  const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);265  const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);266  let initialSyncWaitGeneration = 0;267  const syncLight = () =>268    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());269  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());270  async function loadSyncIndicator() {271    const [stateRes, devicesRes] = await Promise.all([272      sendMessage({ type: "GET_SYNC_STATE" }),273      sendMessage({ type: "LIST_PAIRED_DEVICES" }),274    ]);275    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };276    if (s.ok && s.data) setSyncSummary(s.data);277    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };278    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);279  }280281  interface InitialSyncPairedDevice extends InitialSyncDevice {282    pairedAt?: number;283  }284285  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {286    const response = (await sendMessage({287      type: "LIST_PAIRED_DEVICES",288    })) as {289      ok: boolean;290      data?: { devices?: InitialSyncPairedDevice[] };291    };292    return response.ok ? response.data?.devices ?? [] : [];293  }294295  async function resolveInitialSyncDeviceId(): Promise<string | null> {296    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(297      () => null,298    );299    const devices = await listInitialSyncDevices().catch(() => []);300    if (stored && devices.some((device) => device.deviceId === stored)) {301      return stored;302    }303304    // Fresh adoption has exactly one direct source, but choosing the newest row305    // also repairs the marker if storage failed after the pair itself committed.306    const newest = [...devices].sort(307      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),308    )[0];309    if (!newest) return stored;310    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(311      () => undefined,312    );313    return newest.deviceId;314  }315316  async function finishInitialSync(generation: number): Promise<void> {317    if (generation !== initialSyncWaitGeneration) return;318    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);319    setInitialSyncDeviceId(null);320    setInitialSyncSlow(false);321    await refreshProStatus();322323    // A license transferred during pairing intentionally leaves the one-shot324    // celebration pending. Consume it only now: sync readiness → celebration325    // → populated vault, never celebration → temporarily empty vault.326    const celebration = (await sendMessage({327      type: "SHOULD_PLAY_CELEBRATION",328    })) as { ok: boolean; data?: boolean };329    const shouldCelebrate = celebration.ok && celebration.data === true;330    if (shouldCelebrate) {331      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });332    }333334    const opened = await openVault(undefined, shouldCelebrate);335    if (!opened || generation !== initialSyncWaitGeneration) return;336    if (shouldCelebrate) {337      setView("pro-celebration");338      window.setTimeout(() => {339        if (generation === initialSyncWaitGeneration) setView("entry");340      }, 2500);341    }342  }343344  async function beginInitialSyncWait(deviceId: string): Promise<void> {345    const generation = ++initialSyncWaitGeneration;346    setInitialSyncDeviceId(deviceId);347    setInitialSyncSlow(false);348    setView("initial-sync");349    const startedAt = Date.now();350351    // Best effort: the pairing write already wakes the mesh listener, while352    // this trigger covers the key-order case where this receiver is the dialer.353    void sendMessage({354      type: "TRIGGER_SYNC",355      payload: { reason: "foreground" },356    }).catch(() => undefined);357358    while (359      generation === initialSyncWaitGeneration &&360      view() === "initial-sync"361    ) {362      try {363        const devices = await listInitialSyncDevices();364        if (hasCompletedInitialSync(devices, deviceId)) {365          await finishInitialSync(generation);366          return;367        }368      } catch {369        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.370      }371      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {372        setInitialSyncSlow(true);373      }374      await new Promise((resolve) =>375        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),376      );377    }378  }379380  async function retryInitialSync(): Promise<void> {381    const deviceId =382      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());383    if (deviceId) {384      await beginInitialSyncWait(deviceId);385    } else {386      setInitialSyncSlow(true);387    }388  }389390  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);391  // Set on popup boot when peach_recovery_pending flag is found in session392  // storage — instructs LockView to skip the unlock UI and open the recovery393  // words confirmation surface instead. Cleared via handleUnlock once the394  // user has typed the 3 confirmation words.395  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);396397  let contentPhaseTimer: number | undefined;398  // Set when the popup was opened from the inline "Open Peach to unlock" button.399  // handleUnlock() closes the popup after unlock so the user returns to the page.400  let openedForInlineUnlock = false;401402  onCleanup(() => {403    initialSyncWaitGeneration += 1;404  });405406  function applyAccent(name: AccentColorName) {407    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;408    const hex = color.hex;409    document.documentElement.style.setProperty("--peach-accent", hex);410    // Ambient surface variables — derived from the accent so surfaces shift411    // subtly toward the accent hue rather than staying fixed warm-brown.412    document.documentElement.style.setProperty("--peach-glow", hex + "2A");413    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");414    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");415  }416417  createEffect(() => {418    applyAccent(accentColor());419  });420421  createEffect(() => {422    document.documentElement.classList.toggle("light", theme() === "light");423    document.body.classList.toggle("light", theme() === "light");424  });425426  createEffect(() => {427    document.documentElement.setAttribute("data-text-size", textSize());428  });429430  createEffect(() => {431    if (reduceMotion()) {432      document.documentElement.setAttribute("data-motion", "reduce");433    } else {434      document.documentElement.removeAttribute("data-motion");435    }436  });437438  // Notes are not a destination of the Entry view; selecting a note opens the439  // notes surface instead (handleSelectEntry). Anything that walks or counts440  // the Entry view's neighbours (counter, prev/next, index) must use this441  // filtered list, otherwise the user can arrow into a note and is stuck —442  // the Entry view can't render a note and the prev/next buttons stop moving.443  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));444445  const selectedIndex = createMemo(() => {446    const currentId = selectedEntry()?.id;447    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;448    return nonNoteEntries().findIndex((entry) => entry.id === currentId);449  });450451  async function applyAccentColor(name: AccentColorName) {452    applyAccent(name);453    setAccentColor(name);454    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });455  }456457  async function applyTheme(t: "dark" | "light") {458    setTheme(t);459    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });460  }461462  async function applyTextSize(size: "small" | "medium" | "large") {463    setTextSize(size);464    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });465  }466467  async function applyReduceMotion(enabled: boolean) {468    setReduceMotion(enabled);469    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });470  }471472  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload473  // small and lets future default updates land for actions the user hasn't474  // touched. Settings sends us the full active map; we filter and store.475  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {476    setShortcutBindings(active);477    const overrides: Record<string, Keybinding> = {};478    for (const action of Object.keys(active) as ShortcutAction[]) {479      const a = active[action];480      const d = DEFAULT_BINDINGS[action];481      const same = a.key === d.key482        && Boolean(a.ctrl)  === Boolean(d.ctrl)483        && Boolean(a.meta)  === Boolean(d.meta)484        && Boolean(a.shift) === Boolean(d.shift)485        && Boolean(a.alt)   === Boolean(d.alt);486      if (!same) overrides[action] = a;487    }488    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });489  }490491  async function applyLockOnClose(enabled: boolean) {492    setLockOnClose(enabled);493    await sendMessage({494      type: "UPDATE_SETTINGS",495      payload: { lockOnClose: enabled },496    });497  }498499  async function applyAutoLockMinutes(minutes: number) {500    setAutoLockMinutes(minutes);501    await sendMessage({502      type: "UPDATE_SETTINGS",503      payload: { autoLockMinutes: minutes },504    });505  }506507  async function applyBreachMonitoring(enabled: boolean) {508    setBreachMonitoring(enabled);509    await sendMessage({510      type: "UPDATE_SETTINGS",511      payload: { breachMonitoring: enabled },512    });513  }514515  // Which onboarding exit flow the user is in (create-vault / restore /516  // adopt). Persisted so closing the popup on one of those screens resumes517  // it directly instead of rewinding to the last carousel card.518  function markOnboardingExit(flow: "create" | "restore" | "adopt") {519    setOnboardingCardAtExit(ONBOARDING_LAST_CARD);520    void storageSet(ONBOARDING_EXIT_STORAGE_KEY, flow).catch(() => {});521    // Backing out of the flow remounts the carousel at this card; keep the522    // persisted card in sync so a later popup close resumes consistently.523    void storageSet(ONBOARDING_CARD_STORAGE_KEY, String(ONBOARDING_LAST_CARD)).catch(() => {});524  }525  function clearOnboardingExit() {526    void storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});527    void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});528    setResumeRestoreSource(null);529  }530531  onMount(async () => {532    // Resolve the active tab in parallel with the unlock/has-vault queries —533    // openVault()'s smart selection picks the entry matching currentTabDomain,534    // so it must be populated before openVault runs. Previously refreshCurrentTab535    // ran after openVault, leaving popups that booted already-unlocked falling536    // back to loadedEntries[0] instead of the domain match.537    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([538      sendMessage({ type: "IS_UNLOCKED" }),539      sendMessage({ type: "HAS_VAULT" }),540      refreshCurrentTab(),541      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),542    ]);543    const unlocked = Boolean(544      (unlockResponse as { ok: boolean; data?: boolean }).data545    );546    const vaultExists = Boolean(547      (vaultResponse as { ok: boolean; data?: boolean }).data548    );549    const shouldCelebrate = Boolean(550      (celebrationResponse as { ok: boolean; data?: boolean }).data551    );552    setHasVault(vaultExists);553    // Onboarding gate — show once on first install, never again. Existing554    // users (vaultExists) are auto-marked onboarded so they skip the flow555    // even on the very first popup open after this feature ships.556    try {557      const onboarded = await storageGet("peach_onboarded");558      const seen = onboarded === "true";559      if (vaultExists && !seen) {560        await storageSet("peach_onboarded", "true");561        await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});562        await storageRemove(ONBOARDING_EXIT_STORAGE_KEY).catch(() => {});563        await storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});564        setOnboarded(true);565      } else {566        setOnboarded(seen);567        if (!seen) {568          // A popup close while the user is in an exit flow (create-vault /569          // restore / adopt) resumes that flow directly — landing back on the570          // carousel one screen earlier reads as losing progress.571          const exit = await storageGet(ONBOARDING_EXIT_STORAGE_KEY).catch(() => null);572          if (exit === "create" || exit === "restore" || exit === "adopt") {573            setOnboardingCardAtExit(ONBOARDING_LAST_CARD);574            setOnboarded(true);575            setStartOnboardingRestore(exit === "restore");576            if (exit === "restore") {577              // The OS file picker kills the action popup mid-restore, so the578              // surface resumes on the source the user had already picked.579              const source = await storageGet(RESTORE_SOURCE_STORAGE_KEY).catch(() => null);580              if (source === "symbols" || source === "codex" || source === "csv") {581                setResumeRestoreSource(source);582              }583            }584            if (exit === "adopt") setView("adopting");585          } else {586            // Otherwise resume mid-onboarding where the user left off instead587            // of rewinding to the opening card.588            const stored = Number(589              await storageGet(ONBOARDING_CARD_STORAGE_KEY).catch(() => null),590            );591            if (592              Number.isInteger(stored) &&593              stored > 0 &&594              stored <= ONBOARDING_LAST_CARD595            ) {596              setOnboardingCardAtExit(stored);597            }598          }599        }600      }601    } catch {602      // storage unavailable — default to onboarded so we never block boot603      setOnboarded(true);604    }605    await Promise.all([restoreSettings(), refreshProStatus()]);606607    const pendingInitialSyncMarker =608      unlocked && vaultExists609        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)610        : null;611    const pendingInitialSyncDeviceId = pendingInitialSyncMarker612      ? await resolveInitialSyncDeviceId()613      : null;614615    // Mark played before any animation so a crash mid-sequence never replays616    // it. A newly adopted receiver deliberately defers this until its first617    // real sync finishes, preserving initial sync → celebration → vault.618    if (shouldCelebrate && !pendingInitialSyncDeviceId) {619      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });620    }621622    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome623    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.624    if (unlocked && vaultExists) {625      void sendMessage({626        type: "TRIGGER_SYNC",627        payload: { reason: "foreground" },628      });629      void loadSyncIndicator();630      // Rare device-trust alerts only; routine entry sync stays quiet.631      void loadSyncAlerts();632    }633634    // If the user created a vault but hasn't yet confirmed their recovery635    // words, route back to the recovery-words screen instead of opening the636    // entries view. The flag lives in chrome.storage.local so it survives637    // both popup close (SW suppresses lock-on-close) and full browser638    // restart (handleUnlock checks the same flag after a fresh password639    // unlock). Cleared when confirmation succeeds.640    let recoveryPending = false;641    try {642      const out = await chrome.storage.local?.get("peach_recovery_pending");643      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";644    } catch { /* best-effort */ }645646    // If this popup was opened from the inline "Open Peach to unlock" button,647    // the background set a session flag. Read and clear it so handleUnlock()648    // can close the popup after unlock and return the user to the page.649    if (chrome.storage.session) {650      try {651        const s = await chrome.storage.session.get("peach_inline_unlock");652        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {653          openedForInlineUnlock = true;654          await chrome.storage.session.remove("peach_inline_unlock");655        }656      } catch { /* best-effort */ }657    }658659    // Native: closing the app before recovery-words confirmation means the660    // user didn't finish vault creation. Throw the partial vault away and661    // restart onboarding rather than asking them to unlock a vault they662    // never finished creating. Desktop keeps the existing "unlock to663    // resume" flow because closing the popup there is much more casual.664    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {665      try {666        await chrome.storage.local?.remove([667          "peach_vault_a",668          "peach_vault_b",669          "peach_recovery_pending",670          "peach_onboarded",671          "peach_vault_history",672          ONBOARDING_CARD_STORAGE_KEY,673          ONBOARDING_EXIT_STORAGE_KEY,674        ]);675      } catch { /* best-effort */ }676      setHasVault(false);677      setOnboarded(false);678      setView("lock");679      setBootState("ready");680      return;681    }682683    if (recoveryPending && unlocked) {684      // forceRecoveryWords overrides LockView's hasVault gate so the685      // recovery surface renders even though the vault now exists.686      setForceRecoveryWords(true);687      setView("lock");688    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {689      void beginInitialSyncWait(pendingInitialSyncDeviceId);690    } else if (unlocked && vaultExists) {691      await openVault(undefined, shouldCelebrate);692      if (shouldCelebrate) {693        setView("pro-celebration");694        window.setTimeout(() => setView("entry"), 2500);695      }696    } else if (shouldCelebrate) {697      setPendingCelebration(true);698    }699700    await refreshPendingPasskey();701702    // Track tab changes so smart sort stays current703    const handleTabActivated = () => { void refreshCurrentTab(); };704    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {705      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();706    };707    try {708      chrome.tabs.onActivated.addListener(handleTabActivated);709      chrome.tabs.onUpdated.addListener(handleTabUpdated);710      onCleanup(() => {711        chrome.tabs.onActivated.removeListener(handleTabActivated);712        chrome.tabs.onUpdated.removeListener(handleTabUpdated);713      });714    } catch {715      // tabs permission may not be available in all contexts716    }717718    setBootState("ready");719720    // Deep-link: ?codex=pdf opens a detached window straight into the721    // Codex restore flow with auto-picked PDF. The action popup can't host722    // a file dialog without dismissing itself, so this is the only way the723    // PDF import path survives. See CodexRestoreView.openPdfPicker().724    try {725      const route = new URLSearchParams(window.location.search).get("codex");726      if (route === "pdf" || route === "restore") {727        setView("codex-restore");728      }729    } catch {730      // location.search unavailable — ignore.731    }732733    // Check for pending session-storage notices from the background.734    if (chrome.storage.session) {735      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as736        Record<string, { feature?: string } | undefined>;737      if (session.pendingProGate?.feature) {738        await chrome.storage.session.remove("pendingProGate");739        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);740        setSettingsInitialSection("license");741        setView("settings");742      } else if (session.pendingProNotice?.feature) {743        await chrome.storage.session.remove("pendingProNotice");744        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });745      }746    }747748    // Warm the lazy-module cache so the Suspense fallback never shows for749    // locally-bundled extension views. Without this, the first navigation to750    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which751    // covers the shell and absorbs clicks on the header.752    void Promise.all([753      import("./views/Settings").catch(() => {}),754      import("./views/Import").catch(() => {}),755      import("./views/Export").catch(() => {}),756      import("./views/Health").catch(() => {}),757      import("./views/TrashView").catch(() => {}),758    ]);759760    // Lock-on-close via a persistent port. sendMessage in pagehide is761    // unreliable — the popup context tears down before the message lands.762    // The SW's onConnect listener locks when this port disconnects.763    let popupPort: chrome.runtime.Port | null = null;764    try {765      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect766      // listener accepts the "popup-" prefix; the random suffix is defence in767      // depth against a port named exactly "popup" from anything but our popup.768      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });769    } catch { /* extension context invalidated — ignore */ }770    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });771772    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only773    // reliable signal is appStateChange — setTimeout is killed when the OS774    // backgrounds the app. We measure elapsed background time on resume.775    if (isNativePlatform()) {776      let backgroundedAt: number | null = null;777778      const CapApp = nativePlugin<{779        addListener: (780          ev: string,781          cb: (s: { isActive: boolean }) => void,782        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };783      }>("App");784      if (CapApp?.addListener) {785        const sub = CapApp.addListener(786          "appStateChange",787          ({ isActive }: { isActive: boolean }) => {788            if (!isActive) {789              backgroundedAt = Date.now();790              return;791            }792            if (backgroundedAt !== null && autoLockMinutes() > 0) {793              const elapsed = Date.now() - backgroundedAt;794              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();795            }796            backgroundedAt = null;797          }798        );799        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.800        onCleanup(() => {801          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});802        });803      }804805      // L12/COR-011: foreground idle autolock. appStateChange only fires when806      // the OS backgrounds the app — if the user idles with the screen on,807      // chrome.alarms is no-op'd in Capacitor so the vault would stay open808      // indefinitely. Poll every 30s and lock if elapsed since last user809      // interaction exceeds autoLockMinutes.810      let lastUserActivityAt = Date.now();811      const bumpActivity = () => { lastUserActivityAt = Date.now(); };812      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;813      for (const ev of ACTIVITY_EVENTS) {814        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });815      }816      const idleLockInterval = setInterval(() => {817        const minutes = autoLockMinutes();818        if (!minutes || minutes <= 0) return;819        const elapsed = Date.now() - lastUserActivityAt;820        if (elapsed >= minutes * 60_000) {821          lastUserActivityAt = Date.now();822          handleHeaderLock();823        }824      }, 30_000);825      onCleanup(() => {826        clearInterval(idleLockInterval);827        for (const ev of ACTIVITY_EVENTS) {828          document.removeEventListener(ev, bumpActivity, { capture: true });829        }830      });831832      // The retired native peer-discovery trigger went with the old Capacitor833      // pairing plugin. Reconnection is address-cache first, subnet probe second834      // (sync-runner.ts); relocating a peer that changed networks is an835      // Android-side discovery concern now.836      if (isNativePlatform()) {837        // Android runs the background/sync dispatcher in-process with the838        // popup, so the production runner has to be registered from the839        // UI bootstrap path instead of the MV3 service-worker entry.840        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>841          import("../background/sync-runner").then(({ productionSyncRunner }) => {842            setSyncRunner(productionSyncRunner);843            void hydratePersistedSyncState();844          })845        );846      }847    }848849    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale850    // entries instead of waiting for the next GET_ENTRIES round-trip.851    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {852      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();853      if (msg?.type === "SYNC_STATE_CHANGED") {854        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);855      }856      if (msg?.type === "PRO_GATE_TRIGGERED") {857        setUpgradeHighlight(msg.payload?.feature ?? null);858        setSettingsInitialSection("license");859        setView("settings");860      }861    };862    chrome.runtime.onMessage.addListener(handleRuntimeMessage);863    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));864865    // Android hardware/gesture back. MainActivity fires peach:back; the popup866    // decides what "back" means per surface. Lock+no-vault is the common case867    // — return to onboarding rather than letting the OS dismiss the activity.868    const handlePeachBack = () => {869      // Notes mode captures back first870      if (showNotes()) {871        setShowNotes(false);872        setOpenNoteId(undefined);873        return;874      }875      const v = view();876      if (v === "lock" && !hasVault() && onboarded()) {877        setOnboarded(false);878        return;879      }880      if (v === "list") { setView("entry"); return; }881      if (v === "settings") {882        window.dispatchEvent(new Event("peach:settings-back"));883        return;884      }885      if (v === "import" || v === "health") { setView("settings"); return; }886      if (v === "export") { handleExportBack(); return; }887      if (v === "add") { handleBack(); return; }888      if (v === "pair-device") { setView("settings"); return; }889    };890    window.addEventListener("peach:back", handlePeachBack);891    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));892893    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that894    // peeks from the bottom (search bar handle visible) and drags up to fill895    // the screen. dragOffset is the LIVE finger offset during a drag, in px,896    // 0 when no drag in progress. The wrapper element computes transform =897    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.898    if (isNativePlatform()) {899      let touchStartY = 0;900      let touchStartX = 0;901      let lastY = 0;902      let lastT = 0;903      let dragging = false;904      let captured = false;905      const HORIZONTAL_TOLERANCE = 16;906      const ACTIVATION_DY = 8;907      const PEEK_PX = 60;908909      const onTouchStart = (e: TouchEvent) => {910        const t = e.touches[0];911        if (!t) return;912        const v = view();913        if (v !== "entry" && v !== "list") return;914        // Entry view: only intercept drags starting in the bottom 40%.915        // List view: intercept drags starting in the top 35% (the search/handle row).916        const inBand = v === "entry"917          ? t.clientY > window.innerHeight * 0.6918          : t.clientY < window.innerHeight * 0.35;919        if (!inBand) return;920        touchStartY = lastY = t.clientY;921        touchStartX = t.clientX;922        lastT = e.timeStamp;923        dragging = true;924        captured = false;925      };926927      const onTouchMove = (e: TouchEvent) => {928        if (!dragging) return;929        const t = e.touches[0];930        if (!t) return;931        const dy = t.clientY - touchStartY;932        const dx = Math.abs(t.clientX - touchStartX);933934        if (!captured) {935          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {936            // Looks like a horizontal swipe — release.937            dragging = false;938            return;939          }940          if (Math.abs(dy) < ACTIVATION_DY) return;941          captured = true;942        }943944        // Translate the sheet by dy from its rest (peek) position. Peek is945        // (viewport height - PEEK_PX). Open is 0.946        const v = view();947        const restClosed = window.innerHeight - PEEK_PX;948        const baseTranslate = v === "list" ? 0 : restClosed;949        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));950        setSheetTranslate(next);951        lastY = t.clientY;952        lastT = e.timeStamp;953      };954955      const onTouchEnd = (e: TouchEvent) => {956        if (!dragging) { return; }957        const t = e.changedTouches[0];958        const elapsed = Math.max(1, e.timeStamp - lastT);959        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms960        const wasCaptured = captured;961        dragging = false;962        captured = false;963        const v = view();964965        if (!wasCaptured) {966          // Tap in the peek strip while in entry view → open the vault list.967          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");968          setSheetTranslate(null);969          return;970        }971972        const restClosed = window.innerHeight - PEEK_PX;973        const current = sheetTranslate() ?? restClosed;974975        // Snap rules:976        //   - Strong upward velocity → open977        //   - Strong downward velocity → close978        //   - Otherwise snap to whichever rest is closer979        let nextOpen: boolean;980        if (velocity < -0.05) nextOpen = true;981        else if (velocity > 0.05) nextOpen = false;982        else nextOpen = current < restClosed * 0.5;983984        if (nextOpen && v !== "list") setView("list");985        if (!nextOpen && v !== "entry") setView("entry");986        // Release the live offset so CSS transition handles the snap.987        setSheetTranslate(null);988      };989990      document.addEventListener("touchstart", onTouchStart, { passive: true });991      document.addEventListener("touchmove",  onTouchMove,  { passive: true });992      document.addEventListener("touchend",   onTouchEnd,   { passive: true });993      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });994      onCleanup(() => {995        document.removeEventListener("touchstart", onTouchStart);996        document.removeEventListener("touchmove",  onTouchMove);997        document.removeEventListener("touchend",   onTouchEnd);998      });999    }10001001    // Action handlers — keyed by ShortcutAction. The dispatcher below tests1002    // each binding against the event and runs the matching handler. New1003    // shortcuts only need an entry here; the binding is data, not code.1004    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {1005      copy_password: () => {1006        const entry = selectedEntry();1007        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });1008      },1009      copy_username: () => {1010        const entry = selectedEntry();1011        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });1012      },1013      copy_totp: () => {1014        const entry = selectedEntry();1015        if (!entry?.totp) return;1016        try {1017          const { code } = generateTOTP(entry.totp);1018          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });1019        } catch { /* invalid TOTP secret — silent */ }1020      },1021      new_entry: () => handleAdd(),1022      edit_entry: () => {1023        const entry = selectedEntry();1024        // Passkey-only entries have nothing user-editable in the Add view; the1025        // passkey credential itself is opaque. Skip the edit action for them.1026        if (!entry || isPasskeyOnly(entry)) return;1027        setEditEntry(entry);1028        setView("add");1029      },1030      delete_entry: () => {1031        if (selectedEntry()) void handleDelete();1032      },1033      lock_vault: () => { void handleHeaderLock(); },1034      search: () => openList(),1035      nav_prev: () => navigate(-1),1036      nav_next: () => navigate(1),1037      jump_vault: () => setView("entry"),1038      jump_settings: () => setView("settings"),1039      show_help: () => setShowShortcutsHelp(true),1040    };10411042    // Actions that are MEANINGFUL only on the entry-detail view. Outside1043    // that scope the binding is dormant — pressing C while on Settings1044    // does nothing rather than awkwardly copying from a now-stale entry.1045    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([1046      "copy_password", "copy_username", "copy_totp",1047      "edit_entry", "delete_entry", "nav_prev", "nav_next",1048    ]);10491050    const handleGlobalKeydown = (e: KeyboardEvent) => {1051      const v = view();1052      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"1053        || (e.target as HTMLElement)?.tagName === "TEXTAREA"1054        || (e.target as HTMLElement)?.isContentEditable;1055      const isPrintableSearchKey =1056        e.key.length === 1 &&1057        !e.ctrlKey &&1058        !e.metaKey &&1059        !e.altKey;10601061      // No shortcuts while a full-screen surface owns the whole viewport:1062      // the lock screen, the post-pairing readiness sequence, or the Pro1063      // celebration. Without this the lock screen is at the mercy of whatever1064      // single-key binding is active — e.g. typing "n" in a password that1065      // slips out of focus triggers `new_entry` and escapes the lock screen.1066      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;10671068      // Help dialog: Escape closes it; eat the keypress so it doesn't1069      // also navigate away from the underlying view.1070      if (showShortcutsHelp()) {1071        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }1072        return;1073      }10741075      // ── Escape — fixed binding (not user-customizable) ───────1076      if (e.key === "Escape") {1077        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }1078        if (v === "list") { setView("entry"); return; }1079        if (v === "settings" || v === "add") { handleBack(); return; }1080        if (v === "import" || v === "health") { setView("settings"); return; }1081        if (v === "export") { handleExportBack(); return; }1082        if (v === "pair-device") { setView("settings"); return; }1083      }10841085      // Bindings-driven dispatch. Single-key letter bindings without1086      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is1087      // inside an input, so users can type into search/forms normally.1088      const bindings = shortcutBindings();1089      for (const action of Object.keys(bindings) as ShortcutAction[]) {1090        const binding = bindings[action];1091        if (!matchKeybinding(e, binding)) continue;1092        // Single-key letter bindings need the input-focus guard. Bindings1093        // with any modifier are safe — Ctrl+L doesn't conflict with typing.1094        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;1095        if (!hasMod && binding.key.length === 1 && inInput) return;1096        if (ENTRY_SCOPED.has(action) && v !== "entry") return;1097        e.preventDefault();1098        SHORTCUT_HANDLERS[action]?.();1099        return;1100      }11011102      // Type-to-search: in entry view, any printable key not consumed by a1103      // shortcut above primes the list search seed and opens the list.1104      // Kept outside the bindings table because it's a behavior, not a1105      // discrete action — every printable character can trigger it.1106      if (v === "entry" && !inInput && isPrintableSearchKey) {1107        e.preventDefault();1108        primeListSearch(e.key);1109        return;1110      }1111    };1112    window.addEventListener("keydown", handleGlobalKeydown);1113    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));11141115    const handleStorageChanged = (1116      changes: Record<string, chrome.storage.StorageChange>,1117      areaName: string1118    ) => {1119      if (areaName !== "session") return;1120      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {1121        return;1122      }1123      void refreshPendingPasskey();1124    };1125    chrome.storage.onChanged.addListener(handleStorageChanged);1126    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));1127  });11281129  async function refreshCurrentTab() {1130    try {1131      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1132      const url = tab?.url ?? tab?.pendingUrl ?? "";1133      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");1134      // Skip extension/internal URLs — adding chrome://, about:, or1135      // chrome-extension:// to a vault entry is never what the user wants.1136      const isWebUrl = /^https?:\/\//i.test(url);1137      setCurrentTabUrl(isWebUrl ? url : "");1138    } catch {1139      setCurrentTabDomain("");1140      setCurrentTabUrl("");1141    }1142  }11431144  async function refreshPendingPasskey() {1145    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });1146    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);1147  }11481149  async function refreshProStatus() {1150    const res = await sendMessage({ type: "GET_LICENSE" });1151    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;1152    setProStatus(Boolean(data?.valid && data?.plan === "pro"));1153  }11541155  async function restoreSettings() {1156    const res = await sendMessage({ type: "GET_SETTINGS" });1157    const s = (res as { ok: boolean; data?: any }).data ?? {};1158    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {1159      setAccentColor(s.accentColor as AccentColorName);1160    }1161    setTheme(s.theme === "light" ? "light" : "dark");1162    if (s.textSize === "small" || s.textSize === "large") {1163      setTextSize(s.textSize);1164    } else {1165      setTextSize("medium");1166    }1167    setReduceMotion(s.reduceMotion === true);1168    setLockOnClose(s.lockOnClose === true);1169    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);1170    setBreachMonitoring(s.breachMonitoring !== false);1171    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);1172    setShortcutBindings(getActiveBindings(s.shortcuts));1173  }11741175  async function applyTrashRetention(days: number) {1176    setTrashRetentionDays(days);1177    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });1178  }11791180  function primeListSearch(seed: string) {1181    setListSearchSeed(seed);1182    setListSearchSeedNonce((value) => value + 1);1183    openList();1184  }11851186  // Returns null when it detected a dead service worker and triggered handleLock().1187  // Callers that need to abort (e.g. openVault) check for null rather than relying1188  // on view() state, which may already be "lock" during normal startup flows.1189  async function loadEntries(): Promise<VaultEntry[] | null> {1190    const response = await sendMessage({ type: "GET_ENTRIES" });1191    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };11921193    // If the service worker was killed and restarted (MV3 workers sleep), the1194    // vault will be locked again — or the worker may not respond at all.1195    // In either case, send the user to the lock screen rather than silently1196    // showing an empty vault (which looks like data loss).1197    if (!res.ok) {1198      if (1199        res.error === "vault_locked" ||1200        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1201        (typeof res.error === "string" && res.error.includes("locked"))1202      ) {1203        handleLock();1204        return null; // signal emergency lock to callers1205      }1206      return [];1207    }12081209    const loadedEntries = res.data ?? [];1210    setEntries(loadedEntries);12111212    const currentId = selectedEntry()?.id;1213    if (currentId) {1214      setSelectedEntry(1215        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1216      );1217    }12181219    return loadedEntries;1220  }12211222  async function openVault(preferredEntryId?: string, skipViewSet = false) {1223    // Purge expired trash entries on each vault open1224    const retDays = trashRetentionDays();1225    if (retDays > 0) {1226      void sendMessage({1227        type: "PURGE_EXPIRED_TRASH",1228        payload: { retentionMs: retDays * 86_400_000 },1229      });1230    }12311232    const loadedEntries = await loadEntries();12331234    // null means loadEntries() triggered an emergency lock (service worker died).1235    // Don't override it by setting view back to "entry" with an empty vault.1236    if (loadedEntries === null) return false;12371238    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1239    let nextSelectedEntry: VaultEntry | null = null;1240    if (preferredEntryId) {1241      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1242    }1243    if (!nextSelectedEntry) {1244      const tabDomain = currentTabDomain();1245      if (tabDomain) {1246        nextSelectedEntry = loadedEntries.find((e) => {1247          if (e.type === "login") {1248            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1249            for (const extra of e.additionalUrls ?? []) {1250              if ((extractDomain(extra) ?? "") === tabDomain) return true;1251            }1252            return false;1253          }1254          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1255          return false;1256        }) ?? null;1257      }1258    }1259    nextSelectedEntry ??= pickNavigable(loadedEntries);12601261    setSelectedEntry(nextSelectedEntry);1262    setEditEntry(undefined);1263    setContentTransitioning(false);1264    setContentPhase("enter");1265    queueContentIdle();1266    if (!skipViewSet) setView("entry");1267    return true;1268  }12691270  async function handleUnlock() {1271    // If the user previously created a vault but hadn't yet confirmed their1272    // recovery words (and the browser was closed before they could), the1273    // peach_recovery_pending flag is still set in storage.local. Re-route1274    // back to the recovery surface so they finish the confirmation step1275    // before reaching the entries view — the words can be re-derived now1276    // that the vault is unlocked again.1277    let recoveryPending = false;1278    try {1279      const out = await chrome.storage.local?.get("peach_recovery_pending");1280      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1281    } catch { /* best-effort */ }1282    if (recoveryPending) {1283      setForceRecoveryWords(true);1284      setView("lock");1285      triggerPipPulse();1286      await restoreSettings();1287      return;1288    }1289    setHasVault(true);1290    triggerPipPulse();1291    await restoreSettings();1292    const celebrating = pendingCelebration();1293    if (celebrating) {1294      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1295      setPendingCelebration(false);1296    }1297    await openVault(undefined, celebrating);1298    if (celebrating) {1299      setView("pro-celebration");1300      window.setTimeout(() => setView("entry"), 2500);1301    }1302    // Popup was opened from the inline "Open Peach to unlock" button — close it1303    // now so the user lands back on the page with the autofill selector ready.1304    if (openedForInlineUnlock) {1305      openedForInlineUnlock = false;1306      window.close();1307    }1308  }13091310  function handleSelectEntry(entry: VaultEntry) {1311    if (entry.type === "note") {1312      setOpenNoteId(entry.id);1313      setShowNotes(true);1314      return;1315    }1316    setSelectedEntry(entry);1317    setContentTransitioning(false);1318    setContentPhase("enter");1319    queueContentIdle();1320    setView("entry");1321  }13221323  function handleAdd() {1324    setEditEntry(undefined);1325    setView("add");1326  }13271328  async function handleDelete() {1329    const entry = selectedEntry();1330    if (!entry) return;1331    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1332    const loadedEntries = await loadEntries() ?? [];1333    setSelectedEntry(pickNavigable(loadedEntries));1334    setView("entry");1335  }13361337  async function handleDeleteMany(ids: string[]) {1338    for (const id of ids) {1339      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1340    }1341    const loadedEntries = await loadEntries() ?? [];1342    // If the currently selected entry was among the deleted, move to first1343    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1344    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1345  }13461347  async function handleSave(savedEntry?: VaultEntry) {1348    await openVault(savedEntry?.id);1349  }13501351  function handleBack() {1352    const dest = editBackView();1353    setEditBackView("entry");1354    setEditEntry(undefined);1355    setView(dest);1356  }13571358  function handleExportBack() {1359    if (returnToPanic()) {1360      setReturnToPanic(false);1361      setView("panic");1362      return;1363    }1364    setView("settings");1365  }13661367  function handleLock() {1368    clearCanarySuppressions();1369    setEntries([]);1370    setSelectedEntry(null);1371    setEditEntry(undefined);1372    setContentPhase("idle");1373    setView("lock");1374  }13751376  function handleHeaderLock() {1377    // Lock the UI immediately — do not wait for the service worker. If the SW1378    // is dead or slow, the 5s sendMessage timeout would create a dead-click1379    // window. The SW will lock on its next wake regardless.1380    handleLock();1381    void sendMessage({ type: "LOCK" });1382  }13831384  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1385  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1386  // the trigger's own reply.1387  async function handleHeaderSync(): Promise<void> {1388    if (syncBusy()) return;1389    setSyncBusy(true);1390    setSyncFlash(null);1391    try {1392      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1393      let state: SyncOutcomeSummary = { status: "syncing" };1394      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1395        await new Promise((r) => setTimeout(r, 250));1396        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1397          ok: boolean;1398          data?: SyncOutcomeSummary;1399        };1400        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1401      }1402      setSyncSummary(state);1403      setSyncFlash(state.status === "error" ? "error" : "ok");1404      await loadSyncAlerts();1405      await loadEntries();1406      await loadSyncIndicator();1407    } catch {1408      setSyncSummary({ status: "error", outcome: "run_failed" });1409      setSyncFlash("error");1410    } finally {1411      setSyncBusy(false);1412      setTimeout(() => setSyncFlash(null), 2_000);1413    }1414  }14151416  function navigate(dir: number) {1417    const navigable = nonNoteEntries();1418    if (navigable.length === 0) return;1419    const currentIndex = selectedIndex();1420    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1421    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1422    setSelectedEntry(navigable[nextIndex]);1423    setContentPhase("enter");1424    queueContentIdle();1425  }14261427  /**1428   * The Entry view's selection invariant: never select a note. Notes are a1429   * separate surface (handleSelectEntry opens the notes view), so any code path1430   * that picks a default — vault open, post-delete, refresh — must skip them1431   * and return null if the only entries are notes.1432   */1433  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1434    return list.find((e) => e.type !== "note") ?? null;1435  }14361437  function openList() {1438    setView("list");1439  }14401441  function openHealth() {1442    setEditEntry(undefined);1443    setView("health");1444  }14451446  function handleOpenFileImport() {1447    setRestoreView("file");1448  }14491450  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;14511452  function handleFixEntry(entry: VaultEntry) {1453    setSelectedEntry(entry);1454    // Passkey-only entries have no editable surface — drop into view mode1455    // instead of opening the Add editor.1456    if (isPasskeyOnly(entry)) {1457      setView("entry");1458      return;1459    }1460    setEditBackView(view()); // preserve caller view so back returns here1461    setEditEntry(entry);1462    setView("add");1463  }14641465  const isLockedView = () => view() === "lock" || view() === "adopting";14661467  async function handleAdoptionDone() {1468    await storageSet("peach_onboarded", "true").catch(() => {});1469    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1470    clearOnboardingExit();1471    setOnboarded(true);1472    setHasVault(true);1473    setView("initial-sync");1474    // The background applies a Pro license and persists the source-device1475    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1476    // celebration pending until that exact peer records a completed sync.1477    await refreshProStatus();1478    const deviceId = await resolveInitialSyncDeviceId();1479    if (deviceId) {1480      void beginInitialSyncWait(deviceId);1481    } else {1482      // Pairing completion without a durable peer row should be impossible.1483      // Stay on the honest waiting surface and expose retry instead of falling1484      // through to an empty vault.1485      setInitialSyncSlow(true);1486    }1487  }14881489  async function handleApprovePendingPasskey() {1490    const pending = pendingPasskey();1491    if (!pending) return;1492    if (pending.browser === "firefox" && pending.type === "create") {1493      // Firefox path: popup itself runs navigator.credentials.create. The1494      // background never approved/rejected anything — it just stashed1495      // intent. After the popup-driven flow resolves (success or cancel),1496      // clear the pending key so the popup doesn't re-show this on next open.1497      const { createFirefoxPasskey } = await import("./firefox-passkey");1498      const result = await createFirefoxPasskey(pending);1499      if (!result.ok) {1500        console.warn("Peach Firefox passkey create failed:", result.error);1501      }1502      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1503      setPendingPasskey(null);1504      void loadEntries();1505      window.close();1506      return;1507    }1508    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1509    window.close();1510  }15111512  async function handleDenyPendingPasskey() {1513    const pending = pendingPasskey();1514    if (!pending) return;1515    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1516    window.close();1517  }15181519  function queueContentIdle(after?: () => void) {1520    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1521    contentPhaseTimer = window.setTimeout(() => {1522      setContentPhase("idle");1523      after?.();1524    }, ENTRY_TRANSITION_SETTLE_MS);1525  }15261527  return (1528    <div class="popup-root peach-theme">1529      <Show when={bootState() === "ready"}>1530        <Show1531          when={!pendingPasskey()}1532          fallback={1533            <PasskeyApprovalView1534              type={pendingPasskey()!.type}1535              rpName={pendingPasskey()!.rpName}1536              rpId={pendingPasskey()!.rpId}1537              userName={pendingPasskey()!.userName}1538              userDisplayName={pendingPasskey()!.userDisplayName}1539              onApprove={handleApprovePendingPasskey}1540              onDeny={handleDenyPendingPasskey}1541            />1542          }1543        >1544          <Show1545            when={!isLockedView()}1546            fallback={1547              <Show1548                when={view() !== "adopting"}1549                fallback={1550                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1551                    <AdoptVaultView1552                      onCancel={() => {1553                        clearOnboardingExit();1554                        setOnboarded(false);1555                        setView("lock");1556                      }}1557                      onDone={handleAdoptionDone}1558                    />1559                  </Suspense>1560                }1561              >1562                <Show1563                  when={onboarded() || hasVault()}1564                  fallback={1565                    <Onboarding1566                      initialCard={onboardingCardAtExit()}1567                      onComplete={() => {1568                        markOnboardingExit("create");1569                        setStartOnboardingRestore(false);1570                        setOnboarded(true);1571                      }}1572                      onRestore={() => {1573                        markOnboardingExit("restore");1574                        setStartOnboardingRestore(true);1575                        setOnboarded(true);1576                      }}1577                      onAdopt={() => {1578                        markOnboardingExit("adopt");1579                        setStartOnboardingRestore(false);1580                        setOnboarded(true);1581                        setView("adopting");1582                      }}1583                    />1584                  }1585                >1586                  <LockView1587                    hasVault={hasVault()}1588                    ready={bootState() === "ready"}1589                    isPro={proStatus()}1590                    forceRecoveryWords={forceRecoveryWords()}1591                    initialRestore={startOnboardingRestore()}1592                    initialRestoreSource={resumeRestoreSource() ?? undefined}1593                    onUnlock={() => {1594                      // RecoveryWordDisplay clears the storage flag before1595                      // calling onDone, so handleUnlock will see no pending1596                      // confirmation and proceed through the normal path.1597                      if (forceRecoveryWords()) setForceRecoveryWords(false);1598                      // The create/restore flow is done — a lock later in this1599                      // window must show the unlock screen, not re-enter the1600                      // onboarding restore surface.1601                      setStartOnboardingRestore(false);1602                      setResumeRestoreSource(null);1603                      void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1604                      return handleUnlock();1605                    }}1606                    onBackToOnboarding={1607                      !hasVault()1608                        ? () => {1609                            // Deliberately rewinding to the carousel — the exit1610                            // flow must not reclaim the next popup open.1611                            clearOnboardingExit();1612                            setStartOnboardingRestore(false);1613                            setOnboarded(false);1614                          }1615                        : undefined1616                    }1617                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1618                  />1619                </Show>1620              </Show>1621            }1622          >1623            <Show1624              when={1625                view() !== "pro-celebration" &&1626                view() !== "initial-sync"1627              }1628              fallback={1629                <Show1630                  when={view() === "initial-sync"}1631                  fallback={<ProCelebration />}1632                >1633                  <InitialSyncView1634                    slow={initialSyncSlow()}1635                    onRetry={() => void retryInitialSync()}1636                  />1637                </Show>1638              }1639            >1640            <section1641              id="hd-shell"1642              class="peach-shell peach-theme"1643              data-surface="extension"1644            >1645            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1646              <PeachWordmark unlocked />1647              <div class="peach-chrome-actions">1648                <button1649                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1650                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1651                  aria-label="Notes"1652                  title="Notes"1653                >1654                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1655                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1656                    <line x1="4" y1="5" x2="10" y2="5" />1657                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1658                    <line x1="4" y1="10" x2="7" y2="10" />1659                  </svg>1660                </button>1661                <button1662                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1663                    classList={{1664                      "is-syncing": syncBusy(),1665                      "is-ok": syncFlash() === "ok",1666                      "is-error": syncFlash() === "error",1667                    }}1668                    onClick={() => void handleHeaderSync()}1669                    disabled={syncBusy()}1670                    aria-label={`Sync now. ${syncLabel()}`}1671                    title={syncLabel()}1672                  >1673                    <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">1674                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1675                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1676                      <path d="M2.6 1v2.4h2.4" />1677                      <path d="M11.4 13v-2.4H9" />1678                    </svg>1679                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1680                  </button>1681                <button1682                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1683                  onClick={() => setView("settings")}1684                  aria-label="Settings"1685                >1686                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1687                    <path1688                      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"1689                      stroke="currentColor"1690                      stroke-width="0.9"1691                    />1692                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1693                  </svg>1694                </button>1695                <button1696                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1697                  onClick={handleAdd}1698                  aria-label="New entry"1699                >1700                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1701                    <path d="M5.5 1v9M1 5.5h9" />1702                  </svg>1703                </button>1704                <button1705                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1706                  onClick={() => void handleHeaderLock()}1707                  aria-label="Lock vault"1708                >1709                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1710                    <path1711                      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"1712                      stroke="currentColor"1713                      stroke-width="1"1714                      stroke-linecap="round"1715                    />1716                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1717                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1718                  </svg>1719                </button>1720              </div>1721            </header>17221723            <Show when={pendingProNotice() !== null}>1724              <div class="peach-pro-notice-banner">1725                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1726                <button1727                  class="peach-pro-notice-link"1728                  onClick={() => {1729                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1730                    setSettingsInitialSection("license");1731                    setView("settings");1732                    setPendingProNotice(null);1733                  }}1734                >1735                  Learn more →1736                </button>1737                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1738              </div>1739            </Show>17401741            <div class="peach-shell-body">1742              <div class="peach-shell-veil"></div>1743              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1744                <EntryView1745                  entry={selectedEntry()}1746                  currentTabUrl={currentTabUrl()}1747                  entries={entries()}1748                  isPro={proStatus()}1749                  onDelete={handleDelete}1750                  onFieldSaved={() => void loadEntries()}1751                  onEscape={() => { setView("list"); }}1752                  onProGate={(feature) => {1753                    setUpgradeHighlight(feature);1754                    setSettingsInitialSection("license");1755                    setView("settings");1756                  }}1757                />1758              </div>17591760              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1761                <div class="peach-search-bar">1762                  <span class="peach-search-icon">1763                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1764                      <circle cx="5.5" cy="5.5" r="3.75" />1765                      <path d="M8.75 8.75L11.5 11.5" />1766                    </svg>1767                  </span>1768                  <input1769                    class="peach-search-input"1770                    placeholder="search vault..."1771                    autocomplete="off"1772                    aria-label="Search vault entries"1773                    onClick={openList}1774                    onFocus={openList}1775                    readOnly1776                  />1777                  <div class="peach-search-meta">1778                    <span class="peach-search-counter">1779                      {nonNoteEntries().length > 01780                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1781                        : "0 entries"}1782                    </span>1783                    <span class="peach-divider"></span>1784                    <button1785                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1786                      onClick={() => navigate(-1)}1787                      aria-label="Previous entry"1788                      disabled={nonNoteEntries().length === 0}1789                    >1790                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1791                        <path d="M5 1L1 5.5L5 10" />1792                      </svg>1793                    </button>1794                    <button1795                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1796                      onClick={() => navigate(1)}1797                      aria-label="Next entry"1798                      disabled={nonNoteEntries().length === 0}1799                    >1800                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1801                        <path d="M1 1L5 5.5L1 10" />1802                      </svg>1803                    </button>1804                  </div>1805                </div>1806              </section>1807            </div>18081809            {/* Desktop: shown on demand via Show. Native sheet is rendered1810                via Portal below at the document root so its position:fixed1811                isn't trapped by .peach-shell's transform-based animations. */}1812            {/* Rare device-trust alerts; normal sync changes are silent. */}1813            <Show when={alertGroups().length > 0}>1814              <div class="peach-sync-alerts">1815                <For each={alertGroups()}>1816                  {([type, group]) => {1817                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1818                    return (1819                      <div class="peach-sync-alert">1820                        <Show when={group.length > 1}>1821                          <button1822                            class="peach-sync-alert-flip"1823                            type="button"1824                            aria-label="Previous"1825                            onClick={() => flipAlert(type, -1)}1826                          >‹</button>1827                        </Show>1828                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1829                        <Show when={group.length > 1}>1830                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1831                          <button1832                            class="peach-sync-alert-flip"1833                            type="button"1834                            aria-label="Next"1835                            onClick={() => flipAlert(type, 1)}1836                          >›</button>1837                        </Show>1838                        <button1839                          class="peach-sync-alert-dismiss"1840                          type="button"1841                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1842                          onClick={() => dismissAlertGroup(type)}1843                        >×</button>1844                      </div>1845                    );1846                  }}1847                </For>1848              </div>1849            </Show>18501851            <Show when={!isNativePlatform() && view() === "list"}>1852              <VaultView1853                entries={entries()}1854                selectedEntryId={selectedEntry()?.id}1855                currentTabDomain={currentTabDomain()}1856                sortOrder={sortOrder()}1857                searchSeed={listSearchSeed()}1858                searchSeedNonce={listSearchSeedNonce()}1859                onSelectEntry={handleSelectEntry}1860                onSortOrderChange={setSortOrder}1861                onAdd={handleAdd}1862                onClose={() => setView("entry")}1863                onOpenTrash={() => setView("trash")}1864                onDeleteMany={handleDeleteMany}1865              />1866            </Show>1867            <Show when={isNativePlatform() && hasVault()}>1868              <Portal>1869                <div1870                  class="peach-vault-sheet"1871                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1872                  style={(() => {1873                    const live = sheetTranslate();1874                    if (live === null) return undefined;1875                    return { transform: `translateY(${live}px)` };1876                  })()}1877                >1878                  <VaultView1879                    entries={entries()}1880                    selectedEntryId={selectedEntry()?.id}1881                    currentTabDomain={currentTabDomain()}1882                    sortOrder={sortOrder()}1883                    searchSeed={listSearchSeed()}1884                    searchSeedNonce={listSearchSeedNonce()}1885                    isNative={true}1886                    onSelectEntry={handleSelectEntry}1887                    onSortOrderChange={setSortOrder}1888                    onAdd={handleAdd}1889                    onClose={() => setView("entry")}1890                    onOpenTrash={() => setView("trash")}1891                    onDeleteMany={handleDeleteMany}1892                  />1893                </div>1894              </Portal>1895            </Show>1896            <Show when={view() === "settings" || settingsExiting()}>1897              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1898                <SettingsView1899                  entriesCount={entries().length}1900                  breachMonitoring={breachMonitoring()}1901                  lockOnClose={lockOnClose()}1902                  autoLockMinutes={autoLockMinutes()}1903                  trashRetentionDays={trashRetentionDays()}1904                  theme={theme()}1905                  accentColor={accentColor()}1906                  textSize={textSize()}1907                  reduceMotion={reduceMotion()}1908                  isPro={proStatus()}1909                  initialSection={settingsInitialSection()}1910                  upgradeHighlight={upgradeHighlight()}1911                  isExiting={settingsExiting()}1912                  onBreachMonitoringChange={applyBreachMonitoring}1913                  onLockOnCloseChange={applyLockOnClose}1914                  onAutoLockMinutesChange={applyAutoLockMinutes}1915                  onTrashRetentionChange={applyTrashRetention}1916                  onThemeChange={applyTheme}1917                  onAccentChange={applyAccentColor}1918                  onTextSizeChange={applyTextSize}1919                  onReduceMotionChange={applyReduceMotion}1920                  shortcuts={shortcutBindings()}1921                  onShortcutsChange={applyShortcuts}1922                  onLicenseChange={async () => {1923                    // After activation/deactivation: refresh Pro status,1924                    // re-load entries (defensive — signal state can drift if1925                    // the SW briefly restarts during the verify+save round-trip),1926                    // and replay the Pro celebration if this is the first time1927                    // a valid Pro license is seen on this device.1928                    await refreshProStatus();1929                    void loadEntries();1930                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1931                    if ((should as { ok: boolean; data?: boolean }).data === true) {1932                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1933                      setView("pro-celebration");1934                      window.setTimeout(() => setView("settings"), 2500);1935                    }1936                  }}1937                  onBack={() => {1938                    setSettingsExiting(true);1939                    window.setTimeout(() => {1940                      setSettingsExiting(false);1941                      setSettingsInitialSection(null);1942                      setUpgradeHighlight(null);1943                      handleBack();1944                    }, 200);1945                  }}1946                  onImport={() => setView("import")}1947                  onExport={() => setView("export")}1948                  onBreachCheckDone={loadEntries}1949                  onOpenHealth={openHealth}1950                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1951                  onOpenFileImport={handleOpenFileImport}1952                  onOpenPanic={() => setView("panic")}1953                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1954                  onOpenCodexRestore={() => setView("codex-restore")}1955                  onCardChange={setSettingsActiveCard}1956                  onProGate={(feature) => {1957                    setUpgradeHighlight(feature);1958                    setSettingsInitialSection("license");1959                  }}1960                />1961              </Suspense>1962            </Show>1963            <Show when={view() === "codex-generate"}>1964              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1965                <CodexGenerateView1966                  isPro={proStatus()}1967                  onBack={() => setView("settings")}1968                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1969                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1970                  onVaultLocked={() => handleLock()}1971                />1972              </Suspense>1973            </Show>1974            <Show when={view() === "codex-restore"}>1975              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1976                <CodexRestoreView1977                  onBack={() => setView("lock")}1978                  onRestoreSuccess={async () => {1979                    // After restore the vault is unlocked; refresh entries1980                    // and route to the main vault list. handleUnlock is the1981                    // canonical post-unlock setup path.1982                    await handleUnlock();1983                  }}1984                />1985              </Suspense>1986            </Show>1987            <Show when={view() === "pair-device"}>1988              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1989                <PairDeviceView1990                  isPro={proStatus()}1991                  onProChanged={() => { void refreshProStatus(); }}1992                  onBack={() => setView("settings")}1993                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1994                />1995              </Suspense>1996            </Show>1997            <Show when={view() === "add"}>1998              <AddView1999                entry={editEntry()}2000                entries={entries()}2001                onBack={handleBack}2002                onSave={handleSave}2003              />2004            </Show>2005            <Show when={view() === "import"}>2006              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2007                <ImportView onBack={() => setView("settings")} onImport={handleSave} />2008              </Suspense>2009            </Show>2010            <Show when={view() === "export"}>2011              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2012                <ExportView onBack={handleExportBack} />2013              </Suspense>2014            </Show>2015            <Show when={view() === "panic"}>2016              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2017                <PanicView2018                  onCancel={() => setView("settings")}2019                  onOpenExport={() => {2020                    setReturnToPanic(true);2021                    setView("export");2022                  }}2023                  onDestroyed={async () => {2024                    clearCanarySuppressions();2025                    // Fresh onboarding start after a destroy — don't let the2026                    // resume markers land the user mid-carousel.2027                    setOnboardingCardAtExit(0);2028                    void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});2029                    clearOnboardingExit();2030                    setEntries([]);2031                    setSelectedEntry(null);2032                    setEditEntry(undefined);2033                    setHasVault(false);2034                    setOnboarded(false);2035                    setProStatus(false);2036                    setPendingPasskey(null);2037                    setUpgradeHighlight(null);2038                    setSettingsInitialSection(null);2039                    setPendingProNotice(null);2040                    setPendingCelebration(false);2041                    setReturnToPanic(false);2042                    setContentPhase("idle");2043                    setView("lock");2044                  }}2045                />2046              </Suspense>2047            </Show>2048            {/* Health stays mounted while editing an entry from it so2049                computeReused() doesn't rerun on every cancel/back. */}2050            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>2051              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2052                <HealthView2053                  entries={entries()}2054                  isPro={proStatus()}2055                  onFixEntry={handleFixEntry}2056                  onBack={() => setView("settings")}2057                  onRefresh={loadEntries}2058                  hidden={view() !== "health"}2059                />2060              </Suspense>2061            </Show>2062            <Show when={view() === "trash"}>2063              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2064                <TrashView2065                  onBack={() => setView("list")}2066                  onRestored={() => void loadEntries()}2067                />2068              </Suspense>2069            </Show>2070            <Show when={showNotes()}>2071              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>2072                <NotesMode2073                  notes={entries().filter((e) => e.type === "note")}2074                  initialNoteId={openNoteId()}2075                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}2076                  onNoteListChanged={() => void loadEntries()}2077                />2078              </div>2079            </Show>2080            <Show when={restoreView() === "file"}>2081              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2082                <ImportView2083                  mode="onboarding"2084                  replacesExistingVault={true}2085                  onBack={() => setRestoreView(null)}2086                  onImport={async () => {2087                    setRestoreView(null);2088                    await handleUnlock();2089                  }}2090                />2091              </Suspense>2092            </Show>2093            </section>2094            </Show>2095          </Show>2096        </Show>2097      </Show>2098      <Show when={showShortcutsHelp()}>2099        <ShortcutsHelpOverlay2100          bindings={shortcutBindings()}2101          onClose={() => setShowShortcutsHelp(false)}2102        />2103      </Show>2104    </div>2105  );2106}21072108function ShortcutsHelpOverlay(props: {2109  bindings: Record<ShortcutAction, Keybinding>;2110  onClose: () => void;2111}) {2112  return (2113    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>2114      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>2115        <div class="peach-shortcuts-help-head">2116          <h3>Keyboard shortcuts</h3>2117          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>2118        </div>2119        <div class="peach-shortcuts-help-body">2120          <p class="peach-settings-sub-label">ENTRY VIEW</p>2121          <ul>2122            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (2123              <li>2124                <span>{d.label}</span>2125                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2126              </li>2127            ))}2128          </ul>2129          <p class="peach-settings-sub-label">ANYWHERE</p>2130          <ul>2131            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (2132              <li>2133                <span>{d.label}</span>2134                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2135              </li>2136            ))}2137          </ul>2138        </div>2139      </div>2140    </div>2141  );2142}