App.tsx

68.9 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 type { IncomingPairingRequest } from "../shared/sync-types";8import { isPasskeyOnly } from "../shared/types";9import { LockView } from "./views/Lock";10import { Onboarding } from "./views/Onboarding";11import { NotesMode } from "./views/NotesMode";12import { ProCelebration } from "./views/ProCelebration";13import { VaultView, type SortOrder } from "./views/Vault";14import { EntryView } from "./views/Entry";15import { AddView } from "./views/Add";16import { PeachMark, PeachWordmark } from "./components/PeachMark";17import { PasskeyApprovalView } from "./views/PasskeyApproval";18import { extractDomain } from "../shared/domain";19import { popupCopy } from "./copy";20import {21  DEFAULT_BINDINGS,22  formatKeybinding,23  getActiveBindings,24  matchKeybinding,25  SHORTCUT_DESCRIPTORS,26  type Keybinding,27  type ShortcutAction,28} from "../shared/shortcuts";29import { generateTOTP } from "../crypto/totp";30import { isNativePlatform, nativePlugin } from "../shared/native";3132export { sendMessage } from "../shared/bridge";3334const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));35const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));36const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));37const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));38const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));39const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));40const SyncPairingView = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.SyncPairingView })));41const AddDeviceView   = lazy(() => import("./views/SyncPairing").then(m => ({ default: m.AddDeviceView })));42const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));43const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));4445type View =46  | "lock"47  | "pro-celebration"48  | "entry"49  | "list"50  | "add"51  | "settings"52  | "sync-pairing"53  | "sync-add-device"54  | "import"55  | "export"56  | "health"57  | "trash"58  | "panic"59  | "codex-generate"60  | "codex-restore";61type BootState = "loading" | "ready";6263const canarySuppressMap = new Map<string, boolean>();64let shellRingAnimation: Animation | null = null;6566export function isCanarySuppressed(entryId: string): boolean {67  return canarySuppressMap.get(entryId) ?? false;68}6970export function setCanarySuppressed(entryId: string, suppressed: boolean): void {71  canarySuppressMap.set(entryId, suppressed);72}7374export function clearCanarySuppressions(): void {75  canarySuppressMap.clear();76}7778export function triggerRing() {79  const shell = document.getElementById("hd-shell");80  if (!shell) return;8182  shellRingAnimation?.cancel();83  shell.dataset.glowing = "true";84  const animation = shell.animate(85    [86      { offset: 0, boxShadow: "var(--copy-shadow)" },87      {88        offset: 0.3,89        boxShadow:90          "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)",91      },92      { offset: 1, boxShadow: "var(--copy-shadow)" },93    ],94    {95      duration: 720,96      easing: "cubic-bezier(0.4, 0, 0.2, 1)",97      fill: "none",98    }99  );100  shellRingAnimation = animation;101  const clearGlow = () => {102    if (shellRingAnimation !== animation) return;103    shellRingAnimation = null;104    delete shell.dataset.glowing;105  };106  animation.onfinish = clearGlow;107  animation.oncancel = clearGlow;108}109110111export function triggerPipPulse() {112  const pip = document.querySelector(".peach-status-pip, .pip");113  if (pip) {114    pip.classList.remove("pulse");115    void (pip as HTMLElement).offsetWidth;116    pip.classList.add("pulse");117  }118}119120const ENTRY_TRANSITION_SETTLE_MS = 135;121122export default function App() {123  const [bootState, setBootState] = createSignal<BootState>("loading");124  const [view, setView] = createSignal<View>("lock");125  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,126  // CSS transition takes over for snap animation).127  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);128  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(129    "enter"130  );131  const [contentTransitioning, setContentTransitioning] = createSignal(false);132  const [hasVault, setHasVault] = createSignal(false);133  const [onboarded, setOnboarded] = createSignal(true);134  const [entries, setEntries] = createSignal<VaultEntry[]>([]);135  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);136  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);137  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");138  const [theme, setTheme] = createSignal<"dark" | "light">("dark");139  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");140  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);141  const [lockOnClose, setLockOnClose] = createSignal(true);142  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);143  const [breachMonitoring, setBreachMonitoring] = createSignal(true);144  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);145  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);146  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);147  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);148  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);149  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");150  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");151  // Cached Pro status — synchronous for render paths. Background's152  // GET_LICENSE is async, but render-time reads of isPro() must not block.153  // Refreshed at boot, after activate/deactivate, and whenever the popup154  // re-opens onto a stored license that has changed via another window.155  const [proStatus, setProStatus] = createSignal(false);156  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);157  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);158  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");159  const [listSearchSeed, setListSearchSeed] = createSignal("");160  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);161  const [pendingCelebration, setPendingCelebration] = createSignal(false);162  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);163  const [incomingPair, setIncomingPair] = createSignal<IncomingPairingRequest | null>(null);164  const [recentPairToast, setRecentPairToast] = createSignal<string | null>(null);165  const [incomingPairResponding, setIncomingPairResponding] = createSignal(false);166  const [incomingPairTick, setIncomingPairTick] = createSignal(0);167  const incomingPairSecondsLeft = () => {168    void incomingPairTick();169    const req = incomingPair();170    if (!req) return 0;171    return Math.max(0, Math.ceil((req.expiresAt - Date.now()) / 1000));172  };173  // True while Panic Step 1 has bounced the user out to Export. When Export's174  // onBack fires we return to Panic instead of Settings so the user keeps the175  // destruction context they came from.176  const [returnToPanic, setReturnToPanic] = createSignal(false);177  const [showNotes, setShowNotes] = createSignal(false);178  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);179  // Set on popup boot when peach_recovery_pending flag is found in session180  // storage — instructs LockView to skip the unlock UI and open the recovery181  // words confirmation surface instead. Cleared via handleUnlock once the182  // user has typed the 3 confirmation words.183  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);184185  let contentPhaseTimer: number | undefined;186187  function applyAccent(name: AccentColorName) {188    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;189    const hex = color.hex;190    document.documentElement.style.setProperty("--peach-accent", hex);191    // Ambient surface variables — derived from the accent so surfaces shift192    // subtly toward the accent hue rather than staying fixed warm-brown.193    document.documentElement.style.setProperty("--peach-glow", hex + "2A");194    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");195    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");196  }197198  createEffect(() => {199    applyAccent(accentColor());200  });201202  createEffect(() => {203    document.documentElement.classList.toggle("light", theme() === "light");204    document.body.classList.toggle("light", theme() === "light");205  });206207  createEffect(() => {208    document.documentElement.setAttribute("data-text-size", textSize());209  });210211  createEffect(() => {212    if (reduceMotion()) {213      document.documentElement.setAttribute("data-motion", "reduce");214    } else {215      document.documentElement.removeAttribute("data-motion");216    }217  });218219  const selectedIndex = createMemo(() => {220    const currentId = selectedEntry()?.id;221    if (!currentId) return entries().length > 0 ? 0 : -1;222    return entries().findIndex((entry) => entry.id === currentId);223  });224225  async function applyAccentColor(name: AccentColorName) {226    applyAccent(name);227    setAccentColor(name);228    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });229  }230231  async function applyTheme(t: "dark" | "light") {232    setTheme(t);233    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });234  }235236  async function applyTextSize(size: "small" | "medium" | "large") {237    setTextSize(size);238    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });239  }240241  async function applyReduceMotion(enabled: boolean) {242    setReduceMotion(enabled);243    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });244  }245246  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload247  // small and lets future default updates land for actions the user hasn't248  // touched. Settings sends us the full active map; we filter and store.249  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {250    setShortcutBindings(active);251    const overrides: Record<string, Keybinding> = {};252    for (const action of Object.keys(active) as ShortcutAction[]) {253      const a = active[action];254      const d = DEFAULT_BINDINGS[action];255      const same = a.key === d.key256        && Boolean(a.ctrl)  === Boolean(d.ctrl)257        && Boolean(a.meta)  === Boolean(d.meta)258        && Boolean(a.shift) === Boolean(d.shift)259        && Boolean(a.alt)   === Boolean(d.alt);260      if (!same) overrides[action] = a;261    }262    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });263  }264265  async function applyLockOnClose(enabled: boolean) {266    setLockOnClose(enabled);267    await sendMessage({268      type: "UPDATE_SETTINGS",269      payload: { lockOnClose: enabled },270    });271  }272273  async function applyAutoLockMinutes(minutes: number) {274    setAutoLockMinutes(minutes);275    await sendMessage({276      type: "UPDATE_SETTINGS",277      payload: { autoLockMinutes: minutes },278    });279  }280281  async function applyBreachMonitoring(enabled: boolean) {282    setBreachMonitoring(enabled);283    await sendMessage({284      type: "UPDATE_SETTINGS",285      payload: { breachMonitoring: enabled },286    });287  }288289  onMount(async () => {290    // Resolve the active tab in parallel with the unlock/has-vault queries —291    // openVault()'s smart selection picks the entry matching currentTabDomain,292    // so it must be populated before openVault runs. Previously refreshCurrentTab293    // ran after openVault, leaving popups that booted already-unlocked falling294    // back to loadedEntries[0] instead of the domain match.295    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([296      sendMessage({ type: "IS_UNLOCKED" }),297      sendMessage({ type: "HAS_VAULT" }),298      refreshCurrentTab(),299      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),300    ]);301    const unlocked = Boolean(302      (unlockResponse as { ok: boolean; data?: boolean }).data303    );304    const vaultExists = Boolean(305      (vaultResponse as { ok: boolean; data?: boolean }).data306    );307    const shouldCelebrate = Boolean(308      (celebrationResponse as { ok: boolean; data?: boolean }).data309    );310    setHasVault(vaultExists);311    // Onboarding gate — show once on first install, never again. Existing312    // users (vaultExists) are auto-marked onboarded so they skip the flow313    // even on the very first popup open after this feature ships.314    try {315      const onboarded = await storageGet("peach_onboarded");316      const seen = onboarded === "true";317      if (vaultExists && !seen) {318        await storageSet("peach_onboarded", "true");319        setOnboarded(true);320      } else {321        setOnboarded(seen);322      }323    } catch {324      // storage unavailable — default to onboarded so we never block boot325      setOnboarded(true);326    }327    await Promise.all([restoreSettings(), refreshProStatus()]);328329    // Mark played before any animation so a crash mid-sequence never replays it330    if (shouldCelebrate) {331      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });332    }333334    // If the user created a vault but hasn't yet confirmed their recovery335    // words, route back to the recovery-words screen instead of opening the336    // entries view. The flag lives in chrome.storage.local so it survives337    // both popup close (SW suppresses lock-on-close) and full browser338    // restart (handleUnlock checks the same flag after a fresh password339    // unlock). Cleared when confirmation succeeds.340    let recoveryPending = false;341    try {342      const out = await chrome.storage.local?.get("peach_recovery_pending");343      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";344    } catch { /* best-effort */ }345346    // Native: closing the app before recovery-words confirmation means the347    // user didn't finish vault creation. Throw the partial vault away and348    // restart onboarding rather than asking them to unlock a vault they349    // never finished creating. Desktop keeps the existing "unlock to350    // resume" flow because closing the popup there is much more casual.351    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {352      try {353        await chrome.storage.local?.remove([354          "peach_vault_a",355          "peach_vault_b",356          "peach_recovery_pending",357          "peach_onboarded",358          "peach_vault_history",359        ]);360      } catch { /* best-effort */ }361      setHasVault(false);362      setOnboarded(false);363      setView("lock");364      setBootState("ready");365      document.getElementById("pre-lock")?.setAttribute("hidden", "true");366      return;367    }368369    if (recoveryPending && unlocked) {370      // forceRecoveryWords overrides LockView's hasVault gate so the371      // recovery surface renders even though the vault now exists.372      setForceRecoveryWords(true);373      setView("lock");374    } else if (unlocked && vaultExists) {375      await openVault(undefined, shouldCelebrate);376      if (shouldCelebrate) {377        setView("pro-celebration");378        window.setTimeout(() => setView("entry"), 2500);379      }380    } else if (shouldCelebrate) {381      setPendingCelebration(true);382    }383384    await refreshPendingPasskey();385    await refreshIncomingPairing();386    await consumeRecentPairing();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    // Check for pending session-storage notices from the background.408    if (chrome.storage.session) {409      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as410        Record<string, { feature?: string } | undefined>;411      if (session.pendingProGate?.feature) {412        await chrome.storage.session.remove("pendingProGate");413        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);414        setSettingsInitialSection("license");415        setView("settings");416      } else if (session.pendingProNotice?.feature) {417        await chrome.storage.session.remove("pendingProNotice");418        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });419      }420    }421422    // Warm the lazy-module cache so the Suspense fallback never shows for423    // locally-bundled extension views. Without this, the first navigation to424    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which425    // covers the shell and absorbs clicks on the header.426    void Promise.all([427      import("./views/Settings").catch(() => {}),428      import("./views/Import").catch(() => {}),429      import("./views/Export").catch(() => {}),430      import("./views/Health").catch(() => {}),431      import("./views/TrashView").catch(() => {}),432    ]);433434    // Lock-on-close via a persistent port. sendMessage in pagehide is435    // unreliable — the popup context tears down before the message lands.436    // The SW's onConnect listener locks when this port disconnects.437    let popupPort: chrome.runtime.Port | null = null;438    try {439      popupPort = chrome.runtime.connect({ name: "popup" });440    } catch { /* extension context invalidated — ignore */ }441    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });442443    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only444    // reliable signal is appStateChange — setTimeout is killed when the OS445    // backgrounds the app. We measure elapsed background time on resume.446    if (isNativePlatform()) {447      let backgroundedAt: number | null = null;448      let syncPollInterval: ReturnType<typeof setInterval> | null = null;449450      function startSyncPolling() {451        if (syncPollInterval) return;452        syncPollInterval = setInterval(async () => {453          const res = await sendMessage({ type: 'TRIGGER_SYNC' }).catch(() => null);454          const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;455          if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {456            await sendMessage({ type: 'GET_ENTRIES' }).catch(() => null);457          }458        }, 60_000);459      }460461      function stopSyncPolling() {462        if (syncPollInterval) { clearInterval(syncPollInterval); syncPollInterval = null; }463      }464465      const CapApp = nativePlugin<{466        addListener: (467          ev: string,468          cb: (s: { isActive: boolean }) => void,469        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };470      }>("App");471      if (CapApp?.addListener) {472        const sub = CapApp.addListener(473          "appStateChange",474          ({ isActive }: { isActive: boolean }) => {475            if (!isActive) {476              backgroundedAt = Date.now();477              stopSyncPolling();478              return;479            }480            if (backgroundedAt !== null && autoLockMinutes() > 0) {481              const elapsed = Date.now() - backgroundedAt;482              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();483            }484            backgroundedAt = null;485            // Resume polling when app comes to foreground (Pro only).486            if (proStatus()) startSyncPolling();487          }488        );489        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.490        onCleanup(() => {491          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});492          stopSyncPolling();493        });494      }495496      // L12/COR-011: foreground idle autolock. appStateChange only fires when497      // the OS backgrounds the app — if the user idles with the screen on,498      // chrome.alarms is no-op'd in Capacitor so the vault would stay open499      // indefinitely. Poll every 30s and lock if elapsed since last user500      // interaction exceeds autoLockMinutes.501      let lastUserActivityAt = Date.now();502      const bumpActivity = () => { lastUserActivityAt = Date.now(); };503      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;504      for (const ev of ACTIVITY_EVENTS) {505        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });506      }507      const idleLockInterval = setInterval(() => {508        const minutes = autoLockMinutes();509        if (!minutes || minutes <= 0) return;510        const elapsed = Date.now() - lastUserActivityAt;511        if (elapsed >= minutes * 60_000) {512          lastUserActivityAt = Date.now();513          handleHeaderLock();514        }515      }, 30_000);516      onCleanup(() => {517        clearInterval(idleLockInterval);518        for (const ev of ACTIVITY_EVENTS) {519          document.removeEventListener(ev, bumpActivity, { capture: true });520        }521      });522    }523524    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale525    // entries instead of waiting for the next GET_ENTRIES round-trip.526    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {527      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();528      if (msg?.type === "PRO_GATE_TRIGGERED") {529        setUpgradeHighlight(msg.payload?.feature ?? null);530        setSettingsInitialSection("license");531        setView("settings");532      }533    };534    chrome.runtime.onMessage.addListener(handleRuntimeMessage);535    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));536537    // Android hardware/gesture back. MainActivity fires peach:back; the popup538    // decides what "back" means per surface. Lock+no-vault is the common case539    // — return to onboarding rather than letting the OS dismiss the activity.540    const handlePeachBack = () => {541      // Notes mode captures back first542      if (showNotes()) {543        setShowNotes(false);544        setOpenNoteId(undefined);545        return;546      }547      const v = view();548      if (v === "lock" && !hasVault() && onboarded()) {549        setOnboarded(false);550        return;551      }552      if (v === "list") { setView("entry"); return; }553      if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") {554        handleBack();555        return;556      }557      if (v === "sync-pairing") { setView("settings"); return; }558    };559    window.addEventListener("peach:back", handlePeachBack);560    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));561562    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that563    // peeks from the bottom (search bar handle visible) and drags up to fill564    // the screen. dragOffset is the LIVE finger offset during a drag, in px,565    // 0 when no drag in progress. The wrapper element computes transform =566    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.567    if (isNativePlatform()) {568      let touchStartY = 0;569      let touchStartX = 0;570      let lastY = 0;571      let lastT = 0;572      let dragging = false;573      let captured = false;574      const HORIZONTAL_TOLERANCE = 16;575      const ACTIVATION_DY = 8;576      const PEEK_PX = 60;577578      const onTouchStart = (e: TouchEvent) => {579        const t = e.touches[0];580        if (!t) return;581        const v = view();582        if (v !== "entry" && v !== "list") return;583        // Entry view: only intercept drags starting in the bottom 40%.584        // List view: intercept drags starting in the top 35% (the search/handle row).585        const inBand = v === "entry"586          ? t.clientY > window.innerHeight * 0.6587          : t.clientY < window.innerHeight * 0.35;588        if (!inBand) return;589        touchStartY = lastY = t.clientY;590        touchStartX = t.clientX;591        lastT = e.timeStamp;592        dragging = true;593        captured = false;594      };595596      const onTouchMove = (e: TouchEvent) => {597        if (!dragging) return;598        const t = e.touches[0];599        if (!t) return;600        const dy = t.clientY - touchStartY;601        const dx = Math.abs(t.clientX - touchStartX);602603        if (!captured) {604          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {605            // Looks like a horizontal swipe — release.606            dragging = false;607            return;608          }609          if (Math.abs(dy) < ACTIVATION_DY) return;610          captured = true;611        }612613        // Translate the sheet by dy from its rest (peek) position. Peek is614        // (viewport height - PEEK_PX). Open is 0.615        const v = view();616        const restClosed = window.innerHeight - PEEK_PX;617        const baseTranslate = v === "list" ? 0 : restClosed;618        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));619        setSheetTranslate(next);620        lastY = t.clientY;621        lastT = e.timeStamp;622      };623624      const onTouchEnd = (e: TouchEvent) => {625        if (!dragging) { return; }626        const t = e.changedTouches[0];627        const elapsed = Math.max(1, e.timeStamp - lastT);628        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms629        const wasCaptured = captured;630        dragging = false;631        captured = false;632        const v = view();633634        if (!wasCaptured) {635          // Tap in the peek strip while in entry view → open the vault list.636          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");637          setSheetTranslate(null);638          return;639        }640641        const restClosed = window.innerHeight - PEEK_PX;642        const current = sheetTranslate() ?? restClosed;643644        // Snap rules:645        //   - Strong upward velocity → open646        //   - Strong downward velocity → close647        //   - Otherwise snap to whichever rest is closer648        let nextOpen: boolean;649        if (velocity < -0.05) nextOpen = true;650        else if (velocity > 0.05) nextOpen = false;651        else nextOpen = current < restClosed * 0.5;652653        if (nextOpen && v !== "list") setView("list");654        if (!nextOpen && v !== "entry") setView("entry");655        // Release the live offset so CSS transition handles the snap.656        setSheetTranslate(null);657      };658659      document.addEventListener("touchstart", onTouchStart, { passive: true });660      document.addEventListener("touchmove",  onTouchMove,  { passive: true });661      document.addEventListener("touchend",   onTouchEnd,   { passive: true });662      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });663      onCleanup(() => {664        document.removeEventListener("touchstart", onTouchStart);665        document.removeEventListener("touchmove",  onTouchMove);666        document.removeEventListener("touchend",   onTouchEnd);667      });668    }669670    // Action handlers — keyed by ShortcutAction. The dispatcher below tests671    // each binding against the event and runs the matching handler. New672    // shortcuts only need an entry here; the binding is data, not code.673    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {674      copy_password: () => {675        const entry = selectedEntry();676        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });677      },678      copy_username: () => {679        const entry = selectedEntry();680        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });681      },682      copy_totp: () => {683        const entry = selectedEntry();684        if (!entry?.totp) return;685        try {686          const { code } = generateTOTP(entry.totp);687          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });688        } catch { /* invalid TOTP secret — silent */ }689      },690      new_entry: () => handleAdd(),691      edit_entry: () => {692        const entry = selectedEntry();693        // Passkey-only entries have nothing user-editable in the Add view; the694        // passkey credential itself is opaque. Skip the edit action for them.695        if (!entry || isPasskeyOnly(entry)) return;696        setEditEntry(entry);697        setView("add");698      },699      delete_entry: () => {700        if (selectedEntry()) void handleDelete();701      },702      lock_vault: () => { void handleHeaderLock(); },703      search: () => openList(),704      nav_prev: () => navigate(-1),705      nav_next: () => navigate(1),706      jump_vault: () => setView("entry"),707      jump_settings: () => setView("settings"),708      show_help: () => setShowShortcutsHelp(true),709    };710711    // Actions that are MEANINGFUL only on the entry-detail view. Outside712    // that scope the binding is dormant — pressing C while on Settings713    // does nothing rather than awkwardly copying from a now-stale entry.714    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([715      "copy_password", "copy_username", "copy_totp",716      "edit_entry", "delete_entry", "nav_prev", "nav_next",717    ]);718719    const handleGlobalKeydown = (e: KeyboardEvent) => {720      const v = view();721      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"722        || (e.target as HTMLElement)?.tagName === "TEXTAREA"723        || (e.target as HTMLElement)?.isContentEditable;724      const isPrintableSearchKey =725        e.key.length === 1 &&726        !e.ctrlKey &&727        !e.metaKey &&728        !e.altKey;729730      // No input during the pro celebration sequence731      if (v === "pro-celebration") return;732733      // Help dialog: Escape closes it; eat the keypress so it doesn't734      // also navigate away from the underlying view.735      if (showShortcutsHelp()) {736        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }737        return;738      }739740      // ── Escape — fixed binding (not user-customizable) ───────741      if (e.key === "Escape") {742        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }743        if (v === "list") { setView("entry"); return; }744        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }745        if (v === "sync-pairing") { setView("settings"); return; }746        if (v === "sync-add-device") { setView("sync-pairing"); return; }747      }748749      // Bindings-driven dispatch. Single-key letter bindings without750      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is751      // inside an input, so users can type into search/forms normally.752      const bindings = shortcutBindings();753      for (const action of Object.keys(bindings) as ShortcutAction[]) {754        const binding = bindings[action];755        if (!matchKeybinding(e, binding)) continue;756        // Single-key letter bindings need the input-focus guard. Bindings757        // with any modifier are safe — Ctrl+L doesn't conflict with typing.758        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;759        if (!hasMod && binding.key.length === 1 && inInput) return;760        if (ENTRY_SCOPED.has(action) && v !== "entry") return;761        e.preventDefault();762        SHORTCUT_HANDLERS[action]?.();763        return;764      }765766      // Type-to-search: in entry view, any printable key not consumed by a767      // shortcut above primes the list search seed and opens the list.768      // Kept outside the bindings table because it's a behavior, not a769      // discrete action — every printable character can trigger it.770      if (v === "entry" && !inInput && isPrintableSearchKey) {771        e.preventDefault();772        primeListSearch(e.key);773        return;774      }775    };776    window.addEventListener("keydown", handleGlobalKeydown);777    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));778779    const handleStorageChanged = (780      changes: Record<string, chrome.storage.StorageChange>,781      areaName: string782    ) => {783      if (areaName !== "session") return;784      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {785        return;786      }787      void refreshPendingPasskey();788    };789    chrome.storage.onChanged.addListener(handleStorageChanged);790    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));791  });792793  async function refreshCurrentTab() {794    try {795      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });796      const url = tab?.url ?? tab?.pendingUrl ?? "";797      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");798      // Skip extension/internal URLs — adding chrome://, about:, or799      // chrome-extension:// to a vault entry is never what the user wants.800      const isWebUrl = /^https?:\/\//i.test(url);801      setCurrentTabUrl(isWebUrl ? url : "");802    } catch {803      setCurrentTabDomain("");804      setCurrentTabUrl("");805    }806  }807808  async function refreshPendingPasskey() {809    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });810    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);811  }812813  async function refreshIncomingPairing() {814    const res = await sendMessage({ type: "GET_INCOMING_PAIRING_REQUEST" });815    const data = (res as { ok: boolean; data?: IncomingPairingRequest | null }).data ?? null;816    setIncomingPair(data);817  }818819  // Drains a single one-shot record left by the background when 6-digit820  // pairing succeeded while the popup was closed (or the SyncPairing view was821  // navigated away from before it could show its own success card).822  async function consumeRecentPairing() {823    const res = await sendMessage({ type: "GET_RECENT_PAIRING" });824    const data = (res as { ok: boolean; data?: { deviceName?: string } | null }).data;825    if (data?.deviceName) {826      setRecentPairToast(data.deviceName);827      window.setTimeout(() => setRecentPairToast(null), 4000);828    }829  }830831  async function respondIncomingPairing(accept: boolean) {832    if (incomingPairResponding()) return;833    setIncomingPairResponding(true);834    await sendMessage({ type: "RESPOND_INCOMING_PAIRING", payload: { accept } });835    setIncomingPair(null);836    setIncomingPairResponding(false);837  }838839  // 60-second expiry ticker for the incoming pairing banner. Re-runs when a840  // request appears, ticks once per second, and clears the banner if the841  // request expires while the popup is open.842  createEffect(() => {843    const req = incomingPair();844    if (!req) return;845    const handle = window.setInterval(() => {846      setIncomingPairTick((tick) => tick + 1);847      if (Date.now() >= req.expiresAt) {848        setIncomingPair(null);849        window.clearInterval(handle);850      }851    }, 1000);852    onCleanup(() => window.clearInterval(handle));853  });854855  async function refreshProStatus() {856    const res = await sendMessage({ type: "GET_LICENSE" });857    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;858    setProStatus(Boolean(data?.valid && data?.plan === "pro"));859  }860861  async function restoreSettings() {862    const res = await sendMessage({ type: "GET_SETTINGS" });863    const s = (res as { ok: boolean; data?: any }).data ?? {};864    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {865      setAccentColor(s.accentColor as AccentColorName);866    }867    setTheme(s.theme === "light" ? "light" : "dark");868    if (s.textSize === "small" || s.textSize === "large") {869      setTextSize(s.textSize);870    } else {871      setTextSize("medium");872    }873    setReduceMotion(s.reduceMotion === true);874    setLockOnClose(s.lockOnClose !== false);875    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);876    setBreachMonitoring(s.breachMonitoring !== false);877    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);878    setShortcutBindings(getActiveBindings(s.shortcuts));879  }880881  async function applyTrashRetention(days: number) {882    setTrashRetentionDays(days);883    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });884  }885886  function primeListSearch(seed: string) {887    setListSearchSeed(seed);888    setListSearchSeedNonce((value) => value + 1);889    openList();890  }891892  // Returns null when it detected a dead service worker and triggered handleLock().893  // Callers that need to abort (e.g. openVault) check for null rather than relying894  // on view() state, which may already be "lock" during normal startup flows.895  async function loadEntries(): Promise<VaultEntry[] | null> {896    const response = await sendMessage({ type: "GET_ENTRIES" });897    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };898899    // If the service worker was killed and restarted (MV3 workers sleep), the900    // vault will be locked again — or the worker may not respond at all.901    // In either case, send the user to the lock screen rather than silently902    // showing an empty vault (which looks like data loss).903    if (!res.ok) {904      if (905        res.error === "vault_locked" ||906        res.error === "SERVICE_WORKER_UNAVAILABLE" ||907        (typeof res.error === "string" && res.error.includes("locked"))908      ) {909        handleLock();910        return null; // signal emergency lock to callers911      }912      return [];913    }914915    const loadedEntries = res.data ?? [];916    setEntries(loadedEntries);917918    const currentId = selectedEntry()?.id;919    if (currentId) {920      setSelectedEntry(921        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null922      );923    }924925    return loadedEntries;926  }927928  async function openVault(preferredEntryId?: string, skipViewSet = false) {929    // Desktop: fire-and-forget sync on every vault open (Pro only).930    // Never blocks popup load; refreshes entries if new data arrives.931    if (!isNativePlatform() && proStatus()) {932      void sendMessage({ type: 'TRIGGER_SYNC' }).then((res) => {933        const r = res as { ok?: boolean; data?: { syncedCount?: number } } | null;934        if (r?.ok && (r?.data?.syncedCount ?? 0) > 0) {935          void loadEntries();936        }937      }).catch(() => {});938    }939940    // Purge expired trash entries on each vault open941    const retDays = trashRetentionDays();942    if (retDays > 0) {943      void sendMessage({944        type: "PURGE_EXPIRED_TRASH",945        payload: { retentionMs: retDays * 86_400_000 },946      });947    }948949    const loadedEntries = await loadEntries();950951    // null means loadEntries() triggered an emergency lock (service worker died).952    // Don't override it by setting view back to "entry" with an empty vault.953    if (loadedEntries === null) return;954955    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry956    let nextSelectedEntry: VaultEntry | null = null;957    if (preferredEntryId) {958      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;959    }960    if (!nextSelectedEntry) {961      const tabDomain = currentTabDomain();962      if (tabDomain) {963        nextSelectedEntry = loadedEntries.find((e) => {964          if (e.type === "login") {965            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;966            for (const extra of e.additionalUrls ?? []) {967              if ((extractDomain(extra) ?? "") === tabDomain) return true;968            }969            return false;970          }971          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;972          return false;973        }) ?? null;974      }975    }976    nextSelectedEntry ??= loadedEntries[0] ?? null;977978    setSelectedEntry(nextSelectedEntry);979    setEditEntry(undefined);980    setContentTransitioning(false);981    setContentPhase("enter");982    queueContentIdle();983    if (!skipViewSet) setView("entry");984  }985986  async function handleUnlock() {987    // If the user previously created a vault but hadn't yet confirmed their988    // recovery words (and the browser was closed before they could), the989    // peach_recovery_pending flag is still set in storage.local. Re-route990    // back to the recovery surface so they finish the confirmation step991    // before reaching the entries view — the words can be re-derived now992    // that the vault is unlocked again.993    let recoveryPending = false;994    try {995      const out = await chrome.storage.local?.get("peach_recovery_pending");996      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";997    } catch { /* best-effort */ }998    if (recoveryPending) {999      setForceRecoveryWords(true);1000      setView("lock");1001      triggerPipPulse();1002      await restoreSettings();1003      return;1004    }1005    setHasVault(true);1006    triggerPipPulse();1007    await restoreSettings();1008    const celebrating = pendingCelebration();1009    if (celebrating) {1010      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1011      setPendingCelebration(false);1012    }1013    await openVault(undefined, celebrating);1014    if (celebrating) {1015      setView("pro-celebration");1016      window.setTimeout(() => setView("entry"), 2500);1017    }1018  }10191020  function handleSelectEntry(entry: VaultEntry) {1021    if (entry.type === "note") {1022      setOpenNoteId(entry.id);1023      setShowNotes(true);1024      return;1025    }1026    setSelectedEntry(entry);1027    setContentTransitioning(false);1028    setContentPhase("enter");1029    queueContentIdle();1030    setView("entry");1031  }10321033  function handleAdd() {1034    setEditEntry(undefined);1035    setView("add");1036  }10371038  async function handleDelete() {1039    const entry = selectedEntry();1040    if (!entry) return;1041    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1042    const loadedEntries = await loadEntries() ?? [];1043    setSelectedEntry(loadedEntries[0] ?? null);1044    setView("entry");1045  }10461047  async function handleDeleteMany(ids: string[]) {1048    for (const id of ids) {1049      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1050    }1051    const loadedEntries = await loadEntries() ?? [];1052    // If the currently selected entry was among the deleted, move to first1053    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1054    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1055  }10561057  async function handleSave(savedEntry?: VaultEntry) {1058    await openVault(savedEntry?.id);1059  }10601061  function handleBack() {1062    setEditEntry(undefined);1063    setView("entry");1064  }10651066  function handleLock() {1067    clearCanarySuppressions();1068    setEntries([]);1069    setSelectedEntry(null);1070    setEditEntry(undefined);1071    setContentPhase("idle");1072    setView("lock");1073  }10741075  function handleHeaderLock() {1076    // Lock the UI immediately — do not wait for the service worker. If the SW1077    // is dead or slow, the 5s sendMessage timeout would create a dead-click1078    // window. The SW will lock on its next wake regardless.1079    handleLock();1080    void sendMessage({ type: "LOCK" });1081  }10821083  function navigate(dir: number) {1084    const allEntries = entries();1085    if (allEntries.length === 0) return;1086    const currentIndex = selectedIndex();1087    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1088    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1089    setSelectedEntry(allEntries[nextIndex]);1090    setContentPhase("enter");1091    queueContentIdle();1092  }10931094  function openList() {1095    setView("list");1096  }10971098  function openHealth() {1099    setEditEntry(undefined);1100    setView("health");1101  }11021103  function handleOpenFileImport() {1104    setRestoreView("file");1105  }11061107  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11081109  function handleFixEntry(entry: VaultEntry) {1110    // Passkey-only entries have no editable surface — drop into view mode1111    // instead of opening the Add editor.1112    if (isPasskeyOnly(entry)) {1113      setSelectedEntry(entry);1114      setView("entry");1115      return;1116    }1117    setEditEntry(entry);1118    setView("add");1119  }11201121  const isLockedView = () => view() === "lock";11221123  async function handleApprovePendingPasskey() {1124    const pending = pendingPasskey();1125    if (!pending) return;1126    if (pending.browser === "firefox" && pending.type === "create") {1127      // Firefox path: popup itself runs navigator.credentials.create. The1128      // background never approved/rejected anything — it just stashed1129      // intent. After the popup-driven flow resolves (success or cancel),1130      // clear the pending key so the popup doesn't re-show this on next open.1131      const { createFirefoxPasskey } = await import("./firefox-passkey");1132      const result = await createFirefoxPasskey(pending);1133      if (!result.ok) {1134        console.warn("Peach Firefox passkey create failed:", result.error);1135      }1136      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1137      setPendingPasskey(null);1138      void loadEntries();1139      window.close();1140      return;1141    }1142    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1143    window.close();1144  }11451146  async function handleDenyPendingPasskey() {1147    const pending = pendingPasskey();1148    if (!pending) return;1149    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1150    window.close();1151  }11521153  function queueContentIdle(after?: () => void) {1154    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1155    contentPhaseTimer = window.setTimeout(() => {1156      setContentPhase("idle");1157      after?.();1158    }, ENTRY_TRANSITION_SETTLE_MS);1159  }11601161  return (1162    <div class="popup-root peach-theme">1163      <Show when={bootState() === "ready"}>1164        <Show1165          when={!pendingPasskey()}1166          fallback={1167            <PasskeyApprovalView1168              type={pendingPasskey()!.type}1169              rpName={pendingPasskey()!.rpName}1170              rpId={pendingPasskey()!.rpId}1171              userName={pendingPasskey()!.userName}1172              userDisplayName={pendingPasskey()!.userDisplayName}1173              onApprove={handleApprovePendingPasskey}1174              onDeny={handleDenyPendingPasskey}1175            />1176          }1177        >1178          <Show1179            when={!isLockedView()}1180            fallback={1181              <Show1182                when={onboarded() || hasVault()}1183                fallback={1184                  <Onboarding1185                    onComplete={() => { setOnboarded(true); }}1186                  />1187                }1188              >1189                <LockView1190                  hasVault={hasVault()}1191                  ready={bootState() === "ready"}1192                  isPro={proStatus()}1193                  forceRecoveryWords={forceRecoveryWords()}1194                  onUnlock={() => {1195                    // RecoveryWordDisplay clears the storage flag before1196                    // calling onDone, so handleUnlock will see no pending1197                    // confirmation and proceed through the normal path.1198                    if (forceRecoveryWords()) setForceRecoveryWords(false);1199                    return handleUnlock();1200                  }}1201                  onBackToOnboarding={1202                    !hasVault()1203                      ? () => setOnboarded(false)1204                      : undefined1205                  }1206                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1207                />1208              </Show>1209            }1210          >1211            <Show1212              when={view() !== "pro-celebration"}1213              fallback={<ProCelebration />}1214            >1215            <section1216              id="hd-shell"1217              class="peach-shell peach-theme"1218              data-surface="extension"1219            >1220            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1221              <PeachWordmark unlocked />1222              <div class="peach-chrome-actions">1223                <button1224                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1225                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1226                  aria-label="Notes"1227                  title="Notes"1228                >1229                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1230                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1231                    <line x1="4" y1="5" x2="10" y2="5" />1232                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1233                    <line x1="4" y1="10" x2="7" y2="10" />1234                  </svg>1235                </button>1236                <button1237                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1238                  onClick={() => setView("settings")}1239                  aria-label="Settings"1240                >1241                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1242                    <path1243                      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"1244                      stroke="currentColor"1245                      stroke-width="0.9"1246                    />1247                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1248                  </svg>1249                </button>1250                <button1251                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1252                  onClick={handleAdd}1253                  aria-label="New entry"1254                >1255                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1256                    <path d="M5.5 1v9M1 5.5h9" />1257                  </svg>1258                </button>1259                <button1260                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1261                  onClick={() => void handleHeaderLock()}1262                  aria-label="Lock vault"1263                >1264                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1265                    <path1266                      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"1267                      stroke="currentColor"1268                      stroke-width="1"1269                      stroke-linecap="round"1270                    />1271                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1272                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1273                  </svg>1274                </button>1275              </div>1276            </header>12771278            <Show when={recentPairToast()}>1279              <div class="peach-pair-toast" role="status" aria-live="polite">1280                Paired with <strong>{recentPairToast()}</strong>1281              </div>1282            </Show>12831284            <Show when={incomingPair() !== null}>1285              <div class="peach-pair-request-banner" role="dialog" aria-label="Pairing request">1286                <div class="peach-pair-request-header">1287                  <span class="peach-pair-request-mark"><PeachMark class="peach-pair-request-icon" /></span>1288                  <span class="peach-pair-request-title">Pairing request</span>1289                  <span class="peach-pair-request-countdown">{incomingPairSecondsLeft()}s</span>1290                </div>1291                <p class="peach-pair-request-body">1292                  <strong>{incomingPair()!.deviceName}</strong> wants to sync with this Peach.1293                </p>1294                <div class="peach-pair-request-actions">1295                  <button1296                    class="peach-btn peach-btn--ghost peach-btn--sm"1297                    onClick={() => void respondIncomingPairing(false)}1298                    disabled={incomingPairResponding()}1299                  >1300                    Reject1301                  </button>1302                  <button1303                    class="peach-btn peach-btn--accent peach-btn--sm"1304                    onClick={() => void respondIncomingPairing(true)}1305                    disabled={incomingPairResponding()}1306                  >1307                    Accept1308                  </button>1309                </div>1310              </div>1311            </Show>13121313            <Show when={pendingProNotice() !== null}>1314              <div class="peach-pro-notice-banner">1315                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1316                <button1317                  class="peach-pro-notice-link"1318                  onClick={() => {1319                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1320                    setSettingsInitialSection("license");1321                    setView("settings");1322                    setPendingProNotice(null);1323                  }}1324                >1325                  Learn more →1326                </button>1327                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1328              </div>1329            </Show>13301331            <div class="peach-shell-body">1332              <div class="peach-shell-veil"></div>1333              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1334                <EntryView1335                  entry={selectedEntry()}1336                  currentTabUrl={currentTabUrl()}1337                  entries={entries()}1338                  onDelete={handleDelete}1339                  onFieldSaved={() => void loadEntries()}1340                  onEscape={() => { setView("list"); }}1341                />1342              </div>13431344              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>1345                <div class="peach-search-bar">1346                  <span class="peach-search-icon">1347                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1348                      <circle cx="5.5" cy="5.5" r="3.75" />1349                      <path d="M8.75 8.75L11.5 11.5" />1350                    </svg>1351                  </span>1352                  <input1353                    class="peach-search-input"1354                    placeholder="search vault..."1355                    autocomplete="off"1356                    aria-label="Search vault entries"1357                    onClick={openList}1358                    onFocus={openList}1359                    readOnly1360                  />1361                  <div class="peach-search-meta">1362                    <span class="peach-search-counter">1363                      {entries().length > 01364                        ? `${selectedIndex() + 1} / ${entries().length}`1365                        : "0 entries"}1366                    </span>1367                    <span class="peach-divider"></span>1368                    <button1369                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1370                      onClick={() => navigate(-1)}1371                      aria-label="Previous entry"1372                      disabled={entries().length === 0}1373                    >1374                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1375                        <path d="M5 1L1 5.5L5 10" />1376                      </svg>1377                    </button>1378                    <button1379                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1380                      onClick={() => navigate(1)}1381                      aria-label="Next entry"1382                      disabled={entries().length === 0}1383                    >1384                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1385                        <path d="M1 1L5 5.5L1 10" />1386                      </svg>1387                    </button>1388                  </div>1389                </div>1390              </section>1391            </div>13921393            {/* Desktop: shown on demand via Show. Native sheet is rendered1394                via Portal below at the document root so its position:fixed1395                isn't trapped by .peach-shell's transform-based animations. */}1396            <Show when={!isNativePlatform() && view() === "list"}>1397              <VaultView1398                entries={entries()}1399                selectedEntryId={selectedEntry()?.id}1400                currentTabDomain={currentTabDomain()}1401                sortOrder={sortOrder()}1402                searchSeed={listSearchSeed()}1403                searchSeedNonce={listSearchSeedNonce()}1404                onSelectEntry={handleSelectEntry}1405                onSortOrderChange={setSortOrder}1406                onAdd={handleAdd}1407                onClose={() => setView("entry")}1408                onOpenTrash={() => setView("trash")}1409                onDeleteMany={handleDeleteMany}1410              />1411            </Show>1412            <Show when={isNativePlatform() && hasVault()}>1413              <Portal>1414                <div1415                  class="peach-vault-sheet"1416                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1417                  style={(() => {1418                    const live = sheetTranslate();1419                    if (live === null) return undefined;1420                    return { transform: `translateY(${live}px)` };1421                  })()}1422                >1423                  <VaultView1424                    entries={entries()}1425                    selectedEntryId={selectedEntry()?.id}1426                    currentTabDomain={currentTabDomain()}1427                    sortOrder={sortOrder()}1428                    searchSeed={listSearchSeed()}1429                    searchSeedNonce={listSearchSeedNonce()}1430                    onSelectEntry={handleSelectEntry}1431                    onSortOrderChange={setSortOrder}1432                    onAdd={handleAdd}1433                    onClose={() => setView("entry")}1434                    onOpenTrash={() => setView("trash")}1435                    onDeleteMany={handleDeleteMany}1436                  />1437                </div>1438              </Portal>1439            </Show>1440            <Show when={view() === "settings"}>1441              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1442                <SettingsView1443                  entriesCount={entries().length}1444                  breachMonitoring={breachMonitoring()}1445                  lockOnClose={lockOnClose()}1446                  autoLockMinutes={autoLockMinutes()}1447                  trashRetentionDays={trashRetentionDays()}1448                  theme={theme()}1449                  accentColor={accentColor()}1450                  textSize={textSize()}1451                  reduceMotion={reduceMotion()}1452                  isPro={proStatus()}1453                  initialSection={settingsInitialSection()}1454                  upgradeHighlight={upgradeHighlight()}1455                  onBreachMonitoringChange={applyBreachMonitoring}1456                  onLockOnCloseChange={applyLockOnClose}1457                  onAutoLockMinutesChange={applyAutoLockMinutes}1458                  onTrashRetentionChange={applyTrashRetention}1459                  onThemeChange={applyTheme}1460                  onAccentChange={applyAccentColor}1461                  onTextSizeChange={applyTextSize}1462                  onReduceMotionChange={applyReduceMotion}1463                  shortcuts={shortcutBindings()}1464                  onShortcutsChange={applyShortcuts}1465                  onLicenseChange={async () => {1466                    // After activation/deactivation: refresh Pro status,1467                    // re-load entries (defensive — signal state can drift if1468                    // the SW briefly restarts during the verify+save round-trip),1469                    // and replay the Pro celebration if this is the first time1470                    // a valid Pro license is seen on this device.1471                    await refreshProStatus();1472                    void loadEntries();1473                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1474                    if ((should as { ok: boolean; data?: boolean }).data === true) {1475                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1476                      setView("pro-celebration");1477                      window.setTimeout(() => setView("settings"), 2500);1478                    }1479                  }}1480                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1481                  onImport={() => setView("import")}1482                  onExport={() => setView("export")}1483                  onBreachCheckDone={loadEntries}1484                  onOpenHealth={openHealth}1485                  onOpenSyncPairing={() => setView("sync-pairing")}1486                  onOpenFileImport={handleOpenFileImport}1487                  onOpenPanic={() => setView("panic")}1488                  onOpenCodexGenerate={() => setView("codex-generate")}1489                  onOpenCodexRestore={() => setView("codex-restore")}1490                />1491              </Suspense>1492            </Show>1493            <Show when={view() === "codex-generate"}>1494              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1495                <CodexGenerateView1496                  isPro={proStatus()}1497                  onBack={() => setView("settings")}1498                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1499                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1500                />1501              </Suspense>1502            </Show>1503            <Show when={view() === "codex-restore"}>1504              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1505                <CodexRestoreView1506                  onBack={() => setView("lock")}1507                  onRestoreSuccess={async () => {1508                    // After restore the vault is unlocked; refresh entries1509                    // and route to the main vault list. handleUnlock is the1510                    // canonical post-unlock setup path.1511                    await handleUnlock();1512                  }}1513                />1514              </Suspense>1515            </Show>1516            <Show when={view() === "sync-pairing"}>1517              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1518                <SyncPairingView1519                  isPro={proStatus()}1520                  onAddDevice={() => setView("sync-add-device")}1521                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1522                  onBack={() => setView("settings")}1523                />1524              </Suspense>1525            </Show>1526            <Show when={view() === "sync-add-device"}>1527              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1528                <AddDeviceView1529                  onClose={() => setView("sync-pairing")}1530                  onPaired={() => setView("sync-pairing")}1531                />1532              </Suspense>1533            </Show>1534            <Show when={view() === "add"}>1535              <AddView1536                entry={editEntry()}1537                entries={entries()}1538                onBack={handleBack}1539                onSave={handleSave}1540              />1541            </Show>1542            <Show when={view() === "import"}>1543              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1544                <ImportView onBack={handleBack} onImport={handleSave} />1545              </Suspense>1546            </Show>1547            <Show when={view() === "export"}>1548              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1549                <ExportView1550                  onBack={() => {1551                    if (returnToPanic()) {1552                      setReturnToPanic(false);1553                      setView("panic");1554                    } else {1555                      handleBack();1556                    }1557                  }}1558                />1559              </Suspense>1560            </Show>1561            <Show when={view() === "panic"}>1562              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1563                <PanicView1564                  onCancel={() => setView("settings")}1565                  onOpenExport={() => {1566                    setReturnToPanic(true);1567                    setView("export");1568                  }}1569                  onDestroyed={async () => {1570                    clearCanarySuppressions();1571                    setEntries([]);1572                    setSelectedEntry(null);1573                    setEditEntry(undefined);1574                    setHasVault(false);1575                    setOnboarded(false);1576                    setProStatus(false);1577                    setPendingPasskey(null);1578                    setUpgradeHighlight(null);1579                    setSettingsInitialSection(null);1580                    setPendingProNotice(null);1581                    setPendingCelebration(false);1582                    setReturnToPanic(false);1583                    setContentPhase("idle");1584                    setView("lock");1585                  }}1586                />1587              </Suspense>1588            </Show>1589            <Show when={view() === "health"}>1590              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1591                <HealthView1592                  entries={entries()}1593                  isPro={proStatus()}1594                  onFixEntry={handleFixEntry}1595                  onBack={() => setView("settings")}1596                  onRefresh={loadEntries}1597                />1598              </Suspense>1599            </Show>1600            <Show when={view() === "trash"}>1601              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1602                <TrashView1603                  onBack={() => setView("list")}1604                  onRestored={() => void loadEntries()}1605                />1606              </Suspense>1607            </Show>1608            <Show when={showNotes()}>1609              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1610                <NotesMode1611                  notes={entries().filter((e) => e.type === "note")}1612                  initialNoteId={openNoteId()}1613                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1614                  onNoteListChanged={() => void loadEntries()}1615                />1616              </div>1617            </Show>1618            <Show when={restoreView() === "file"}>1619              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1620                <ImportView1621                  mode="onboarding"1622                  replacesExistingVault={true}1623                  onBack={() => setRestoreView(null)}1624                  onImport={async () => {1625                    setRestoreView(null);1626                    await handleUnlock();1627                  }}1628                />1629              </Suspense>1630            </Show>1631            </section>1632            </Show>1633          </Show>1634        </Show>1635      </Show>1636      <Show when={showShortcutsHelp()}>1637        <ShortcutsHelpOverlay1638          bindings={shortcutBindings()}1639          onClose={() => setShowShortcutsHelp(false)}1640        />1641      </Show>1642    </div>1643  );1644}16451646function ShortcutsHelpOverlay(props: {1647  bindings: Record<ShortcutAction, Keybinding>;1648  onClose: () => void;1649}) {1650  return (1651    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1652      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1653        <div class="peach-shortcuts-help-head">1654          <h3>Keyboard shortcuts</h3>1655          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1656        </div>1657        <div class="peach-shortcuts-help-body">1658          <p class="peach-settings-sub-label">ENTRY VIEW</p>1659          <ul>1660            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1661              <li>1662                <span>{d.label}</span>1663                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1664              </li>1665            ))}1666          </ul>1667          <p class="peach-settings-sub-label">ANYWHERE</p>1668          <ul>1669            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1670              <li>1671                <span>{d.label}</span>1672                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1673              </li>1674            ))}1675          </ul>1676        </div>1677      </div>1678    </div>1679  );1680}