App.tsx

78.8 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 { popupCopy } from "./copy";19import {20  DEFAULT_BINDINGS,21  formatKeybinding,22  getActiveBindings,23  matchKeybinding,24  SHORTCUT_DESCRIPTORS,25  type Keybinding,26  type ShortcutAction,27} from "../shared/shortcuts";28import { generateTOTP } from "../crypto/totp";29import { isNativePlatform, nativePlugin } from "../shared/native";3031export { sendMessage } from "../shared/bridge";3233const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));34const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));35const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));36const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));37const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));38const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));39const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));40const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));41const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));42const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));4344type View =45  | "lock"46  | "pro-celebration"47  | "entry"48  | "list"49  | "add"50  | "settings"51  | "pair-device"52  | "import"53  | "export"54  | "health"55  | "trash"56  | "panic"57  | "adopting"58  | "codex-generate"59  | "codex-restore";60type BootState = "loading" | "ready";6162const canarySuppressMap = new Map<string, boolean>();63let shellRingAnimation: Animation | null = null;6465export function isCanarySuppressed(entryId: string): boolean {66  return canarySuppressMap.get(entryId) ?? false;67}6869export function setCanarySuppressed(entryId: string, suppressed: boolean): void {70  canarySuppressMap.set(entryId, suppressed);71}7273export function clearCanarySuppressions(): void {74  canarySuppressMap.clear();75}7677export function triggerRing() {78  const shell = document.getElementById("hd-shell");79  if (!shell) return;8081  shellRingAnimation?.cancel();82  shell.dataset.glowing = "true";83  const animation = shell.animate(84    [85      { offset: 0, boxShadow: "var(--copy-shadow)" },86      {87        offset: 0.3,88        boxShadow:89          "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)",90      },91      { offset: 1, boxShadow: "var(--copy-shadow)" },92    ],93    {94      duration: 720,95      easing: "cubic-bezier(0.4, 0, 0.2, 1)",96      fill: "none",97    }98  );99  shellRingAnimation = animation;100  const clearGlow = () => {101    if (shellRingAnimation !== animation) return;102    shellRingAnimation = null;103    delete shell.dataset.glowing;104  };105  animation.onfinish = clearGlow;106  animation.oncancel = clearGlow;107}108109110export function triggerPipPulse() {111  const pip = document.querySelector(".peach-status-pip, .pip");112  if (pip) {113    pip.classList.remove("pulse");114    void (pip as HTMLElement).offsetWidth;115    pip.classList.add("pulse");116  }117}118119function defaultAdoptionDeviceName(): string {120  const ua = (typeof navigator !== "undefined" ? navigator.userAgent : "") || "";121  if (/Firefox/i.test(ua)) return "Firefox";122  if (/Edg\//i.test(ua)) return "Edge";123  if (/Chrome/i.test(ua)) return "Chrome";124  if (/Safari/i.test(ua)) return "Safari";125  return "Peach";126}127128const ENTRY_TRANSITION_SETTLE_MS = 135;129130export default function App() {131  const [bootState, setBootState] = createSignal<BootState>("loading");132  const [view, setView] = createSignal<View>("lock");133  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,134  // CSS transition takes over for snap animation).135  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);136  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(137    "enter"138  );139  const [contentTransitioning, setContentTransitioning] = createSignal(false);140  const [hasVault, setHasVault] = createSignal(false);141  const [onboarded, setOnboarded] = createSignal(true);142  const [entries, setEntries] = createSignal<VaultEntry[]>([]);143  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);144  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);145146  // UI-1 / HV-1b + MV-8d: remote-mutation alerts queued by the sync merge,147  // shown as dismissible banners on popup open.148  interface SyncAlert {149    type: "REMOTE_PASSWORD_CHANGE" | "REMOTE_DELETE" | "DEVICE_KEY_ROTATED";150    entryId: string;151    entryTitle: string;152    deviceName: string;153    timestamp: number;154  }155  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);156  async function loadSyncAlerts() {157    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {158      ok: boolean;159      data?: SyncAlert[];160    };161    if (r.ok && (r.data?.length ?? 0) > 0) {162      setSyncAlerts(r.data ?? []);163      // Acknowledge so a crash between read and render doesn't lose them —164      // they remain on screen until the user dismisses each.165      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });166    }167  }168  function dismissSyncAlert(index: number) {169    setSyncAlerts((arr) => arr.filter((_, i) => i !== index));170  }171  function syncAlertText(a: SyncAlert): string {172    if (a.type === "REMOTE_PASSWORD_CHANGE") {173      return `${a.deviceName} changed the password for ${a.entryTitle}`;174    }175    if (a.type === "REMOTE_DELETE") {176      return `${a.deviceName} deleted ${a.entryTitle}`;177    }178    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;179  }180  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");181  const [theme, setTheme] = createSignal<"dark" | "light">("dark");182  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");183  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);184  const [lockOnClose, setLockOnClose] = createSignal(true);185  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);186  const [breachMonitoring, setBreachMonitoring] = createSignal(true);187  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);188  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);189  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);190  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);191  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);192  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");193  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");194  // Cached Pro status — synchronous for render paths. Background's195  // GET_LICENSE is async, but render-time reads of isPro() must not block.196  // Refreshed at boot, after activate/deactivate, and whenever the popup197  // re-opens onto a stored license that has changed via another window.198  const [proStatus, setProStatus] = createSignal(false);199  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);200  // When the sync card's pairing button opens the pairing view, deep-link201  // straight into that pairing path instead of the rest screen.202  const [syncPairIntent, setSyncPairIntent] = createSignal<"code" | null>(null);203  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");204  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);205  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");206  const [listSearchSeed, setListSearchSeed] = createSignal("");207  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);208  const [pendingCelebration, setPendingCelebration] = createSignal(false);209  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);210  // True while Panic Step 1 has bounced the user out to Export. When Export's211  // onBack fires we return to Panic instead of Settings so the user keeps the212  // destruction context they came from.213  const [returnToPanic, setReturnToPanic] = createSignal(false);214  // The view to return to when the add/edit view is dismissed. Normally "entry"215  // but "health" when the user arrives via the fix-entry path from Vault Health.216  const [editBackView, setEditBackView] = createSignal<View>("entry");217  const [settingsExiting, setSettingsExiting] = createSignal(false);218  const [showNotes, setShowNotes] = createSignal(false);219  // Topbar sync affordance. Always present: gating it on having a paired device220  // meant it never appeared for the person trying to set pairing up, which is221  // exactly when you reach for it.222  const [syncBusy, setSyncBusy] = createSignal(false);223  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);224  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);225  // Set on popup boot when peach_recovery_pending flag is found in session226  // storage — instructs LockView to skip the unlock UI and open the recovery227  // words confirmation surface instead. Cleared via handleUnlock once the228  // user has typed the 3 confirmation words.229  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);230231  let contentPhaseTimer: number | undefined;232  // Set when the popup was opened from the inline "Open Peach to unlock" button.233  // handleUnlock() closes the popup after unlock so the user returns to the page.234  let openedForInlineUnlock = false;235236  function applyAccent(name: AccentColorName) {237    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;238    const hex = color.hex;239    document.documentElement.style.setProperty("--peach-accent", hex);240    // Ambient surface variables — derived from the accent so surfaces shift241    // subtly toward the accent hue rather than staying fixed warm-brown.242    document.documentElement.style.setProperty("--peach-glow", hex + "2A");243    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");244    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");245  }246247  createEffect(() => {248    applyAccent(accentColor());249  });250251  createEffect(() => {252    document.documentElement.classList.toggle("light", theme() === "light");253    document.body.classList.toggle("light", theme() === "light");254  });255256  createEffect(() => {257    document.documentElement.setAttribute("data-text-size", textSize());258  });259260  createEffect(() => {261    if (reduceMotion()) {262      document.documentElement.setAttribute("data-motion", "reduce");263    } else {264      document.documentElement.removeAttribute("data-motion");265    }266  });267268  const selectedIndex = createMemo(() => {269    const currentId = selectedEntry()?.id;270    if (!currentId) return entries().length > 0 ? 0 : -1;271    return entries().findIndex((entry) => entry.id === currentId);272  });273274  async function applyAccentColor(name: AccentColorName) {275    applyAccent(name);276    setAccentColor(name);277    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });278  }279280  async function applyTheme(t: "dark" | "light") {281    setTheme(t);282    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });283  }284285  async function applyTextSize(size: "small" | "medium" | "large") {286    setTextSize(size);287    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });288  }289290  async function applyReduceMotion(enabled: boolean) {291    setReduceMotion(enabled);292    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });293  }294295  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload296  // small and lets future default updates land for actions the user hasn't297  // touched. Settings sends us the full active map; we filter and store.298  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {299    setShortcutBindings(active);300    const overrides: Record<string, Keybinding> = {};301    for (const action of Object.keys(active) as ShortcutAction[]) {302      const a = active[action];303      const d = DEFAULT_BINDINGS[action];304      const same = a.key === d.key305        && Boolean(a.ctrl)  === Boolean(d.ctrl)306        && Boolean(a.meta)  === Boolean(d.meta)307        && Boolean(a.shift) === Boolean(d.shift)308        && Boolean(a.alt)   === Boolean(d.alt);309      if (!same) overrides[action] = a;310    }311    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });312  }313314  async function applyLockOnClose(enabled: boolean) {315    setLockOnClose(enabled);316    await sendMessage({317      type: "UPDATE_SETTINGS",318      payload: { lockOnClose: enabled },319    });320  }321322  async function applyAutoLockMinutes(minutes: number) {323    setAutoLockMinutes(minutes);324    await sendMessage({325      type: "UPDATE_SETTINGS",326      payload: { autoLockMinutes: minutes },327    });328  }329330  async function applyBreachMonitoring(enabled: boolean) {331    setBreachMonitoring(enabled);332    await sendMessage({333      type: "UPDATE_SETTINGS",334      payload: { breachMonitoring: enabled },335    });336  }337338  onMount(async () => {339    // Resolve the active tab in parallel with the unlock/has-vault queries —340    // openVault()'s smart selection picks the entry matching currentTabDomain,341    // so it must be populated before openVault runs. Previously refreshCurrentTab342    // ran after openVault, leaving popups that booted already-unlocked falling343    // back to loadedEntries[0] instead of the domain match.344    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([345      sendMessage({ type: "IS_UNLOCKED" }),346      sendMessage({ type: "HAS_VAULT" }),347      refreshCurrentTab(),348      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),349    ]);350    const unlocked = Boolean(351      (unlockResponse as { ok: boolean; data?: boolean }).data352    );353    const vaultExists = Boolean(354      (vaultResponse as { ok: boolean; data?: boolean }).data355    );356    const shouldCelebrate = Boolean(357      (celebrationResponse as { ok: boolean; data?: boolean }).data358    );359    setHasVault(vaultExists);360    // Onboarding gate — show once on first install, never again. Existing361    // users (vaultExists) are auto-marked onboarded so they skip the flow362    // even on the very first popup open after this feature ships.363    try {364      const onboarded = await storageGet("peach_onboarded");365      const seen = onboarded === "true";366      if (vaultExists && !seen) {367        await storageSet("peach_onboarded", "true");368        setOnboarded(true);369      } else {370        setOnboarded(seen);371      }372    } catch {373      // storage unavailable — default to onboarded so we never block boot374      setOnboarded(true);375    }376    await Promise.all([restoreSettings(), refreshProStatus()]);377378    // Mark played before any animation so a crash mid-sequence never replays it379    if (shouldCelebrate) {380      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });381    }382383    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the384    // background ignores it when no mobile hosts are paired or while385    // another sync is already in flight.386    if (unlocked && vaultExists) {387      void sendMessage({388        type: "TRIGGER_SYNC",389        payload: { reason: "foreground" },390      });391      // UI-1 / HV-1b: surface any remote-mutation alerts the sync merge queued.392      void loadSyncAlerts();393    }394395    // If the user created a vault but hasn't yet confirmed their recovery396    // words, route back to the recovery-words screen instead of opening the397    // entries view. The flag lives in chrome.storage.local so it survives398    // both popup close (SW suppresses lock-on-close) and full browser399    // restart (handleUnlock checks the same flag after a fresh password400    // unlock). Cleared when confirmation succeeds.401    let recoveryPending = false;402    try {403      const out = await chrome.storage.local?.get("peach_recovery_pending");404      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";405    } catch { /* best-effort */ }406407    // If this popup was opened from the inline "Open Peach to unlock" button,408    // the background set a session flag. Read and clear it so handleUnlock()409    // can close the popup after unlock and return the user to the page.410    if (chrome.storage.session) {411      try {412        const s = await chrome.storage.session.get("peach_inline_unlock");413        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {414          openedForInlineUnlock = true;415          await chrome.storage.session.remove("peach_inline_unlock");416        }417      } catch { /* best-effort */ }418    }419420    // Native: closing the app before recovery-words confirmation means the421    // user didn't finish vault creation. Throw the partial vault away and422    // restart onboarding rather than asking them to unlock a vault they423    // never finished creating. Desktop keeps the existing "unlock to424    // resume" flow because closing the popup there is much more casual.425    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {426      try {427        await chrome.storage.local?.remove([428          "peach_vault_a",429          "peach_vault_b",430          "peach_recovery_pending",431          "peach_onboarded",432          "peach_vault_history",433        ]);434      } catch { /* best-effort */ }435      setHasVault(false);436      setOnboarded(false);437      setView("lock");438      setBootState("ready");439      return;440    }441442    if (recoveryPending && unlocked) {443      // forceRecoveryWords overrides LockView's hasVault gate so the444      // recovery surface renders even though the vault now exists.445      setForceRecoveryWords(true);446      setView("lock");447    } else if (unlocked && vaultExists) {448      await openVault(undefined, shouldCelebrate);449      if (shouldCelebrate) {450        setView("pro-celebration");451        window.setTimeout(() => setView("entry"), 2500);452      }453    } else if (shouldCelebrate) {454      setPendingCelebration(true);455    }456457    await refreshPendingPasskey();458459    // Track tab changes so smart sort stays current460    const handleTabActivated = () => { void refreshCurrentTab(); };461    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {462      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();463    };464    try {465      chrome.tabs.onActivated.addListener(handleTabActivated);466      chrome.tabs.onUpdated.addListener(handleTabUpdated);467      onCleanup(() => {468        chrome.tabs.onActivated.removeListener(handleTabActivated);469        chrome.tabs.onUpdated.removeListener(handleTabUpdated);470      });471    } catch {472      // tabs permission may not be available in all contexts473    }474475    setBootState("ready");476477    // Deep-link: ?codex=pdf opens a detached window straight into the478    // Codex restore flow with auto-picked PDF. The action popup can't host479    // a file dialog without dismissing itself, so this is the only way the480    // PDF import path survives. See CodexRestoreView.openPdfPicker().481    try {482      const route = new URLSearchParams(window.location.search).get("codex");483      if (route === "pdf" || route === "restore") {484        setView("codex-restore");485      }486    } catch {487      // location.search unavailable — ignore.488    }489490    // Check for pending session-storage notices from the background.491    if (chrome.storage.session) {492      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as493        Record<string, { feature?: string } | undefined>;494      if (session.pendingProGate?.feature) {495        await chrome.storage.session.remove("pendingProGate");496        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);497        setSettingsInitialSection("license");498        setView("settings");499      } else if (session.pendingProNotice?.feature) {500        await chrome.storage.session.remove("pendingProNotice");501        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });502      }503    }504505    // Warm the lazy-module cache so the Suspense fallback never shows for506    // locally-bundled extension views. Without this, the first navigation to507    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which508    // covers the shell and absorbs clicks on the header.509    void Promise.all([510      import("./views/Settings").catch(() => {}),511      import("./views/Import").catch(() => {}),512      import("./views/Export").catch(() => {}),513      import("./views/Health").catch(() => {}),514      import("./views/TrashView").catch(() => {}),515    ]);516517    // Lock-on-close via a persistent port. sendMessage in pagehide is518    // unreliable — the popup context tears down before the message lands.519    // The SW's onConnect listener locks when this port disconnects.520    let popupPort: chrome.runtime.Port | null = null;521    try {522      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect523      // listener accepts the "popup-" prefix; the random suffix is defence in524      // depth against a port named exactly "popup" from anything but our popup.525      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });526    } catch { /* extension context invalidated — ignore */ }527    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });528529    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only530    // reliable signal is appStateChange — setTimeout is killed when the OS531    // backgrounds the app. We measure elapsed background time on resume.532    if (isNativePlatform()) {533      let backgroundedAt: number | null = null;534535      const CapApp = nativePlugin<{536        addListener: (537          ev: string,538          cb: (s: { isActive: boolean }) => void,539        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };540      }>("App");541      if (CapApp?.addListener) {542        const sub = CapApp.addListener(543          "appStateChange",544          ({ isActive }: { isActive: boolean }) => {545            if (!isActive) {546              backgroundedAt = Date.now();547              return;548            }549            if (backgroundedAt !== null && autoLockMinutes() > 0) {550              const elapsed = Date.now() - backgroundedAt;551              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();552            }553            backgroundedAt = null;554          }555        );556        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.557        onCleanup(() => {558          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});559        });560      }561562      // L12/COR-011: foreground idle autolock. appStateChange only fires when563      // the OS backgrounds the app — if the user idles with the screen on,564      // chrome.alarms is no-op'd in Capacitor so the vault would stay open565      // indefinitely. Poll every 30s and lock if elapsed since last user566      // interaction exceeds autoLockMinutes.567      let lastUserActivityAt = Date.now();568      const bumpActivity = () => { lastUserActivityAt = Date.now(); };569      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;570      for (const ev of ACTIVITY_EVENTS) {571        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });572      }573      const idleLockInterval = setInterval(() => {574        const minutes = autoLockMinutes();575        if (!minutes || minutes <= 0) return;576        const elapsed = Date.now() - lastUserActivityAt;577        if (elapsed >= minutes * 60_000) {578          lastUserActivityAt = Date.now();579          handleHeaderLock();580        }581      }, 30_000);582      onCleanup(() => {583        clearInterval(idleLockInterval);584        for (const ev of ACTIVITY_EVENTS) {585          document.removeEventListener(ev, bumpActivity, { capture: true });586        }587      });588589      // The retired native peer-discovery trigger went with the old Capacitor590      // pairing plugin. Reconnection is address-cache first, subnet probe second591      // (sync-runner.ts); relocating a peer that changed networks is an592      // Android-side discovery concern now.593      if (isNativePlatform()) {594        // Android runs the background/sync dispatcher in-process with the595        // popup, so the production runner has to be registered from the596        // UI bootstrap path instead of the MV3 service-worker entry.597        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>598          import("../background/sync-runner").then(({ productionSyncRunner }) => {599            setSyncRunner(productionSyncRunner);600            void hydratePersistedSyncState();601          })602        );603      }604    }605606    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale607    // entries instead of waiting for the next GET_ENTRIES round-trip.608    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {609      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();610      if (msg?.type === "PRO_GATE_TRIGGERED") {611        setUpgradeHighlight(msg.payload?.feature ?? null);612        setSettingsInitialSection("license");613        setView("settings");614      }615    };616    chrome.runtime.onMessage.addListener(handleRuntimeMessage);617    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));618619    // Android hardware/gesture back. MainActivity fires peach:back; the popup620    // decides what "back" means per surface. Lock+no-vault is the common case621    // — return to onboarding rather than letting the OS dismiss the activity.622    const handlePeachBack = () => {623      // Notes mode captures back first624      if (showNotes()) {625        setShowNotes(false);626        setOpenNoteId(undefined);627        return;628      }629      const v = view();630      if (v === "lock" && !hasVault() && onboarded()) {631        setOnboarded(false);632        return;633      }634      if (v === "list") { setView("entry"); return; }635      if (v === "settings") {636        window.dispatchEvent(new Event("peach:settings-back"));637        return;638      }639      if (v === "import" || v === "health") { setView("settings"); return; }640      if (v === "export") { handleExportBack(); return; }641      if (v === "add") { handleBack(); return; }642      if (v === "pair-device") { setView("settings"); return; }643    };644    window.addEventListener("peach:back", handlePeachBack);645    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));646647    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that648    // peeks from the bottom (search bar handle visible) and drags up to fill649    // the screen. dragOffset is the LIVE finger offset during a drag, in px,650    // 0 when no drag in progress. The wrapper element computes transform =651    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.652    if (isNativePlatform()) {653      let touchStartY = 0;654      let touchStartX = 0;655      let lastY = 0;656      let lastT = 0;657      let dragging = false;658      let captured = false;659      const HORIZONTAL_TOLERANCE = 16;660      const ACTIVATION_DY = 8;661      const PEEK_PX = 60;662663      const onTouchStart = (e: TouchEvent) => {664        const t = e.touches[0];665        if (!t) return;666        const v = view();667        if (v !== "entry" && v !== "list") return;668        // Entry view: only intercept drags starting in the bottom 40%.669        // List view: intercept drags starting in the top 35% (the search/handle row).670        const inBand = v === "entry"671          ? t.clientY > window.innerHeight * 0.6672          : t.clientY < window.innerHeight * 0.35;673        if (!inBand) return;674        touchStartY = lastY = t.clientY;675        touchStartX = t.clientX;676        lastT = e.timeStamp;677        dragging = true;678        captured = false;679      };680681      const onTouchMove = (e: TouchEvent) => {682        if (!dragging) return;683        const t = e.touches[0];684        if (!t) return;685        const dy = t.clientY - touchStartY;686        const dx = Math.abs(t.clientX - touchStartX);687688        if (!captured) {689          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {690            // Looks like a horizontal swipe — release.691            dragging = false;692            return;693          }694          if (Math.abs(dy) < ACTIVATION_DY) return;695          captured = true;696        }697698        // Translate the sheet by dy from its rest (peek) position. Peek is699        // (viewport height - PEEK_PX). Open is 0.700        const v = view();701        const restClosed = window.innerHeight - PEEK_PX;702        const baseTranslate = v === "list" ? 0 : restClosed;703        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));704        setSheetTranslate(next);705        lastY = t.clientY;706        lastT = e.timeStamp;707      };708709      const onTouchEnd = (e: TouchEvent) => {710        if (!dragging) { return; }711        const t = e.changedTouches[0];712        const elapsed = Math.max(1, e.timeStamp - lastT);713        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms714        const wasCaptured = captured;715        dragging = false;716        captured = false;717        const v = view();718719        if (!wasCaptured) {720          // Tap in the peek strip while in entry view → open the vault list.721          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");722          setSheetTranslate(null);723          return;724        }725726        const restClosed = window.innerHeight - PEEK_PX;727        const current = sheetTranslate() ?? restClosed;728729        // Snap rules:730        //   - Strong upward velocity → open731        //   - Strong downward velocity → close732        //   - Otherwise snap to whichever rest is closer733        let nextOpen: boolean;734        if (velocity < -0.05) nextOpen = true;735        else if (velocity > 0.05) nextOpen = false;736        else nextOpen = current < restClosed * 0.5;737738        if (nextOpen && v !== "list") setView("list");739        if (!nextOpen && v !== "entry") setView("entry");740        // Release the live offset so CSS transition handles the snap.741        setSheetTranslate(null);742      };743744      document.addEventListener("touchstart", onTouchStart, { passive: true });745      document.addEventListener("touchmove",  onTouchMove,  { passive: true });746      document.addEventListener("touchend",   onTouchEnd,   { passive: true });747      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });748      onCleanup(() => {749        document.removeEventListener("touchstart", onTouchStart);750        document.removeEventListener("touchmove",  onTouchMove);751        document.removeEventListener("touchend",   onTouchEnd);752      });753    }754755    // Action handlers — keyed by ShortcutAction. The dispatcher below tests756    // each binding against the event and runs the matching handler. New757    // shortcuts only need an entry here; the binding is data, not code.758    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {759      copy_password: () => {760        const entry = selectedEntry();761        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });762      },763      copy_username: () => {764        const entry = selectedEntry();765        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });766      },767      copy_totp: () => {768        const entry = selectedEntry();769        if (!entry?.totp) return;770        try {771          const { code } = generateTOTP(entry.totp);772          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });773        } catch { /* invalid TOTP secret — silent */ }774      },775      new_entry: () => handleAdd(),776      edit_entry: () => {777        const entry = selectedEntry();778        // Passkey-only entries have nothing user-editable in the Add view; the779        // passkey credential itself is opaque. Skip the edit action for them.780        if (!entry || isPasskeyOnly(entry)) return;781        setEditEntry(entry);782        setView("add");783      },784      delete_entry: () => {785        if (selectedEntry()) void handleDelete();786      },787      lock_vault: () => { void handleHeaderLock(); },788      search: () => openList(),789      nav_prev: () => navigate(-1),790      nav_next: () => navigate(1),791      jump_vault: () => setView("entry"),792      jump_settings: () => setView("settings"),793      show_help: () => setShowShortcutsHelp(true),794    };795796    // Actions that are MEANINGFUL only on the entry-detail view. Outside797    // that scope the binding is dormant — pressing C while on Settings798    // does nothing rather than awkwardly copying from a now-stale entry.799    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([800      "copy_password", "copy_username", "copy_totp",801      "edit_entry", "delete_entry", "nav_prev", "nav_next",802    ]);803804    const handleGlobalKeydown = (e: KeyboardEvent) => {805      const v = view();806      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"807        || (e.target as HTMLElement)?.tagName === "TEXTAREA"808        || (e.target as HTMLElement)?.isContentEditable;809      const isPrintableSearchKey =810        e.key.length === 1 &&811        !e.ctrlKey &&812        !e.metaKey &&813        !e.altKey;814815      // No input during the pro celebration sequence816      if (v === "pro-celebration") return;817818      // Help dialog: Escape closes it; eat the keypress so it doesn't819      // also navigate away from the underlying view.820      if (showShortcutsHelp()) {821        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }822        return;823      }824825      // ── Escape — fixed binding (not user-customizable) ───────826      if (e.key === "Escape") {827        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }828        if (v === "list") { setView("entry"); return; }829        if (v === "settings" || v === "add") { handleBack(); return; }830        if (v === "import" || v === "health") { setView("settings"); return; }831        if (v === "export") { handleExportBack(); return; }832        if (v === "pair-device") { setView("settings"); return; }833      }834835      // Bindings-driven dispatch. Single-key letter bindings without836      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is837      // inside an input, so users can type into search/forms normally.838      const bindings = shortcutBindings();839      for (const action of Object.keys(bindings) as ShortcutAction[]) {840        const binding = bindings[action];841        if (!matchKeybinding(e, binding)) continue;842        // Single-key letter bindings need the input-focus guard. Bindings843        // with any modifier are safe — Ctrl+L doesn't conflict with typing.844        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;845        if (!hasMod && binding.key.length === 1 && inInput) return;846        if (ENTRY_SCOPED.has(action) && v !== "entry") return;847        e.preventDefault();848        SHORTCUT_HANDLERS[action]?.();849        return;850      }851852      // Type-to-search: in entry view, any printable key not consumed by a853      // shortcut above primes the list search seed and opens the list.854      // Kept outside the bindings table because it's a behavior, not a855      // discrete action — every printable character can trigger it.856      if (v === "entry" && !inInput && isPrintableSearchKey) {857        e.preventDefault();858        primeListSearch(e.key);859        return;860      }861    };862    window.addEventListener("keydown", handleGlobalKeydown);863    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));864865    const handleStorageChanged = (866      changes: Record<string, chrome.storage.StorageChange>,867      areaName: string868    ) => {869      if (areaName !== "session") return;870      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {871        return;872      }873      void refreshPendingPasskey();874    };875    chrome.storage.onChanged.addListener(handleStorageChanged);876    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));877  });878879  async function refreshCurrentTab() {880    try {881      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });882      const url = tab?.url ?? tab?.pendingUrl ?? "";883      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");884      // Skip extension/internal URLs — adding chrome://, about:, or885      // chrome-extension:// to a vault entry is never what the user wants.886      const isWebUrl = /^https?:\/\//i.test(url);887      setCurrentTabUrl(isWebUrl ? url : "");888    } catch {889      setCurrentTabDomain("");890      setCurrentTabUrl("");891    }892  }893894  async function refreshPendingPasskey() {895    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });896    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);897  }898899  async function refreshProStatus() {900    const res = await sendMessage({ type: "GET_LICENSE" });901    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;902    setProStatus(Boolean(data?.valid && data?.plan === "pro"));903  }904905  async function restoreSettings() {906    const res = await sendMessage({ type: "GET_SETTINGS" });907    const s = (res as { ok: boolean; data?: any }).data ?? {};908    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {909      setAccentColor(s.accentColor as AccentColorName);910    }911    setTheme(s.theme === "light" ? "light" : "dark");912    if (s.textSize === "small" || s.textSize === "large") {913      setTextSize(s.textSize);914    } else {915      setTextSize("medium");916    }917    setReduceMotion(s.reduceMotion === true);918    setLockOnClose(s.lockOnClose !== false);919    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);920    setBreachMonitoring(s.breachMonitoring !== false);921    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);922    setShortcutBindings(getActiveBindings(s.shortcuts));923  }924925  async function applyTrashRetention(days: number) {926    setTrashRetentionDays(days);927    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });928  }929930  function primeListSearch(seed: string) {931    setListSearchSeed(seed);932    setListSearchSeedNonce((value) => value + 1);933    openList();934  }935936  // Returns null when it detected a dead service worker and triggered handleLock().937  // Callers that need to abort (e.g. openVault) check for null rather than relying938  // on view() state, which may already be "lock" during normal startup flows.939  async function loadEntries(): Promise<VaultEntry[] | null> {940    const response = await sendMessage({ type: "GET_ENTRIES" });941    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };942943    // If the service worker was killed and restarted (MV3 workers sleep), the944    // vault will be locked again — or the worker may not respond at all.945    // In either case, send the user to the lock screen rather than silently946    // showing an empty vault (which looks like data loss).947    if (!res.ok) {948      if (949        res.error === "vault_locked" ||950        res.error === "SERVICE_WORKER_UNAVAILABLE" ||951        (typeof res.error === "string" && res.error.includes("locked"))952      ) {953        handleLock();954        return null; // signal emergency lock to callers955      }956      return [];957    }958959    const loadedEntries = res.data ?? [];960    setEntries(loadedEntries);961962    const currentId = selectedEntry()?.id;963    if (currentId) {964      setSelectedEntry(965        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null966      );967    }968969    return loadedEntries;970  }971972  async function openVault(preferredEntryId?: string, skipViewSet = false) {973    // Purge expired trash entries on each vault open974    const retDays = trashRetentionDays();975    if (retDays > 0) {976      void sendMessage({977        type: "PURGE_EXPIRED_TRASH",978        payload: { retentionMs: retDays * 86_400_000 },979      });980    }981982    const loadedEntries = await loadEntries();983984    // null means loadEntries() triggered an emergency lock (service worker died).985    // Don't override it by setting view back to "entry" with an empty vault.986    if (loadedEntries === null) return;987988    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry989    let nextSelectedEntry: VaultEntry | null = null;990    if (preferredEntryId) {991      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;992    }993    if (!nextSelectedEntry) {994      const tabDomain = currentTabDomain();995      if (tabDomain) {996        nextSelectedEntry = loadedEntries.find((e) => {997          if (e.type === "login") {998            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;999            for (const extra of e.additionalUrls ?? []) {1000              if ((extractDomain(extra) ?? "") === tabDomain) return true;1001            }1002            return false;1003          }1004          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1005          return false;1006        }) ?? null;1007      }1008    }1009    nextSelectedEntry ??= loadedEntries[0] ?? null;10101011    setSelectedEntry(nextSelectedEntry);1012    setEditEntry(undefined);1013    setContentTransitioning(false);1014    setContentPhase("enter");1015    queueContentIdle();1016    if (!skipViewSet) setView("entry");1017  }10181019  async function handleUnlock() {1020    // If the user previously created a vault but hadn't yet confirmed their1021    // recovery words (and the browser was closed before they could), the1022    // peach_recovery_pending flag is still set in storage.local. Re-route1023    // back to the recovery surface so they finish the confirmation step1024    // before reaching the entries view — the words can be re-derived now1025    // that the vault is unlocked again.1026    let recoveryPending = false;1027    try {1028      const out = await chrome.storage.local?.get("peach_recovery_pending");1029      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1030    } catch { /* best-effort */ }1031    if (recoveryPending) {1032      setForceRecoveryWords(true);1033      setView("lock");1034      triggerPipPulse();1035      await restoreSettings();1036      return;1037    }1038    setHasVault(true);1039    triggerPipPulse();1040    await restoreSettings();1041    const celebrating = pendingCelebration();1042    if (celebrating) {1043      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1044      setPendingCelebration(false);1045    }1046    await openVault(undefined, celebrating);1047    if (celebrating) {1048      setView("pro-celebration");1049      window.setTimeout(() => setView("entry"), 2500);1050    }1051    // Popup was opened from the inline "Open Peach to unlock" button — close it1052    // now so the user lands back on the page with the autofill selector ready.1053    if (openedForInlineUnlock) {1054      openedForInlineUnlock = false;1055      window.close();1056    }1057  }10581059  function handleSelectEntry(entry: VaultEntry) {1060    if (entry.type === "note") {1061      setOpenNoteId(entry.id);1062      setShowNotes(true);1063      return;1064    }1065    setSelectedEntry(entry);1066    setContentTransitioning(false);1067    setContentPhase("enter");1068    queueContentIdle();1069    setView("entry");1070  }10711072  function handleAdd() {1073    setEditEntry(undefined);1074    setView("add");1075  }10761077  async function handleDelete() {1078    const entry = selectedEntry();1079    if (!entry) return;1080    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1081    const loadedEntries = await loadEntries() ?? [];1082    setSelectedEntry(loadedEntries[0] ?? null);1083    setView("entry");1084  }10851086  async function handleDeleteMany(ids: string[]) {1087    for (const id of ids) {1088      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1089    }1090    const loadedEntries = await loadEntries() ?? [];1091    // If the currently selected entry was among the deleted, move to first1092    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1093    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1094  }10951096  async function handleSave(savedEntry?: VaultEntry) {1097    await openVault(savedEntry?.id);1098  }10991100  function handleBack() {1101    const dest = editBackView();1102    setEditBackView("entry");1103    setEditEntry(undefined);1104    setView(dest);1105  }11061107  function handleExportBack() {1108    if (returnToPanic()) {1109      setReturnToPanic(false);1110      setView("panic");1111      return;1112    }1113    setView("settings");1114  }11151116  function handleLock() {1117    clearCanarySuppressions();1118    setEntries([]);1119    setSelectedEntry(null);1120    setEditEntry(undefined);1121    setContentPhase("idle");1122    setView("lock");1123  }11241125  function handleHeaderLock() {1126    // Lock the UI immediately — do not wait for the service worker. If the SW1127    // is dead or slow, the 5s sendMessage timeout would create a dead-click1128    // window. The SW will lock on its next wake regardless.1129    handleLock();1130    void sendMessage({ type: "LOCK" });1131  }11321133  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1134  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1135  // the trigger's own reply.1136  async function handleHeaderSync(): Promise<void> {1137    if (syncBusy()) return;1138    setSyncBusy(true);1139    setSyncFlash(null);1140    try {1141      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1142      let status: string = "syncing";1143      for (let i = 0; i < 40 && status === "syncing"; i++) {1144        await new Promise((r) => setTimeout(r, 250));1145        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1146          ok: boolean;1147          data?: { status?: string };1148        };1149        status = res.ok ? res.data?.status ?? "idle" : "error";1150      }1151      setSyncFlash(status === "error" ? "error" : "ok");1152      await loadSyncAlerts();1153      await loadEntries();1154    } catch {1155      setSyncFlash("error");1156    } finally {1157      setSyncBusy(false);1158      setTimeout(() => setSyncFlash(null), 2_000);1159    }1160  }11611162  function navigate(dir: number) {1163    const allEntries = entries();1164    if (allEntries.length === 0) return;1165    const currentIndex = selectedIndex();1166    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1167    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1168    setSelectedEntry(allEntries[nextIndex]);1169    setContentPhase("enter");1170    queueContentIdle();1171  }11721173  function openList() {1174    setView("list");1175  }11761177  function openHealth() {1178    setEditEntry(undefined);1179    setView("health");1180  }11811182  function handleOpenFileImport() {1183    setRestoreView("file");1184  }11851186  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11871188  function handleFixEntry(entry: VaultEntry) {1189    setSelectedEntry(entry);1190    // Passkey-only entries have no editable surface — drop into view mode1191    // instead of opening the Add editor.1192    if (isPasskeyOnly(entry)) {1193      setView("entry");1194      return;1195    }1196    setEditBackView(view()); // preserve caller view so back returns here1197    setEditEntry(entry);1198    setView("add");1199  }12001201  const isLockedView = () => view() === "lock" || view() === "adopting";12021203  async function handleAdoptionDone() {1204    await storageSet("peach_onboarded", "true").catch(() => {});1205    setOnboarded(true);1206    setHasVault(true);1207    await handleUnlock();1208    void sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "foreground" } });1209  }12101211  /**1212   * Join an existing vault from a brand-new install.1213   *1214   * This used to require the receiver to LISTEN for the other device (a1215   * Capacitor pairing server), which a browser extension structurally cannot1216   * do — so on every real browser build it threw before doing anything. Over a1217   * pairing code the receiver is the DIALLER instead, which is the only shape1218   * that works here: dial the code, confirm the SAS, then ask for the vault.1219   *1220   * The vault does not exist yet at dial time, so nothing in this path may1221   * touch the vault before `createVaultFromRootKey` runs.1222   */1223  async function startVaultAdoption(args: {1224    password: string;1225    connection:1226      | { mode: "relay"; invitation: string }1227      | { mode: "lan"; code: string };1228    confirmSAS(sas: string): Promise<boolean>;1229    createVault(rootKeyHex: string): Promise<{ vaultId: string }>;1230  }) {1231    const [{1232      dialPairingChannel,1233      dialRelayPairingChannel,1234      openPairingSocket,1235      openRelayPairingSocket,1236    }, { requestAdoption }, { setLastKnownIp }] =1237      await Promise.all([1238        import("../shared/pairing-dial"),1239        import("../shared/vault-adopt"),1240        import("../background/paired-devices"),1241      ]);12421243    const dial = args.connection.mode === "relay"1244      ? await dialRelayPairingChannel(args.connection.invitation, {1245        openSocket: openRelayPairingSocket,1246      })1247      : await dialPairingChannel(args.connection.code, {1248        openSocket: openPairingSocket,1249      }, { flow: "adoption" });1250    if (!dial.ok) throw new Error(dial.error);1251    const {1252      channel,1253      sas,1254      socket,1255      host,1256      relayUrl,1257      rendezvousSecretHex,1258    } = dial.dialled;12591260    try {1261      const source = await requestAdoption(channel, {1262        deviceName: defaultAdoptionDeviceName(),1263        generateDeviceId: () => crypto.randomUUID(),1264        // requestAdoption writes ADOPT_CONFIRM and refuses to read a root-key1265        // grant until this local SAS decision is true.1266        confirmSas: () => args.confirmSAS(sas),1267        pairState: { rendezvousSecretHex, relayUrl },1268        createVaultFromRootKey: args.createVault,1269        deriveLocalIdentity: async () => {1270          const res = await sendMessage({ type: "GET_LOCAL_IDENTITY" });1271          const r = res as { ok: boolean; data?: unknown; error?: string };1272          if (!r.ok || !r.data) throw new Error(r.error ?? "identity_unavailable");1273          return r.data as Awaited<ReturnType<Parameters<typeof requestAdoption>[1]["deriveLocalIdentity"]>>;1274        },1275        upsertPairedDevice: async (paired) => {1276          const res = await sendMessage({ type: "COMPLETE_PAIRING", payload: { paired } });1277          const r = res as { ok: boolean; error?: string };1278          if (!r.ok) throw new Error(r.error ?? "complete_pairing_failed");1279          // Seed the reconnect cache with the address we just dialled, exactly as1280          // device pairing does (code-pairing.ts). Without it an adopted browser1281          // never syncs on Chrome: the runner lives in the MV3 service worker,1282          // its probe fallback needs RTCPeerConnection to find the /24, and that1283          // API does not exist in a service worker — so getSubnet() always1284          // returns null and connect() throws subnet_unknown forever. The cache1285          // is the only route that ever reaches the peer.1286          if (!relayUrl && paired.longTermPublicKeyHex) {1287            await setLastKnownIp(paired.longTermPublicKeyHex, host).catch(() => undefined);1288          }1289        },1290        applyLicense: async (license) => {1291          const res = (await sendMessage({1292            type: "ACTIVATE_LICENSE",1293            payload: { key: license },1294          })) as { ok: boolean; data?: { valid?: boolean; plan?: string } };1295          if (res.ok && res.data?.valid && res.data?.plan === "pro") await refreshProStatus();1296        },1297        onError(error) {1298          throw new Error(1299            error === "ADOPT_SAS_REJECTED" ? "sas_rejected" : error,1300          );1301        },1302      });1303      if (!source) throw new Error("adoption_rejected");1304      if (relayUrl) {1305        const setting = (await sendMessage({1306          type: "SET_RELAY_SETTINGS",1307          payload: { relayUrl, lanOnly: false },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={() => { setOnboarded(true); }}1394                      onRestore={() => { setOnboarded(true); }}1395                      onAdopt={() => {1396                        setOnboarded(true);1397                        setView("adopting");1398                      }}1399                    />1400                  }1401                >1402                  <LockView1403                    hasVault={hasVault()}1404                    ready={bootState() === "ready"}1405                    isPro={proStatus()}1406                    forceRecoveryWords={forceRecoveryWords()}1407                    onUnlock={() => {1408                      // RecoveryWordDisplay clears the storage flag before1409                      // calling onDone, so handleUnlock will see no pending1410                      // confirmation and proceed through the normal path.1411                      if (forceRecoveryWords()) setForceRecoveryWords(false);1412                      return handleUnlock();1413                    }}1414                    onBackToOnboarding={1415                      !hasVault()1416                        ? () => setOnboarded(false)1417                        : undefined1418                    }1419                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1420                  />1421                </Show>1422              </Show>1423            }1424          >1425            <Show1426              when={view() !== "pro-celebration"}1427              fallback={<ProCelebration />}1428            >1429            <section1430              id="hd-shell"1431              class="peach-shell peach-theme"1432              data-surface="extension"1433            >1434            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1435              <PeachWordmark unlocked />1436              <div class="peach-chrome-actions">1437                <button1438                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1439                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1440                  aria-label="Notes"1441                  title="Notes"1442                >1443                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1444                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1445                    <line x1="4" y1="5" x2="10" y2="5" />1446                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1447                    <line x1="4" y1="10" x2="7" y2="10" />1448                  </svg>1449                </button>1450                <button1451                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1452                    classList={{1453                      "is-syncing": syncBusy(),1454                      "is-ok": syncFlash() === "ok",1455                      "is-error": syncFlash() === "error",1456                    }}1457                    onClick={() => void handleHeaderSync()}1458                    disabled={syncBusy()}1459                    aria-label={syncBusy() ? "Syncing" : "Sync now"}1460                    title="Sync now"1461                  >1462                    <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">1463                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1464                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1465                      <path d="M2.6 1v2.4h2.4" />1466                      <path d="M11.4 13v-2.4H9" />1467                    </svg>1468                  </button>1469                <button1470                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1471                  onClick={() => setView("settings")}1472                  aria-label="Settings"1473                >1474                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1475                    <path1476                      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"1477                      stroke="currentColor"1478                      stroke-width="0.9"1479                    />1480                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1481                  </svg>1482                </button>1483                <button1484                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1485                  onClick={handleAdd}1486                  aria-label="New entry"1487                >1488                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1489                    <path d="M5.5 1v9M1 5.5h9" />1490                  </svg>1491                </button>1492                <button1493                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1494                  onClick={() => void handleHeaderLock()}1495                  aria-label="Lock vault"1496                >1497                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1498                    <path1499                      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"1500                      stroke="currentColor"1501                      stroke-width="1"1502                      stroke-linecap="round"1503                    />1504                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1505                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1506                  </svg>1507                </button>1508              </div>1509            </header>15101511            <Show when={pendingProNotice() !== null}>1512              <div class="peach-pro-notice-banner">1513                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1514                <button1515                  class="peach-pro-notice-link"1516                  onClick={() => {1517                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1518                    setSettingsInitialSection("license");1519                    setView("settings");1520                    setPendingProNotice(null);1521                  }}1522                >1523                  Learn more →1524                </button>1525                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1526              </div>1527            </Show>15281529            <div class="peach-shell-body">1530              <div class="peach-shell-veil"></div>1531              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1532                <EntryView1533                  entry={selectedEntry()}1534                  currentTabUrl={currentTabUrl()}1535                  entries={entries()}1536                  isPro={proStatus()}1537                  onDelete={handleDelete}1538                  onFieldSaved={() => void loadEntries()}1539                  onEscape={() => { setView("list"); }}1540                  onProGate={(feature) => {1541                    setUpgradeHighlight(feature);1542                    setSettingsInitialSection("license");1543                    setView("settings");1544                  }}1545                />1546              </div>15471548              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1549                <div class="peach-search-bar">1550                  <span class="peach-search-icon">1551                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1552                      <circle cx="5.5" cy="5.5" r="3.75" />1553                      <path d="M8.75 8.75L11.5 11.5" />1554                    </svg>1555                  </span>1556                  <input1557                    class="peach-search-input"1558                    placeholder="search vault..."1559                    autocomplete="off"1560                    aria-label="Search vault entries"1561                    onClick={openList}1562                    onFocus={openList}1563                    readOnly1564                  />1565                  <div class="peach-search-meta">1566                    <span class="peach-search-counter">1567                      {entries().length > 01568                        ? `${selectedIndex() + 1} / ${entries().length}`1569                        : "0 entries"}1570                    </span>1571                    <span class="peach-divider"></span>1572                    <button1573                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1574                      onClick={() => navigate(-1)}1575                      aria-label="Previous entry"1576                      disabled={entries().length === 0}1577                    >1578                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1579                        <path d="M5 1L1 5.5L5 10" />1580                      </svg>1581                    </button>1582                    <button1583                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1584                      onClick={() => navigate(1)}1585                      aria-label="Next entry"1586                      disabled={entries().length === 0}1587                    >1588                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1589                        <path d="M1 1L5 5.5L1 10" />1590                      </svg>1591                    </button>1592                  </div>1593                </div>1594              </section>1595            </div>15961597            {/* Desktop: shown on demand via Show. Native sheet is rendered1598                via Portal below at the document root so its position:fixed1599                isn't trapped by .peach-shell's transform-based animations. */}1600            {/* UI-1 / HV-1b: dismissible remote-mutation alert banners. */}1601            <Show when={syncAlerts().length > 0}>1602              <div class="peach-sync-alerts">1603                <For each={syncAlerts()}>1604                  {(alert, i) => (1605                    <div class="peach-sync-alert">1606                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1607                      <button1608                        class="peach-sync-alert-dismiss"1609                        type="button"1610                        aria-label="Dismiss"1611                        onClick={() => dismissSyncAlert(i())}1612                      >×</button>1613                    </div>1614                  )}1615                </For>1616              </div>1617            </Show>16181619            <Show when={!isNativePlatform() && view() === "list"}>1620              <VaultView1621                entries={entries()}1622                selectedEntryId={selectedEntry()?.id}1623                currentTabDomain={currentTabDomain()}1624                sortOrder={sortOrder()}1625                searchSeed={listSearchSeed()}1626                searchSeedNonce={listSearchSeedNonce()}1627                onSelectEntry={handleSelectEntry}1628                onSortOrderChange={setSortOrder}1629                onAdd={handleAdd}1630                onClose={() => setView("entry")}1631                onOpenTrash={() => setView("trash")}1632                onDeleteMany={handleDeleteMany}1633              />1634            </Show>1635            <Show when={isNativePlatform() && hasVault()}>1636              <Portal>1637                <div1638                  class="peach-vault-sheet"1639                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1640                  style={(() => {1641                    const live = sheetTranslate();1642                    if (live === null) return undefined;1643                    return { transform: `translateY(${live}px)` };1644                  })()}1645                >1646                  <VaultView1647                    entries={entries()}1648                    selectedEntryId={selectedEntry()?.id}1649                    currentTabDomain={currentTabDomain()}1650                    sortOrder={sortOrder()}1651                    searchSeed={listSearchSeed()}1652                    searchSeedNonce={listSearchSeedNonce()}1653                    isNative={true}1654                    onSelectEntry={handleSelectEntry}1655                    onSortOrderChange={setSortOrder}1656                    onAdd={handleAdd}1657                    onClose={() => setView("entry")}1658                    onOpenTrash={() => setView("trash")}1659                    onDeleteMany={handleDeleteMany}1660                  />1661                </div>1662              </Portal>1663            </Show>1664            <Show when={view() === "settings" || settingsExiting()}>1665              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1666                <SettingsView1667                  entriesCount={entries().length}1668                  breachMonitoring={breachMonitoring()}1669                  lockOnClose={lockOnClose()}1670                  autoLockMinutes={autoLockMinutes()}1671                  trashRetentionDays={trashRetentionDays()}1672                  theme={theme()}1673                  accentColor={accentColor()}1674                  textSize={textSize()}1675                  reduceMotion={reduceMotion()}1676                  isPro={proStatus()}1677                  initialSection={settingsInitialSection()}1678                  upgradeHighlight={upgradeHighlight()}1679                  isExiting={settingsExiting()}1680                  onBreachMonitoringChange={applyBreachMonitoring}1681                  onLockOnCloseChange={applyLockOnClose}1682                  onAutoLockMinutesChange={applyAutoLockMinutes}1683                  onTrashRetentionChange={applyTrashRetention}1684                  onThemeChange={applyTheme}1685                  onAccentChange={applyAccentColor}1686                  onTextSizeChange={applyTextSize}1687                  onReduceMotionChange={applyReduceMotion}1688                  shortcuts={shortcutBindings()}1689                  onShortcutsChange={applyShortcuts}1690                  onLicenseChange={async () => {1691                    // After activation/deactivation: refresh Pro status,1692                    // re-load entries (defensive — signal state can drift if1693                    // the SW briefly restarts during the verify+save round-trip),1694                    // and replay the Pro celebration if this is the first time1695                    // a valid Pro license is seen on this device.1696                    await refreshProStatus();1697                    void loadEntries();1698                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1699                    if ((should as { ok: boolean; data?: boolean }).data === true) {1700                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1701                      setView("pro-celebration");1702                      window.setTimeout(() => setView("settings"), 2500);1703                    }1704                  }}1705                  onBack={() => {1706                    setSettingsExiting(true);1707                    window.setTimeout(() => {1708                      setSettingsExiting(false);1709                      setSettingsInitialSection(null);1710                      setUpgradeHighlight(null);1711                      handleBack();1712                    }, 200);1713                  }}1714                  onImport={() => setView("import")}1715                  onExport={() => setView("export")}1716                  onBreachCheckDone={loadEntries}1717                  onOpenHealth={openHealth}1718                  onOpenSyncPairing={(method) => { setSettingsInitialSection(settingsActiveCard()); setSyncPairIntent(method ?? null); setView("pair-device"); }}1719                  onOpenFileImport={handleOpenFileImport}1720                  onOpenPanic={() => setView("panic")}1721                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1722                  onOpenCodexRestore={() => setView("codex-restore")}1723                  onCardChange={setSettingsActiveCard}1724                  onProGate={(feature) => {1725                    setUpgradeHighlight(feature);1726                    setSettingsInitialSection("license");1727                  }}1728                />1729              </Suspense>1730            </Show>1731            <Show when={view() === "codex-generate"}>1732              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1733                <CodexGenerateView1734                  isPro={proStatus()}1735                  onBack={() => setView("settings")}1736                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1737                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1738                  onVaultLocked={() => handleLock()}1739                />1740              </Suspense>1741            </Show>1742            <Show when={view() === "codex-restore"}>1743              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1744                <CodexRestoreView1745                  onBack={() => setView("lock")}1746                  onRestoreSuccess={async () => {1747                    // After restore the vault is unlocked; refresh entries1748                    // and route to the main vault list. handleUnlock is the1749                    // canonical post-unlock setup path.1750                    await handleUnlock();1751                  }}1752                />1753              </Suspense>1754            </Show>1755            <Show when={view() === "pair-device"}>1756              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1757                <PairDeviceView1758                  isPro={proStatus()}1759                  initialPair={syncPairIntent()}1760                  onProChanged={() => { void refreshProStatus(); }}1761                  onBack={() => { setSyncPairIntent(null); setView("settings"); }}1762                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1763                />1764              </Suspense>1765            </Show>1766            <Show when={view() === "add"}>1767              <AddView1768                entry={editEntry()}1769                entries={entries()}1770                onBack={handleBack}1771                onSave={handleSave}1772              />1773            </Show>1774            <Show when={view() === "import"}>1775              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1776                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1777              </Suspense>1778            </Show>1779            <Show when={view() === "export"}>1780              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1781                <ExportView onBack={handleExportBack} />1782              </Suspense>1783            </Show>1784            <Show when={view() === "panic"}>1785              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1786                <PanicView1787                  onCancel={() => setView("settings")}1788                  onOpenExport={() => {1789                    setReturnToPanic(true);1790                    setView("export");1791                  }}1792                  onDestroyed={async () => {1793                    clearCanarySuppressions();1794                    setEntries([]);1795                    setSelectedEntry(null);1796                    setEditEntry(undefined);1797                    setHasVault(false);1798                    setOnboarded(false);1799                    setProStatus(false);1800                    setPendingPasskey(null);1801                    setUpgradeHighlight(null);1802                    setSettingsInitialSection(null);1803                    setPendingProNotice(null);1804                    setPendingCelebration(false);1805                    setReturnToPanic(false);1806                    setContentPhase("idle");1807                    setView("lock");1808                  }}1809                />1810              </Suspense>1811            </Show>1812            {/* Health stays mounted while editing an entry from it so1813                computeReused() doesn't rerun on every cancel/back. */}1814            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1815              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1816                <HealthView1817                  entries={entries()}1818                  isPro={proStatus()}1819                  onFixEntry={handleFixEntry}1820                  onBack={() => setView("settings")}1821                  onRefresh={loadEntries}1822                  hidden={view() !== "health"}1823                />1824              </Suspense>1825            </Show>1826            <Show when={view() === "trash"}>1827              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1828                <TrashView1829                  onBack={() => setView("list")}1830                  onRestored={() => void loadEntries()}1831                />1832              </Suspense>1833            </Show>1834            <Show when={showNotes()}>1835              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1836                <NotesMode1837                  notes={entries().filter((e) => e.type === "note")}1838                  initialNoteId={openNoteId()}1839                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1840                  onNoteListChanged={() => void loadEntries()}1841                />1842              </div>1843            </Show>1844            <Show when={restoreView() === "file"}>1845              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1846                <ImportView1847                  mode="onboarding"1848                  replacesExistingVault={true}1849                  onBack={() => setRestoreView(null)}1850                  onImport={async () => {1851                    setRestoreView(null);1852                    await handleUnlock();1853                  }}1854                />1855              </Suspense>1856            </Show>1857            </section>1858            </Show>1859          </Show>1860        </Show>1861      </Show>1862      <Show when={showShortcutsHelp()}>1863        <ShortcutsHelpOverlay1864          bindings={shortcutBindings()}1865          onClose={() => setShowShortcutsHelp(false)}1866        />1867      </Show>1868    </div>1869  );1870}18711872function ShortcutsHelpOverlay(props: {1873  bindings: Record<ShortcutAction, Keybinding>;1874  onClose: () => void;1875}) {1876  return (1877    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1878      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1879        <div class="peach-shortcuts-help-head">1880          <h3>Keyboard shortcuts</h3>1881          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1882        </div>1883        <div class="peach-shortcuts-help-body">1884          <p class="peach-settings-sub-label">ENTRY VIEW</p>1885          <ul>1886            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1887              <li>1888                <span>{d.label}</span>1889                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1890              </li>1891            ))}1892          </ul>1893          <p class="peach-settings-sub-label">ANYWHERE</p>1894          <ul>1895            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1896              <li>1897                <span>{d.label}</span>1898                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1899              </li>1900            ))}1901          </ul>1902        </div>1903      </div>1904    </div>1905  );1906}