App.tsx

90.0 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    }605606    // Deep-link: ?restore=peachscript|csv — the detached-window half of the607    // file-picker flow. The action popup dismisses when the OS dialog steals608    // focus, so LockView.detachForFilePicker() reopens this URL in a609    // standalone window that owns the dialog. Routing runs before first610    // render so LockView mounts straight onto the right source form.611    try {612      const restoreRoute = new URLSearchParams(window.location.search).get("restore");613      if (restoreRoute === "peachscript" || restoreRoute === "csv") {614        setOnboarded(true);615        setStartOnboardingRestore(true);616        setResumeRestoreSource(restoreRoute === "peachscript" ? "symbols" : "csv");617      }618    } catch {619      // location.search unavailable — ignore.620    }621622    await Promise.all([restoreSettings(), refreshProStatus()]);623624    const pendingInitialSyncMarker =625      unlocked && vaultExists626        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)627        : null;628    const pendingInitialSyncDeviceId = pendingInitialSyncMarker629      ? await resolveInitialSyncDeviceId()630      : null;631632    // Mark played before any animation so a crash mid-sequence never replays633    // it. A newly adopted receiver deliberately defers this until its first634    // real sync finishes, preserving initial sync → celebration → vault.635    if (shouldCelebrate && !pendingInitialSyncDeviceId) {636      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });637    }638639    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome640    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.641    if (unlocked && vaultExists) {642      void sendMessage({643        type: "TRIGGER_SYNC",644        payload: { reason: "foreground" },645      });646      void loadSyncIndicator();647      // Rare device-trust alerts only; routine entry sync stays quiet.648      void loadSyncAlerts();649    }650651    // If the user created a vault but hasn't yet confirmed their recovery652    // words, route back to the recovery-words screen instead of opening the653    // entries view. The flag lives in chrome.storage.local so it survives654    // both popup close (SW suppresses lock-on-close) and full browser655    // restart (handleUnlock checks the same flag after a fresh password656    // unlock). Cleared when confirmation succeeds.657    let recoveryPending = false;658    try {659      const out = await chrome.storage.local?.get("peach_recovery_pending");660      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";661    } catch { /* best-effort */ }662663    // If this popup was opened from the inline "Open Peach to unlock" button,664    // the background set a session flag. Read and clear it so handleUnlock()665    // can close the popup after unlock and return the user to the page.666    if (chrome.storage.session) {667      try {668        const s = await chrome.storage.session.get("peach_inline_unlock");669        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {670          openedForInlineUnlock = true;671          await chrome.storage.session.remove("peach_inline_unlock");672        }673      } catch { /* best-effort */ }674    }675676    // Native: closing the app before recovery-words confirmation means the677    // user didn't finish vault creation. Throw the partial vault away and678    // restart onboarding rather than asking them to unlock a vault they679    // never finished creating. Desktop keeps the existing "unlock to680    // resume" flow because closing the popup there is much more casual.681    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {682      try {683        await chrome.storage.local?.remove([684          "peach_vault_a",685          "peach_vault_b",686          "peach_recovery_pending",687          "peach_onboarded",688          "peach_vault_history",689          ONBOARDING_CARD_STORAGE_KEY,690          ONBOARDING_EXIT_STORAGE_KEY,691        ]);692      } catch { /* best-effort */ }693      setHasVault(false);694      setOnboarded(false);695      setView("lock");696      setBootState("ready");697      return;698    }699700    if (recoveryPending && unlocked) {701      // forceRecoveryWords overrides LockView's hasVault gate so the702      // recovery surface renders even though the vault now exists.703      setForceRecoveryWords(true);704      setView("lock");705    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {706      void beginInitialSyncWait(pendingInitialSyncDeviceId);707    } else if (unlocked && vaultExists) {708      await openVault(undefined, shouldCelebrate);709      if (shouldCelebrate) {710        setView("pro-celebration");711        window.setTimeout(() => setView("entry"), 2500);712      }713    } else if (shouldCelebrate) {714      setPendingCelebration(true);715    }716717    await refreshPendingPasskey();718719    // Track tab changes so smart sort stays current720    const handleTabActivated = () => { void refreshCurrentTab(); };721    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {722      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();723    };724    try {725      chrome.tabs.onActivated.addListener(handleTabActivated);726      chrome.tabs.onUpdated.addListener(handleTabUpdated);727      onCleanup(() => {728        chrome.tabs.onActivated.removeListener(handleTabActivated);729        chrome.tabs.onUpdated.removeListener(handleTabUpdated);730      });731    } catch {732      // tabs permission may not be available in all contexts733    }734735    setBootState("ready");736737    // Deep-link: ?codex=pdf opens a detached window straight into the738    // Codex restore flow with auto-picked PDF. The action popup can't host739    // a file dialog without dismissing itself, so this is the only way the740    // PDF import path survives. See CodexRestoreView.openPdfPicker().741    try {742      const route = new URLSearchParams(window.location.search).get("codex");743      if (route === "pdf" || route === "restore") {744        setView("codex-restore");745      }746    } catch {747      // location.search unavailable — ignore.748    }749750    // Check for pending session-storage notices from the background.751    if (chrome.storage.session) {752      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as753        Record<string, { feature?: string } | undefined>;754      if (session.pendingProGate?.feature) {755        await chrome.storage.session.remove("pendingProGate");756        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);757        setSettingsInitialSection("license");758        setView("settings");759      } else if (session.pendingProNotice?.feature) {760        await chrome.storage.session.remove("pendingProNotice");761        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });762      }763    }764765    // Warm the lazy-module cache so the Suspense fallback never shows for766    // locally-bundled extension views. Without this, the first navigation to767    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which768    // covers the shell and absorbs clicks on the header.769    void Promise.all([770      import("./views/Settings").catch(() => {}),771      import("./views/Import").catch(() => {}),772      import("./views/Export").catch(() => {}),773      import("./views/Health").catch(() => {}),774      import("./views/TrashView").catch(() => {}),775    ]);776777    // Lock-on-close via a persistent port. sendMessage in pagehide is778    // unreliable — the popup context tears down before the message lands.779    // The SW's onConnect listener locks when this port disconnects.780    let popupPort: chrome.runtime.Port | null = null;781    try {782      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect783      // listener accepts the "popup-" prefix; the random suffix is defence in784      // depth against a port named exactly "popup" from anything but our popup.785      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });786    } catch { /* extension context invalidated — ignore */ }787    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });788789    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only790    // reliable signal is appStateChange — setTimeout is killed when the OS791    // backgrounds the app. We measure elapsed background time on resume.792    if (isNativePlatform()) {793      let backgroundedAt: number | null = null;794795      const CapApp = nativePlugin<{796        addListener: (797          ev: string,798          cb: (s: { isActive: boolean }) => void,799        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };800      }>("App");801      if (CapApp?.addListener) {802        const sub = CapApp.addListener(803          "appStateChange",804          ({ isActive }: { isActive: boolean }) => {805            if (!isActive) {806              backgroundedAt = Date.now();807              return;808            }809            if (backgroundedAt !== null && autoLockMinutes() > 0) {810              const elapsed = Date.now() - backgroundedAt;811              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();812            }813            backgroundedAt = null;814          }815        );816        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.817        onCleanup(() => {818          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});819        });820      }821822      // L12/COR-011: foreground idle autolock. appStateChange only fires when823      // the OS backgrounds the app — if the user idles with the screen on,824      // chrome.alarms is no-op'd in Capacitor so the vault would stay open825      // indefinitely. Poll every 30s and lock if elapsed since last user826      // interaction exceeds autoLockMinutes.827      let lastUserActivityAt = Date.now();828      const bumpActivity = () => { lastUserActivityAt = Date.now(); };829      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;830      for (const ev of ACTIVITY_EVENTS) {831        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });832      }833      const idleLockInterval = setInterval(() => {834        const minutes = autoLockMinutes();835        if (!minutes || minutes <= 0) return;836        const elapsed = Date.now() - lastUserActivityAt;837        if (elapsed >= minutes * 60_000) {838          lastUserActivityAt = Date.now();839          handleHeaderLock();840        }841      }, 30_000);842      onCleanup(() => {843        clearInterval(idleLockInterval);844        for (const ev of ACTIVITY_EVENTS) {845          document.removeEventListener(ev, bumpActivity, { capture: true });846        }847      });848849      // The retired native peer-discovery trigger went with the old Capacitor850      // pairing plugin. Reconnection is address-cache first, subnet probe second851      // (sync-runner.ts); relocating a peer that changed networks is an852      // Android-side discovery concern now.853      if (isNativePlatform()) {854        // Android runs the background/sync dispatcher in-process with the855        // popup, so the production runner has to be registered from the856        // UI bootstrap path instead of the MV3 service-worker entry.857        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>858          import("../background/sync-runner").then(({ productionSyncRunner }) => {859            setSyncRunner(productionSyncRunner);860            void hydratePersistedSyncState();861          })862        );863      }864    }865866    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale867    // entries instead of waiting for the next GET_ENTRIES round-trip.868    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {869      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();870      if (msg?.type === "SYNC_STATE_CHANGED") {871        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);872      }873      if (msg?.type === "PRO_GATE_TRIGGERED") {874        setUpgradeHighlight(msg.payload?.feature ?? null);875        setSettingsInitialSection("license");876        setView("settings");877      }878    };879    chrome.runtime.onMessage.addListener(handleRuntimeMessage);880    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));881882    // Android hardware/gesture back. MainActivity fires peach:back; the popup883    // decides what "back" means per surface. Lock+no-vault is the common case884    // — return to onboarding rather than letting the OS dismiss the activity.885    const handlePeachBack = () => {886      // Notes mode captures back first887      if (showNotes()) {888        setShowNotes(false);889        setOpenNoteId(undefined);890        return;891      }892      const v = view();893      if (v === "lock" && !hasVault() && onboarded()) {894        setOnboarded(false);895        return;896      }897      if (v === "list") { setView("entry"); return; }898      if (v === "settings") {899        window.dispatchEvent(new Event("peach:settings-back"));900        return;901      }902      if (v === "import" || v === "health") { setView("settings"); return; }903      if (v === "export") { handleExportBack(); return; }904      if (v === "add") { handleBack(); return; }905      if (v === "pair-device") { setView("settings"); return; }906    };907    window.addEventListener("peach:back", handlePeachBack);908    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));909910    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that911    // peeks from the bottom (search bar handle visible) and drags up to fill912    // the screen. dragOffset is the LIVE finger offset during a drag, in px,913    // 0 when no drag in progress. The wrapper element computes transform =914    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.915    if (isNativePlatform()) {916      let touchStartY = 0;917      let touchStartX = 0;918      let lastY = 0;919      let lastT = 0;920      let dragging = false;921      let captured = false;922      const HORIZONTAL_TOLERANCE = 16;923      const ACTIVATION_DY = 8;924      const PEEK_PX = 60;925926      const onTouchStart = (e: TouchEvent) => {927        const t = e.touches[0];928        if (!t) return;929        const v = view();930        if (v !== "entry" && v !== "list") return;931        // Entry view: only intercept drags starting in the bottom 40%.932        // List view: intercept drags starting in the top 35% (the search/handle row).933        const inBand = v === "entry"934          ? t.clientY > window.innerHeight * 0.6935          : t.clientY < window.innerHeight * 0.35;936        if (!inBand) return;937        touchStartY = lastY = t.clientY;938        touchStartX = t.clientX;939        lastT = e.timeStamp;940        dragging = true;941        captured = false;942      };943944      const onTouchMove = (e: TouchEvent) => {945        if (!dragging) return;946        const t = e.touches[0];947        if (!t) return;948        const dy = t.clientY - touchStartY;949        const dx = Math.abs(t.clientX - touchStartX);950951        if (!captured) {952          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {953            // Looks like a horizontal swipe — release.954            dragging = false;955            return;956          }957          if (Math.abs(dy) < ACTIVATION_DY) return;958          captured = true;959        }960961        // Translate the sheet by dy from its rest (peek) position. Peek is962        // (viewport height - PEEK_PX). Open is 0.963        const v = view();964        const restClosed = window.innerHeight - PEEK_PX;965        const baseTranslate = v === "list" ? 0 : restClosed;966        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));967        setSheetTranslate(next);968        lastY = t.clientY;969        lastT = e.timeStamp;970      };971972      const onTouchEnd = (e: TouchEvent) => {973        if (!dragging) { return; }974        const t = e.changedTouches[0];975        const elapsed = Math.max(1, e.timeStamp - lastT);976        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms977        const wasCaptured = captured;978        dragging = false;979        captured = false;980        const v = view();981982        if (!wasCaptured) {983          // Tap in the peek strip while in entry view → open the vault list.984          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");985          setSheetTranslate(null);986          return;987        }988989        const restClosed = window.innerHeight - PEEK_PX;990        const current = sheetTranslate() ?? restClosed;991992        // Snap rules:993        //   - Strong upward velocity → open994        //   - Strong downward velocity → close995        //   - Otherwise snap to whichever rest is closer996        let nextOpen: boolean;997        if (velocity < -0.05) nextOpen = true;998        else if (velocity > 0.05) nextOpen = false;999        else nextOpen = current < restClosed * 0.5;10001001        if (nextOpen && v !== "list") setView("list");1002        if (!nextOpen && v !== "entry") setView("entry");1003        // Release the live offset so CSS transition handles the snap.1004        setSheetTranslate(null);1005      };10061007      document.addEventListener("touchstart", onTouchStart, { passive: true });1008      document.addEventListener("touchmove",  onTouchMove,  { passive: true });1009      document.addEventListener("touchend",   onTouchEnd,   { passive: true });1010      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });1011      onCleanup(() => {1012        document.removeEventListener("touchstart", onTouchStart);1013        document.removeEventListener("touchmove",  onTouchMove);1014        document.removeEventListener("touchend",   onTouchEnd);1015      });1016    }10171018    // Action handlers — keyed by ShortcutAction. The dispatcher below tests1019    // each binding against the event and runs the matching handler. New1020    // shortcuts only need an entry here; the binding is data, not code.1021    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {1022      copy_password: () => {1023        const entry = selectedEntry();1024        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });1025      },1026      copy_username: () => {1027        const entry = selectedEntry();1028        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });1029      },1030      copy_totp: () => {1031        const entry = selectedEntry();1032        if (!entry?.totp) return;1033        try {1034          const { code } = generateTOTP(entry.totp);1035          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });1036        } catch { /* invalid TOTP secret — silent */ }1037      },1038      new_entry: () => handleAdd(),1039      edit_entry: () => {1040        const entry = selectedEntry();1041        // Passkey-only entries have nothing user-editable in the Add view; the1042        // passkey credential itself is opaque. Skip the edit action for them.1043        if (!entry || isPasskeyOnly(entry)) return;1044        setEditEntry(entry);1045        setView("add");1046      },1047      delete_entry: () => {1048        if (selectedEntry()) void handleDelete();1049      },1050      lock_vault: () => { void handleHeaderLock(); },1051      search: () => openList(),1052      nav_prev: () => navigate(-1),1053      nav_next: () => navigate(1),1054      jump_vault: () => setView("entry"),1055      jump_settings: () => setView("settings"),1056      show_help: () => setShowShortcutsHelp(true),1057    };10581059    // Actions that are MEANINGFUL only on the entry-detail view. Outside1060    // that scope the binding is dormant — pressing C while on Settings1061    // does nothing rather than awkwardly copying from a now-stale entry.1062    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([1063      "copy_password", "copy_username", "copy_totp",1064      "edit_entry", "delete_entry", "nav_prev", "nav_next",1065    ]);10661067    const handleGlobalKeydown = (e: KeyboardEvent) => {1068      const v = view();1069      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"1070        || (e.target as HTMLElement)?.tagName === "TEXTAREA"1071        || (e.target as HTMLElement)?.isContentEditable;1072      const isPrintableSearchKey =1073        e.key.length === 1 &&1074        !e.ctrlKey &&1075        !e.metaKey &&1076        !e.altKey;10771078      // No shortcuts while a full-screen surface owns the whole viewport:1079      // the lock screen, the post-pairing readiness sequence, or the Pro1080      // celebration. Without this the lock screen is at the mercy of whatever1081      // single-key binding is active — e.g. typing "n" in a password that1082      // slips out of focus triggers `new_entry` and escapes the lock screen.1083      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;10841085      // Help dialog: Escape closes it; eat the keypress so it doesn't1086      // also navigate away from the underlying view.1087      if (showShortcutsHelp()) {1088        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }1089        return;1090      }10911092      // ── Escape — fixed binding (not user-customizable) ───────1093      if (e.key === "Escape") {1094        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }1095        if (v === "list") { setView("entry"); return; }1096        if (v === "settings" || v === "add") { handleBack(); return; }1097        if (v === "import" || v === "health") { setView("settings"); return; }1098        if (v === "export") { handleExportBack(); return; }1099        if (v === "pair-device") { setView("settings"); return; }1100      }11011102      // Bindings-driven dispatch. Single-key letter bindings without1103      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is1104      // inside an input, so users can type into search/forms normally.1105      const bindings = shortcutBindings();1106      for (const action of Object.keys(bindings) as ShortcutAction[]) {1107        const binding = bindings[action];1108        if (!matchKeybinding(e, binding)) continue;1109        // Single-key letter bindings need the input-focus guard. Bindings1110        // with any modifier are safe — Ctrl+L doesn't conflict with typing.1111        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;1112        if (!hasMod && binding.key.length === 1 && inInput) return;1113        if (ENTRY_SCOPED.has(action) && v !== "entry") return;1114        e.preventDefault();1115        SHORTCUT_HANDLERS[action]?.();1116        return;1117      }11181119      // Type-to-search: in entry view, any printable key not consumed by a1120      // shortcut above primes the list search seed and opens the list.1121      // Kept outside the bindings table because it's a behavior, not a1122      // discrete action — every printable character can trigger it.1123      if (v === "entry" && !inInput && isPrintableSearchKey) {1124        e.preventDefault();1125        primeListSearch(e.key);1126        return;1127      }1128    };1129    window.addEventListener("keydown", handleGlobalKeydown);1130    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));11311132    const handleStorageChanged = (1133      changes: Record<string, chrome.storage.StorageChange>,1134      areaName: string1135    ) => {1136      if (areaName !== "session") return;1137      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {1138        return;1139      }1140      void refreshPendingPasskey();1141    };1142    chrome.storage.onChanged.addListener(handleStorageChanged);1143    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));1144  });11451146  async function refreshCurrentTab() {1147    try {1148      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1149      const url = tab?.url ?? tab?.pendingUrl ?? "";1150      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");1151      // Skip extension/internal URLs — adding chrome://, about:, or1152      // chrome-extension:// to a vault entry is never what the user wants.1153      const isWebUrl = /^https?:\/\//i.test(url);1154      setCurrentTabUrl(isWebUrl ? url : "");1155    } catch {1156      setCurrentTabDomain("");1157      setCurrentTabUrl("");1158    }1159  }11601161  async function refreshPendingPasskey() {1162    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });1163    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);1164  }11651166  async function refreshProStatus() {1167    const res = await sendMessage({ type: "GET_LICENSE" });1168    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;1169    setProStatus(Boolean(data?.valid && data?.plan === "pro"));1170  }11711172  async function restoreSettings() {1173    const res = await sendMessage({ type: "GET_SETTINGS" });1174    const s = (res as { ok: boolean; data?: any }).data ?? {};1175    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {1176      setAccentColor(s.accentColor as AccentColorName);1177    }1178    setTheme(s.theme === "light" ? "light" : "dark");1179    if (s.textSize === "small" || s.textSize === "large") {1180      setTextSize(s.textSize);1181    } else {1182      setTextSize("medium");1183    }1184    setReduceMotion(s.reduceMotion === true);1185    setLockOnClose(s.lockOnClose === true);1186    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);1187    setBreachMonitoring(s.breachMonitoring !== false);1188    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);1189    setShortcutBindings(getActiveBindings(s.shortcuts));1190  }11911192  async function applyTrashRetention(days: number) {1193    setTrashRetentionDays(days);1194    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });1195  }11961197  function primeListSearch(seed: string) {1198    setListSearchSeed(seed);1199    setListSearchSeedNonce((value) => value + 1);1200    openList();1201  }12021203  // Returns null when it detected a dead service worker and triggered handleLock().1204  // Callers that need to abort (e.g. openVault) check for null rather than relying1205  // on view() state, which may already be "lock" during normal startup flows.1206  async function loadEntries(): Promise<VaultEntry[] | null> {1207    const response = await sendMessage({ type: "GET_ENTRIES" });1208    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };12091210    // If the service worker was killed and restarted (MV3 workers sleep), the1211    // vault will be locked again — or the worker may not respond at all.1212    // In either case, send the user to the lock screen rather than silently1213    // showing an empty vault (which looks like data loss).1214    if (!res.ok) {1215      if (1216        res.error === "vault_locked" ||1217        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1218        (typeof res.error === "string" && res.error.includes("locked"))1219      ) {1220        handleLock();1221        return null; // signal emergency lock to callers1222      }1223      return [];1224    }12251226    const loadedEntries = res.data ?? [];1227    setEntries(loadedEntries);12281229    const currentId = selectedEntry()?.id;1230    if (currentId) {1231      setSelectedEntry(1232        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1233      );1234    }12351236    return loadedEntries;1237  }12381239  async function openVault(preferredEntryId?: string, skipViewSet = false) {1240    // Purge expired trash entries on each vault open1241    const retDays = trashRetentionDays();1242    if (retDays > 0) {1243      void sendMessage({1244        type: "PURGE_EXPIRED_TRASH",1245        payload: { retentionMs: retDays * 86_400_000 },1246      });1247    }12481249    const loadedEntries = await loadEntries();12501251    // null means loadEntries() triggered an emergency lock (service worker died).1252    // Don't override it by setting view back to "entry" with an empty vault.1253    if (loadedEntries === null) return false;12541255    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1256    let nextSelectedEntry: VaultEntry | null = null;1257    if (preferredEntryId) {1258      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1259    }1260    if (!nextSelectedEntry) {1261      const tabDomain = currentTabDomain();1262      if (tabDomain) {1263        nextSelectedEntry = loadedEntries.find((e) => {1264          if (e.type === "login") {1265            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1266            for (const extra of e.additionalUrls ?? []) {1267              if ((extractDomain(extra) ?? "") === tabDomain) return true;1268            }1269            return false;1270          }1271          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1272          return false;1273        }) ?? null;1274      }1275    }1276    nextSelectedEntry ??= pickNavigable(loadedEntries);12771278    setSelectedEntry(nextSelectedEntry);1279    setEditEntry(undefined);1280    setContentTransitioning(false);1281    setContentPhase("enter");1282    queueContentIdle();1283    if (!skipViewSet) setView("entry");1284    return true;1285  }12861287  async function handleUnlock() {1288    // If the user previously created a vault but hadn't yet confirmed their1289    // recovery words (and the browser was closed before they could), the1290    // peach_recovery_pending flag is still set in storage.local. Re-route1291    // back to the recovery surface so they finish the confirmation step1292    // before reaching the entries view — the words can be re-derived now1293    // that the vault is unlocked again.1294    let recoveryPending = false;1295    try {1296      const out = await chrome.storage.local?.get("peach_recovery_pending");1297      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1298    } catch { /* best-effort */ }1299    if (recoveryPending) {1300      setForceRecoveryWords(true);1301      setView("lock");1302      triggerPipPulse();1303      await restoreSettings();1304      return;1305    }1306    setHasVault(true);1307    triggerPipPulse();1308    await restoreSettings();1309    const celebrating = pendingCelebration();1310    if (celebrating) {1311      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1312      setPendingCelebration(false);1313    }1314    await openVault(undefined, celebrating);1315    if (celebrating) {1316      setView("pro-celebration");1317      window.setTimeout(() => setView("entry"), 2500);1318    }1319    // Popup was opened from the inline "Open Peach to unlock" button — close it1320    // now so the user lands back on the page with the autofill selector ready.1321    if (openedForInlineUnlock) {1322      openedForInlineUnlock = false;1323      window.close();1324    }1325  }13261327  function handleSelectEntry(entry: VaultEntry) {1328    if (entry.type === "note") {1329      setOpenNoteId(entry.id);1330      setShowNotes(true);1331      return;1332    }1333    setSelectedEntry(entry);1334    setContentTransitioning(false);1335    setContentPhase("enter");1336    queueContentIdle();1337    setView("entry");1338  }13391340  function handleAdd() {1341    setEditEntry(undefined);1342    setView("add");1343  }13441345  async function handleDelete() {1346    const entry = selectedEntry();1347    if (!entry) return;1348    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1349    const loadedEntries = await loadEntries() ?? [];1350    setSelectedEntry(pickNavigable(loadedEntries));1351    setView("entry");1352  }13531354  async function handleDeleteMany(ids: string[]) {1355    for (const id of ids) {1356      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1357    }1358    const loadedEntries = await loadEntries() ?? [];1359    // If the currently selected entry was among the deleted, move to first1360    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1361    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1362  }13631364  async function handleSave(savedEntry?: VaultEntry) {1365    await openVault(savedEntry?.id);1366  }13671368  function handleBack() {1369    const dest = editBackView();1370    setEditBackView("entry");1371    setEditEntry(undefined);1372    setView(dest);1373  }13741375  function handleExportBack() {1376    if (returnToPanic()) {1377      setReturnToPanic(false);1378      setView("panic");1379      return;1380    }1381    setView("settings");1382  }13831384  function handleLock() {1385    clearCanarySuppressions();1386    setEntries([]);1387    setSelectedEntry(null);1388    setEditEntry(undefined);1389    setContentPhase("idle");1390    setView("lock");1391  }13921393  function handleHeaderLock() {1394    // Lock the UI immediately — do not wait for the service worker. If the SW1395    // is dead or slow, the 5s sendMessage timeout would create a dead-click1396    // window. The SW will lock on its next wake regardless.1397    handleLock();1398    void sendMessage({ type: "LOCK" });1399  }14001401  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1402  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1403  // the trigger's own reply.1404  async function handleHeaderSync(): Promise<void> {1405    if (syncBusy()) return;1406    setSyncBusy(true);1407    setSyncFlash(null);1408    try {1409      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1410      let state: SyncOutcomeSummary = { status: "syncing" };1411      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1412        await new Promise((r) => setTimeout(r, 250));1413        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1414          ok: boolean;1415          data?: SyncOutcomeSummary;1416        };1417        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1418      }1419      setSyncSummary(state);1420      setSyncFlash(state.status === "error" ? "error" : "ok");1421      await loadSyncAlerts();1422      await loadEntries();1423      await loadSyncIndicator();1424    } catch {1425      setSyncSummary({ status: "error", outcome: "run_failed" });1426      setSyncFlash("error");1427    } finally {1428      setSyncBusy(false);1429      setTimeout(() => setSyncFlash(null), 2_000);1430    }1431  }14321433  function navigate(dir: number) {1434    const navigable = nonNoteEntries();1435    if (navigable.length === 0) return;1436    const currentIndex = selectedIndex();1437    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1438    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1439    setSelectedEntry(navigable[nextIndex]);1440    setContentPhase("enter");1441    queueContentIdle();1442  }14431444  /**1445   * The Entry view's selection invariant: never select a note. Notes are a1446   * separate surface (handleSelectEntry opens the notes view), so any code path1447   * that picks a default — vault open, post-delete, refresh — must skip them1448   * and return null if the only entries are notes.1449   */1450  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1451    return list.find((e) => e.type !== "note") ?? null;1452  }14531454  function openList() {1455    setView("list");1456  }14571458  function openHealth() {1459    setEditEntry(undefined);1460    setView("health");1461  }14621463  function handleOpenFileImport() {1464    setRestoreView("file");1465  }14661467  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;14681469  function handleFixEntry(entry: VaultEntry) {1470    setSelectedEntry(entry);1471    // Passkey-only entries have no editable surface — drop into view mode1472    // instead of opening the Add editor.1473    if (isPasskeyOnly(entry)) {1474      setView("entry");1475      return;1476    }1477    setEditBackView(view()); // preserve caller view so back returns here1478    setEditEntry(entry);1479    setView("add");1480  }14811482  const isLockedView = () => view() === "lock" || view() === "adopting";14831484  async function handleAdoptionDone() {1485    await storageSet("peach_onboarded", "true").catch(() => {});1486    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1487    clearOnboardingExit();1488    setOnboarded(true);1489    setHasVault(true);1490    setView("initial-sync");1491    // The background applies a Pro license and persists the source-device1492    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1493    // celebration pending until that exact peer records a completed sync.1494    await refreshProStatus();1495    const deviceId = await resolveInitialSyncDeviceId();1496    if (deviceId) {1497      void beginInitialSyncWait(deviceId);1498    } else {1499      // Pairing completion without a durable peer row should be impossible.1500      // Stay on the honest waiting surface and expose retry instead of falling1501      // through to an empty vault.1502      setInitialSyncSlow(true);1503    }1504  }15051506  async function handleApprovePendingPasskey() {1507    const pending = pendingPasskey();1508    if (!pending) return;1509    if (pending.browser === "firefox" && pending.type === "create") {1510      // Firefox path: popup itself runs navigator.credentials.create. The1511      // background never approved/rejected anything — it just stashed1512      // intent. After the popup-driven flow resolves (success or cancel),1513      // clear the pending key so the popup doesn't re-show this on next open.1514      const { createFirefoxPasskey } = await import("./firefox-passkey");1515      const result = await createFirefoxPasskey(pending);1516      if (!result.ok) {1517        console.warn("Peach Firefox passkey create failed:", result.error);1518      }1519      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1520      setPendingPasskey(null);1521      void loadEntries();1522      window.close();1523      return;1524    }1525    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1526    window.close();1527  }15281529  async function handleDenyPendingPasskey() {1530    const pending = pendingPasskey();1531    if (!pending) return;1532    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1533    window.close();1534  }15351536  function queueContentIdle(after?: () => void) {1537    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1538    contentPhaseTimer = window.setTimeout(() => {1539      setContentPhase("idle");1540      after?.();1541    }, ENTRY_TRANSITION_SETTLE_MS);1542  }15431544  return (1545    <div class="popup-root peach-theme">1546      <Show when={bootState() === "ready"}>1547        <Show1548          when={!pendingPasskey()}1549          fallback={1550            <PasskeyApprovalView1551              type={pendingPasskey()!.type}1552              rpName={pendingPasskey()!.rpName}1553              rpId={pendingPasskey()!.rpId}1554              userName={pendingPasskey()!.userName}1555              userDisplayName={pendingPasskey()!.userDisplayName}1556              onApprove={handleApprovePendingPasskey}1557              onDeny={handleDenyPendingPasskey}1558            />1559          }1560        >1561          <Show1562            when={!isLockedView()}1563            fallback={1564              <Show1565                when={view() !== "adopting"}1566                fallback={1567                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1568                    <AdoptVaultView1569                      onCancel={() => {1570                        clearOnboardingExit();1571                        setOnboarded(false);1572                        setView("lock");1573                      }}1574                      onDone={handleAdoptionDone}1575                    />1576                  </Suspense>1577                }1578              >1579                <Show1580                  when={onboarded() || hasVault()}1581                  fallback={1582                    <Onboarding1583                      initialCard={onboardingCardAtExit()}1584                      onComplete={() => {1585                        markOnboardingExit("create");1586                        setStartOnboardingRestore(false);1587                        setOnboarded(true);1588                      }}1589                      onRestore={() => {1590                        markOnboardingExit("restore");1591                        setStartOnboardingRestore(true);1592                        setOnboarded(true);1593                      }}1594                      onAdopt={() => {1595                        markOnboardingExit("adopt");1596                        setStartOnboardingRestore(false);1597                        setOnboarded(true);1598                        setView("adopting");1599                      }}1600                    />1601                  }1602                >1603                  <LockView1604                    hasVault={hasVault()}1605                    ready={bootState() === "ready"}1606                    isPro={proStatus()}1607                    forceRecoveryWords={forceRecoveryWords()}1608                    initialRestore={startOnboardingRestore()}1609                    initialRestoreSource={resumeRestoreSource() ?? undefined}1610                    onUnlock={() => {1611                      // RecoveryWordDisplay clears the storage flag before1612                      // calling onDone, so handleUnlock will see no pending1613                      // confirmation and proceed through the normal path.1614                      if (forceRecoveryWords()) setForceRecoveryWords(false);1615                      // The create/restore flow is done — a lock later in this1616                      // window must show the unlock screen, not re-enter the1617                      // onboarding restore surface.1618                      setStartOnboardingRestore(false);1619                      setResumeRestoreSource(null);1620                      void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});1621                      return handleUnlock();1622                    }}1623                    onBackToOnboarding={1624                      !hasVault()1625                        ? () => {1626                            // Deliberately rewinding to the carousel — the exit1627                            // flow must not reclaim the next popup open.1628                            clearOnboardingExit();1629                            setStartOnboardingRestore(false);1630                            setOnboarded(false);1631                          }1632                        : undefined1633                    }1634                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1635                  />1636                </Show>1637              </Show>1638            }1639          >1640            <Show1641              when={1642                view() !== "pro-celebration" &&1643                view() !== "initial-sync"1644              }1645              fallback={1646                <Show1647                  when={view() === "initial-sync"}1648                  fallback={<ProCelebration />}1649                >1650                  <InitialSyncView1651                    slow={initialSyncSlow()}1652                    onRetry={() => void retryInitialSync()}1653                  />1654                </Show>1655              }1656            >1657            <section1658              id="hd-shell"1659              class="peach-shell peach-theme"1660              data-surface="extension"1661            >1662            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1663              <PeachWordmark unlocked />1664              <div class="peach-chrome-actions">1665                <button1666                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1667                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1668                  aria-label="Notes"1669                  title="Notes"1670                >1671                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1672                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1673                    <line x1="4" y1="5" x2="10" y2="5" />1674                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1675                    <line x1="4" y1="10" x2="7" y2="10" />1676                  </svg>1677                </button>1678                <button1679                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1680                    classList={{1681                      "is-syncing": syncBusy(),1682                      "is-ok": syncFlash() === "ok",1683                      "is-error": syncFlash() === "error",1684                    }}1685                    onClick={() => void handleHeaderSync()}1686                    disabled={syncBusy()}1687                    aria-label={`Sync now. ${syncLabel()}`}1688                    title={syncLabel()}1689                  >1690                    <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">1691                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1692                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1693                      <path d="M2.6 1v2.4h2.4" />1694                      <path d="M11.4 13v-2.4H9" />1695                    </svg>1696                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1697                  </button>1698                <button1699                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1700                  onClick={() => setView("settings")}1701                  aria-label="Settings"1702                >1703                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1704                    <path1705                      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"1706                      stroke="currentColor"1707                      stroke-width="0.9"1708                    />1709                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1710                  </svg>1711                </button>1712                <button1713                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1714                  onClick={handleAdd}1715                  aria-label="New entry"1716                >1717                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1718                    <path d="M5.5 1v9M1 5.5h9" />1719                  </svg>1720                </button>1721                <button1722                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1723                  onClick={() => void handleHeaderLock()}1724                  aria-label="Lock vault"1725                >1726                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1727                    <path1728                      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"1729                      stroke="currentColor"1730                      stroke-width="1"1731                      stroke-linecap="round"1732                    />1733                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1734                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1735                  </svg>1736                </button>1737              </div>1738            </header>17391740            <Show when={pendingProNotice() !== null}>1741              <div class="peach-pro-notice-banner">1742                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1743                <button1744                  class="peach-pro-notice-link"1745                  onClick={() => {1746                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1747                    setSettingsInitialSection("license");1748                    setView("settings");1749                    setPendingProNotice(null);1750                  }}1751                >1752                  Learn more →1753                </button>1754                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1755              </div>1756            </Show>17571758            <div class="peach-shell-body">1759              <div class="peach-shell-veil"></div>1760              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1761                <EntryView1762                  entry={selectedEntry()}1763                  currentTabUrl={currentTabUrl()}1764                  entries={entries()}1765                  isPro={proStatus()}1766                  onDelete={handleDelete}1767                  onFieldSaved={() => void loadEntries()}1768                  onEscape={() => { setView("list"); }}1769                  onProGate={(feature) => {1770                    setUpgradeHighlight(feature);1771                    setSettingsInitialSection("license");1772                    setView("settings");1773                  }}1774                />1775              </div>17761777              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1778                <div class="peach-search-bar">1779                  <span class="peach-search-icon">1780                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1781                      <circle cx="5.5" cy="5.5" r="3.75" />1782                      <path d="M8.75 8.75L11.5 11.5" />1783                    </svg>1784                  </span>1785                  <input1786                    class="peach-search-input"1787                    placeholder="search vault..."1788                    autocomplete="off"1789                    aria-label="Search vault entries"1790                    onClick={openList}1791                    onFocus={openList}1792                    readOnly1793                  />1794                  <div class="peach-search-meta">1795                    <span class="peach-search-counter">1796                      {nonNoteEntries().length > 01797                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1798                        : "0 entries"}1799                    </span>1800                    <span class="peach-divider"></span>1801                    <button1802                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1803                      onClick={() => navigate(-1)}1804                      aria-label="Previous entry"1805                      disabled={nonNoteEntries().length === 0}1806                    >1807                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1808                        <path d="M5 1L1 5.5L5 10" />1809                      </svg>1810                    </button>1811                    <button1812                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1813                      onClick={() => navigate(1)}1814                      aria-label="Next entry"1815                      disabled={nonNoteEntries().length === 0}1816                    >1817                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1818                        <path d="M1 1L5 5.5L1 10" />1819                      </svg>1820                    </button>1821                  </div>1822                </div>1823              </section>1824            </div>18251826            {/* Desktop: shown on demand via Show. Native sheet is rendered1827                via Portal below at the document root so its position:fixed1828                isn't trapped by .peach-shell's transform-based animations. */}1829            {/* Rare device-trust alerts; normal sync changes are silent. */}1830            <Show when={alertGroups().length > 0}>1831              <div class="peach-sync-alerts">1832                <For each={alertGroups()}>1833                  {([type, group]) => {1834                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1835                    return (1836                      <div class="peach-sync-alert">1837                        <Show when={group.length > 1}>1838                          <button1839                            class="peach-sync-alert-flip"1840                            type="button"1841                            aria-label="Previous"1842                            onClick={() => flipAlert(type, -1)}1843                          >‹</button>1844                        </Show>1845                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1846                        <Show when={group.length > 1}>1847                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1848                          <button1849                            class="peach-sync-alert-flip"1850                            type="button"1851                            aria-label="Next"1852                            onClick={() => flipAlert(type, 1)}1853                          >›</button>1854                        </Show>1855                        <button1856                          class="peach-sync-alert-dismiss"1857                          type="button"1858                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1859                          onClick={() => dismissAlertGroup(type)}1860                        >×</button>1861                      </div>1862                    );1863                  }}1864                </For>1865              </div>1866            </Show>18671868            <Show when={!isNativePlatform() && view() === "list"}>1869              <VaultView1870                entries={entries()}1871                selectedEntryId={selectedEntry()?.id}1872                currentTabDomain={currentTabDomain()}1873                sortOrder={sortOrder()}1874                searchSeed={listSearchSeed()}1875                searchSeedNonce={listSearchSeedNonce()}1876                onSelectEntry={handleSelectEntry}1877                onSortOrderChange={setSortOrder}1878                onAdd={handleAdd}1879                onClose={() => setView("entry")}1880                onOpenTrash={() => setView("trash")}1881                onDeleteMany={handleDeleteMany}1882              />1883            </Show>1884            <Show when={isNativePlatform() && hasVault()}>1885              <Portal>1886                <div1887                  class="peach-vault-sheet"1888                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1889                  style={(() => {1890                    const live = sheetTranslate();1891                    if (live === null) return undefined;1892                    return { transform: `translateY(${live}px)` };1893                  })()}1894                >1895                  <VaultView1896                    entries={entries()}1897                    selectedEntryId={selectedEntry()?.id}1898                    currentTabDomain={currentTabDomain()}1899                    sortOrder={sortOrder()}1900                    searchSeed={listSearchSeed()}1901                    searchSeedNonce={listSearchSeedNonce()}1902                    isNative={true}1903                    onSelectEntry={handleSelectEntry}1904                    onSortOrderChange={setSortOrder}1905                    onAdd={handleAdd}1906                    onClose={() => setView("entry")}1907                    onOpenTrash={() => setView("trash")}1908                    onDeleteMany={handleDeleteMany}1909                  />1910                </div>1911              </Portal>1912            </Show>1913            <Show when={view() === "settings" || settingsExiting()}>1914              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1915                <SettingsView1916                  entriesCount={entries().length}1917                  breachMonitoring={breachMonitoring()}1918                  lockOnClose={lockOnClose()}1919                  autoLockMinutes={autoLockMinutes()}1920                  trashRetentionDays={trashRetentionDays()}1921                  theme={theme()}1922                  accentColor={accentColor()}1923                  textSize={textSize()}1924                  reduceMotion={reduceMotion()}1925                  isPro={proStatus()}1926                  initialSection={settingsInitialSection()}1927                  upgradeHighlight={upgradeHighlight()}1928                  isExiting={settingsExiting()}1929                  onBreachMonitoringChange={applyBreachMonitoring}1930                  onLockOnCloseChange={applyLockOnClose}1931                  onAutoLockMinutesChange={applyAutoLockMinutes}1932                  onTrashRetentionChange={applyTrashRetention}1933                  onThemeChange={applyTheme}1934                  onAccentChange={applyAccentColor}1935                  onTextSizeChange={applyTextSize}1936                  onReduceMotionChange={applyReduceMotion}1937                  shortcuts={shortcutBindings()}1938                  onShortcutsChange={applyShortcuts}1939                  onLicenseChange={async () => {1940                    // After activation/deactivation: refresh Pro status,1941                    // re-load entries (defensive — signal state can drift if1942                    // the SW briefly restarts during the verify+save round-trip),1943                    // and replay the Pro celebration if this is the first time1944                    // a valid Pro license is seen on this device.1945                    await refreshProStatus();1946                    void loadEntries();1947                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1948                    if ((should as { ok: boolean; data?: boolean }).data === true) {1949                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1950                      setView("pro-celebration");1951                      window.setTimeout(() => setView("settings"), 2500);1952                    }1953                  }}1954                  onBack={() => {1955                    setSettingsExiting(true);1956                    window.setTimeout(() => {1957                      setSettingsExiting(false);1958                      setSettingsInitialSection(null);1959                      setUpgradeHighlight(null);1960                      handleBack();1961                    }, 200);1962                  }}1963                  onImport={() => setView("import")}1964                  onExport={() => setView("export")}1965                  onBreachCheckDone={loadEntries}1966                  onOpenHealth={openHealth}1967                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1968                  onOpenFileImport={handleOpenFileImport}1969                  onOpenPanic={() => setView("panic")}1970                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1971                  onOpenCodexRestore={() => setView("codex-restore")}1972                  onCardChange={setSettingsActiveCard}1973                  onProGate={(feature) => {1974                    setUpgradeHighlight(feature);1975                    setSettingsInitialSection("license");1976                  }}1977                />1978              </Suspense>1979            </Show>1980            <Show when={view() === "codex-generate"}>1981              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1982                <CodexGenerateView1983                  isPro={proStatus()}1984                  onBack={() => setView("settings")}1985                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1986                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1987                  onVaultLocked={() => handleLock()}1988                />1989              </Suspense>1990            </Show>1991            <Show when={view() === "codex-restore"}>1992              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1993                <CodexRestoreView1994                  onBack={() => setView("lock")}1995                  onRestoreSuccess={async () => {1996                    // After restore the vault is unlocked; refresh entries1997                    // and route to the main vault list. handleUnlock is the1998                    // canonical post-unlock setup path.1999                    await handleUnlock();2000                  }}2001                />2002              </Suspense>2003            </Show>2004            <Show when={view() === "pair-device"}>2005              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2006                <PairDeviceView2007                  isPro={proStatus()}2008                  onProChanged={() => { void refreshProStatus(); }}2009                  onBack={() => setView("settings")}2010                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}2011                />2012              </Suspense>2013            </Show>2014            <Show when={view() === "add"}>2015              <AddView2016                entry={editEntry()}2017                entries={entries()}2018                onBack={handleBack}2019                onSave={handleSave}2020              />2021            </Show>2022            <Show when={view() === "import"}>2023              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2024                <ImportView onBack={() => setView("settings")} onImport={handleSave} />2025              </Suspense>2026            </Show>2027            <Show when={view() === "export"}>2028              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2029                <ExportView onBack={handleExportBack} />2030              </Suspense>2031            </Show>2032            <Show when={view() === "panic"}>2033              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2034                <PanicView2035                  onCancel={() => setView("settings")}2036                  onOpenExport={() => {2037                    setReturnToPanic(true);2038                    setView("export");2039                  }}2040                  onDestroyed={async () => {2041                    clearCanarySuppressions();2042                    // Fresh onboarding start after a destroy — don't let the2043                    // resume markers land the user mid-carousel.2044                    setOnboardingCardAtExit(0);2045                    void storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});2046                    clearOnboardingExit();2047                    setEntries([]);2048                    setSelectedEntry(null);2049                    setEditEntry(undefined);2050                    setHasVault(false);2051                    setOnboarded(false);2052                    setProStatus(false);2053                    setPendingPasskey(null);2054                    setUpgradeHighlight(null);2055                    setSettingsInitialSection(null);2056                    setPendingProNotice(null);2057                    setPendingCelebration(false);2058                    setReturnToPanic(false);2059                    setContentPhase("idle");2060                    setView("lock");2061                  }}2062                />2063              </Suspense>2064            </Show>2065            {/* Health stays mounted while editing an entry from it so2066                computeReused() doesn't rerun on every cancel/back. */}2067            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>2068              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2069                <HealthView2070                  entries={entries()}2071                  isPro={proStatus()}2072                  onFixEntry={handleFixEntry}2073                  onBack={() => setView("settings")}2074                  onRefresh={loadEntries}2075                  hidden={view() !== "health"}2076                />2077              </Suspense>2078            </Show>2079            <Show when={view() === "trash"}>2080              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2081                <TrashView2082                  onBack={() => setView("list")}2083                  onRestored={() => void loadEntries()}2084                />2085              </Suspense>2086            </Show>2087            <Show when={showNotes()}>2088              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>2089                <NotesMode2090                  notes={entries().filter((e) => e.type === "note")}2091                  initialNoteId={openNoteId()}2092                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}2093                  onNoteListChanged={() => void loadEntries()}2094                />2095              </div>2096            </Show>2097            <Show when={restoreView() === "file"}>2098              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2099                <ImportView2100                  mode="onboarding"2101                  replacesExistingVault={true}2102                  onBack={() => setRestoreView(null)}2103                  onImport={async () => {2104                    setRestoreView(null);2105                    await handleUnlock();2106                  }}2107                />2108              </Suspense>2109            </Show>2110            </section>2111            </Show>2112          </Show>2113        </Show>2114      </Show>2115      <Show when={showShortcutsHelp()}>2116        <ShortcutsHelpOverlay2117          bindings={shortcutBindings()}2118          onClose={() => setShowShortcutsHelp(false)}2119        />2120      </Show>2121    </div>2122  );2123}21242125function ShortcutsHelpOverlay(props: {2126  bindings: Record<ShortcutAction, Keybinding>;2127  onClose: () => void;2128}) {2129  return (2130    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>2131      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>2132        <div class="peach-shortcuts-help-head">2133          <h3>Keyboard shortcuts</h3>2134          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>2135        </div>2136        <div class="peach-shortcuts-help-body">2137          <p class="peach-settings-sub-label">ENTRY VIEW</p>2138          <ul>2139            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (2140              <li>2141                <span>{d.label}</span>2142                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2143              </li>2144            ))}2145          </ul>2146          <p class="peach-settings-sub-label">ANYWHERE</p>2147          <ul>2148            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (2149              <li>2150                <span>{d.label}</span>2151                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2152              </li>2153            ))}2154          </ul>2155        </div>2156      </div>2157    </div>2158  );2159}