App.tsx

75.4 KB · raw

1import { createEffect, createMemo, createSignal, For, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageSet } from "../shared/storage";4import { sendMessage } from "../shared/bridge";5import { ACCENT_COLORS } from "../shared/types";6import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";7import { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { NotesMode } from "./views/NotesMode";11import { ProCelebration } from "./views/ProCelebration";12import { VaultView, type SortOrder } from "./views/Vault";13import { EntryView } from "./views/Entry";14import { AddView } from "./views/Add";15import { PeachWordmark } from "./components/PeachMark";16import { PasskeyApprovalView } from "./views/PasskeyApproval";17import { extractDomain } from "../shared/domain";18import { 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 ChirpSyncView   = lazy(() => import("./views/ChirpSync").then(m => ({ default: m.ChirpSyncView })));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  | "chirp-sync"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 "Chirp"/"Code" buttons open the sync view, deep-link201  // straight into that pairing path instead of the rest screen.202  const [syncPairIntent, setSyncPairIntent] = createSignal<"chirp" | "desktop" | 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      // mDNS peer-discovery trigger. Register onCleanup synchronously so585      // SolidJS captures it within the reactive owner — onCleanup inside a586      // .then() callback may miss the capture window and leak the listener.587      let stopMDNS: () => void = () => undefined;588      onCleanup(() => stopMDNS());589      if (isNativePlatform()) {590        // Android runs the background/sync dispatcher in-process with the591        // popup, so the production runner has to be registered from the592        // UI bootstrap path instead of the MV3 service-worker entry.593        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>594          import("../background/chirp-sync-runner").then(({ productionSyncRunner }) => {595            setSyncRunner(productionSyncRunner);596            void hydratePersistedSyncState();597          })598        );599      }600      void import("./chirp-pair-capacitor").then(({ startMDNSListener }) => {601        stopMDNS = startMDNSListener();602      });603    }604605    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale606    // entries instead of waiting for the next GET_ENTRIES round-trip.607    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {608      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();609      if (msg?.type === "PRO_GATE_TRIGGERED") {610        setUpgradeHighlight(msg.payload?.feature ?? null);611        setSettingsInitialSection("license");612        setView("settings");613      }614    };615    chrome.runtime.onMessage.addListener(handleRuntimeMessage);616    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));617618    // Android hardware/gesture back. MainActivity fires peach:back; the popup619    // decides what "back" means per surface. Lock+no-vault is the common case620    // — return to onboarding rather than letting the OS dismiss the activity.621    const handlePeachBack = () => {622      // Notes mode captures back first623      if (showNotes()) {624        setShowNotes(false);625        setOpenNoteId(undefined);626        return;627      }628      const v = view();629      if (v === "lock" && !hasVault() && onboarded()) {630        setOnboarded(false);631        return;632      }633      if (v === "list") { setView("entry"); return; }634      if (v === "settings") {635        window.dispatchEvent(new Event("peach:settings-back"));636        return;637      }638      if (v === "import" || v === "health") { setView("settings"); return; }639      if (v === "export") { handleExportBack(); return; }640      if (v === "add") { handleBack(); return; }641      if (v === "chirp-sync") { setView("settings"); return; }642    };643    window.addEventListener("peach:back", handlePeachBack);644    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));645646    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that647    // peeks from the bottom (search bar handle visible) and drags up to fill648    // the screen. dragOffset is the LIVE finger offset during a drag, in px,649    // 0 when no drag in progress. The wrapper element computes transform =650    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.651    if (isNativePlatform()) {652      let touchStartY = 0;653      let touchStartX = 0;654      let lastY = 0;655      let lastT = 0;656      let dragging = false;657      let captured = false;658      const HORIZONTAL_TOLERANCE = 16;659      const ACTIVATION_DY = 8;660      const PEEK_PX = 60;661662      const onTouchStart = (e: TouchEvent) => {663        const t = e.touches[0];664        if (!t) return;665        const v = view();666        if (v !== "entry" && v !== "list") return;667        // Entry view: only intercept drags starting in the bottom 40%.668        // List view: intercept drags starting in the top 35% (the search/handle row).669        const inBand = v === "entry"670          ? t.clientY > window.innerHeight * 0.6671          : t.clientY < window.innerHeight * 0.35;672        if (!inBand) return;673        touchStartY = lastY = t.clientY;674        touchStartX = t.clientX;675        lastT = e.timeStamp;676        dragging = true;677        captured = false;678      };679680      const onTouchMove = (e: TouchEvent) => {681        if (!dragging) return;682        const t = e.touches[0];683        if (!t) return;684        const dy = t.clientY - touchStartY;685        const dx = Math.abs(t.clientX - touchStartX);686687        if (!captured) {688          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {689            // Looks like a horizontal swipe — release.690            dragging = false;691            return;692          }693          if (Math.abs(dy) < ACTIVATION_DY) return;694          captured = true;695        }696697        // Translate the sheet by dy from its rest (peek) position. Peek is698        // (viewport height - PEEK_PX). Open is 0.699        const v = view();700        const restClosed = window.innerHeight - PEEK_PX;701        const baseTranslate = v === "list" ? 0 : restClosed;702        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));703        setSheetTranslate(next);704        lastY = t.clientY;705        lastT = e.timeStamp;706      };707708      const onTouchEnd = (e: TouchEvent) => {709        if (!dragging) { return; }710        const t = e.changedTouches[0];711        const elapsed = Math.max(1, e.timeStamp - lastT);712        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms713        const wasCaptured = captured;714        dragging = false;715        captured = false;716        const v = view();717718        if (!wasCaptured) {719          // Tap in the peek strip while in entry view → open the vault list.720          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");721          setSheetTranslate(null);722          return;723        }724725        const restClosed = window.innerHeight - PEEK_PX;726        const current = sheetTranslate() ?? restClosed;727728        // Snap rules:729        //   - Strong upward velocity → open730        //   - Strong downward velocity → close731        //   - Otherwise snap to whichever rest is closer732        let nextOpen: boolean;733        if (velocity < -0.05) nextOpen = true;734        else if (velocity > 0.05) nextOpen = false;735        else nextOpen = current < restClosed * 0.5;736737        if (nextOpen && v !== "list") setView("list");738        if (!nextOpen && v !== "entry") setView("entry");739        // Release the live offset so CSS transition handles the snap.740        setSheetTranslate(null);741      };742743      document.addEventListener("touchstart", onTouchStart, { passive: true });744      document.addEventListener("touchmove",  onTouchMove,  { passive: true });745      document.addEventListener("touchend",   onTouchEnd,   { passive: true });746      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });747      onCleanup(() => {748        document.removeEventListener("touchstart", onTouchStart);749        document.removeEventListener("touchmove",  onTouchMove);750        document.removeEventListener("touchend",   onTouchEnd);751      });752    }753754    // Action handlers — keyed by ShortcutAction. The dispatcher below tests755    // each binding against the event and runs the matching handler. New756    // shortcuts only need an entry here; the binding is data, not code.757    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {758      copy_password: () => {759        const entry = selectedEntry();760        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });761      },762      copy_username: () => {763        const entry = selectedEntry();764        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });765      },766      copy_totp: () => {767        const entry = selectedEntry();768        if (!entry?.totp) return;769        try {770          const { code } = generateTOTP(entry.totp);771          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });772        } catch { /* invalid TOTP secret — silent */ }773      },774      new_entry: () => handleAdd(),775      edit_entry: () => {776        const entry = selectedEntry();777        // Passkey-only entries have nothing user-editable in the Add view; the778        // passkey credential itself is opaque. Skip the edit action for them.779        if (!entry || isPasskeyOnly(entry)) return;780        setEditEntry(entry);781        setView("add");782      },783      delete_entry: () => {784        if (selectedEntry()) void handleDelete();785      },786      lock_vault: () => { void handleHeaderLock(); },787      search: () => openList(),788      nav_prev: () => navigate(-1),789      nav_next: () => navigate(1),790      jump_vault: () => setView("entry"),791      jump_settings: () => setView("settings"),792      show_help: () => setShowShortcutsHelp(true),793    };794795    // Actions that are MEANINGFUL only on the entry-detail view. Outside796    // that scope the binding is dormant — pressing C while on Settings797    // does nothing rather than awkwardly copying from a now-stale entry.798    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([799      "copy_password", "copy_username", "copy_totp",800      "edit_entry", "delete_entry", "nav_prev", "nav_next",801    ]);802803    const handleGlobalKeydown = (e: KeyboardEvent) => {804      const v = view();805      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"806        || (e.target as HTMLElement)?.tagName === "TEXTAREA"807        || (e.target as HTMLElement)?.isContentEditable;808      const isPrintableSearchKey =809        e.key.length === 1 &&810        !e.ctrlKey &&811        !e.metaKey &&812        !e.altKey;813814      // No input during the pro celebration sequence815      if (v === "pro-celebration") return;816817      // Help dialog: Escape closes it; eat the keypress so it doesn't818      // also navigate away from the underlying view.819      if (showShortcutsHelp()) {820        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }821        return;822      }823824      // ── Escape — fixed binding (not user-customizable) ───────825      if (e.key === "Escape") {826        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }827        if (v === "list") { setView("entry"); return; }828        if (v === "settings" || v === "add") { handleBack(); return; }829        if (v === "import" || v === "health") { setView("settings"); return; }830        if (v === "export") { handleExportBack(); return; }831        if (v === "chirp-sync") { setView("settings"); return; }832      }833834      // Bindings-driven dispatch. Single-key letter bindings without835      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is836      // inside an input, so users can type into search/forms normally.837      const bindings = shortcutBindings();838      for (const action of Object.keys(bindings) as ShortcutAction[]) {839        const binding = bindings[action];840        if (!matchKeybinding(e, binding)) continue;841        // Single-key letter bindings need the input-focus guard. Bindings842        // with any modifier are safe — Ctrl+L doesn't conflict with typing.843        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;844        if (!hasMod && binding.key.length === 1 && inInput) return;845        if (ENTRY_SCOPED.has(action) && v !== "entry") return;846        e.preventDefault();847        SHORTCUT_HANDLERS[action]?.();848        return;849      }850851      // Type-to-search: in entry view, any printable key not consumed by a852      // shortcut above primes the list search seed and opens the list.853      // Kept outside the bindings table because it's a behavior, not a854      // discrete action — every printable character can trigger it.855      if (v === "entry" && !inInput && isPrintableSearchKey) {856        e.preventDefault();857        primeListSearch(e.key);858        return;859      }860    };861    window.addEventListener("keydown", handleGlobalKeydown);862    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));863864    const handleStorageChanged = (865      changes: Record<string, chrome.storage.StorageChange>,866      areaName: string867    ) => {868      if (areaName !== "session") return;869      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {870        return;871      }872      void refreshPendingPasskey();873    };874    chrome.storage.onChanged.addListener(handleStorageChanged);875    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));876  });877878  async function refreshCurrentTab() {879    try {880      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });881      const url = tab?.url ?? tab?.pendingUrl ?? "";882      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");883      // Skip extension/internal URLs — adding chrome://, about:, or884      // chrome-extension:// to a vault entry is never what the user wants.885      const isWebUrl = /^https?:\/\//i.test(url);886      setCurrentTabUrl(isWebUrl ? url : "");887    } catch {888      setCurrentTabDomain("");889      setCurrentTabUrl("");890    }891  }892893  async function refreshPendingPasskey() {894    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });895    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);896  }897898  async function refreshProStatus() {899    const res = await sendMessage({ type: "GET_LICENSE" });900    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;901    setProStatus(Boolean(data?.valid && data?.plan === "pro"));902  }903904  async function restoreSettings() {905    const res = await sendMessage({ type: "GET_SETTINGS" });906    const s = (res as { ok: boolean; data?: any }).data ?? {};907    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {908      setAccentColor(s.accentColor as AccentColorName);909    }910    setTheme(s.theme === "light" ? "light" : "dark");911    if (s.textSize === "small" || s.textSize === "large") {912      setTextSize(s.textSize);913    } else {914      setTextSize("medium");915    }916    setReduceMotion(s.reduceMotion === true);917    setLockOnClose(s.lockOnClose !== false);918    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);919    setBreachMonitoring(s.breachMonitoring !== false);920    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);921    setShortcutBindings(getActiveBindings(s.shortcuts));922  }923924  async function applyTrashRetention(days: number) {925    setTrashRetentionDays(days);926    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });927  }928929  function primeListSearch(seed: string) {930    setListSearchSeed(seed);931    setListSearchSeedNonce((value) => value + 1);932    openList();933  }934935  // Returns null when it detected a dead service worker and triggered handleLock().936  // Callers that need to abort (e.g. openVault) check for null rather than relying937  // on view() state, which may already be "lock" during normal startup flows.938  async function loadEntries(): Promise<VaultEntry[] | null> {939    const response = await sendMessage({ type: "GET_ENTRIES" });940    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };941942    // If the service worker was killed and restarted (MV3 workers sleep), the943    // vault will be locked again — or the worker may not respond at all.944    // In either case, send the user to the lock screen rather than silently945    // showing an empty vault (which looks like data loss).946    if (!res.ok) {947      if (948        res.error === "vault_locked" ||949        res.error === "SERVICE_WORKER_UNAVAILABLE" ||950        (typeof res.error === "string" && res.error.includes("locked"))951      ) {952        handleLock();953        return null; // signal emergency lock to callers954      }955      return [];956    }957958    const loadedEntries = res.data ?? [];959    setEntries(loadedEntries);960961    const currentId = selectedEntry()?.id;962    if (currentId) {963      setSelectedEntry(964        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null965      );966    }967968    return loadedEntries;969  }970971  async function openVault(preferredEntryId?: string, skipViewSet = false) {972    // Purge expired trash entries on each vault open973    const retDays = trashRetentionDays();974    if (retDays > 0) {975      void sendMessage({976        type: "PURGE_EXPIRED_TRASH",977        payload: { retentionMs: retDays * 86_400_000 },978      });979    }980981    const loadedEntries = await loadEntries();982983    // null means loadEntries() triggered an emergency lock (service worker died).984    // Don't override it by setting view back to "entry" with an empty vault.985    if (loadedEntries === null) return;986987    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry988    let nextSelectedEntry: VaultEntry | null = null;989    if (preferredEntryId) {990      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;991    }992    if (!nextSelectedEntry) {993      const tabDomain = currentTabDomain();994      if (tabDomain) {995        nextSelectedEntry = loadedEntries.find((e) => {996          if (e.type === "login") {997            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;998            for (const extra of e.additionalUrls ?? []) {999              if ((extractDomain(extra) ?? "") === tabDomain) return true;1000            }1001            return false;1002          }1003          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1004          return false;1005        }) ?? null;1006      }1007    }1008    nextSelectedEntry ??= loadedEntries[0] ?? null;10091010    setSelectedEntry(nextSelectedEntry);1011    setEditEntry(undefined);1012    setContentTransitioning(false);1013    setContentPhase("enter");1014    queueContentIdle();1015    if (!skipViewSet) setView("entry");1016  }10171018  async function handleUnlock() {1019    // If the user previously created a vault but hadn't yet confirmed their1020    // recovery words (and the browser was closed before they could), the1021    // peach_recovery_pending flag is still set in storage.local. Re-route1022    // back to the recovery surface so they finish the confirmation step1023    // before reaching the entries view — the words can be re-derived now1024    // that the vault is unlocked again.1025    let recoveryPending = false;1026    try {1027      const out = await chrome.storage.local?.get("peach_recovery_pending");1028      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1029    } catch { /* best-effort */ }1030    if (recoveryPending) {1031      setForceRecoveryWords(true);1032      setView("lock");1033      triggerPipPulse();1034      await restoreSettings();1035      return;1036    }1037    setHasVault(true);1038    triggerPipPulse();1039    await restoreSettings();1040    const celebrating = pendingCelebration();1041    if (celebrating) {1042      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1043      setPendingCelebration(false);1044    }1045    await openVault(undefined, celebrating);1046    if (celebrating) {1047      setView("pro-celebration");1048      window.setTimeout(() => setView("entry"), 2500);1049    }1050    // Popup was opened from the inline "Open Peach to unlock" button — close it1051    // now so the user lands back on the page with the autofill selector ready.1052    if (openedForInlineUnlock) {1053      openedForInlineUnlock = false;1054      window.close();1055    }1056  }10571058  function handleSelectEntry(entry: VaultEntry) {1059    if (entry.type === "note") {1060      setOpenNoteId(entry.id);1061      setShowNotes(true);1062      return;1063    }1064    setSelectedEntry(entry);1065    setContentTransitioning(false);1066    setContentPhase("enter");1067    queueContentIdle();1068    setView("entry");1069  }10701071  function handleAdd() {1072    setEditEntry(undefined);1073    setView("add");1074  }10751076  async function handleDelete() {1077    const entry = selectedEntry();1078    if (!entry) return;1079    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1080    const loadedEntries = await loadEntries() ?? [];1081    setSelectedEntry(loadedEntries[0] ?? null);1082    setView("entry");1083  }10841085  async function handleDeleteMany(ids: string[]) {1086    for (const id of ids) {1087      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1088    }1089    const loadedEntries = await loadEntries() ?? [];1090    // If the currently selected entry was among the deleted, move to first1091    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1092    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1093  }10941095  async function handleSave(savedEntry?: VaultEntry) {1096    await openVault(savedEntry?.id);1097  }10981099  function handleBack() {1100    const dest = editBackView();1101    setEditBackView("entry");1102    setEditEntry(undefined);1103    setView(dest);1104  }11051106  function handleExportBack() {1107    if (returnToPanic()) {1108      setReturnToPanic(false);1109      setView("panic");1110      return;1111    }1112    setView("settings");1113  }11141115  function handleLock() {1116    clearCanarySuppressions();1117    setEntries([]);1118    setSelectedEntry(null);1119    setEditEntry(undefined);1120    setContentPhase("idle");1121    setView("lock");1122  }11231124  function handleHeaderLock() {1125    // Lock the UI immediately — do not wait for the service worker. If the SW1126    // is dead or slow, the 5s sendMessage timeout would create a dead-click1127    // window. The SW will lock on its next wake regardless.1128    handleLock();1129    void sendMessage({ type: "LOCK" });1130  }11311132  function navigate(dir: number) {1133    const allEntries = entries();1134    if (allEntries.length === 0) return;1135    const currentIndex = selectedIndex();1136    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1137    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1138    setSelectedEntry(allEntries[nextIndex]);1139    setContentPhase("enter");1140    queueContentIdle();1141  }11421143  function openList() {1144    setView("list");1145  }11461147  function openHealth() {1148    setEditEntry(undefined);1149    setView("health");1150  }11511152  function handleOpenFileImport() {1153    setRestoreView("file");1154  }11551156  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11571158  function handleFixEntry(entry: VaultEntry) {1159    setSelectedEntry(entry);1160    // Passkey-only entries have no editable surface — drop into view mode1161    // instead of opening the Add editor.1162    if (isPasskeyOnly(entry)) {1163      setView("entry");1164      return;1165    }1166    setEditBackView(view()); // preserve caller view so back returns here1167    setEditEntry(entry);1168    setView("add");1169  }11701171  const isLockedView = () => view() === "lock" || view() === "adopting";11721173  async function handleAdoptionDone() {1174    await storageSet("peach_onboarded", "true").catch(() => {});1175    setOnboarded(true);1176    setHasVault(true);1177    await handleUnlock();1178    void sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "foreground" } });1179  }11801181  /**1182   * Join an existing vault from a brand-new install.1183   *1184   * This used to require the receiver to LISTEN for the other device (a1185   * Capacitor pairing server), which a browser extension structurally cannot1186   * do — so on every real browser build it threw before doing anything. Over a1187   * pairing code the receiver is the DIALLER instead, which is the only shape1188   * that works here: dial the code, confirm the SAS, then ask for the vault.1189   *1190   * The vault does not exist yet at dial time, so nothing in this path may1191   * touch the vault before `createVaultFromRootKey` runs.1192   */1193  async function startVaultAdoption(args: {1194    password: string;1195    code: string;1196    confirmSAS(sas: string): Promise<boolean>;1197    createVault(rootKeyHex: string): Promise<{ vaultId: string }>;1198  }) {1199    const [{ dialPairingChannel, openPairingSocket }, { requestAdoption }] = await Promise.all([1200      import("../shared/pairing-dial"),1201      import("../shared/chirp-adopt"),1202    ]);12031204    // No `findHost`: adoption only accepts a pairing code, which carries its1205    // own address. There is nothing to probe the LAN for.1206    const dial = await dialPairingChannel(args.code, { openSocket: openPairingSocket });1207    if (!dial.ok) throw new Error(dial.error);1208    const { channel, sas, socket } = dial.dialled;12091210    try {1211      // Same out-of-band gate as device pairing, and for the same reason: the1212      // token proves nothing, the user comparing this code does. Ask BEFORE1213      // requesting the vault's root key.1214      if (!(await args.confirmSAS(sas))) throw new Error("sas_rejected");12151216      const source = await requestAdoption(channel, {1217        deviceName: defaultAdoptionDeviceName(),1218        generateDeviceId: () => crypto.randomUUID(),1219        createVaultFromRootKey: args.createVault,1220        deriveLocalIdentity: async () => {1221          const res = await sendMessage({ type: "CHIRP_GET_LOCAL_IDENTITY" });1222          const r = res as { ok: boolean; data?: unknown; error?: string };1223          if (!r.ok || !r.data) throw new Error(r.error ?? "identity_unavailable");1224          return r.data as Awaited<ReturnType<Parameters<typeof requestAdoption>[1]["deriveLocalIdentity"]>>;1225        },1226        upsertPairedDevice: async (paired) => {1227          const res = await sendMessage({ type: "CHIRP_COMPLETE_PAIRING", payload: { paired } });1228          const r = res as { ok: boolean; error?: string };1229          if (!r.ok) throw new Error(r.error ?? "complete_pairing_failed");1230        },1231        applyLicense: async (license) => {1232          const res = (await sendMessage({1233            type: "ACTIVATE_LICENSE",1234            payload: { key: license },1235          })) as { ok: boolean; data?: { valid?: boolean; plan?: string } };1236          if (res.ok && res.data?.valid && res.data?.plan === "pro") await refreshProStatus();1237        },1238        onError(error) {1239          throw new Error(error);1240        },1241      });1242      if (!source) throw new Error("adoption_rejected");1243      // No last-known-IP cache write here: the first sync round falls back to1244      // the subnet probe and persists the address itself once it lands, so a1245      // popup→background message just to save that one scan isn't worth it.1246    } finally {1247      socket.close();1248    }1249  }12501251  async function handleApprovePendingPasskey() {1252    const pending = pendingPasskey();1253    if (!pending) return;1254    if (pending.browser === "firefox" && pending.type === "create") {1255      // Firefox path: popup itself runs navigator.credentials.create. The1256      // background never approved/rejected anything — it just stashed1257      // intent. After the popup-driven flow resolves (success or cancel),1258      // clear the pending key so the popup doesn't re-show this on next open.1259      const { createFirefoxPasskey } = await import("./firefox-passkey");1260      const result = await createFirefoxPasskey(pending);1261      if (!result.ok) {1262        console.warn("Peach Firefox passkey create failed:", result.error);1263      }1264      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1265      setPendingPasskey(null);1266      void loadEntries();1267      window.close();1268      return;1269    }1270    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1271    window.close();1272  }12731274  async function handleDenyPendingPasskey() {1275    const pending = pendingPasskey();1276    if (!pending) return;1277    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1278    window.close();1279  }12801281  function queueContentIdle(after?: () => void) {1282    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1283    contentPhaseTimer = window.setTimeout(() => {1284      setContentPhase("idle");1285      after?.();1286    }, ENTRY_TRANSITION_SETTLE_MS);1287  }12881289  return (1290    <div class="popup-root peach-theme">1291      <Show when={bootState() === "ready"}>1292        <Show1293          when={!pendingPasskey()}1294          fallback={1295            <PasskeyApprovalView1296              type={pendingPasskey()!.type}1297              rpName={pendingPasskey()!.rpName}1298              rpId={pendingPasskey()!.rpId}1299              userName={pendingPasskey()!.userName}1300              userDisplayName={pendingPasskey()!.userDisplayName}1301              onApprove={handleApprovePendingPasskey}1302              onDeny={handleDenyPendingPasskey}1303            />1304          }1305        >1306          <Show1307            when={!isLockedView()}1308            fallback={1309              <Show1310                when={view() !== "adopting"}1311                fallback={1312                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1313                    <AdoptVaultView1314                      onCancel={() => {1315                        setOnboarded(false);1316                        setView("lock");1317                      }}1318                      onDone={handleAdoptionDone}1319                      startAdoption={startVaultAdoption}1320                    />1321                  </Suspense>1322                }1323              >1324                <Show1325                  when={onboarded() || hasVault()}1326                  fallback={1327                    <Onboarding1328                      onComplete={() => { setOnboarded(true); }}1329                      onRestore={() => { setOnboarded(true); }}1330                      onAdopt={() => {1331                        setOnboarded(true);1332                        setView("adopting");1333                      }}1334                    />1335                  }1336                >1337                  <LockView1338                    hasVault={hasVault()}1339                    ready={bootState() === "ready"}1340                    isPro={proStatus()}1341                    forceRecoveryWords={forceRecoveryWords()}1342                    onUnlock={() => {1343                      // RecoveryWordDisplay clears the storage flag before1344                      // calling onDone, so handleUnlock will see no pending1345                      // confirmation and proceed through the normal path.1346                      if (forceRecoveryWords()) setForceRecoveryWords(false);1347                      return handleUnlock();1348                    }}1349                    onBackToOnboarding={1350                      !hasVault()1351                        ? () => setOnboarded(false)1352                        : undefined1353                    }1354                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1355                  />1356                </Show>1357              </Show>1358            }1359          >1360            <Show1361              when={view() !== "pro-celebration"}1362              fallback={<ProCelebration />}1363            >1364            <section1365              id="hd-shell"1366              class="peach-shell peach-theme"1367              data-surface="extension"1368            >1369            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1370              <PeachWordmark unlocked />1371              <div class="peach-chrome-actions">1372                <button1373                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1374                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1375                  aria-label="Notes"1376                  title="Notes"1377                >1378                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1379                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1380                    <line x1="4" y1="5" x2="10" y2="5" />1381                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1382                    <line x1="4" y1="10" x2="7" y2="10" />1383                  </svg>1384                </button>1385                <button1386                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1387                  onClick={() => setView("settings")}1388                  aria-label="Settings"1389                >1390                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1391                    <path1392                      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"1393                      stroke="currentColor"1394                      stroke-width="0.9"1395                    />1396                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1397                  </svg>1398                </button>1399                <button1400                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1401                  onClick={handleAdd}1402                  aria-label="New entry"1403                >1404                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1405                    <path d="M5.5 1v9M1 5.5h9" />1406                  </svg>1407                </button>1408                <button1409                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1410                  onClick={() => void handleHeaderLock()}1411                  aria-label="Lock vault"1412                >1413                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1414                    <path1415                      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"1416                      stroke="currentColor"1417                      stroke-width="1"1418                      stroke-linecap="round"1419                    />1420                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1421                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1422                  </svg>1423                </button>1424              </div>1425            </header>14261427            <Show when={pendingProNotice() !== null}>1428              <div class="peach-pro-notice-banner">1429                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1430                <button1431                  class="peach-pro-notice-link"1432                  onClick={() => {1433                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1434                    setSettingsInitialSection("license");1435                    setView("settings");1436                    setPendingProNotice(null);1437                  }}1438                >1439                  Learn more →1440                </button>1441                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1442              </div>1443            </Show>14441445            <div class="peach-shell-body">1446              <div class="peach-shell-veil"></div>1447              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1448                <EntryView1449                  entry={selectedEntry()}1450                  currentTabUrl={currentTabUrl()}1451                  entries={entries()}1452                  isPro={proStatus()}1453                  onDelete={handleDelete}1454                  onFieldSaved={() => void loadEntries()}1455                  onEscape={() => { setView("list"); }}1456                  onProGate={(feature) => {1457                    setUpgradeHighlight(feature);1458                    setSettingsInitialSection("license");1459                    setView("settings");1460                  }}1461                />1462              </div>14631464              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1465                <div class="peach-search-bar">1466                  <span class="peach-search-icon">1467                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1468                      <circle cx="5.5" cy="5.5" r="3.75" />1469                      <path d="M8.75 8.75L11.5 11.5" />1470                    </svg>1471                  </span>1472                  <input1473                    class="peach-search-input"1474                    placeholder="search vault..."1475                    autocomplete="off"1476                    aria-label="Search vault entries"1477                    onClick={openList}1478                    onFocus={openList}1479                    readOnly1480                  />1481                  <div class="peach-search-meta">1482                    <span class="peach-search-counter">1483                      {entries().length > 01484                        ? `${selectedIndex() + 1} / ${entries().length}`1485                        : "0 entries"}1486                    </span>1487                    <span class="peach-divider"></span>1488                    <button1489                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1490                      onClick={() => navigate(-1)}1491                      aria-label="Previous entry"1492                      disabled={entries().length === 0}1493                    >1494                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1495                        <path d="M5 1L1 5.5L5 10" />1496                      </svg>1497                    </button>1498                    <button1499                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1500                      onClick={() => navigate(1)}1501                      aria-label="Next entry"1502                      disabled={entries().length === 0}1503                    >1504                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1505                        <path d="M1 1L5 5.5L1 10" />1506                      </svg>1507                    </button>1508                  </div>1509                </div>1510              </section>1511            </div>15121513            {/* Desktop: shown on demand via Show. Native sheet is rendered1514                via Portal below at the document root so its position:fixed1515                isn't trapped by .peach-shell's transform-based animations. */}1516            {/* UI-1 / HV-1b: dismissible remote-mutation alert banners. */}1517            <Show when={syncAlerts().length > 0}>1518              <div class="peach-sync-alerts">1519                <For each={syncAlerts()}>1520                  {(alert, i) => (1521                    <div class="peach-sync-alert">1522                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1523                      <button1524                        class="peach-sync-alert-dismiss"1525                        type="button"1526                        aria-label="Dismiss"1527                        onClick={() => dismissSyncAlert(i())}1528                      >×</button>1529                    </div>1530                  )}1531                </For>1532              </div>1533            </Show>15341535            <Show when={!isNativePlatform() && view() === "list"}>1536              <VaultView1537                entries={entries()}1538                selectedEntryId={selectedEntry()?.id}1539                currentTabDomain={currentTabDomain()}1540                sortOrder={sortOrder()}1541                searchSeed={listSearchSeed()}1542                searchSeedNonce={listSearchSeedNonce()}1543                onSelectEntry={handleSelectEntry}1544                onSortOrderChange={setSortOrder}1545                onAdd={handleAdd}1546                onClose={() => setView("entry")}1547                onOpenTrash={() => setView("trash")}1548                onDeleteMany={handleDeleteMany}1549              />1550            </Show>1551            <Show when={isNativePlatform() && hasVault()}>1552              <Portal>1553                <div1554                  class="peach-vault-sheet"1555                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1556                  style={(() => {1557                    const live = sheetTranslate();1558                    if (live === null) return undefined;1559                    return { transform: `translateY(${live}px)` };1560                  })()}1561                >1562                  <VaultView1563                    entries={entries()}1564                    selectedEntryId={selectedEntry()?.id}1565                    currentTabDomain={currentTabDomain()}1566                    sortOrder={sortOrder()}1567                    searchSeed={listSearchSeed()}1568                    searchSeedNonce={listSearchSeedNonce()}1569                    isNative={true}1570                    onSelectEntry={handleSelectEntry}1571                    onSortOrderChange={setSortOrder}1572                    onAdd={handleAdd}1573                    onClose={() => setView("entry")}1574                    onOpenTrash={() => setView("trash")}1575                    onDeleteMany={handleDeleteMany}1576                  />1577                </div>1578              </Portal>1579            </Show>1580            <Show when={view() === "settings" || settingsExiting()}>1581              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1582                <SettingsView1583                  entriesCount={entries().length}1584                  breachMonitoring={breachMonitoring()}1585                  lockOnClose={lockOnClose()}1586                  autoLockMinutes={autoLockMinutes()}1587                  trashRetentionDays={trashRetentionDays()}1588                  theme={theme()}1589                  accentColor={accentColor()}1590                  textSize={textSize()}1591                  reduceMotion={reduceMotion()}1592                  isPro={proStatus()}1593                  initialSection={settingsInitialSection()}1594                  upgradeHighlight={upgradeHighlight()}1595                  isExiting={settingsExiting()}1596                  onBreachMonitoringChange={applyBreachMonitoring}1597                  onLockOnCloseChange={applyLockOnClose}1598                  onAutoLockMinutesChange={applyAutoLockMinutes}1599                  onTrashRetentionChange={applyTrashRetention}1600                  onThemeChange={applyTheme}1601                  onAccentChange={applyAccentColor}1602                  onTextSizeChange={applyTextSize}1603                  onReduceMotionChange={applyReduceMotion}1604                  shortcuts={shortcutBindings()}1605                  onShortcutsChange={applyShortcuts}1606                  onLicenseChange={async () => {1607                    // After activation/deactivation: refresh Pro status,1608                    // re-load entries (defensive — signal state can drift if1609                    // the SW briefly restarts during the verify+save round-trip),1610                    // and replay the Pro celebration if this is the first time1611                    // a valid Pro license is seen on this device.1612                    await refreshProStatus();1613                    void loadEntries();1614                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1615                    if ((should as { ok: boolean; data?: boolean }).data === true) {1616                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1617                      setView("pro-celebration");1618                      window.setTimeout(() => setView("settings"), 2500);1619                    }1620                  }}1621                  onBack={() => {1622                    setSettingsExiting(true);1623                    window.setTimeout(() => {1624                      setSettingsExiting(false);1625                      setSettingsInitialSection(null);1626                      setUpgradeHighlight(null);1627                      handleBack();1628                    }, 200);1629                  }}1630                  onImport={() => setView("import")}1631                  onExport={() => setView("export")}1632                  onBreachCheckDone={loadEntries}1633                  onOpenHealth={openHealth}1634                  onOpenSyncPairing={(method) => { setSettingsInitialSection(settingsActiveCard()); setSyncPairIntent(method ?? null); setView("chirp-sync"); }}1635                  onOpenFileImport={handleOpenFileImport}1636                  onOpenPanic={() => setView("panic")}1637                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1638                  onOpenCodexRestore={() => setView("codex-restore")}1639                  onCardChange={setSettingsActiveCard}1640                  onProGate={(feature) => {1641                    setUpgradeHighlight(feature);1642                    setSettingsInitialSection("license");1643                  }}1644                />1645              </Suspense>1646            </Show>1647            <Show when={view() === "codex-generate"}>1648              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1649                <CodexGenerateView1650                  isPro={proStatus()}1651                  onBack={() => setView("settings")}1652                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1653                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1654                  onVaultLocked={() => handleLock()}1655                />1656              </Suspense>1657            </Show>1658            <Show when={view() === "codex-restore"}>1659              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1660                <CodexRestoreView1661                  onBack={() => setView("lock")}1662                  onRestoreSuccess={async () => {1663                    // After restore the vault is unlocked; refresh entries1664                    // and route to the main vault list. handleUnlock is the1665                    // canonical post-unlock setup path.1666                    await handleUnlock();1667                  }}1668                />1669              </Suspense>1670            </Show>1671            <Show when={view() === "chirp-sync"}>1672              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1673                <ChirpSyncView1674                  isPro={proStatus()}1675                  initialPair={syncPairIntent()}1676                  onProChanged={() => { void refreshProStatus(); }}1677                  onBack={() => { setSyncPairIntent(null); setView("settings"); }}1678                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1679                />1680              </Suspense>1681            </Show>1682            <Show when={view() === "add"}>1683              <AddView1684                entry={editEntry()}1685                entries={entries()}1686                onBack={handleBack}1687                onSave={handleSave}1688              />1689            </Show>1690            <Show when={view() === "import"}>1691              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1692                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1693              </Suspense>1694            </Show>1695            <Show when={view() === "export"}>1696              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1697                <ExportView onBack={handleExportBack} />1698              </Suspense>1699            </Show>1700            <Show when={view() === "panic"}>1701              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1702                <PanicView1703                  onCancel={() => setView("settings")}1704                  onOpenExport={() => {1705                    setReturnToPanic(true);1706                    setView("export");1707                  }}1708                  onDestroyed={async () => {1709                    clearCanarySuppressions();1710                    setEntries([]);1711                    setSelectedEntry(null);1712                    setEditEntry(undefined);1713                    setHasVault(false);1714                    setOnboarded(false);1715                    setProStatus(false);1716                    setPendingPasskey(null);1717                    setUpgradeHighlight(null);1718                    setSettingsInitialSection(null);1719                    setPendingProNotice(null);1720                    setPendingCelebration(false);1721                    setReturnToPanic(false);1722                    setContentPhase("idle");1723                    setView("lock");1724                  }}1725                />1726              </Suspense>1727            </Show>1728            {/* Health stays mounted while editing an entry from it so1729                computeReused() doesn't rerun on every cancel/back. */}1730            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1731              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1732                <HealthView1733                  entries={entries()}1734                  isPro={proStatus()}1735                  onFixEntry={handleFixEntry}1736                  onBack={() => setView("settings")}1737                  onRefresh={loadEntries}1738                  hidden={view() !== "health"}1739                />1740              </Suspense>1741            </Show>1742            <Show when={view() === "trash"}>1743              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1744                <TrashView1745                  onBack={() => setView("list")}1746                  onRestored={() => void loadEntries()}1747                />1748              </Suspense>1749            </Show>1750            <Show when={showNotes()}>1751              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1752                <NotesMode1753                  notes={entries().filter((e) => e.type === "note")}1754                  initialNoteId={openNoteId()}1755                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1756                  onNoteListChanged={() => void loadEntries()}1757                />1758              </div>1759            </Show>1760            <Show when={restoreView() === "file"}>1761              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1762                <ImportView1763                  mode="onboarding"1764                  replacesExistingVault={true}1765                  onBack={() => setRestoreView(null)}1766                  onImport={async () => {1767                    setRestoreView(null);1768                    await handleUnlock();1769                  }}1770                />1771              </Suspense>1772            </Show>1773            </section>1774            </Show>1775          </Show>1776        </Show>1777      </Show>1778      <Show when={showShortcutsHelp()}>1779        <ShortcutsHelpOverlay1780          bindings={shortcutBindings()}1781          onClose={() => setShowShortcutsHelp(false)}1782        />1783      </Show>1784    </div>1785  );1786}17871788function ShortcutsHelpOverlay(props: {1789  bindings: Record<ShortcutAction, Keybinding>;1790  onClose: () => void;1791}) {1792  return (1793    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1794      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1795        <div class="peach-shortcuts-help-head">1796          <h3>Keyboard shortcuts</h3>1797          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1798        </div>1799        <div class="peach-shortcuts-help-body">1800          <p class="peach-settings-sub-label">ENTRY VIEW</p>1801          <ul>1802            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1803              <li>1804                <span>{d.label}</span>1805                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1806              </li>1807            ))}1808          </ul>1809          <p class="peach-settings-sub-label">ANYWHERE</p>1810          <ul>1811            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1812              <li>1813                <span>{d.label}</span>1814                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1815              </li>1816            ))}1817          </ul>1818        </div>1819      </div>1820    </div>1821  );1822}