App.tsx

75.7 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  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);220  // Set on popup boot when peach_recovery_pending flag is found in session221  // storage — instructs LockView to skip the unlock UI and open the recovery222  // words confirmation surface instead. Cleared via handleUnlock once the223  // user has typed the 3 confirmation words.224  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);225226  let contentPhaseTimer: number | undefined;227  // Set when the popup was opened from the inline "Open Peach to unlock" button.228  // handleUnlock() closes the popup after unlock so the user returns to the page.229  let openedForInlineUnlock = false;230231  function applyAccent(name: AccentColorName) {232    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;233    const hex = color.hex;234    document.documentElement.style.setProperty("--peach-accent", hex);235    // Ambient surface variables — derived from the accent so surfaces shift236    // subtly toward the accent hue rather than staying fixed warm-brown.237    document.documentElement.style.setProperty("--peach-glow", hex + "2A");238    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");239    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");240  }241242  createEffect(() => {243    applyAccent(accentColor());244  });245246  createEffect(() => {247    document.documentElement.classList.toggle("light", theme() === "light");248    document.body.classList.toggle("light", theme() === "light");249  });250251  createEffect(() => {252    document.documentElement.setAttribute("data-text-size", textSize());253  });254255  createEffect(() => {256    if (reduceMotion()) {257      document.documentElement.setAttribute("data-motion", "reduce");258    } else {259      document.documentElement.removeAttribute("data-motion");260    }261  });262263  const selectedIndex = createMemo(() => {264    const currentId = selectedEntry()?.id;265    if (!currentId) return entries().length > 0 ? 0 : -1;266    return entries().findIndex((entry) => entry.id === currentId);267  });268269  async function applyAccentColor(name: AccentColorName) {270    applyAccent(name);271    setAccentColor(name);272    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });273  }274275  async function applyTheme(t: "dark" | "light") {276    setTheme(t);277    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });278  }279280  async function applyTextSize(size: "small" | "medium" | "large") {281    setTextSize(size);282    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });283  }284285  async function applyReduceMotion(enabled: boolean) {286    setReduceMotion(enabled);287    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });288  }289290  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload291  // small and lets future default updates land for actions the user hasn't292  // touched. Settings sends us the full active map; we filter and store.293  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {294    setShortcutBindings(active);295    const overrides: Record<string, Keybinding> = {};296    for (const action of Object.keys(active) as ShortcutAction[]) {297      const a = active[action];298      const d = DEFAULT_BINDINGS[action];299      const same = a.key === d.key300        && Boolean(a.ctrl)  === Boolean(d.ctrl)301        && Boolean(a.meta)  === Boolean(d.meta)302        && Boolean(a.shift) === Boolean(d.shift)303        && Boolean(a.alt)   === Boolean(d.alt);304      if (!same) overrides[action] = a;305    }306    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });307  }308309  async function applyLockOnClose(enabled: boolean) {310    setLockOnClose(enabled);311    await sendMessage({312      type: "UPDATE_SETTINGS",313      payload: { lockOnClose: enabled },314    });315  }316317  async function applyAutoLockMinutes(minutes: number) {318    setAutoLockMinutes(minutes);319    await sendMessage({320      type: "UPDATE_SETTINGS",321      payload: { autoLockMinutes: minutes },322    });323  }324325  async function applyBreachMonitoring(enabled: boolean) {326    setBreachMonitoring(enabled);327    await sendMessage({328      type: "UPDATE_SETTINGS",329      payload: { breachMonitoring: enabled },330    });331  }332333  onMount(async () => {334    // Resolve the active tab in parallel with the unlock/has-vault queries —335    // openVault()'s smart selection picks the entry matching currentTabDomain,336    // so it must be populated before openVault runs. Previously refreshCurrentTab337    // ran after openVault, leaving popups that booted already-unlocked falling338    // back to loadedEntries[0] instead of the domain match.339    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([340      sendMessage({ type: "IS_UNLOCKED" }),341      sendMessage({ type: "HAS_VAULT" }),342      refreshCurrentTab(),343      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),344    ]);345    const unlocked = Boolean(346      (unlockResponse as { ok: boolean; data?: boolean }).data347    );348    const vaultExists = Boolean(349      (vaultResponse as { ok: boolean; data?: boolean }).data350    );351    const shouldCelebrate = Boolean(352      (celebrationResponse as { ok: boolean; data?: boolean }).data353    );354    setHasVault(vaultExists);355    // Onboarding gate — show once on first install, never again. Existing356    // users (vaultExists) are auto-marked onboarded so they skip the flow357    // even on the very first popup open after this feature ships.358    try {359      const onboarded = await storageGet("peach_onboarded");360      const seen = onboarded === "true";361      if (vaultExists && !seen) {362        await storageSet("peach_onboarded", "true");363        setOnboarded(true);364      } else {365        setOnboarded(seen);366      }367    } catch {368      // storage unavailable — default to onboarded so we never block boot369      setOnboarded(true);370    }371    await Promise.all([restoreSettings(), refreshProStatus()]);372373    // Mark played before any animation so a crash mid-sequence never replays it374    if (shouldCelebrate) {375      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });376    }377378    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the379    // background ignores it when no mobile hosts are paired or while380    // another sync is already in flight.381    if (unlocked && vaultExists) {382      void sendMessage({383        type: "TRIGGER_SYNC",384        payload: { reason: "foreground" },385      });386      // UI-1 / HV-1b: surface any remote-mutation alerts the sync merge queued.387      void loadSyncAlerts();388    }389390    // If the user created a vault but hasn't yet confirmed their recovery391    // words, route back to the recovery-words screen instead of opening the392    // entries view. The flag lives in chrome.storage.local so it survives393    // both popup close (SW suppresses lock-on-close) and full browser394    // restart (handleUnlock checks the same flag after a fresh password395    // unlock). Cleared when confirmation succeeds.396    let recoveryPending = false;397    try {398      const out = await chrome.storage.local?.get("peach_recovery_pending");399      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";400    } catch { /* best-effort */ }401402    // If this popup was opened from the inline "Open Peach to unlock" button,403    // the background set a session flag. Read and clear it so handleUnlock()404    // can close the popup after unlock and return the user to the page.405    if (chrome.storage.session) {406      try {407        const s = await chrome.storage.session.get("peach_inline_unlock");408        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {409          openedForInlineUnlock = true;410          await chrome.storage.session.remove("peach_inline_unlock");411        }412      } catch { /* best-effort */ }413    }414415    // Native: closing the app before recovery-words confirmation means the416    // user didn't finish vault creation. Throw the partial vault away and417    // restart onboarding rather than asking them to unlock a vault they418    // never finished creating. Desktop keeps the existing "unlock to419    // resume" flow because closing the popup there is much more casual.420    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {421      try {422        await chrome.storage.local?.remove([423          "peach_vault_a",424          "peach_vault_b",425          "peach_recovery_pending",426          "peach_onboarded",427          "peach_vault_history",428        ]);429      } catch { /* best-effort */ }430      setHasVault(false);431      setOnboarded(false);432      setView("lock");433      setBootState("ready");434      return;435    }436437    if (recoveryPending && unlocked) {438      // forceRecoveryWords overrides LockView's hasVault gate so the439      // recovery surface renders even though the vault now exists.440      setForceRecoveryWords(true);441      setView("lock");442    } else if (unlocked && vaultExists) {443      await openVault(undefined, shouldCelebrate);444      if (shouldCelebrate) {445        setView("pro-celebration");446        window.setTimeout(() => setView("entry"), 2500);447      }448    } else if (shouldCelebrate) {449      setPendingCelebration(true);450    }451452    await refreshPendingPasskey();453454    // Track tab changes so smart sort stays current455    const handleTabActivated = () => { void refreshCurrentTab(); };456    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {457      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();458    };459    try {460      chrome.tabs.onActivated.addListener(handleTabActivated);461      chrome.tabs.onUpdated.addListener(handleTabUpdated);462      onCleanup(() => {463        chrome.tabs.onActivated.removeListener(handleTabActivated);464        chrome.tabs.onUpdated.removeListener(handleTabUpdated);465      });466    } catch {467      // tabs permission may not be available in all contexts468    }469470    setBootState("ready");471472    // Deep-link: ?codex=pdf opens a detached window straight into the473    // Codex restore flow with auto-picked PDF. The action popup can't host474    // a file dialog without dismissing itself, so this is the only way the475    // PDF import path survives. See CodexRestoreView.openPdfPicker().476    try {477      const route = new URLSearchParams(window.location.search).get("codex");478      if (route === "pdf" || route === "restore") {479        setView("codex-restore");480      }481    } catch {482      // location.search unavailable — ignore.483    }484485    // Check for pending session-storage notices from the background.486    if (chrome.storage.session) {487      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as488        Record<string, { feature?: string } | undefined>;489      if (session.pendingProGate?.feature) {490        await chrome.storage.session.remove("pendingProGate");491        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);492        setSettingsInitialSection("license");493        setView("settings");494      } else if (session.pendingProNotice?.feature) {495        await chrome.storage.session.remove("pendingProNotice");496        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });497      }498    }499500    // Warm the lazy-module cache so the Suspense fallback never shows for501    // locally-bundled extension views. Without this, the first navigation to502    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which503    // covers the shell and absorbs clicks on the header.504    void Promise.all([505      import("./views/Settings").catch(() => {}),506      import("./views/Import").catch(() => {}),507      import("./views/Export").catch(() => {}),508      import("./views/Health").catch(() => {}),509      import("./views/TrashView").catch(() => {}),510    ]);511512    // Lock-on-close via a persistent port. sendMessage in pagehide is513    // unreliable — the popup context tears down before the message lands.514    // The SW's onConnect listener locks when this port disconnects.515    let popupPort: chrome.runtime.Port | null = null;516    try {517      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect518      // listener accepts the "popup-" prefix; the random suffix is defence in519      // depth against a port named exactly "popup" from anything but our popup.520      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });521    } catch { /* extension context invalidated — ignore */ }522    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });523524    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only525    // reliable signal is appStateChange — setTimeout is killed when the OS526    // backgrounds the app. We measure elapsed background time on resume.527    if (isNativePlatform()) {528      let backgroundedAt: number | null = null;529530      const CapApp = nativePlugin<{531        addListener: (532          ev: string,533          cb: (s: { isActive: boolean }) => void,534        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };535      }>("App");536      if (CapApp?.addListener) {537        const sub = CapApp.addListener(538          "appStateChange",539          ({ isActive }: { isActive: boolean }) => {540            if (!isActive) {541              backgroundedAt = Date.now();542              return;543            }544            if (backgroundedAt !== null && autoLockMinutes() > 0) {545              const elapsed = Date.now() - backgroundedAt;546              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();547            }548            backgroundedAt = null;549          }550        );551        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.552        onCleanup(() => {553          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});554        });555      }556557      // L12/COR-011: foreground idle autolock. appStateChange only fires when558      // the OS backgrounds the app — if the user idles with the screen on,559      // chrome.alarms is no-op'd in Capacitor so the vault would stay open560      // indefinitely. Poll every 30s and lock if elapsed since last user561      // interaction exceeds autoLockMinutes.562      let lastUserActivityAt = Date.now();563      const bumpActivity = () => { lastUserActivityAt = Date.now(); };564      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;565      for (const ev of ACTIVITY_EVENTS) {566        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });567      }568      const idleLockInterval = setInterval(() => {569        const minutes = autoLockMinutes();570        if (!minutes || minutes <= 0) return;571        const elapsed = Date.now() - lastUserActivityAt;572        if (elapsed >= minutes * 60_000) {573          lastUserActivityAt = Date.now();574          handleHeaderLock();575        }576      }, 30_000);577      onCleanup(() => {578        clearInterval(idleLockInterval);579        for (const ev of ACTIVITY_EVENTS) {580          document.removeEventListener(ev, bumpActivity, { capture: true });581        }582      });583584      // The retired native peer-discovery trigger went with the old Capacitor585      // pairing plugin. Reconnection is address-cache first, subnet probe second586      // (sync-runner.ts); relocating a peer that changed networks is an587      // Android-side discovery concern now.588      if (isNativePlatform()) {589        // Android runs the background/sync dispatcher in-process with the590        // popup, so the production runner has to be registered from the591        // UI bootstrap path instead of the MV3 service-worker entry.592        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>593          import("../background/sync-runner").then(({ productionSyncRunner }) => {594            setSyncRunner(productionSyncRunner);595            void hydratePersistedSyncState();596          })597        );598      }599    }600601    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale602    // entries instead of waiting for the next GET_ENTRIES round-trip.603    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {604      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();605      if (msg?.type === "PRO_GATE_TRIGGERED") {606        setUpgradeHighlight(msg.payload?.feature ?? null);607        setSettingsInitialSection("license");608        setView("settings");609      }610    };611    chrome.runtime.onMessage.addListener(handleRuntimeMessage);612    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));613614    // Android hardware/gesture back. MainActivity fires peach:back; the popup615    // decides what "back" means per surface. Lock+no-vault is the common case616    // — return to onboarding rather than letting the OS dismiss the activity.617    const handlePeachBack = () => {618      // Notes mode captures back first619      if (showNotes()) {620        setShowNotes(false);621        setOpenNoteId(undefined);622        return;623      }624      const v = view();625      if (v === "lock" && !hasVault() && onboarded()) {626        setOnboarded(false);627        return;628      }629      if (v === "list") { setView("entry"); return; }630      if (v === "settings") {631        window.dispatchEvent(new Event("peach:settings-back"));632        return;633      }634      if (v === "import" || v === "health") { setView("settings"); return; }635      if (v === "export") { handleExportBack(); return; }636      if (v === "add") { handleBack(); return; }637      if (v === "pair-device") { setView("settings"); return; }638    };639    window.addEventListener("peach:back", handlePeachBack);640    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));641642    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that643    // peeks from the bottom (search bar handle visible) and drags up to fill644    // the screen. dragOffset is the LIVE finger offset during a drag, in px,645    // 0 when no drag in progress. The wrapper element computes transform =646    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.647    if (isNativePlatform()) {648      let touchStartY = 0;649      let touchStartX = 0;650      let lastY = 0;651      let lastT = 0;652      let dragging = false;653      let captured = false;654      const HORIZONTAL_TOLERANCE = 16;655      const ACTIVATION_DY = 8;656      const PEEK_PX = 60;657658      const onTouchStart = (e: TouchEvent) => {659        const t = e.touches[0];660        if (!t) return;661        const v = view();662        if (v !== "entry" && v !== "list") return;663        // Entry view: only intercept drags starting in the bottom 40%.664        // List view: intercept drags starting in the top 35% (the search/handle row).665        const inBand = v === "entry"666          ? t.clientY > window.innerHeight * 0.6667          : t.clientY < window.innerHeight * 0.35;668        if (!inBand) return;669        touchStartY = lastY = t.clientY;670        touchStartX = t.clientX;671        lastT = e.timeStamp;672        dragging = true;673        captured = false;674      };675676      const onTouchMove = (e: TouchEvent) => {677        if (!dragging) return;678        const t = e.touches[0];679        if (!t) return;680        const dy = t.clientY - touchStartY;681        const dx = Math.abs(t.clientX - touchStartX);682683        if (!captured) {684          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {685            // Looks like a horizontal swipe — release.686            dragging = false;687            return;688          }689          if (Math.abs(dy) < ACTIVATION_DY) return;690          captured = true;691        }692693        // Translate the sheet by dy from its rest (peek) position. Peek is694        // (viewport height - PEEK_PX). Open is 0.695        const v = view();696        const restClosed = window.innerHeight - PEEK_PX;697        const baseTranslate = v === "list" ? 0 : restClosed;698        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));699        setSheetTranslate(next);700        lastY = t.clientY;701        lastT = e.timeStamp;702      };703704      const onTouchEnd = (e: TouchEvent) => {705        if (!dragging) { return; }706        const t = e.changedTouches[0];707        const elapsed = Math.max(1, e.timeStamp - lastT);708        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms709        const wasCaptured = captured;710        dragging = false;711        captured = false;712        const v = view();713714        if (!wasCaptured) {715          // Tap in the peek strip while in entry view → open the vault list.716          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");717          setSheetTranslate(null);718          return;719        }720721        const restClosed = window.innerHeight - PEEK_PX;722        const current = sheetTranslate() ?? restClosed;723724        // Snap rules:725        //   - Strong upward velocity → open726        //   - Strong downward velocity → close727        //   - Otherwise snap to whichever rest is closer728        let nextOpen: boolean;729        if (velocity < -0.05) nextOpen = true;730        else if (velocity > 0.05) nextOpen = false;731        else nextOpen = current < restClosed * 0.5;732733        if (nextOpen && v !== "list") setView("list");734        if (!nextOpen && v !== "entry") setView("entry");735        // Release the live offset so CSS transition handles the snap.736        setSheetTranslate(null);737      };738739      document.addEventListener("touchstart", onTouchStart, { passive: true });740      document.addEventListener("touchmove",  onTouchMove,  { passive: true });741      document.addEventListener("touchend",   onTouchEnd,   { passive: true });742      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });743      onCleanup(() => {744        document.removeEventListener("touchstart", onTouchStart);745        document.removeEventListener("touchmove",  onTouchMove);746        document.removeEventListener("touchend",   onTouchEnd);747      });748    }749750    // Action handlers — keyed by ShortcutAction. The dispatcher below tests751    // each binding against the event and runs the matching handler. New752    // shortcuts only need an entry here; the binding is data, not code.753    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {754      copy_password: () => {755        const entry = selectedEntry();756        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });757      },758      copy_username: () => {759        const entry = selectedEntry();760        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });761      },762      copy_totp: () => {763        const entry = selectedEntry();764        if (!entry?.totp) return;765        try {766          const { code } = generateTOTP(entry.totp);767          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });768        } catch { /* invalid TOTP secret — silent */ }769      },770      new_entry: () => handleAdd(),771      edit_entry: () => {772        const entry = selectedEntry();773        // Passkey-only entries have nothing user-editable in the Add view; the774        // passkey credential itself is opaque. Skip the edit action for them.775        if (!entry || isPasskeyOnly(entry)) return;776        setEditEntry(entry);777        setView("add");778      },779      delete_entry: () => {780        if (selectedEntry()) void handleDelete();781      },782      lock_vault: () => { void handleHeaderLock(); },783      search: () => openList(),784      nav_prev: () => navigate(-1),785      nav_next: () => navigate(1),786      jump_vault: () => setView("entry"),787      jump_settings: () => setView("settings"),788      show_help: () => setShowShortcutsHelp(true),789    };790791    // Actions that are MEANINGFUL only on the entry-detail view. Outside792    // that scope the binding is dormant — pressing C while on Settings793    // does nothing rather than awkwardly copying from a now-stale entry.794    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([795      "copy_password", "copy_username", "copy_totp",796      "edit_entry", "delete_entry", "nav_prev", "nav_next",797    ]);798799    const handleGlobalKeydown = (e: KeyboardEvent) => {800      const v = view();801      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"802        || (e.target as HTMLElement)?.tagName === "TEXTAREA"803        || (e.target as HTMLElement)?.isContentEditable;804      const isPrintableSearchKey =805        e.key.length === 1 &&806        !e.ctrlKey &&807        !e.metaKey &&808        !e.altKey;809810      // No input during the pro celebration sequence811      if (v === "pro-celebration") return;812813      // Help dialog: Escape closes it; eat the keypress so it doesn't814      // also navigate away from the underlying view.815      if (showShortcutsHelp()) {816        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }817        return;818      }819820      // ── Escape — fixed binding (not user-customizable) ───────821      if (e.key === "Escape") {822        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }823        if (v === "list") { setView("entry"); return; }824        if (v === "settings" || v === "add") { handleBack(); return; }825        if (v === "import" || v === "health") { setView("settings"); return; }826        if (v === "export") { handleExportBack(); return; }827        if (v === "pair-device") { setView("settings"); return; }828      }829830      // Bindings-driven dispatch. Single-key letter bindings without831      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is832      // inside an input, so users can type into search/forms normally.833      const bindings = shortcutBindings();834      for (const action of Object.keys(bindings) as ShortcutAction[]) {835        const binding = bindings[action];836        if (!matchKeybinding(e, binding)) continue;837        // Single-key letter bindings need the input-focus guard. Bindings838        // with any modifier are safe — Ctrl+L doesn't conflict with typing.839        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;840        if (!hasMod && binding.key.length === 1 && inInput) return;841        if (ENTRY_SCOPED.has(action) && v !== "entry") return;842        e.preventDefault();843        SHORTCUT_HANDLERS[action]?.();844        return;845      }846847      // Type-to-search: in entry view, any printable key not consumed by a848      // shortcut above primes the list search seed and opens the list.849      // Kept outside the bindings table because it's a behavior, not a850      // discrete action — every printable character can trigger it.851      if (v === "entry" && !inInput && isPrintableSearchKey) {852        e.preventDefault();853        primeListSearch(e.key);854        return;855      }856    };857    window.addEventListener("keydown", handleGlobalKeydown);858    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));859860    const handleStorageChanged = (861      changes: Record<string, chrome.storage.StorageChange>,862      areaName: string863    ) => {864      if (areaName !== "session") return;865      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {866        return;867      }868      void refreshPendingPasskey();869    };870    chrome.storage.onChanged.addListener(handleStorageChanged);871    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));872  });873874  async function refreshCurrentTab() {875    try {876      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });877      const url = tab?.url ?? tab?.pendingUrl ?? "";878      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");879      // Skip extension/internal URLs — adding chrome://, about:, or880      // chrome-extension:// to a vault entry is never what the user wants.881      const isWebUrl = /^https?:\/\//i.test(url);882      setCurrentTabUrl(isWebUrl ? url : "");883    } catch {884      setCurrentTabDomain("");885      setCurrentTabUrl("");886    }887  }888889  async function refreshPendingPasskey() {890    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });891    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);892  }893894  async function refreshProStatus() {895    const res = await sendMessage({ type: "GET_LICENSE" });896    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;897    setProStatus(Boolean(data?.valid && data?.plan === "pro"));898  }899900  async function restoreSettings() {901    const res = await sendMessage({ type: "GET_SETTINGS" });902    const s = (res as { ok: boolean; data?: any }).data ?? {};903    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {904      setAccentColor(s.accentColor as AccentColorName);905    }906    setTheme(s.theme === "light" ? "light" : "dark");907    if (s.textSize === "small" || s.textSize === "large") {908      setTextSize(s.textSize);909    } else {910      setTextSize("medium");911    }912    setReduceMotion(s.reduceMotion === true);913    setLockOnClose(s.lockOnClose !== false);914    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);915    setBreachMonitoring(s.breachMonitoring !== false);916    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);917    setShortcutBindings(getActiveBindings(s.shortcuts));918  }919920  async function applyTrashRetention(days: number) {921    setTrashRetentionDays(days);922    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });923  }924925  function primeListSearch(seed: string) {926    setListSearchSeed(seed);927    setListSearchSeedNonce((value) => value + 1);928    openList();929  }930931  // Returns null when it detected a dead service worker and triggered handleLock().932  // Callers that need to abort (e.g. openVault) check for null rather than relying933  // on view() state, which may already be "lock" during normal startup flows.934  async function loadEntries(): Promise<VaultEntry[] | null> {935    const response = await sendMessage({ type: "GET_ENTRIES" });936    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };937938    // If the service worker was killed and restarted (MV3 workers sleep), the939    // vault will be locked again — or the worker may not respond at all.940    // In either case, send the user to the lock screen rather than silently941    // showing an empty vault (which looks like data loss).942    if (!res.ok) {943      if (944        res.error === "vault_locked" ||945        res.error === "SERVICE_WORKER_UNAVAILABLE" ||946        (typeof res.error === "string" && res.error.includes("locked"))947      ) {948        handleLock();949        return null; // signal emergency lock to callers950      }951      return [];952    }953954    const loadedEntries = res.data ?? [];955    setEntries(loadedEntries);956957    const currentId = selectedEntry()?.id;958    if (currentId) {959      setSelectedEntry(960        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null961      );962    }963964    return loadedEntries;965  }966967  async function openVault(preferredEntryId?: string, skipViewSet = false) {968    // Purge expired trash entries on each vault open969    const retDays = trashRetentionDays();970    if (retDays > 0) {971      void sendMessage({972        type: "PURGE_EXPIRED_TRASH",973        payload: { retentionMs: retDays * 86_400_000 },974      });975    }976977    const loadedEntries = await loadEntries();978979    // null means loadEntries() triggered an emergency lock (service worker died).980    // Don't override it by setting view back to "entry" with an empty vault.981    if (loadedEntries === null) return;982983    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry984    let nextSelectedEntry: VaultEntry | null = null;985    if (preferredEntryId) {986      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;987    }988    if (!nextSelectedEntry) {989      const tabDomain = currentTabDomain();990      if (tabDomain) {991        nextSelectedEntry = loadedEntries.find((e) => {992          if (e.type === "login") {993            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;994            for (const extra of e.additionalUrls ?? []) {995              if ((extractDomain(extra) ?? "") === tabDomain) return true;996            }997            return false;998          }999          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1000          return false;1001        }) ?? null;1002      }1003    }1004    nextSelectedEntry ??= loadedEntries[0] ?? null;10051006    setSelectedEntry(nextSelectedEntry);1007    setEditEntry(undefined);1008    setContentTransitioning(false);1009    setContentPhase("enter");1010    queueContentIdle();1011    if (!skipViewSet) setView("entry");1012  }10131014  async function handleUnlock() {1015    // If the user previously created a vault but hadn't yet confirmed their1016    // recovery words (and the browser was closed before they could), the1017    // peach_recovery_pending flag is still set in storage.local. Re-route1018    // back to the recovery surface so they finish the confirmation step1019    // before reaching the entries view — the words can be re-derived now1020    // that the vault is unlocked again.1021    let recoveryPending = false;1022    try {1023      const out = await chrome.storage.local?.get("peach_recovery_pending");1024      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1025    } catch { /* best-effort */ }1026    if (recoveryPending) {1027      setForceRecoveryWords(true);1028      setView("lock");1029      triggerPipPulse();1030      await restoreSettings();1031      return;1032    }1033    setHasVault(true);1034    triggerPipPulse();1035    await restoreSettings();1036    const celebrating = pendingCelebration();1037    if (celebrating) {1038      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1039      setPendingCelebration(false);1040    }1041    await openVault(undefined, celebrating);1042    if (celebrating) {1043      setView("pro-celebration");1044      window.setTimeout(() => setView("entry"), 2500);1045    }1046    // Popup was opened from the inline "Open Peach to unlock" button — close it1047    // now so the user lands back on the page with the autofill selector ready.1048    if (openedForInlineUnlock) {1049      openedForInlineUnlock = false;1050      window.close();1051    }1052  }10531054  function handleSelectEntry(entry: VaultEntry) {1055    if (entry.type === "note") {1056      setOpenNoteId(entry.id);1057      setShowNotes(true);1058      return;1059    }1060    setSelectedEntry(entry);1061    setContentTransitioning(false);1062    setContentPhase("enter");1063    queueContentIdle();1064    setView("entry");1065  }10661067  function handleAdd() {1068    setEditEntry(undefined);1069    setView("add");1070  }10711072  async function handleDelete() {1073    const entry = selectedEntry();1074    if (!entry) return;1075    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1076    const loadedEntries = await loadEntries() ?? [];1077    setSelectedEntry(loadedEntries[0] ?? null);1078    setView("entry");1079  }10801081  async function handleDeleteMany(ids: string[]) {1082    for (const id of ids) {1083      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1084    }1085    const loadedEntries = await loadEntries() ?? [];1086    // If the currently selected entry was among the deleted, move to first1087    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1088    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1089  }10901091  async function handleSave(savedEntry?: VaultEntry) {1092    await openVault(savedEntry?.id);1093  }10941095  function handleBack() {1096    const dest = editBackView();1097    setEditBackView("entry");1098    setEditEntry(undefined);1099    setView(dest);1100  }11011102  function handleExportBack() {1103    if (returnToPanic()) {1104      setReturnToPanic(false);1105      setView("panic");1106      return;1107    }1108    setView("settings");1109  }11101111  function handleLock() {1112    clearCanarySuppressions();1113    setEntries([]);1114    setSelectedEntry(null);1115    setEditEntry(undefined);1116    setContentPhase("idle");1117    setView("lock");1118  }11191120  function handleHeaderLock() {1121    // Lock the UI immediately — do not wait for the service worker. If the SW1122    // is dead or slow, the 5s sendMessage timeout would create a dead-click1123    // window. The SW will lock on its next wake regardless.1124    handleLock();1125    void sendMessage({ type: "LOCK" });1126  }11271128  function navigate(dir: number) {1129    const allEntries = entries();1130    if (allEntries.length === 0) return;1131    const currentIndex = selectedIndex();1132    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1133    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1134    setSelectedEntry(allEntries[nextIndex]);1135    setContentPhase("enter");1136    queueContentIdle();1137  }11381139  function openList() {1140    setView("list");1141  }11421143  function openHealth() {1144    setEditEntry(undefined);1145    setView("health");1146  }11471148  function handleOpenFileImport() {1149    setRestoreView("file");1150  }11511152  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11531154  function handleFixEntry(entry: VaultEntry) {1155    setSelectedEntry(entry);1156    // Passkey-only entries have no editable surface — drop into view mode1157    // instead of opening the Add editor.1158    if (isPasskeyOnly(entry)) {1159      setView("entry");1160      return;1161    }1162    setEditBackView(view()); // preserve caller view so back returns here1163    setEditEntry(entry);1164    setView("add");1165  }11661167  const isLockedView = () => view() === "lock" || view() === "adopting";11681169  async function handleAdoptionDone() {1170    await storageSet("peach_onboarded", "true").catch(() => {});1171    setOnboarded(true);1172    setHasVault(true);1173    await handleUnlock();1174    void sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "foreground" } });1175  }11761177  /**1178   * Join an existing vault from a brand-new install.1179   *1180   * This used to require the receiver to LISTEN for the other device (a1181   * Capacitor pairing server), which a browser extension structurally cannot1182   * do — so on every real browser build it threw before doing anything. Over a1183   * pairing code the receiver is the DIALLER instead, which is the only shape1184   * that works here: dial the code, confirm the SAS, then ask for the vault.1185   *1186   * The vault does not exist yet at dial time, so nothing in this path may1187   * touch the vault before `createVaultFromRootKey` runs.1188   */1189  async function startVaultAdoption(args: {1190    password: string;1191    code: string;1192    confirmSAS(sas: string): Promise<boolean>;1193    createVault(rootKeyHex: string): Promise<{ vaultId: string }>;1194  }) {1195    const [{ dialPairingChannel, openPairingSocket }, { requestAdoption }, { setLastKnownIp }] =1196      await Promise.all([1197        import("../shared/pairing-dial"),1198        import("../shared/vault-adopt"),1199        import("../background/paired-devices"),1200      ]);12011202    // Adoption accepts the same pairing code as device pairing; it carries the1203    // listener address and one-time token.1204    const dial = await dialPairingChannel(args.code, { openSocket: openPairingSocket });1205    if (!dial.ok) throw new Error(dial.error);1206    const { channel, sas, socket, host } = dial.dialled;12071208    try {1209      const source = await requestAdoption(channel, {1210        deviceName: defaultAdoptionDeviceName(),1211        generateDeviceId: () => crypto.randomUUID(),1212        // requestAdoption writes ADOPT_CONFIRM and refuses to read a root-key1213        // grant until this local SAS decision is true.1214        confirmSas: () => args.confirmSAS(sas),1215        createVaultFromRootKey: args.createVault,1216        deriveLocalIdentity: async () => {1217          const res = await sendMessage({ type: "GET_LOCAL_IDENTITY" });1218          const r = res as { ok: boolean; data?: unknown; error?: string };1219          if (!r.ok || !r.data) throw new Error(r.error ?? "identity_unavailable");1220          return r.data as Awaited<ReturnType<Parameters<typeof requestAdoption>[1]["deriveLocalIdentity"]>>;1221        },1222        upsertPairedDevice: async (paired) => {1223          const res = await sendMessage({ type: "COMPLETE_PAIRING", payload: { paired } });1224          const r = res as { ok: boolean; error?: string };1225          if (!r.ok) throw new Error(r.error ?? "complete_pairing_failed");1226          // Seed the reconnect cache with the address we just dialled, exactly as1227          // device pairing does (code-pairing.ts). Without it an adopted browser1228          // never syncs on Chrome: the runner lives in the MV3 service worker,1229          // its probe fallback needs RTCPeerConnection to find the /24, and that1230          // API does not exist in a service worker — so getSubnet() always1231          // returns null and connect() throws subnet_unknown forever. The cache1232          // is the only route that ever reaches the peer.1233          if (paired.longTermPublicKeyHex) {1234            await setLastKnownIp(paired.longTermPublicKeyHex, host).catch(() => undefined);1235          }1236        },1237        applyLicense: async (license) => {1238          const res = (await sendMessage({1239            type: "ACTIVATE_LICENSE",1240            payload: { key: license },1241          })) as { ok: boolean; data?: { valid?: boolean; plan?: string } };1242          if (res.ok && res.data?.valid && res.data?.plan === "pro") await refreshProStatus();1243        },1244        onError(error) {1245          throw new Error(1246            error === "ADOPT_SAS_REJECTED" ? "sas_rejected" : error,1247          );1248        },1249      });1250      if (!source) throw new Error("adoption_rejected");1251    } finally {1252      socket.close();1253    }1254  }12551256  async function handleApprovePendingPasskey() {1257    const pending = pendingPasskey();1258    if (!pending) return;1259    if (pending.browser === "firefox" && pending.type === "create") {1260      // Firefox path: popup itself runs navigator.credentials.create. The1261      // background never approved/rejected anything — it just stashed1262      // intent. After the popup-driven flow resolves (success or cancel),1263      // clear the pending key so the popup doesn't re-show this on next open.1264      const { createFirefoxPasskey } = await import("./firefox-passkey");1265      const result = await createFirefoxPasskey(pending);1266      if (!result.ok) {1267        console.warn("Peach Firefox passkey create failed:", result.error);1268      }1269      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1270      setPendingPasskey(null);1271      void loadEntries();1272      window.close();1273      return;1274    }1275    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1276    window.close();1277  }12781279  async function handleDenyPendingPasskey() {1280    const pending = pendingPasskey();1281    if (!pending) return;1282    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1283    window.close();1284  }12851286  function queueContentIdle(after?: () => void) {1287    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1288    contentPhaseTimer = window.setTimeout(() => {1289      setContentPhase("idle");1290      after?.();1291    }, ENTRY_TRANSITION_SETTLE_MS);1292  }12931294  return (1295    <div class="popup-root peach-theme">1296      <Show when={bootState() === "ready"}>1297        <Show1298          when={!pendingPasskey()}1299          fallback={1300            <PasskeyApprovalView1301              type={pendingPasskey()!.type}1302              rpName={pendingPasskey()!.rpName}1303              rpId={pendingPasskey()!.rpId}1304              userName={pendingPasskey()!.userName}1305              userDisplayName={pendingPasskey()!.userDisplayName}1306              onApprove={handleApprovePendingPasskey}1307              onDeny={handleDenyPendingPasskey}1308            />1309          }1310        >1311          <Show1312            when={!isLockedView()}1313            fallback={1314              <Show1315                when={view() !== "adopting"}1316                fallback={1317                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1318                    <AdoptVaultView1319                      onCancel={() => {1320                        setOnboarded(false);1321                        setView("lock");1322                      }}1323                      onDone={handleAdoptionDone}1324                      startAdoption={startVaultAdoption}1325                    />1326                  </Suspense>1327                }1328              >1329                <Show1330                  when={onboarded() || hasVault()}1331                  fallback={1332                    <Onboarding1333                      onComplete={() => { setOnboarded(true); }}1334                      onRestore={() => { setOnboarded(true); }}1335                      onAdopt={() => {1336                        setOnboarded(true);1337                        setView("adopting");1338                      }}1339                    />1340                  }1341                >1342                  <LockView1343                    hasVault={hasVault()}1344                    ready={bootState() === "ready"}1345                    isPro={proStatus()}1346                    forceRecoveryWords={forceRecoveryWords()}1347                    onUnlock={() => {1348                      // RecoveryWordDisplay clears the storage flag before1349                      // calling onDone, so handleUnlock will see no pending1350                      // confirmation and proceed through the normal path.1351                      if (forceRecoveryWords()) setForceRecoveryWords(false);1352                      return handleUnlock();1353                    }}1354                    onBackToOnboarding={1355                      !hasVault()1356                        ? () => setOnboarded(false)1357                        : undefined1358                    }1359                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1360                  />1361                </Show>1362              </Show>1363            }1364          >1365            <Show1366              when={view() !== "pro-celebration"}1367              fallback={<ProCelebration />}1368            >1369            <section1370              id="hd-shell"1371              class="peach-shell peach-theme"1372              data-surface="extension"1373            >1374            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1375              <PeachWordmark unlocked />1376              <div class="peach-chrome-actions">1377                <button1378                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1379                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1380                  aria-label="Notes"1381                  title="Notes"1382                >1383                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1384                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1385                    <line x1="4" y1="5" x2="10" y2="5" />1386                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1387                    <line x1="4" y1="10" x2="7" y2="10" />1388                  </svg>1389                </button>1390                <button1391                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1392                  onClick={() => setView("settings")}1393                  aria-label="Settings"1394                >1395                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1396                    <path1397                      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"1398                      stroke="currentColor"1399                      stroke-width="0.9"1400                    />1401                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1402                  </svg>1403                </button>1404                <button1405                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1406                  onClick={handleAdd}1407                  aria-label="New entry"1408                >1409                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1410                    <path d="M5.5 1v9M1 5.5h9" />1411                  </svg>1412                </button>1413                <button1414                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1415                  onClick={() => void handleHeaderLock()}1416                  aria-label="Lock vault"1417                >1418                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1419                    <path1420                      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"1421                      stroke="currentColor"1422                      stroke-width="1"1423                      stroke-linecap="round"1424                    />1425                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1426                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1427                  </svg>1428                </button>1429              </div>1430            </header>14311432            <Show when={pendingProNotice() !== null}>1433              <div class="peach-pro-notice-banner">1434                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1435                <button1436                  class="peach-pro-notice-link"1437                  onClick={() => {1438                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1439                    setSettingsInitialSection("license");1440                    setView("settings");1441                    setPendingProNotice(null);1442                  }}1443                >1444                  Learn more →1445                </button>1446                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1447              </div>1448            </Show>14491450            <div class="peach-shell-body">1451              <div class="peach-shell-veil"></div>1452              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1453                <EntryView1454                  entry={selectedEntry()}1455                  currentTabUrl={currentTabUrl()}1456                  entries={entries()}1457                  isPro={proStatus()}1458                  onDelete={handleDelete}1459                  onFieldSaved={() => void loadEntries()}1460                  onEscape={() => { setView("list"); }}1461                  onProGate={(feature) => {1462                    setUpgradeHighlight(feature);1463                    setSettingsInitialSection("license");1464                    setView("settings");1465                  }}1466                />1467              </div>14681469              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1470                <div class="peach-search-bar">1471                  <span class="peach-search-icon">1472                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1473                      <circle cx="5.5" cy="5.5" r="3.75" />1474                      <path d="M8.75 8.75L11.5 11.5" />1475                    </svg>1476                  </span>1477                  <input1478                    class="peach-search-input"1479                    placeholder="search vault..."1480                    autocomplete="off"1481                    aria-label="Search vault entries"1482                    onClick={openList}1483                    onFocus={openList}1484                    readOnly1485                  />1486                  <div class="peach-search-meta">1487                    <span class="peach-search-counter">1488                      {entries().length > 01489                        ? `${selectedIndex() + 1} / ${entries().length}`1490                        : "0 entries"}1491                    </span>1492                    <span class="peach-divider"></span>1493                    <button1494                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1495                      onClick={() => navigate(-1)}1496                      aria-label="Previous entry"1497                      disabled={entries().length === 0}1498                    >1499                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1500                        <path d="M5 1L1 5.5L5 10" />1501                      </svg>1502                    </button>1503                    <button1504                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1505                      onClick={() => navigate(1)}1506                      aria-label="Next entry"1507                      disabled={entries().length === 0}1508                    >1509                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1510                        <path d="M1 1L5 5.5L1 10" />1511                      </svg>1512                    </button>1513                  </div>1514                </div>1515              </section>1516            </div>15171518            {/* Desktop: shown on demand via Show. Native sheet is rendered1519                via Portal below at the document root so its position:fixed1520                isn't trapped by .peach-shell's transform-based animations. */}1521            {/* UI-1 / HV-1b: dismissible remote-mutation alert banners. */}1522            <Show when={syncAlerts().length > 0}>1523              <div class="peach-sync-alerts">1524                <For each={syncAlerts()}>1525                  {(alert, i) => (1526                    <div class="peach-sync-alert">1527                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1528                      <button1529                        class="peach-sync-alert-dismiss"1530                        type="button"1531                        aria-label="Dismiss"1532                        onClick={() => dismissSyncAlert(i())}1533                      >×</button>1534                    </div>1535                  )}1536                </For>1537              </div>1538            </Show>15391540            <Show when={!isNativePlatform() && view() === "list"}>1541              <VaultView1542                entries={entries()}1543                selectedEntryId={selectedEntry()?.id}1544                currentTabDomain={currentTabDomain()}1545                sortOrder={sortOrder()}1546                searchSeed={listSearchSeed()}1547                searchSeedNonce={listSearchSeedNonce()}1548                onSelectEntry={handleSelectEntry}1549                onSortOrderChange={setSortOrder}1550                onAdd={handleAdd}1551                onClose={() => setView("entry")}1552                onOpenTrash={() => setView("trash")}1553                onDeleteMany={handleDeleteMany}1554              />1555            </Show>1556            <Show when={isNativePlatform() && hasVault()}>1557              <Portal>1558                <div1559                  class="peach-vault-sheet"1560                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1561                  style={(() => {1562                    const live = sheetTranslate();1563                    if (live === null) return undefined;1564                    return { transform: `translateY(${live}px)` };1565                  })()}1566                >1567                  <VaultView1568                    entries={entries()}1569                    selectedEntryId={selectedEntry()?.id}1570                    currentTabDomain={currentTabDomain()}1571                    sortOrder={sortOrder()}1572                    searchSeed={listSearchSeed()}1573                    searchSeedNonce={listSearchSeedNonce()}1574                    isNative={true}1575                    onSelectEntry={handleSelectEntry}1576                    onSortOrderChange={setSortOrder}1577                    onAdd={handleAdd}1578                    onClose={() => setView("entry")}1579                    onOpenTrash={() => setView("trash")}1580                    onDeleteMany={handleDeleteMany}1581                  />1582                </div>1583              </Portal>1584            </Show>1585            <Show when={view() === "settings" || settingsExiting()}>1586              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1587                <SettingsView1588                  entriesCount={entries().length}1589                  breachMonitoring={breachMonitoring()}1590                  lockOnClose={lockOnClose()}1591                  autoLockMinutes={autoLockMinutes()}1592                  trashRetentionDays={trashRetentionDays()}1593                  theme={theme()}1594                  accentColor={accentColor()}1595                  textSize={textSize()}1596                  reduceMotion={reduceMotion()}1597                  isPro={proStatus()}1598                  initialSection={settingsInitialSection()}1599                  upgradeHighlight={upgradeHighlight()}1600                  isExiting={settingsExiting()}1601                  onBreachMonitoringChange={applyBreachMonitoring}1602                  onLockOnCloseChange={applyLockOnClose}1603                  onAutoLockMinutesChange={applyAutoLockMinutes}1604                  onTrashRetentionChange={applyTrashRetention}1605                  onThemeChange={applyTheme}1606                  onAccentChange={applyAccentColor}1607                  onTextSizeChange={applyTextSize}1608                  onReduceMotionChange={applyReduceMotion}1609                  shortcuts={shortcutBindings()}1610                  onShortcutsChange={applyShortcuts}1611                  onLicenseChange={async () => {1612                    // After activation/deactivation: refresh Pro status,1613                    // re-load entries (defensive — signal state can drift if1614                    // the SW briefly restarts during the verify+save round-trip),1615                    // and replay the Pro celebration if this is the first time1616                    // a valid Pro license is seen on this device.1617                    await refreshProStatus();1618                    void loadEntries();1619                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1620                    if ((should as { ok: boolean; data?: boolean }).data === true) {1621                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1622                      setView("pro-celebration");1623                      window.setTimeout(() => setView("settings"), 2500);1624                    }1625                  }}1626                  onBack={() => {1627                    setSettingsExiting(true);1628                    window.setTimeout(() => {1629                      setSettingsExiting(false);1630                      setSettingsInitialSection(null);1631                      setUpgradeHighlight(null);1632                      handleBack();1633                    }, 200);1634                  }}1635                  onImport={() => setView("import")}1636                  onExport={() => setView("export")}1637                  onBreachCheckDone={loadEntries}1638                  onOpenHealth={openHealth}1639                  onOpenSyncPairing={(method) => { setSettingsInitialSection(settingsActiveCard()); setSyncPairIntent(method ?? null); setView("pair-device"); }}1640                  onOpenFileImport={handleOpenFileImport}1641                  onOpenPanic={() => setView("panic")}1642                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1643                  onOpenCodexRestore={() => setView("codex-restore")}1644                  onCardChange={setSettingsActiveCard}1645                  onProGate={(feature) => {1646                    setUpgradeHighlight(feature);1647                    setSettingsInitialSection("license");1648                  }}1649                />1650              </Suspense>1651            </Show>1652            <Show when={view() === "codex-generate"}>1653              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1654                <CodexGenerateView1655                  isPro={proStatus()}1656                  onBack={() => setView("settings")}1657                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1658                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1659                  onVaultLocked={() => handleLock()}1660                />1661              </Suspense>1662            </Show>1663            <Show when={view() === "codex-restore"}>1664              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1665                <CodexRestoreView1666                  onBack={() => setView("lock")}1667                  onRestoreSuccess={async () => {1668                    // After restore the vault is unlocked; refresh entries1669                    // and route to the main vault list. handleUnlock is the1670                    // canonical post-unlock setup path.1671                    await handleUnlock();1672                  }}1673                />1674              </Suspense>1675            </Show>1676            <Show when={view() === "pair-device"}>1677              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1678                <PairDeviceView1679                  isPro={proStatus()}1680                  initialPair={syncPairIntent()}1681                  onProChanged={() => { void refreshProStatus(); }}1682                  onBack={() => { setSyncPairIntent(null); setView("settings"); }}1683                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1684                />1685              </Suspense>1686            </Show>1687            <Show when={view() === "add"}>1688              <AddView1689                entry={editEntry()}1690                entries={entries()}1691                onBack={handleBack}1692                onSave={handleSave}1693              />1694            </Show>1695            <Show when={view() === "import"}>1696              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1697                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1698              </Suspense>1699            </Show>1700            <Show when={view() === "export"}>1701              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1702                <ExportView onBack={handleExportBack} />1703              </Suspense>1704            </Show>1705            <Show when={view() === "panic"}>1706              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1707                <PanicView1708                  onCancel={() => setView("settings")}1709                  onOpenExport={() => {1710                    setReturnToPanic(true);1711                    setView("export");1712                  }}1713                  onDestroyed={async () => {1714                    clearCanarySuppressions();1715                    setEntries([]);1716                    setSelectedEntry(null);1717                    setEditEntry(undefined);1718                    setHasVault(false);1719                    setOnboarded(false);1720                    setProStatus(false);1721                    setPendingPasskey(null);1722                    setUpgradeHighlight(null);1723                    setSettingsInitialSection(null);1724                    setPendingProNotice(null);1725                    setPendingCelebration(false);1726                    setReturnToPanic(false);1727                    setContentPhase("idle");1728                    setView("lock");1729                  }}1730                />1731              </Suspense>1732            </Show>1733            {/* Health stays mounted while editing an entry from it so1734                computeReused() doesn't rerun on every cancel/back. */}1735            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1736              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1737                <HealthView1738                  entries={entries()}1739                  isPro={proStatus()}1740                  onFixEntry={handleFixEntry}1741                  onBack={() => setView("settings")}1742                  onRefresh={loadEntries}1743                  hidden={view() !== "health"}1744                />1745              </Suspense>1746            </Show>1747            <Show when={view() === "trash"}>1748              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1749                <TrashView1750                  onBack={() => setView("list")}1751                  onRestored={() => void loadEntries()}1752                />1753              </Suspense>1754            </Show>1755            <Show when={showNotes()}>1756              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1757                <NotesMode1758                  notes={entries().filter((e) => e.type === "note")}1759                  initialNoteId={openNoteId()}1760                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1761                  onNoteListChanged={() => void loadEntries()}1762                />1763              </div>1764            </Show>1765            <Show when={restoreView() === "file"}>1766              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1767                <ImportView1768                  mode="onboarding"1769                  replacesExistingVault={true}1770                  onBack={() => setRestoreView(null)}1771                  onImport={async () => {1772                    setRestoreView(null);1773                    await handleUnlock();1774                  }}1775                />1776              </Suspense>1777            </Show>1778            </section>1779            </Show>1780          </Show>1781        </Show>1782      </Show>1783      <Show when={showShortcutsHelp()}>1784        <ShortcutsHelpOverlay1785          bindings={shortcutBindings()}1786          onClose={() => setShowShortcutsHelp(false)}1787        />1788      </Show>1789    </div>1790  );1791}17921793function ShortcutsHelpOverlay(props: {1794  bindings: Record<ShortcutAction, Keybinding>;1795  onClose: () => void;1796}) {1797  return (1798    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1799      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1800        <div class="peach-shortcuts-help-head">1801          <h3>Keyboard shortcuts</h3>1802          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1803        </div>1804        <div class="peach-shortcuts-help-body">1805          <p class="peach-settings-sub-label">ENTRY VIEW</p>1806          <ul>1807            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1808              <li>1809                <span>{d.label}</span>1810                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1811              </li>1812            ))}1813          </ul>1814          <p class="peach-settings-sub-label">ANYWHERE</p>1815          <ul>1816            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1817              <li>1818                <span>{d.label}</span>1819                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1820              </li>1821            ))}1822          </ul>1823        </div>1824      </div>1825    </div>1826  );1827}