App.tsx

79.4 KB · raw

1import { createEffect, createMemo, createSignal, For, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, 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 { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { NotesMode } from "./views/NotesMode";11import { ProCelebration } from "./views/ProCelebration";12import { VaultView, type SortOrder } from "./views/Vault";13import { EntryView } from "./views/Entry";14import { AddView } from "./views/Add";15import { PeachWordmark } from "./components/PeachMark";16import { PasskeyApprovalView } from "./views/PasskeyApproval";17import { extractDomain } from "../shared/domain";18import {19  syncIndicator,20  syncIndicatorLabel,21  type SyncOutcomeSummary,22} from "../shared/sync-outcome";23import { popupCopy } from "./copy";24import {25  DEFAULT_BINDINGS,26  formatKeybinding,27  getActiveBindings,28  matchKeybinding,29  SHORTCUT_DESCRIPTORS,30  type Keybinding,31  type ShortcutAction,32} from "../shared/shortcuts";33import { generateTOTP } from "../crypto/totp";34import { isNativePlatform, nativePlugin } from "../shared/native";3536export { sendMessage } from "../shared/bridge";3738const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));39const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));40const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));41const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));42const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));43const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));44const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));45const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));46const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));47const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));4849type View =50  | "lock"51  | "pro-celebration"52  | "entry"53  | "list"54  | "add"55  | "settings"56  | "pair-device"57  | "import"58  | "export"59  | "health"60  | "trash"61  | "panic"62  | "adopting"63  | "codex-generate"64  | "codex-restore";65type BootState = "loading" | "ready";6667const canarySuppressMap = new Map<string, boolean>();68let shellRingAnimation: Animation | null = null;6970export function isCanarySuppressed(entryId: string): boolean {71  return canarySuppressMap.get(entryId) ?? false;72}7374export function setCanarySuppressed(entryId: string, suppressed: boolean): void {75  canarySuppressMap.set(entryId, suppressed);76}7778export function clearCanarySuppressions(): void {79  canarySuppressMap.clear();80}8182export function triggerRing() {83  const shell = document.getElementById("hd-shell");84  if (!shell) return;8586  shellRingAnimation?.cancel();87  shell.dataset.glowing = "true";88  const animation = shell.animate(89    [90      { offset: 0, boxShadow: "var(--copy-shadow)" },91      {92        offset: 0.3,93        boxShadow:94          "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)",95      },96      { offset: 1, boxShadow: "var(--copy-shadow)" },97    ],98    {99      duration: 720,100      easing: "cubic-bezier(0.4, 0, 0.2, 1)",101      fill: "none",102    }103  );104  shellRingAnimation = animation;105  const clearGlow = () => {106    if (shellRingAnimation !== animation) return;107    shellRingAnimation = null;108    delete shell.dataset.glowing;109  };110  animation.onfinish = clearGlow;111  animation.oncancel = clearGlow;112}113114115export function triggerPipPulse() {116  const pip = document.querySelector(".peach-status-pip, .pip");117  if (pip) {118    pip.classList.remove("pulse");119    void (pip as HTMLElement).offsetWidth;120    pip.classList.add("pulse");121  }122}123124function defaultAdoptionDeviceName(): string {125  const ua = (typeof navigator !== "undefined" ? navigator.userAgent : "") || "";126  if (/Firefox/i.test(ua)) return "Firefox";127  if (/Edg\//i.test(ua)) return "Edge";128  if (/Chrome/i.test(ua)) return "Chrome";129  if (/Safari/i.test(ua)) return "Safari";130  return "Peach";131}132133const ENTRY_TRANSITION_SETTLE_MS = 135;134135export default function App() {136  const [bootState, setBootState] = createSignal<BootState>("loading");137  const [view, setView] = createSignal<View>("lock");138  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,139  // CSS transition takes over for snap animation).140  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);141  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(142    "enter"143  );144  const [contentTransitioning, setContentTransitioning] = createSignal(false);145  const [hasVault, setHasVault] = createSignal(false);146  const [onboarded, setOnboarded] = createSignal(true);147  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);148  const [entries, setEntries] = createSignal<VaultEntry[]>([]);149  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);150  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);151152  // UI-1 / HV-1b + MV-8d: remote-mutation alerts queued by the sync merge,153  // shown as dismissible banners on popup open.154  interface SyncAlert {155    type: "REMOTE_PASSWORD_CHANGE" | "REMOTE_DELETE" | "DEVICE_KEY_ROTATED";156    entryId: string;157    entryTitle: string;158    deviceName: string;159    timestamp: number;160  }161  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);162  async function loadSyncAlerts() {163    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {164      ok: boolean;165      data?: SyncAlert[];166    };167    if (r.ok && (r.data?.length ?? 0) > 0) {168      setSyncAlerts(r.data ?? []);169      // Acknowledge so a crash between read and render doesn't lose them —170      // they remain on screen until the user dismisses each.171      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });172    }173  }174  function dismissSyncAlert(index: number) {175    setSyncAlerts((arr) => arr.filter((_, i) => i !== index));176  }177  function syncAlertText(a: SyncAlert): string {178    if (a.type === "REMOTE_PASSWORD_CHANGE") {179      return `${a.deviceName} changed the password for ${a.entryTitle}`;180    }181    if (a.type === "REMOTE_DELETE") {182      return `${a.deviceName} deleted ${a.entryTitle}`;183    }184    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;185  }186  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");187  const [theme, setTheme] = createSignal<"dark" | "light">("dark");188  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");189  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);190  const [lockOnClose, setLockOnClose] = createSignal(true);191  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);192  const [breachMonitoring, setBreachMonitoring] = createSignal(true);193  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);194  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);195  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);196  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);197  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);198  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");199  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");200  // Cached Pro status — synchronous for render paths. Background's201  // GET_LICENSE is async, but render-time reads of isPro() must not block.202  // Refreshed at boot, after activate/deactivate, and whenever the popup203  // re-opens onto a stored license that has changed via another window.204  const [proStatus, setProStatus] = createSignal(false);205  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);206  // When the sync card's pairing button opens the pairing view, deep-link207  // straight into that pairing path instead of the rest screen.208  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");209  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);210  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");211  const [listSearchSeed, setListSearchSeed] = createSignal("");212  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);213  const [pendingCelebration, setPendingCelebration] = createSignal(false);214  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);215  // True while Panic Step 1 has bounced the user out to Export. When Export's216  // onBack fires we return to Panic instead of Settings so the user keeps the217  // destruction context they came from.218  const [returnToPanic, setReturnToPanic] = createSignal(false);219  // The view to return to when the add/edit view is dismissed. Normally "entry"220  // but "health" when the user arrives via the fix-entry path from Vault Health.221  const [editBackView, setEditBackView] = createSignal<View>("entry");222  const [settingsExiting, setSettingsExiting] = createSignal(false);223  const [showNotes, setShowNotes] = createSignal(false);224  // Topbar sync affordance. Always present: gating it on having a paired device225  // meant it never appeared for the person trying to set pairing up, which is226  // exactly when you reach for it.227  const [syncBusy, setSyncBusy] = createSignal(false);228  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);229  // The indicator light + its spoken-word equivalent. Colour alone is not the230  // signal; the title/aria-label always carries the same claim in English.231  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});232  const [pairedCount, setPairedCount] = createSignal(0);233  const syncLight = () =>234    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());235  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());236  async function loadSyncIndicator() {237    const [stateRes, devicesRes] = await Promise.all([238      sendMessage({ type: "GET_SYNC_STATE" }),239      sendMessage({ type: "LIST_PAIRED_DEVICES" }),240    ]);241    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };242    if (s.ok && s.data) setSyncSummary(s.data);243    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };244    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);245  }246  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);247  // Set on popup boot when peach_recovery_pending flag is found in session248  // storage — instructs LockView to skip the unlock UI and open the recovery249  // words confirmation surface instead. Cleared via handleUnlock once the250  // user has typed the 3 confirmation words.251  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);252253  let contentPhaseTimer: number | undefined;254  // Set when the popup was opened from the inline "Open Peach to unlock" button.255  // handleUnlock() closes the popup after unlock so the user returns to the page.256  let openedForInlineUnlock = false;257258  function applyAccent(name: AccentColorName) {259    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;260    const hex = color.hex;261    document.documentElement.style.setProperty("--peach-accent", hex);262    // Ambient surface variables — derived from the accent so surfaces shift263    // subtly toward the accent hue rather than staying fixed warm-brown.264    document.documentElement.style.setProperty("--peach-glow", hex + "2A");265    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");266    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");267  }268269  createEffect(() => {270    applyAccent(accentColor());271  });272273  createEffect(() => {274    document.documentElement.classList.toggle("light", theme() === "light");275    document.body.classList.toggle("light", theme() === "light");276  });277278  createEffect(() => {279    document.documentElement.setAttribute("data-text-size", textSize());280  });281282  createEffect(() => {283    if (reduceMotion()) {284      document.documentElement.setAttribute("data-motion", "reduce");285    } else {286      document.documentElement.removeAttribute("data-motion");287    }288  });289290  const selectedIndex = createMemo(() => {291    const currentId = selectedEntry()?.id;292    if (!currentId) return entries().length > 0 ? 0 : -1;293    return entries().findIndex((entry) => entry.id === currentId);294  });295296  async function applyAccentColor(name: AccentColorName) {297    applyAccent(name);298    setAccentColor(name);299    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });300  }301302  async function applyTheme(t: "dark" | "light") {303    setTheme(t);304    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });305  }306307  async function applyTextSize(size: "small" | "medium" | "large") {308    setTextSize(size);309    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });310  }311312  async function applyReduceMotion(enabled: boolean) {313    setReduceMotion(enabled);314    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });315  }316317  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload318  // small and lets future default updates land for actions the user hasn't319  // touched. Settings sends us the full active map; we filter and store.320  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {321    setShortcutBindings(active);322    const overrides: Record<string, Keybinding> = {};323    for (const action of Object.keys(active) as ShortcutAction[]) {324      const a = active[action];325      const d = DEFAULT_BINDINGS[action];326      const same = a.key === d.key327        && Boolean(a.ctrl)  === Boolean(d.ctrl)328        && Boolean(a.meta)  === Boolean(d.meta)329        && Boolean(a.shift) === Boolean(d.shift)330        && Boolean(a.alt)   === Boolean(d.alt);331      if (!same) overrides[action] = a;332    }333    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });334  }335336  async function applyLockOnClose(enabled: boolean) {337    setLockOnClose(enabled);338    await sendMessage({339      type: "UPDATE_SETTINGS",340      payload: { lockOnClose: enabled },341    });342  }343344  async function applyAutoLockMinutes(minutes: number) {345    setAutoLockMinutes(minutes);346    await sendMessage({347      type: "UPDATE_SETTINGS",348      payload: { autoLockMinutes: minutes },349    });350  }351352  async function applyBreachMonitoring(enabled: boolean) {353    setBreachMonitoring(enabled);354    await sendMessage({355      type: "UPDATE_SETTINGS",356      payload: { breachMonitoring: enabled },357    });358  }359360  onMount(async () => {361    // Resolve the active tab in parallel with the unlock/has-vault queries —362    // openVault()'s smart selection picks the entry matching currentTabDomain,363    // so it must be populated before openVault runs. Previously refreshCurrentTab364    // ran after openVault, leaving popups that booted already-unlocked falling365    // back to loadedEntries[0] instead of the domain match.366    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([367      sendMessage({ type: "IS_UNLOCKED" }),368      sendMessage({ type: "HAS_VAULT" }),369      refreshCurrentTab(),370      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),371    ]);372    const unlocked = Boolean(373      (unlockResponse as { ok: boolean; data?: boolean }).data374    );375    const vaultExists = Boolean(376      (vaultResponse as { ok: boolean; data?: boolean }).data377    );378    const shouldCelebrate = Boolean(379      (celebrationResponse as { ok: boolean; data?: boolean }).data380    );381    setHasVault(vaultExists);382    // Onboarding gate — show once on first install, never again. Existing383    // users (vaultExists) are auto-marked onboarded so they skip the flow384    // even on the very first popup open after this feature ships.385    try {386      const onboarded = await storageGet("peach_onboarded");387      const seen = onboarded === "true";388      if (vaultExists && !seen) {389        await storageSet("peach_onboarded", "true");390        setOnboarded(true);391      } else {392        setOnboarded(seen);393      }394    } catch {395      // storage unavailable — default to onboarded so we never block boot396      setOnboarded(true);397    }398    await Promise.all([restoreSettings(), refreshProStatus()]);399400    // Mark played before any animation so a crash mid-sequence never replays it401    if (shouldCelebrate) {402      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });403    }404405    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome406    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.407    if (unlocked && vaultExists) {408      void sendMessage({409        type: "TRIGGER_SYNC",410        payload: { reason: "foreground" },411      });412      void loadSyncIndicator();413      // UI-1 / HV-1b: surface any remote-mutation alerts the sync merge queued.414      void loadSyncAlerts();415    }416417    // If the user created a vault but hasn't yet confirmed their recovery418    // words, route back to the recovery-words screen instead of opening the419    // entries view. The flag lives in chrome.storage.local so it survives420    // both popup close (SW suppresses lock-on-close) and full browser421    // restart (handleUnlock checks the same flag after a fresh password422    // unlock). Cleared when confirmation succeeds.423    let recoveryPending = false;424    try {425      const out = await chrome.storage.local?.get("peach_recovery_pending");426      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";427    } catch { /* best-effort */ }428429    // If this popup was opened from the inline "Open Peach to unlock" button,430    // the background set a session flag. Read and clear it so handleUnlock()431    // can close the popup after unlock and return the user to the page.432    if (chrome.storage.session) {433      try {434        const s = await chrome.storage.session.get("peach_inline_unlock");435        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {436          openedForInlineUnlock = true;437          await chrome.storage.session.remove("peach_inline_unlock");438        }439      } catch { /* best-effort */ }440    }441442    // Native: closing the app before recovery-words confirmation means the443    // user didn't finish vault creation. Throw the partial vault away and444    // restart onboarding rather than asking them to unlock a vault they445    // never finished creating. Desktop keeps the existing "unlock to446    // resume" flow because closing the popup there is much more casual.447    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {448      try {449        await chrome.storage.local?.remove([450          "peach_vault_a",451          "peach_vault_b",452          "peach_recovery_pending",453          "peach_onboarded",454          "peach_vault_history",455        ]);456      } catch { /* best-effort */ }457      setHasVault(false);458      setOnboarded(false);459      setView("lock");460      setBootState("ready");461      return;462    }463464    if (recoveryPending && unlocked) {465      // forceRecoveryWords overrides LockView's hasVault gate so the466      // recovery surface renders even though the vault now exists.467      setForceRecoveryWords(true);468      setView("lock");469    } else if (unlocked && vaultExists) {470      await openVault(undefined, shouldCelebrate);471      if (shouldCelebrate) {472        setView("pro-celebration");473        window.setTimeout(() => setView("entry"), 2500);474      }475    } else if (shouldCelebrate) {476      setPendingCelebration(true);477    }478479    await refreshPendingPasskey();480481    // Track tab changes so smart sort stays current482    const handleTabActivated = () => { void refreshCurrentTab(); };483    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {484      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();485    };486    try {487      chrome.tabs.onActivated.addListener(handleTabActivated);488      chrome.tabs.onUpdated.addListener(handleTabUpdated);489      onCleanup(() => {490        chrome.tabs.onActivated.removeListener(handleTabActivated);491        chrome.tabs.onUpdated.removeListener(handleTabUpdated);492      });493    } catch {494      // tabs permission may not be available in all contexts495    }496497    setBootState("ready");498499    // Deep-link: ?codex=pdf opens a detached window straight into the500    // Codex restore flow with auto-picked PDF. The action popup can't host501    // a file dialog without dismissing itself, so this is the only way the502    // PDF import path survives. See CodexRestoreView.openPdfPicker().503    try {504      const route = new URLSearchParams(window.location.search).get("codex");505      if (route === "pdf" || route === "restore") {506        setView("codex-restore");507      }508    } catch {509      // location.search unavailable — ignore.510    }511512    // Check for pending session-storage notices from the background.513    if (chrome.storage.session) {514      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as515        Record<string, { feature?: string } | undefined>;516      if (session.pendingProGate?.feature) {517        await chrome.storage.session.remove("pendingProGate");518        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);519        setSettingsInitialSection("license");520        setView("settings");521      } else if (session.pendingProNotice?.feature) {522        await chrome.storage.session.remove("pendingProNotice");523        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });524      }525    }526527    // Warm the lazy-module cache so the Suspense fallback never shows for528    // locally-bundled extension views. Without this, the first navigation to529    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which530    // covers the shell and absorbs clicks on the header.531    void Promise.all([532      import("./views/Settings").catch(() => {}),533      import("./views/Import").catch(() => {}),534      import("./views/Export").catch(() => {}),535      import("./views/Health").catch(() => {}),536      import("./views/TrashView").catch(() => {}),537    ]);538539    // Lock-on-close via a persistent port. sendMessage in pagehide is540    // unreliable — the popup context tears down before the message lands.541    // The SW's onConnect listener locks when this port disconnects.542    let popupPort: chrome.runtime.Port | null = null;543    try {544      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect545      // listener accepts the "popup-" prefix; the random suffix is defence in546      // depth against a port named exactly "popup" from anything but our popup.547      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });548    } catch { /* extension context invalidated — ignore */ }549    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });550551    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only552    // reliable signal is appStateChange — setTimeout is killed when the OS553    // backgrounds the app. We measure elapsed background time on resume.554    if (isNativePlatform()) {555      let backgroundedAt: number | null = null;556557      const CapApp = nativePlugin<{558        addListener: (559          ev: string,560          cb: (s: { isActive: boolean }) => void,561        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };562      }>("App");563      if (CapApp?.addListener) {564        const sub = CapApp.addListener(565          "appStateChange",566          ({ isActive }: { isActive: boolean }) => {567            if (!isActive) {568              backgroundedAt = Date.now();569              return;570            }571            if (backgroundedAt !== null && autoLockMinutes() > 0) {572              const elapsed = Date.now() - backgroundedAt;573              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();574            }575            backgroundedAt = null;576          }577        );578        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.579        onCleanup(() => {580          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});581        });582      }583584      // L12/COR-011: foreground idle autolock. appStateChange only fires when585      // the OS backgrounds the app — if the user idles with the screen on,586      // chrome.alarms is no-op'd in Capacitor so the vault would stay open587      // indefinitely. Poll every 30s and lock if elapsed since last user588      // interaction exceeds autoLockMinutes.589      let lastUserActivityAt = Date.now();590      const bumpActivity = () => { lastUserActivityAt = Date.now(); };591      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;592      for (const ev of ACTIVITY_EVENTS) {593        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });594      }595      const idleLockInterval = setInterval(() => {596        const minutes = autoLockMinutes();597        if (!minutes || minutes <= 0) return;598        const elapsed = Date.now() - lastUserActivityAt;599        if (elapsed >= minutes * 60_000) {600          lastUserActivityAt = Date.now();601          handleHeaderLock();602        }603      }, 30_000);604      onCleanup(() => {605        clearInterval(idleLockInterval);606        for (const ev of ACTIVITY_EVENTS) {607          document.removeEventListener(ev, bumpActivity, { capture: true });608        }609      });610611      // The retired native peer-discovery trigger went with the old Capacitor612      // pairing plugin. Reconnection is address-cache first, subnet probe second613      // (sync-runner.ts); relocating a peer that changed networks is an614      // Android-side discovery concern now.615      if (isNativePlatform()) {616        // Android runs the background/sync dispatcher in-process with the617        // popup, so the production runner has to be registered from the618        // UI bootstrap path instead of the MV3 service-worker entry.619        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>620          import("../background/sync-runner").then(({ productionSyncRunner }) => {621            setSyncRunner(productionSyncRunner);622            void hydratePersistedSyncState();623          })624        );625      }626    }627628    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale629    // entries instead of waiting for the next GET_ENTRIES round-trip.630    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {631      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();632      if (msg?.type === "SYNC_STATE_CHANGED") {633        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);634      }635      if (msg?.type === "PRO_GATE_TRIGGERED") {636        setUpgradeHighlight(msg.payload?.feature ?? null);637        setSettingsInitialSection("license");638        setView("settings");639      }640    };641    chrome.runtime.onMessage.addListener(handleRuntimeMessage);642    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));643644    // Android hardware/gesture back. MainActivity fires peach:back; the popup645    // decides what "back" means per surface. Lock+no-vault is the common case646    // — return to onboarding rather than letting the OS dismiss the activity.647    const handlePeachBack = () => {648      // Notes mode captures back first649      if (showNotes()) {650        setShowNotes(false);651        setOpenNoteId(undefined);652        return;653      }654      const v = view();655      if (v === "lock" && !hasVault() && onboarded()) {656        setOnboarded(false);657        return;658      }659      if (v === "list") { setView("entry"); return; }660      if (v === "settings") {661        window.dispatchEvent(new Event("peach:settings-back"));662        return;663      }664      if (v === "import" || v === "health") { setView("settings"); return; }665      if (v === "export") { handleExportBack(); return; }666      if (v === "add") { handleBack(); return; }667      if (v === "pair-device") { setView("settings"); return; }668    };669    window.addEventListener("peach:back", handlePeachBack);670    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));671672    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that673    // peeks from the bottom (search bar handle visible) and drags up to fill674    // the screen. dragOffset is the LIVE finger offset during a drag, in px,675    // 0 when no drag in progress. The wrapper element computes transform =676    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.677    if (isNativePlatform()) {678      let touchStartY = 0;679      let touchStartX = 0;680      let lastY = 0;681      let lastT = 0;682      let dragging = false;683      let captured = false;684      const HORIZONTAL_TOLERANCE = 16;685      const ACTIVATION_DY = 8;686      const PEEK_PX = 60;687688      const onTouchStart = (e: TouchEvent) => {689        const t = e.touches[0];690        if (!t) return;691        const v = view();692        if (v !== "entry" && v !== "list") return;693        // Entry view: only intercept drags starting in the bottom 40%.694        // List view: intercept drags starting in the top 35% (the search/handle row).695        const inBand = v === "entry"696          ? t.clientY > window.innerHeight * 0.6697          : t.clientY < window.innerHeight * 0.35;698        if (!inBand) return;699        touchStartY = lastY = t.clientY;700        touchStartX = t.clientX;701        lastT = e.timeStamp;702        dragging = true;703        captured = false;704      };705706      const onTouchMove = (e: TouchEvent) => {707        if (!dragging) return;708        const t = e.touches[0];709        if (!t) return;710        const dy = t.clientY - touchStartY;711        const dx = Math.abs(t.clientX - touchStartX);712713        if (!captured) {714          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {715            // Looks like a horizontal swipe — release.716            dragging = false;717            return;718          }719          if (Math.abs(dy) < ACTIVATION_DY) return;720          captured = true;721        }722723        // Translate the sheet by dy from its rest (peek) position. Peek is724        // (viewport height - PEEK_PX). Open is 0.725        const v = view();726        const restClosed = window.innerHeight - PEEK_PX;727        const baseTranslate = v === "list" ? 0 : restClosed;728        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));729        setSheetTranslate(next);730        lastY = t.clientY;731        lastT = e.timeStamp;732      };733734      const onTouchEnd = (e: TouchEvent) => {735        if (!dragging) { return; }736        const t = e.changedTouches[0];737        const elapsed = Math.max(1, e.timeStamp - lastT);738        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms739        const wasCaptured = captured;740        dragging = false;741        captured = false;742        const v = view();743744        if (!wasCaptured) {745          // Tap in the peek strip while in entry view → open the vault list.746          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");747          setSheetTranslate(null);748          return;749        }750751        const restClosed = window.innerHeight - PEEK_PX;752        const current = sheetTranslate() ?? restClosed;753754        // Snap rules:755        //   - Strong upward velocity → open756        //   - Strong downward velocity → close757        //   - Otherwise snap to whichever rest is closer758        let nextOpen: boolean;759        if (velocity < -0.05) nextOpen = true;760        else if (velocity > 0.05) nextOpen = false;761        else nextOpen = current < restClosed * 0.5;762763        if (nextOpen && v !== "list") setView("list");764        if (!nextOpen && v !== "entry") setView("entry");765        // Release the live offset so CSS transition handles the snap.766        setSheetTranslate(null);767      };768769      document.addEventListener("touchstart", onTouchStart, { passive: true });770      document.addEventListener("touchmove",  onTouchMove,  { passive: true });771      document.addEventListener("touchend",   onTouchEnd,   { passive: true });772      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });773      onCleanup(() => {774        document.removeEventListener("touchstart", onTouchStart);775        document.removeEventListener("touchmove",  onTouchMove);776        document.removeEventListener("touchend",   onTouchEnd);777      });778    }779780    // Action handlers — keyed by ShortcutAction. The dispatcher below tests781    // each binding against the event and runs the matching handler. New782    // shortcuts only need an entry here; the binding is data, not code.783    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {784      copy_password: () => {785        const entry = selectedEntry();786        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });787      },788      copy_username: () => {789        const entry = selectedEntry();790        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });791      },792      copy_totp: () => {793        const entry = selectedEntry();794        if (!entry?.totp) return;795        try {796          const { code } = generateTOTP(entry.totp);797          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });798        } catch { /* invalid TOTP secret — silent */ }799      },800      new_entry: () => handleAdd(),801      edit_entry: () => {802        const entry = selectedEntry();803        // Passkey-only entries have nothing user-editable in the Add view; the804        // passkey credential itself is opaque. Skip the edit action for them.805        if (!entry || isPasskeyOnly(entry)) return;806        setEditEntry(entry);807        setView("add");808      },809      delete_entry: () => {810        if (selectedEntry()) void handleDelete();811      },812      lock_vault: () => { void handleHeaderLock(); },813      search: () => openList(),814      nav_prev: () => navigate(-1),815      nav_next: () => navigate(1),816      jump_vault: () => setView("entry"),817      jump_settings: () => setView("settings"),818      show_help: () => setShowShortcutsHelp(true),819    };820821    // Actions that are MEANINGFUL only on the entry-detail view. Outside822    // that scope the binding is dormant — pressing C while on Settings823    // does nothing rather than awkwardly copying from a now-stale entry.824    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([825      "copy_password", "copy_username", "copy_totp",826      "edit_entry", "delete_entry", "nav_prev", "nav_next",827    ]);828829    const handleGlobalKeydown = (e: KeyboardEvent) => {830      const v = view();831      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"832        || (e.target as HTMLElement)?.tagName === "TEXTAREA"833        || (e.target as HTMLElement)?.isContentEditable;834      const isPrintableSearchKey =835        e.key.length === 1 &&836        !e.ctrlKey &&837        !e.metaKey &&838        !e.altKey;839840      // No input during the pro celebration sequence841      if (v === "pro-celebration") return;842843      // Help dialog: Escape closes it; eat the keypress so it doesn't844      // also navigate away from the underlying view.845      if (showShortcutsHelp()) {846        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }847        return;848      }849850      // ── Escape — fixed binding (not user-customizable) ───────851      if (e.key === "Escape") {852        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }853        if (v === "list") { setView("entry"); return; }854        if (v === "settings" || v === "add") { handleBack(); return; }855        if (v === "import" || v === "health") { setView("settings"); return; }856        if (v === "export") { handleExportBack(); return; }857        if (v === "pair-device") { setView("settings"); return; }858      }859860      // Bindings-driven dispatch. Single-key letter bindings without861      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is862      // inside an input, so users can type into search/forms normally.863      const bindings = shortcutBindings();864      for (const action of Object.keys(bindings) as ShortcutAction[]) {865        const binding = bindings[action];866        if (!matchKeybinding(e, binding)) continue;867        // Single-key letter bindings need the input-focus guard. Bindings868        // with any modifier are safe — Ctrl+L doesn't conflict with typing.869        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;870        if (!hasMod && binding.key.length === 1 && inInput) return;871        if (ENTRY_SCOPED.has(action) && v !== "entry") return;872        e.preventDefault();873        SHORTCUT_HANDLERS[action]?.();874        return;875      }876877      // Type-to-search: in entry view, any printable key not consumed by a878      // shortcut above primes the list search seed and opens the list.879      // Kept outside the bindings table because it's a behavior, not a880      // discrete action — every printable character can trigger it.881      if (v === "entry" && !inInput && isPrintableSearchKey) {882        e.preventDefault();883        primeListSearch(e.key);884        return;885      }886    };887    window.addEventListener("keydown", handleGlobalKeydown);888    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));889890    const handleStorageChanged = (891      changes: Record<string, chrome.storage.StorageChange>,892      areaName: string893    ) => {894      if (areaName !== "session") return;895      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {896        return;897      }898      void refreshPendingPasskey();899    };900    chrome.storage.onChanged.addListener(handleStorageChanged);901    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));902  });903904  async function refreshCurrentTab() {905    try {906      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });907      const url = tab?.url ?? tab?.pendingUrl ?? "";908      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");909      // Skip extension/internal URLs — adding chrome://, about:, or910      // chrome-extension:// to a vault entry is never what the user wants.911      const isWebUrl = /^https?:\/\//i.test(url);912      setCurrentTabUrl(isWebUrl ? url : "");913    } catch {914      setCurrentTabDomain("");915      setCurrentTabUrl("");916    }917  }918919  async function refreshPendingPasskey() {920    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });921    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);922  }923924  async function refreshProStatus() {925    const res = await sendMessage({ type: "GET_LICENSE" });926    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;927    setProStatus(Boolean(data?.valid && data?.plan === "pro"));928  }929930  async function restoreSettings() {931    const res = await sendMessage({ type: "GET_SETTINGS" });932    const s = (res as { ok: boolean; data?: any }).data ?? {};933    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {934      setAccentColor(s.accentColor as AccentColorName);935    }936    setTheme(s.theme === "light" ? "light" : "dark");937    if (s.textSize === "small" || s.textSize === "large") {938      setTextSize(s.textSize);939    } else {940      setTextSize("medium");941    }942    setReduceMotion(s.reduceMotion === true);943    setLockOnClose(s.lockOnClose !== false);944    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);945    setBreachMonitoring(s.breachMonitoring !== false);946    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);947    setShortcutBindings(getActiveBindings(s.shortcuts));948  }949950  async function applyTrashRetention(days: number) {951    setTrashRetentionDays(days);952    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });953  }954955  function primeListSearch(seed: string) {956    setListSearchSeed(seed);957    setListSearchSeedNonce((value) => value + 1);958    openList();959  }960961  // Returns null when it detected a dead service worker and triggered handleLock().962  // Callers that need to abort (e.g. openVault) check for null rather than relying963  // on view() state, which may already be "lock" during normal startup flows.964  async function loadEntries(): Promise<VaultEntry[] | null> {965    const response = await sendMessage({ type: "GET_ENTRIES" });966    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };967968    // If the service worker was killed and restarted (MV3 workers sleep), the969    // vault will be locked again — or the worker may not respond at all.970    // In either case, send the user to the lock screen rather than silently971    // showing an empty vault (which looks like data loss).972    if (!res.ok) {973      if (974        res.error === "vault_locked" ||975        res.error === "SERVICE_WORKER_UNAVAILABLE" ||976        (typeof res.error === "string" && res.error.includes("locked"))977      ) {978        handleLock();979        return null; // signal emergency lock to callers980      }981      return [];982    }983984    const loadedEntries = res.data ?? [];985    setEntries(loadedEntries);986987    const currentId = selectedEntry()?.id;988    if (currentId) {989      setSelectedEntry(990        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null991      );992    }993994    return loadedEntries;995  }996997  async function openVault(preferredEntryId?: string, skipViewSet = false) {998    // Purge expired trash entries on each vault open999    const retDays = trashRetentionDays();1000    if (retDays > 0) {1001      void sendMessage({1002        type: "PURGE_EXPIRED_TRASH",1003        payload: { retentionMs: retDays * 86_400_000 },1004      });1005    }10061007    const loadedEntries = await loadEntries();10081009    // null means loadEntries() triggered an emergency lock (service worker died).1010    // Don't override it by setting view back to "entry" with an empty vault.1011    if (loadedEntries === null) return;10121013    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1014    let nextSelectedEntry: VaultEntry | null = null;1015    if (preferredEntryId) {1016      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1017    }1018    if (!nextSelectedEntry) {1019      const tabDomain = currentTabDomain();1020      if (tabDomain) {1021        nextSelectedEntry = loadedEntries.find((e) => {1022          if (e.type === "login") {1023            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1024            for (const extra of e.additionalUrls ?? []) {1025              if ((extractDomain(extra) ?? "") === tabDomain) return true;1026            }1027            return false;1028          }1029          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1030          return false;1031        }) ?? null;1032      }1033    }1034    nextSelectedEntry ??= loadedEntries[0] ?? null;10351036    setSelectedEntry(nextSelectedEntry);1037    setEditEntry(undefined);1038    setContentTransitioning(false);1039    setContentPhase("enter");1040    queueContentIdle();1041    if (!skipViewSet) setView("entry");1042  }10431044  async function handleUnlock() {1045    // If the user previously created a vault but hadn't yet confirmed their1046    // recovery words (and the browser was closed before they could), the1047    // peach_recovery_pending flag is still set in storage.local. Re-route1048    // back to the recovery surface so they finish the confirmation step1049    // before reaching the entries view — the words can be re-derived now1050    // that the vault is unlocked again.1051    let recoveryPending = false;1052    try {1053      const out = await chrome.storage.local?.get("peach_recovery_pending");1054      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1055    } catch { /* best-effort */ }1056    if (recoveryPending) {1057      setForceRecoveryWords(true);1058      setView("lock");1059      triggerPipPulse();1060      await restoreSettings();1061      return;1062    }1063    setHasVault(true);1064    triggerPipPulse();1065    await restoreSettings();1066    const celebrating = pendingCelebration();1067    if (celebrating) {1068      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1069      setPendingCelebration(false);1070    }1071    await openVault(undefined, celebrating);1072    if (celebrating) {1073      setView("pro-celebration");1074      window.setTimeout(() => setView("entry"), 2500);1075    }1076    // Popup was opened from the inline "Open Peach to unlock" button — close it1077    // now so the user lands back on the page with the autofill selector ready.1078    if (openedForInlineUnlock) {1079      openedForInlineUnlock = false;1080      window.close();1081    }1082  }10831084  function handleSelectEntry(entry: VaultEntry) {1085    if (entry.type === "note") {1086      setOpenNoteId(entry.id);1087      setShowNotes(true);1088      return;1089    }1090    setSelectedEntry(entry);1091    setContentTransitioning(false);1092    setContentPhase("enter");1093    queueContentIdle();1094    setView("entry");1095  }10961097  function handleAdd() {1098    setEditEntry(undefined);1099    setView("add");1100  }11011102  async function handleDelete() {1103    const entry = selectedEntry();1104    if (!entry) return;1105    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1106    const loadedEntries = await loadEntries() ?? [];1107    setSelectedEntry(loadedEntries[0] ?? null);1108    setView("entry");1109  }11101111  async function handleDeleteMany(ids: string[]) {1112    for (const id of ids) {1113      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1114    }1115    const loadedEntries = await loadEntries() ?? [];1116    // If the currently selected entry was among the deleted, move to first1117    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1118    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1119  }11201121  async function handleSave(savedEntry?: VaultEntry) {1122    await openVault(savedEntry?.id);1123  }11241125  function handleBack() {1126    const dest = editBackView();1127    setEditBackView("entry");1128    setEditEntry(undefined);1129    setView(dest);1130  }11311132  function handleExportBack() {1133    if (returnToPanic()) {1134      setReturnToPanic(false);1135      setView("panic");1136      return;1137    }1138    setView("settings");1139  }11401141  function handleLock() {1142    clearCanarySuppressions();1143    setEntries([]);1144    setSelectedEntry(null);1145    setEditEntry(undefined);1146    setContentPhase("idle");1147    setView("lock");1148  }11491150  function handleHeaderLock() {1151    // Lock the UI immediately — do not wait for the service worker. If the SW1152    // is dead or slow, the 5s sendMessage timeout would create a dead-click1153    // window. The SW will lock on its next wake regardless.1154    handleLock();1155    void sendMessage({ type: "LOCK" });1156  }11571158  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1159  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1160  // the trigger's own reply.1161  async function handleHeaderSync(): Promise<void> {1162    if (syncBusy()) return;1163    setSyncBusy(true);1164    setSyncFlash(null);1165    try {1166      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1167      let state: SyncOutcomeSummary = { status: "syncing" };1168      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1169        await new Promise((r) => setTimeout(r, 250));1170        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1171          ok: boolean;1172          data?: SyncOutcomeSummary;1173        };1174        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1175      }1176      setSyncSummary(state);1177      setSyncFlash(state.status === "error" ? "error" : "ok");1178      await loadSyncAlerts();1179      await loadEntries();1180      await loadSyncIndicator();1181    } catch {1182      setSyncSummary({ status: "error", outcome: "run_failed" });1183      setSyncFlash("error");1184    } finally {1185      setSyncBusy(false);1186      setTimeout(() => setSyncFlash(null), 2_000);1187    }1188  }11891190  function navigate(dir: number) {1191    const allEntries = entries();1192    if (allEntries.length === 0) return;1193    const currentIndex = selectedIndex();1194    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1195    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1196    setSelectedEntry(allEntries[nextIndex]);1197    setContentPhase("enter");1198    queueContentIdle();1199  }12001201  function openList() {1202    setView("list");1203  }12041205  function openHealth() {1206    setEditEntry(undefined);1207    setView("health");1208  }12091210  function handleOpenFileImport() {1211    setRestoreView("file");1212  }12131214  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;12151216  function handleFixEntry(entry: VaultEntry) {1217    setSelectedEntry(entry);1218    // Passkey-only entries have no editable surface — drop into view mode1219    // instead of opening the Add editor.1220    if (isPasskeyOnly(entry)) {1221      setView("entry");1222      return;1223    }1224    setEditBackView(view()); // preserve caller view so back returns here1225    setEditEntry(entry);1226    setView("add");1227  }12281229  const isLockedView = () => view() === "lock" || view() === "adopting";12301231  async function handleAdoptionDone() {1232    await storageSet("peach_onboarded", "true").catch(() => {});1233    setOnboarded(true);1234    setHasVault(true);1235    await handleUnlock();1236    void sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "foreground" } });1237  }12381239  /**1240   * Join an existing vault from a brand-new install.1241   *1242   * This used to require the receiver to LISTEN for the other device (a1243   * Capacitor pairing server), which a browser extension structurally cannot1244   * do — so on every real browser build it threw before doing anything. Over a1245   * pairing code the receiver is the DIALLER instead, which is the only shape1246   * that works here: dial the code, confirm the SAS, then ask for the vault.1247   *1248   * The vault does not exist yet at dial time, so nothing in this path may1249   * touch the vault before `createVaultFromRootKey` runs.1250   */1251  async function startVaultAdoption(args: {1252    password: string;1253    connection: { invitation: string };1254    confirmSAS(sas: string): Promise<boolean>;1255    createVault(rootKeyHex: string): Promise<{ vaultId: string }>;1256  }) {1257    const [{ dialRelayPairingChannel, openRelayPairingSocket }, { requestAdoption }] =1258      await Promise.all([1259        import("../shared/pairing-dial"),1260        import("../shared/vault-adopt"),1261      ]);12621263    const dial = await dialRelayPairingChannel(args.connection.invitation, {1264      openSocket: openRelayPairingSocket,1265    });1266    if (!dial.ok) throw new Error(dial.error);1267    const { channel, sas, socket, relayUrl, rendezvousSecretHex } = dial.dialled;12681269    try {1270      const source = await requestAdoption(channel, {1271        deviceName: defaultAdoptionDeviceName(),1272        generateDeviceId: () => crypto.randomUUID(),1273        // requestAdoption writes ADOPT_CONFIRM and refuses to read a root-key1274        // grant until this local SAS decision is true.1275        confirmSas: () => args.confirmSAS(sas),1276        pairState: { rendezvousSecretHex, relayUrl },1277        createVaultFromRootKey: args.createVault,1278        deriveLocalIdentity: async () => {1279          const res = await sendMessage({ type: "GET_LOCAL_IDENTITY" });1280          const r = res as { ok: boolean; data?: unknown; error?: string };1281          if (!r.ok || !r.data) throw new Error(r.error ?? "identity_unavailable");1282          return r.data as Awaited<ReturnType<Parameters<typeof requestAdoption>[1]["deriveLocalIdentity"]>>;1283        },1284        upsertPairedDevice: async (paired) => {1285          const res = await sendMessage({ type: "COMPLETE_PAIRING", payload: { paired } });1286          const r = res as { ok: boolean; error?: string };1287          if (!r.ok) throw new Error(r.error ?? "complete_pairing_failed");1288        },1289        applyLicense: async (license) => {1290          const res = (await sendMessage({1291            type: "ACTIVATE_LICENSE",1292            payload: { key: license },1293          })) as { ok: boolean; data?: { valid?: boolean; plan?: string } };1294          if (res.ok && res.data?.valid && res.data?.plan === "pro") await refreshProStatus();1295        },1296        onError(error) {1297          throw new Error(1298            error === "ADOPT_SAS_REJECTED" ? "sas_rejected" : error,1299          );1300        },1301      });1302      if (!source) throw new Error("adoption_rejected");1303      if (relayUrl) {1304        // Adopt the source's relay so this device dials the same rendezvous.1305        const setting = (await sendMessage({1306          type: "SET_SYNC_SETTINGS",1307          payload: { relayUrl },1308        })) as { ok: boolean; error?: string };1309        if (!setting.ok) throw new Error(setting.error ?? "relay_settings_failed");1310      }1311    } finally {1312      socket.close();1313    }1314  }13151316  async function handleApprovePendingPasskey() {1317    const pending = pendingPasskey();1318    if (!pending) return;1319    if (pending.browser === "firefox" && pending.type === "create") {1320      // Firefox path: popup itself runs navigator.credentials.create. The1321      // background never approved/rejected anything — it just stashed1322      // intent. After the popup-driven flow resolves (success or cancel),1323      // clear the pending key so the popup doesn't re-show this on next open.1324      const { createFirefoxPasskey } = await import("./firefox-passkey");1325      const result = await createFirefoxPasskey(pending);1326      if (!result.ok) {1327        console.warn("Peach Firefox passkey create failed:", result.error);1328      }1329      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1330      setPendingPasskey(null);1331      void loadEntries();1332      window.close();1333      return;1334    }1335    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1336    window.close();1337  }13381339  async function handleDenyPendingPasskey() {1340    const pending = pendingPasskey();1341    if (!pending) return;1342    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1343    window.close();1344  }13451346  function queueContentIdle(after?: () => void) {1347    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1348    contentPhaseTimer = window.setTimeout(() => {1349      setContentPhase("idle");1350      after?.();1351    }, ENTRY_TRANSITION_SETTLE_MS);1352  }13531354  return (1355    <div class="popup-root peach-theme">1356      <Show when={bootState() === "ready"}>1357        <Show1358          when={!pendingPasskey()}1359          fallback={1360            <PasskeyApprovalView1361              type={pendingPasskey()!.type}1362              rpName={pendingPasskey()!.rpName}1363              rpId={pendingPasskey()!.rpId}1364              userName={pendingPasskey()!.userName}1365              userDisplayName={pendingPasskey()!.userDisplayName}1366              onApprove={handleApprovePendingPasskey}1367              onDeny={handleDenyPendingPasskey}1368            />1369          }1370        >1371          <Show1372            when={!isLockedView()}1373            fallback={1374              <Show1375                when={view() !== "adopting"}1376                fallback={1377                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1378                    <AdoptVaultView1379                      onCancel={() => {1380                        setOnboarded(false);1381                        setView("lock");1382                      }}1383                      onDone={handleAdoptionDone}1384                      startAdoption={startVaultAdoption}1385                    />1386                  </Suspense>1387                }1388              >1389                <Show1390                  when={onboarded() || hasVault()}1391                  fallback={1392                    <Onboarding1393                      onComplete={() => {1394                        setStartOnboardingRestore(false);1395                        setOnboarded(true);1396                      }}1397                      onRestore={() => {1398                        setStartOnboardingRestore(true);1399                        setOnboarded(true);1400                      }}1401                      onAdopt={() => {1402                        setStartOnboardingRestore(false);1403                        setOnboarded(true);1404                        setView("adopting");1405                      }}1406                    />1407                  }1408                >1409                  <LockView1410                    hasVault={hasVault()}1411                    ready={bootState() === "ready"}1412                    isPro={proStatus()}1413                    forceRecoveryWords={forceRecoveryWords()}1414                    initialRestore={startOnboardingRestore()}1415                    onUnlock={() => {1416                      // RecoveryWordDisplay clears the storage flag before1417                      // calling onDone, so handleUnlock will see no pending1418                      // confirmation and proceed through the normal path.1419                      if (forceRecoveryWords()) setForceRecoveryWords(false);1420                      return handleUnlock();1421                    }}1422                    onBackToOnboarding={1423                      !hasVault()1424                        ? () => {1425                            setStartOnboardingRestore(false);1426                            setOnboarded(false);1427                          }1428                        : undefined1429                    }1430                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1431                  />1432                </Show>1433              </Show>1434            }1435          >1436            <Show1437              when={view() !== "pro-celebration"}1438              fallback={<ProCelebration />}1439            >1440            <section1441              id="hd-shell"1442              class="peach-shell peach-theme"1443              data-surface="extension"1444            >1445            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1446              <PeachWordmark unlocked />1447              <div class="peach-chrome-actions">1448                <button1449                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1450                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1451                  aria-label="Notes"1452                  title="Notes"1453                >1454                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1455                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1456                    <line x1="4" y1="5" x2="10" y2="5" />1457                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1458                    <line x1="4" y1="10" x2="7" y2="10" />1459                  </svg>1460                </button>1461                <button1462                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1463                    classList={{1464                      "is-syncing": syncBusy(),1465                      "is-ok": syncFlash() === "ok",1466                      "is-error": syncFlash() === "error",1467                    }}1468                    onClick={() => void handleHeaderSync()}1469                    disabled={syncBusy()}1470                    aria-label={`Sync now. ${syncLabel()}`}1471                    title={syncLabel()}1472                  >1473                    <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">1474                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1475                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1476                      <path d="M2.6 1v2.4h2.4" />1477                      <path d="M11.4 13v-2.4H9" />1478                    </svg>1479                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1480                  </button>1481                <button1482                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1483                  onClick={() => setView("settings")}1484                  aria-label="Settings"1485                >1486                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1487                    <path1488                      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"1489                      stroke="currentColor"1490                      stroke-width="0.9"1491                    />1492                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1493                  </svg>1494                </button>1495                <button1496                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1497                  onClick={handleAdd}1498                  aria-label="New entry"1499                >1500                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1501                    <path d="M5.5 1v9M1 5.5h9" />1502                  </svg>1503                </button>1504                <button1505                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1506                  onClick={() => void handleHeaderLock()}1507                  aria-label="Lock vault"1508                >1509                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1510                    <path1511                      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"1512                      stroke="currentColor"1513                      stroke-width="1"1514                      stroke-linecap="round"1515                    />1516                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1517                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1518                  </svg>1519                </button>1520              </div>1521            </header>15221523            <Show when={pendingProNotice() !== null}>1524              <div class="peach-pro-notice-banner">1525                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1526                <button1527                  class="peach-pro-notice-link"1528                  onClick={() => {1529                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1530                    setSettingsInitialSection("license");1531                    setView("settings");1532                    setPendingProNotice(null);1533                  }}1534                >1535                  Learn more →1536                </button>1537                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1538              </div>1539            </Show>15401541            <div class="peach-shell-body">1542              <div class="peach-shell-veil"></div>1543              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1544                <EntryView1545                  entry={selectedEntry()}1546                  currentTabUrl={currentTabUrl()}1547                  entries={entries()}1548                  isPro={proStatus()}1549                  onDelete={handleDelete}1550                  onFieldSaved={() => void loadEntries()}1551                  onEscape={() => { setView("list"); }}1552                  onProGate={(feature) => {1553                    setUpgradeHighlight(feature);1554                    setSettingsInitialSection("license");1555                    setView("settings");1556                  }}1557                />1558              </div>15591560              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1561                <div class="peach-search-bar">1562                  <span class="peach-search-icon">1563                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1564                      <circle cx="5.5" cy="5.5" r="3.75" />1565                      <path d="M8.75 8.75L11.5 11.5" />1566                    </svg>1567                  </span>1568                  <input1569                    class="peach-search-input"1570                    placeholder="search vault..."1571                    autocomplete="off"1572                    aria-label="Search vault entries"1573                    onClick={openList}1574                    onFocus={openList}1575                    readOnly1576                  />1577                  <div class="peach-search-meta">1578                    <span class="peach-search-counter">1579                      {entries().length > 01580                        ? `${selectedIndex() + 1} / ${entries().length}`1581                        : "0 entries"}1582                    </span>1583                    <span class="peach-divider"></span>1584                    <button1585                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1586                      onClick={() => navigate(-1)}1587                      aria-label="Previous entry"1588                      disabled={entries().length === 0}1589                    >1590                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1591                        <path d="M5 1L1 5.5L5 10" />1592                      </svg>1593                    </button>1594                    <button1595                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1596                      onClick={() => navigate(1)}1597                      aria-label="Next entry"1598                      disabled={entries().length === 0}1599                    >1600                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1601                        <path d="M1 1L5 5.5L1 10" />1602                      </svg>1603                    </button>1604                  </div>1605                </div>1606              </section>1607            </div>16081609            {/* Desktop: shown on demand via Show. Native sheet is rendered1610                via Portal below at the document root so its position:fixed1611                isn't trapped by .peach-shell's transform-based animations. */}1612            {/* UI-1 / HV-1b: dismissible remote-mutation alert banners. */}1613            <Show when={syncAlerts().length > 0}>1614              <div class="peach-sync-alerts">1615                <For each={syncAlerts()}>1616                  {(alert, i) => (1617                    <div class="peach-sync-alert">1618                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1619                      <button1620                        class="peach-sync-alert-dismiss"1621                        type="button"1622                        aria-label="Dismiss"1623                        onClick={() => dismissSyncAlert(i())}1624                      >×</button>1625                    </div>1626                  )}1627                </For>1628              </div>1629            </Show>16301631            <Show when={!isNativePlatform() && view() === "list"}>1632              <VaultView1633                entries={entries()}1634                selectedEntryId={selectedEntry()?.id}1635                currentTabDomain={currentTabDomain()}1636                sortOrder={sortOrder()}1637                searchSeed={listSearchSeed()}1638                searchSeedNonce={listSearchSeedNonce()}1639                onSelectEntry={handleSelectEntry}1640                onSortOrderChange={setSortOrder}1641                onAdd={handleAdd}1642                onClose={() => setView("entry")}1643                onOpenTrash={() => setView("trash")}1644                onDeleteMany={handleDeleteMany}1645              />1646            </Show>1647            <Show when={isNativePlatform() && hasVault()}>1648              <Portal>1649                <div1650                  class="peach-vault-sheet"1651                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1652                  style={(() => {1653                    const live = sheetTranslate();1654                    if (live === null) return undefined;1655                    return { transform: `translateY(${live}px)` };1656                  })()}1657                >1658                  <VaultView1659                    entries={entries()}1660                    selectedEntryId={selectedEntry()?.id}1661                    currentTabDomain={currentTabDomain()}1662                    sortOrder={sortOrder()}1663                    searchSeed={listSearchSeed()}1664                    searchSeedNonce={listSearchSeedNonce()}1665                    isNative={true}1666                    onSelectEntry={handleSelectEntry}1667                    onSortOrderChange={setSortOrder}1668                    onAdd={handleAdd}1669                    onClose={() => setView("entry")}1670                    onOpenTrash={() => setView("trash")}1671                    onDeleteMany={handleDeleteMany}1672                  />1673                </div>1674              </Portal>1675            </Show>1676            <Show when={view() === "settings" || settingsExiting()}>1677              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1678                <SettingsView1679                  entriesCount={entries().length}1680                  breachMonitoring={breachMonitoring()}1681                  lockOnClose={lockOnClose()}1682                  autoLockMinutes={autoLockMinutes()}1683                  trashRetentionDays={trashRetentionDays()}1684                  theme={theme()}1685                  accentColor={accentColor()}1686                  textSize={textSize()}1687                  reduceMotion={reduceMotion()}1688                  isPro={proStatus()}1689                  initialSection={settingsInitialSection()}1690                  upgradeHighlight={upgradeHighlight()}1691                  isExiting={settingsExiting()}1692                  onBreachMonitoringChange={applyBreachMonitoring}1693                  onLockOnCloseChange={applyLockOnClose}1694                  onAutoLockMinutesChange={applyAutoLockMinutes}1695                  onTrashRetentionChange={applyTrashRetention}1696                  onThemeChange={applyTheme}1697                  onAccentChange={applyAccentColor}1698                  onTextSizeChange={applyTextSize}1699                  onReduceMotionChange={applyReduceMotion}1700                  shortcuts={shortcutBindings()}1701                  onShortcutsChange={applyShortcuts}1702                  onLicenseChange={async () => {1703                    // After activation/deactivation: refresh Pro status,1704                    // re-load entries (defensive — signal state can drift if1705                    // the SW briefly restarts during the verify+save round-trip),1706                    // and replay the Pro celebration if this is the first time1707                    // a valid Pro license is seen on this device.1708                    await refreshProStatus();1709                    void loadEntries();1710                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1711                    if ((should as { ok: boolean; data?: boolean }).data === true) {1712                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1713                      setView("pro-celebration");1714                      window.setTimeout(() => setView("settings"), 2500);1715                    }1716                  }}1717                  onBack={() => {1718                    setSettingsExiting(true);1719                    window.setTimeout(() => {1720                      setSettingsExiting(false);1721                      setSettingsInitialSection(null);1722                      setUpgradeHighlight(null);1723                      handleBack();1724                    }, 200);1725                  }}1726                  onImport={() => setView("import")}1727                  onExport={() => setView("export")}1728                  onBreachCheckDone={loadEntries}1729                  onOpenHealth={openHealth}1730                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1731                  onOpenFileImport={handleOpenFileImport}1732                  onOpenPanic={() => setView("panic")}1733                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1734                  onOpenCodexRestore={() => setView("codex-restore")}1735                  onCardChange={setSettingsActiveCard}1736                  onProGate={(feature) => {1737                    setUpgradeHighlight(feature);1738                    setSettingsInitialSection("license");1739                  }}1740                />1741              </Suspense>1742            </Show>1743            <Show when={view() === "codex-generate"}>1744              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1745                <CodexGenerateView1746                  isPro={proStatus()}1747                  onBack={() => setView("settings")}1748                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1749                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1750                  onVaultLocked={() => handleLock()}1751                />1752              </Suspense>1753            </Show>1754            <Show when={view() === "codex-restore"}>1755              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1756                <CodexRestoreView1757                  onBack={() => setView("lock")}1758                  onRestoreSuccess={async () => {1759                    // After restore the vault is unlocked; refresh entries1760                    // and route to the main vault list. handleUnlock is the1761                    // canonical post-unlock setup path.1762                    await handleUnlock();1763                  }}1764                />1765              </Suspense>1766            </Show>1767            <Show when={view() === "pair-device"}>1768              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1769                <PairDeviceView1770                  isPro={proStatus()}1771                  onProChanged={() => { void refreshProStatus(); }}1772                  onBack={() => setView("settings")}1773                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1774                />1775              </Suspense>1776            </Show>1777            <Show when={view() === "add"}>1778              <AddView1779                entry={editEntry()}1780                entries={entries()}1781                onBack={handleBack}1782                onSave={handleSave}1783              />1784            </Show>1785            <Show when={view() === "import"}>1786              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1787                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1788              </Suspense>1789            </Show>1790            <Show when={view() === "export"}>1791              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1792                <ExportView onBack={handleExportBack} />1793              </Suspense>1794            </Show>1795            <Show when={view() === "panic"}>1796              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1797                <PanicView1798                  onCancel={() => setView("settings")}1799                  onOpenExport={() => {1800                    setReturnToPanic(true);1801                    setView("export");1802                  }}1803                  onDestroyed={async () => {1804                    clearCanarySuppressions();1805                    setEntries([]);1806                    setSelectedEntry(null);1807                    setEditEntry(undefined);1808                    setHasVault(false);1809                    setOnboarded(false);1810                    setProStatus(false);1811                    setPendingPasskey(null);1812                    setUpgradeHighlight(null);1813                    setSettingsInitialSection(null);1814                    setPendingProNotice(null);1815                    setPendingCelebration(false);1816                    setReturnToPanic(false);1817                    setContentPhase("idle");1818                    setView("lock");1819                  }}1820                />1821              </Suspense>1822            </Show>1823            {/* Health stays mounted while editing an entry from it so1824                computeReused() doesn't rerun on every cancel/back. */}1825            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1826              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1827                <HealthView1828                  entries={entries()}1829                  isPro={proStatus()}1830                  onFixEntry={handleFixEntry}1831                  onBack={() => setView("settings")}1832                  onRefresh={loadEntries}1833                  hidden={view() !== "health"}1834                />1835              </Suspense>1836            </Show>1837            <Show when={view() === "trash"}>1838              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1839                <TrashView1840                  onBack={() => setView("list")}1841                  onRestored={() => void loadEntries()}1842                />1843              </Suspense>1844            </Show>1845            <Show when={showNotes()}>1846              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1847                <NotesMode1848                  notes={entries().filter((e) => e.type === "note")}1849                  initialNoteId={openNoteId()}1850                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1851                  onNoteListChanged={() => void loadEntries()}1852                />1853              </div>1854            </Show>1855            <Show when={restoreView() === "file"}>1856              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1857                <ImportView1858                  mode="onboarding"1859                  replacesExistingVault={true}1860                  onBack={() => setRestoreView(null)}1861                  onImport={async () => {1862                    setRestoreView(null);1863                    await handleUnlock();1864                  }}1865                />1866              </Suspense>1867            </Show>1868            </section>1869            </Show>1870          </Show>1871        </Show>1872      </Show>1873      <Show when={showShortcutsHelp()}>1874        <ShortcutsHelpOverlay1875          bindings={shortcutBindings()}1876          onClose={() => setShowShortcutsHelp(false)}1877        />1878      </Show>1879    </div>1880  );1881}18821883function ShortcutsHelpOverlay(props: {1884  bindings: Record<ShortcutAction, Keybinding>;1885  onClose: () => void;1886}) {1887  return (1888    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1889      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1890        <div class="peach-shortcuts-help-head">1891          <h3>Keyboard shortcuts</h3>1892          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1893        </div>1894        <div class="peach-shortcuts-help-body">1895          <p class="peach-settings-sub-label">ENTRY VIEW</p>1896          <ul>1897            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1898              <li>1899                <span>{d.label}</span>1900                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1901              </li>1902            ))}1903          </ul>1904          <p class="peach-settings-sub-label">ANYWHERE</p>1905          <ul>1906            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1907              <li>1908                <span>{d.label}</span>1909                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1910              </li>1911            ))}1912          </ul>1913        </div>1914      </div>1915    </div>1916  );1917}