App.tsx

66.3 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;178179  function applyAccent(name: AccentColorName) {180    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;181    const hex = color.hex;182    document.documentElement.style.setProperty("--peach-accent", hex);183    // Ambient surface variables — derived from the accent so surfaces shift184    // subtly toward the accent hue rather than staying fixed warm-brown.185    document.documentElement.style.setProperty("--peach-glow", hex + "2A");186    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");187    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");188  }189190  createEffect(() => {191    applyAccent(accentColor());192  });193194  createEffect(() => {195    document.documentElement.classList.toggle("light", theme() === "light");196    document.body.classList.toggle("light", theme() === "light");197  });198199  createEffect(() => {200    document.documentElement.setAttribute("data-text-size", textSize());201  });202203  createEffect(() => {204    if (reduceMotion()) {205      document.documentElement.setAttribute("data-motion", "reduce");206    } else {207      document.documentElement.removeAttribute("data-motion");208    }209  });210211  const selectedIndex = createMemo(() => {212    const currentId = selectedEntry()?.id;213    if (!currentId) return entries().length > 0 ? 0 : -1;214    return entries().findIndex((entry) => entry.id === currentId);215  });216217  async function applyAccentColor(name: AccentColorName) {218    applyAccent(name);219    setAccentColor(name);220    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });221  }222223  async function applyTheme(t: "dark" | "light") {224    setTheme(t);225    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });226  }227228  async function applyTextSize(size: "small" | "medium" | "large") {229    setTextSize(size);230    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });231  }232233  async function applyReduceMotion(enabled: boolean) {234    setReduceMotion(enabled);235    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });236  }237238  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload239  // small and lets future default updates land for actions the user hasn't240  // touched. Settings sends us the full active map; we filter and store.241  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {242    setShortcutBindings(active);243    const overrides: Record<string, Keybinding> = {};244    for (const action of Object.keys(active) as ShortcutAction[]) {245      const a = active[action];246      const d = DEFAULT_BINDINGS[action];247      const same = a.key === d.key248        && Boolean(a.ctrl)  === Boolean(d.ctrl)249        && Boolean(a.meta)  === Boolean(d.meta)250        && Boolean(a.shift) === Boolean(d.shift)251        && Boolean(a.alt)   === Boolean(d.alt);252      if (!same) overrides[action] = a;253    }254    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });255  }256257  async function applyLockOnClose(enabled: boolean) {258    setLockOnClose(enabled);259    await sendMessage({260      type: "UPDATE_SETTINGS",261      payload: { lockOnClose: enabled },262    });263  }264265  async function applyAutoLockMinutes(minutes: number) {266    setAutoLockMinutes(minutes);267    await sendMessage({268      type: "UPDATE_SETTINGS",269      payload: { autoLockMinutes: minutes },270    });271  }272273  async function applyBreachMonitoring(enabled: boolean) {274    setBreachMonitoring(enabled);275    await sendMessage({276      type: "UPDATE_SETTINGS",277      payload: { breachMonitoring: enabled },278    });279  }280281  onMount(async () => {282    // Resolve the active tab in parallel with the unlock/has-vault queries —283    // openVault()'s smart selection picks the entry matching currentTabDomain,284    // so it must be populated before openVault runs. Previously refreshCurrentTab285    // ran after openVault, leaving popups that booted already-unlocked falling286    // back to loadedEntries[0] instead of the domain match.287    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([288      sendMessage({ type: "IS_UNLOCKED" }),289      sendMessage({ type: "HAS_VAULT" }),290      refreshCurrentTab(),291      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),292    ]);293    const unlocked = Boolean(294      (unlockResponse as { ok: boolean; data?: boolean }).data295    );296    const vaultExists = Boolean(297      (vaultResponse as { ok: boolean; data?: boolean }).data298    );299    const shouldCelebrate = Boolean(300      (celebrationResponse as { ok: boolean; data?: boolean }).data301    );302    setHasVault(vaultExists);303    // Onboarding gate — show once on first install, never again. Existing304    // users (vaultExists) are auto-marked onboarded so they skip the flow305    // even on the very first popup open after this feature ships.306    try {307      const onboarded = await storageGet("peach_onboarded");308      const seen = onboarded === "true";309      if (vaultExists && !seen) {310        await storageSet("peach_onboarded", "true");311        setOnboarded(true);312      } else {313        setOnboarded(seen);314      }315    } catch {316      // storage unavailable — default to onboarded so we never block boot317      setOnboarded(true);318    }319    await Promise.all([restoreSettings(), refreshProStatus()]);320321    // Mark played before any animation so a crash mid-sequence never replays it322    if (shouldCelebrate) {323      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });324    }325326    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the327    // background ignores it when no mobile hosts are paired or while328    // another sync is already in flight.329    if (unlocked && vaultExists) {330      void sendMessage({331        type: "TRIGGER_SYNC",332        payload: { reason: "foreground" },333      });334    }335336    // If the user created a vault but hasn't yet confirmed their recovery337    // words, route back to the recovery-words screen instead of opening the338    // entries view. The flag lives in chrome.storage.local so it survives339    // both popup close (SW suppresses lock-on-close) and full browser340    // restart (handleUnlock checks the same flag after a fresh password341    // unlock). Cleared when confirmation succeeds.342    let recoveryPending = false;343    try {344      const out = await chrome.storage.local?.get("peach_recovery_pending");345      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";346    } catch { /* best-effort */ }347348    // Native: closing the app before recovery-words confirmation means the349    // user didn't finish vault creation. Throw the partial vault away and350    // restart onboarding rather than asking them to unlock a vault they351    // never finished creating. Desktop keeps the existing "unlock to352    // resume" flow because closing the popup there is much more casual.353    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {354      try {355        await chrome.storage.local?.remove([356          "peach_vault_a",357          "peach_vault_b",358          "peach_recovery_pending",359          "peach_onboarded",360          "peach_vault_history",361        ]);362      } catch { /* best-effort */ }363      setHasVault(false);364      setOnboarded(false);365      setView("lock");366      setBootState("ready");367      document.getElementById("pre-lock")?.setAttribute("hidden", "true");368      return;369    }370371    if (recoveryPending && unlocked) {372      // forceRecoveryWords overrides LockView's hasVault gate so the373      // recovery surface renders even though the vault now exists.374      setForceRecoveryWords(true);375      setView("lock");376    } else if (unlocked && vaultExists) {377      await openVault(undefined, shouldCelebrate);378      if (shouldCelebrate) {379        setView("pro-celebration");380        window.setTimeout(() => setView("entry"), 2500);381      }382    } else if (shouldCelebrate) {383      setPendingCelebration(true);384    }385386    await refreshPendingPasskey();387388    // Track tab changes so smart sort stays current389    const handleTabActivated = () => { void refreshCurrentTab(); };390    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {391      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();392    };393    try {394      chrome.tabs.onActivated.addListener(handleTabActivated);395      chrome.tabs.onUpdated.addListener(handleTabUpdated);396      onCleanup(() => {397        chrome.tabs.onActivated.removeListener(handleTabActivated);398        chrome.tabs.onUpdated.removeListener(handleTabUpdated);399      });400    } catch {401      // tabs permission may not be available in all contexts402    }403404    setBootState("ready");405    document.getElementById("pre-lock")?.setAttribute("hidden", "true");406407    // Deep-link: ?codex=pdf opens a detached window straight into the408    // Codex restore flow with auto-picked PDF. The action popup can't host409    // a file dialog without dismissing itself, so this is the only way the410    // PDF import path survives. See CodexRestoreView.openPdfPicker().411    try {412      const route = new URLSearchParams(window.location.search).get("codex");413      if (route === "pdf" || route === "restore") {414        setView("codex-restore");415      }416    } catch {417      // location.search unavailable — ignore.418    }419420    // Check for pending session-storage notices from the background.421    if (chrome.storage.session) {422      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as423        Record<string, { feature?: string } | undefined>;424      if (session.pendingProGate?.feature) {425        await chrome.storage.session.remove("pendingProGate");426        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);427        setSettingsInitialSection("license");428        setView("settings");429      } else if (session.pendingProNotice?.feature) {430        await chrome.storage.session.remove("pendingProNotice");431        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });432      }433    }434435    // Warm the lazy-module cache so the Suspense fallback never shows for436    // locally-bundled extension views. Without this, the first navigation to437    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which438    // covers the shell and absorbs clicks on the header.439    void Promise.all([440      import("./views/Settings").catch(() => {}),441      import("./views/Import").catch(() => {}),442      import("./views/Export").catch(() => {}),443      import("./views/Health").catch(() => {}),444      import("./views/TrashView").catch(() => {}),445    ]);446447    // Lock-on-close via a persistent port. sendMessage in pagehide is448    // unreliable — the popup context tears down before the message lands.449    // The SW's onConnect listener locks when this port disconnects.450    let popupPort: chrome.runtime.Port | null = null;451    try {452      popupPort = chrome.runtime.connect({ name: "popup" });453    } catch { /* extension context invalidated — ignore */ }454    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });455456    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only457    // reliable signal is appStateChange — setTimeout is killed when the OS458    // backgrounds the app. We measure elapsed background time on resume.459    if (isNativePlatform()) {460      let backgroundedAt: number | null = null;461462      const CapApp = nativePlugin<{463        addListener: (464          ev: string,465          cb: (s: { isActive: boolean }) => void,466        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };467      }>("App");468      if (CapApp?.addListener) {469        const sub = CapApp.addListener(470          "appStateChange",471          ({ isActive }: { isActive: boolean }) => {472            if (!isActive) {473              backgroundedAt = Date.now();474              return;475            }476            if (backgroundedAt !== null && autoLockMinutes() > 0) {477              const elapsed = Date.now() - backgroundedAt;478              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();479            }480            backgroundedAt = null;481          }482        );483        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.484        onCleanup(() => {485          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});486        });487      }488489      // L12/COR-011: foreground idle autolock. appStateChange only fires when490      // the OS backgrounds the app — if the user idles with the screen on,491      // chrome.alarms is no-op'd in Capacitor so the vault would stay open492      // indefinitely. Poll every 30s and lock if elapsed since last user493      // interaction exceeds autoLockMinutes.494      let lastUserActivityAt = Date.now();495      const bumpActivity = () => { lastUserActivityAt = Date.now(); };496      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;497      for (const ev of ACTIVITY_EVENTS) {498        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });499      }500      const idleLockInterval = setInterval(() => {501        const minutes = autoLockMinutes();502        if (!minutes || minutes <= 0) return;503        const elapsed = Date.now() - lastUserActivityAt;504        if (elapsed >= minutes * 60_000) {505          lastUserActivityAt = Date.now();506          handleHeaderLock();507        }508      }, 30_000);509      onCleanup(() => {510        clearInterval(idleLockInterval);511        for (const ev of ACTIVITY_EVENTS) {512          document.removeEventListener(ev, bumpActivity, { capture: true });513        }514      });515516      // mDNS peer-discovery trigger. Register onCleanup synchronously so517      // SolidJS captures it within the reactive owner — onCleanup inside a518      // .then() callback may miss the capture window and leak the listener.519      let stopMDNS: () => void = () => undefined;520      onCleanup(() => stopMDNS());521      void import("./chirp-pair-capacitor").then(({ startMDNSListener }) => {522        stopMDNS = startMDNSListener();523      });524    }525526    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale527    // entries instead of waiting for the next GET_ENTRIES round-trip.528    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {529      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();530      if (msg?.type === "PRO_GATE_TRIGGERED") {531        setUpgradeHighlight(msg.payload?.feature ?? null);532        setSettingsInitialSection("license");533        setView("settings");534      }535    };536    chrome.runtime.onMessage.addListener(handleRuntimeMessage);537    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));538539    // Android hardware/gesture back. MainActivity fires peach:back; the popup540    // decides what "back" means per surface. Lock+no-vault is the common case541    // — return to onboarding rather than letting the OS dismiss the activity.542    const handlePeachBack = () => {543      // Notes mode captures back first544      if (showNotes()) {545        setShowNotes(false);546        setOpenNoteId(undefined);547        return;548      }549      const v = view();550      if (v === "lock" && !hasVault() && onboarded()) {551        setOnboarded(false);552        return;553      }554      if (v === "list") { setView("entry"); return; }555      if (v === "settings") {556        window.dispatchEvent(new Event("peach:settings-back"));557        return;558      }559      if (v === "import" || v === "health") { setView("settings"); return; }560      if (v === "export") { handleExportBack(); return; }561      if (v === "add") { handleBack(); return; }562      if (v === "chirp-sync") { setView("settings"); return; }563    };564    window.addEventListener("peach:back", handlePeachBack);565    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));566567    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that568    // peeks from the bottom (search bar handle visible) and drags up to fill569    // the screen. dragOffset is the LIVE finger offset during a drag, in px,570    // 0 when no drag in progress. The wrapper element computes transform =571    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.572    if (isNativePlatform()) {573      let touchStartY = 0;574      let touchStartX = 0;575      let lastY = 0;576      let lastT = 0;577      let dragging = false;578      let captured = false;579      const HORIZONTAL_TOLERANCE = 16;580      const ACTIVATION_DY = 8;581      const PEEK_PX = 60;582583      const onTouchStart = (e: TouchEvent) => {584        const t = e.touches[0];585        if (!t) return;586        const v = view();587        if (v !== "entry" && v !== "list") return;588        // Entry view: only intercept drags starting in the bottom 40%.589        // List view: intercept drags starting in the top 35% (the search/handle row).590        const inBand = v === "entry"591          ? t.clientY > window.innerHeight * 0.6592          : t.clientY < window.innerHeight * 0.35;593        if (!inBand) return;594        touchStartY = lastY = t.clientY;595        touchStartX = t.clientX;596        lastT = e.timeStamp;597        dragging = true;598        captured = false;599      };600601      const onTouchMove = (e: TouchEvent) => {602        if (!dragging) return;603        const t = e.touches[0];604        if (!t) return;605        const dy = t.clientY - touchStartY;606        const dx = Math.abs(t.clientX - touchStartX);607608        if (!captured) {609          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {610            // Looks like a horizontal swipe — release.611            dragging = false;612            return;613          }614          if (Math.abs(dy) < ACTIVATION_DY) return;615          captured = true;616        }617618        // Translate the sheet by dy from its rest (peek) position. Peek is619        // (viewport height - PEEK_PX). Open is 0.620        const v = view();621        const restClosed = window.innerHeight - PEEK_PX;622        const baseTranslate = v === "list" ? 0 : restClosed;623        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));624        setSheetTranslate(next);625        lastY = t.clientY;626        lastT = e.timeStamp;627      };628629      const onTouchEnd = (e: TouchEvent) => {630        if (!dragging) { return; }631        const t = e.changedTouches[0];632        const elapsed = Math.max(1, e.timeStamp - lastT);633        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms634        const wasCaptured = captured;635        dragging = false;636        captured = false;637        const v = view();638639        if (!wasCaptured) {640          // Tap in the peek strip while in entry view → open the vault list.641          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");642          setSheetTranslate(null);643          return;644        }645646        const restClosed = window.innerHeight - PEEK_PX;647        const current = sheetTranslate() ?? restClosed;648649        // Snap rules:650        //   - Strong upward velocity → open651        //   - Strong downward velocity → close652        //   - Otherwise snap to whichever rest is closer653        let nextOpen: boolean;654        if (velocity < -0.05) nextOpen = true;655        else if (velocity > 0.05) nextOpen = false;656        else nextOpen = current < restClosed * 0.5;657658        if (nextOpen && v !== "list") setView("list");659        if (!nextOpen && v !== "entry") setView("entry");660        // Release the live offset so CSS transition handles the snap.661        setSheetTranslate(null);662      };663664      document.addEventListener("touchstart", onTouchStart, { passive: true });665      document.addEventListener("touchmove",  onTouchMove,  { passive: true });666      document.addEventListener("touchend",   onTouchEnd,   { passive: true });667      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });668      onCleanup(() => {669        document.removeEventListener("touchstart", onTouchStart);670        document.removeEventListener("touchmove",  onTouchMove);671        document.removeEventListener("touchend",   onTouchEnd);672      });673    }674675    // Action handlers — keyed by ShortcutAction. The dispatcher below tests676    // each binding against the event and runs the matching handler. New677    // shortcuts only need an entry here; the binding is data, not code.678    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {679      copy_password: () => {680        const entry = selectedEntry();681        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });682      },683      copy_username: () => {684        const entry = selectedEntry();685        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });686      },687      copy_totp: () => {688        const entry = selectedEntry();689        if (!entry?.totp) return;690        try {691          const { code } = generateTOTP(entry.totp);692          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });693        } catch { /* invalid TOTP secret — silent */ }694      },695      new_entry: () => handleAdd(),696      edit_entry: () => {697        const entry = selectedEntry();698        // Passkey-only entries have nothing user-editable in the Add view; the699        // passkey credential itself is opaque. Skip the edit action for them.700        if (!entry || isPasskeyOnly(entry)) return;701        setEditEntry(entry);702        setView("add");703      },704      delete_entry: () => {705        if (selectedEntry()) void handleDelete();706      },707      lock_vault: () => { void handleHeaderLock(); },708      search: () => openList(),709      nav_prev: () => navigate(-1),710      nav_next: () => navigate(1),711      jump_vault: () => setView("entry"),712      jump_settings: () => setView("settings"),713      show_help: () => setShowShortcutsHelp(true),714    };715716    // Actions that are MEANINGFUL only on the entry-detail view. Outside717    // that scope the binding is dormant — pressing C while on Settings718    // does nothing rather than awkwardly copying from a now-stale entry.719    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([720      "copy_password", "copy_username", "copy_totp",721      "edit_entry", "delete_entry", "nav_prev", "nav_next",722    ]);723724    const handleGlobalKeydown = (e: KeyboardEvent) => {725      const v = view();726      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"727        || (e.target as HTMLElement)?.tagName === "TEXTAREA"728        || (e.target as HTMLElement)?.isContentEditable;729      const isPrintableSearchKey =730        e.key.length === 1 &&731        !e.ctrlKey &&732        !e.metaKey &&733        !e.altKey;734735      // No input during the pro celebration sequence736      if (v === "pro-celebration") return;737738      // Help dialog: Escape closes it; eat the keypress so it doesn't739      // also navigate away from the underlying view.740      if (showShortcutsHelp()) {741        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }742        return;743      }744745      // ── Escape — fixed binding (not user-customizable) ───────746      if (e.key === "Escape") {747        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }748        if (v === "list") { setView("entry"); return; }749        if (v === "settings" || v === "add") { handleBack(); return; }750        if (v === "import" || v === "health") { setView("settings"); return; }751        if (v === "export") { handleExportBack(); return; }752        if (v === "chirp-sync") { setView("settings"); return; }753      }754755      // Bindings-driven dispatch. Single-key letter bindings without756      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is757      // inside an input, so users can type into search/forms normally.758      const bindings = shortcutBindings();759      for (const action of Object.keys(bindings) as ShortcutAction[]) {760        const binding = bindings[action];761        if (!matchKeybinding(e, binding)) continue;762        // Single-key letter bindings need the input-focus guard. Bindings763        // with any modifier are safe — Ctrl+L doesn't conflict with typing.764        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;765        if (!hasMod && binding.key.length === 1 && inInput) return;766        if (ENTRY_SCOPED.has(action) && v !== "entry") return;767        e.preventDefault();768        SHORTCUT_HANDLERS[action]?.();769        return;770      }771772      // Type-to-search: in entry view, any printable key not consumed by a773      // shortcut above primes the list search seed and opens the list.774      // Kept outside the bindings table because it's a behavior, not a775      // discrete action — every printable character can trigger it.776      if (v === "entry" && !inInput && isPrintableSearchKey) {777        e.preventDefault();778        primeListSearch(e.key);779        return;780      }781    };782    window.addEventListener("keydown", handleGlobalKeydown);783    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));784785    const handleStorageChanged = (786      changes: Record<string, chrome.storage.StorageChange>,787      areaName: string788    ) => {789      if (areaName !== "session") return;790      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {791        return;792      }793      void refreshPendingPasskey();794    };795    chrome.storage.onChanged.addListener(handleStorageChanged);796    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));797  });798799  async function refreshCurrentTab() {800    try {801      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });802      const url = tab?.url ?? tab?.pendingUrl ?? "";803      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");804      // Skip extension/internal URLs — adding chrome://, about:, or805      // chrome-extension:// to a vault entry is never what the user wants.806      const isWebUrl = /^https?:\/\//i.test(url);807      setCurrentTabUrl(isWebUrl ? url : "");808    } catch {809      setCurrentTabDomain("");810      setCurrentTabUrl("");811    }812  }813814  async function refreshPendingPasskey() {815    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });816    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);817  }818819  async function refreshProStatus() {820    const res = await sendMessage({ type: "GET_LICENSE" });821    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;822    setProStatus(Boolean(data?.valid && data?.plan === "pro"));823  }824825  async function restoreSettings() {826    const res = await sendMessage({ type: "GET_SETTINGS" });827    const s = (res as { ok: boolean; data?: any }).data ?? {};828    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {829      setAccentColor(s.accentColor as AccentColorName);830    }831    setTheme(s.theme === "light" ? "light" : "dark");832    if (s.textSize === "small" || s.textSize === "large") {833      setTextSize(s.textSize);834    } else {835      setTextSize("medium");836    }837    setReduceMotion(s.reduceMotion === true);838    setLockOnClose(s.lockOnClose !== false);839    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);840    setBreachMonitoring(s.breachMonitoring !== false);841    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);842    setShortcutBindings(getActiveBindings(s.shortcuts));843  }844845  async function applyTrashRetention(days: number) {846    setTrashRetentionDays(days);847    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });848  }849850  function primeListSearch(seed: string) {851    setListSearchSeed(seed);852    setListSearchSeedNonce((value) => value + 1);853    openList();854  }855856  // Returns null when it detected a dead service worker and triggered handleLock().857  // Callers that need to abort (e.g. openVault) check for null rather than relying858  // on view() state, which may already be "lock" during normal startup flows.859  async function loadEntries(): Promise<VaultEntry[] | null> {860    const response = await sendMessage({ type: "GET_ENTRIES" });861    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };862863    // If the service worker was killed and restarted (MV3 workers sleep), the864    // vault will be locked again — or the worker may not respond at all.865    // In either case, send the user to the lock screen rather than silently866    // showing an empty vault (which looks like data loss).867    if (!res.ok) {868      if (869        res.error === "vault_locked" ||870        res.error === "SERVICE_WORKER_UNAVAILABLE" ||871        (typeof res.error === "string" && res.error.includes("locked"))872      ) {873        handleLock();874        return null; // signal emergency lock to callers875      }876      return [];877    }878879    const loadedEntries = res.data ?? [];880    setEntries(loadedEntries);881882    const currentId = selectedEntry()?.id;883    if (currentId) {884      setSelectedEntry(885        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null886      );887    }888889    return loadedEntries;890  }891892  async function openVault(preferredEntryId?: string, skipViewSet = false) {893    // Purge expired trash entries on each vault open894    const retDays = trashRetentionDays();895    if (retDays > 0) {896      void sendMessage({897        type: "PURGE_EXPIRED_TRASH",898        payload: { retentionMs: retDays * 86_400_000 },899      });900    }901902    const loadedEntries = await loadEntries();903904    // null means loadEntries() triggered an emergency lock (service worker died).905    // Don't override it by setting view back to "entry" with an empty vault.906    if (loadedEntries === null) return;907908    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry909    let nextSelectedEntry: VaultEntry | null = null;910    if (preferredEntryId) {911      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;912    }913    if (!nextSelectedEntry) {914      const tabDomain = currentTabDomain();915      if (tabDomain) {916        nextSelectedEntry = loadedEntries.find((e) => {917          if (e.type === "login") {918            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;919            for (const extra of e.additionalUrls ?? []) {920              if ((extractDomain(extra) ?? "") === tabDomain) return true;921            }922            return false;923          }924          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;925          return false;926        }) ?? null;927      }928    }929    nextSelectedEntry ??= loadedEntries[0] ?? null;930931    setSelectedEntry(nextSelectedEntry);932    setEditEntry(undefined);933    setContentTransitioning(false);934    setContentPhase("enter");935    queueContentIdle();936    if (!skipViewSet) setView("entry");937  }938939  async function handleUnlock() {940    // If the user previously created a vault but hadn't yet confirmed their941    // recovery words (and the browser was closed before they could), the942    // peach_recovery_pending flag is still set in storage.local. Re-route943    // back to the recovery surface so they finish the confirmation step944    // before reaching the entries view — the words can be re-derived now945    // that the vault is unlocked again.946    let recoveryPending = false;947    try {948      const out = await chrome.storage.local?.get("peach_recovery_pending");949      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";950    } catch { /* best-effort */ }951    if (recoveryPending) {952      setForceRecoveryWords(true);953      setView("lock");954      triggerPipPulse();955      await restoreSettings();956      return;957    }958    setHasVault(true);959    triggerPipPulse();960    await restoreSettings();961    const celebrating = pendingCelebration();962    if (celebrating) {963      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });964      setPendingCelebration(false);965    }966    await openVault(undefined, celebrating);967    if (celebrating) {968      setView("pro-celebration");969      window.setTimeout(() => setView("entry"), 2500);970    }971  }972973  function handleSelectEntry(entry: VaultEntry) {974    if (entry.type === "note") {975      setOpenNoteId(entry.id);976      setShowNotes(true);977      return;978    }979    setSelectedEntry(entry);980    setContentTransitioning(false);981    setContentPhase("enter");982    queueContentIdle();983    setView("entry");984  }985986  function handleAdd() {987    setEditEntry(undefined);988    setView("add");989  }990991  async function handleDelete() {992    const entry = selectedEntry();993    if (!entry) return;994    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });995    const loadedEntries = await loadEntries() ?? [];996    setSelectedEntry(loadedEntries[0] ?? null);997    setView("entry");998  }9991000  async function handleDeleteMany(ids: string[]) {1001    for (const id of ids) {1002      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1003    }1004    const loadedEntries = await loadEntries() ?? [];1005    // If the currently selected entry was among the deleted, move to first1006    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1007    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1008  }10091010  async function handleSave(savedEntry?: VaultEntry) {1011    await openVault(savedEntry?.id);1012  }10131014  function handleBack() {1015    const dest = editBackView();1016    setEditBackView("entry");1017    setEditEntry(undefined);1018    setView(dest);1019  }10201021  function handleExportBack() {1022    if (returnToPanic()) {1023      setReturnToPanic(false);1024      setView("panic");1025      return;1026    }1027    setView("settings");1028  }10291030  function handleLock() {1031    clearCanarySuppressions();1032    setEntries([]);1033    setSelectedEntry(null);1034    setEditEntry(undefined);1035    setContentPhase("idle");1036    setView("lock");1037  }10381039  function handleHeaderLock() {1040    // Lock the UI immediately — do not wait for the service worker. If the SW1041    // is dead or slow, the 5s sendMessage timeout would create a dead-click1042    // window. The SW will lock on its next wake regardless.1043    handleLock();1044    void sendMessage({ type: "LOCK" });1045  }10461047  function navigate(dir: number) {1048    const allEntries = entries();1049    if (allEntries.length === 0) return;1050    const currentIndex = selectedIndex();1051    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1052    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1053    setSelectedEntry(allEntries[nextIndex]);1054    setContentPhase("enter");1055    queueContentIdle();1056  }10571058  function openList() {1059    setView("list");1060  }10611062  function openHealth() {1063    setEditEntry(undefined);1064    setView("health");1065  }10661067  function handleOpenFileImport() {1068    setRestoreView("file");1069  }10701071  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;10721073  function handleFixEntry(entry: VaultEntry) {1074    setSelectedEntry(entry);1075    // Passkey-only entries have no editable surface — drop into view mode1076    // instead of opening the Add editor.1077    if (isPasskeyOnly(entry)) {1078      setView("entry");1079      return;1080    }1081    setEditBackView(view()); // preserve caller view so back returns here1082    setEditEntry(entry);1083    setView("add");1084  }10851086  const isLockedView = () => view() === "lock";10871088  async function handleApprovePendingPasskey() {1089    const pending = pendingPasskey();1090    if (!pending) return;1091    if (pending.browser === "firefox" && pending.type === "create") {1092      // Firefox path: popup itself runs navigator.credentials.create. The1093      // background never approved/rejected anything — it just stashed1094      // intent. After the popup-driven flow resolves (success or cancel),1095      // clear the pending key so the popup doesn't re-show this on next open.1096      const { createFirefoxPasskey } = await import("./firefox-passkey");1097      const result = await createFirefoxPasskey(pending);1098      if (!result.ok) {1099        console.warn("Peach Firefox passkey create failed:", result.error);1100      }1101      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1102      setPendingPasskey(null);1103      void loadEntries();1104      window.close();1105      return;1106    }1107    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1108    window.close();1109  }11101111  async function handleDenyPendingPasskey() {1112    const pending = pendingPasskey();1113    if (!pending) return;1114    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1115    window.close();1116  }11171118  function queueContentIdle(after?: () => void) {1119    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1120    contentPhaseTimer = window.setTimeout(() => {1121      setContentPhase("idle");1122      after?.();1123    }, ENTRY_TRANSITION_SETTLE_MS);1124  }11251126  return (1127    <div class="popup-root peach-theme">1128      <Show when={bootState() === "ready"}>1129        <Show1130          when={!pendingPasskey()}1131          fallback={1132            <PasskeyApprovalView1133              type={pendingPasskey()!.type}1134              rpName={pendingPasskey()!.rpName}1135              rpId={pendingPasskey()!.rpId}1136              userName={pendingPasskey()!.userName}1137              userDisplayName={pendingPasskey()!.userDisplayName}1138              onApprove={handleApprovePendingPasskey}1139              onDeny={handleDenyPendingPasskey}1140            />1141          }1142        >1143          <Show1144            when={!isLockedView()}1145            fallback={1146              <Show1147                when={onboarded() || hasVault()}1148                fallback={1149                  <Onboarding1150                    onComplete={() => { setOnboarded(true); }}1151                  />1152                }1153              >1154                <LockView1155                  hasVault={hasVault()}1156                  ready={bootState() === "ready"}1157                  isPro={proStatus()}1158                  forceRecoveryWords={forceRecoveryWords()}1159                  onUnlock={() => {1160                    // RecoveryWordDisplay clears the storage flag before1161                    // calling onDone, so handleUnlock will see no pending1162                    // confirmation and proceed through the normal path.1163                    if (forceRecoveryWords()) setForceRecoveryWords(false);1164                    return handleUnlock();1165                  }}1166                  onBackToOnboarding={1167                    !hasVault()1168                      ? () => setOnboarded(false)1169                      : undefined1170                  }1171                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1172                />1173              </Show>1174            }1175          >1176            <Show1177              when={view() !== "pro-celebration"}1178              fallback={<ProCelebration />}1179            >1180            <section1181              id="hd-shell"1182              class="peach-shell peach-theme"1183              data-surface="extension"1184            >1185            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1186              <PeachWordmark unlocked />1187              <div class="peach-chrome-actions">1188                <button1189                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1190                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1191                  aria-label="Notes"1192                  title="Notes"1193                >1194                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1195                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1196                    <line x1="4" y1="5" x2="10" y2="5" />1197                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1198                    <line x1="4" y1="10" x2="7" y2="10" />1199                  </svg>1200                </button>1201                <button1202                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1203                  onClick={() => setView("settings")}1204                  aria-label="Settings"1205                >1206                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1207                    <path1208                      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"1209                      stroke="currentColor"1210                      stroke-width="0.9"1211                    />1212                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1213                  </svg>1214                </button>1215                <button1216                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1217                  onClick={handleAdd}1218                  aria-label="New entry"1219                >1220                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1221                    <path d="M5.5 1v9M1 5.5h9" />1222                  </svg>1223                </button>1224                <button1225                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1226                  onClick={() => void handleHeaderLock()}1227                  aria-label="Lock vault"1228                >1229                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1230                    <path1231                      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"1232                      stroke="currentColor"1233                      stroke-width="1"1234                      stroke-linecap="round"1235                    />1236                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1237                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1238                  </svg>1239                </button>1240              </div>1241            </header>12421243            <Show when={pendingProNotice() !== null}>1244              <div class="peach-pro-notice-banner">1245                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1246                <button1247                  class="peach-pro-notice-link"1248                  onClick={() => {1249                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1250                    setSettingsInitialSection("license");1251                    setView("settings");1252                    setPendingProNotice(null);1253                  }}1254                >1255                  Learn more →1256                </button>1257                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1258              </div>1259            </Show>12601261            <div class="peach-shell-body">1262              <div class="peach-shell-veil"></div>1263              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1264                <EntryView1265                  entry={selectedEntry()}1266                  currentTabUrl={currentTabUrl()}1267                  entries={entries()}1268                  isPro={proStatus()}1269                  onDelete={handleDelete}1270                  onFieldSaved={() => void loadEntries()}1271                  onEscape={() => { setView("list"); }}1272                  onProGate={(feature) => {1273                    setUpgradeHighlight(feature);1274                    setSettingsInitialSection("license");1275                    setView("settings");1276                  }}1277                />1278              </div>12791280              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1281                <div class="peach-search-bar">1282                  <span class="peach-search-icon">1283                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1284                      <circle cx="5.5" cy="5.5" r="3.75" />1285                      <path d="M8.75 8.75L11.5 11.5" />1286                    </svg>1287                  </span>1288                  <input1289                    class="peach-search-input"1290                    placeholder="search vault..."1291                    autocomplete="off"1292                    aria-label="Search vault entries"1293                    onClick={openList}1294                    onFocus={openList}1295                    readOnly1296                  />1297                  <div class="peach-search-meta">1298                    <span class="peach-search-counter">1299                      {entries().length > 01300                        ? `${selectedIndex() + 1} / ${entries().length}`1301                        : "0 entries"}1302                    </span>1303                    <span class="peach-divider"></span>1304                    <button1305                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1306                      onClick={() => navigate(-1)}1307                      aria-label="Previous entry"1308                      disabled={entries().length === 0}1309                    >1310                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1311                        <path d="M5 1L1 5.5L5 10" />1312                      </svg>1313                    </button>1314                    <button1315                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1316                      onClick={() => navigate(1)}1317                      aria-label="Next entry"1318                      disabled={entries().length === 0}1319                    >1320                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1321                        <path d="M1 1L5 5.5L1 10" />1322                      </svg>1323                    </button>1324                  </div>1325                </div>1326              </section>1327            </div>13281329            {/* Desktop: shown on demand via Show. Native sheet is rendered1330                via Portal below at the document root so its position:fixed1331                isn't trapped by .peach-shell's transform-based animations. */}1332            <Show when={!isNativePlatform() && view() === "list"}>1333              <VaultView1334                entries={entries()}1335                selectedEntryId={selectedEntry()?.id}1336                currentTabDomain={currentTabDomain()}1337                sortOrder={sortOrder()}1338                searchSeed={listSearchSeed()}1339                searchSeedNonce={listSearchSeedNonce()}1340                onSelectEntry={handleSelectEntry}1341                onSortOrderChange={setSortOrder}1342                onAdd={handleAdd}1343                onClose={() => setView("entry")}1344                onOpenTrash={() => setView("trash")}1345                onDeleteMany={handleDeleteMany}1346              />1347            </Show>1348            <Show when={isNativePlatform() && hasVault()}>1349              <Portal>1350                <div1351                  class="peach-vault-sheet"1352                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1353                  style={(() => {1354                    const live = sheetTranslate();1355                    if (live === null) return undefined;1356                    return { transform: `translateY(${live}px)` };1357                  })()}1358                >1359                  <VaultView1360                    entries={entries()}1361                    selectedEntryId={selectedEntry()?.id}1362                    currentTabDomain={currentTabDomain()}1363                    sortOrder={sortOrder()}1364                    searchSeed={listSearchSeed()}1365                    searchSeedNonce={listSearchSeedNonce()}1366                    isNative={true}1367                    onSelectEntry={handleSelectEntry}1368                    onSortOrderChange={setSortOrder}1369                    onAdd={handleAdd}1370                    onClose={() => setView("entry")}1371                    onOpenTrash={() => setView("trash")}1372                    onDeleteMany={handleDeleteMany}1373                  />1374                </div>1375              </Portal>1376            </Show>1377            <Show when={view() === "settings" || settingsExiting()}>1378              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1379                <SettingsView1380                  entriesCount={entries().length}1381                  breachMonitoring={breachMonitoring()}1382                  lockOnClose={lockOnClose()}1383                  autoLockMinutes={autoLockMinutes()}1384                  trashRetentionDays={trashRetentionDays()}1385                  theme={theme()}1386                  accentColor={accentColor()}1387                  textSize={textSize()}1388                  reduceMotion={reduceMotion()}1389                  isPro={proStatus()}1390                  initialSection={settingsInitialSection()}1391                  upgradeHighlight={upgradeHighlight()}1392                  isExiting={settingsExiting()}1393                  onBreachMonitoringChange={applyBreachMonitoring}1394                  onLockOnCloseChange={applyLockOnClose}1395                  onAutoLockMinutesChange={applyAutoLockMinutes}1396                  onTrashRetentionChange={applyTrashRetention}1397                  onThemeChange={applyTheme}1398                  onAccentChange={applyAccentColor}1399                  onTextSizeChange={applyTextSize}1400                  onReduceMotionChange={applyReduceMotion}1401                  shortcuts={shortcutBindings()}1402                  onShortcutsChange={applyShortcuts}1403                  onLicenseChange={async () => {1404                    // After activation/deactivation: refresh Pro status,1405                    // re-load entries (defensive — signal state can drift if1406                    // the SW briefly restarts during the verify+save round-trip),1407                    // and replay the Pro celebration if this is the first time1408                    // a valid Pro license is seen on this device.1409                    await refreshProStatus();1410                    void loadEntries();1411                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1412                    if ((should as { ok: boolean; data?: boolean }).data === true) {1413                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1414                      setView("pro-celebration");1415                      window.setTimeout(() => setView("settings"), 2500);1416                    }1417                  }}1418                  onBack={() => {1419                    setSettingsExiting(true);1420                    window.setTimeout(() => {1421                      setSettingsExiting(false);1422                      setSettingsInitialSection(null);1423                      setUpgradeHighlight(null);1424                      handleBack();1425                    }, 200);1426                  }}1427                  onImport={() => setView("import")}1428                  onExport={() => setView("export")}1429                  onBreachCheckDone={loadEntries}1430                  onOpenHealth={openHealth}1431                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("chirp-sync"); }}1432                  onOpenFileImport={handleOpenFileImport}1433                  onOpenPanic={() => setView("panic")}1434                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1435                  onOpenCodexRestore={() => setView("codex-restore")}1436                  onCardChange={setSettingsActiveCard}1437                  onProGate={(feature) => {1438                    setUpgradeHighlight(feature);1439                    setSettingsInitialSection("license");1440                  }}1441                />1442              </Suspense>1443            </Show>1444            <Show when={view() === "codex-generate"}>1445              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1446                <CodexGenerateView1447                  isPro={proStatus()}1448                  onBack={() => setView("settings")}1449                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1450                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1451                  onVaultLocked={() => handleLock()}1452                />1453              </Suspense>1454            </Show>1455            <Show when={view() === "codex-restore"}>1456              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1457                <CodexRestoreView1458                  onBack={() => setView("lock")}1459                  onRestoreSuccess={async () => {1460                    // After restore the vault is unlocked; refresh entries1461                    // and route to the main vault list. handleUnlock is the1462                    // canonical post-unlock setup path.1463                    await handleUnlock();1464                  }}1465                />1466              </Suspense>1467            </Show>1468            <Show when={view() === "chirp-sync"}>1469              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1470                <ChirpSyncView1471                  isPro={proStatus()}1472                  onBack={() => setView("settings")}1473                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1474                />1475              </Suspense>1476            </Show>1477            <Show when={view() === "add"}>1478              <AddView1479                entry={editEntry()}1480                entries={entries()}1481                onBack={handleBack}1482                onSave={handleSave}1483              />1484            </Show>1485            <Show when={view() === "import"}>1486              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1487                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1488              </Suspense>1489            </Show>1490            <Show when={view() === "export"}>1491              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1492                <ExportView onBack={handleExportBack} />1493              </Suspense>1494            </Show>1495            <Show when={view() === "panic"}>1496              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1497                <PanicView1498                  onCancel={() => setView("settings")}1499                  onOpenExport={() => {1500                    setReturnToPanic(true);1501                    setView("export");1502                  }}1503                  onDestroyed={async () => {1504                    clearCanarySuppressions();1505                    setEntries([]);1506                    setSelectedEntry(null);1507                    setEditEntry(undefined);1508                    setHasVault(false);1509                    setOnboarded(false);1510                    setProStatus(false);1511                    setPendingPasskey(null);1512                    setUpgradeHighlight(null);1513                    setSettingsInitialSection(null);1514                    setPendingProNotice(null);1515                    setPendingCelebration(false);1516                    setReturnToPanic(false);1517                    setContentPhase("idle");1518                    setView("lock");1519                  }}1520                />1521              </Suspense>1522            </Show>1523            {/* Health stays mounted while editing an entry from it so1524                computeReused() doesn't rerun on every cancel/back. */}1525            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1526              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1527                <HealthView1528                  entries={entries()}1529                  isPro={proStatus()}1530                  onFixEntry={handleFixEntry}1531                  onBack={() => setView("settings")}1532                  onRefresh={loadEntries}1533                  hidden={view() !== "health"}1534                />1535              </Suspense>1536            </Show>1537            <Show when={view() === "trash"}>1538              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1539                <TrashView1540                  onBack={() => setView("list")}1541                  onRestored={() => void loadEntries()}1542                />1543              </Suspense>1544            </Show>1545            <Show when={showNotes()}>1546              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1547                <NotesMode1548                  notes={entries().filter((e) => e.type === "note")}1549                  initialNoteId={openNoteId()}1550                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1551                  onNoteListChanged={() => void loadEntries()}1552                />1553              </div>1554            </Show>1555            <Show when={restoreView() === "file"}>1556              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1557                <ImportView1558                  mode="onboarding"1559                  replacesExistingVault={true}1560                  onBack={() => setRestoreView(null)}1561                  onImport={async () => {1562                    setRestoreView(null);1563                    await handleUnlock();1564                  }}1565                />1566              </Suspense>1567            </Show>1568            </section>1569            </Show>1570          </Show>1571        </Show>1572      </Show>1573      <Show when={showShortcutsHelp()}>1574        <ShortcutsHelpOverlay1575          bindings={shortcutBindings()}1576          onClose={() => setShowShortcutsHelp(false)}1577        />1578      </Show>1579    </div>1580  );1581}15821583function ShortcutsHelpOverlay(props: {1584  bindings: Record<ShortcutAction, Keybinding>;1585  onClose: () => void;1586}) {1587  return (1588    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1589      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1590        <div class="peach-shortcuts-help-head">1591          <h3>Keyboard shortcuts</h3>1592          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1593        </div>1594        <div class="peach-shortcuts-help-body">1595          <p class="peach-settings-sub-label">ENTRY VIEW</p>1596          <ul>1597            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1598              <li>1599                <span>{d.label}</span>1600                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1601              </li>1602            ))}1603          </ul>1604          <p class="peach-settings-sub-label">ANYWHERE</p>1605          <ul>1606            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1607              <li>1608                <span>{d.label}</span>1609                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1610              </li>1611            ))}1612          </ul>1613        </div>1614      </div>1615    </div>1616  );1617}