App.tsx

74.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}127128function adoptionDeviceType(): "extension" | "android" | "ios" {129  const cap = (globalThis as unknown as { Capacitor?: { getPlatform?: () => string } }).Capacitor;130  const platform = cap?.getPlatform?.();131  if (platform === "ios") return "ios";132  if (platform === "android") return "android";133  return "extension";134}135136const ENTRY_TRANSITION_SETTLE_MS = 135;137138export default function App() {139  const [bootState, setBootState] = createSignal<BootState>("loading");140  const [view, setView] = createSignal<View>("lock");141  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,142  // CSS transition takes over for snap animation).143  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);144  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(145    "enter"146  );147  const [contentTransitioning, setContentTransitioning] = createSignal(false);148  const [hasVault, setHasVault] = createSignal(false);149  const [onboarded, setOnboarded] = createSignal(true);150  const [entries, setEntries] = createSignal<VaultEntry[]>([]);151  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);152  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);153154  // UI-1 / HV-1b + MV-8d: remote-mutation alerts queued by the sync merge,155  // shown as dismissible banners on popup open.156  interface SyncAlert {157    type: "REMOTE_PASSWORD_CHANGE" | "REMOTE_DELETE" | "DEVICE_KEY_ROTATED";158    entryId: string;159    entryTitle: string;160    deviceName: string;161    timestamp: number;162  }163  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);164  async function loadSyncAlerts() {165    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {166      ok: boolean;167      data?: SyncAlert[];168    };169    if (r.ok && (r.data?.length ?? 0) > 0) {170      setSyncAlerts(r.data ?? []);171      // Acknowledge so a crash between read and render doesn't lose them —172      // they remain on screen until the user dismisses each.173      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });174    }175  }176  function dismissSyncAlert(index: number) {177    setSyncAlerts((arr) => arr.filter((_, i) => i !== index));178  }179  function syncAlertText(a: SyncAlert): string {180    if (a.type === "REMOTE_PASSWORD_CHANGE") {181      return `${a.deviceName} changed the password for ${a.entryTitle}`;182    }183    if (a.type === "REMOTE_DELETE") {184      return `${a.deviceName} deleted ${a.entryTitle}`;185    }186    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;187  }188  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");189  const [theme, setTheme] = createSignal<"dark" | "light">("dark");190  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");191  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);192  const [lockOnClose, setLockOnClose] = createSignal(true);193  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);194  const [breachMonitoring, setBreachMonitoring] = createSignal(true);195  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);196  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);197  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);198  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);199  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);200  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");201  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");202  // Cached Pro status — synchronous for render paths. Background's203  // GET_LICENSE is async, but render-time reads of isPro() must not block.204  // Refreshed at boot, after activate/deactivate, and whenever the popup205  // re-opens onto a stored license that has changed via another window.206  const [proStatus, setProStatus] = createSignal(false);207  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);208  // When the sync card's "Chirp"/"Code" buttons open the sync view, deep-link209  // straight into that pairing path instead of the rest screen.210  const [syncPairIntent, setSyncPairIntent] = createSignal<"chirp" | "desktop" | null>(null);211  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");212  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);213  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");214  const [listSearchSeed, setListSearchSeed] = createSignal("");215  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);216  const [pendingCelebration, setPendingCelebration] = createSignal(false);217  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);218  // True while Panic Step 1 has bounced the user out to Export. When Export's219  // onBack fires we return to Panic instead of Settings so the user keeps the220  // destruction context they came from.221  const [returnToPanic, setReturnToPanic] = createSignal(false);222  // The view to return to when the add/edit view is dismissed. Normally "entry"223  // but "health" when the user arrives via the fix-entry path from Vault Health.224  const [editBackView, setEditBackView] = createSignal<View>("entry");225  const [settingsExiting, setSettingsExiting] = createSignal(false);226  const [showNotes, setShowNotes] = createSignal(false);227  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);228  // Set on popup boot when peach_recovery_pending flag is found in session229  // storage — instructs LockView to skip the unlock UI and open the recovery230  // words confirmation surface instead. Cleared via handleUnlock once the231  // user has typed the 3 confirmation words.232  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);233234  let contentPhaseTimer: number | undefined;235  // Set when the popup was opened from the inline "Open Peach to unlock" button.236  // handleUnlock() closes the popup after unlock so the user returns to the page.237  let openedForInlineUnlock = false;238239  function applyAccent(name: AccentColorName) {240    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;241    const hex = color.hex;242    document.documentElement.style.setProperty("--peach-accent", hex);243    // Ambient surface variables — derived from the accent so surfaces shift244    // subtly toward the accent hue rather than staying fixed warm-brown.245    document.documentElement.style.setProperty("--peach-glow", hex + "2A");246    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");247    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");248  }249250  createEffect(() => {251    applyAccent(accentColor());252  });253254  createEffect(() => {255    document.documentElement.classList.toggle("light", theme() === "light");256    document.body.classList.toggle("light", theme() === "light");257  });258259  createEffect(() => {260    document.documentElement.setAttribute("data-text-size", textSize());261  });262263  createEffect(() => {264    if (reduceMotion()) {265      document.documentElement.setAttribute("data-motion", "reduce");266    } else {267      document.documentElement.removeAttribute("data-motion");268    }269  });270271  const selectedIndex = createMemo(() => {272    const currentId = selectedEntry()?.id;273    if (!currentId) return entries().length > 0 ? 0 : -1;274    return entries().findIndex((entry) => entry.id === currentId);275  });276277  async function applyAccentColor(name: AccentColorName) {278    applyAccent(name);279    setAccentColor(name);280    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });281  }282283  async function applyTheme(t: "dark" | "light") {284    setTheme(t);285    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });286  }287288  async function applyTextSize(size: "small" | "medium" | "large") {289    setTextSize(size);290    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });291  }292293  async function applyReduceMotion(enabled: boolean) {294    setReduceMotion(enabled);295    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });296  }297298  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload299  // small and lets future default updates land for actions the user hasn't300  // touched. Settings sends us the full active map; we filter and store.301  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {302    setShortcutBindings(active);303    const overrides: Record<string, Keybinding> = {};304    for (const action of Object.keys(active) as ShortcutAction[]) {305      const a = active[action];306      const d = DEFAULT_BINDINGS[action];307      const same = a.key === d.key308        && Boolean(a.ctrl)  === Boolean(d.ctrl)309        && Boolean(a.meta)  === Boolean(d.meta)310        && Boolean(a.shift) === Boolean(d.shift)311        && Boolean(a.alt)   === Boolean(d.alt);312      if (!same) overrides[action] = a;313    }314    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });315  }316317  async function applyLockOnClose(enabled: boolean) {318    setLockOnClose(enabled);319    await sendMessage({320      type: "UPDATE_SETTINGS",321      payload: { lockOnClose: enabled },322    });323  }324325  async function applyAutoLockMinutes(minutes: number) {326    setAutoLockMinutes(minutes);327    await sendMessage({328      type: "UPDATE_SETTINGS",329      payload: { autoLockMinutes: minutes },330    });331  }332333  async function applyBreachMonitoring(enabled: boolean) {334    setBreachMonitoring(enabled);335    await sendMessage({336      type: "UPDATE_SETTINGS",337      payload: { breachMonitoring: enabled },338    });339  }340341  onMount(async () => {342    // Resolve the active tab in parallel with the unlock/has-vault queries —343    // openVault()'s smart selection picks the entry matching currentTabDomain,344    // so it must be populated before openVault runs. Previously refreshCurrentTab345    // ran after openVault, leaving popups that booted already-unlocked falling346    // back to loadedEntries[0] instead of the domain match.347    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([348      sendMessage({ type: "IS_UNLOCKED" }),349      sendMessage({ type: "HAS_VAULT" }),350      refreshCurrentTab(),351      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),352    ]);353    const unlocked = Boolean(354      (unlockResponse as { ok: boolean; data?: boolean }).data355    );356    const vaultExists = Boolean(357      (vaultResponse as { ok: boolean; data?: boolean }).data358    );359    const shouldCelebrate = Boolean(360      (celebrationResponse as { ok: boolean; data?: boolean }).data361    );362    setHasVault(vaultExists);363    // Onboarding gate — show once on first install, never again. Existing364    // users (vaultExists) are auto-marked onboarded so they skip the flow365    // even on the very first popup open after this feature ships.366    try {367      const onboarded = await storageGet("peach_onboarded");368      const seen = onboarded === "true";369      if (vaultExists && !seen) {370        await storageSet("peach_onboarded", "true");371        setOnboarded(true);372      } else {373        setOnboarded(seen);374      }375    } catch {376      // storage unavailable — default to onboarded so we never block boot377      setOnboarded(true);378    }379    await Promise.all([restoreSettings(), refreshProStatus()]);380381    // Mark played before any animation so a crash mid-sequence never replays it382    if (shouldCelebrate) {383      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });384    }385386    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the387    // background ignores it when no mobile hosts are paired or while388    // another sync is already in flight.389    if (unlocked && vaultExists) {390      void sendMessage({391        type: "TRIGGER_SYNC",392        payload: { reason: "foreground" },393      });394      // UI-1 / HV-1b: surface any remote-mutation alerts the sync merge queued.395      void loadSyncAlerts();396    }397398    // If the user created a vault but hasn't yet confirmed their recovery399    // words, route back to the recovery-words screen instead of opening the400    // entries view. The flag lives in chrome.storage.local so it survives401    // both popup close (SW suppresses lock-on-close) and full browser402    // restart (handleUnlock checks the same flag after a fresh password403    // unlock). Cleared when confirmation succeeds.404    let recoveryPending = false;405    try {406      const out = await chrome.storage.local?.get("peach_recovery_pending");407      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";408    } catch { /* best-effort */ }409410    // If this popup was opened from the inline "Open Peach to unlock" button,411    // the background set a session flag. Read and clear it so handleUnlock()412    // can close the popup after unlock and return the user to the page.413    if (chrome.storage.session) {414      try {415        const s = await chrome.storage.session.get("peach_inline_unlock");416        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {417          openedForInlineUnlock = true;418          await chrome.storage.session.remove("peach_inline_unlock");419        }420      } catch { /* best-effort */ }421    }422423    // Native: closing the app before recovery-words confirmation means the424    // user didn't finish vault creation. Throw the partial vault away and425    // restart onboarding rather than asking them to unlock a vault they426    // never finished creating. Desktop keeps the existing "unlock to427    // resume" flow because closing the popup there is much more casual.428    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {429      try {430        await chrome.storage.local?.remove([431          "peach_vault_a",432          "peach_vault_b",433          "peach_recovery_pending",434          "peach_onboarded",435          "peach_vault_history",436        ]);437      } catch { /* best-effort */ }438      setHasVault(false);439      setOnboarded(false);440      setView("lock");441      setBootState("ready");442      return;443    }444445    if (recoveryPending && unlocked) {446      // forceRecoveryWords overrides LockView's hasVault gate so the447      // recovery surface renders even though the vault now exists.448      setForceRecoveryWords(true);449      setView("lock");450    } else if (unlocked && vaultExists) {451      await openVault(undefined, shouldCelebrate);452      if (shouldCelebrate) {453        setView("pro-celebration");454        window.setTimeout(() => setView("entry"), 2500);455      }456    } else if (shouldCelebrate) {457      setPendingCelebration(true);458    }459460    await refreshPendingPasskey();461462    // Track tab changes so smart sort stays current463    const handleTabActivated = () => { void refreshCurrentTab(); };464    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {465      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();466    };467    try {468      chrome.tabs.onActivated.addListener(handleTabActivated);469      chrome.tabs.onUpdated.addListener(handleTabUpdated);470      onCleanup(() => {471        chrome.tabs.onActivated.removeListener(handleTabActivated);472        chrome.tabs.onUpdated.removeListener(handleTabUpdated);473      });474    } catch {475      // tabs permission may not be available in all contexts476    }477478    setBootState("ready");479480    // Deep-link: ?codex=pdf opens a detached window straight into the481    // Codex restore flow with auto-picked PDF. The action popup can't host482    // a file dialog without dismissing itself, so this is the only way the483    // PDF import path survives. See CodexRestoreView.openPdfPicker().484    try {485      const route = new URLSearchParams(window.location.search).get("codex");486      if (route === "pdf" || route === "restore") {487        setView("codex-restore");488      }489    } catch {490      // location.search unavailable — ignore.491    }492493    // Check for pending session-storage notices from the background.494    if (chrome.storage.session) {495      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as496        Record<string, { feature?: string } | undefined>;497      if (session.pendingProGate?.feature) {498        await chrome.storage.session.remove("pendingProGate");499        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);500        setSettingsInitialSection("license");501        setView("settings");502      } else if (session.pendingProNotice?.feature) {503        await chrome.storage.session.remove("pendingProNotice");504        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });505      }506    }507508    // Warm the lazy-module cache so the Suspense fallback never shows for509    // locally-bundled extension views. Without this, the first navigation to510    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which511    // covers the shell and absorbs clicks on the header.512    void Promise.all([513      import("./views/Settings").catch(() => {}),514      import("./views/Import").catch(() => {}),515      import("./views/Export").catch(() => {}),516      import("./views/Health").catch(() => {}),517      import("./views/TrashView").catch(() => {}),518    ]);519520    // Lock-on-close via a persistent port. sendMessage in pagehide is521    // unreliable — the popup context tears down before the message lands.522    // The SW's onConnect listener locks when this port disconnects.523    let popupPort: chrome.runtime.Port | null = null;524    try {525      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect526      // listener accepts the "popup-" prefix; the random suffix is defence in527      // depth against a port named exactly "popup" from anything but our popup.528      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });529    } catch { /* extension context invalidated — ignore */ }530    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });531532    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only533    // reliable signal is appStateChange — setTimeout is killed when the OS534    // backgrounds the app. We measure elapsed background time on resume.535    if (isNativePlatform()) {536      let backgroundedAt: number | null = null;537538      const CapApp = nativePlugin<{539        addListener: (540          ev: string,541          cb: (s: { isActive: boolean }) => void,542        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };543      }>("App");544      if (CapApp?.addListener) {545        const sub = CapApp.addListener(546          "appStateChange",547          ({ isActive }: { isActive: boolean }) => {548            if (!isActive) {549              backgroundedAt = Date.now();550              return;551            }552            if (backgroundedAt !== null && autoLockMinutes() > 0) {553              const elapsed = Date.now() - backgroundedAt;554              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();555            }556            backgroundedAt = null;557          }558        );559        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.560        onCleanup(() => {561          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});562        });563      }564565      // L12/COR-011: foreground idle autolock. appStateChange only fires when566      // the OS backgrounds the app — if the user idles with the screen on,567      // chrome.alarms is no-op'd in Capacitor so the vault would stay open568      // indefinitely. Poll every 30s and lock if elapsed since last user569      // interaction exceeds autoLockMinutes.570      let lastUserActivityAt = Date.now();571      const bumpActivity = () => { lastUserActivityAt = Date.now(); };572      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;573      for (const ev of ACTIVITY_EVENTS) {574        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });575      }576      const idleLockInterval = setInterval(() => {577        const minutes = autoLockMinutes();578        if (!minutes || minutes <= 0) return;579        const elapsed = Date.now() - lastUserActivityAt;580        if (elapsed >= minutes * 60_000) {581          lastUserActivityAt = Date.now();582          handleHeaderLock();583        }584      }, 30_000);585      onCleanup(() => {586        clearInterval(idleLockInterval);587        for (const ev of ACTIVITY_EVENTS) {588          document.removeEventListener(ev, bumpActivity, { capture: true });589        }590      });591592      // mDNS peer-discovery trigger. Register onCleanup synchronously so593      // SolidJS captures it within the reactive owner — onCleanup inside a594      // .then() callback may miss the capture window and leak the listener.595      let stopMDNS: () => void = () => undefined;596      onCleanup(() => stopMDNS());597      if (isNativePlatform()) {598        // Android runs the background/sync dispatcher in-process with the599        // popup, so the production runner has to be registered from the600        // UI bootstrap path instead of the MV3 service-worker entry.601        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>602          import("../background/chirp-sync-runner").then(({ productionSyncRunner }) => {603            setSyncRunner(productionSyncRunner);604            void hydratePersistedSyncState();605          })606        );607      }608      void import("./chirp-pair-capacitor").then(({ startMDNSListener }) => {609        stopMDNS = startMDNSListener();610      });611    }612613    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale614    // entries instead of waiting for the next GET_ENTRIES round-trip.615    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {616      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();617      if (msg?.type === "PRO_GATE_TRIGGERED") {618        setUpgradeHighlight(msg.payload?.feature ?? null);619        setSettingsInitialSection("license");620        setView("settings");621      }622    };623    chrome.runtime.onMessage.addListener(handleRuntimeMessage);624    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));625626    // Android hardware/gesture back. MainActivity fires peach:back; the popup627    // decides what "back" means per surface. Lock+no-vault is the common case628    // — return to onboarding rather than letting the OS dismiss the activity.629    const handlePeachBack = () => {630      // Notes mode captures back first631      if (showNotes()) {632        setShowNotes(false);633        setOpenNoteId(undefined);634        return;635      }636      const v = view();637      if (v === "lock" && !hasVault() && onboarded()) {638        setOnboarded(false);639        return;640      }641      if (v === "list") { setView("entry"); return; }642      if (v === "settings") {643        window.dispatchEvent(new Event("peach:settings-back"));644        return;645      }646      if (v === "import" || v === "health") { setView("settings"); return; }647      if (v === "export") { handleExportBack(); return; }648      if (v === "add") { handleBack(); return; }649      if (v === "chirp-sync") { setView("settings"); return; }650    };651    window.addEventListener("peach:back", handlePeachBack);652    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));653654    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that655    // peeks from the bottom (search bar handle visible) and drags up to fill656    // the screen. dragOffset is the LIVE finger offset during a drag, in px,657    // 0 when no drag in progress. The wrapper element computes transform =658    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.659    if (isNativePlatform()) {660      let touchStartY = 0;661      let touchStartX = 0;662      let lastY = 0;663      let lastT = 0;664      let dragging = false;665      let captured = false;666      const HORIZONTAL_TOLERANCE = 16;667      const ACTIVATION_DY = 8;668      const PEEK_PX = 60;669670      const onTouchStart = (e: TouchEvent) => {671        const t = e.touches[0];672        if (!t) return;673        const v = view();674        if (v !== "entry" && v !== "list") return;675        // Entry view: only intercept drags starting in the bottom 40%.676        // List view: intercept drags starting in the top 35% (the search/handle row).677        const inBand = v === "entry"678          ? t.clientY > window.innerHeight * 0.6679          : t.clientY < window.innerHeight * 0.35;680        if (!inBand) return;681        touchStartY = lastY = t.clientY;682        touchStartX = t.clientX;683        lastT = e.timeStamp;684        dragging = true;685        captured = false;686      };687688      const onTouchMove = (e: TouchEvent) => {689        if (!dragging) return;690        const t = e.touches[0];691        if (!t) return;692        const dy = t.clientY - touchStartY;693        const dx = Math.abs(t.clientX - touchStartX);694695        if (!captured) {696          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {697            // Looks like a horizontal swipe — release.698            dragging = false;699            return;700          }701          if (Math.abs(dy) < ACTIVATION_DY) return;702          captured = true;703        }704705        // Translate the sheet by dy from its rest (peek) position. Peek is706        // (viewport height - PEEK_PX). Open is 0.707        const v = view();708        const restClosed = window.innerHeight - PEEK_PX;709        const baseTranslate = v === "list" ? 0 : restClosed;710        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));711        setSheetTranslate(next);712        lastY = t.clientY;713        lastT = e.timeStamp;714      };715716      const onTouchEnd = (e: TouchEvent) => {717        if (!dragging) { return; }718        const t = e.changedTouches[0];719        const elapsed = Math.max(1, e.timeStamp - lastT);720        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms721        const wasCaptured = captured;722        dragging = false;723        captured = false;724        const v = view();725726        if (!wasCaptured) {727          // Tap in the peek strip while in entry view → open the vault list.728          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");729          setSheetTranslate(null);730          return;731        }732733        const restClosed = window.innerHeight - PEEK_PX;734        const current = sheetTranslate() ?? restClosed;735736        // Snap rules:737        //   - Strong upward velocity → open738        //   - Strong downward velocity → close739        //   - Otherwise snap to whichever rest is closer740        let nextOpen: boolean;741        if (velocity < -0.05) nextOpen = true;742        else if (velocity > 0.05) nextOpen = false;743        else nextOpen = current < restClosed * 0.5;744745        if (nextOpen && v !== "list") setView("list");746        if (!nextOpen && v !== "entry") setView("entry");747        // Release the live offset so CSS transition handles the snap.748        setSheetTranslate(null);749      };750751      document.addEventListener("touchstart", onTouchStart, { passive: true });752      document.addEventListener("touchmove",  onTouchMove,  { passive: true });753      document.addEventListener("touchend",   onTouchEnd,   { passive: true });754      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });755      onCleanup(() => {756        document.removeEventListener("touchstart", onTouchStart);757        document.removeEventListener("touchmove",  onTouchMove);758        document.removeEventListener("touchend",   onTouchEnd);759      });760    }761762    // Action handlers — keyed by ShortcutAction. The dispatcher below tests763    // each binding against the event and runs the matching handler. New764    // shortcuts only need an entry here; the binding is data, not code.765    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {766      copy_password: () => {767        const entry = selectedEntry();768        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });769      },770      copy_username: () => {771        const entry = selectedEntry();772        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });773      },774      copy_totp: () => {775        const entry = selectedEntry();776        if (!entry?.totp) return;777        try {778          const { code } = generateTOTP(entry.totp);779          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });780        } catch { /* invalid TOTP secret — silent */ }781      },782      new_entry: () => handleAdd(),783      edit_entry: () => {784        const entry = selectedEntry();785        // Passkey-only entries have nothing user-editable in the Add view; the786        // passkey credential itself is opaque. Skip the edit action for them.787        if (!entry || isPasskeyOnly(entry)) return;788        setEditEntry(entry);789        setView("add");790      },791      delete_entry: () => {792        if (selectedEntry()) void handleDelete();793      },794      lock_vault: () => { void handleHeaderLock(); },795      search: () => openList(),796      nav_prev: () => navigate(-1),797      nav_next: () => navigate(1),798      jump_vault: () => setView("entry"),799      jump_settings: () => setView("settings"),800      show_help: () => setShowShortcutsHelp(true),801    };802803    // Actions that are MEANINGFUL only on the entry-detail view. Outside804    // that scope the binding is dormant — pressing C while on Settings805    // does nothing rather than awkwardly copying from a now-stale entry.806    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([807      "copy_password", "copy_username", "copy_totp",808      "edit_entry", "delete_entry", "nav_prev", "nav_next",809    ]);810811    const handleGlobalKeydown = (e: KeyboardEvent) => {812      const v = view();813      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"814        || (e.target as HTMLElement)?.tagName === "TEXTAREA"815        || (e.target as HTMLElement)?.isContentEditable;816      const isPrintableSearchKey =817        e.key.length === 1 &&818        !e.ctrlKey &&819        !e.metaKey &&820        !e.altKey;821822      // No input during the pro celebration sequence823      if (v === "pro-celebration") return;824825      // Help dialog: Escape closes it; eat the keypress so it doesn't826      // also navigate away from the underlying view.827      if (showShortcutsHelp()) {828        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }829        return;830      }831832      // ── Escape — fixed binding (not user-customizable) ───────833      if (e.key === "Escape") {834        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }835        if (v === "list") { setView("entry"); return; }836        if (v === "settings" || v === "add") { handleBack(); return; }837        if (v === "import" || v === "health") { setView("settings"); return; }838        if (v === "export") { handleExportBack(); return; }839        if (v === "chirp-sync") { setView("settings"); return; }840      }841842      // Bindings-driven dispatch. Single-key letter bindings without843      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is844      // inside an input, so users can type into search/forms normally.845      const bindings = shortcutBindings();846      for (const action of Object.keys(bindings) as ShortcutAction[]) {847        const binding = bindings[action];848        if (!matchKeybinding(e, binding)) continue;849        // Single-key letter bindings need the input-focus guard. Bindings850        // with any modifier are safe — Ctrl+L doesn't conflict with typing.851        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;852        if (!hasMod && binding.key.length === 1 && inInput) return;853        if (ENTRY_SCOPED.has(action) && v !== "entry") return;854        e.preventDefault();855        SHORTCUT_HANDLERS[action]?.();856        return;857      }858859      // Type-to-search: in entry view, any printable key not consumed by a860      // shortcut above primes the list search seed and opens the list.861      // Kept outside the bindings table because it's a behavior, not a862      // discrete action — every printable character can trigger it.863      if (v === "entry" && !inInput && isPrintableSearchKey) {864        e.preventDefault();865        primeListSearch(e.key);866        return;867      }868    };869    window.addEventListener("keydown", handleGlobalKeydown);870    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));871872    const handleStorageChanged = (873      changes: Record<string, chrome.storage.StorageChange>,874      areaName: string875    ) => {876      if (areaName !== "session") return;877      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {878        return;879      }880      void refreshPendingPasskey();881    };882    chrome.storage.onChanged.addListener(handleStorageChanged);883    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));884  });885886  async function refreshCurrentTab() {887    try {888      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });889      const url = tab?.url ?? tab?.pendingUrl ?? "";890      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");891      // Skip extension/internal URLs — adding chrome://, about:, or892      // chrome-extension:// to a vault entry is never what the user wants.893      const isWebUrl = /^https?:\/\//i.test(url);894      setCurrentTabUrl(isWebUrl ? url : "");895    } catch {896      setCurrentTabDomain("");897      setCurrentTabUrl("");898    }899  }900901  async function refreshPendingPasskey() {902    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });903    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);904  }905906  async function refreshProStatus() {907    const res = await sendMessage({ type: "GET_LICENSE" });908    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;909    setProStatus(Boolean(data?.valid && data?.plan === "pro"));910  }911912  async function restoreSettings() {913    const res = await sendMessage({ type: "GET_SETTINGS" });914    const s = (res as { ok: boolean; data?: any }).data ?? {};915    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {916      setAccentColor(s.accentColor as AccentColorName);917    }918    setTheme(s.theme === "light" ? "light" : "dark");919    if (s.textSize === "small" || s.textSize === "large") {920      setTextSize(s.textSize);921    } else {922      setTextSize("medium");923    }924    setReduceMotion(s.reduceMotion === true);925    setLockOnClose(s.lockOnClose !== false);926    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);927    setBreachMonitoring(s.breachMonitoring !== false);928    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);929    setShortcutBindings(getActiveBindings(s.shortcuts));930  }931932  async function applyTrashRetention(days: number) {933    setTrashRetentionDays(days);934    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });935  }936937  function primeListSearch(seed: string) {938    setListSearchSeed(seed);939    setListSearchSeedNonce((value) => value + 1);940    openList();941  }942943  // Returns null when it detected a dead service worker and triggered handleLock().944  // Callers that need to abort (e.g. openVault) check for null rather than relying945  // on view() state, which may already be "lock" during normal startup flows.946  async function loadEntries(): Promise<VaultEntry[] | null> {947    const response = await sendMessage({ type: "GET_ENTRIES" });948    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };949950    // If the service worker was killed and restarted (MV3 workers sleep), the951    // vault will be locked again — or the worker may not respond at all.952    // In either case, send the user to the lock screen rather than silently953    // showing an empty vault (which looks like data loss).954    if (!res.ok) {955      if (956        res.error === "vault_locked" ||957        res.error === "SERVICE_WORKER_UNAVAILABLE" ||958        (typeof res.error === "string" && res.error.includes("locked"))959      ) {960        handleLock();961        return null; // signal emergency lock to callers962      }963      return [];964    }965966    const loadedEntries = res.data ?? [];967    setEntries(loadedEntries);968969    const currentId = selectedEntry()?.id;970    if (currentId) {971      setSelectedEntry(972        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null973      );974    }975976    return loadedEntries;977  }978979  async function openVault(preferredEntryId?: string, skipViewSet = false) {980    // Purge expired trash entries on each vault open981    const retDays = trashRetentionDays();982    if (retDays > 0) {983      void sendMessage({984        type: "PURGE_EXPIRED_TRASH",985        payload: { retentionMs: retDays * 86_400_000 },986      });987    }988989    const loadedEntries = await loadEntries();990991    // null means loadEntries() triggered an emergency lock (service worker died).992    // Don't override it by setting view back to "entry" with an empty vault.993    if (loadedEntries === null) return;994995    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry996    let nextSelectedEntry: VaultEntry | null = null;997    if (preferredEntryId) {998      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;999    }1000    if (!nextSelectedEntry) {1001      const tabDomain = currentTabDomain();1002      if (tabDomain) {1003        nextSelectedEntry = loadedEntries.find((e) => {1004          if (e.type === "login") {1005            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1006            for (const extra of e.additionalUrls ?? []) {1007              if ((extractDomain(extra) ?? "") === tabDomain) return true;1008            }1009            return false;1010          }1011          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1012          return false;1013        }) ?? null;1014      }1015    }1016    nextSelectedEntry ??= loadedEntries[0] ?? null;10171018    setSelectedEntry(nextSelectedEntry);1019    setEditEntry(undefined);1020    setContentTransitioning(false);1021    setContentPhase("enter");1022    queueContentIdle();1023    if (!skipViewSet) setView("entry");1024  }10251026  async function handleUnlock() {1027    // If the user previously created a vault but hadn't yet confirmed their1028    // recovery words (and the browser was closed before they could), the1029    // peach_recovery_pending flag is still set in storage.local. Re-route1030    // back to the recovery surface so they finish the confirmation step1031    // before reaching the entries view — the words can be re-derived now1032    // that the vault is unlocked again.1033    let recoveryPending = false;1034    try {1035      const out = await chrome.storage.local?.get("peach_recovery_pending");1036      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1037    } catch { /* best-effort */ }1038    if (recoveryPending) {1039      setForceRecoveryWords(true);1040      setView("lock");1041      triggerPipPulse();1042      await restoreSettings();1043      return;1044    }1045    setHasVault(true);1046    triggerPipPulse();1047    await restoreSettings();1048    const celebrating = pendingCelebration();1049    if (celebrating) {1050      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1051      setPendingCelebration(false);1052    }1053    await openVault(undefined, celebrating);1054    if (celebrating) {1055      setView("pro-celebration");1056      window.setTimeout(() => setView("entry"), 2500);1057    }1058    // Popup was opened from the inline "Open Peach to unlock" button — close it1059    // now so the user lands back on the page with the autofill selector ready.1060    if (openedForInlineUnlock) {1061      openedForInlineUnlock = false;1062      window.close();1063    }1064  }10651066  function handleSelectEntry(entry: VaultEntry) {1067    if (entry.type === "note") {1068      setOpenNoteId(entry.id);1069      setShowNotes(true);1070      return;1071    }1072    setSelectedEntry(entry);1073    setContentTransitioning(false);1074    setContentPhase("enter");1075    queueContentIdle();1076    setView("entry");1077  }10781079  function handleAdd() {1080    setEditEntry(undefined);1081    setView("add");1082  }10831084  async function handleDelete() {1085    const entry = selectedEntry();1086    if (!entry) return;1087    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1088    const loadedEntries = await loadEntries() ?? [];1089    setSelectedEntry(loadedEntries[0] ?? null);1090    setView("entry");1091  }10921093  async function handleDeleteMany(ids: string[]) {1094    for (const id of ids) {1095      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1096    }1097    const loadedEntries = await loadEntries() ?? [];1098    // If the currently selected entry was among the deleted, move to first1099    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1100    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1101  }11021103  async function handleSave(savedEntry?: VaultEntry) {1104    await openVault(savedEntry?.id);1105  }11061107  function handleBack() {1108    const dest = editBackView();1109    setEditBackView("entry");1110    setEditEntry(undefined);1111    setView(dest);1112  }11131114  function handleExportBack() {1115    if (returnToPanic()) {1116      setReturnToPanic(false);1117      setView("panic");1118      return;1119    }1120    setView("settings");1121  }11221123  function handleLock() {1124    clearCanarySuppressions();1125    setEntries([]);1126    setSelectedEntry(null);1127    setEditEntry(undefined);1128    setContentPhase("idle");1129    setView("lock");1130  }11311132  function handleHeaderLock() {1133    // Lock the UI immediately — do not wait for the service worker. If the SW1134    // is dead or slow, the 5s sendMessage timeout would create a dead-click1135    // window. The SW will lock on its next wake regardless.1136    handleLock();1137    void sendMessage({ type: "LOCK" });1138  }11391140  function navigate(dir: number) {1141    const allEntries = entries();1142    if (allEntries.length === 0) return;1143    const currentIndex = selectedIndex();1144    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1145    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1146    setSelectedEntry(allEntries[nextIndex]);1147    setContentPhase("enter");1148    queueContentIdle();1149  }11501151  function openList() {1152    setView("list");1153  }11541155  function openHealth() {1156    setEditEntry(undefined);1157    setView("health");1158  }11591160  function handleOpenFileImport() {1161    setRestoreView("file");1162  }11631164  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11651166  function handleFixEntry(entry: VaultEntry) {1167    setSelectedEntry(entry);1168    // Passkey-only entries have no editable surface — drop into view mode1169    // instead of opening the Add editor.1170    if (isPasskeyOnly(entry)) {1171      setView("entry");1172      return;1173    }1174    setEditBackView(view()); // preserve caller view so back returns here1175    setEditEntry(entry);1176    setView("add");1177  }11781179  const isLockedView = () => view() === "lock" || view() === "adopting";11801181  async function handleAdoptionDone() {1182    await storageSet("peach_onboarded", "true").catch(() => {});1183    setOnboarded(true);1184    setHasVault(true);1185    await handleUnlock();1186    void sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "foreground" } });1187  }11881189  async function startVaultAdoption(args: {1190    password: string;1191    confirmSAS(sas: string): Promise<boolean>;1192    createVault(rootKeyHex: string): Promise<{ vaultId: string }>;1193  }) {1194    if (!isNativePlatform()) {1195      throw new Error("adoption_pairing_requires_native_server");1196    }11971198    const [{ runChirpAdoptionReceiver }, { openCapacitorPairingServer }] = await Promise.all([1199      import("./chirp-pair"),1200      import("./chirp-pair-capacitor"),1201    ]);12021203    await runChirpAdoptionReceiver({1204      deviceName: defaultAdoptionDeviceName(),1205      deviceType: adoptionDeviceType(),1206      openPairingServer: openCapacitorPairingServer,1207      confirmSAS: args.confirmSAS,1208      createVaultFromRootKey: args.createVault,1209      deriveLocalIdentity: async () => {1210        const res = await sendMessage({ type: "CHIRP_GET_LOCAL_IDENTITY" });1211        const r = res as { ok: boolean; data?: unknown; error?: string };1212        if (!r.ok || !r.data) throw new Error(r.error ?? "identity_unavailable");1213        return r.data as Awaited<ReturnType<Parameters<typeof runChirpAdoptionReceiver>[0]["deriveLocalIdentity"]>>;1214      },1215      completePairing: async (paired) => {1216        const res = await sendMessage({ type: "CHIRP_COMPLETE_PAIRING", payload: { paired } });1217        const r = res as { ok: boolean; error?: string };1218        if (!r.ok) throw new Error(r.error ?? "complete_pairing_failed");1219      },1220      applyLicense: async (license) => {1221        const res = (await sendMessage({1222          type: "ACTIVATE_LICENSE",1223          payload: { key: license },1224        })) as { ok: boolean; data?: { valid?: boolean; plan?: string } };1225        if (res.ok && res.data?.valid && res.data?.plan === "pro") await refreshProStatus();1226      },1227      onProgress() {1228        // AdoptVaultView owns the visible phase copy; its SAS callback moves1229        // from chirping to verification, and success/error are local there.1230      },1231    });1232  }12331234  async function handleApprovePendingPasskey() {1235    const pending = pendingPasskey();1236    if (!pending) return;1237    if (pending.browser === "firefox" && pending.type === "create") {1238      // Firefox path: popup itself runs navigator.credentials.create. The1239      // background never approved/rejected anything — it just stashed1240      // intent. After the popup-driven flow resolves (success or cancel),1241      // clear the pending key so the popup doesn't re-show this on next open.1242      const { createFirefoxPasskey } = await import("./firefox-passkey");1243      const result = await createFirefoxPasskey(pending);1244      if (!result.ok) {1245        console.warn("Peach Firefox passkey create failed:", result.error);1246      }1247      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1248      setPendingPasskey(null);1249      void loadEntries();1250      window.close();1251      return;1252    }1253    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1254    window.close();1255  }12561257  async function handleDenyPendingPasskey() {1258    const pending = pendingPasskey();1259    if (!pending) return;1260    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1261    window.close();1262  }12631264  function queueContentIdle(after?: () => void) {1265    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1266    contentPhaseTimer = window.setTimeout(() => {1267      setContentPhase("idle");1268      after?.();1269    }, ENTRY_TRANSITION_SETTLE_MS);1270  }12711272  return (1273    <div class="popup-root peach-theme">1274      <Show when={bootState() === "ready"}>1275        <Show1276          when={!pendingPasskey()}1277          fallback={1278            <PasskeyApprovalView1279              type={pendingPasskey()!.type}1280              rpName={pendingPasskey()!.rpName}1281              rpId={pendingPasskey()!.rpId}1282              userName={pendingPasskey()!.userName}1283              userDisplayName={pendingPasskey()!.userDisplayName}1284              onApprove={handleApprovePendingPasskey}1285              onDeny={handleDenyPendingPasskey}1286            />1287          }1288        >1289          <Show1290            when={!isLockedView()}1291            fallback={1292              <Show1293                when={view() !== "adopting"}1294                fallback={1295                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1296                    <AdoptVaultView1297                      onCancel={() => {1298                        setOnboarded(false);1299                        setView("lock");1300                      }}1301                      onDone={handleAdoptionDone}1302                      startAdoption={startVaultAdoption}1303                    />1304                  </Suspense>1305                }1306              >1307                <Show1308                  when={onboarded() || hasVault()}1309                  fallback={1310                    <Onboarding1311                      onComplete={() => { setOnboarded(true); }}1312                      onRestore={() => { setOnboarded(true); }}1313                      onAdopt={() => {1314                        setOnboarded(true);1315                        setView("adopting");1316                      }}1317                    />1318                  }1319                >1320                  <LockView1321                    hasVault={hasVault()}1322                    ready={bootState() === "ready"}1323                    isPro={proStatus()}1324                    forceRecoveryWords={forceRecoveryWords()}1325                    onUnlock={() => {1326                      // RecoveryWordDisplay clears the storage flag before1327                      // calling onDone, so handleUnlock will see no pending1328                      // confirmation and proceed through the normal path.1329                      if (forceRecoveryWords()) setForceRecoveryWords(false);1330                      return handleUnlock();1331                    }}1332                    onBackToOnboarding={1333                      !hasVault()1334                        ? () => setOnboarded(false)1335                        : undefined1336                    }1337                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1338                  />1339                </Show>1340              </Show>1341            }1342          >1343            <Show1344              when={view() !== "pro-celebration"}1345              fallback={<ProCelebration />}1346            >1347            <section1348              id="hd-shell"1349              class="peach-shell peach-theme"1350              data-surface="extension"1351            >1352            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1353              <PeachWordmark unlocked />1354              <div class="peach-chrome-actions">1355                <button1356                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1357                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1358                  aria-label="Notes"1359                  title="Notes"1360                >1361                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1362                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1363                    <line x1="4" y1="5" x2="10" y2="5" />1364                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1365                    <line x1="4" y1="10" x2="7" y2="10" />1366                  </svg>1367                </button>1368                <button1369                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1370                  onClick={() => setView("settings")}1371                  aria-label="Settings"1372                >1373                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1374                    <path1375                      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"1376                      stroke="currentColor"1377                      stroke-width="0.9"1378                    />1379                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1380                  </svg>1381                </button>1382                <button1383                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1384                  onClick={handleAdd}1385                  aria-label="New entry"1386                >1387                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1388                    <path d="M5.5 1v9M1 5.5h9" />1389                  </svg>1390                </button>1391                <button1392                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1393                  onClick={() => void handleHeaderLock()}1394                  aria-label="Lock vault"1395                >1396                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1397                    <path1398                      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"1399                      stroke="currentColor"1400                      stroke-width="1"1401                      stroke-linecap="round"1402                    />1403                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1404                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1405                  </svg>1406                </button>1407              </div>1408            </header>14091410            <Show when={pendingProNotice() !== null}>1411              <div class="peach-pro-notice-banner">1412                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1413                <button1414                  class="peach-pro-notice-link"1415                  onClick={() => {1416                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1417                    setSettingsInitialSection("license");1418                    setView("settings");1419                    setPendingProNotice(null);1420                  }}1421                >1422                  Learn more →1423                </button>1424                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1425              </div>1426            </Show>14271428            <div class="peach-shell-body">1429              <div class="peach-shell-veil"></div>1430              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1431                <EntryView1432                  entry={selectedEntry()}1433                  currentTabUrl={currentTabUrl()}1434                  entries={entries()}1435                  isPro={proStatus()}1436                  onDelete={handleDelete}1437                  onFieldSaved={() => void loadEntries()}1438                  onEscape={() => { setView("list"); }}1439                  onProGate={(feature) => {1440                    setUpgradeHighlight(feature);1441                    setSettingsInitialSection("license");1442                    setView("settings");1443                  }}1444                />1445              </div>14461447              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1448                <div class="peach-search-bar">1449                  <span class="peach-search-icon">1450                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1451                      <circle cx="5.5" cy="5.5" r="3.75" />1452                      <path d="M8.75 8.75L11.5 11.5" />1453                    </svg>1454                  </span>1455                  <input1456                    class="peach-search-input"1457                    placeholder="search vault..."1458                    autocomplete="off"1459                    aria-label="Search vault entries"1460                    onClick={openList}1461                    onFocus={openList}1462                    readOnly1463                  />1464                  <div class="peach-search-meta">1465                    <span class="peach-search-counter">1466                      {entries().length > 01467                        ? `${selectedIndex() + 1} / ${entries().length}`1468                        : "0 entries"}1469                    </span>1470                    <span class="peach-divider"></span>1471                    <button1472                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1473                      onClick={() => navigate(-1)}1474                      aria-label="Previous entry"1475                      disabled={entries().length === 0}1476                    >1477                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1478                        <path d="M5 1L1 5.5L5 10" />1479                      </svg>1480                    </button>1481                    <button1482                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1483                      onClick={() => navigate(1)}1484                      aria-label="Next entry"1485                      disabled={entries().length === 0}1486                    >1487                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1488                        <path d="M1 1L5 5.5L1 10" />1489                      </svg>1490                    </button>1491                  </div>1492                </div>1493              </section>1494            </div>14951496            {/* Desktop: shown on demand via Show. Native sheet is rendered1497                via Portal below at the document root so its position:fixed1498                isn't trapped by .peach-shell's transform-based animations. */}1499            {/* UI-1 / HV-1b: dismissible remote-mutation alert banners. */}1500            <Show when={syncAlerts().length > 0}>1501              <div class="peach-sync-alerts">1502                <For each={syncAlerts()}>1503                  {(alert, i) => (1504                    <div class="peach-sync-alert">1505                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1506                      <button1507                        class="peach-sync-alert-dismiss"1508                        type="button"1509                        aria-label="Dismiss"1510                        onClick={() => dismissSyncAlert(i())}1511                      >×</button>1512                    </div>1513                  )}1514                </For>1515              </div>1516            </Show>15171518            <Show when={!isNativePlatform() && view() === "list"}>1519              <VaultView1520                entries={entries()}1521                selectedEntryId={selectedEntry()?.id}1522                currentTabDomain={currentTabDomain()}1523                sortOrder={sortOrder()}1524                searchSeed={listSearchSeed()}1525                searchSeedNonce={listSearchSeedNonce()}1526                onSelectEntry={handleSelectEntry}1527                onSortOrderChange={setSortOrder}1528                onAdd={handleAdd}1529                onClose={() => setView("entry")}1530                onOpenTrash={() => setView("trash")}1531                onDeleteMany={handleDeleteMany}1532              />1533            </Show>1534            <Show when={isNativePlatform() && hasVault()}>1535              <Portal>1536                <div1537                  class="peach-vault-sheet"1538                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1539                  style={(() => {1540                    const live = sheetTranslate();1541                    if (live === null) return undefined;1542                    return { transform: `translateY(${live}px)` };1543                  })()}1544                >1545                  <VaultView1546                    entries={entries()}1547                    selectedEntryId={selectedEntry()?.id}1548                    currentTabDomain={currentTabDomain()}1549                    sortOrder={sortOrder()}1550                    searchSeed={listSearchSeed()}1551                    searchSeedNonce={listSearchSeedNonce()}1552                    isNative={true}1553                    onSelectEntry={handleSelectEntry}1554                    onSortOrderChange={setSortOrder}1555                    onAdd={handleAdd}1556                    onClose={() => setView("entry")}1557                    onOpenTrash={() => setView("trash")}1558                    onDeleteMany={handleDeleteMany}1559                  />1560                </div>1561              </Portal>1562            </Show>1563            <Show when={view() === "settings" || settingsExiting()}>1564              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1565                <SettingsView1566                  entriesCount={entries().length}1567                  breachMonitoring={breachMonitoring()}1568                  lockOnClose={lockOnClose()}1569                  autoLockMinutes={autoLockMinutes()}1570                  trashRetentionDays={trashRetentionDays()}1571                  theme={theme()}1572                  accentColor={accentColor()}1573                  textSize={textSize()}1574                  reduceMotion={reduceMotion()}1575                  isPro={proStatus()}1576                  initialSection={settingsInitialSection()}1577                  upgradeHighlight={upgradeHighlight()}1578                  isExiting={settingsExiting()}1579                  onBreachMonitoringChange={applyBreachMonitoring}1580                  onLockOnCloseChange={applyLockOnClose}1581                  onAutoLockMinutesChange={applyAutoLockMinutes}1582                  onTrashRetentionChange={applyTrashRetention}1583                  onThemeChange={applyTheme}1584                  onAccentChange={applyAccentColor}1585                  onTextSizeChange={applyTextSize}1586                  onReduceMotionChange={applyReduceMotion}1587                  shortcuts={shortcutBindings()}1588                  onShortcutsChange={applyShortcuts}1589                  onLicenseChange={async () => {1590                    // After activation/deactivation: refresh Pro status,1591                    // re-load entries (defensive — signal state can drift if1592                    // the SW briefly restarts during the verify+save round-trip),1593                    // and replay the Pro celebration if this is the first time1594                    // a valid Pro license is seen on this device.1595                    await refreshProStatus();1596                    void loadEntries();1597                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1598                    if ((should as { ok: boolean; data?: boolean }).data === true) {1599                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1600                      setView("pro-celebration");1601                      window.setTimeout(() => setView("settings"), 2500);1602                    }1603                  }}1604                  onBack={() => {1605                    setSettingsExiting(true);1606                    window.setTimeout(() => {1607                      setSettingsExiting(false);1608                      setSettingsInitialSection(null);1609                      setUpgradeHighlight(null);1610                      handleBack();1611                    }, 200);1612                  }}1613                  onImport={() => setView("import")}1614                  onExport={() => setView("export")}1615                  onBreachCheckDone={loadEntries}1616                  onOpenHealth={openHealth}1617                  onOpenSyncPairing={(method) => { setSettingsInitialSection(settingsActiveCard()); setSyncPairIntent(method ?? null); setView("chirp-sync"); }}1618                  onOpenFileImport={handleOpenFileImport}1619                  onOpenPanic={() => setView("panic")}1620                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1621                  onOpenCodexRestore={() => setView("codex-restore")}1622                  onCardChange={setSettingsActiveCard}1623                  onProGate={(feature) => {1624                    setUpgradeHighlight(feature);1625                    setSettingsInitialSection("license");1626                  }}1627                />1628              </Suspense>1629            </Show>1630            <Show when={view() === "codex-generate"}>1631              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1632                <CodexGenerateView1633                  isPro={proStatus()}1634                  onBack={() => setView("settings")}1635                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1636                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1637                  onVaultLocked={() => handleLock()}1638                />1639              </Suspense>1640            </Show>1641            <Show when={view() === "codex-restore"}>1642              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1643                <CodexRestoreView1644                  onBack={() => setView("lock")}1645                  onRestoreSuccess={async () => {1646                    // After restore the vault is unlocked; refresh entries1647                    // and route to the main vault list. handleUnlock is the1648                    // canonical post-unlock setup path.1649                    await handleUnlock();1650                  }}1651                />1652              </Suspense>1653            </Show>1654            <Show when={view() === "chirp-sync"}>1655              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1656                <ChirpSyncView1657                  isPro={proStatus()}1658                  initialPair={syncPairIntent()}1659                  onProChanged={() => { void refreshProStatus(); }}1660                  onBack={() => { setSyncPairIntent(null); setView("settings"); }}1661                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1662                />1663              </Suspense>1664            </Show>1665            <Show when={view() === "add"}>1666              <AddView1667                entry={editEntry()}1668                entries={entries()}1669                onBack={handleBack}1670                onSave={handleSave}1671              />1672            </Show>1673            <Show when={view() === "import"}>1674              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1675                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1676              </Suspense>1677            </Show>1678            <Show when={view() === "export"}>1679              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1680                <ExportView onBack={handleExportBack} />1681              </Suspense>1682            </Show>1683            <Show when={view() === "panic"}>1684              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1685                <PanicView1686                  onCancel={() => setView("settings")}1687                  onOpenExport={() => {1688                    setReturnToPanic(true);1689                    setView("export");1690                  }}1691                  onDestroyed={async () => {1692                    clearCanarySuppressions();1693                    setEntries([]);1694                    setSelectedEntry(null);1695                    setEditEntry(undefined);1696                    setHasVault(false);1697                    setOnboarded(false);1698                    setProStatus(false);1699                    setPendingPasskey(null);1700                    setUpgradeHighlight(null);1701                    setSettingsInitialSection(null);1702                    setPendingProNotice(null);1703                    setPendingCelebration(false);1704                    setReturnToPanic(false);1705                    setContentPhase("idle");1706                    setView("lock");1707                  }}1708                />1709              </Suspense>1710            </Show>1711            {/* Health stays mounted while editing an entry from it so1712                computeReused() doesn't rerun on every cancel/back. */}1713            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1714              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1715                <HealthView1716                  entries={entries()}1717                  isPro={proStatus()}1718                  onFixEntry={handleFixEntry}1719                  onBack={() => setView("settings")}1720                  onRefresh={loadEntries}1721                  hidden={view() !== "health"}1722                />1723              </Suspense>1724            </Show>1725            <Show when={view() === "trash"}>1726              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1727                <TrashView1728                  onBack={() => setView("list")}1729                  onRestored={() => void loadEntries()}1730                />1731              </Suspense>1732            </Show>1733            <Show when={showNotes()}>1734              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1735                <NotesMode1736                  notes={entries().filter((e) => e.type === "note")}1737                  initialNoteId={openNoteId()}1738                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1739                  onNoteListChanged={() => void loadEntries()}1740                />1741              </div>1742            </Show>1743            <Show when={restoreView() === "file"}>1744              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1745                <ImportView1746                  mode="onboarding"1747                  replacesExistingVault={true}1748                  onBack={() => setRestoreView(null)}1749                  onImport={async () => {1750                    setRestoreView(null);1751                    await handleUnlock();1752                  }}1753                />1754              </Suspense>1755            </Show>1756            </section>1757            </Show>1758          </Show>1759        </Show>1760      </Show>1761      <Show when={showShortcutsHelp()}>1762        <ShortcutsHelpOverlay1763          bindings={shortcutBindings()}1764          onClose={() => setShowShortcutsHelp(false)}1765        />1766      </Show>1767    </div>1768  );1769}17701771function ShortcutsHelpOverlay(props: {1772  bindings: Record<ShortcutAction, Keybinding>;1773  onClose: () => void;1774}) {1775  return (1776    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1777      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1778        <div class="peach-shortcuts-help-head">1779          <h3>Keyboard shortcuts</h3>1780          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1781        </div>1782        <div class="peach-shortcuts-help-body">1783          <p class="peach-settings-sub-label">ENTRY VIEW</p>1784          <ul>1785            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1786              <li>1787                <span>{d.label}</span>1788                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1789              </li>1790            ))}1791          </ul>1792          <p class="peach-settings-sub-label">ANYWHERE</p>1793          <ul>1794            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1795              <li>1796                <span>{d.label}</span>1797                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1798              </li>1799            ))}1800          </ul>1801        </div>1802      </div>1803    </div>1804  );1805}