App.tsx

72.0 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}118119const ENTRY_TRANSITION_SETTLE_MS = 135;120121export default function App() {122  const [bootState, setBootState] = createSignal<BootState>("loading");123  const [view, setView] = createSignal<View>("lock");124  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,125  // CSS transition takes over for snap animation).126  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);127  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(128    "enter"129  );130  const [contentTransitioning, setContentTransitioning] = createSignal(false);131  const [hasVault, setHasVault] = createSignal(false);132  const [onboarded, setOnboarded] = createSignal(true);133  const [entries, setEntries] = createSignal<VaultEntry[]>([]);134  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);135  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);136137  // UI-1 / HV-1b + MV-8d: remote-mutation alerts queued by the sync merge,138  // shown as dismissible banners on popup open.139  interface SyncAlert {140    type: "REMOTE_PASSWORD_CHANGE" | "REMOTE_DELETE" | "DEVICE_KEY_ROTATED";141    entryId: string;142    entryTitle: string;143    deviceName: string;144    timestamp: number;145  }146  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);147  async function loadSyncAlerts() {148    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {149      ok: boolean;150      data?: SyncAlert[];151    };152    if (r.ok && (r.data?.length ?? 0) > 0) {153      setSyncAlerts(r.data ?? []);154      // Acknowledge so a crash between read and render doesn't lose them —155      // they remain on screen until the user dismisses each.156      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });157    }158  }159  function dismissSyncAlert(index: number) {160    setSyncAlerts((arr) => arr.filter((_, i) => i !== index));161  }162  function syncAlertText(a: SyncAlert): string {163    if (a.type === "REMOTE_PASSWORD_CHANGE") {164      return `${a.deviceName} changed the password for ${a.entryTitle}`;165    }166    if (a.type === "REMOTE_DELETE") {167      return `${a.deviceName} deleted ${a.entryTitle}`;168    }169    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;170  }171  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");172  const [theme, setTheme] = createSignal<"dark" | "light">("dark");173  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");174  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);175  const [lockOnClose, setLockOnClose] = createSignal(true);176  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);177  const [breachMonitoring, setBreachMonitoring] = createSignal(true);178  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);179  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);180  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);181  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);182  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);183  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");184  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");185  // Cached Pro status — synchronous for render paths. Background's186  // GET_LICENSE is async, but render-time reads of isPro() must not block.187  // Refreshed at boot, after activate/deactivate, and whenever the popup188  // re-opens onto a stored license that has changed via another window.189  const [proStatus, setProStatus] = createSignal(false);190  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);191  // When the sync card's "Chirp"/"Code" buttons open the sync view, deep-link192  // straight into that pairing path instead of the rest screen.193  const [syncPairIntent, setSyncPairIntent] = createSignal<"chirp" | "desktop" | null>(null);194  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");195  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);196  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");197  const [listSearchSeed, setListSearchSeed] = createSignal("");198  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);199  const [pendingCelebration, setPendingCelebration] = createSignal(false);200  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);201  // True while Panic Step 1 has bounced the user out to Export. When Export's202  // onBack fires we return to Panic instead of Settings so the user keeps the203  // destruction context they came from.204  const [returnToPanic, setReturnToPanic] = createSignal(false);205  // The view to return to when the add/edit view is dismissed. Normally "entry"206  // but "health" when the user arrives via the fix-entry path from Vault Health.207  const [editBackView, setEditBackView] = createSignal<View>("entry");208  const [settingsExiting, setSettingsExiting] = createSignal(false);209  const [showNotes, setShowNotes] = createSignal(false);210  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);211  // Set on popup boot when peach_recovery_pending flag is found in session212  // storage — instructs LockView to skip the unlock UI and open the recovery213  // words confirmation surface instead. Cleared via handleUnlock once the214  // user has typed the 3 confirmation words.215  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);216217  let contentPhaseTimer: number | undefined;218  // Set when the popup was opened from the inline "Open Peach to unlock" button.219  // handleUnlock() closes the popup after unlock so the user returns to the page.220  let openedForInlineUnlock = false;221222  function applyAccent(name: AccentColorName) {223    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;224    const hex = color.hex;225    document.documentElement.style.setProperty("--peach-accent", hex);226    // Ambient surface variables — derived from the accent so surfaces shift227    // subtly toward the accent hue rather than staying fixed warm-brown.228    document.documentElement.style.setProperty("--peach-glow", hex + "2A");229    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");230    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");231  }232233  createEffect(() => {234    applyAccent(accentColor());235  });236237  createEffect(() => {238    document.documentElement.classList.toggle("light", theme() === "light");239    document.body.classList.toggle("light", theme() === "light");240  });241242  createEffect(() => {243    document.documentElement.setAttribute("data-text-size", textSize());244  });245246  createEffect(() => {247    if (reduceMotion()) {248      document.documentElement.setAttribute("data-motion", "reduce");249    } else {250      document.documentElement.removeAttribute("data-motion");251    }252  });253254  const selectedIndex = createMemo(() => {255    const currentId = selectedEntry()?.id;256    if (!currentId) return entries().length > 0 ? 0 : -1;257    return entries().findIndex((entry) => entry.id === currentId);258  });259260  async function applyAccentColor(name: AccentColorName) {261    applyAccent(name);262    setAccentColor(name);263    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });264  }265266  async function applyTheme(t: "dark" | "light") {267    setTheme(t);268    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });269  }270271  async function applyTextSize(size: "small" | "medium" | "large") {272    setTextSize(size);273    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });274  }275276  async function applyReduceMotion(enabled: boolean) {277    setReduceMotion(enabled);278    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });279  }280281  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload282  // small and lets future default updates land for actions the user hasn't283  // touched. Settings sends us the full active map; we filter and store.284  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {285    setShortcutBindings(active);286    const overrides: Record<string, Keybinding> = {};287    for (const action of Object.keys(active) as ShortcutAction[]) {288      const a = active[action];289      const d = DEFAULT_BINDINGS[action];290      const same = a.key === d.key291        && Boolean(a.ctrl)  === Boolean(d.ctrl)292        && Boolean(a.meta)  === Boolean(d.meta)293        && Boolean(a.shift) === Boolean(d.shift)294        && Boolean(a.alt)   === Boolean(d.alt);295      if (!same) overrides[action] = a;296    }297    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });298  }299300  async function applyLockOnClose(enabled: boolean) {301    setLockOnClose(enabled);302    await sendMessage({303      type: "UPDATE_SETTINGS",304      payload: { lockOnClose: enabled },305    });306  }307308  async function applyAutoLockMinutes(minutes: number) {309    setAutoLockMinutes(minutes);310    await sendMessage({311      type: "UPDATE_SETTINGS",312      payload: { autoLockMinutes: minutes },313    });314  }315316  async function applyBreachMonitoring(enabled: boolean) {317    setBreachMonitoring(enabled);318    await sendMessage({319      type: "UPDATE_SETTINGS",320      payload: { breachMonitoring: enabled },321    });322  }323324  onMount(async () => {325    // Resolve the active tab in parallel with the unlock/has-vault queries —326    // openVault()'s smart selection picks the entry matching currentTabDomain,327    // so it must be populated before openVault runs. Previously refreshCurrentTab328    // ran after openVault, leaving popups that booted already-unlocked falling329    // back to loadedEntries[0] instead of the domain match.330    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([331      sendMessage({ type: "IS_UNLOCKED" }),332      sendMessage({ type: "HAS_VAULT" }),333      refreshCurrentTab(),334      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),335    ]);336    const unlocked = Boolean(337      (unlockResponse as { ok: boolean; data?: boolean }).data338    );339    const vaultExists = Boolean(340      (vaultResponse as { ok: boolean; data?: boolean }).data341    );342    const shouldCelebrate = Boolean(343      (celebrationResponse as { ok: boolean; data?: boolean }).data344    );345    setHasVault(vaultExists);346    // Onboarding gate — show once on first install, never again. Existing347    // users (vaultExists) are auto-marked onboarded so they skip the flow348    // even on the very first popup open after this feature ships.349    try {350      const onboarded = await storageGet("peach_onboarded");351      const seen = onboarded === "true";352      if (vaultExists && !seen) {353        await storageSet("peach_onboarded", "true");354        setOnboarded(true);355      } else {356        setOnboarded(seen);357      }358    } catch {359      // storage unavailable — default to onboarded so we never block boot360      setOnboarded(true);361    }362    await Promise.all([restoreSettings(), refreshProStatus()]);363364    // Mark played before any animation so a crash mid-sequence never replays it365    if (shouldCelebrate) {366      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });367    }368369    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the370    // background ignores it when no mobile hosts are paired or while371    // another sync is already in flight.372    if (unlocked && vaultExists) {373      void sendMessage({374        type: "TRIGGER_SYNC",375        payload: { reason: "foreground" },376      });377      // UI-1 / HV-1b: surface any remote-mutation alerts the sync merge queued.378      void loadSyncAlerts();379    }380381    // If the user created a vault but hasn't yet confirmed their recovery382    // words, route back to the recovery-words screen instead of opening the383    // entries view. The flag lives in chrome.storage.local so it survives384    // both popup close (SW suppresses lock-on-close) and full browser385    // restart (handleUnlock checks the same flag after a fresh password386    // unlock). Cleared when confirmation succeeds.387    let recoveryPending = false;388    try {389      const out = await chrome.storage.local?.get("peach_recovery_pending");390      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";391    } catch { /* best-effort */ }392393    // If this popup was opened from the inline "Open Peach to unlock" button,394    // the background set a session flag. Read and clear it so handleUnlock()395    // can close the popup after unlock and return the user to the page.396    if (chrome.storage.session) {397      try {398        const s = await chrome.storage.session.get("peach_inline_unlock");399        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {400          openedForInlineUnlock = true;401          await chrome.storage.session.remove("peach_inline_unlock");402        }403      } catch { /* best-effort */ }404    }405406    // Native: closing the app before recovery-words confirmation means the407    // user didn't finish vault creation. Throw the partial vault away and408    // restart onboarding rather than asking them to unlock a vault they409    // never finished creating. Desktop keeps the existing "unlock to410    // resume" flow because closing the popup there is much more casual.411    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {412      try {413        await chrome.storage.local?.remove([414          "peach_vault_a",415          "peach_vault_b",416          "peach_recovery_pending",417          "peach_onboarded",418          "peach_vault_history",419        ]);420      } catch { /* best-effort */ }421      setHasVault(false);422      setOnboarded(false);423      setView("lock");424      setBootState("ready");425      return;426    }427428    if (recoveryPending && unlocked) {429      // forceRecoveryWords overrides LockView's hasVault gate so the430      // recovery surface renders even though the vault now exists.431      setForceRecoveryWords(true);432      setView("lock");433    } else if (unlocked && vaultExists) {434      await openVault(undefined, shouldCelebrate);435      if (shouldCelebrate) {436        setView("pro-celebration");437        window.setTimeout(() => setView("entry"), 2500);438      }439    } else if (shouldCelebrate) {440      setPendingCelebration(true);441    }442443    await refreshPendingPasskey();444445    // Track tab changes so smart sort stays current446    const handleTabActivated = () => { void refreshCurrentTab(); };447    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {448      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();449    };450    try {451      chrome.tabs.onActivated.addListener(handleTabActivated);452      chrome.tabs.onUpdated.addListener(handleTabUpdated);453      onCleanup(() => {454        chrome.tabs.onActivated.removeListener(handleTabActivated);455        chrome.tabs.onUpdated.removeListener(handleTabUpdated);456      });457    } catch {458      // tabs permission may not be available in all contexts459    }460461    setBootState("ready");462463    // Deep-link: ?codex=pdf opens a detached window straight into the464    // Codex restore flow with auto-picked PDF. The action popup can't host465    // a file dialog without dismissing itself, so this is the only way the466    // PDF import path survives. See CodexRestoreView.openPdfPicker().467    try {468      const route = new URLSearchParams(window.location.search).get("codex");469      if (route === "pdf" || route === "restore") {470        setView("codex-restore");471      }472    } catch {473      // location.search unavailable — ignore.474    }475476    // Check for pending session-storage notices from the background.477    if (chrome.storage.session) {478      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as479        Record<string, { feature?: string } | undefined>;480      if (session.pendingProGate?.feature) {481        await chrome.storage.session.remove("pendingProGate");482        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);483        setSettingsInitialSection("license");484        setView("settings");485      } else if (session.pendingProNotice?.feature) {486        await chrome.storage.session.remove("pendingProNotice");487        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });488      }489    }490491    // Warm the lazy-module cache so the Suspense fallback never shows for492    // locally-bundled extension views. Without this, the first navigation to493    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which494    // covers the shell and absorbs clicks on the header.495    void Promise.all([496      import("./views/Settings").catch(() => {}),497      import("./views/Import").catch(() => {}),498      import("./views/Export").catch(() => {}),499      import("./views/Health").catch(() => {}),500      import("./views/TrashView").catch(() => {}),501    ]);502503    // Lock-on-close via a persistent port. sendMessage in pagehide is504    // unreliable — the popup context tears down before the message lands.505    // The SW's onConnect listener locks when this port disconnects.506    let popupPort: chrome.runtime.Port | null = null;507    try {508      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect509      // listener accepts the "popup-" prefix; the random suffix is defence in510      // depth against a port named exactly "popup" from anything but our popup.511      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });512    } catch { /* extension context invalidated — ignore */ }513    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });514515    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only516    // reliable signal is appStateChange — setTimeout is killed when the OS517    // backgrounds the app. We measure elapsed background time on resume.518    if (isNativePlatform()) {519      let backgroundedAt: number | null = null;520521      const CapApp = nativePlugin<{522        addListener: (523          ev: string,524          cb: (s: { isActive: boolean }) => void,525        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };526      }>("App");527      if (CapApp?.addListener) {528        const sub = CapApp.addListener(529          "appStateChange",530          ({ isActive }: { isActive: boolean }) => {531            if (!isActive) {532              backgroundedAt = Date.now();533              return;534            }535            if (backgroundedAt !== null && autoLockMinutes() > 0) {536              const elapsed = Date.now() - backgroundedAt;537              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();538            }539            backgroundedAt = null;540          }541        );542        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.543        onCleanup(() => {544          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});545        });546      }547548      // L12/COR-011: foreground idle autolock. appStateChange only fires when549      // the OS backgrounds the app — if the user idles with the screen on,550      // chrome.alarms is no-op'd in Capacitor so the vault would stay open551      // indefinitely. Poll every 30s and lock if elapsed since last user552      // interaction exceeds autoLockMinutes.553      let lastUserActivityAt = Date.now();554      const bumpActivity = () => { lastUserActivityAt = Date.now(); };555      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;556      for (const ev of ACTIVITY_EVENTS) {557        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });558      }559      const idleLockInterval = setInterval(() => {560        const minutes = autoLockMinutes();561        if (!minutes || minutes <= 0) return;562        const elapsed = Date.now() - lastUserActivityAt;563        if (elapsed >= minutes * 60_000) {564          lastUserActivityAt = Date.now();565          handleHeaderLock();566        }567      }, 30_000);568      onCleanup(() => {569        clearInterval(idleLockInterval);570        for (const ev of ACTIVITY_EVENTS) {571          document.removeEventListener(ev, bumpActivity, { capture: true });572        }573      });574575      // mDNS peer-discovery trigger. Register onCleanup synchronously so576      // SolidJS captures it within the reactive owner — onCleanup inside a577      // .then() callback may miss the capture window and leak the listener.578      let stopMDNS: () => void = () => undefined;579      onCleanup(() => stopMDNS());580      if (isNativePlatform()) {581        // Android runs the background/sync dispatcher in-process with the582        // popup, so the production runner has to be registered from the583        // UI bootstrap path instead of the MV3 service-worker entry.584        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>585          import("../background/chirp-sync-runner").then(({ productionSyncRunner }) => {586            setSyncRunner(productionSyncRunner);587            void hydratePersistedSyncState();588          })589        );590      }591      void import("./chirp-pair-capacitor").then(({ startMDNSListener }) => {592        stopMDNS = startMDNSListener();593      });594    }595596    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale597    // entries instead of waiting for the next GET_ENTRIES round-trip.598    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {599      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();600      if (msg?.type === "PRO_GATE_TRIGGERED") {601        setUpgradeHighlight(msg.payload?.feature ?? null);602        setSettingsInitialSection("license");603        setView("settings");604      }605    };606    chrome.runtime.onMessage.addListener(handleRuntimeMessage);607    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));608609    // Android hardware/gesture back. MainActivity fires peach:back; the popup610    // decides what "back" means per surface. Lock+no-vault is the common case611    // — return to onboarding rather than letting the OS dismiss the activity.612    const handlePeachBack = () => {613      // Notes mode captures back first614      if (showNotes()) {615        setShowNotes(false);616        setOpenNoteId(undefined);617        return;618      }619      const v = view();620      if (v === "lock" && !hasVault() && onboarded()) {621        setOnboarded(false);622        return;623      }624      if (v === "list") { setView("entry"); return; }625      if (v === "settings") {626        window.dispatchEvent(new Event("peach:settings-back"));627        return;628      }629      if (v === "import" || v === "health") { setView("settings"); return; }630      if (v === "export") { handleExportBack(); return; }631      if (v === "add") { handleBack(); return; }632      if (v === "chirp-sync") { setView("settings"); return; }633    };634    window.addEventListener("peach:back", handlePeachBack);635    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));636637    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that638    // peeks from the bottom (search bar handle visible) and drags up to fill639    // the screen. dragOffset is the LIVE finger offset during a drag, in px,640    // 0 when no drag in progress. The wrapper element computes transform =641    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.642    if (isNativePlatform()) {643      let touchStartY = 0;644      let touchStartX = 0;645      let lastY = 0;646      let lastT = 0;647      let dragging = false;648      let captured = false;649      const HORIZONTAL_TOLERANCE = 16;650      const ACTIVATION_DY = 8;651      const PEEK_PX = 60;652653      const onTouchStart = (e: TouchEvent) => {654        const t = e.touches[0];655        if (!t) return;656        const v = view();657        if (v !== "entry" && v !== "list") return;658        // Entry view: only intercept drags starting in the bottom 40%.659        // List view: intercept drags starting in the top 35% (the search/handle row).660        const inBand = v === "entry"661          ? t.clientY > window.innerHeight * 0.6662          : t.clientY < window.innerHeight * 0.35;663        if (!inBand) return;664        touchStartY = lastY = t.clientY;665        touchStartX = t.clientX;666        lastT = e.timeStamp;667        dragging = true;668        captured = false;669      };670671      const onTouchMove = (e: TouchEvent) => {672        if (!dragging) return;673        const t = e.touches[0];674        if (!t) return;675        const dy = t.clientY - touchStartY;676        const dx = Math.abs(t.clientX - touchStartX);677678        if (!captured) {679          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {680            // Looks like a horizontal swipe — release.681            dragging = false;682            return;683          }684          if (Math.abs(dy) < ACTIVATION_DY) return;685          captured = true;686        }687688        // Translate the sheet by dy from its rest (peek) position. Peek is689        // (viewport height - PEEK_PX). Open is 0.690        const v = view();691        const restClosed = window.innerHeight - PEEK_PX;692        const baseTranslate = v === "list" ? 0 : restClosed;693        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));694        setSheetTranslate(next);695        lastY = t.clientY;696        lastT = e.timeStamp;697      };698699      const onTouchEnd = (e: TouchEvent) => {700        if (!dragging) { return; }701        const t = e.changedTouches[0];702        const elapsed = Math.max(1, e.timeStamp - lastT);703        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms704        const wasCaptured = captured;705        dragging = false;706        captured = false;707        const v = view();708709        if (!wasCaptured) {710          // Tap in the peek strip while in entry view → open the vault list.711          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");712          setSheetTranslate(null);713          return;714        }715716        const restClosed = window.innerHeight - PEEK_PX;717        const current = sheetTranslate() ?? restClosed;718719        // Snap rules:720        //   - Strong upward velocity → open721        //   - Strong downward velocity → close722        //   - Otherwise snap to whichever rest is closer723        let nextOpen: boolean;724        if (velocity < -0.05) nextOpen = true;725        else if (velocity > 0.05) nextOpen = false;726        else nextOpen = current < restClosed * 0.5;727728        if (nextOpen && v !== "list") setView("list");729        if (!nextOpen && v !== "entry") setView("entry");730        // Release the live offset so CSS transition handles the snap.731        setSheetTranslate(null);732      };733734      document.addEventListener("touchstart", onTouchStart, { passive: true });735      document.addEventListener("touchmove",  onTouchMove,  { passive: true });736      document.addEventListener("touchend",   onTouchEnd,   { passive: true });737      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });738      onCleanup(() => {739        document.removeEventListener("touchstart", onTouchStart);740        document.removeEventListener("touchmove",  onTouchMove);741        document.removeEventListener("touchend",   onTouchEnd);742      });743    }744745    // Action handlers — keyed by ShortcutAction. The dispatcher below tests746    // each binding against the event and runs the matching handler. New747    // shortcuts only need an entry here; the binding is data, not code.748    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {749      copy_password: () => {750        const entry = selectedEntry();751        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });752      },753      copy_username: () => {754        const entry = selectedEntry();755        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });756      },757      copy_totp: () => {758        const entry = selectedEntry();759        if (!entry?.totp) return;760        try {761          const { code } = generateTOTP(entry.totp);762          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });763        } catch { /* invalid TOTP secret — silent */ }764      },765      new_entry: () => handleAdd(),766      edit_entry: () => {767        const entry = selectedEntry();768        // Passkey-only entries have nothing user-editable in the Add view; the769        // passkey credential itself is opaque. Skip the edit action for them.770        if (!entry || isPasskeyOnly(entry)) return;771        setEditEntry(entry);772        setView("add");773      },774      delete_entry: () => {775        if (selectedEntry()) void handleDelete();776      },777      lock_vault: () => { void handleHeaderLock(); },778      search: () => openList(),779      nav_prev: () => navigate(-1),780      nav_next: () => navigate(1),781      jump_vault: () => setView("entry"),782      jump_settings: () => setView("settings"),783      show_help: () => setShowShortcutsHelp(true),784    };785786    // Actions that are MEANINGFUL only on the entry-detail view. Outside787    // that scope the binding is dormant — pressing C while on Settings788    // does nothing rather than awkwardly copying from a now-stale entry.789    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([790      "copy_password", "copy_username", "copy_totp",791      "edit_entry", "delete_entry", "nav_prev", "nav_next",792    ]);793794    const handleGlobalKeydown = (e: KeyboardEvent) => {795      const v = view();796      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"797        || (e.target as HTMLElement)?.tagName === "TEXTAREA"798        || (e.target as HTMLElement)?.isContentEditable;799      const isPrintableSearchKey =800        e.key.length === 1 &&801        !e.ctrlKey &&802        !e.metaKey &&803        !e.altKey;804805      // No input during the pro celebration sequence806      if (v === "pro-celebration") return;807808      // Help dialog: Escape closes it; eat the keypress so it doesn't809      // also navigate away from the underlying view.810      if (showShortcutsHelp()) {811        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }812        return;813      }814815      // ── Escape — fixed binding (not user-customizable) ───────816      if (e.key === "Escape") {817        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }818        if (v === "list") { setView("entry"); return; }819        if (v === "settings" || v === "add") { handleBack(); return; }820        if (v === "import" || v === "health") { setView("settings"); return; }821        if (v === "export") { handleExportBack(); return; }822        if (v === "chirp-sync") { setView("settings"); return; }823      }824825      // Bindings-driven dispatch. Single-key letter bindings without826      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is827      // inside an input, so users can type into search/forms normally.828      const bindings = shortcutBindings();829      for (const action of Object.keys(bindings) as ShortcutAction[]) {830        const binding = bindings[action];831        if (!matchKeybinding(e, binding)) continue;832        // Single-key letter bindings need the input-focus guard. Bindings833        // with any modifier are safe — Ctrl+L doesn't conflict with typing.834        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;835        if (!hasMod && binding.key.length === 1 && inInput) return;836        if (ENTRY_SCOPED.has(action) && v !== "entry") return;837        e.preventDefault();838        SHORTCUT_HANDLERS[action]?.();839        return;840      }841842      // Type-to-search: in entry view, any printable key not consumed by a843      // shortcut above primes the list search seed and opens the list.844      // Kept outside the bindings table because it's a behavior, not a845      // discrete action — every printable character can trigger it.846      if (v === "entry" && !inInput && isPrintableSearchKey) {847        e.preventDefault();848        primeListSearch(e.key);849        return;850      }851    };852    window.addEventListener("keydown", handleGlobalKeydown);853    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));854855    const handleStorageChanged = (856      changes: Record<string, chrome.storage.StorageChange>,857      areaName: string858    ) => {859      if (areaName !== "session") return;860      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {861        return;862      }863      void refreshPendingPasskey();864    };865    chrome.storage.onChanged.addListener(handleStorageChanged);866    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));867  });868869  async function refreshCurrentTab() {870    try {871      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });872      const url = tab?.url ?? tab?.pendingUrl ?? "";873      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");874      // Skip extension/internal URLs — adding chrome://, about:, or875      // chrome-extension:// to a vault entry is never what the user wants.876      const isWebUrl = /^https?:\/\//i.test(url);877      setCurrentTabUrl(isWebUrl ? url : "");878    } catch {879      setCurrentTabDomain("");880      setCurrentTabUrl("");881    }882  }883884  async function refreshPendingPasskey() {885    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });886    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);887  }888889  async function refreshProStatus() {890    const res = await sendMessage({ type: "GET_LICENSE" });891    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;892    setProStatus(Boolean(data?.valid && data?.plan === "pro"));893  }894895  async function restoreSettings() {896    const res = await sendMessage({ type: "GET_SETTINGS" });897    const s = (res as { ok: boolean; data?: any }).data ?? {};898    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {899      setAccentColor(s.accentColor as AccentColorName);900    }901    setTheme(s.theme === "light" ? "light" : "dark");902    if (s.textSize === "small" || s.textSize === "large") {903      setTextSize(s.textSize);904    } else {905      setTextSize("medium");906    }907    setReduceMotion(s.reduceMotion === true);908    setLockOnClose(s.lockOnClose !== false);909    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);910    setBreachMonitoring(s.breachMonitoring !== false);911    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);912    setShortcutBindings(getActiveBindings(s.shortcuts));913  }914915  async function applyTrashRetention(days: number) {916    setTrashRetentionDays(days);917    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });918  }919920  function primeListSearch(seed: string) {921    setListSearchSeed(seed);922    setListSearchSeedNonce((value) => value + 1);923    openList();924  }925926  // Returns null when it detected a dead service worker and triggered handleLock().927  // Callers that need to abort (e.g. openVault) check for null rather than relying928  // on view() state, which may already be "lock" during normal startup flows.929  async function loadEntries(): Promise<VaultEntry[] | null> {930    const response = await sendMessage({ type: "GET_ENTRIES" });931    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };932933    // If the service worker was killed and restarted (MV3 workers sleep), the934    // vault will be locked again — or the worker may not respond at all.935    // In either case, send the user to the lock screen rather than silently936    // showing an empty vault (which looks like data loss).937    if (!res.ok) {938      if (939        res.error === "vault_locked" ||940        res.error === "SERVICE_WORKER_UNAVAILABLE" ||941        (typeof res.error === "string" && res.error.includes("locked"))942      ) {943        handleLock();944        return null; // signal emergency lock to callers945      }946      return [];947    }948949    const loadedEntries = res.data ?? [];950    setEntries(loadedEntries);951952    const currentId = selectedEntry()?.id;953    if (currentId) {954      setSelectedEntry(955        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null956      );957    }958959    return loadedEntries;960  }961962  async function openVault(preferredEntryId?: string, skipViewSet = false) {963    // Purge expired trash entries on each vault open964    const retDays = trashRetentionDays();965    if (retDays > 0) {966      void sendMessage({967        type: "PURGE_EXPIRED_TRASH",968        payload: { retentionMs: retDays * 86_400_000 },969      });970    }971972    const loadedEntries = await loadEntries();973974    // null means loadEntries() triggered an emergency lock (service worker died).975    // Don't override it by setting view back to "entry" with an empty vault.976    if (loadedEntries === null) return;977978    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry979    let nextSelectedEntry: VaultEntry | null = null;980    if (preferredEntryId) {981      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;982    }983    if (!nextSelectedEntry) {984      const tabDomain = currentTabDomain();985      if (tabDomain) {986        nextSelectedEntry = loadedEntries.find((e) => {987          if (e.type === "login") {988            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;989            for (const extra of e.additionalUrls ?? []) {990              if ((extractDomain(extra) ?? "") === tabDomain) return true;991            }992            return false;993          }994          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;995          return false;996        }) ?? null;997      }998    }999    nextSelectedEntry ??= loadedEntries[0] ?? null;10001001    setSelectedEntry(nextSelectedEntry);1002    setEditEntry(undefined);1003    setContentTransitioning(false);1004    setContentPhase("enter");1005    queueContentIdle();1006    if (!skipViewSet) setView("entry");1007  }10081009  async function handleUnlock() {1010    // If the user previously created a vault but hadn't yet confirmed their1011    // recovery words (and the browser was closed before they could), the1012    // peach_recovery_pending flag is still set in storage.local. Re-route1013    // back to the recovery surface so they finish the confirmation step1014    // before reaching the entries view — the words can be re-derived now1015    // that the vault is unlocked again.1016    let recoveryPending = false;1017    try {1018      const out = await chrome.storage.local?.get("peach_recovery_pending");1019      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1020    } catch { /* best-effort */ }1021    if (recoveryPending) {1022      setForceRecoveryWords(true);1023      setView("lock");1024      triggerPipPulse();1025      await restoreSettings();1026      return;1027    }1028    setHasVault(true);1029    triggerPipPulse();1030    await restoreSettings();1031    const celebrating = pendingCelebration();1032    if (celebrating) {1033      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1034      setPendingCelebration(false);1035    }1036    await openVault(undefined, celebrating);1037    if (celebrating) {1038      setView("pro-celebration");1039      window.setTimeout(() => setView("entry"), 2500);1040    }1041    // Popup was opened from the inline "Open Peach to unlock" button — close it1042    // now so the user lands back on the page with the autofill selector ready.1043    if (openedForInlineUnlock) {1044      openedForInlineUnlock = false;1045      window.close();1046    }1047  }10481049  function handleSelectEntry(entry: VaultEntry) {1050    if (entry.type === "note") {1051      setOpenNoteId(entry.id);1052      setShowNotes(true);1053      return;1054    }1055    setSelectedEntry(entry);1056    setContentTransitioning(false);1057    setContentPhase("enter");1058    queueContentIdle();1059    setView("entry");1060  }10611062  function handleAdd() {1063    setEditEntry(undefined);1064    setView("add");1065  }10661067  async function handleDelete() {1068    const entry = selectedEntry();1069    if (!entry) return;1070    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1071    const loadedEntries = await loadEntries() ?? [];1072    setSelectedEntry(loadedEntries[0] ?? null);1073    setView("entry");1074  }10751076  async function handleDeleteMany(ids: string[]) {1077    for (const id of ids) {1078      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1079    }1080    const loadedEntries = await loadEntries() ?? [];1081    // If the currently selected entry was among the deleted, move to first1082    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1083    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1084  }10851086  async function handleSave(savedEntry?: VaultEntry) {1087    await openVault(savedEntry?.id);1088  }10891090  function handleBack() {1091    const dest = editBackView();1092    setEditBackView("entry");1093    setEditEntry(undefined);1094    setView(dest);1095  }10961097  function handleExportBack() {1098    if (returnToPanic()) {1099      setReturnToPanic(false);1100      setView("panic");1101      return;1102    }1103    setView("settings");1104  }11051106  function handleLock() {1107    clearCanarySuppressions();1108    setEntries([]);1109    setSelectedEntry(null);1110    setEditEntry(undefined);1111    setContentPhase("idle");1112    setView("lock");1113  }11141115  function handleHeaderLock() {1116    // Lock the UI immediately — do not wait for the service worker. If the SW1117    // is dead or slow, the 5s sendMessage timeout would create a dead-click1118    // window. The SW will lock on its next wake regardless.1119    handleLock();1120    void sendMessage({ type: "LOCK" });1121  }11221123  function navigate(dir: number) {1124    const allEntries = entries();1125    if (allEntries.length === 0) return;1126    const currentIndex = selectedIndex();1127    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1128    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1129    setSelectedEntry(allEntries[nextIndex]);1130    setContentPhase("enter");1131    queueContentIdle();1132  }11331134  function openList() {1135    setView("list");1136  }11371138  function openHealth() {1139    setEditEntry(undefined);1140    setView("health");1141  }11421143  function handleOpenFileImport() {1144    setRestoreView("file");1145  }11461147  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11481149  function handleFixEntry(entry: VaultEntry) {1150    setSelectedEntry(entry);1151    // Passkey-only entries have no editable surface — drop into view mode1152    // instead of opening the Add editor.1153    if (isPasskeyOnly(entry)) {1154      setView("entry");1155      return;1156    }1157    setEditBackView(view()); // preserve caller view so back returns here1158    setEditEntry(entry);1159    setView("add");1160  }11611162  const isLockedView = () => view() === "lock" || view() === "adopting";11631164  async function handleAdoptionDone() {1165    await storageSet("peach_onboarded", "true").catch(() => {});1166    setOnboarded(true);1167    setHasVault(true);1168    await handleUnlock();1169    void sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "foreground" } });1170  }11711172  async function handleApprovePendingPasskey() {1173    const pending = pendingPasskey();1174    if (!pending) return;1175    if (pending.browser === "firefox" && pending.type === "create") {1176      // Firefox path: popup itself runs navigator.credentials.create. The1177      // background never approved/rejected anything — it just stashed1178      // intent. After the popup-driven flow resolves (success or cancel),1179      // clear the pending key so the popup doesn't re-show this on next open.1180      const { createFirefoxPasskey } = await import("./firefox-passkey");1181      const result = await createFirefoxPasskey(pending);1182      if (!result.ok) {1183        console.warn("Peach Firefox passkey create failed:", result.error);1184      }1185      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1186      setPendingPasskey(null);1187      void loadEntries();1188      window.close();1189      return;1190    }1191    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1192    window.close();1193  }11941195  async function handleDenyPendingPasskey() {1196    const pending = pendingPasskey();1197    if (!pending) return;1198    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1199    window.close();1200  }12011202  function queueContentIdle(after?: () => void) {1203    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1204    contentPhaseTimer = window.setTimeout(() => {1205      setContentPhase("idle");1206      after?.();1207    }, ENTRY_TRANSITION_SETTLE_MS);1208  }12091210  return (1211    <div class="popup-root peach-theme">1212      <Show when={bootState() === "ready"}>1213        <Show1214          when={!pendingPasskey()}1215          fallback={1216            <PasskeyApprovalView1217              type={pendingPasskey()!.type}1218              rpName={pendingPasskey()!.rpName}1219              rpId={pendingPasskey()!.rpId}1220              userName={pendingPasskey()!.userName}1221              userDisplayName={pendingPasskey()!.userDisplayName}1222              onApprove={handleApprovePendingPasskey}1223              onDeny={handleDenyPendingPasskey}1224            />1225          }1226        >1227          <Show1228            when={!isLockedView()}1229            fallback={1230              <Show1231                when={view() !== "adopting"}1232                fallback={1233                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1234                    <AdoptVaultView1235                      onCancel={() => {1236                        setOnboarded(false);1237                        setView("lock");1238                      }}1239                      onDone={handleAdoptionDone}1240                      startAdoption={async () => {1241                        throw new Error("adoption pairing is not available yet");1242                      }}1243                    />1244                  </Suspense>1245                }1246              >1247                <Show1248                  when={onboarded() || hasVault()}1249                  fallback={1250                    <Onboarding1251                      onComplete={() => { setOnboarded(true); }}1252                      onRestore={() => { setOnboarded(true); }}1253                      onAdopt={() => {1254                        setOnboarded(true);1255                        setView("adopting");1256                      }}1257                    />1258                  }1259                >1260                  <LockView1261                    hasVault={hasVault()}1262                    ready={bootState() === "ready"}1263                    isPro={proStatus()}1264                    forceRecoveryWords={forceRecoveryWords()}1265                    onUnlock={() => {1266                      // RecoveryWordDisplay clears the storage flag before1267                      // calling onDone, so handleUnlock will see no pending1268                      // confirmation and proceed through the normal path.1269                      if (forceRecoveryWords()) setForceRecoveryWords(false);1270                      return handleUnlock();1271                    }}1272                    onBackToOnboarding={1273                      !hasVault()1274                        ? () => setOnboarded(false)1275                        : undefined1276                    }1277                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1278                  />1279                </Show>1280              </Show>1281            }1282          >1283            <Show1284              when={view() !== "pro-celebration"}1285              fallback={<ProCelebration />}1286            >1287            <section1288              id="hd-shell"1289              class="peach-shell peach-theme"1290              data-surface="extension"1291            >1292            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1293              <PeachWordmark unlocked />1294              <div class="peach-chrome-actions">1295                <button1296                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1297                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1298                  aria-label="Notes"1299                  title="Notes"1300                >1301                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1302                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1303                    <line x1="4" y1="5" x2="10" y2="5" />1304                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1305                    <line x1="4" y1="10" x2="7" y2="10" />1306                  </svg>1307                </button>1308                <button1309                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1310                  onClick={() => setView("settings")}1311                  aria-label="Settings"1312                >1313                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1314                    <path1315                      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"1316                      stroke="currentColor"1317                      stroke-width="0.9"1318                    />1319                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1320                  </svg>1321                </button>1322                <button1323                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1324                  onClick={handleAdd}1325                  aria-label="New entry"1326                >1327                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1328                    <path d="M5.5 1v9M1 5.5h9" />1329                  </svg>1330                </button>1331                <button1332                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1333                  onClick={() => void handleHeaderLock()}1334                  aria-label="Lock vault"1335                >1336                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1337                    <path1338                      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"1339                      stroke="currentColor"1340                      stroke-width="1"1341                      stroke-linecap="round"1342                    />1343                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1344                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1345                  </svg>1346                </button>1347              </div>1348            </header>13491350            <Show when={pendingProNotice() !== null}>1351              <div class="peach-pro-notice-banner">1352                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1353                <button1354                  class="peach-pro-notice-link"1355                  onClick={() => {1356                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1357                    setSettingsInitialSection("license");1358                    setView("settings");1359                    setPendingProNotice(null);1360                  }}1361                >1362                  Learn more →1363                </button>1364                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1365              </div>1366            </Show>13671368            <div class="peach-shell-body">1369              <div class="peach-shell-veil"></div>1370              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1371                <EntryView1372                  entry={selectedEntry()}1373                  currentTabUrl={currentTabUrl()}1374                  entries={entries()}1375                  isPro={proStatus()}1376                  onDelete={handleDelete}1377                  onFieldSaved={() => void loadEntries()}1378                  onEscape={() => { setView("list"); }}1379                  onProGate={(feature) => {1380                    setUpgradeHighlight(feature);1381                    setSettingsInitialSection("license");1382                    setView("settings");1383                  }}1384                />1385              </div>13861387              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1388                <div class="peach-search-bar">1389                  <span class="peach-search-icon">1390                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1391                      <circle cx="5.5" cy="5.5" r="3.75" />1392                      <path d="M8.75 8.75L11.5 11.5" />1393                    </svg>1394                  </span>1395                  <input1396                    class="peach-search-input"1397                    placeholder="search vault..."1398                    autocomplete="off"1399                    aria-label="Search vault entries"1400                    onClick={openList}1401                    onFocus={openList}1402                    readOnly1403                  />1404                  <div class="peach-search-meta">1405                    <span class="peach-search-counter">1406                      {entries().length > 01407                        ? `${selectedIndex() + 1} / ${entries().length}`1408                        : "0 entries"}1409                    </span>1410                    <span class="peach-divider"></span>1411                    <button1412                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1413                      onClick={() => navigate(-1)}1414                      aria-label="Previous entry"1415                      disabled={entries().length === 0}1416                    >1417                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1418                        <path d="M5 1L1 5.5L5 10" />1419                      </svg>1420                    </button>1421                    <button1422                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1423                      onClick={() => navigate(1)}1424                      aria-label="Next entry"1425                      disabled={entries().length === 0}1426                    >1427                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1428                        <path d="M1 1L5 5.5L1 10" />1429                      </svg>1430                    </button>1431                  </div>1432                </div>1433              </section>1434            </div>14351436            {/* Desktop: shown on demand via Show. Native sheet is rendered1437                via Portal below at the document root so its position:fixed1438                isn't trapped by .peach-shell's transform-based animations. */}1439            {/* UI-1 / HV-1b: dismissible remote-mutation alert banners. */}1440            <Show when={syncAlerts().length > 0}>1441              <div class="peach-sync-alerts">1442                <For each={syncAlerts()}>1443                  {(alert, i) => (1444                    <div class="peach-sync-alert">1445                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1446                      <button1447                        class="peach-sync-alert-dismiss"1448                        type="button"1449                        aria-label="Dismiss"1450                        onClick={() => dismissSyncAlert(i())}1451                      >×</button>1452                    </div>1453                  )}1454                </For>1455              </div>1456            </Show>14571458            <Show when={!isNativePlatform() && view() === "list"}>1459              <VaultView1460                entries={entries()}1461                selectedEntryId={selectedEntry()?.id}1462                currentTabDomain={currentTabDomain()}1463                sortOrder={sortOrder()}1464                searchSeed={listSearchSeed()}1465                searchSeedNonce={listSearchSeedNonce()}1466                onSelectEntry={handleSelectEntry}1467                onSortOrderChange={setSortOrder}1468                onAdd={handleAdd}1469                onClose={() => setView("entry")}1470                onOpenTrash={() => setView("trash")}1471                onDeleteMany={handleDeleteMany}1472              />1473            </Show>1474            <Show when={isNativePlatform() && hasVault()}>1475              <Portal>1476                <div1477                  class="peach-vault-sheet"1478                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1479                  style={(() => {1480                    const live = sheetTranslate();1481                    if (live === null) return undefined;1482                    return { transform: `translateY(${live}px)` };1483                  })()}1484                >1485                  <VaultView1486                    entries={entries()}1487                    selectedEntryId={selectedEntry()?.id}1488                    currentTabDomain={currentTabDomain()}1489                    sortOrder={sortOrder()}1490                    searchSeed={listSearchSeed()}1491                    searchSeedNonce={listSearchSeedNonce()}1492                    isNative={true}1493                    onSelectEntry={handleSelectEntry}1494                    onSortOrderChange={setSortOrder}1495                    onAdd={handleAdd}1496                    onClose={() => setView("entry")}1497                    onOpenTrash={() => setView("trash")}1498                    onDeleteMany={handleDeleteMany}1499                  />1500                </div>1501              </Portal>1502            </Show>1503            <Show when={view() === "settings" || settingsExiting()}>1504              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1505                <SettingsView1506                  entriesCount={entries().length}1507                  breachMonitoring={breachMonitoring()}1508                  lockOnClose={lockOnClose()}1509                  autoLockMinutes={autoLockMinutes()}1510                  trashRetentionDays={trashRetentionDays()}1511                  theme={theme()}1512                  accentColor={accentColor()}1513                  textSize={textSize()}1514                  reduceMotion={reduceMotion()}1515                  isPro={proStatus()}1516                  initialSection={settingsInitialSection()}1517                  upgradeHighlight={upgradeHighlight()}1518                  isExiting={settingsExiting()}1519                  onBreachMonitoringChange={applyBreachMonitoring}1520                  onLockOnCloseChange={applyLockOnClose}1521                  onAutoLockMinutesChange={applyAutoLockMinutes}1522                  onTrashRetentionChange={applyTrashRetention}1523                  onThemeChange={applyTheme}1524                  onAccentChange={applyAccentColor}1525                  onTextSizeChange={applyTextSize}1526                  onReduceMotionChange={applyReduceMotion}1527                  shortcuts={shortcutBindings()}1528                  onShortcutsChange={applyShortcuts}1529                  onLicenseChange={async () => {1530                    // After activation/deactivation: refresh Pro status,1531                    // re-load entries (defensive — signal state can drift if1532                    // the SW briefly restarts during the verify+save round-trip),1533                    // and replay the Pro celebration if this is the first time1534                    // a valid Pro license is seen on this device.1535                    await refreshProStatus();1536                    void loadEntries();1537                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1538                    if ((should as { ok: boolean; data?: boolean }).data === true) {1539                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1540                      setView("pro-celebration");1541                      window.setTimeout(() => setView("settings"), 2500);1542                    }1543                  }}1544                  onBack={() => {1545                    setSettingsExiting(true);1546                    window.setTimeout(() => {1547                      setSettingsExiting(false);1548                      setSettingsInitialSection(null);1549                      setUpgradeHighlight(null);1550                      handleBack();1551                    }, 200);1552                  }}1553                  onImport={() => setView("import")}1554                  onExport={() => setView("export")}1555                  onBreachCheckDone={loadEntries}1556                  onOpenHealth={openHealth}1557                  onOpenSyncPairing={(method) => { setSettingsInitialSection(settingsActiveCard()); setSyncPairIntent(method ?? null); setView("chirp-sync"); }}1558                  onOpenFileImport={handleOpenFileImport}1559                  onOpenPanic={() => setView("panic")}1560                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1561                  onOpenCodexRestore={() => setView("codex-restore")}1562                  onCardChange={setSettingsActiveCard}1563                  onProGate={(feature) => {1564                    setUpgradeHighlight(feature);1565                    setSettingsInitialSection("license");1566                  }}1567                />1568              </Suspense>1569            </Show>1570            <Show when={view() === "codex-generate"}>1571              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1572                <CodexGenerateView1573                  isPro={proStatus()}1574                  onBack={() => setView("settings")}1575                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1576                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1577                  onVaultLocked={() => handleLock()}1578                />1579              </Suspense>1580            </Show>1581            <Show when={view() === "codex-restore"}>1582              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1583                <CodexRestoreView1584                  onBack={() => setView("lock")}1585                  onRestoreSuccess={async () => {1586                    // After restore the vault is unlocked; refresh entries1587                    // and route to the main vault list. handleUnlock is the1588                    // canonical post-unlock setup path.1589                    await handleUnlock();1590                  }}1591                />1592              </Suspense>1593            </Show>1594            <Show when={view() === "chirp-sync"}>1595              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1596                <ChirpSyncView1597                  isPro={proStatus()}1598                  initialPair={syncPairIntent()}1599                  onProChanged={() => { void refreshProStatus(); }}1600                  onBack={() => { setSyncPairIntent(null); setView("settings"); }}1601                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1602                />1603              </Suspense>1604            </Show>1605            <Show when={view() === "add"}>1606              <AddView1607                entry={editEntry()}1608                entries={entries()}1609                onBack={handleBack}1610                onSave={handleSave}1611              />1612            </Show>1613            <Show when={view() === "import"}>1614              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1615                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1616              </Suspense>1617            </Show>1618            <Show when={view() === "export"}>1619              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1620                <ExportView onBack={handleExportBack} />1621              </Suspense>1622            </Show>1623            <Show when={view() === "panic"}>1624              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1625                <PanicView1626                  onCancel={() => setView("settings")}1627                  onOpenExport={() => {1628                    setReturnToPanic(true);1629                    setView("export");1630                  }}1631                  onDestroyed={async () => {1632                    clearCanarySuppressions();1633                    setEntries([]);1634                    setSelectedEntry(null);1635                    setEditEntry(undefined);1636                    setHasVault(false);1637                    setOnboarded(false);1638                    setProStatus(false);1639                    setPendingPasskey(null);1640                    setUpgradeHighlight(null);1641                    setSettingsInitialSection(null);1642                    setPendingProNotice(null);1643                    setPendingCelebration(false);1644                    setReturnToPanic(false);1645                    setContentPhase("idle");1646                    setView("lock");1647                  }}1648                />1649              </Suspense>1650            </Show>1651            {/* Health stays mounted while editing an entry from it so1652                computeReused() doesn't rerun on every cancel/back. */}1653            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1654              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1655                <HealthView1656                  entries={entries()}1657                  isPro={proStatus()}1658                  onFixEntry={handleFixEntry}1659                  onBack={() => setView("settings")}1660                  onRefresh={loadEntries}1661                  hidden={view() !== "health"}1662                />1663              </Suspense>1664            </Show>1665            <Show when={view() === "trash"}>1666              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1667                <TrashView1668                  onBack={() => setView("list")}1669                  onRestored={() => void loadEntries()}1670                />1671              </Suspense>1672            </Show>1673            <Show when={showNotes()}>1674              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1675                <NotesMode1676                  notes={entries().filter((e) => e.type === "note")}1677                  initialNoteId={openNoteId()}1678                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1679                  onNoteListChanged={() => void loadEntries()}1680                />1681              </div>1682            </Show>1683            <Show when={restoreView() === "file"}>1684              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1685                <ImportView1686                  mode="onboarding"1687                  replacesExistingVault={true}1688                  onBack={() => setRestoreView(null)}1689                  onImport={async () => {1690                    setRestoreView(null);1691                    await handleUnlock();1692                  }}1693                />1694              </Suspense>1695            </Show>1696            </section>1697            </Show>1698          </Show>1699        </Show>1700      </Show>1701      <Show when={showShortcutsHelp()}>1702        <ShortcutsHelpOverlay1703          bindings={shortcutBindings()}1704          onClose={() => setShowShortcutsHelp(false)}1705        />1706      </Show>1707    </div>1708  );1709}17101711function ShortcutsHelpOverlay(props: {1712  bindings: Record<ShortcutAction, Keybinding>;1713  onClose: () => void;1714}) {1715  return (1716    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1717      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1718        <div class="peach-shortcuts-help-head">1719          <h3>Keyboard shortcuts</h3>1720          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1721        </div>1722        <div class="peach-shortcuts-help-body">1723          <p class="peach-settings-sub-label">ENTRY VIEW</p>1724          <ul>1725            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1726              <li>1727                <span>{d.label}</span>1728                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1729              </li>1730            ))}1731          </ul>1732          <p class="peach-settings-sub-label">ANYWHERE</p>1733          <ul>1734            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1735              <li>1736                <span>{d.label}</span>1737                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1738              </li>1739            ))}1740          </ul>1741        </div>1742      </div>1743    </div>1744  );1745}