App.tsx

68.0 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      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect467      // listener accepts the "popup-" prefix; the random suffix is defence in468      // depth against a port named exactly "popup" from anything but our popup.469      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });470    } catch { /* extension context invalidated — ignore */ }471    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });472473    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only474    // reliable signal is appStateChange — setTimeout is killed when the OS475    // backgrounds the app. We measure elapsed background time on resume.476    if (isNativePlatform()) {477      let backgroundedAt: number | null = null;478479      const CapApp = nativePlugin<{480        addListener: (481          ev: string,482          cb: (s: { isActive: boolean }) => void,483        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };484      }>("App");485      if (CapApp?.addListener) {486        const sub = CapApp.addListener(487          "appStateChange",488          ({ isActive }: { isActive: boolean }) => {489            if (!isActive) {490              backgroundedAt = Date.now();491              return;492            }493            if (backgroundedAt !== null && autoLockMinutes() > 0) {494              const elapsed = Date.now() - backgroundedAt;495              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();496            }497            backgroundedAt = null;498          }499        );500        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.501        onCleanup(() => {502          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});503        });504      }505506      // L12/COR-011: foreground idle autolock. appStateChange only fires when507      // the OS backgrounds the app — if the user idles with the screen on,508      // chrome.alarms is no-op'd in Capacitor so the vault would stay open509      // indefinitely. Poll every 30s and lock if elapsed since last user510      // interaction exceeds autoLockMinutes.511      let lastUserActivityAt = Date.now();512      const bumpActivity = () => { lastUserActivityAt = Date.now(); };513      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;514      for (const ev of ACTIVITY_EVENTS) {515        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });516      }517      const idleLockInterval = setInterval(() => {518        const minutes = autoLockMinutes();519        if (!minutes || minutes <= 0) return;520        const elapsed = Date.now() - lastUserActivityAt;521        if (elapsed >= minutes * 60_000) {522          lastUserActivityAt = Date.now();523          handleHeaderLock();524        }525      }, 30_000);526      onCleanup(() => {527        clearInterval(idleLockInterval);528        for (const ev of ACTIVITY_EVENTS) {529          document.removeEventListener(ev, bumpActivity, { capture: true });530        }531      });532533      // mDNS peer-discovery trigger. Register onCleanup synchronously so534      // SolidJS captures it within the reactive owner — onCleanup inside a535      // .then() callback may miss the capture window and leak the listener.536      let stopMDNS: () => void = () => undefined;537      onCleanup(() => stopMDNS());538      if (isNativePlatform()) {539        // Android runs the background/sync dispatcher in-process with the540        // popup, so the production runner has to be registered from the541        // UI bootstrap path instead of the MV3 service-worker entry.542        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>543          import("../background/chirp-sync-runner").then(({ productionSyncRunner }) => {544            setSyncRunner(productionSyncRunner);545            void hydratePersistedSyncState();546          })547        );548      }549      void import("./chirp-pair-capacitor").then(({ startMDNSListener }) => {550        stopMDNS = startMDNSListener();551      });552    }553554    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale555    // entries instead of waiting for the next GET_ENTRIES round-trip.556    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {557      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();558      if (msg?.type === "PRO_GATE_TRIGGERED") {559        setUpgradeHighlight(msg.payload?.feature ?? null);560        setSettingsInitialSection("license");561        setView("settings");562      }563    };564    chrome.runtime.onMessage.addListener(handleRuntimeMessage);565    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));566567    // Android hardware/gesture back. MainActivity fires peach:back; the popup568    // decides what "back" means per surface. Lock+no-vault is the common case569    // — return to onboarding rather than letting the OS dismiss the activity.570    const handlePeachBack = () => {571      // Notes mode captures back first572      if (showNotes()) {573        setShowNotes(false);574        setOpenNoteId(undefined);575        return;576      }577      const v = view();578      if (v === "lock" && !hasVault() && onboarded()) {579        setOnboarded(false);580        return;581      }582      if (v === "list") { setView("entry"); return; }583      if (v === "settings") {584        window.dispatchEvent(new Event("peach:settings-back"));585        return;586      }587      if (v === "import" || v === "health") { setView("settings"); return; }588      if (v === "export") { handleExportBack(); return; }589      if (v === "add") { handleBack(); return; }590      if (v === "chirp-sync") { setView("settings"); return; }591    };592    window.addEventListener("peach:back", handlePeachBack);593    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));594595    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that596    // peeks from the bottom (search bar handle visible) and drags up to fill597    // the screen. dragOffset is the LIVE finger offset during a drag, in px,598    // 0 when no drag in progress. The wrapper element computes transform =599    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.600    if (isNativePlatform()) {601      let touchStartY = 0;602      let touchStartX = 0;603      let lastY = 0;604      let lastT = 0;605      let dragging = false;606      let captured = false;607      const HORIZONTAL_TOLERANCE = 16;608      const ACTIVATION_DY = 8;609      const PEEK_PX = 60;610611      const onTouchStart = (e: TouchEvent) => {612        const t = e.touches[0];613        if (!t) return;614        const v = view();615        if (v !== "entry" && v !== "list") return;616        // Entry view: only intercept drags starting in the bottom 40%.617        // List view: intercept drags starting in the top 35% (the search/handle row).618        const inBand = v === "entry"619          ? t.clientY > window.innerHeight * 0.6620          : t.clientY < window.innerHeight * 0.35;621        if (!inBand) return;622        touchStartY = lastY = t.clientY;623        touchStartX = t.clientX;624        lastT = e.timeStamp;625        dragging = true;626        captured = false;627      };628629      const onTouchMove = (e: TouchEvent) => {630        if (!dragging) return;631        const t = e.touches[0];632        if (!t) return;633        const dy = t.clientY - touchStartY;634        const dx = Math.abs(t.clientX - touchStartX);635636        if (!captured) {637          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {638            // Looks like a horizontal swipe — release.639            dragging = false;640            return;641          }642          if (Math.abs(dy) < ACTIVATION_DY) return;643          captured = true;644        }645646        // Translate the sheet by dy from its rest (peek) position. Peek is647        // (viewport height - PEEK_PX). Open is 0.648        const v = view();649        const restClosed = window.innerHeight - PEEK_PX;650        const baseTranslate = v === "list" ? 0 : restClosed;651        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));652        setSheetTranslate(next);653        lastY = t.clientY;654        lastT = e.timeStamp;655      };656657      const onTouchEnd = (e: TouchEvent) => {658        if (!dragging) { return; }659        const t = e.changedTouches[0];660        const elapsed = Math.max(1, e.timeStamp - lastT);661        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms662        const wasCaptured = captured;663        dragging = false;664        captured = false;665        const v = view();666667        if (!wasCaptured) {668          // Tap in the peek strip while in entry view → open the vault list.669          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");670          setSheetTranslate(null);671          return;672        }673674        const restClosed = window.innerHeight - PEEK_PX;675        const current = sheetTranslate() ?? restClosed;676677        // Snap rules:678        //   - Strong upward velocity → open679        //   - Strong downward velocity → close680        //   - Otherwise snap to whichever rest is closer681        let nextOpen: boolean;682        if (velocity < -0.05) nextOpen = true;683        else if (velocity > 0.05) nextOpen = false;684        else nextOpen = current < restClosed * 0.5;685686        if (nextOpen && v !== "list") setView("list");687        if (!nextOpen && v !== "entry") setView("entry");688        // Release the live offset so CSS transition handles the snap.689        setSheetTranslate(null);690      };691692      document.addEventListener("touchstart", onTouchStart, { passive: true });693      document.addEventListener("touchmove",  onTouchMove,  { passive: true });694      document.addEventListener("touchend",   onTouchEnd,   { passive: true });695      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });696      onCleanup(() => {697        document.removeEventListener("touchstart", onTouchStart);698        document.removeEventListener("touchmove",  onTouchMove);699        document.removeEventListener("touchend",   onTouchEnd);700      });701    }702703    // Action handlers — keyed by ShortcutAction. The dispatcher below tests704    // each binding against the event and runs the matching handler. New705    // shortcuts only need an entry here; the binding is data, not code.706    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {707      copy_password: () => {708        const entry = selectedEntry();709        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });710      },711      copy_username: () => {712        const entry = selectedEntry();713        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });714      },715      copy_totp: () => {716        const entry = selectedEntry();717        if (!entry?.totp) return;718        try {719          const { code } = generateTOTP(entry.totp);720          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });721        } catch { /* invalid TOTP secret — silent */ }722      },723      new_entry: () => handleAdd(),724      edit_entry: () => {725        const entry = selectedEntry();726        // Passkey-only entries have nothing user-editable in the Add view; the727        // passkey credential itself is opaque. Skip the edit action for them.728        if (!entry || isPasskeyOnly(entry)) return;729        setEditEntry(entry);730        setView("add");731      },732      delete_entry: () => {733        if (selectedEntry()) void handleDelete();734      },735      lock_vault: () => { void handleHeaderLock(); },736      search: () => openList(),737      nav_prev: () => navigate(-1),738      nav_next: () => navigate(1),739      jump_vault: () => setView("entry"),740      jump_settings: () => setView("settings"),741      show_help: () => setShowShortcutsHelp(true),742    };743744    // Actions that are MEANINGFUL only on the entry-detail view. Outside745    // that scope the binding is dormant — pressing C while on Settings746    // does nothing rather than awkwardly copying from a now-stale entry.747    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([748      "copy_password", "copy_username", "copy_totp",749      "edit_entry", "delete_entry", "nav_prev", "nav_next",750    ]);751752    const handleGlobalKeydown = (e: KeyboardEvent) => {753      const v = view();754      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"755        || (e.target as HTMLElement)?.tagName === "TEXTAREA"756        || (e.target as HTMLElement)?.isContentEditable;757      const isPrintableSearchKey =758        e.key.length === 1 &&759        !e.ctrlKey &&760        !e.metaKey &&761        !e.altKey;762763      // No input during the pro celebration sequence764      if (v === "pro-celebration") return;765766      // Help dialog: Escape closes it; eat the keypress so it doesn't767      // also navigate away from the underlying view.768      if (showShortcutsHelp()) {769        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }770        return;771      }772773      // ── Escape — fixed binding (not user-customizable) ───────774      if (e.key === "Escape") {775        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }776        if (v === "list") { setView("entry"); return; }777        if (v === "settings" || v === "add") { handleBack(); return; }778        if (v === "import" || v === "health") { setView("settings"); return; }779        if (v === "export") { handleExportBack(); return; }780        if (v === "chirp-sync") { setView("settings"); return; }781      }782783      // Bindings-driven dispatch. Single-key letter bindings without784      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is785      // inside an input, so users can type into search/forms normally.786      const bindings = shortcutBindings();787      for (const action of Object.keys(bindings) as ShortcutAction[]) {788        const binding = bindings[action];789        if (!matchKeybinding(e, binding)) continue;790        // Single-key letter bindings need the input-focus guard. Bindings791        // with any modifier are safe — Ctrl+L doesn't conflict with typing.792        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;793        if (!hasMod && binding.key.length === 1 && inInput) return;794        if (ENTRY_SCOPED.has(action) && v !== "entry") return;795        e.preventDefault();796        SHORTCUT_HANDLERS[action]?.();797        return;798      }799800      // Type-to-search: in entry view, any printable key not consumed by a801      // shortcut above primes the list search seed and opens the list.802      // Kept outside the bindings table because it's a behavior, not a803      // discrete action — every printable character can trigger it.804      if (v === "entry" && !inInput && isPrintableSearchKey) {805        e.preventDefault();806        primeListSearch(e.key);807        return;808      }809    };810    window.addEventListener("keydown", handleGlobalKeydown);811    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));812813    const handleStorageChanged = (814      changes: Record<string, chrome.storage.StorageChange>,815      areaName: string816    ) => {817      if (areaName !== "session") return;818      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {819        return;820      }821      void refreshPendingPasskey();822    };823    chrome.storage.onChanged.addListener(handleStorageChanged);824    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));825  });826827  async function refreshCurrentTab() {828    try {829      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });830      const url = tab?.url ?? tab?.pendingUrl ?? "";831      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");832      // Skip extension/internal URLs — adding chrome://, about:, or833      // chrome-extension:// to a vault entry is never what the user wants.834      const isWebUrl = /^https?:\/\//i.test(url);835      setCurrentTabUrl(isWebUrl ? url : "");836    } catch {837      setCurrentTabDomain("");838      setCurrentTabUrl("");839    }840  }841842  async function refreshPendingPasskey() {843    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });844    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);845  }846847  async function refreshProStatus() {848    const res = await sendMessage({ type: "GET_LICENSE" });849    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;850    setProStatus(Boolean(data?.valid && data?.plan === "pro"));851  }852853  async function restoreSettings() {854    const res = await sendMessage({ type: "GET_SETTINGS" });855    const s = (res as { ok: boolean; data?: any }).data ?? {};856    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {857      setAccentColor(s.accentColor as AccentColorName);858    }859    setTheme(s.theme === "light" ? "light" : "dark");860    if (s.textSize === "small" || s.textSize === "large") {861      setTextSize(s.textSize);862    } else {863      setTextSize("medium");864    }865    setReduceMotion(s.reduceMotion === true);866    setLockOnClose(s.lockOnClose !== false);867    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);868    setBreachMonitoring(s.breachMonitoring !== false);869    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);870    setShortcutBindings(getActiveBindings(s.shortcuts));871  }872873  async function applyTrashRetention(days: number) {874    setTrashRetentionDays(days);875    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });876  }877878  function primeListSearch(seed: string) {879    setListSearchSeed(seed);880    setListSearchSeedNonce((value) => value + 1);881    openList();882  }883884  // Returns null when it detected a dead service worker and triggered handleLock().885  // Callers that need to abort (e.g. openVault) check for null rather than relying886  // on view() state, which may already be "lock" during normal startup flows.887  async function loadEntries(): Promise<VaultEntry[] | null> {888    const response = await sendMessage({ type: "GET_ENTRIES" });889    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };890891    // If the service worker was killed and restarted (MV3 workers sleep), the892    // vault will be locked again — or the worker may not respond at all.893    // In either case, send the user to the lock screen rather than silently894    // showing an empty vault (which looks like data loss).895    if (!res.ok) {896      if (897        res.error === "vault_locked" ||898        res.error === "SERVICE_WORKER_UNAVAILABLE" ||899        (typeof res.error === "string" && res.error.includes("locked"))900      ) {901        handleLock();902        return null; // signal emergency lock to callers903      }904      return [];905    }906907    const loadedEntries = res.data ?? [];908    setEntries(loadedEntries);909910    const currentId = selectedEntry()?.id;911    if (currentId) {912      setSelectedEntry(913        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null914      );915    }916917    return loadedEntries;918  }919920  async function openVault(preferredEntryId?: string, skipViewSet = false) {921    // Purge expired trash entries on each vault open922    const retDays = trashRetentionDays();923    if (retDays > 0) {924      void sendMessage({925        type: "PURGE_EXPIRED_TRASH",926        payload: { retentionMs: retDays * 86_400_000 },927      });928    }929930    const loadedEntries = await loadEntries();931932    // null means loadEntries() triggered an emergency lock (service worker died).933    // Don't override it by setting view back to "entry" with an empty vault.934    if (loadedEntries === null) return;935936    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry937    let nextSelectedEntry: VaultEntry | null = null;938    if (preferredEntryId) {939      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;940    }941    if (!nextSelectedEntry) {942      const tabDomain = currentTabDomain();943      if (tabDomain) {944        nextSelectedEntry = loadedEntries.find((e) => {945          if (e.type === "login") {946            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;947            for (const extra of e.additionalUrls ?? []) {948              if ((extractDomain(extra) ?? "") === tabDomain) return true;949            }950            return false;951          }952          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;953          return false;954        }) ?? null;955      }956    }957    nextSelectedEntry ??= loadedEntries[0] ?? null;958959    setSelectedEntry(nextSelectedEntry);960    setEditEntry(undefined);961    setContentTransitioning(false);962    setContentPhase("enter");963    queueContentIdle();964    if (!skipViewSet) setView("entry");965  }966967  async function handleUnlock() {968    // If the user previously created a vault but hadn't yet confirmed their969    // recovery words (and the browser was closed before they could), the970    // peach_recovery_pending flag is still set in storage.local. Re-route971    // back to the recovery surface so they finish the confirmation step972    // before reaching the entries view — the words can be re-derived now973    // that the vault is unlocked again.974    let recoveryPending = false;975    try {976      const out = await chrome.storage.local?.get("peach_recovery_pending");977      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";978    } catch { /* best-effort */ }979    if (recoveryPending) {980      setForceRecoveryWords(true);981      setView("lock");982      triggerPipPulse();983      await restoreSettings();984      return;985    }986    setHasVault(true);987    triggerPipPulse();988    await restoreSettings();989    const celebrating = pendingCelebration();990    if (celebrating) {991      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });992      setPendingCelebration(false);993    }994    await openVault(undefined, celebrating);995    if (celebrating) {996      setView("pro-celebration");997      window.setTimeout(() => setView("entry"), 2500);998    }999    // Popup was opened from the inline "Open Peach to unlock" button — close it1000    // now so the user lands back on the page with the autofill selector ready.1001    if (openedForInlineUnlock) {1002      openedForInlineUnlock = false;1003      window.close();1004    }1005  }10061007  function handleSelectEntry(entry: VaultEntry) {1008    if (entry.type === "note") {1009      setOpenNoteId(entry.id);1010      setShowNotes(true);1011      return;1012    }1013    setSelectedEntry(entry);1014    setContentTransitioning(false);1015    setContentPhase("enter");1016    queueContentIdle();1017    setView("entry");1018  }10191020  function handleAdd() {1021    setEditEntry(undefined);1022    setView("add");1023  }10241025  async function handleDelete() {1026    const entry = selectedEntry();1027    if (!entry) return;1028    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1029    const loadedEntries = await loadEntries() ?? [];1030    setSelectedEntry(loadedEntries[0] ?? null);1031    setView("entry");1032  }10331034  async function handleDeleteMany(ids: string[]) {1035    for (const id of ids) {1036      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1037    }1038    const loadedEntries = await loadEntries() ?? [];1039    // If the currently selected entry was among the deleted, move to first1040    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1041    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1042  }10431044  async function handleSave(savedEntry?: VaultEntry) {1045    await openVault(savedEntry?.id);1046  }10471048  function handleBack() {1049    const dest = editBackView();1050    setEditBackView("entry");1051    setEditEntry(undefined);1052    setView(dest);1053  }10541055  function handleExportBack() {1056    if (returnToPanic()) {1057      setReturnToPanic(false);1058      setView("panic");1059      return;1060    }1061    setView("settings");1062  }10631064  function handleLock() {1065    clearCanarySuppressions();1066    setEntries([]);1067    setSelectedEntry(null);1068    setEditEntry(undefined);1069    setContentPhase("idle");1070    setView("lock");1071  }10721073  function handleHeaderLock() {1074    // Lock the UI immediately — do not wait for the service worker. If the SW1075    // is dead or slow, the 5s sendMessage timeout would create a dead-click1076    // window. The SW will lock on its next wake regardless.1077    handleLock();1078    void sendMessage({ type: "LOCK" });1079  }10801081  function navigate(dir: number) {1082    const allEntries = entries();1083    if (allEntries.length === 0) return;1084    const currentIndex = selectedIndex();1085    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1086    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1087    setSelectedEntry(allEntries[nextIndex]);1088    setContentPhase("enter");1089    queueContentIdle();1090  }10911092  function openList() {1093    setView("list");1094  }10951096  function openHealth() {1097    setEditEntry(undefined);1098    setView("health");1099  }11001101  function handleOpenFileImport() {1102    setRestoreView("file");1103  }11041105  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11061107  function handleFixEntry(entry: VaultEntry) {1108    setSelectedEntry(entry);1109    // Passkey-only entries have no editable surface — drop into view mode1110    // instead of opening the Add editor.1111    if (isPasskeyOnly(entry)) {1112      setView("entry");1113      return;1114    }1115    setEditBackView(view()); // preserve caller view so back returns here1116    setEditEntry(entry);1117    setView("add");1118  }11191120  const isLockedView = () => view() === "lock";11211122  async function handleApprovePendingPasskey() {1123    const pending = pendingPasskey();1124    if (!pending) return;1125    if (pending.browser === "firefox" && pending.type === "create") {1126      // Firefox path: popup itself runs navigator.credentials.create. The1127      // background never approved/rejected anything — it just stashed1128      // intent. After the popup-driven flow resolves (success or cancel),1129      // clear the pending key so the popup doesn't re-show this on next open.1130      const { createFirefoxPasskey } = await import("./firefox-passkey");1131      const result = await createFirefoxPasskey(pending);1132      if (!result.ok) {1133        console.warn("Peach Firefox passkey create failed:", result.error);1134      }1135      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1136      setPendingPasskey(null);1137      void loadEntries();1138      window.close();1139      return;1140    }1141    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1142    window.close();1143  }11441145  async function handleDenyPendingPasskey() {1146    const pending = pendingPasskey();1147    if (!pending) return;1148    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1149    window.close();1150  }11511152  function queueContentIdle(after?: () => void) {1153    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1154    contentPhaseTimer = window.setTimeout(() => {1155      setContentPhase("idle");1156      after?.();1157    }, ENTRY_TRANSITION_SETTLE_MS);1158  }11591160  return (1161    <div class="popup-root peach-theme">1162      <Show when={bootState() === "ready"}>1163        <Show1164          when={!pendingPasskey()}1165          fallback={1166            <PasskeyApprovalView1167              type={pendingPasskey()!.type}1168              rpName={pendingPasskey()!.rpName}1169              rpId={pendingPasskey()!.rpId}1170              userName={pendingPasskey()!.userName}1171              userDisplayName={pendingPasskey()!.userDisplayName}1172              onApprove={handleApprovePendingPasskey}1173              onDeny={handleDenyPendingPasskey}1174            />1175          }1176        >1177          <Show1178            when={!isLockedView()}1179            fallback={1180              <Show1181                when={onboarded() || hasVault()}1182                fallback={1183                  <Onboarding1184                    onComplete={() => { setOnboarded(true); }}1185                  />1186                }1187              >1188                <LockView1189                  hasVault={hasVault()}1190                  ready={bootState() === "ready"}1191                  isPro={proStatus()}1192                  forceRecoveryWords={forceRecoveryWords()}1193                  onUnlock={() => {1194                    // RecoveryWordDisplay clears the storage flag before1195                    // calling onDone, so handleUnlock will see no pending1196                    // confirmation and proceed through the normal path.1197                    if (forceRecoveryWords()) setForceRecoveryWords(false);1198                    return handleUnlock();1199                  }}1200                  onBackToOnboarding={1201                    !hasVault()1202                      ? () => setOnboarded(false)1203                      : undefined1204                  }1205                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1206                />1207              </Show>1208            }1209          >1210            <Show1211              when={view() !== "pro-celebration"}1212              fallback={<ProCelebration />}1213            >1214            <section1215              id="hd-shell"1216              class="peach-shell peach-theme"1217              data-surface="extension"1218            >1219            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1220              <PeachWordmark unlocked />1221              <div class="peach-chrome-actions">1222                <button1223                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1224                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1225                  aria-label="Notes"1226                  title="Notes"1227                >1228                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1229                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1230                    <line x1="4" y1="5" x2="10" y2="5" />1231                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1232                    <line x1="4" y1="10" x2="7" y2="10" />1233                  </svg>1234                </button>1235                <button1236                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1237                  onClick={() => setView("settings")}1238                  aria-label="Settings"1239                >1240                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1241                    <path1242                      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"1243                      stroke="currentColor"1244                      stroke-width="0.9"1245                    />1246                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1247                  </svg>1248                </button>1249                <button1250                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1251                  onClick={handleAdd}1252                  aria-label="New entry"1253                >1254                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1255                    <path d="M5.5 1v9M1 5.5h9" />1256                  </svg>1257                </button>1258                <button1259                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1260                  onClick={() => void handleHeaderLock()}1261                  aria-label="Lock vault"1262                >1263                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1264                    <path1265                      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"1266                      stroke="currentColor"1267                      stroke-width="1"1268                      stroke-linecap="round"1269                    />1270                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1271                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1272                  </svg>1273                </button>1274              </div>1275            </header>12761277            <Show when={pendingProNotice() !== null}>1278              <div class="peach-pro-notice-banner">1279                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1280                <button1281                  class="peach-pro-notice-link"1282                  onClick={() => {1283                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1284                    setSettingsInitialSection("license");1285                    setView("settings");1286                    setPendingProNotice(null);1287                  }}1288                >1289                  Learn more →1290                </button>1291                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1292              </div>1293            </Show>12941295            <div class="peach-shell-body">1296              <div class="peach-shell-veil"></div>1297              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1298                <EntryView1299                  entry={selectedEntry()}1300                  currentTabUrl={currentTabUrl()}1301                  entries={entries()}1302                  isPro={proStatus()}1303                  onDelete={handleDelete}1304                  onFieldSaved={() => void loadEntries()}1305                  onEscape={() => { setView("list"); }}1306                  onProGate={(feature) => {1307                    setUpgradeHighlight(feature);1308                    setSettingsInitialSection("license");1309                    setView("settings");1310                  }}1311                />1312              </div>13131314              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1315                <div class="peach-search-bar">1316                  <span class="peach-search-icon">1317                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1318                      <circle cx="5.5" cy="5.5" r="3.75" />1319                      <path d="M8.75 8.75L11.5 11.5" />1320                    </svg>1321                  </span>1322                  <input1323                    class="peach-search-input"1324                    placeholder="search vault..."1325                    autocomplete="off"1326                    aria-label="Search vault entries"1327                    onClick={openList}1328                    onFocus={openList}1329                    readOnly1330                  />1331                  <div class="peach-search-meta">1332                    <span class="peach-search-counter">1333                      {entries().length > 01334                        ? `${selectedIndex() + 1} / ${entries().length}`1335                        : "0 entries"}1336                    </span>1337                    <span class="peach-divider"></span>1338                    <button1339                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1340                      onClick={() => navigate(-1)}1341                      aria-label="Previous entry"1342                      disabled={entries().length === 0}1343                    >1344                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1345                        <path d="M5 1L1 5.5L5 10" />1346                      </svg>1347                    </button>1348                    <button1349                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1350                      onClick={() => navigate(1)}1351                      aria-label="Next entry"1352                      disabled={entries().length === 0}1353                    >1354                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1355                        <path d="M1 1L5 5.5L1 10" />1356                      </svg>1357                    </button>1358                  </div>1359                </div>1360              </section>1361            </div>13621363            {/* Desktop: shown on demand via Show. Native sheet is rendered1364                via Portal below at the document root so its position:fixed1365                isn't trapped by .peach-shell's transform-based animations. */}1366            <Show when={!isNativePlatform() && view() === "list"}>1367              <VaultView1368                entries={entries()}1369                selectedEntryId={selectedEntry()?.id}1370                currentTabDomain={currentTabDomain()}1371                sortOrder={sortOrder()}1372                searchSeed={listSearchSeed()}1373                searchSeedNonce={listSearchSeedNonce()}1374                onSelectEntry={handleSelectEntry}1375                onSortOrderChange={setSortOrder}1376                onAdd={handleAdd}1377                onClose={() => setView("entry")}1378                onOpenTrash={() => setView("trash")}1379                onDeleteMany={handleDeleteMany}1380              />1381            </Show>1382            <Show when={isNativePlatform() && hasVault()}>1383              <Portal>1384                <div1385                  class="peach-vault-sheet"1386                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1387                  style={(() => {1388                    const live = sheetTranslate();1389                    if (live === null) return undefined;1390                    return { transform: `translateY(${live}px)` };1391                  })()}1392                >1393                  <VaultView1394                    entries={entries()}1395                    selectedEntryId={selectedEntry()?.id}1396                    currentTabDomain={currentTabDomain()}1397                    sortOrder={sortOrder()}1398                    searchSeed={listSearchSeed()}1399                    searchSeedNonce={listSearchSeedNonce()}1400                    isNative={true}1401                    onSelectEntry={handleSelectEntry}1402                    onSortOrderChange={setSortOrder}1403                    onAdd={handleAdd}1404                    onClose={() => setView("entry")}1405                    onOpenTrash={() => setView("trash")}1406                    onDeleteMany={handleDeleteMany}1407                  />1408                </div>1409              </Portal>1410            </Show>1411            <Show when={view() === "settings" || settingsExiting()}>1412              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1413                <SettingsView1414                  entriesCount={entries().length}1415                  breachMonitoring={breachMonitoring()}1416                  lockOnClose={lockOnClose()}1417                  autoLockMinutes={autoLockMinutes()}1418                  trashRetentionDays={trashRetentionDays()}1419                  theme={theme()}1420                  accentColor={accentColor()}1421                  textSize={textSize()}1422                  reduceMotion={reduceMotion()}1423                  isPro={proStatus()}1424                  initialSection={settingsInitialSection()}1425                  upgradeHighlight={upgradeHighlight()}1426                  isExiting={settingsExiting()}1427                  onBreachMonitoringChange={applyBreachMonitoring}1428                  onLockOnCloseChange={applyLockOnClose}1429                  onAutoLockMinutesChange={applyAutoLockMinutes}1430                  onTrashRetentionChange={applyTrashRetention}1431                  onThemeChange={applyTheme}1432                  onAccentChange={applyAccentColor}1433                  onTextSizeChange={applyTextSize}1434                  onReduceMotionChange={applyReduceMotion}1435                  shortcuts={shortcutBindings()}1436                  onShortcutsChange={applyShortcuts}1437                  onLicenseChange={async () => {1438                    // After activation/deactivation: refresh Pro status,1439                    // re-load entries (defensive — signal state can drift if1440                    // the SW briefly restarts during the verify+save round-trip),1441                    // and replay the Pro celebration if this is the first time1442                    // a valid Pro license is seen on this device.1443                    await refreshProStatus();1444                    void loadEntries();1445                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1446                    if ((should as { ok: boolean; data?: boolean }).data === true) {1447                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1448                      setView("pro-celebration");1449                      window.setTimeout(() => setView("settings"), 2500);1450                    }1451                  }}1452                  onBack={() => {1453                    setSettingsExiting(true);1454                    window.setTimeout(() => {1455                      setSettingsExiting(false);1456                      setSettingsInitialSection(null);1457                      setUpgradeHighlight(null);1458                      handleBack();1459                    }, 200);1460                  }}1461                  onImport={() => setView("import")}1462                  onExport={() => setView("export")}1463                  onBreachCheckDone={loadEntries}1464                  onOpenHealth={openHealth}1465                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("chirp-sync"); }}1466                  onOpenFileImport={handleOpenFileImport}1467                  onOpenPanic={() => setView("panic")}1468                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1469                  onOpenCodexRestore={() => setView("codex-restore")}1470                  onCardChange={setSettingsActiveCard}1471                  onProGate={(feature) => {1472                    setUpgradeHighlight(feature);1473                    setSettingsInitialSection("license");1474                  }}1475                />1476              </Suspense>1477            </Show>1478            <Show when={view() === "codex-generate"}>1479              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1480                <CodexGenerateView1481                  isPro={proStatus()}1482                  onBack={() => setView("settings")}1483                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1484                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1485                  onVaultLocked={() => handleLock()}1486                />1487              </Suspense>1488            </Show>1489            <Show when={view() === "codex-restore"}>1490              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1491                <CodexRestoreView1492                  onBack={() => setView("lock")}1493                  onRestoreSuccess={async () => {1494                    // After restore the vault is unlocked; refresh entries1495                    // and route to the main vault list. handleUnlock is the1496                    // canonical post-unlock setup path.1497                    await handleUnlock();1498                  }}1499                />1500              </Suspense>1501            </Show>1502            <Show when={view() === "chirp-sync"}>1503              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1504                <ChirpSyncView1505                  isPro={proStatus()}1506                  onBack={() => setView("settings")}1507                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1508                />1509              </Suspense>1510            </Show>1511            <Show when={view() === "add"}>1512              <AddView1513                entry={editEntry()}1514                entries={entries()}1515                onBack={handleBack}1516                onSave={handleSave}1517              />1518            </Show>1519            <Show when={view() === "import"}>1520              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1521                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1522              </Suspense>1523            </Show>1524            <Show when={view() === "export"}>1525              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1526                <ExportView onBack={handleExportBack} />1527              </Suspense>1528            </Show>1529            <Show when={view() === "panic"}>1530              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1531                <PanicView1532                  onCancel={() => setView("settings")}1533                  onOpenExport={() => {1534                    setReturnToPanic(true);1535                    setView("export");1536                  }}1537                  onDestroyed={async () => {1538                    clearCanarySuppressions();1539                    setEntries([]);1540                    setSelectedEntry(null);1541                    setEditEntry(undefined);1542                    setHasVault(false);1543                    setOnboarded(false);1544                    setProStatus(false);1545                    setPendingPasskey(null);1546                    setUpgradeHighlight(null);1547                    setSettingsInitialSection(null);1548                    setPendingProNotice(null);1549                    setPendingCelebration(false);1550                    setReturnToPanic(false);1551                    setContentPhase("idle");1552                    setView("lock");1553                  }}1554                />1555              </Suspense>1556            </Show>1557            {/* Health stays mounted while editing an entry from it so1558                computeReused() doesn't rerun on every cancel/back. */}1559            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1560              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1561                <HealthView1562                  entries={entries()}1563                  isPro={proStatus()}1564                  onFixEntry={handleFixEntry}1565                  onBack={() => setView("settings")}1566                  onRefresh={loadEntries}1567                  hidden={view() !== "health"}1568                />1569              </Suspense>1570            </Show>1571            <Show when={view() === "trash"}>1572              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1573                <TrashView1574                  onBack={() => setView("list")}1575                  onRestored={() => void loadEntries()}1576                />1577              </Suspense>1578            </Show>1579            <Show when={showNotes()}>1580              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1581                <NotesMode1582                  notes={entries().filter((e) => e.type === "note")}1583                  initialNoteId={openNoteId()}1584                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1585                  onNoteListChanged={() => void loadEntries()}1586                />1587              </div>1588            </Show>1589            <Show when={restoreView() === "file"}>1590              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1591                <ImportView1592                  mode="onboarding"1593                  replacesExistingVault={true}1594                  onBack={() => setRestoreView(null)}1595                  onImport={async () => {1596                    setRestoreView(null);1597                    await handleUnlock();1598                  }}1599                />1600              </Suspense>1601            </Show>1602            </section>1603            </Show>1604          </Show>1605        </Show>1606      </Show>1607      <Show when={showShortcutsHelp()}>1608        <ShortcutsHelpOverlay1609          bindings={shortcutBindings()}1610          onClose={() => setShowShortcutsHelp(false)}1611        />1612      </Show>1613    </div>1614  );1615}16161617function ShortcutsHelpOverlay(props: {1618  bindings: Record<ShortcutAction, Keybinding>;1619  onClose: () => void;1620}) {1621  return (1622    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1623      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1624        <div class="peach-shortcuts-help-head">1625          <h3>Keyboard shortcuts</h3>1626          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1627        </div>1628        <div class="peach-shortcuts-help-body">1629          <p class="peach-settings-sub-label">ENTRY VIEW</p>1630          <ul>1631            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1632              <li>1633                <span>{d.label}</span>1634                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1635              </li>1636            ))}1637          </ul>1638          <p class="peach-settings-sub-label">ANYWHERE</p>1639          <ul>1640            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1641              <li>1642                <span>{d.label}</span>1643                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1644              </li>1645            ))}1646          </ul>1647        </div>1648      </div>1649    </div>1650  );1651}