App.tsx

67.8 KB · raw

1import { createEffect, createMemo, createSignal, 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);134  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");135  const [theme, setTheme] = createSignal<"dark" | "light">("dark");136  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");137  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);138  const [lockOnClose, setLockOnClose] = createSignal(true);139  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);140  const [breachMonitoring, setBreachMonitoring] = createSignal(true);141  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);142  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);143  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);144  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);145  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);146  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");147  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");148  // Cached Pro status — synchronous for render paths. Background's149  // GET_LICENSE is async, but render-time reads of isPro() must not block.150  // Refreshed at boot, after activate/deactivate, and whenever the popup151  // re-opens onto a stored license that has changed via another window.152  const [proStatus, setProStatus] = createSignal(false);153  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);154  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");155  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);156  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");157  const [listSearchSeed, setListSearchSeed] = createSignal("");158  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);159  const [pendingCelebration, setPendingCelebration] = createSignal(false);160  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);161  // True while Panic Step 1 has bounced the user out to Export. When Export's162  // onBack fires we return to Panic instead of Settings so the user keeps the163  // destruction context they came from.164  const [returnToPanic, setReturnToPanic] = createSignal(false);165  // The view to return to when the add/edit view is dismissed. Normally "entry"166  // but "health" when the user arrives via the fix-entry path from Vault Health.167  const [editBackView, setEditBackView] = createSignal<View>("entry");168  const [settingsExiting, setSettingsExiting] = createSignal(false);169  const [showNotes, setShowNotes] = createSignal(false);170  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);171  // Set on popup boot when peach_recovery_pending flag is found in session172  // storage — instructs LockView to skip the unlock UI and open the recovery173  // words confirmation surface instead. Cleared via handleUnlock once the174  // user has typed the 3 confirmation words.175  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);176177  let contentPhaseTimer: number | undefined;178  // Set when the popup was opened from the inline "Open Peach to unlock" button.179  // handleUnlock() closes the popup after unlock so the user returns to the page.180  let openedForInlineUnlock = false;181182  function applyAccent(name: AccentColorName) {183    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;184    const hex = color.hex;185    document.documentElement.style.setProperty("--peach-accent", hex);186    // Ambient surface variables — derived from the accent so surfaces shift187    // subtly toward the accent hue rather than staying fixed warm-brown.188    document.documentElement.style.setProperty("--peach-glow", hex + "2A");189    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");190    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");191  }192193  createEffect(() => {194    applyAccent(accentColor());195  });196197  createEffect(() => {198    document.documentElement.classList.toggle("light", theme() === "light");199    document.body.classList.toggle("light", theme() === "light");200  });201202  createEffect(() => {203    document.documentElement.setAttribute("data-text-size", textSize());204  });205206  createEffect(() => {207    if (reduceMotion()) {208      document.documentElement.setAttribute("data-motion", "reduce");209    } else {210      document.documentElement.removeAttribute("data-motion");211    }212  });213214  const selectedIndex = createMemo(() => {215    const currentId = selectedEntry()?.id;216    if (!currentId) return entries().length > 0 ? 0 : -1;217    return entries().findIndex((entry) => entry.id === currentId);218  });219220  async function applyAccentColor(name: AccentColorName) {221    applyAccent(name);222    setAccentColor(name);223    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });224  }225226  async function applyTheme(t: "dark" | "light") {227    setTheme(t);228    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });229  }230231  async function applyTextSize(size: "small" | "medium" | "large") {232    setTextSize(size);233    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });234  }235236  async function applyReduceMotion(enabled: boolean) {237    setReduceMotion(enabled);238    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });239  }240241  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload242  // small and lets future default updates land for actions the user hasn't243  // touched. Settings sends us the full active map; we filter and store.244  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {245    setShortcutBindings(active);246    const overrides: Record<string, Keybinding> = {};247    for (const action of Object.keys(active) as ShortcutAction[]) {248      const a = active[action];249      const d = DEFAULT_BINDINGS[action];250      const same = a.key === d.key251        && Boolean(a.ctrl)  === Boolean(d.ctrl)252        && Boolean(a.meta)  === Boolean(d.meta)253        && Boolean(a.shift) === Boolean(d.shift)254        && Boolean(a.alt)   === Boolean(d.alt);255      if (!same) overrides[action] = a;256    }257    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });258  }259260  async function applyLockOnClose(enabled: boolean) {261    setLockOnClose(enabled);262    await sendMessage({263      type: "UPDATE_SETTINGS",264      payload: { lockOnClose: enabled },265    });266  }267268  async function applyAutoLockMinutes(minutes: number) {269    setAutoLockMinutes(minutes);270    await sendMessage({271      type: "UPDATE_SETTINGS",272      payload: { autoLockMinutes: minutes },273    });274  }275276  async function applyBreachMonitoring(enabled: boolean) {277    setBreachMonitoring(enabled);278    await sendMessage({279      type: "UPDATE_SETTINGS",280      payload: { breachMonitoring: enabled },281    });282  }283284  onMount(async () => {285    // Resolve the active tab in parallel with the unlock/has-vault queries —286    // openVault()'s smart selection picks the entry matching currentTabDomain,287    // so it must be populated before openVault runs. Previously refreshCurrentTab288    // ran after openVault, leaving popups that booted already-unlocked falling289    // back to loadedEntries[0] instead of the domain match.290    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([291      sendMessage({ type: "IS_UNLOCKED" }),292      sendMessage({ type: "HAS_VAULT" }),293      refreshCurrentTab(),294      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),295    ]);296    const unlocked = Boolean(297      (unlockResponse as { ok: boolean; data?: boolean }).data298    );299    const vaultExists = Boolean(300      (vaultResponse as { ok: boolean; data?: boolean }).data301    );302    const shouldCelebrate = Boolean(303      (celebrationResponse as { ok: boolean; data?: boolean }).data304    );305    setHasVault(vaultExists);306    // Onboarding gate — show once on first install, never again. Existing307    // users (vaultExists) are auto-marked onboarded so they skip the flow308    // even on the very first popup open after this feature ships.309    try {310      const onboarded = await storageGet("peach_onboarded");311      const seen = onboarded === "true";312      if (vaultExists && !seen) {313        await storageSet("peach_onboarded", "true");314        setOnboarded(true);315      } else {316        setOnboarded(seen);317      }318    } catch {319      // storage unavailable — default to onboarded so we never block boot320      setOnboarded(true);321    }322    await Promise.all([restoreSettings(), refreshProStatus()]);323324    // Mark played before any animation so a crash mid-sequence never replays it325    if (shouldCelebrate) {326      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });327    }328329    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the330    // background ignores it when no mobile hosts are paired or while331    // another sync is already in flight.332    if (unlocked && vaultExists) {333      void sendMessage({334        type: "TRIGGER_SYNC",335        payload: { reason: "foreground" },336      });337    }338339    // If the user created a vault but hasn't yet confirmed their recovery340    // words, route back to the recovery-words screen instead of opening the341    // entries view. The flag lives in chrome.storage.local so it survives342    // both popup close (SW suppresses lock-on-close) and full browser343    // restart (handleUnlock checks the same flag after a fresh password344    // unlock). Cleared when confirmation succeeds.345    let recoveryPending = false;346    try {347      const out = await chrome.storage.local?.get("peach_recovery_pending");348      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";349    } catch { /* best-effort */ }350351    // If this popup was opened from the inline "Open Peach to unlock" button,352    // the background set a session flag. Read and clear it so handleUnlock()353    // can close the popup after unlock and return the user to the page.354    if (chrome.storage.session) {355      try {356        const s = await chrome.storage.session.get("peach_inline_unlock");357        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {358          openedForInlineUnlock = true;359          await chrome.storage.session.remove("peach_inline_unlock");360        }361      } catch { /* best-effort */ }362    }363364    // Native: closing the app before recovery-words confirmation means the365    // user didn't finish vault creation. Throw the partial vault away and366    // restart onboarding rather than asking them to unlock a vault they367    // never finished creating. Desktop keeps the existing "unlock to368    // resume" flow because closing the popup there is much more casual.369    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {370      try {371        await chrome.storage.local?.remove([372          "peach_vault_a",373          "peach_vault_b",374          "peach_recovery_pending",375          "peach_onboarded",376          "peach_vault_history",377        ]);378      } catch { /* best-effort */ }379      setHasVault(false);380      setOnboarded(false);381      setView("lock");382      setBootState("ready");383      return;384    }385386    if (recoveryPending && unlocked) {387      // forceRecoveryWords overrides LockView's hasVault gate so the388      // recovery surface renders even though the vault now exists.389      setForceRecoveryWords(true);390      setView("lock");391    } else if (unlocked && vaultExists) {392      await openVault(undefined, shouldCelebrate);393      if (shouldCelebrate) {394        setView("pro-celebration");395        window.setTimeout(() => setView("entry"), 2500);396      }397    } else if (shouldCelebrate) {398      setPendingCelebration(true);399    }400401    await refreshPendingPasskey();402403    // Track tab changes so smart sort stays current404    const handleTabActivated = () => { void refreshCurrentTab(); };405    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {406      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();407    };408    try {409      chrome.tabs.onActivated.addListener(handleTabActivated);410      chrome.tabs.onUpdated.addListener(handleTabUpdated);411      onCleanup(() => {412        chrome.tabs.onActivated.removeListener(handleTabActivated);413        chrome.tabs.onUpdated.removeListener(handleTabUpdated);414      });415    } catch {416      // tabs permission may not be available in all contexts417    }418419    setBootState("ready");420421    // Deep-link: ?codex=pdf opens a detached window straight into the422    // Codex restore flow with auto-picked PDF. The action popup can't host423    // a file dialog without dismissing itself, so this is the only way the424    // PDF import path survives. See CodexRestoreView.openPdfPicker().425    try {426      const route = new URLSearchParams(window.location.search).get("codex");427      if (route === "pdf" || route === "restore") {428        setView("codex-restore");429      }430    } catch {431      // location.search unavailable — ignore.432    }433434    // Check for pending session-storage notices from the background.435    if (chrome.storage.session) {436      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as437        Record<string, { feature?: string } | undefined>;438      if (session.pendingProGate?.feature) {439        await chrome.storage.session.remove("pendingProGate");440        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);441        setSettingsInitialSection("license");442        setView("settings");443      } else if (session.pendingProNotice?.feature) {444        await chrome.storage.session.remove("pendingProNotice");445        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });446      }447    }448449    // Warm the lazy-module cache so the Suspense fallback never shows for450    // locally-bundled extension views. Without this, the first navigation to451    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which452    // covers the shell and absorbs clicks on the header.453    void Promise.all([454      import("./views/Settings").catch(() => {}),455      import("./views/Import").catch(() => {}),456      import("./views/Export").catch(() => {}),457      import("./views/Health").catch(() => {}),458      import("./views/TrashView").catch(() => {}),459    ]);460461    // Lock-on-close via a persistent port. sendMessage in pagehide is462    // unreliable — the popup context tears down before the message lands.463    // The SW's onConnect listener locks when this port disconnects.464    let popupPort: chrome.runtime.Port | null = null;465    try {466      popupPort = chrome.runtime.connect({ name: "popup" });467    } catch { /* extension context invalidated — ignore */ }468    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });469470    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only471    // reliable signal is appStateChange — setTimeout is killed when the OS472    // backgrounds the app. We measure elapsed background time on resume.473    if (isNativePlatform()) {474      let backgroundedAt: number | null = null;475476      const CapApp = nativePlugin<{477        addListener: (478          ev: string,479          cb: (s: { isActive: boolean }) => void,480        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };481      }>("App");482      if (CapApp?.addListener) {483        const sub = CapApp.addListener(484          "appStateChange",485          ({ isActive }: { isActive: boolean }) => {486            if (!isActive) {487              backgroundedAt = Date.now();488              return;489            }490            if (backgroundedAt !== null && autoLockMinutes() > 0) {491              const elapsed = Date.now() - backgroundedAt;492              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();493            }494            backgroundedAt = null;495          }496        );497        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.498        onCleanup(() => {499          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});500        });501      }502503      // L12/COR-011: foreground idle autolock. appStateChange only fires when504      // the OS backgrounds the app — if the user idles with the screen on,505      // chrome.alarms is no-op'd in Capacitor so the vault would stay open506      // indefinitely. Poll every 30s and lock if elapsed since last user507      // interaction exceeds autoLockMinutes.508      let lastUserActivityAt = Date.now();509      const bumpActivity = () => { lastUserActivityAt = Date.now(); };510      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;511      for (const ev of ACTIVITY_EVENTS) {512        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });513      }514      const idleLockInterval = setInterval(() => {515        const minutes = autoLockMinutes();516        if (!minutes || minutes <= 0) return;517        const elapsed = Date.now() - lastUserActivityAt;518        if (elapsed >= minutes * 60_000) {519          lastUserActivityAt = Date.now();520          handleHeaderLock();521        }522      }, 30_000);523      onCleanup(() => {524        clearInterval(idleLockInterval);525        for (const ev of ACTIVITY_EVENTS) {526          document.removeEventListener(ev, bumpActivity, { capture: true });527        }528      });529530      // mDNS peer-discovery trigger. Register onCleanup synchronously so531      // SolidJS captures it within the reactive owner — onCleanup inside a532      // .then() callback may miss the capture window and leak the listener.533      let stopMDNS: () => void = () => undefined;534      onCleanup(() => stopMDNS());535      if (isNativePlatform()) {536        // Android runs the background/sync dispatcher in-process with the537        // popup, so the production runner has to be registered from the538        // UI bootstrap path instead of the MV3 service-worker entry.539        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>540          import("../background/chirp-sync-runner").then(({ productionSyncRunner }) => {541            setSyncRunner(productionSyncRunner);542            void hydratePersistedSyncState();543          })544        );545      }546      void import("./chirp-pair-capacitor").then(({ startMDNSListener }) => {547        stopMDNS = startMDNSListener();548      });549    }550551    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale552    // entries instead of waiting for the next GET_ENTRIES round-trip.553    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {554      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();555      if (msg?.type === "PRO_GATE_TRIGGERED") {556        setUpgradeHighlight(msg.payload?.feature ?? null);557        setSettingsInitialSection("license");558        setView("settings");559      }560    };561    chrome.runtime.onMessage.addListener(handleRuntimeMessage);562    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));563564    // Android hardware/gesture back. MainActivity fires peach:back; the popup565    // decides what "back" means per surface. Lock+no-vault is the common case566    // — return to onboarding rather than letting the OS dismiss the activity.567    const handlePeachBack = () => {568      // Notes mode captures back first569      if (showNotes()) {570        setShowNotes(false);571        setOpenNoteId(undefined);572        return;573      }574      const v = view();575      if (v === "lock" && !hasVault() && onboarded()) {576        setOnboarded(false);577        return;578      }579      if (v === "list") { setView("entry"); return; }580      if (v === "settings") {581        window.dispatchEvent(new Event("peach:settings-back"));582        return;583      }584      if (v === "import" || v === "health") { setView("settings"); return; }585      if (v === "export") { handleExportBack(); return; }586      if (v === "add") { handleBack(); return; }587      if (v === "chirp-sync") { setView("settings"); return; }588    };589    window.addEventListener("peach:back", handlePeachBack);590    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));591592    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that593    // peeks from the bottom (search bar handle visible) and drags up to fill594    // the screen. dragOffset is the LIVE finger offset during a drag, in px,595    // 0 when no drag in progress. The wrapper element computes transform =596    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.597    if (isNativePlatform()) {598      let touchStartY = 0;599      let touchStartX = 0;600      let lastY = 0;601      let lastT = 0;602      let dragging = false;603      let captured = false;604      const HORIZONTAL_TOLERANCE = 16;605      const ACTIVATION_DY = 8;606      const PEEK_PX = 60;607608      const onTouchStart = (e: TouchEvent) => {609        const t = e.touches[0];610        if (!t) return;611        const v = view();612        if (v !== "entry" && v !== "list") return;613        // Entry view: only intercept drags starting in the bottom 40%.614        // List view: intercept drags starting in the top 35% (the search/handle row).615        const inBand = v === "entry"616          ? t.clientY > window.innerHeight * 0.6617          : t.clientY < window.innerHeight * 0.35;618        if (!inBand) return;619        touchStartY = lastY = t.clientY;620        touchStartX = t.clientX;621        lastT = e.timeStamp;622        dragging = true;623        captured = false;624      };625626      const onTouchMove = (e: TouchEvent) => {627        if (!dragging) return;628        const t = e.touches[0];629        if (!t) return;630        const dy = t.clientY - touchStartY;631        const dx = Math.abs(t.clientX - touchStartX);632633        if (!captured) {634          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {635            // Looks like a horizontal swipe — release.636            dragging = false;637            return;638          }639          if (Math.abs(dy) < ACTIVATION_DY) return;640          captured = true;641        }642643        // Translate the sheet by dy from its rest (peek) position. Peek is644        // (viewport height - PEEK_PX). Open is 0.645        const v = view();646        const restClosed = window.innerHeight - PEEK_PX;647        const baseTranslate = v === "list" ? 0 : restClosed;648        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));649        setSheetTranslate(next);650        lastY = t.clientY;651        lastT = e.timeStamp;652      };653654      const onTouchEnd = (e: TouchEvent) => {655        if (!dragging) { return; }656        const t = e.changedTouches[0];657        const elapsed = Math.max(1, e.timeStamp - lastT);658        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms659        const wasCaptured = captured;660        dragging = false;661        captured = false;662        const v = view();663664        if (!wasCaptured) {665          // Tap in the peek strip while in entry view → open the vault list.666          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");667          setSheetTranslate(null);668          return;669        }670671        const restClosed = window.innerHeight - PEEK_PX;672        const current = sheetTranslate() ?? restClosed;673674        // Snap rules:675        //   - Strong upward velocity → open676        //   - Strong downward velocity → close677        //   - Otherwise snap to whichever rest is closer678        let nextOpen: boolean;679        if (velocity < -0.05) nextOpen = true;680        else if (velocity > 0.05) nextOpen = false;681        else nextOpen = current < restClosed * 0.5;682683        if (nextOpen && v !== "list") setView("list");684        if (!nextOpen && v !== "entry") setView("entry");685        // Release the live offset so CSS transition handles the snap.686        setSheetTranslate(null);687      };688689      document.addEventListener("touchstart", onTouchStart, { passive: true });690      document.addEventListener("touchmove",  onTouchMove,  { passive: true });691      document.addEventListener("touchend",   onTouchEnd,   { passive: true });692      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });693      onCleanup(() => {694        document.removeEventListener("touchstart", onTouchStart);695        document.removeEventListener("touchmove",  onTouchMove);696        document.removeEventListener("touchend",   onTouchEnd);697      });698    }699700    // Action handlers — keyed by ShortcutAction. The dispatcher below tests701    // each binding against the event and runs the matching handler. New702    // shortcuts only need an entry here; the binding is data, not code.703    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {704      copy_password: () => {705        const entry = selectedEntry();706        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });707      },708      copy_username: () => {709        const entry = selectedEntry();710        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });711      },712      copy_totp: () => {713        const entry = selectedEntry();714        if (!entry?.totp) return;715        try {716          const { code } = generateTOTP(entry.totp);717          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });718        } catch { /* invalid TOTP secret — silent */ }719      },720      new_entry: () => handleAdd(),721      edit_entry: () => {722        const entry = selectedEntry();723        // Passkey-only entries have nothing user-editable in the Add view; the724        // passkey credential itself is opaque. Skip the edit action for them.725        if (!entry || isPasskeyOnly(entry)) return;726        setEditEntry(entry);727        setView("add");728      },729      delete_entry: () => {730        if (selectedEntry()) void handleDelete();731      },732      lock_vault: () => { void handleHeaderLock(); },733      search: () => openList(),734      nav_prev: () => navigate(-1),735      nav_next: () => navigate(1),736      jump_vault: () => setView("entry"),737      jump_settings: () => setView("settings"),738      show_help: () => setShowShortcutsHelp(true),739    };740741    // Actions that are MEANINGFUL only on the entry-detail view. Outside742    // that scope the binding is dormant — pressing C while on Settings743    // does nothing rather than awkwardly copying from a now-stale entry.744    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([745      "copy_password", "copy_username", "copy_totp",746      "edit_entry", "delete_entry", "nav_prev", "nav_next",747    ]);748749    const handleGlobalKeydown = (e: KeyboardEvent) => {750      const v = view();751      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"752        || (e.target as HTMLElement)?.tagName === "TEXTAREA"753        || (e.target as HTMLElement)?.isContentEditable;754      const isPrintableSearchKey =755        e.key.length === 1 &&756        !e.ctrlKey &&757        !e.metaKey &&758        !e.altKey;759760      // No input during the pro celebration sequence761      if (v === "pro-celebration") return;762763      // Help dialog: Escape closes it; eat the keypress so it doesn't764      // also navigate away from the underlying view.765      if (showShortcutsHelp()) {766        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }767        return;768      }769770      // ── Escape — fixed binding (not user-customizable) ───────771      if (e.key === "Escape") {772        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }773        if (v === "list") { setView("entry"); return; }774        if (v === "settings" || v === "add") { handleBack(); return; }775        if (v === "import" || v === "health") { setView("settings"); return; }776        if (v === "export") { handleExportBack(); return; }777        if (v === "chirp-sync") { setView("settings"); return; }778      }779780      // Bindings-driven dispatch. Single-key letter bindings without781      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is782      // inside an input, so users can type into search/forms normally.783      const bindings = shortcutBindings();784      for (const action of Object.keys(bindings) as ShortcutAction[]) {785        const binding = bindings[action];786        if (!matchKeybinding(e, binding)) continue;787        // Single-key letter bindings need the input-focus guard. Bindings788        // with any modifier are safe — Ctrl+L doesn't conflict with typing.789        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;790        if (!hasMod && binding.key.length === 1 && inInput) return;791        if (ENTRY_SCOPED.has(action) && v !== "entry") return;792        e.preventDefault();793        SHORTCUT_HANDLERS[action]?.();794        return;795      }796797      // Type-to-search: in entry view, any printable key not consumed by a798      // shortcut above primes the list search seed and opens the list.799      // Kept outside the bindings table because it's a behavior, not a800      // discrete action — every printable character can trigger it.801      if (v === "entry" && !inInput && isPrintableSearchKey) {802        e.preventDefault();803        primeListSearch(e.key);804        return;805      }806    };807    window.addEventListener("keydown", handleGlobalKeydown);808    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));809810    const handleStorageChanged = (811      changes: Record<string, chrome.storage.StorageChange>,812      areaName: string813    ) => {814      if (areaName !== "session") return;815      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {816        return;817      }818      void refreshPendingPasskey();819    };820    chrome.storage.onChanged.addListener(handleStorageChanged);821    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));822  });823824  async function refreshCurrentTab() {825    try {826      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });827      const url = tab?.url ?? tab?.pendingUrl ?? "";828      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");829      // Skip extension/internal URLs — adding chrome://, about:, or830      // chrome-extension:// to a vault entry is never what the user wants.831      const isWebUrl = /^https?:\/\//i.test(url);832      setCurrentTabUrl(isWebUrl ? url : "");833    } catch {834      setCurrentTabDomain("");835      setCurrentTabUrl("");836    }837  }838839  async function refreshPendingPasskey() {840    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });841    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);842  }843844  async function refreshProStatus() {845    const res = await sendMessage({ type: "GET_LICENSE" });846    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;847    setProStatus(Boolean(data?.valid && data?.plan === "pro"));848  }849850  async function restoreSettings() {851    const res = await sendMessage({ type: "GET_SETTINGS" });852    const s = (res as { ok: boolean; data?: any }).data ?? {};853    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {854      setAccentColor(s.accentColor as AccentColorName);855    }856    setTheme(s.theme === "light" ? "light" : "dark");857    if (s.textSize === "small" || s.textSize === "large") {858      setTextSize(s.textSize);859    } else {860      setTextSize("medium");861    }862    setReduceMotion(s.reduceMotion === true);863    setLockOnClose(s.lockOnClose !== false);864    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);865    setBreachMonitoring(s.breachMonitoring !== false);866    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);867    setShortcutBindings(getActiveBindings(s.shortcuts));868  }869870  async function applyTrashRetention(days: number) {871    setTrashRetentionDays(days);872    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });873  }874875  function primeListSearch(seed: string) {876    setListSearchSeed(seed);877    setListSearchSeedNonce((value) => value + 1);878    openList();879  }880881  // Returns null when it detected a dead service worker and triggered handleLock().882  // Callers that need to abort (e.g. openVault) check for null rather than relying883  // on view() state, which may already be "lock" during normal startup flows.884  async function loadEntries(): Promise<VaultEntry[] | null> {885    const response = await sendMessage({ type: "GET_ENTRIES" });886    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };887888    // If the service worker was killed and restarted (MV3 workers sleep), the889    // vault will be locked again — or the worker may not respond at all.890    // In either case, send the user to the lock screen rather than silently891    // showing an empty vault (which looks like data loss).892    if (!res.ok) {893      if (894        res.error === "vault_locked" ||895        res.error === "SERVICE_WORKER_UNAVAILABLE" ||896        (typeof res.error === "string" && res.error.includes("locked"))897      ) {898        handleLock();899        return null; // signal emergency lock to callers900      }901      return [];902    }903904    const loadedEntries = res.data ?? [];905    setEntries(loadedEntries);906907    const currentId = selectedEntry()?.id;908    if (currentId) {909      setSelectedEntry(910        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null911      );912    }913914    return loadedEntries;915  }916917  async function openVault(preferredEntryId?: string, skipViewSet = false) {918    // Purge expired trash entries on each vault open919    const retDays = trashRetentionDays();920    if (retDays > 0) {921      void sendMessage({922        type: "PURGE_EXPIRED_TRASH",923        payload: { retentionMs: retDays * 86_400_000 },924      });925    }926927    const loadedEntries = await loadEntries();928929    // null means loadEntries() triggered an emergency lock (service worker died).930    // Don't override it by setting view back to "entry" with an empty vault.931    if (loadedEntries === null) return;932933    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry934    let nextSelectedEntry: VaultEntry | null = null;935    if (preferredEntryId) {936      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;937    }938    if (!nextSelectedEntry) {939      const tabDomain = currentTabDomain();940      if (tabDomain) {941        nextSelectedEntry = loadedEntries.find((e) => {942          if (e.type === "login") {943            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;944            for (const extra of e.additionalUrls ?? []) {945              if ((extractDomain(extra) ?? "") === tabDomain) return true;946            }947            return false;948          }949          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;950          return false;951        }) ?? null;952      }953    }954    nextSelectedEntry ??= loadedEntries[0] ?? null;955956    setSelectedEntry(nextSelectedEntry);957    setEditEntry(undefined);958    setContentTransitioning(false);959    setContentPhase("enter");960    queueContentIdle();961    if (!skipViewSet) setView("entry");962  }963964  async function handleUnlock() {965    // If the user previously created a vault but hadn't yet confirmed their966    // recovery words (and the browser was closed before they could), the967    // peach_recovery_pending flag is still set in storage.local. Re-route968    // back to the recovery surface so they finish the confirmation step969    // before reaching the entries view — the words can be re-derived now970    // that the vault is unlocked again.971    let recoveryPending = false;972    try {973      const out = await chrome.storage.local?.get("peach_recovery_pending");974      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";975    } catch { /* best-effort */ }976    if (recoveryPending) {977      setForceRecoveryWords(true);978      setView("lock");979      triggerPipPulse();980      await restoreSettings();981      return;982    }983    setHasVault(true);984    triggerPipPulse();985    await restoreSettings();986    const celebrating = pendingCelebration();987    if (celebrating) {988      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });989      setPendingCelebration(false);990    }991    await openVault(undefined, celebrating);992    if (celebrating) {993      setView("pro-celebration");994      window.setTimeout(() => setView("entry"), 2500);995    }996    // Popup was opened from the inline "Open Peach to unlock" button — close it997    // now so the user lands back on the page with the autofill selector ready.998    if (openedForInlineUnlock) {999      openedForInlineUnlock = false;1000      window.close();1001    }1002  }10031004  function handleSelectEntry(entry: VaultEntry) {1005    if (entry.type === "note") {1006      setOpenNoteId(entry.id);1007      setShowNotes(true);1008      return;1009    }1010    setSelectedEntry(entry);1011    setContentTransitioning(false);1012    setContentPhase("enter");1013    queueContentIdle();1014    setView("entry");1015  }10161017  function handleAdd() {1018    setEditEntry(undefined);1019    setView("add");1020  }10211022  async function handleDelete() {1023    const entry = selectedEntry();1024    if (!entry) return;1025    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1026    const loadedEntries = await loadEntries() ?? [];1027    setSelectedEntry(loadedEntries[0] ?? null);1028    setView("entry");1029  }10301031  async function handleDeleteMany(ids: string[]) {1032    for (const id of ids) {1033      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1034    }1035    const loadedEntries = await loadEntries() ?? [];1036    // If the currently selected entry was among the deleted, move to first1037    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1038    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1039  }10401041  async function handleSave(savedEntry?: VaultEntry) {1042    await openVault(savedEntry?.id);1043  }10441045  function handleBack() {1046    const dest = editBackView();1047    setEditBackView("entry");1048    setEditEntry(undefined);1049    setView(dest);1050  }10511052  function handleExportBack() {1053    if (returnToPanic()) {1054      setReturnToPanic(false);1055      setView("panic");1056      return;1057    }1058    setView("settings");1059  }10601061  function handleLock() {1062    clearCanarySuppressions();1063    setEntries([]);1064    setSelectedEntry(null);1065    setEditEntry(undefined);1066    setContentPhase("idle");1067    setView("lock");1068  }10691070  function handleHeaderLock() {1071    // Lock the UI immediately — do not wait for the service worker. If the SW1072    // is dead or slow, the 5s sendMessage timeout would create a dead-click1073    // window. The SW will lock on its next wake regardless.1074    handleLock();1075    void sendMessage({ type: "LOCK" });1076  }10771078  function navigate(dir: number) {1079    const allEntries = entries();1080    if (allEntries.length === 0) return;1081    const currentIndex = selectedIndex();1082    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1083    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1084    setSelectedEntry(allEntries[nextIndex]);1085    setContentPhase("enter");1086    queueContentIdle();1087  }10881089  function openList() {1090    setView("list");1091  }10921093  function openHealth() {1094    setEditEntry(undefined);1095    setView("health");1096  }10971098  function handleOpenFileImport() {1099    setRestoreView("file");1100  }11011102  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11031104  function handleFixEntry(entry: VaultEntry) {1105    setSelectedEntry(entry);1106    // Passkey-only entries have no editable surface — drop into view mode1107    // instead of opening the Add editor.1108    if (isPasskeyOnly(entry)) {1109      setView("entry");1110      return;1111    }1112    setEditBackView(view()); // preserve caller view so back returns here1113    setEditEntry(entry);1114    setView("add");1115  }11161117  const isLockedView = () => view() === "lock";11181119  async function handleApprovePendingPasskey() {1120    const pending = pendingPasskey();1121    if (!pending) return;1122    if (pending.browser === "firefox" && pending.type === "create") {1123      // Firefox path: popup itself runs navigator.credentials.create. The1124      // background never approved/rejected anything — it just stashed1125      // intent. After the popup-driven flow resolves (success or cancel),1126      // clear the pending key so the popup doesn't re-show this on next open.1127      const { createFirefoxPasskey } = await import("./firefox-passkey");1128      const result = await createFirefoxPasskey(pending);1129      if (!result.ok) {1130        console.warn("Peach Firefox passkey create failed:", result.error);1131      }1132      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1133      setPendingPasskey(null);1134      void loadEntries();1135      window.close();1136      return;1137    }1138    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1139    window.close();1140  }11411142  async function handleDenyPendingPasskey() {1143    const pending = pendingPasskey();1144    if (!pending) return;1145    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1146    window.close();1147  }11481149  function queueContentIdle(after?: () => void) {1150    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1151    contentPhaseTimer = window.setTimeout(() => {1152      setContentPhase("idle");1153      after?.();1154    }, ENTRY_TRANSITION_SETTLE_MS);1155  }11561157  return (1158    <div class="popup-root peach-theme">1159      <Show when={bootState() === "ready"}>1160        <Show1161          when={!pendingPasskey()}1162          fallback={1163            <PasskeyApprovalView1164              type={pendingPasskey()!.type}1165              rpName={pendingPasskey()!.rpName}1166              rpId={pendingPasskey()!.rpId}1167              userName={pendingPasskey()!.userName}1168              userDisplayName={pendingPasskey()!.userDisplayName}1169              onApprove={handleApprovePendingPasskey}1170              onDeny={handleDenyPendingPasskey}1171            />1172          }1173        >1174          <Show1175            when={!isLockedView()}1176            fallback={1177              <Show1178                when={onboarded() || hasVault()}1179                fallback={1180                  <Onboarding1181                    onComplete={() => { setOnboarded(true); }}1182                  />1183                }1184              >1185                <LockView1186                  hasVault={hasVault()}1187                  ready={bootState() === "ready"}1188                  isPro={proStatus()}1189                  forceRecoveryWords={forceRecoveryWords()}1190                  onUnlock={() => {1191                    // RecoveryWordDisplay clears the storage flag before1192                    // calling onDone, so handleUnlock will see no pending1193                    // confirmation and proceed through the normal path.1194                    if (forceRecoveryWords()) setForceRecoveryWords(false);1195                    return handleUnlock();1196                  }}1197                  onBackToOnboarding={1198                    !hasVault()1199                      ? () => setOnboarded(false)1200                      : undefined1201                  }1202                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1203                />1204              </Show>1205            }1206          >1207            <Show1208              when={view() !== "pro-celebration"}1209              fallback={<ProCelebration />}1210            >1211            <section1212              id="hd-shell"1213              class="peach-shell peach-theme"1214              data-surface="extension"1215            >1216            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1217              <PeachWordmark unlocked />1218              <div class="peach-chrome-actions">1219                <button1220                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1221                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1222                  aria-label="Notes"1223                  title="Notes"1224                >1225                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1226                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1227                    <line x1="4" y1="5" x2="10" y2="5" />1228                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1229                    <line x1="4" y1="10" x2="7" y2="10" />1230                  </svg>1231                </button>1232                <button1233                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1234                  onClick={() => setView("settings")}1235                  aria-label="Settings"1236                >1237                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1238                    <path1239                      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"1240                      stroke="currentColor"1241                      stroke-width="0.9"1242                    />1243                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1244                  </svg>1245                </button>1246                <button1247                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1248                  onClick={handleAdd}1249                  aria-label="New entry"1250                >1251                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1252                    <path d="M5.5 1v9M1 5.5h9" />1253                  </svg>1254                </button>1255                <button1256                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1257                  onClick={() => void handleHeaderLock()}1258                  aria-label="Lock vault"1259                >1260                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1261                    <path1262                      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"1263                      stroke="currentColor"1264                      stroke-width="1"1265                      stroke-linecap="round"1266                    />1267                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1268                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1269                  </svg>1270                </button>1271              </div>1272            </header>12731274            <Show when={pendingProNotice() !== null}>1275              <div class="peach-pro-notice-banner">1276                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1277                <button1278                  class="peach-pro-notice-link"1279                  onClick={() => {1280                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1281                    setSettingsInitialSection("license");1282                    setView("settings");1283                    setPendingProNotice(null);1284                  }}1285                >1286                  Learn more →1287                </button>1288                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1289              </div>1290            </Show>12911292            <div class="peach-shell-body">1293              <div class="peach-shell-veil"></div>1294              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1295                <EntryView1296                  entry={selectedEntry()}1297                  currentTabUrl={currentTabUrl()}1298                  entries={entries()}1299                  isPro={proStatus()}1300                  onDelete={handleDelete}1301                  onFieldSaved={() => void loadEntries()}1302                  onEscape={() => { setView("list"); }}1303                  onProGate={(feature) => {1304                    setUpgradeHighlight(feature);1305                    setSettingsInitialSection("license");1306                    setView("settings");1307                  }}1308                />1309              </div>13101311              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1312                <div class="peach-search-bar">1313                  <span class="peach-search-icon">1314                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1315                      <circle cx="5.5" cy="5.5" r="3.75" />1316                      <path d="M8.75 8.75L11.5 11.5" />1317                    </svg>1318                  </span>1319                  <input1320                    class="peach-search-input"1321                    placeholder="search vault..."1322                    autocomplete="off"1323                    aria-label="Search vault entries"1324                    onClick={openList}1325                    onFocus={openList}1326                    readOnly1327                  />1328                  <div class="peach-search-meta">1329                    <span class="peach-search-counter">1330                      {entries().length > 01331                        ? `${selectedIndex() + 1} / ${entries().length}`1332                        : "0 entries"}1333                    </span>1334                    <span class="peach-divider"></span>1335                    <button1336                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1337                      onClick={() => navigate(-1)}1338                      aria-label="Previous entry"1339                      disabled={entries().length === 0}1340                    >1341                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1342                        <path d="M5 1L1 5.5L5 10" />1343                      </svg>1344                    </button>1345                    <button1346                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1347                      onClick={() => navigate(1)}1348                      aria-label="Next entry"1349                      disabled={entries().length === 0}1350                    >1351                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1352                        <path d="M1 1L5 5.5L1 10" />1353                      </svg>1354                    </button>1355                  </div>1356                </div>1357              </section>1358            </div>13591360            {/* Desktop: shown on demand via Show. Native sheet is rendered1361                via Portal below at the document root so its position:fixed1362                isn't trapped by .peach-shell's transform-based animations. */}1363            <Show when={!isNativePlatform() && view() === "list"}>1364              <VaultView1365                entries={entries()}1366                selectedEntryId={selectedEntry()?.id}1367                currentTabDomain={currentTabDomain()}1368                sortOrder={sortOrder()}1369                searchSeed={listSearchSeed()}1370                searchSeedNonce={listSearchSeedNonce()}1371                onSelectEntry={handleSelectEntry}1372                onSortOrderChange={setSortOrder}1373                onAdd={handleAdd}1374                onClose={() => setView("entry")}1375                onOpenTrash={() => setView("trash")}1376                onDeleteMany={handleDeleteMany}1377              />1378            </Show>1379            <Show when={isNativePlatform() && hasVault()}>1380              <Portal>1381                <div1382                  class="peach-vault-sheet"1383                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1384                  style={(() => {1385                    const live = sheetTranslate();1386                    if (live === null) return undefined;1387                    return { transform: `translateY(${live}px)` };1388                  })()}1389                >1390                  <VaultView1391                    entries={entries()}1392                    selectedEntryId={selectedEntry()?.id}1393                    currentTabDomain={currentTabDomain()}1394                    sortOrder={sortOrder()}1395                    searchSeed={listSearchSeed()}1396                    searchSeedNonce={listSearchSeedNonce()}1397                    isNative={true}1398                    onSelectEntry={handleSelectEntry}1399                    onSortOrderChange={setSortOrder}1400                    onAdd={handleAdd}1401                    onClose={() => setView("entry")}1402                    onOpenTrash={() => setView("trash")}1403                    onDeleteMany={handleDeleteMany}1404                  />1405                </div>1406              </Portal>1407            </Show>1408            <Show when={view() === "settings" || settingsExiting()}>1409              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1410                <SettingsView1411                  entriesCount={entries().length}1412                  breachMonitoring={breachMonitoring()}1413                  lockOnClose={lockOnClose()}1414                  autoLockMinutes={autoLockMinutes()}1415                  trashRetentionDays={trashRetentionDays()}1416                  theme={theme()}1417                  accentColor={accentColor()}1418                  textSize={textSize()}1419                  reduceMotion={reduceMotion()}1420                  isPro={proStatus()}1421                  initialSection={settingsInitialSection()}1422                  upgradeHighlight={upgradeHighlight()}1423                  isExiting={settingsExiting()}1424                  onBreachMonitoringChange={applyBreachMonitoring}1425                  onLockOnCloseChange={applyLockOnClose}1426                  onAutoLockMinutesChange={applyAutoLockMinutes}1427                  onTrashRetentionChange={applyTrashRetention}1428                  onThemeChange={applyTheme}1429                  onAccentChange={applyAccentColor}1430                  onTextSizeChange={applyTextSize}1431                  onReduceMotionChange={applyReduceMotion}1432                  shortcuts={shortcutBindings()}1433                  onShortcutsChange={applyShortcuts}1434                  onLicenseChange={async () => {1435                    // After activation/deactivation: refresh Pro status,1436                    // re-load entries (defensive — signal state can drift if1437                    // the SW briefly restarts during the verify+save round-trip),1438                    // and replay the Pro celebration if this is the first time1439                    // a valid Pro license is seen on this device.1440                    await refreshProStatus();1441                    void loadEntries();1442                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1443                    if ((should as { ok: boolean; data?: boolean }).data === true) {1444                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1445                      setView("pro-celebration");1446                      window.setTimeout(() => setView("settings"), 2500);1447                    }1448                  }}1449                  onBack={() => {1450                    setSettingsExiting(true);1451                    window.setTimeout(() => {1452                      setSettingsExiting(false);1453                      setSettingsInitialSection(null);1454                      setUpgradeHighlight(null);1455                      handleBack();1456                    }, 200);1457                  }}1458                  onImport={() => setView("import")}1459                  onExport={() => setView("export")}1460                  onBreachCheckDone={loadEntries}1461                  onOpenHealth={openHealth}1462                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("chirp-sync"); }}1463                  onOpenFileImport={handleOpenFileImport}1464                  onOpenPanic={() => setView("panic")}1465                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1466                  onOpenCodexRestore={() => setView("codex-restore")}1467                  onCardChange={setSettingsActiveCard}1468                  onProGate={(feature) => {1469                    setUpgradeHighlight(feature);1470                    setSettingsInitialSection("license");1471                  }}1472                />1473              </Suspense>1474            </Show>1475            <Show when={view() === "codex-generate"}>1476              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1477                <CodexGenerateView1478                  isPro={proStatus()}1479                  onBack={() => setView("settings")}1480                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1481                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1482                  onVaultLocked={() => handleLock()}1483                />1484              </Suspense>1485            </Show>1486            <Show when={view() === "codex-restore"}>1487              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1488                <CodexRestoreView1489                  onBack={() => setView("lock")}1490                  onRestoreSuccess={async () => {1491                    // After restore the vault is unlocked; refresh entries1492                    // and route to the main vault list. handleUnlock is the1493                    // canonical post-unlock setup path.1494                    await handleUnlock();1495                  }}1496                />1497              </Suspense>1498            </Show>1499            <Show when={view() === "chirp-sync"}>1500              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1501                <ChirpSyncView1502                  isPro={proStatus()}1503                  onBack={() => setView("settings")}1504                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1505                />1506              </Suspense>1507            </Show>1508            <Show when={view() === "add"}>1509              <AddView1510                entry={editEntry()}1511                entries={entries()}1512                onBack={handleBack}1513                onSave={handleSave}1514              />1515            </Show>1516            <Show when={view() === "import"}>1517              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1518                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1519              </Suspense>1520            </Show>1521            <Show when={view() === "export"}>1522              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1523                <ExportView onBack={handleExportBack} />1524              </Suspense>1525            </Show>1526            <Show when={view() === "panic"}>1527              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1528                <PanicView1529                  onCancel={() => setView("settings")}1530                  onOpenExport={() => {1531                    setReturnToPanic(true);1532                    setView("export");1533                  }}1534                  onDestroyed={async () => {1535                    clearCanarySuppressions();1536                    setEntries([]);1537                    setSelectedEntry(null);1538                    setEditEntry(undefined);1539                    setHasVault(false);1540                    setOnboarded(false);1541                    setProStatus(false);1542                    setPendingPasskey(null);1543                    setUpgradeHighlight(null);1544                    setSettingsInitialSection(null);1545                    setPendingProNotice(null);1546                    setPendingCelebration(false);1547                    setReturnToPanic(false);1548                    setContentPhase("idle");1549                    setView("lock");1550                  }}1551                />1552              </Suspense>1553            </Show>1554            {/* Health stays mounted while editing an entry from it so1555                computeReused() doesn't rerun on every cancel/back. */}1556            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1557              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1558                <HealthView1559                  entries={entries()}1560                  isPro={proStatus()}1561                  onFixEntry={handleFixEntry}1562                  onBack={() => setView("settings")}1563                  onRefresh={loadEntries}1564                  hidden={view() !== "health"}1565                />1566              </Suspense>1567            </Show>1568            <Show when={view() === "trash"}>1569              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1570                <TrashView1571                  onBack={() => setView("list")}1572                  onRestored={() => void loadEntries()}1573                />1574              </Suspense>1575            </Show>1576            <Show when={showNotes()}>1577              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1578                <NotesMode1579                  notes={entries().filter((e) => e.type === "note")}1580                  initialNoteId={openNoteId()}1581                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1582                  onNoteListChanged={() => void loadEntries()}1583                />1584              </div>1585            </Show>1586            <Show when={restoreView() === "file"}>1587              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1588                <ImportView1589                  mode="onboarding"1590                  replacesExistingVault={true}1591                  onBack={() => setRestoreView(null)}1592                  onImport={async () => {1593                    setRestoreView(null);1594                    await handleUnlock();1595                  }}1596                />1597              </Suspense>1598            </Show>1599            </section>1600            </Show>1601          </Show>1602        </Show>1603      </Show>1604      <Show when={showShortcutsHelp()}>1605        <ShortcutsHelpOverlay1606          bindings={shortcutBindings()}1607          onClose={() => setShowShortcutsHelp(false)}1608        />1609      </Show>1610    </div>1611  );1612}16131614function ShortcutsHelpOverlay(props: {1615  bindings: Record<ShortcutAction, Keybinding>;1616  onClose: () => void;1617}) {1618  return (1619    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1620      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1621        <div class="peach-shortcuts-help-head">1622          <h3>Keyboard shortcuts</h3>1623          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1624        </div>1625        <div class="peach-shortcuts-help-body">1626          <p class="peach-settings-sub-label">ENTRY VIEW</p>1627          <ul>1628            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1629              <li>1630                <span>{d.label}</span>1631                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1632              </li>1633            ))}1634          </ul>1635          <p class="peach-settings-sub-label">ANYWHERE</p>1636          <ul>1637            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1638              <li>1639                <span>{d.label}</span>1640                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1641              </li>1642            ))}1643          </ul>1644        </div>1645      </div>1646    </div>1647  );1648}