App.tsx

79.1 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. `syncPaired` gates the button's existence — with no220  // paired device there is nothing to sync and the icon would be a dead control.221  const [syncPaired, setSyncPaired] = createSignal(false);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      void sendMessage({ type: "LIST_PAIRED_DEVICES" }).then((res) => {394        const devices = (res as { ok: boolean; data?: unknown }).data;395        setSyncPaired(Array.isArray(devices) && devices.length > 0);396      });397    }398399    // If the user created a vault but hasn't yet confirmed their recovery400    // words, route back to the recovery-words screen instead of opening the401    // entries view. The flag lives in chrome.storage.local so it survives402    // both popup close (SW suppresses lock-on-close) and full browser403    // restart (handleUnlock checks the same flag after a fresh password404    // unlock). Cleared when confirmation succeeds.405    let recoveryPending = false;406    try {407      const out = await chrome.storage.local?.get("peach_recovery_pending");408      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";409    } catch { /* best-effort */ }410411    // If this popup was opened from the inline "Open Peach to unlock" button,412    // the background set a session flag. Read and clear it so handleUnlock()413    // can close the popup after unlock and return the user to the page.414    if (chrome.storage.session) {415      try {416        const s = await chrome.storage.session.get("peach_inline_unlock");417        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {418          openedForInlineUnlock = true;419          await chrome.storage.session.remove("peach_inline_unlock");420        }421      } catch { /* best-effort */ }422    }423424    // Native: closing the app before recovery-words confirmation means the425    // user didn't finish vault creation. Throw the partial vault away and426    // restart onboarding rather than asking them to unlock a vault they427    // never finished creating. Desktop keeps the existing "unlock to428    // resume" flow because closing the popup there is much more casual.429    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {430      try {431        await chrome.storage.local?.remove([432          "peach_vault_a",433          "peach_vault_b",434          "peach_recovery_pending",435          "peach_onboarded",436          "peach_vault_history",437        ]);438      } catch { /* best-effort */ }439      setHasVault(false);440      setOnboarded(false);441      setView("lock");442      setBootState("ready");443      return;444    }445446    if (recoveryPending && unlocked) {447      // forceRecoveryWords overrides LockView's hasVault gate so the448      // recovery surface renders even though the vault now exists.449      setForceRecoveryWords(true);450      setView("lock");451    } else if (unlocked && vaultExists) {452      await openVault(undefined, shouldCelebrate);453      if (shouldCelebrate) {454        setView("pro-celebration");455        window.setTimeout(() => setView("entry"), 2500);456      }457    } else if (shouldCelebrate) {458      setPendingCelebration(true);459    }460461    await refreshPendingPasskey();462463    // Track tab changes so smart sort stays current464    const handleTabActivated = () => { void refreshCurrentTab(); };465    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {466      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();467    };468    try {469      chrome.tabs.onActivated.addListener(handleTabActivated);470      chrome.tabs.onUpdated.addListener(handleTabUpdated);471      onCleanup(() => {472        chrome.tabs.onActivated.removeListener(handleTabActivated);473        chrome.tabs.onUpdated.removeListener(handleTabUpdated);474      });475    } catch {476      // tabs permission may not be available in all contexts477    }478479    setBootState("ready");480481    // Deep-link: ?codex=pdf opens a detached window straight into the482    // Codex restore flow with auto-picked PDF. The action popup can't host483    // a file dialog without dismissing itself, so this is the only way the484    // PDF import path survives. See CodexRestoreView.openPdfPicker().485    try {486      const route = new URLSearchParams(window.location.search).get("codex");487      if (route === "pdf" || route === "restore") {488        setView("codex-restore");489      }490    } catch {491      // location.search unavailable — ignore.492    }493494    // Check for pending session-storage notices from the background.495    if (chrome.storage.session) {496      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as497        Record<string, { feature?: string } | undefined>;498      if (session.pendingProGate?.feature) {499        await chrome.storage.session.remove("pendingProGate");500        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);501        setSettingsInitialSection("license");502        setView("settings");503      } else if (session.pendingProNotice?.feature) {504        await chrome.storage.session.remove("pendingProNotice");505        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });506      }507    }508509    // Warm the lazy-module cache so the Suspense fallback never shows for510    // locally-bundled extension views. Without this, the first navigation to511    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which512    // covers the shell and absorbs clicks on the header.513    void Promise.all([514      import("./views/Settings").catch(() => {}),515      import("./views/Import").catch(() => {}),516      import("./views/Export").catch(() => {}),517      import("./views/Health").catch(() => {}),518      import("./views/TrashView").catch(() => {}),519    ]);520521    // Lock-on-close via a persistent port. sendMessage in pagehide is522    // unreliable — the popup context tears down before the message lands.523    // The SW's onConnect listener locks when this port disconnects.524    let popupPort: chrome.runtime.Port | null = null;525    try {526      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect527      // listener accepts the "popup-" prefix; the random suffix is defence in528      // depth against a port named exactly "popup" from anything but our popup.529      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });530    } catch { /* extension context invalidated — ignore */ }531    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });532533    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only534    // reliable signal is appStateChange — setTimeout is killed when the OS535    // backgrounds the app. We measure elapsed background time on resume.536    if (isNativePlatform()) {537      let backgroundedAt: number | null = null;538539      const CapApp = nativePlugin<{540        addListener: (541          ev: string,542          cb: (s: { isActive: boolean }) => void,543        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };544      }>("App");545      if (CapApp?.addListener) {546        const sub = CapApp.addListener(547          "appStateChange",548          ({ isActive }: { isActive: boolean }) => {549            if (!isActive) {550              backgroundedAt = Date.now();551              return;552            }553            if (backgroundedAt !== null && autoLockMinutes() > 0) {554              const elapsed = Date.now() - backgroundedAt;555              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();556            }557            backgroundedAt = null;558          }559        );560        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.561        onCleanup(() => {562          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});563        });564      }565566      // L12/COR-011: foreground idle autolock. appStateChange only fires when567      // the OS backgrounds the app — if the user idles with the screen on,568      // chrome.alarms is no-op'd in Capacitor so the vault would stay open569      // indefinitely. Poll every 30s and lock if elapsed since last user570      // interaction exceeds autoLockMinutes.571      let lastUserActivityAt = Date.now();572      const bumpActivity = () => { lastUserActivityAt = Date.now(); };573      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;574      for (const ev of ACTIVITY_EVENTS) {575        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });576      }577      const idleLockInterval = setInterval(() => {578        const minutes = autoLockMinutes();579        if (!minutes || minutes <= 0) return;580        const elapsed = Date.now() - lastUserActivityAt;581        if (elapsed >= minutes * 60_000) {582          lastUserActivityAt = Date.now();583          handleHeaderLock();584        }585      }, 30_000);586      onCleanup(() => {587        clearInterval(idleLockInterval);588        for (const ev of ACTIVITY_EVENTS) {589          document.removeEventListener(ev, bumpActivity, { capture: true });590        }591      });592593      // The retired native peer-discovery trigger went with the old Capacitor594      // pairing plugin. Reconnection is address-cache first, subnet probe second595      // (sync-runner.ts); relocating a peer that changed networks is an596      // Android-side discovery concern now.597      if (isNativePlatform()) {598        // Android runs the background/sync dispatcher in-process with the599        // popup, so the production runner has to be registered from the600        // UI bootstrap path instead of the MV3 service-worker entry.601        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>602          import("../background/sync-runner").then(({ productionSyncRunner }) => {603            setSyncRunner(productionSyncRunner);604            void hydratePersistedSyncState();605          })606        );607      }608    }609610    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale611    // entries instead of waiting for the next GET_ENTRIES round-trip.612    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {613      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();614      if (msg?.type === "PRO_GATE_TRIGGERED") {615        setUpgradeHighlight(msg.payload?.feature ?? null);616        setSettingsInitialSection("license");617        setView("settings");618      }619    };620    chrome.runtime.onMessage.addListener(handleRuntimeMessage);621    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));622623    // Android hardware/gesture back. MainActivity fires peach:back; the popup624    // decides what "back" means per surface. Lock+no-vault is the common case625    // — return to onboarding rather than letting the OS dismiss the activity.626    const handlePeachBack = () => {627      // Notes mode captures back first628      if (showNotes()) {629        setShowNotes(false);630        setOpenNoteId(undefined);631        return;632      }633      const v = view();634      if (v === "lock" && !hasVault() && onboarded()) {635        setOnboarded(false);636        return;637      }638      if (v === "list") { setView("entry"); return; }639      if (v === "settings") {640        window.dispatchEvent(new Event("peach:settings-back"));641        return;642      }643      if (v === "import" || v === "health") { setView("settings"); return; }644      if (v === "export") { handleExportBack(); return; }645      if (v === "add") { handleBack(); return; }646      if (v === "pair-device") { setView("settings"); return; }647    };648    window.addEventListener("peach:back", handlePeachBack);649    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));650651    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that652    // peeks from the bottom (search bar handle visible) and drags up to fill653    // the screen. dragOffset is the LIVE finger offset during a drag, in px,654    // 0 when no drag in progress. The wrapper element computes transform =655    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.656    if (isNativePlatform()) {657      let touchStartY = 0;658      let touchStartX = 0;659      let lastY = 0;660      let lastT = 0;661      let dragging = false;662      let captured = false;663      const HORIZONTAL_TOLERANCE = 16;664      const ACTIVATION_DY = 8;665      const PEEK_PX = 60;666667      const onTouchStart = (e: TouchEvent) => {668        const t = e.touches[0];669        if (!t) return;670        const v = view();671        if (v !== "entry" && v !== "list") return;672        // Entry view: only intercept drags starting in the bottom 40%.673        // List view: intercept drags starting in the top 35% (the search/handle row).674        const inBand = v === "entry"675          ? t.clientY > window.innerHeight * 0.6676          : t.clientY < window.innerHeight * 0.35;677        if (!inBand) return;678        touchStartY = lastY = t.clientY;679        touchStartX = t.clientX;680        lastT = e.timeStamp;681        dragging = true;682        captured = false;683      };684685      const onTouchMove = (e: TouchEvent) => {686        if (!dragging) return;687        const t = e.touches[0];688        if (!t) return;689        const dy = t.clientY - touchStartY;690        const dx = Math.abs(t.clientX - touchStartX);691692        if (!captured) {693          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {694            // Looks like a horizontal swipe — release.695            dragging = false;696            return;697          }698          if (Math.abs(dy) < ACTIVATION_DY) return;699          captured = true;700        }701702        // Translate the sheet by dy from its rest (peek) position. Peek is703        // (viewport height - PEEK_PX). Open is 0.704        const v = view();705        const restClosed = window.innerHeight - PEEK_PX;706        const baseTranslate = v === "list" ? 0 : restClosed;707        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));708        setSheetTranslate(next);709        lastY = t.clientY;710        lastT = e.timeStamp;711      };712713      const onTouchEnd = (e: TouchEvent) => {714        if (!dragging) { return; }715        const t = e.changedTouches[0];716        const elapsed = Math.max(1, e.timeStamp - lastT);717        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms718        const wasCaptured = captured;719        dragging = false;720        captured = false;721        const v = view();722723        if (!wasCaptured) {724          // Tap in the peek strip while in entry view → open the vault list.725          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");726          setSheetTranslate(null);727          return;728        }729730        const restClosed = window.innerHeight - PEEK_PX;731        const current = sheetTranslate() ?? restClosed;732733        // Snap rules:734        //   - Strong upward velocity → open735        //   - Strong downward velocity → close736        //   - Otherwise snap to whichever rest is closer737        let nextOpen: boolean;738        if (velocity < -0.05) nextOpen = true;739        else if (velocity > 0.05) nextOpen = false;740        else nextOpen = current < restClosed * 0.5;741742        if (nextOpen && v !== "list") setView("list");743        if (!nextOpen && v !== "entry") setView("entry");744        // Release the live offset so CSS transition handles the snap.745        setSheetTranslate(null);746      };747748      document.addEventListener("touchstart", onTouchStart, { passive: true });749      document.addEventListener("touchmove",  onTouchMove,  { passive: true });750      document.addEventListener("touchend",   onTouchEnd,   { passive: true });751      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });752      onCleanup(() => {753        document.removeEventListener("touchstart", onTouchStart);754        document.removeEventListener("touchmove",  onTouchMove);755        document.removeEventListener("touchend",   onTouchEnd);756      });757    }758759    // Action handlers — keyed by ShortcutAction. The dispatcher below tests760    // each binding against the event and runs the matching handler. New761    // shortcuts only need an entry here; the binding is data, not code.762    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {763      copy_password: () => {764        const entry = selectedEntry();765        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });766      },767      copy_username: () => {768        const entry = selectedEntry();769        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });770      },771      copy_totp: () => {772        const entry = selectedEntry();773        if (!entry?.totp) return;774        try {775          const { code } = generateTOTP(entry.totp);776          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });777        } catch { /* invalid TOTP secret — silent */ }778      },779      new_entry: () => handleAdd(),780      edit_entry: () => {781        const entry = selectedEntry();782        // Passkey-only entries have nothing user-editable in the Add view; the783        // passkey credential itself is opaque. Skip the edit action for them.784        if (!entry || isPasskeyOnly(entry)) return;785        setEditEntry(entry);786        setView("add");787      },788      delete_entry: () => {789        if (selectedEntry()) void handleDelete();790      },791      lock_vault: () => { void handleHeaderLock(); },792      search: () => openList(),793      nav_prev: () => navigate(-1),794      nav_next: () => navigate(1),795      jump_vault: () => setView("entry"),796      jump_settings: () => setView("settings"),797      show_help: () => setShowShortcutsHelp(true),798    };799800    // Actions that are MEANINGFUL only on the entry-detail view. Outside801    // that scope the binding is dormant — pressing C while on Settings802    // does nothing rather than awkwardly copying from a now-stale entry.803    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([804      "copy_password", "copy_username", "copy_totp",805      "edit_entry", "delete_entry", "nav_prev", "nav_next",806    ]);807808    const handleGlobalKeydown = (e: KeyboardEvent) => {809      const v = view();810      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"811        || (e.target as HTMLElement)?.tagName === "TEXTAREA"812        || (e.target as HTMLElement)?.isContentEditable;813      const isPrintableSearchKey =814        e.key.length === 1 &&815        !e.ctrlKey &&816        !e.metaKey &&817        !e.altKey;818819      // No input during the pro celebration sequence820      if (v === "pro-celebration") return;821822      // Help dialog: Escape closes it; eat the keypress so it doesn't823      // also navigate away from the underlying view.824      if (showShortcutsHelp()) {825        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }826        return;827      }828829      // ── Escape — fixed binding (not user-customizable) ───────830      if (e.key === "Escape") {831        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }832        if (v === "list") { setView("entry"); return; }833        if (v === "settings" || v === "add") { handleBack(); return; }834        if (v === "import" || v === "health") { setView("settings"); return; }835        if (v === "export") { handleExportBack(); return; }836        if (v === "pair-device") { setView("settings"); return; }837      }838839      // Bindings-driven dispatch. Single-key letter bindings without840      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is841      // inside an input, so users can type into search/forms normally.842      const bindings = shortcutBindings();843      for (const action of Object.keys(bindings) as ShortcutAction[]) {844        const binding = bindings[action];845        if (!matchKeybinding(e, binding)) continue;846        // Single-key letter bindings need the input-focus guard. Bindings847        // with any modifier are safe — Ctrl+L doesn't conflict with typing.848        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;849        if (!hasMod && binding.key.length === 1 && inInput) return;850        if (ENTRY_SCOPED.has(action) && v !== "entry") return;851        e.preventDefault();852        SHORTCUT_HANDLERS[action]?.();853        return;854      }855856      // Type-to-search: in entry view, any printable key not consumed by a857      // shortcut above primes the list search seed and opens the list.858      // Kept outside the bindings table because it's a behavior, not a859      // discrete action — every printable character can trigger it.860      if (v === "entry" && !inInput && isPrintableSearchKey) {861        e.preventDefault();862        primeListSearch(e.key);863        return;864      }865    };866    window.addEventListener("keydown", handleGlobalKeydown);867    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));868869    const handleStorageChanged = (870      changes: Record<string, chrome.storage.StorageChange>,871      areaName: string872    ) => {873      if (areaName !== "session") return;874      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {875        return;876      }877      void refreshPendingPasskey();878    };879    chrome.storage.onChanged.addListener(handleStorageChanged);880    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));881  });882883  async function refreshCurrentTab() {884    try {885      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });886      const url = tab?.url ?? tab?.pendingUrl ?? "";887      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");888      // Skip extension/internal URLs — adding chrome://, about:, or889      // chrome-extension:// to a vault entry is never what the user wants.890      const isWebUrl = /^https?:\/\//i.test(url);891      setCurrentTabUrl(isWebUrl ? url : "");892    } catch {893      setCurrentTabDomain("");894      setCurrentTabUrl("");895    }896  }897898  async function refreshPendingPasskey() {899    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });900    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);901  }902903  async function refreshProStatus() {904    const res = await sendMessage({ type: "GET_LICENSE" });905    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;906    setProStatus(Boolean(data?.valid && data?.plan === "pro"));907  }908909  async function restoreSettings() {910    const res = await sendMessage({ type: "GET_SETTINGS" });911    const s = (res as { ok: boolean; data?: any }).data ?? {};912    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {913      setAccentColor(s.accentColor as AccentColorName);914    }915    setTheme(s.theme === "light" ? "light" : "dark");916    if (s.textSize === "small" || s.textSize === "large") {917      setTextSize(s.textSize);918    } else {919      setTextSize("medium");920    }921    setReduceMotion(s.reduceMotion === true);922    setLockOnClose(s.lockOnClose !== false);923    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);924    setBreachMonitoring(s.breachMonitoring !== false);925    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);926    setShortcutBindings(getActiveBindings(s.shortcuts));927  }928929  async function applyTrashRetention(days: number) {930    setTrashRetentionDays(days);931    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });932  }933934  function primeListSearch(seed: string) {935    setListSearchSeed(seed);936    setListSearchSeedNonce((value) => value + 1);937    openList();938  }939940  // Returns null when it detected a dead service worker and triggered handleLock().941  // Callers that need to abort (e.g. openVault) check for null rather than relying942  // on view() state, which may already be "lock" during normal startup flows.943  async function loadEntries(): Promise<VaultEntry[] | null> {944    const response = await sendMessage({ type: "GET_ENTRIES" });945    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };946947    // If the service worker was killed and restarted (MV3 workers sleep), the948    // vault will be locked again — or the worker may not respond at all.949    // In either case, send the user to the lock screen rather than silently950    // showing an empty vault (which looks like data loss).951    if (!res.ok) {952      if (953        res.error === "vault_locked" ||954        res.error === "SERVICE_WORKER_UNAVAILABLE" ||955        (typeof res.error === "string" && res.error.includes("locked"))956      ) {957        handleLock();958        return null; // signal emergency lock to callers959      }960      return [];961    }962963    const loadedEntries = res.data ?? [];964    setEntries(loadedEntries);965966    const currentId = selectedEntry()?.id;967    if (currentId) {968      setSelectedEntry(969        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null970      );971    }972973    return loadedEntries;974  }975976  async function openVault(preferredEntryId?: string, skipViewSet = false) {977    // Purge expired trash entries on each vault open978    const retDays = trashRetentionDays();979    if (retDays > 0) {980      void sendMessage({981        type: "PURGE_EXPIRED_TRASH",982        payload: { retentionMs: retDays * 86_400_000 },983      });984    }985986    const loadedEntries = await loadEntries();987988    // null means loadEntries() triggered an emergency lock (service worker died).989    // Don't override it by setting view back to "entry" with an empty vault.990    if (loadedEntries === null) return;991992    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry993    let nextSelectedEntry: VaultEntry | null = null;994    if (preferredEntryId) {995      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;996    }997    if (!nextSelectedEntry) {998      const tabDomain = currentTabDomain();999      if (tabDomain) {1000        nextSelectedEntry = loadedEntries.find((e) => {1001          if (e.type === "login") {1002            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1003            for (const extra of e.additionalUrls ?? []) {1004              if ((extractDomain(extra) ?? "") === tabDomain) return true;1005            }1006            return false;1007          }1008          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1009          return false;1010        }) ?? null;1011      }1012    }1013    nextSelectedEntry ??= loadedEntries[0] ?? null;10141015    setSelectedEntry(nextSelectedEntry);1016    setEditEntry(undefined);1017    setContentTransitioning(false);1018    setContentPhase("enter");1019    queueContentIdle();1020    if (!skipViewSet) setView("entry");1021  }10221023  async function handleUnlock() {1024    // If the user previously created a vault but hadn't yet confirmed their1025    // recovery words (and the browser was closed before they could), the1026    // peach_recovery_pending flag is still set in storage.local. Re-route1027    // back to the recovery surface so they finish the confirmation step1028    // before reaching the entries view — the words can be re-derived now1029    // that the vault is unlocked again.1030    let recoveryPending = false;1031    try {1032      const out = await chrome.storage.local?.get("peach_recovery_pending");1033      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1034    } catch { /* best-effort */ }1035    if (recoveryPending) {1036      setForceRecoveryWords(true);1037      setView("lock");1038      triggerPipPulse();1039      await restoreSettings();1040      return;1041    }1042    setHasVault(true);1043    triggerPipPulse();1044    await restoreSettings();1045    const celebrating = pendingCelebration();1046    if (celebrating) {1047      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1048      setPendingCelebration(false);1049    }1050    await openVault(undefined, celebrating);1051    if (celebrating) {1052      setView("pro-celebration");1053      window.setTimeout(() => setView("entry"), 2500);1054    }1055    // Popup was opened from the inline "Open Peach to unlock" button — close it1056    // now so the user lands back on the page with the autofill selector ready.1057    if (openedForInlineUnlock) {1058      openedForInlineUnlock = false;1059      window.close();1060    }1061  }10621063  function handleSelectEntry(entry: VaultEntry) {1064    if (entry.type === "note") {1065      setOpenNoteId(entry.id);1066      setShowNotes(true);1067      return;1068    }1069    setSelectedEntry(entry);1070    setContentTransitioning(false);1071    setContentPhase("enter");1072    queueContentIdle();1073    setView("entry");1074  }10751076  function handleAdd() {1077    setEditEntry(undefined);1078    setView("add");1079  }10801081  async function handleDelete() {1082    const entry = selectedEntry();1083    if (!entry) return;1084    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1085    const loadedEntries = await loadEntries() ?? [];1086    setSelectedEntry(loadedEntries[0] ?? null);1087    setView("entry");1088  }10891090  async function handleDeleteMany(ids: string[]) {1091    for (const id of ids) {1092      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1093    }1094    const loadedEntries = await loadEntries() ?? [];1095    // If the currently selected entry was among the deleted, move to first1096    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1097    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1098  }10991100  async function handleSave(savedEntry?: VaultEntry) {1101    await openVault(savedEntry?.id);1102  }11031104  function handleBack() {1105    const dest = editBackView();1106    setEditBackView("entry");1107    setEditEntry(undefined);1108    setView(dest);1109  }11101111  function handleExportBack() {1112    if (returnToPanic()) {1113      setReturnToPanic(false);1114      setView("panic");1115      return;1116    }1117    setView("settings");1118  }11191120  function handleLock() {1121    clearCanarySuppressions();1122    setEntries([]);1123    setSelectedEntry(null);1124    setEditEntry(undefined);1125    setContentPhase("idle");1126    setView("lock");1127  }11281129  function handleHeaderLock() {1130    // Lock the UI immediately — do not wait for the service worker. If the SW1131    // is dead or slow, the 5s sendMessage timeout would create a dead-click1132    // window. The SW will lock on its next wake regardless.1133    handleLock();1134    void sendMessage({ type: "LOCK" });1135  }11361137  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1138  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1139  // the trigger's own reply.1140  async function handleHeaderSync(): Promise<void> {1141    if (syncBusy()) return;1142    setSyncBusy(true);1143    setSyncFlash(null);1144    try {1145      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1146      let status: string = "syncing";1147      for (let i = 0; i < 40 && status === "syncing"; i++) {1148        await new Promise((r) => setTimeout(r, 250));1149        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1150          ok: boolean;1151          data?: { status?: string };1152        };1153        status = res.ok ? res.data?.status ?? "idle" : "error";1154      }1155      setSyncFlash(status === "error" ? "error" : "ok");1156      await loadSyncAlerts();1157      await loadEntries();1158    } catch {1159      setSyncFlash("error");1160    } finally {1161      setSyncBusy(false);1162      setTimeout(() => setSyncFlash(null), 2_000);1163    }1164  }11651166  function navigate(dir: number) {1167    const allEntries = entries();1168    if (allEntries.length === 0) return;1169    const currentIndex = selectedIndex();1170    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1171    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1172    setSelectedEntry(allEntries[nextIndex]);1173    setContentPhase("enter");1174    queueContentIdle();1175  }11761177  function openList() {1178    setView("list");1179  }11801181  function openHealth() {1182    setEditEntry(undefined);1183    setView("health");1184  }11851186  function handleOpenFileImport() {1187    setRestoreView("file");1188  }11891190  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11911192  function handleFixEntry(entry: VaultEntry) {1193    setSelectedEntry(entry);1194    // Passkey-only entries have no editable surface — drop into view mode1195    // instead of opening the Add editor.1196    if (isPasskeyOnly(entry)) {1197      setView("entry");1198      return;1199    }1200    setEditBackView(view()); // preserve caller view so back returns here1201    setEditEntry(entry);1202    setView("add");1203  }12041205  const isLockedView = () => view() === "lock" || view() === "adopting";12061207  async function handleAdoptionDone() {1208    await storageSet("peach_onboarded", "true").catch(() => {});1209    setOnboarded(true);1210    setHasVault(true);1211    await handleUnlock();1212    void sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "foreground" } });1213  }12141215  /**1216   * Join an existing vault from a brand-new install.1217   *1218   * This used to require the receiver to LISTEN for the other device (a1219   * Capacitor pairing server), which a browser extension structurally cannot1220   * do — so on every real browser build it threw before doing anything. Over a1221   * pairing code the receiver is the DIALLER instead, which is the only shape1222   * that works here: dial the code, confirm the SAS, then ask for the vault.1223   *1224   * The vault does not exist yet at dial time, so nothing in this path may1225   * touch the vault before `createVaultFromRootKey` runs.1226   */1227  async function startVaultAdoption(args: {1228    password: string;1229    connection:1230      | { mode: "relay"; invitation: string }1231      | { mode: "lan"; code: string };1232    confirmSAS(sas: string): Promise<boolean>;1233    createVault(rootKeyHex: string): Promise<{ vaultId: string }>;1234  }) {1235    const [{1236      dialPairingChannel,1237      dialRelayPairingChannel,1238      openPairingSocket,1239      openRelayPairingSocket,1240    }, { requestAdoption }, { setLastKnownIp }] =1241      await Promise.all([1242        import("../shared/pairing-dial"),1243        import("../shared/vault-adopt"),1244        import("../background/paired-devices"),1245      ]);12461247    const dial = args.connection.mode === "relay"1248      ? await dialRelayPairingChannel(args.connection.invitation, {1249        openSocket: openRelayPairingSocket,1250      })1251      : await dialPairingChannel(args.connection.code, {1252        openSocket: openPairingSocket,1253      }, { flow: "adoption" });1254    if (!dial.ok) throw new Error(dial.error);1255    const {1256      channel,1257      sas,1258      socket,1259      host,1260      relayUrl,1261      rendezvousSecretHex,1262    } = dial.dialled;12631264    try {1265      const source = await requestAdoption(channel, {1266        deviceName: defaultAdoptionDeviceName(),1267        generateDeviceId: () => crypto.randomUUID(),1268        // requestAdoption writes ADOPT_CONFIRM and refuses to read a root-key1269        // grant until this local SAS decision is true.1270        confirmSas: () => args.confirmSAS(sas),1271        pairState: { rendezvousSecretHex, relayUrl },1272        createVaultFromRootKey: args.createVault,1273        deriveLocalIdentity: async () => {1274          const res = await sendMessage({ type: "GET_LOCAL_IDENTITY" });1275          const r = res as { ok: boolean; data?: unknown; error?: string };1276          if (!r.ok || !r.data) throw new Error(r.error ?? "identity_unavailable");1277          return r.data as Awaited<ReturnType<Parameters<typeof requestAdoption>[1]["deriveLocalIdentity"]>>;1278        },1279        upsertPairedDevice: async (paired) => {1280          const res = await sendMessage({ type: "COMPLETE_PAIRING", payload: { paired } });1281          const r = res as { ok: boolean; error?: string };1282          if (!r.ok) throw new Error(r.error ?? "complete_pairing_failed");1283          // Seed the reconnect cache with the address we just dialled, exactly as1284          // device pairing does (code-pairing.ts). Without it an adopted browser1285          // never syncs on Chrome: the runner lives in the MV3 service worker,1286          // its probe fallback needs RTCPeerConnection to find the /24, and that1287          // API does not exist in a service worker — so getSubnet() always1288          // returns null and connect() throws subnet_unknown forever. The cache1289          // is the only route that ever reaches the peer.1290          if (!relayUrl && paired.longTermPublicKeyHex) {1291            await setLastKnownIp(paired.longTermPublicKeyHex, host).catch(() => undefined);1292          }1293        },1294        applyLicense: async (license) => {1295          const res = (await sendMessage({1296            type: "ACTIVATE_LICENSE",1297            payload: { key: license },1298          })) as { ok: boolean; data?: { valid?: boolean; plan?: string } };1299          if (res.ok && res.data?.valid && res.data?.plan === "pro") await refreshProStatus();1300        },1301        onError(error) {1302          throw new Error(1303            error === "ADOPT_SAS_REJECTED" ? "sas_rejected" : error,1304          );1305        },1306      });1307      if (!source) throw new Error("adoption_rejected");1308      if (relayUrl) {1309        const setting = (await sendMessage({1310          type: "SET_RELAY_SETTINGS",1311          payload: { relayUrl, lanOnly: false },1312        })) as { ok: boolean; error?: string };1313        if (!setting.ok) throw new Error(setting.error ?? "relay_settings_failed");1314      }1315    } finally {1316      socket.close();1317    }1318  }13191320  async function handleApprovePendingPasskey() {1321    const pending = pendingPasskey();1322    if (!pending) return;1323    if (pending.browser === "firefox" && pending.type === "create") {1324      // Firefox path: popup itself runs navigator.credentials.create. The1325      // background never approved/rejected anything — it just stashed1326      // intent. After the popup-driven flow resolves (success or cancel),1327      // clear the pending key so the popup doesn't re-show this on next open.1328      const { createFirefoxPasskey } = await import("./firefox-passkey");1329      const result = await createFirefoxPasskey(pending);1330      if (!result.ok) {1331        console.warn("Peach Firefox passkey create failed:", result.error);1332      }1333      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1334      setPendingPasskey(null);1335      void loadEntries();1336      window.close();1337      return;1338    }1339    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1340    window.close();1341  }13421343  async function handleDenyPendingPasskey() {1344    const pending = pendingPasskey();1345    if (!pending) return;1346    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1347    window.close();1348  }13491350  function queueContentIdle(after?: () => void) {1351    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1352    contentPhaseTimer = window.setTimeout(() => {1353      setContentPhase("idle");1354      after?.();1355    }, ENTRY_TRANSITION_SETTLE_MS);1356  }13571358  return (1359    <div class="popup-root peach-theme">1360      <Show when={bootState() === "ready"}>1361        <Show1362          when={!pendingPasskey()}1363          fallback={1364            <PasskeyApprovalView1365              type={pendingPasskey()!.type}1366              rpName={pendingPasskey()!.rpName}1367              rpId={pendingPasskey()!.rpId}1368              userName={pendingPasskey()!.userName}1369              userDisplayName={pendingPasskey()!.userDisplayName}1370              onApprove={handleApprovePendingPasskey}1371              onDeny={handleDenyPendingPasskey}1372            />1373          }1374        >1375          <Show1376            when={!isLockedView()}1377            fallback={1378              <Show1379                when={view() !== "adopting"}1380                fallback={1381                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1382                    <AdoptVaultView1383                      onCancel={() => {1384                        setOnboarded(false);1385                        setView("lock");1386                      }}1387                      onDone={handleAdoptionDone}1388                      startAdoption={startVaultAdoption}1389                    />1390                  </Suspense>1391                }1392              >1393                <Show1394                  when={onboarded() || hasVault()}1395                  fallback={1396                    <Onboarding1397                      onComplete={() => { setOnboarded(true); }}1398                      onRestore={() => { setOnboarded(true); }}1399                      onAdopt={() => {1400                        setOnboarded(true);1401                        setView("adopting");1402                      }}1403                    />1404                  }1405                >1406                  <LockView1407                    hasVault={hasVault()}1408                    ready={bootState() === "ready"}1409                    isPro={proStatus()}1410                    forceRecoveryWords={forceRecoveryWords()}1411                    onUnlock={() => {1412                      // RecoveryWordDisplay clears the storage flag before1413                      // calling onDone, so handleUnlock will see no pending1414                      // confirmation and proceed through the normal path.1415                      if (forceRecoveryWords()) setForceRecoveryWords(false);1416                      return handleUnlock();1417                    }}1418                    onBackToOnboarding={1419                      !hasVault()1420                        ? () => setOnboarded(false)1421                        : undefined1422                    }1423                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1424                  />1425                </Show>1426              </Show>1427            }1428          >1429            <Show1430              when={view() !== "pro-celebration"}1431              fallback={<ProCelebration />}1432            >1433            <section1434              id="hd-shell"1435              class="peach-shell peach-theme"1436              data-surface="extension"1437            >1438            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1439              <PeachWordmark unlocked />1440              <div class="peach-chrome-actions">1441                <button1442                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1443                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1444                  aria-label="Notes"1445                  title="Notes"1446                >1447                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1448                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1449                    <line x1="4" y1="5" x2="10" y2="5" />1450                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1451                    <line x1="4" y1="10" x2="7" y2="10" />1452                  </svg>1453                </button>1454                <Show when={syncPaired()}>1455                  <button1456                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1457                    classList={{1458                      "is-syncing": syncBusy(),1459                      "is-ok": syncFlash() === "ok",1460                      "is-error": syncFlash() === "error",1461                    }}1462                    onClick={() => void handleHeaderSync()}1463                    disabled={syncBusy()}1464                    aria-label={syncBusy() ? "Syncing" : "Sync now"}1465                    title="Sync now"1466                  >1467                    <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">1468                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1469                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1470                      <path d="M2.6 1v2.4h2.4" />1471                      <path d="M11.4 13v-2.4H9" />1472                    </svg>1473                  </button>1474                </Show>1475                <button1476                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1477                  onClick={() => setView("settings")}1478                  aria-label="Settings"1479                >1480                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1481                    <path1482                      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"1483                      stroke="currentColor"1484                      stroke-width="0.9"1485                    />1486                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1487                  </svg>1488                </button>1489                <button1490                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1491                  onClick={handleAdd}1492                  aria-label="New entry"1493                >1494                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1495                    <path d="M5.5 1v9M1 5.5h9" />1496                  </svg>1497                </button>1498                <button1499                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1500                  onClick={() => void handleHeaderLock()}1501                  aria-label="Lock vault"1502                >1503                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1504                    <path1505                      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"1506                      stroke="currentColor"1507                      stroke-width="1"1508                      stroke-linecap="round"1509                    />1510                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1511                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1512                  </svg>1513                </button>1514              </div>1515            </header>15161517            <Show when={pendingProNotice() !== null}>1518              <div class="peach-pro-notice-banner">1519                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1520                <button1521                  class="peach-pro-notice-link"1522                  onClick={() => {1523                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1524                    setSettingsInitialSection("license");1525                    setView("settings");1526                    setPendingProNotice(null);1527                  }}1528                >1529                  Learn more →1530                </button>1531                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1532              </div>1533            </Show>15341535            <div class="peach-shell-body">1536              <div class="peach-shell-veil"></div>1537              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1538                <EntryView1539                  entry={selectedEntry()}1540                  currentTabUrl={currentTabUrl()}1541                  entries={entries()}1542                  isPro={proStatus()}1543                  onDelete={handleDelete}1544                  onFieldSaved={() => void loadEntries()}1545                  onEscape={() => { setView("list"); }}1546                  onProGate={(feature) => {1547                    setUpgradeHighlight(feature);1548                    setSettingsInitialSection("license");1549                    setView("settings");1550                  }}1551                />1552              </div>15531554              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1555                <div class="peach-search-bar">1556                  <span class="peach-search-icon">1557                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1558                      <circle cx="5.5" cy="5.5" r="3.75" />1559                      <path d="M8.75 8.75L11.5 11.5" />1560                    </svg>1561                  </span>1562                  <input1563                    class="peach-search-input"1564                    placeholder="search vault..."1565                    autocomplete="off"1566                    aria-label="Search vault entries"1567                    onClick={openList}1568                    onFocus={openList}1569                    readOnly1570                  />1571                  <div class="peach-search-meta">1572                    <span class="peach-search-counter">1573                      {entries().length > 01574                        ? `${selectedIndex() + 1} / ${entries().length}`1575                        : "0 entries"}1576                    </span>1577                    <span class="peach-divider"></span>1578                    <button1579                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1580                      onClick={() => navigate(-1)}1581                      aria-label="Previous entry"1582                      disabled={entries().length === 0}1583                    >1584                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1585                        <path d="M5 1L1 5.5L5 10" />1586                      </svg>1587                    </button>1588                    <button1589                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1590                      onClick={() => navigate(1)}1591                      aria-label="Next entry"1592                      disabled={entries().length === 0}1593                    >1594                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1595                        <path d="M1 1L5 5.5L1 10" />1596                      </svg>1597                    </button>1598                  </div>1599                </div>1600              </section>1601            </div>16021603            {/* Desktop: shown on demand via Show. Native sheet is rendered1604                via Portal below at the document root so its position:fixed1605                isn't trapped by .peach-shell's transform-based animations. */}1606            {/* UI-1 / HV-1b: dismissible remote-mutation alert banners. */}1607            <Show when={syncAlerts().length > 0}>1608              <div class="peach-sync-alerts">1609                <For each={syncAlerts()}>1610                  {(alert, i) => (1611                    <div class="peach-sync-alert">1612                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1613                      <button1614                        class="peach-sync-alert-dismiss"1615                        type="button"1616                        aria-label="Dismiss"1617                        onClick={() => dismissSyncAlert(i())}1618                      >×</button>1619                    </div>1620                  )}1621                </For>1622              </div>1623            </Show>16241625            <Show when={!isNativePlatform() && view() === "list"}>1626              <VaultView1627                entries={entries()}1628                selectedEntryId={selectedEntry()?.id}1629                currentTabDomain={currentTabDomain()}1630                sortOrder={sortOrder()}1631                searchSeed={listSearchSeed()}1632                searchSeedNonce={listSearchSeedNonce()}1633                onSelectEntry={handleSelectEntry}1634                onSortOrderChange={setSortOrder}1635                onAdd={handleAdd}1636                onClose={() => setView("entry")}1637                onOpenTrash={() => setView("trash")}1638                onDeleteMany={handleDeleteMany}1639              />1640            </Show>1641            <Show when={isNativePlatform() && hasVault()}>1642              <Portal>1643                <div1644                  class="peach-vault-sheet"1645                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1646                  style={(() => {1647                    const live = sheetTranslate();1648                    if (live === null) return undefined;1649                    return { transform: `translateY(${live}px)` };1650                  })()}1651                >1652                  <VaultView1653                    entries={entries()}1654                    selectedEntryId={selectedEntry()?.id}1655                    currentTabDomain={currentTabDomain()}1656                    sortOrder={sortOrder()}1657                    searchSeed={listSearchSeed()}1658                    searchSeedNonce={listSearchSeedNonce()}1659                    isNative={true}1660                    onSelectEntry={handleSelectEntry}1661                    onSortOrderChange={setSortOrder}1662                    onAdd={handleAdd}1663                    onClose={() => setView("entry")}1664                    onOpenTrash={() => setView("trash")}1665                    onDeleteMany={handleDeleteMany}1666                  />1667                </div>1668              </Portal>1669            </Show>1670            <Show when={view() === "settings" || settingsExiting()}>1671              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1672                <SettingsView1673                  entriesCount={entries().length}1674                  breachMonitoring={breachMonitoring()}1675                  lockOnClose={lockOnClose()}1676                  autoLockMinutes={autoLockMinutes()}1677                  trashRetentionDays={trashRetentionDays()}1678                  theme={theme()}1679                  accentColor={accentColor()}1680                  textSize={textSize()}1681                  reduceMotion={reduceMotion()}1682                  isPro={proStatus()}1683                  initialSection={settingsInitialSection()}1684                  upgradeHighlight={upgradeHighlight()}1685                  isExiting={settingsExiting()}1686                  onBreachMonitoringChange={applyBreachMonitoring}1687                  onLockOnCloseChange={applyLockOnClose}1688                  onAutoLockMinutesChange={applyAutoLockMinutes}1689                  onTrashRetentionChange={applyTrashRetention}1690                  onThemeChange={applyTheme}1691                  onAccentChange={applyAccentColor}1692                  onTextSizeChange={applyTextSize}1693                  onReduceMotionChange={applyReduceMotion}1694                  shortcuts={shortcutBindings()}1695                  onShortcutsChange={applyShortcuts}1696                  onLicenseChange={async () => {1697                    // After activation/deactivation: refresh Pro status,1698                    // re-load entries (defensive — signal state can drift if1699                    // the SW briefly restarts during the verify+save round-trip),1700                    // and replay the Pro celebration if this is the first time1701                    // a valid Pro license is seen on this device.1702                    await refreshProStatus();1703                    void loadEntries();1704                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1705                    if ((should as { ok: boolean; data?: boolean }).data === true) {1706                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1707                      setView("pro-celebration");1708                      window.setTimeout(() => setView("settings"), 2500);1709                    }1710                  }}1711                  onBack={() => {1712                    setSettingsExiting(true);1713                    window.setTimeout(() => {1714                      setSettingsExiting(false);1715                      setSettingsInitialSection(null);1716                      setUpgradeHighlight(null);1717                      handleBack();1718                    }, 200);1719                  }}1720                  onImport={() => setView("import")}1721                  onExport={() => setView("export")}1722                  onBreachCheckDone={loadEntries}1723                  onOpenHealth={openHealth}1724                  onOpenSyncPairing={(method) => { setSettingsInitialSection(settingsActiveCard()); setSyncPairIntent(method ?? null); setView("pair-device"); }}1725                  onOpenFileImport={handleOpenFileImport}1726                  onOpenPanic={() => setView("panic")}1727                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1728                  onOpenCodexRestore={() => setView("codex-restore")}1729                  onCardChange={setSettingsActiveCard}1730                  onProGate={(feature) => {1731                    setUpgradeHighlight(feature);1732                    setSettingsInitialSection("license");1733                  }}1734                />1735              </Suspense>1736            </Show>1737            <Show when={view() === "codex-generate"}>1738              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1739                <CodexGenerateView1740                  isPro={proStatus()}1741                  onBack={() => setView("settings")}1742                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1743                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1744                  onVaultLocked={() => handleLock()}1745                />1746              </Suspense>1747            </Show>1748            <Show when={view() === "codex-restore"}>1749              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1750                <CodexRestoreView1751                  onBack={() => setView("lock")}1752                  onRestoreSuccess={async () => {1753                    // After restore the vault is unlocked; refresh entries1754                    // and route to the main vault list. handleUnlock is the1755                    // canonical post-unlock setup path.1756                    await handleUnlock();1757                  }}1758                />1759              </Suspense>1760            </Show>1761            <Show when={view() === "pair-device"}>1762              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1763                <PairDeviceView1764                  isPro={proStatus()}1765                  initialPair={syncPairIntent()}1766                  onProChanged={() => { void refreshProStatus(); }}1767                  onBack={() => { setSyncPairIntent(null); setView("settings"); }}1768                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1769                />1770              </Suspense>1771            </Show>1772            <Show when={view() === "add"}>1773              <AddView1774                entry={editEntry()}1775                entries={entries()}1776                onBack={handleBack}1777                onSave={handleSave}1778              />1779            </Show>1780            <Show when={view() === "import"}>1781              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1782                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1783              </Suspense>1784            </Show>1785            <Show when={view() === "export"}>1786              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1787                <ExportView onBack={handleExportBack} />1788              </Suspense>1789            </Show>1790            <Show when={view() === "panic"}>1791              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1792                <PanicView1793                  onCancel={() => setView("settings")}1794                  onOpenExport={() => {1795                    setReturnToPanic(true);1796                    setView("export");1797                  }}1798                  onDestroyed={async () => {1799                    clearCanarySuppressions();1800                    setEntries([]);1801                    setSelectedEntry(null);1802                    setEditEntry(undefined);1803                    setHasVault(false);1804                    setOnboarded(false);1805                    setProStatus(false);1806                    setPendingPasskey(null);1807                    setUpgradeHighlight(null);1808                    setSettingsInitialSection(null);1809                    setPendingProNotice(null);1810                    setPendingCelebration(false);1811                    setReturnToPanic(false);1812                    setContentPhase("idle");1813                    setView("lock");1814                  }}1815                />1816              </Suspense>1817            </Show>1818            {/* Health stays mounted while editing an entry from it so1819                computeReused() doesn't rerun on every cancel/back. */}1820            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1821              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1822                <HealthView1823                  entries={entries()}1824                  isPro={proStatus()}1825                  onFixEntry={handleFixEntry}1826                  onBack={() => setView("settings")}1827                  onRefresh={loadEntries}1828                  hidden={view() !== "health"}1829                />1830              </Suspense>1831            </Show>1832            <Show when={view() === "trash"}>1833              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1834                <TrashView1835                  onBack={() => setView("list")}1836                  onRestored={() => void loadEntries()}1837                />1838              </Suspense>1839            </Show>1840            <Show when={showNotes()}>1841              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1842                <NotesMode1843                  notes={entries().filter((e) => e.type === "note")}1844                  initialNoteId={openNoteId()}1845                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1846                  onNoteListChanged={() => void loadEntries()}1847                />1848              </div>1849            </Show>1850            <Show when={restoreView() === "file"}>1851              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1852                <ImportView1853                  mode="onboarding"1854                  replacesExistingVault={true}1855                  onBack={() => setRestoreView(null)}1856                  onImport={async () => {1857                    setRestoreView(null);1858                    await handleUnlock();1859                  }}1860                />1861              </Suspense>1862            </Show>1863            </section>1864            </Show>1865          </Show>1866        </Show>1867      </Show>1868      <Show when={showShortcutsHelp()}>1869        <ShortcutsHelpOverlay1870          bindings={shortcutBindings()}1871          onClose={() => setShowShortcutsHelp(false)}1872        />1873      </Show>1874    </div>1875  );1876}18771878function ShortcutsHelpOverlay(props: {1879  bindings: Record<ShortcutAction, Keybinding>;1880  onClose: () => void;1881}) {1882  return (1883    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1884      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1885        <div class="peach-shortcuts-help-head">1886          <h3>Keyboard shortcuts</h3>1887          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1888        </div>1889        <div class="peach-shortcuts-help-body">1890          <p class="peach-settings-sub-label">ENTRY VIEW</p>1891          <ul>1892            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1893              <li>1894                <span>{d.label}</span>1895                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1896              </li>1897            ))}1898          </ul>1899          <p class="peach-settings-sub-label">ANYWHERE</p>1900          <ul>1901            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1902              <li>1903                <span>{d.label}</span>1904                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1905              </li>1906            ))}1907          </ul>1908        </div>1909      </div>1910    </div>1911  );1912}