App.tsx

70.6 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 })));4243type View =44  | "lock"45  | "pro-celebration"46  | "entry"47  | "list"48  | "add"49  | "settings"50  | "chirp-sync"51  | "import"52  | "export"53  | "health"54  | "trash"55  | "panic"56  | "codex-generate"57  | "codex-restore";58type BootState = "loading" | "ready";5960const canarySuppressMap = new Map<string, boolean>();61let shellRingAnimation: Animation | null = null;6263export function isCanarySuppressed(entryId: string): boolean {64  return canarySuppressMap.get(entryId) ?? false;65}6667export function setCanarySuppressed(entryId: string, suppressed: boolean): void {68  canarySuppressMap.set(entryId, suppressed);69}7071export function clearCanarySuppressions(): void {72  canarySuppressMap.clear();73}7475export function triggerRing() {76  const shell = document.getElementById("hd-shell");77  if (!shell) return;7879  shellRingAnimation?.cancel();80  shell.dataset.glowing = "true";81  const animation = shell.animate(82    [83      { offset: 0, boxShadow: "var(--copy-shadow)" },84      {85        offset: 0.3,86        boxShadow:87          "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)",88      },89      { offset: 1, boxShadow: "var(--copy-shadow)" },90    ],91    {92      duration: 720,93      easing: "cubic-bezier(0.4, 0, 0.2, 1)",94      fill: "none",95    }96  );97  shellRingAnimation = animation;98  const clearGlow = () => {99    if (shellRingAnimation !== animation) return;100    shellRingAnimation = null;101    delete shell.dataset.glowing;102  };103  animation.onfinish = clearGlow;104  animation.oncancel = clearGlow;105}106107108export function triggerPipPulse() {109  const pip = document.querySelector(".peach-status-pip, .pip");110  if (pip) {111    pip.classList.remove("pulse");112    void (pip as HTMLElement).offsetWidth;113    pip.classList.add("pulse");114  }115}116117const ENTRY_TRANSITION_SETTLE_MS = 135;118119export default function App() {120  const [bootState, setBootState] = createSignal<BootState>("loading");121  const [view, setView] = createSignal<View>("lock");122  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,123  // CSS transition takes over for snap animation).124  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);125  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(126    "enter"127  );128  const [contentTransitioning, setContentTransitioning] = createSignal(false);129  const [hasVault, setHasVault] = createSignal(false);130  const [onboarded, setOnboarded] = createSignal(true);131  const [entries, setEntries] = createSignal<VaultEntry[]>([]);132  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);133  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);134135  // UI-1 / HV-1b + MV-8d: remote-mutation alerts queued by the sync merge,136  // shown as dismissible banners on popup open.137  interface SyncAlert {138    type: "REMOTE_PASSWORD_CHANGE" | "REMOTE_DELETE" | "DEVICE_KEY_ROTATED";139    entryId: string;140    entryTitle: string;141    deviceName: string;142    timestamp: number;143  }144  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);145  async function loadSyncAlerts() {146    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {147      ok: boolean;148      data?: SyncAlert[];149    };150    if (r.ok && (r.data?.length ?? 0) > 0) {151      setSyncAlerts(r.data ?? []);152      // Acknowledge so a crash between read and render doesn't lose them —153      // they remain on screen until the user dismisses each.154      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });155    }156  }157  function dismissSyncAlert(index: number) {158    setSyncAlerts((arr) => arr.filter((_, i) => i !== index));159  }160  function syncAlertText(a: SyncAlert): string {161    if (a.type === "REMOTE_PASSWORD_CHANGE") {162      return `${a.deviceName} changed the password for ${a.entryTitle}`;163    }164    if (a.type === "REMOTE_DELETE") {165      return `${a.deviceName} deleted ${a.entryTitle}`;166    }167    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;168  }169  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");170  const [theme, setTheme] = createSignal<"dark" | "light">("dark");171  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");172  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);173  const [lockOnClose, setLockOnClose] = createSignal(true);174  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);175  const [breachMonitoring, setBreachMonitoring] = createSignal(true);176  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);177  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);178  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);179  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);180  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);181  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");182  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");183  // Cached Pro status — synchronous for render paths. Background's184  // GET_LICENSE is async, but render-time reads of isPro() must not block.185  // Refreshed at boot, after activate/deactivate, and whenever the popup186  // re-opens onto a stored license that has changed via another window.187  const [proStatus, setProStatus] = createSignal(false);188  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);189  // When the sync card's "Chirp"/"Code" buttons open the sync view, deep-link190  // straight into that pairing path instead of the rest screen.191  const [syncPairIntent, setSyncPairIntent] = createSignal<"chirp" | "desktop" | null>(null);192  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");193  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);194  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");195  const [listSearchSeed, setListSearchSeed] = createSignal("");196  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);197  const [pendingCelebration, setPendingCelebration] = createSignal(false);198  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);199  // True while Panic Step 1 has bounced the user out to Export. When Export's200  // onBack fires we return to Panic instead of Settings so the user keeps the201  // destruction context they came from.202  const [returnToPanic, setReturnToPanic] = createSignal(false);203  // The view to return to when the add/edit view is dismissed. Normally "entry"204  // but "health" when the user arrives via the fix-entry path from Vault Health.205  const [editBackView, setEditBackView] = createSignal<View>("entry");206  const [settingsExiting, setSettingsExiting] = createSignal(false);207  const [showNotes, setShowNotes] = createSignal(false);208  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);209  // Set on popup boot when peach_recovery_pending flag is found in session210  // storage — instructs LockView to skip the unlock UI and open the recovery211  // words confirmation surface instead. Cleared via handleUnlock once the212  // user has typed the 3 confirmation words.213  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);214215  let contentPhaseTimer: number | undefined;216  // Set when the popup was opened from the inline "Open Peach to unlock" button.217  // handleUnlock() closes the popup after unlock so the user returns to the page.218  let openedForInlineUnlock = false;219220  function applyAccent(name: AccentColorName) {221    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;222    const hex = color.hex;223    document.documentElement.style.setProperty("--peach-accent", hex);224    // Ambient surface variables — derived from the accent so surfaces shift225    // subtly toward the accent hue rather than staying fixed warm-brown.226    document.documentElement.style.setProperty("--peach-glow", hex + "2A");227    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");228    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");229  }230231  createEffect(() => {232    applyAccent(accentColor());233  });234235  createEffect(() => {236    document.documentElement.classList.toggle("light", theme() === "light");237    document.body.classList.toggle("light", theme() === "light");238  });239240  createEffect(() => {241    document.documentElement.setAttribute("data-text-size", textSize());242  });243244  createEffect(() => {245    if (reduceMotion()) {246      document.documentElement.setAttribute("data-motion", "reduce");247    } else {248      document.documentElement.removeAttribute("data-motion");249    }250  });251252  const selectedIndex = createMemo(() => {253    const currentId = selectedEntry()?.id;254    if (!currentId) return entries().length > 0 ? 0 : -1;255    return entries().findIndex((entry) => entry.id === currentId);256  });257258  async function applyAccentColor(name: AccentColorName) {259    applyAccent(name);260    setAccentColor(name);261    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });262  }263264  async function applyTheme(t: "dark" | "light") {265    setTheme(t);266    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });267  }268269  async function applyTextSize(size: "small" | "medium" | "large") {270    setTextSize(size);271    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });272  }273274  async function applyReduceMotion(enabled: boolean) {275    setReduceMotion(enabled);276    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });277  }278279  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload280  // small and lets future default updates land for actions the user hasn't281  // touched. Settings sends us the full active map; we filter and store.282  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {283    setShortcutBindings(active);284    const overrides: Record<string, Keybinding> = {};285    for (const action of Object.keys(active) as ShortcutAction[]) {286      const a = active[action];287      const d = DEFAULT_BINDINGS[action];288      const same = a.key === d.key289        && Boolean(a.ctrl)  === Boolean(d.ctrl)290        && Boolean(a.meta)  === Boolean(d.meta)291        && Boolean(a.shift) === Boolean(d.shift)292        && Boolean(a.alt)   === Boolean(d.alt);293      if (!same) overrides[action] = a;294    }295    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });296  }297298  async function applyLockOnClose(enabled: boolean) {299    setLockOnClose(enabled);300    await sendMessage({301      type: "UPDATE_SETTINGS",302      payload: { lockOnClose: enabled },303    });304  }305306  async function applyAutoLockMinutes(minutes: number) {307    setAutoLockMinutes(minutes);308    await sendMessage({309      type: "UPDATE_SETTINGS",310      payload: { autoLockMinutes: minutes },311    });312  }313314  async function applyBreachMonitoring(enabled: boolean) {315    setBreachMonitoring(enabled);316    await sendMessage({317      type: "UPDATE_SETTINGS",318      payload: { breachMonitoring: enabled },319    });320  }321322  onMount(async () => {323    // Resolve the active tab in parallel with the unlock/has-vault queries —324    // openVault()'s smart selection picks the entry matching currentTabDomain,325    // so it must be populated before openVault runs. Previously refreshCurrentTab326    // ran after openVault, leaving popups that booted already-unlocked falling327    // back to loadedEntries[0] instead of the domain match.328    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([329      sendMessage({ type: "IS_UNLOCKED" }),330      sendMessage({ type: "HAS_VAULT" }),331      refreshCurrentTab(),332      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),333    ]);334    const unlocked = Boolean(335      (unlockResponse as { ok: boolean; data?: boolean }).data336    );337    const vaultExists = Boolean(338      (vaultResponse as { ok: boolean; data?: boolean }).data339    );340    const shouldCelebrate = Boolean(341      (celebrationResponse as { ok: boolean; data?: boolean }).data342    );343    setHasVault(vaultExists);344    // Onboarding gate — show once on first install, never again. Existing345    // users (vaultExists) are auto-marked onboarded so they skip the flow346    // even on the very first popup open after this feature ships.347    try {348      const onboarded = await storageGet("peach_onboarded");349      const seen = onboarded === "true";350      if (vaultExists && !seen) {351        await storageSet("peach_onboarded", "true");352        setOnboarded(true);353      } else {354        setOnboarded(seen);355      }356    } catch {357      // storage unavailable — default to onboarded so we never block boot358      setOnboarded(true);359    }360    await Promise.all([restoreSettings(), refreshProStatus()]);361362    // Mark played before any animation so a crash mid-sequence never replays it363    if (shouldCelebrate) {364      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });365    }366367    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the368    // background ignores it when no mobile hosts are paired or while369    // another sync is already in flight.370    if (unlocked && vaultExists) {371      void sendMessage({372        type: "TRIGGER_SYNC",373        payload: { reason: "foreground" },374      });375      // UI-1 / HV-1b: surface any remote-mutation alerts the sync merge queued.376      void loadSyncAlerts();377    }378379    // If the user created a vault but hasn't yet confirmed their recovery380    // words, route back to the recovery-words screen instead of opening the381    // entries view. The flag lives in chrome.storage.local so it survives382    // both popup close (SW suppresses lock-on-close) and full browser383    // restart (handleUnlock checks the same flag after a fresh password384    // unlock). Cleared when confirmation succeeds.385    let recoveryPending = false;386    try {387      const out = await chrome.storage.local?.get("peach_recovery_pending");388      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";389    } catch { /* best-effort */ }390391    // If this popup was opened from the inline "Open Peach to unlock" button,392    // the background set a session flag. Read and clear it so handleUnlock()393    // can close the popup after unlock and return the user to the page.394    if (chrome.storage.session) {395      try {396        const s = await chrome.storage.session.get("peach_inline_unlock");397        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {398          openedForInlineUnlock = true;399          await chrome.storage.session.remove("peach_inline_unlock");400        }401      } catch { /* best-effort */ }402    }403404    // Native: closing the app before recovery-words confirmation means the405    // user didn't finish vault creation. Throw the partial vault away and406    // restart onboarding rather than asking them to unlock a vault they407    // never finished creating. Desktop keeps the existing "unlock to408    // resume" flow because closing the popup there is much more casual.409    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {410      try {411        await chrome.storage.local?.remove([412          "peach_vault_a",413          "peach_vault_b",414          "peach_recovery_pending",415          "peach_onboarded",416          "peach_vault_history",417        ]);418      } catch { /* best-effort */ }419      setHasVault(false);420      setOnboarded(false);421      setView("lock");422      setBootState("ready");423      return;424    }425426    if (recoveryPending && unlocked) {427      // forceRecoveryWords overrides LockView's hasVault gate so the428      // recovery surface renders even though the vault now exists.429      setForceRecoveryWords(true);430      setView("lock");431    } else if (unlocked && vaultExists) {432      await openVault(undefined, shouldCelebrate);433      if (shouldCelebrate) {434        setView("pro-celebration");435        window.setTimeout(() => setView("entry"), 2500);436      }437    } else if (shouldCelebrate) {438      setPendingCelebration(true);439    }440441    await refreshPendingPasskey();442443    // Track tab changes so smart sort stays current444    const handleTabActivated = () => { void refreshCurrentTab(); };445    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {446      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();447    };448    try {449      chrome.tabs.onActivated.addListener(handleTabActivated);450      chrome.tabs.onUpdated.addListener(handleTabUpdated);451      onCleanup(() => {452        chrome.tabs.onActivated.removeListener(handleTabActivated);453        chrome.tabs.onUpdated.removeListener(handleTabUpdated);454      });455    } catch {456      // tabs permission may not be available in all contexts457    }458459    setBootState("ready");460461    // Deep-link: ?codex=pdf opens a detached window straight into the462    // Codex restore flow with auto-picked PDF. The action popup can't host463    // a file dialog without dismissing itself, so this is the only way the464    // PDF import path survives. See CodexRestoreView.openPdfPicker().465    try {466      const route = new URLSearchParams(window.location.search).get("codex");467      if (route === "pdf" || route === "restore") {468        setView("codex-restore");469      }470    } catch {471      // location.search unavailable — ignore.472    }473474    // Check for pending session-storage notices from the background.475    if (chrome.storage.session) {476      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as477        Record<string, { feature?: string } | undefined>;478      if (session.pendingProGate?.feature) {479        await chrome.storage.session.remove("pendingProGate");480        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);481        setSettingsInitialSection("license");482        setView("settings");483      } else if (session.pendingProNotice?.feature) {484        await chrome.storage.session.remove("pendingProNotice");485        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });486      }487    }488489    // Warm the lazy-module cache so the Suspense fallback never shows for490    // locally-bundled extension views. Without this, the first navigation to491    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which492    // covers the shell and absorbs clicks on the header.493    void Promise.all([494      import("./views/Settings").catch(() => {}),495      import("./views/Import").catch(() => {}),496      import("./views/Export").catch(() => {}),497      import("./views/Health").catch(() => {}),498      import("./views/TrashView").catch(() => {}),499    ]);500501    // Lock-on-close via a persistent port. sendMessage in pagehide is502    // unreliable — the popup context tears down before the message lands.503    // The SW's onConnect listener locks when this port disconnects.504    let popupPort: chrome.runtime.Port | null = null;505    try {506      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect507      // listener accepts the "popup-" prefix; the random suffix is defence in508      // depth against a port named exactly "popup" from anything but our popup.509      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });510    } catch { /* extension context invalidated — ignore */ }511    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });512513    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only514    // reliable signal is appStateChange — setTimeout is killed when the OS515    // backgrounds the app. We measure elapsed background time on resume.516    if (isNativePlatform()) {517      let backgroundedAt: number | null = null;518519      const CapApp = nativePlugin<{520        addListener: (521          ev: string,522          cb: (s: { isActive: boolean }) => void,523        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };524      }>("App");525      if (CapApp?.addListener) {526        const sub = CapApp.addListener(527          "appStateChange",528          ({ isActive }: { isActive: boolean }) => {529            if (!isActive) {530              backgroundedAt = Date.now();531              return;532            }533            if (backgroundedAt !== null && autoLockMinutes() > 0) {534              const elapsed = Date.now() - backgroundedAt;535              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();536            }537            backgroundedAt = null;538          }539        );540        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.541        onCleanup(() => {542          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});543        });544      }545546      // L12/COR-011: foreground idle autolock. appStateChange only fires when547      // the OS backgrounds the app — if the user idles with the screen on,548      // chrome.alarms is no-op'd in Capacitor so the vault would stay open549      // indefinitely. Poll every 30s and lock if elapsed since last user550      // interaction exceeds autoLockMinutes.551      let lastUserActivityAt = Date.now();552      const bumpActivity = () => { lastUserActivityAt = Date.now(); };553      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;554      for (const ev of ACTIVITY_EVENTS) {555        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });556      }557      const idleLockInterval = setInterval(() => {558        const minutes = autoLockMinutes();559        if (!minutes || minutes <= 0) return;560        const elapsed = Date.now() - lastUserActivityAt;561        if (elapsed >= minutes * 60_000) {562          lastUserActivityAt = Date.now();563          handleHeaderLock();564        }565      }, 30_000);566      onCleanup(() => {567        clearInterval(idleLockInterval);568        for (const ev of ACTIVITY_EVENTS) {569          document.removeEventListener(ev, bumpActivity, { capture: true });570        }571      });572573      // mDNS peer-discovery trigger. Register onCleanup synchronously so574      // SolidJS captures it within the reactive owner — onCleanup inside a575      // .then() callback may miss the capture window and leak the listener.576      let stopMDNS: () => void = () => undefined;577      onCleanup(() => stopMDNS());578      if (isNativePlatform()) {579        // Android runs the background/sync dispatcher in-process with the580        // popup, so the production runner has to be registered from the581        // UI bootstrap path instead of the MV3 service-worker entry.582        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>583          import("../background/chirp-sync-runner").then(({ productionSyncRunner }) => {584            setSyncRunner(productionSyncRunner);585            void hydratePersistedSyncState();586          })587        );588      }589      void import("./chirp-pair-capacitor").then(({ startMDNSListener }) => {590        stopMDNS = startMDNSListener();591      });592    }593594    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale595    // entries instead of waiting for the next GET_ENTRIES round-trip.596    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {597      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();598      if (msg?.type === "PRO_GATE_TRIGGERED") {599        setUpgradeHighlight(msg.payload?.feature ?? null);600        setSettingsInitialSection("license");601        setView("settings");602      }603    };604    chrome.runtime.onMessage.addListener(handleRuntimeMessage);605    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));606607    // Android hardware/gesture back. MainActivity fires peach:back; the popup608    // decides what "back" means per surface. Lock+no-vault is the common case609    // — return to onboarding rather than letting the OS dismiss the activity.610    const handlePeachBack = () => {611      // Notes mode captures back first612      if (showNotes()) {613        setShowNotes(false);614        setOpenNoteId(undefined);615        return;616      }617      const v = view();618      if (v === "lock" && !hasVault() && onboarded()) {619        setOnboarded(false);620        return;621      }622      if (v === "list") { setView("entry"); return; }623      if (v === "settings") {624        window.dispatchEvent(new Event("peach:settings-back"));625        return;626      }627      if (v === "import" || v === "health") { setView("settings"); return; }628      if (v === "export") { handleExportBack(); return; }629      if (v === "add") { handleBack(); return; }630      if (v === "chirp-sync") { setView("settings"); return; }631    };632    window.addEventListener("peach:back", handlePeachBack);633    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));634635    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that636    // peeks from the bottom (search bar handle visible) and drags up to fill637    // the screen. dragOffset is the LIVE finger offset during a drag, in px,638    // 0 when no drag in progress. The wrapper element computes transform =639    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.640    if (isNativePlatform()) {641      let touchStartY = 0;642      let touchStartX = 0;643      let lastY = 0;644      let lastT = 0;645      let dragging = false;646      let captured = false;647      const HORIZONTAL_TOLERANCE = 16;648      const ACTIVATION_DY = 8;649      const PEEK_PX = 60;650651      const onTouchStart = (e: TouchEvent) => {652        const t = e.touches[0];653        if (!t) return;654        const v = view();655        if (v !== "entry" && v !== "list") return;656        // Entry view: only intercept drags starting in the bottom 40%.657        // List view: intercept drags starting in the top 35% (the search/handle row).658        const inBand = v === "entry"659          ? t.clientY > window.innerHeight * 0.6660          : t.clientY < window.innerHeight * 0.35;661        if (!inBand) return;662        touchStartY = lastY = t.clientY;663        touchStartX = t.clientX;664        lastT = e.timeStamp;665        dragging = true;666        captured = false;667      };668669      const onTouchMove = (e: TouchEvent) => {670        if (!dragging) return;671        const t = e.touches[0];672        if (!t) return;673        const dy = t.clientY - touchStartY;674        const dx = Math.abs(t.clientX - touchStartX);675676        if (!captured) {677          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {678            // Looks like a horizontal swipe — release.679            dragging = false;680            return;681          }682          if (Math.abs(dy) < ACTIVATION_DY) return;683          captured = true;684        }685686        // Translate the sheet by dy from its rest (peek) position. Peek is687        // (viewport height - PEEK_PX). Open is 0.688        const v = view();689        const restClosed = window.innerHeight - PEEK_PX;690        const baseTranslate = v === "list" ? 0 : restClosed;691        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));692        setSheetTranslate(next);693        lastY = t.clientY;694        lastT = e.timeStamp;695      };696697      const onTouchEnd = (e: TouchEvent) => {698        if (!dragging) { return; }699        const t = e.changedTouches[0];700        const elapsed = Math.max(1, e.timeStamp - lastT);701        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms702        const wasCaptured = captured;703        dragging = false;704        captured = false;705        const v = view();706707        if (!wasCaptured) {708          // Tap in the peek strip while in entry view → open the vault list.709          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");710          setSheetTranslate(null);711          return;712        }713714        const restClosed = window.innerHeight - PEEK_PX;715        const current = sheetTranslate() ?? restClosed;716717        // Snap rules:718        //   - Strong upward velocity → open719        //   - Strong downward velocity → close720        //   - Otherwise snap to whichever rest is closer721        let nextOpen: boolean;722        if (velocity < -0.05) nextOpen = true;723        else if (velocity > 0.05) nextOpen = false;724        else nextOpen = current < restClosed * 0.5;725726        if (nextOpen && v !== "list") setView("list");727        if (!nextOpen && v !== "entry") setView("entry");728        // Release the live offset so CSS transition handles the snap.729        setSheetTranslate(null);730      };731732      document.addEventListener("touchstart", onTouchStart, { passive: true });733      document.addEventListener("touchmove",  onTouchMove,  { passive: true });734      document.addEventListener("touchend",   onTouchEnd,   { passive: true });735      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });736      onCleanup(() => {737        document.removeEventListener("touchstart", onTouchStart);738        document.removeEventListener("touchmove",  onTouchMove);739        document.removeEventListener("touchend",   onTouchEnd);740      });741    }742743    // Action handlers — keyed by ShortcutAction. The dispatcher below tests744    // each binding against the event and runs the matching handler. New745    // shortcuts only need an entry here; the binding is data, not code.746    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {747      copy_password: () => {748        const entry = selectedEntry();749        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });750      },751      copy_username: () => {752        const entry = selectedEntry();753        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });754      },755      copy_totp: () => {756        const entry = selectedEntry();757        if (!entry?.totp) return;758        try {759          const { code } = generateTOTP(entry.totp);760          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });761        } catch { /* invalid TOTP secret — silent */ }762      },763      new_entry: () => handleAdd(),764      edit_entry: () => {765        const entry = selectedEntry();766        // Passkey-only entries have nothing user-editable in the Add view; the767        // passkey credential itself is opaque. Skip the edit action for them.768        if (!entry || isPasskeyOnly(entry)) return;769        setEditEntry(entry);770        setView("add");771      },772      delete_entry: () => {773        if (selectedEntry()) void handleDelete();774      },775      lock_vault: () => { void handleHeaderLock(); },776      search: () => openList(),777      nav_prev: () => navigate(-1),778      nav_next: () => navigate(1),779      jump_vault: () => setView("entry"),780      jump_settings: () => setView("settings"),781      show_help: () => setShowShortcutsHelp(true),782    };783784    // Actions that are MEANINGFUL only on the entry-detail view. Outside785    // that scope the binding is dormant — pressing C while on Settings786    // does nothing rather than awkwardly copying from a now-stale entry.787    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([788      "copy_password", "copy_username", "copy_totp",789      "edit_entry", "delete_entry", "nav_prev", "nav_next",790    ]);791792    const handleGlobalKeydown = (e: KeyboardEvent) => {793      const v = view();794      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"795        || (e.target as HTMLElement)?.tagName === "TEXTAREA"796        || (e.target as HTMLElement)?.isContentEditable;797      const isPrintableSearchKey =798        e.key.length === 1 &&799        !e.ctrlKey &&800        !e.metaKey &&801        !e.altKey;802803      // No input during the pro celebration sequence804      if (v === "pro-celebration") return;805806      // Help dialog: Escape closes it; eat the keypress so it doesn't807      // also navigate away from the underlying view.808      if (showShortcutsHelp()) {809        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }810        return;811      }812813      // ── Escape — fixed binding (not user-customizable) ───────814      if (e.key === "Escape") {815        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }816        if (v === "list") { setView("entry"); return; }817        if (v === "settings" || v === "add") { handleBack(); return; }818        if (v === "import" || v === "health") { setView("settings"); return; }819        if (v === "export") { handleExportBack(); return; }820        if (v === "chirp-sync") { setView("settings"); return; }821      }822823      // Bindings-driven dispatch. Single-key letter bindings without824      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is825      // inside an input, so users can type into search/forms normally.826      const bindings = shortcutBindings();827      for (const action of Object.keys(bindings) as ShortcutAction[]) {828        const binding = bindings[action];829        if (!matchKeybinding(e, binding)) continue;830        // Single-key letter bindings need the input-focus guard. Bindings831        // with any modifier are safe — Ctrl+L doesn't conflict with typing.832        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;833        if (!hasMod && binding.key.length === 1 && inInput) return;834        if (ENTRY_SCOPED.has(action) && v !== "entry") return;835        e.preventDefault();836        SHORTCUT_HANDLERS[action]?.();837        return;838      }839840      // Type-to-search: in entry view, any printable key not consumed by a841      // shortcut above primes the list search seed and opens the list.842      // Kept outside the bindings table because it's a behavior, not a843      // discrete action — every printable character can trigger it.844      if (v === "entry" && !inInput && isPrintableSearchKey) {845        e.preventDefault();846        primeListSearch(e.key);847        return;848      }849    };850    window.addEventListener("keydown", handleGlobalKeydown);851    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));852853    const handleStorageChanged = (854      changes: Record<string, chrome.storage.StorageChange>,855      areaName: string856    ) => {857      if (areaName !== "session") return;858      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {859        return;860      }861      void refreshPendingPasskey();862    };863    chrome.storage.onChanged.addListener(handleStorageChanged);864    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));865  });866867  async function refreshCurrentTab() {868    try {869      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });870      const url = tab?.url ?? tab?.pendingUrl ?? "";871      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");872      // Skip extension/internal URLs — adding chrome://, about:, or873      // chrome-extension:// to a vault entry is never what the user wants.874      const isWebUrl = /^https?:\/\//i.test(url);875      setCurrentTabUrl(isWebUrl ? url : "");876    } catch {877      setCurrentTabDomain("");878      setCurrentTabUrl("");879    }880  }881882  async function refreshPendingPasskey() {883    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });884    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);885  }886887  async function refreshProStatus() {888    const res = await sendMessage({ type: "GET_LICENSE" });889    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;890    setProStatus(Boolean(data?.valid && data?.plan === "pro"));891  }892893  async function restoreSettings() {894    const res = await sendMessage({ type: "GET_SETTINGS" });895    const s = (res as { ok: boolean; data?: any }).data ?? {};896    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {897      setAccentColor(s.accentColor as AccentColorName);898    }899    setTheme(s.theme === "light" ? "light" : "dark");900    if (s.textSize === "small" || s.textSize === "large") {901      setTextSize(s.textSize);902    } else {903      setTextSize("medium");904    }905    setReduceMotion(s.reduceMotion === true);906    setLockOnClose(s.lockOnClose !== false);907    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);908    setBreachMonitoring(s.breachMonitoring !== false);909    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);910    setShortcutBindings(getActiveBindings(s.shortcuts));911  }912913  async function applyTrashRetention(days: number) {914    setTrashRetentionDays(days);915    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });916  }917918  function primeListSearch(seed: string) {919    setListSearchSeed(seed);920    setListSearchSeedNonce((value) => value + 1);921    openList();922  }923924  // Returns null when it detected a dead service worker and triggered handleLock().925  // Callers that need to abort (e.g. openVault) check for null rather than relying926  // on view() state, which may already be "lock" during normal startup flows.927  async function loadEntries(): Promise<VaultEntry[] | null> {928    const response = await sendMessage({ type: "GET_ENTRIES" });929    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };930931    // If the service worker was killed and restarted (MV3 workers sleep), the932    // vault will be locked again — or the worker may not respond at all.933    // In either case, send the user to the lock screen rather than silently934    // showing an empty vault (which looks like data loss).935    if (!res.ok) {936      if (937        res.error === "vault_locked" ||938        res.error === "SERVICE_WORKER_UNAVAILABLE" ||939        (typeof res.error === "string" && res.error.includes("locked"))940      ) {941        handleLock();942        return null; // signal emergency lock to callers943      }944      return [];945    }946947    const loadedEntries = res.data ?? [];948    setEntries(loadedEntries);949950    const currentId = selectedEntry()?.id;951    if (currentId) {952      setSelectedEntry(953        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null954      );955    }956957    return loadedEntries;958  }959960  async function openVault(preferredEntryId?: string, skipViewSet = false) {961    // Purge expired trash entries on each vault open962    const retDays = trashRetentionDays();963    if (retDays > 0) {964      void sendMessage({965        type: "PURGE_EXPIRED_TRASH",966        payload: { retentionMs: retDays * 86_400_000 },967      });968    }969970    const loadedEntries = await loadEntries();971972    // null means loadEntries() triggered an emergency lock (service worker died).973    // Don't override it by setting view back to "entry" with an empty vault.974    if (loadedEntries === null) return;975976    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry977    let nextSelectedEntry: VaultEntry | null = null;978    if (preferredEntryId) {979      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;980    }981    if (!nextSelectedEntry) {982      const tabDomain = currentTabDomain();983      if (tabDomain) {984        nextSelectedEntry = loadedEntries.find((e) => {985          if (e.type === "login") {986            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;987            for (const extra of e.additionalUrls ?? []) {988              if ((extractDomain(extra) ?? "") === tabDomain) return true;989            }990            return false;991          }992          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;993          return false;994        }) ?? null;995      }996    }997    nextSelectedEntry ??= loadedEntries[0] ?? null;998999    setSelectedEntry(nextSelectedEntry);1000    setEditEntry(undefined);1001    setContentTransitioning(false);1002    setContentPhase("enter");1003    queueContentIdle();1004    if (!skipViewSet) setView("entry");1005  }10061007  async function handleUnlock() {1008    // If the user previously created a vault but hadn't yet confirmed their1009    // recovery words (and the browser was closed before they could), the1010    // peach_recovery_pending flag is still set in storage.local. Re-route1011    // back to the recovery surface so they finish the confirmation step1012    // before reaching the entries view — the words can be re-derived now1013    // that the vault is unlocked again.1014    let recoveryPending = false;1015    try {1016      const out = await chrome.storage.local?.get("peach_recovery_pending");1017      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1018    } catch { /* best-effort */ }1019    if (recoveryPending) {1020      setForceRecoveryWords(true);1021      setView("lock");1022      triggerPipPulse();1023      await restoreSettings();1024      return;1025    }1026    setHasVault(true);1027    triggerPipPulse();1028    await restoreSettings();1029    const celebrating = pendingCelebration();1030    if (celebrating) {1031      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1032      setPendingCelebration(false);1033    }1034    await openVault(undefined, celebrating);1035    if (celebrating) {1036      setView("pro-celebration");1037      window.setTimeout(() => setView("entry"), 2500);1038    }1039    // Popup was opened from the inline "Open Peach to unlock" button — close it1040    // now so the user lands back on the page with the autofill selector ready.1041    if (openedForInlineUnlock) {1042      openedForInlineUnlock = false;1043      window.close();1044    }1045  }10461047  function handleSelectEntry(entry: VaultEntry) {1048    if (entry.type === "note") {1049      setOpenNoteId(entry.id);1050      setShowNotes(true);1051      return;1052    }1053    setSelectedEntry(entry);1054    setContentTransitioning(false);1055    setContentPhase("enter");1056    queueContentIdle();1057    setView("entry");1058  }10591060  function handleAdd() {1061    setEditEntry(undefined);1062    setView("add");1063  }10641065  async function handleDelete() {1066    const entry = selectedEntry();1067    if (!entry) return;1068    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1069    const loadedEntries = await loadEntries() ?? [];1070    setSelectedEntry(loadedEntries[0] ?? null);1071    setView("entry");1072  }10731074  async function handleDeleteMany(ids: string[]) {1075    for (const id of ids) {1076      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1077    }1078    const loadedEntries = await loadEntries() ?? [];1079    // If the currently selected entry was among the deleted, move to first1080    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1081    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1082  }10831084  async function handleSave(savedEntry?: VaultEntry) {1085    await openVault(savedEntry?.id);1086  }10871088  function handleBack() {1089    const dest = editBackView();1090    setEditBackView("entry");1091    setEditEntry(undefined);1092    setView(dest);1093  }10941095  function handleExportBack() {1096    if (returnToPanic()) {1097      setReturnToPanic(false);1098      setView("panic");1099      return;1100    }1101    setView("settings");1102  }11031104  function handleLock() {1105    clearCanarySuppressions();1106    setEntries([]);1107    setSelectedEntry(null);1108    setEditEntry(undefined);1109    setContentPhase("idle");1110    setView("lock");1111  }11121113  function handleHeaderLock() {1114    // Lock the UI immediately — do not wait for the service worker. If the SW1115    // is dead or slow, the 5s sendMessage timeout would create a dead-click1116    // window. The SW will lock on its next wake regardless.1117    handleLock();1118    void sendMessage({ type: "LOCK" });1119  }11201121  function navigate(dir: number) {1122    const allEntries = entries();1123    if (allEntries.length === 0) return;1124    const currentIndex = selectedIndex();1125    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1126    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1127    setSelectedEntry(allEntries[nextIndex]);1128    setContentPhase("enter");1129    queueContentIdle();1130  }11311132  function openList() {1133    setView("list");1134  }11351136  function openHealth() {1137    setEditEntry(undefined);1138    setView("health");1139  }11401141  function handleOpenFileImport() {1142    setRestoreView("file");1143  }11441145  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11461147  function handleFixEntry(entry: VaultEntry) {1148    setSelectedEntry(entry);1149    // Passkey-only entries have no editable surface — drop into view mode1150    // instead of opening the Add editor.1151    if (isPasskeyOnly(entry)) {1152      setView("entry");1153      return;1154    }1155    setEditBackView(view()); // preserve caller view so back returns here1156    setEditEntry(entry);1157    setView("add");1158  }11591160  const isLockedView = () => view() === "lock";11611162  async function handleApprovePendingPasskey() {1163    const pending = pendingPasskey();1164    if (!pending) return;1165    if (pending.browser === "firefox" && pending.type === "create") {1166      // Firefox path: popup itself runs navigator.credentials.create. The1167      // background never approved/rejected anything — it just stashed1168      // intent. After the popup-driven flow resolves (success or cancel),1169      // clear the pending key so the popup doesn't re-show this on next open.1170      const { createFirefoxPasskey } = await import("./firefox-passkey");1171      const result = await createFirefoxPasskey(pending);1172      if (!result.ok) {1173        console.warn("Peach Firefox passkey create failed:", result.error);1174      }1175      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1176      setPendingPasskey(null);1177      void loadEntries();1178      window.close();1179      return;1180    }1181    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1182    window.close();1183  }11841185  async function handleDenyPendingPasskey() {1186    const pending = pendingPasskey();1187    if (!pending) return;1188    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1189    window.close();1190  }11911192  function queueContentIdle(after?: () => void) {1193    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1194    contentPhaseTimer = window.setTimeout(() => {1195      setContentPhase("idle");1196      after?.();1197    }, ENTRY_TRANSITION_SETTLE_MS);1198  }11991200  return (1201    <div class="popup-root peach-theme">1202      <Show when={bootState() === "ready"}>1203        <Show1204          when={!pendingPasskey()}1205          fallback={1206            <PasskeyApprovalView1207              type={pendingPasskey()!.type}1208              rpName={pendingPasskey()!.rpName}1209              rpId={pendingPasskey()!.rpId}1210              userName={pendingPasskey()!.userName}1211              userDisplayName={pendingPasskey()!.userDisplayName}1212              onApprove={handleApprovePendingPasskey}1213              onDeny={handleDenyPendingPasskey}1214            />1215          }1216        >1217          <Show1218            when={!isLockedView()}1219            fallback={1220              <Show1221                when={onboarded() || hasVault()}1222                fallback={1223                  <Onboarding1224                    onComplete={() => { setOnboarded(true); }}1225                  />1226                }1227              >1228                <LockView1229                  hasVault={hasVault()}1230                  ready={bootState() === "ready"}1231                  isPro={proStatus()}1232                  forceRecoveryWords={forceRecoveryWords()}1233                  onUnlock={() => {1234                    // RecoveryWordDisplay clears the storage flag before1235                    // calling onDone, so handleUnlock will see no pending1236                    // confirmation and proceed through the normal path.1237                    if (forceRecoveryWords()) setForceRecoveryWords(false);1238                    return handleUnlock();1239                  }}1240                  onBackToOnboarding={1241                    !hasVault()1242                      ? () => setOnboarded(false)1243                      : undefined1244                  }1245                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1246                />1247              </Show>1248            }1249          >1250            <Show1251              when={view() !== "pro-celebration"}1252              fallback={<ProCelebration />}1253            >1254            <section1255              id="hd-shell"1256              class="peach-shell peach-theme"1257              data-surface="extension"1258            >1259            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1260              <PeachWordmark unlocked />1261              <div class="peach-chrome-actions">1262                <button1263                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1264                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1265                  aria-label="Notes"1266                  title="Notes"1267                >1268                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1269                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1270                    <line x1="4" y1="5" x2="10" y2="5" />1271                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1272                    <line x1="4" y1="10" x2="7" y2="10" />1273                  </svg>1274                </button>1275                <button1276                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1277                  onClick={() => setView("settings")}1278                  aria-label="Settings"1279                >1280                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1281                    <path1282                      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"1283                      stroke="currentColor"1284                      stroke-width="0.9"1285                    />1286                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1287                  </svg>1288                </button>1289                <button1290                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1291                  onClick={handleAdd}1292                  aria-label="New entry"1293                >1294                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1295                    <path d="M5.5 1v9M1 5.5h9" />1296                  </svg>1297                </button>1298                <button1299                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1300                  onClick={() => void handleHeaderLock()}1301                  aria-label="Lock vault"1302                >1303                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1304                    <path1305                      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"1306                      stroke="currentColor"1307                      stroke-width="1"1308                      stroke-linecap="round"1309                    />1310                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1311                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1312                  </svg>1313                </button>1314              </div>1315            </header>13161317            <Show when={pendingProNotice() !== null}>1318              <div class="peach-pro-notice-banner">1319                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1320                <button1321                  class="peach-pro-notice-link"1322                  onClick={() => {1323                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1324                    setSettingsInitialSection("license");1325                    setView("settings");1326                    setPendingProNotice(null);1327                  }}1328                >1329                  Learn more →1330                </button>1331                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1332              </div>1333            </Show>13341335            <div class="peach-shell-body">1336              <div class="peach-shell-veil"></div>1337              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1338                <EntryView1339                  entry={selectedEntry()}1340                  currentTabUrl={currentTabUrl()}1341                  entries={entries()}1342                  isPro={proStatus()}1343                  onDelete={handleDelete}1344                  onFieldSaved={() => void loadEntries()}1345                  onEscape={() => { setView("list"); }}1346                  onProGate={(feature) => {1347                    setUpgradeHighlight(feature);1348                    setSettingsInitialSection("license");1349                    setView("settings");1350                  }}1351                />1352              </div>13531354              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1355                <div class="peach-search-bar">1356                  <span class="peach-search-icon">1357                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1358                      <circle cx="5.5" cy="5.5" r="3.75" />1359                      <path d="M8.75 8.75L11.5 11.5" />1360                    </svg>1361                  </span>1362                  <input1363                    class="peach-search-input"1364                    placeholder="search vault..."1365                    autocomplete="off"1366                    aria-label="Search vault entries"1367                    onClick={openList}1368                    onFocus={openList}1369                    readOnly1370                  />1371                  <div class="peach-search-meta">1372                    <span class="peach-search-counter">1373                      {entries().length > 01374                        ? `${selectedIndex() + 1} / ${entries().length}`1375                        : "0 entries"}1376                    </span>1377                    <span class="peach-divider"></span>1378                    <button1379                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1380                      onClick={() => navigate(-1)}1381                      aria-label="Previous entry"1382                      disabled={entries().length === 0}1383                    >1384                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1385                        <path d="M5 1L1 5.5L5 10" />1386                      </svg>1387                    </button>1388                    <button1389                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1390                      onClick={() => navigate(1)}1391                      aria-label="Next entry"1392                      disabled={entries().length === 0}1393                    >1394                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1395                        <path d="M1 1L5 5.5L1 10" />1396                      </svg>1397                    </button>1398                  </div>1399                </div>1400              </section>1401            </div>14021403            {/* Desktop: shown on demand via Show. Native sheet is rendered1404                via Portal below at the document root so its position:fixed1405                isn't trapped by .peach-shell's transform-based animations. */}1406            {/* UI-1 / HV-1b: dismissible remote-mutation alert banners. */}1407            <Show when={syncAlerts().length > 0}>1408              <div class="peach-sync-alerts">1409                <For each={syncAlerts()}>1410                  {(alert, i) => (1411                    <div class="peach-sync-alert">1412                      <span class="peach-sync-alert-text">⚠ {syncAlertText(alert)}</span>1413                      <button1414                        class="peach-sync-alert-dismiss"1415                        type="button"1416                        aria-label="Dismiss"1417                        onClick={() => dismissSyncAlert(i())}1418                      >×</button>1419                    </div>1420                  )}1421                </For>1422              </div>1423            </Show>14241425            <Show when={!isNativePlatform() && view() === "list"}>1426              <VaultView1427                entries={entries()}1428                selectedEntryId={selectedEntry()?.id}1429                currentTabDomain={currentTabDomain()}1430                sortOrder={sortOrder()}1431                searchSeed={listSearchSeed()}1432                searchSeedNonce={listSearchSeedNonce()}1433                onSelectEntry={handleSelectEntry}1434                onSortOrderChange={setSortOrder}1435                onAdd={handleAdd}1436                onClose={() => setView("entry")}1437                onOpenTrash={() => setView("trash")}1438                onDeleteMany={handleDeleteMany}1439              />1440            </Show>1441            <Show when={isNativePlatform() && hasVault()}>1442              <Portal>1443                <div1444                  class="peach-vault-sheet"1445                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1446                  style={(() => {1447                    const live = sheetTranslate();1448                    if (live === null) return undefined;1449                    return { transform: `translateY(${live}px)` };1450                  })()}1451                >1452                  <VaultView1453                    entries={entries()}1454                    selectedEntryId={selectedEntry()?.id}1455                    currentTabDomain={currentTabDomain()}1456                    sortOrder={sortOrder()}1457                    searchSeed={listSearchSeed()}1458                    searchSeedNonce={listSearchSeedNonce()}1459                    isNative={true}1460                    onSelectEntry={handleSelectEntry}1461                    onSortOrderChange={setSortOrder}1462                    onAdd={handleAdd}1463                    onClose={() => setView("entry")}1464                    onOpenTrash={() => setView("trash")}1465                    onDeleteMany={handleDeleteMany}1466                  />1467                </div>1468              </Portal>1469            </Show>1470            <Show when={view() === "settings" || settingsExiting()}>1471              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1472                <SettingsView1473                  entriesCount={entries().length}1474                  breachMonitoring={breachMonitoring()}1475                  lockOnClose={lockOnClose()}1476                  autoLockMinutes={autoLockMinutes()}1477                  trashRetentionDays={trashRetentionDays()}1478                  theme={theme()}1479                  accentColor={accentColor()}1480                  textSize={textSize()}1481                  reduceMotion={reduceMotion()}1482                  isPro={proStatus()}1483                  initialSection={settingsInitialSection()}1484                  upgradeHighlight={upgradeHighlight()}1485                  isExiting={settingsExiting()}1486                  onBreachMonitoringChange={applyBreachMonitoring}1487                  onLockOnCloseChange={applyLockOnClose}1488                  onAutoLockMinutesChange={applyAutoLockMinutes}1489                  onTrashRetentionChange={applyTrashRetention}1490                  onThemeChange={applyTheme}1491                  onAccentChange={applyAccentColor}1492                  onTextSizeChange={applyTextSize}1493                  onReduceMotionChange={applyReduceMotion}1494                  shortcuts={shortcutBindings()}1495                  onShortcutsChange={applyShortcuts}1496                  onLicenseChange={async () => {1497                    // After activation/deactivation: refresh Pro status,1498                    // re-load entries (defensive — signal state can drift if1499                    // the SW briefly restarts during the verify+save round-trip),1500                    // and replay the Pro celebration if this is the first time1501                    // a valid Pro license is seen on this device.1502                    await refreshProStatus();1503                    void loadEntries();1504                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1505                    if ((should as { ok: boolean; data?: boolean }).data === true) {1506                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1507                      setView("pro-celebration");1508                      window.setTimeout(() => setView("settings"), 2500);1509                    }1510                  }}1511                  onBack={() => {1512                    setSettingsExiting(true);1513                    window.setTimeout(() => {1514                      setSettingsExiting(false);1515                      setSettingsInitialSection(null);1516                      setUpgradeHighlight(null);1517                      handleBack();1518                    }, 200);1519                  }}1520                  onImport={() => setView("import")}1521                  onExport={() => setView("export")}1522                  onBreachCheckDone={loadEntries}1523                  onOpenHealth={openHealth}1524                  onOpenSyncPairing={(method) => { setSettingsInitialSection(settingsActiveCard()); setSyncPairIntent(method ?? null); setView("chirp-sync"); }}1525                  onOpenFileImport={handleOpenFileImport}1526                  onOpenPanic={() => setView("panic")}1527                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1528                  onOpenCodexRestore={() => setView("codex-restore")}1529                  onCardChange={setSettingsActiveCard}1530                  onProGate={(feature) => {1531                    setUpgradeHighlight(feature);1532                    setSettingsInitialSection("license");1533                  }}1534                />1535              </Suspense>1536            </Show>1537            <Show when={view() === "codex-generate"}>1538              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1539                <CodexGenerateView1540                  isPro={proStatus()}1541                  onBack={() => setView("settings")}1542                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1543                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1544                  onVaultLocked={() => handleLock()}1545                />1546              </Suspense>1547            </Show>1548            <Show when={view() === "codex-restore"}>1549              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1550                <CodexRestoreView1551                  onBack={() => setView("lock")}1552                  onRestoreSuccess={async () => {1553                    // After restore the vault is unlocked; refresh entries1554                    // and route to the main vault list. handleUnlock is the1555                    // canonical post-unlock setup path.1556                    await handleUnlock();1557                  }}1558                />1559              </Suspense>1560            </Show>1561            <Show when={view() === "chirp-sync"}>1562              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1563                <ChirpSyncView1564                  isPro={proStatus()}1565                  initialPair={syncPairIntent()}1566                  onBack={() => { setSyncPairIntent(null); setView("settings"); }}1567                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1568                />1569              </Suspense>1570            </Show>1571            <Show when={view() === "add"}>1572              <AddView1573                entry={editEntry()}1574                entries={entries()}1575                onBack={handleBack}1576                onSave={handleSave}1577              />1578            </Show>1579            <Show when={view() === "import"}>1580              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1581                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1582              </Suspense>1583            </Show>1584            <Show when={view() === "export"}>1585              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1586                <ExportView onBack={handleExportBack} />1587              </Suspense>1588            </Show>1589            <Show when={view() === "panic"}>1590              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1591                <PanicView1592                  onCancel={() => setView("settings")}1593                  onOpenExport={() => {1594                    setReturnToPanic(true);1595                    setView("export");1596                  }}1597                  onDestroyed={async () => {1598                    clearCanarySuppressions();1599                    setEntries([]);1600                    setSelectedEntry(null);1601                    setEditEntry(undefined);1602                    setHasVault(false);1603                    setOnboarded(false);1604                    setProStatus(false);1605                    setPendingPasskey(null);1606                    setUpgradeHighlight(null);1607                    setSettingsInitialSection(null);1608                    setPendingProNotice(null);1609                    setPendingCelebration(false);1610                    setReturnToPanic(false);1611                    setContentPhase("idle");1612                    setView("lock");1613                  }}1614                />1615              </Suspense>1616            </Show>1617            {/* Health stays mounted while editing an entry from it so1618                computeReused() doesn't rerun on every cancel/back. */}1619            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1620              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1621                <HealthView1622                  entries={entries()}1623                  isPro={proStatus()}1624                  onFixEntry={handleFixEntry}1625                  onBack={() => setView("settings")}1626                  onRefresh={loadEntries}1627                  hidden={view() !== "health"}1628                />1629              </Suspense>1630            </Show>1631            <Show when={view() === "trash"}>1632              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1633                <TrashView1634                  onBack={() => setView("list")}1635                  onRestored={() => void loadEntries()}1636                />1637              </Suspense>1638            </Show>1639            <Show when={showNotes()}>1640              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1641                <NotesMode1642                  notes={entries().filter((e) => e.type === "note")}1643                  initialNoteId={openNoteId()}1644                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1645                  onNoteListChanged={() => void loadEntries()}1646                />1647              </div>1648            </Show>1649            <Show when={restoreView() === "file"}>1650              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1651                <ImportView1652                  mode="onboarding"1653                  replacesExistingVault={true}1654                  onBack={() => setRestoreView(null)}1655                  onImport={async () => {1656                    setRestoreView(null);1657                    await handleUnlock();1658                  }}1659                />1660              </Suspense>1661            </Show>1662            </section>1663            </Show>1664          </Show>1665        </Show>1666      </Show>1667      <Show when={showShortcutsHelp()}>1668        <ShortcutsHelpOverlay1669          bindings={shortcutBindings()}1670          onClose={() => setShowShortcutsHelp(false)}1671        />1672      </Show>1673    </div>1674  );1675}16761677function ShortcutsHelpOverlay(props: {1678  bindings: Record<ShortcutAction, Keybinding>;1679  onClose: () => void;1680}) {1681  return (1682    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1683      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1684        <div class="peach-shortcuts-help-head">1685          <h3>Keyboard shortcuts</h3>1686          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1687        </div>1688        <div class="peach-shortcuts-help-body">1689          <p class="peach-settings-sub-label">ENTRY VIEW</p>1690          <ul>1691            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1692              <li>1693                <span>{d.label}</span>1694                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1695              </li>1696            ))}1697          </ul>1698          <p class="peach-settings-sub-label">ANYWHERE</p>1699          <ul>1700            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1701              <li>1702                <span>{d.label}</span>1703                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1704              </li>1705            ))}1706          </ul>1707        </div>1708      </div>1709    </div>1710  );1711}