App.tsx

67.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 { isPasskeyOnly } from "../shared/types";8import { LockView } from "./views/Lock";9import { Onboarding } from "./views/Onboarding";10import { NotesMode } from "./views/NotesMode";11import { ProCelebration } from "./views/ProCelebration";12import { VaultView, type SortOrder } from "./views/Vault";13import { EntryView } from "./views/Entry";14import { AddView } from "./views/Add";15import { PeachWordmark } from "./components/PeachMark";16import { PasskeyApprovalView } from "./views/PasskeyApproval";17import { extractDomain } from "../shared/domain";18import { popupCopy } from "./copy";19import {20  DEFAULT_BINDINGS,21  formatKeybinding,22  getActiveBindings,23  matchKeybinding,24  SHORTCUT_DESCRIPTORS,25  type Keybinding,26  type ShortcutAction,27} from "../shared/shortcuts";28import { generateTOTP } from "../crypto/totp";29import { isNativePlatform, nativePlugin } from "../shared/native";3031export { sendMessage } from "../shared/bridge";3233const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));34const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));35const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));36const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));37const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));38const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));39const ChirpSyncView   = lazy(() => import("./views/ChirpSync").then(m => ({ default: m.ChirpSyncView })));40const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));41const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));4243type View =44  | "lock"45  | "pro-celebration"46  | "entry"47  | "list"48  | "add"49  | "settings"50  | "chirp-sync"51  | "import"52  | "export"53  | "health"54  | "trash"55  | "panic"56  | "codex-generate"57  | "codex-restore";58type BootState = "loading" | "ready";5960const canarySuppressMap = new Map<string, boolean>();61let shellRingAnimation: Animation | null = null;6263export function isCanarySuppressed(entryId: string): boolean {64  return canarySuppressMap.get(entryId) ?? false;65}6667export function setCanarySuppressed(entryId: string, suppressed: boolean): void {68  canarySuppressMap.set(entryId, suppressed);69}7071export function clearCanarySuppressions(): void {72  canarySuppressMap.clear();73}7475export function triggerRing() {76  const shell = document.getElementById("hd-shell");77  if (!shell) return;7879  shellRingAnimation?.cancel();80  shell.dataset.glowing = "true";81  const animation = shell.animate(82    [83      { offset: 0, boxShadow: "var(--copy-shadow)" },84      {85        offset: 0.3,86        boxShadow:87          "0 2px 8px rgba(0,0,0,0.5), 0 14px 48px rgba(0,0,0,0.6), 0 0 0 1.5px color-mix(in srgb, var(--peach-accent) 58%, transparent), 0 0 22px color-mix(in srgb, var(--peach-accent) 18%, transparent)",88      },89      { offset: 1, boxShadow: "var(--copy-shadow)" },90    ],91    {92      duration: 720,93      easing: "cubic-bezier(0.4, 0, 0.2, 1)",94      fill: "none",95    }96  );97  shellRingAnimation = animation;98  const clearGlow = () => {99    if (shellRingAnimation !== animation) return;100    shellRingAnimation = null;101    delete shell.dataset.glowing;102  };103  animation.onfinish = clearGlow;104  animation.oncancel = clearGlow;105}106107108export function triggerPipPulse() {109  const pip = document.querySelector(".peach-status-pip, .pip");110  if (pip) {111    pip.classList.remove("pulse");112    void (pip as HTMLElement).offsetWidth;113    pip.classList.add("pulse");114  }115}116117const ENTRY_TRANSITION_SETTLE_MS = 135;118119export default function App() {120  const [bootState, setBootState] = createSignal<BootState>("loading");121  const [view, setView] = createSignal<View>("lock");122  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,123  // CSS transition takes over for snap animation).124  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);125  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(126    "enter"127  );128  const [contentTransitioning, setContentTransitioning] = createSignal(false);129  const [hasVault, setHasVault] = createSignal(false);130  const [onboarded, setOnboarded] = createSignal(true);131  const [entries, setEntries] = createSignal<VaultEntry[]>([]);132  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);133  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);134  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");135  const [theme, setTheme] = createSignal<"dark" | "light">("dark");136  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");137  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);138  const [lockOnClose, setLockOnClose] = createSignal(true);139  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);140  const [breachMonitoring, setBreachMonitoring] = createSignal(true);141  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);142  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);143  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);144  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);145  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);146  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");147  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");148  // Cached Pro status — synchronous for render paths. Background's149  // GET_LICENSE is async, but render-time reads of isPro() must not block.150  // Refreshed at boot, after activate/deactivate, and whenever the popup151  // re-opens onto a stored license that has changed via another window.152  const [proStatus, setProStatus] = createSignal(false);153  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);154  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");155  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);156  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");157  const [listSearchSeed, setListSearchSeed] = createSignal("");158  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);159  const [pendingCelebration, setPendingCelebration] = createSignal(false);160  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);161  // True while Panic Step 1 has bounced the user out to Export. When Export's162  // onBack fires we return to Panic instead of Settings so the user keeps the163  // destruction context they came from.164  const [returnToPanic, setReturnToPanic] = createSignal(false);165  // The view to return to when the add/edit view is dismissed. Normally "entry"166  // but "health" when the user arrives via the fix-entry path from Vault Health.167  const [editBackView, setEditBackView] = createSignal<View>("entry");168  const [settingsExiting, setSettingsExiting] = createSignal(false);169  const [showNotes, setShowNotes] = createSignal(false);170  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);171  // Set on popup boot when peach_recovery_pending flag is found in session172  // storage — instructs LockView to skip the unlock UI and open the recovery173  // words confirmation surface instead. Cleared via handleUnlock once the174  // user has typed the 3 confirmation words.175  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);176177  let contentPhaseTimer: number | undefined;178  // Set when the popup was opened from the inline "Open Peach to unlock" button.179  // handleUnlock() closes the popup after unlock so the user returns to the page.180  let openedForInlineUnlock = false;181182  function applyAccent(name: AccentColorName) {183    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;184    const hex = color.hex;185    document.documentElement.style.setProperty("--peach-accent", hex);186    // Ambient surface variables — derived from the accent so surfaces shift187    // subtly toward the accent hue rather than staying fixed warm-brown.188    document.documentElement.style.setProperty("--peach-glow", hex + "2A");189    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");190    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");191  }192193  createEffect(() => {194    applyAccent(accentColor());195  });196197  createEffect(() => {198    document.documentElement.classList.toggle("light", theme() === "light");199    document.body.classList.toggle("light", theme() === "light");200  });201202  createEffect(() => {203    document.documentElement.setAttribute("data-text-size", textSize());204  });205206  createEffect(() => {207    if (reduceMotion()) {208      document.documentElement.setAttribute("data-motion", "reduce");209    } else {210      document.documentElement.removeAttribute("data-motion");211    }212  });213214  const selectedIndex = createMemo(() => {215    const currentId = selectedEntry()?.id;216    if (!currentId) return entries().length > 0 ? 0 : -1;217    return entries().findIndex((entry) => entry.id === currentId);218  });219220  async function applyAccentColor(name: AccentColorName) {221    applyAccent(name);222    setAccentColor(name);223    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });224  }225226  async function applyTheme(t: "dark" | "light") {227    setTheme(t);228    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });229  }230231  async function applyTextSize(size: "small" | "medium" | "large") {232    setTextSize(size);233    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });234  }235236  async function applyReduceMotion(enabled: boolean) {237    setReduceMotion(enabled);238    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });239  }240241  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload242  // small and lets future default updates land for actions the user hasn't243  // touched. Settings sends us the full active map; we filter and store.244  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {245    setShortcutBindings(active);246    const overrides: Record<string, Keybinding> = {};247    for (const action of Object.keys(active) as ShortcutAction[]) {248      const a = active[action];249      const d = DEFAULT_BINDINGS[action];250      const same = a.key === d.key251        && Boolean(a.ctrl)  === Boolean(d.ctrl)252        && Boolean(a.meta)  === Boolean(d.meta)253        && Boolean(a.shift) === Boolean(d.shift)254        && Boolean(a.alt)   === Boolean(d.alt);255      if (!same) overrides[action] = a;256    }257    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });258  }259260  async function applyLockOnClose(enabled: boolean) {261    setLockOnClose(enabled);262    await sendMessage({263      type: "UPDATE_SETTINGS",264      payload: { lockOnClose: enabled },265    });266  }267268  async function applyAutoLockMinutes(minutes: number) {269    setAutoLockMinutes(minutes);270    await sendMessage({271      type: "UPDATE_SETTINGS",272      payload: { autoLockMinutes: minutes },273    });274  }275276  async function applyBreachMonitoring(enabled: boolean) {277    setBreachMonitoring(enabled);278    await sendMessage({279      type: "UPDATE_SETTINGS",280      payload: { breachMonitoring: enabled },281    });282  }283284  onMount(async () => {285    // Resolve the active tab in parallel with the unlock/has-vault queries —286    // openVault()'s smart selection picks the entry matching currentTabDomain,287    // so it must be populated before openVault runs. Previously refreshCurrentTab288    // ran after openVault, leaving popups that booted already-unlocked falling289    // back to loadedEntries[0] instead of the domain match.290    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([291      sendMessage({ type: "IS_UNLOCKED" }),292      sendMessage({ type: "HAS_VAULT" }),293      refreshCurrentTab(),294      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),295    ]);296    const unlocked = Boolean(297      (unlockResponse as { ok: boolean; data?: boolean }).data298    );299    const vaultExists = Boolean(300      (vaultResponse as { ok: boolean; data?: boolean }).data301    );302    const shouldCelebrate = Boolean(303      (celebrationResponse as { ok: boolean; data?: boolean }).data304    );305    setHasVault(vaultExists);306    // Onboarding gate — show once on first install, never again. Existing307    // users (vaultExists) are auto-marked onboarded so they skip the flow308    // even on the very first popup open after this feature ships.309    try {310      const onboarded = await storageGet("peach_onboarded");311      const seen = onboarded === "true";312      if (vaultExists && !seen) {313        await storageSet("peach_onboarded", "true");314        setOnboarded(true);315      } else {316        setOnboarded(seen);317      }318    } catch {319      // storage unavailable — default to onboarded so we never block boot320      setOnboarded(true);321    }322    await Promise.all([restoreSettings(), refreshProStatus()]);323324    // Mark played before any animation so a crash mid-sequence never replays it325    if (shouldCelebrate) {326      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });327    }328329    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget; the330    // background ignores it when no mobile hosts are paired or while331    // another sync is already in flight.332    if (unlocked && vaultExists) {333      void sendMessage({334        type: "TRIGGER_SYNC",335        payload: { reason: "foreground" },336      });337    }338339    // If the user created a vault but hasn't yet confirmed their recovery340    // words, route back to the recovery-words screen instead of opening the341    // entries view. The flag lives in chrome.storage.local so it survives342    // both popup close (SW suppresses lock-on-close) and full browser343    // restart (handleUnlock checks the same flag after a fresh password344    // unlock). Cleared when confirmation succeeds.345    let recoveryPending = false;346    try {347      const out = await chrome.storage.local?.get("peach_recovery_pending");348      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";349    } catch { /* best-effort */ }350351    // If this popup was opened from the inline "Open Peach to unlock" button,352    // the background set a session flag. Read and clear it so handleUnlock()353    // can close the popup after unlock and return the user to the page.354    if (chrome.storage.session) {355      try {356        const s = await chrome.storage.session.get("peach_inline_unlock");357        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {358          openedForInlineUnlock = true;359          await chrome.storage.session.remove("peach_inline_unlock");360        }361      } catch { /* best-effort */ }362    }363364    // Native: closing the app before recovery-words confirmation means the365    // user didn't finish vault creation. Throw the partial vault away and366    // restart onboarding rather than asking them to unlock a vault they367    // never finished creating. Desktop keeps the existing "unlock to368    // resume" flow because closing the popup there is much more casual.369    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {370      try {371        await chrome.storage.local?.remove([372          "peach_vault_a",373          "peach_vault_b",374          "peach_recovery_pending",375          "peach_onboarded",376          "peach_vault_history",377        ]);378      } catch { /* best-effort */ }379      setHasVault(false);380      setOnboarded(false);381      setView("lock");382      setBootState("ready");383      document.getElementById("pre-lock")?.setAttribute("hidden", "true");384      return;385    }386387    if (recoveryPending && unlocked) {388      // forceRecoveryWords overrides LockView's hasVault gate so the389      // recovery surface renders even though the vault now exists.390      setForceRecoveryWords(true);391      setView("lock");392    } else if (unlocked && vaultExists) {393      await openVault(undefined, shouldCelebrate);394      if (shouldCelebrate) {395        setView("pro-celebration");396        window.setTimeout(() => setView("entry"), 2500);397      }398    } else if (shouldCelebrate) {399      setPendingCelebration(true);400    }401402    await refreshPendingPasskey();403404    // Track tab changes so smart sort stays current405    const handleTabActivated = () => { void refreshCurrentTab(); };406    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {407      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();408    };409    try {410      chrome.tabs.onActivated.addListener(handleTabActivated);411      chrome.tabs.onUpdated.addListener(handleTabUpdated);412      onCleanup(() => {413        chrome.tabs.onActivated.removeListener(handleTabActivated);414        chrome.tabs.onUpdated.removeListener(handleTabUpdated);415      });416    } catch {417      // tabs permission may not be available in all contexts418    }419420    setBootState("ready");421    document.getElementById("pre-lock")?.setAttribute("hidden", "true");422423    // Deep-link: ?codex=pdf opens a detached window straight into the424    // Codex restore flow with auto-picked PDF. The action popup can't host425    // a file dialog without dismissing itself, so this is the only way the426    // PDF import path survives. See CodexRestoreView.openPdfPicker().427    try {428      const route = new URLSearchParams(window.location.search).get("codex");429      if (route === "pdf" || route === "restore") {430        setView("codex-restore");431      }432    } catch {433      // location.search unavailable — ignore.434    }435436    // Check for pending session-storage notices from the background.437    if (chrome.storage.session) {438      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as439        Record<string, { feature?: string } | undefined>;440      if (session.pendingProGate?.feature) {441        await chrome.storage.session.remove("pendingProGate");442        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);443        setSettingsInitialSection("license");444        setView("settings");445      } else if (session.pendingProNotice?.feature) {446        await chrome.storage.session.remove("pendingProNotice");447        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });448      }449    }450451    // Warm the lazy-module cache so the Suspense fallback never shows for452    // locally-bundled extension views. Without this, the first navigation to453    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which454    // covers the shell and absorbs clicks on the header.455    void Promise.all([456      import("./views/Settings").catch(() => {}),457      import("./views/Import").catch(() => {}),458      import("./views/Export").catch(() => {}),459      import("./views/Health").catch(() => {}),460      import("./views/TrashView").catch(() => {}),461    ]);462463    // Lock-on-close via a persistent port. sendMessage in pagehide is464    // unreliable — the popup context tears down before the message lands.465    // The SW's onConnect listener locks when this port disconnects.466    let popupPort: chrome.runtime.Port | null = null;467    try {468      popupPort = chrome.runtime.connect({ name: "popup" });469    } catch { /* extension context invalidated — ignore */ }470    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });471472    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only473    // reliable signal is appStateChange — setTimeout is killed when the OS474    // backgrounds the app. We measure elapsed background time on resume.475    if (isNativePlatform()) {476      let backgroundedAt: number | null = null;477478      const CapApp = nativePlugin<{479        addListener: (480          ev: string,481          cb: (s: { isActive: boolean }) => void,482        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };483      }>("App");484      if (CapApp?.addListener) {485        const sub = CapApp.addListener(486          "appStateChange",487          ({ isActive }: { isActive: boolean }) => {488            if (!isActive) {489              backgroundedAt = Date.now();490              return;491            }492            if (backgroundedAt !== null && autoLockMinutes() > 0) {493              const elapsed = Date.now() - backgroundedAt;494              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();495            }496            backgroundedAt = null;497          }498        );499        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.500        onCleanup(() => {501          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});502        });503      }504505      // L12/COR-011: foreground idle autolock. appStateChange only fires when506      // the OS backgrounds the app — if the user idles with the screen on,507      // chrome.alarms is no-op'd in Capacitor so the vault would stay open508      // indefinitely. Poll every 30s and lock if elapsed since last user509      // interaction exceeds autoLockMinutes.510      let lastUserActivityAt = Date.now();511      const bumpActivity = () => { lastUserActivityAt = Date.now(); };512      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;513      for (const ev of ACTIVITY_EVENTS) {514        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });515      }516      const idleLockInterval = setInterval(() => {517        const minutes = autoLockMinutes();518        if (!minutes || minutes <= 0) return;519        const elapsed = Date.now() - lastUserActivityAt;520        if (elapsed >= minutes * 60_000) {521          lastUserActivityAt = Date.now();522          handleHeaderLock();523        }524      }, 30_000);525      onCleanup(() => {526        clearInterval(idleLockInterval);527        for (const ev of ACTIVITY_EVENTS) {528          document.removeEventListener(ev, bumpActivity, { capture: true });529        }530      });531532      // mDNS peer-discovery trigger. Register onCleanup synchronously so533      // SolidJS captures it within the reactive owner — onCleanup inside a534      // .then() callback may miss the capture window and leak the listener.535      let stopMDNS: () => void = () => undefined;536      onCleanup(() => stopMDNS());537      if (isNativePlatform()) {538        // Android runs the background/sync dispatcher in-process with the539        // popup, so the production runner has to be registered from the540        // UI bootstrap path instead of the MV3 service-worker entry.541        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>542          import("../background/chirp-sync-runner").then(({ productionSyncRunner }) => {543            setSyncRunner(productionSyncRunner);544            void hydratePersistedSyncState();545          })546        );547      }548      void import("./chirp-pair-capacitor").then(({ startMDNSListener }) => {549        stopMDNS = startMDNSListener();550      });551    }552553    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale554    // entries instead of waiting for the next GET_ENTRIES round-trip.555    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {556      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();557      if (msg?.type === "PRO_GATE_TRIGGERED") {558        setUpgradeHighlight(msg.payload?.feature ?? null);559        setSettingsInitialSection("license");560        setView("settings");561      }562    };563    chrome.runtime.onMessage.addListener(handleRuntimeMessage);564    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));565566    // Android hardware/gesture back. MainActivity fires peach:back; the popup567    // decides what "back" means per surface. Lock+no-vault is the common case568    // — return to onboarding rather than letting the OS dismiss the activity.569    const handlePeachBack = () => {570      // Notes mode captures back first571      if (showNotes()) {572        setShowNotes(false);573        setOpenNoteId(undefined);574        return;575      }576      const v = view();577      if (v === "lock" && !hasVault() && onboarded()) {578        setOnboarded(false);579        return;580      }581      if (v === "list") { setView("entry"); return; }582      if (v === "settings") {583        window.dispatchEvent(new Event("peach:settings-back"));584        return;585      }586      if (v === "import" || v === "health") { setView("settings"); return; }587      if (v === "export") { handleExportBack(); return; }588      if (v === "add") { handleBack(); return; }589      if (v === "chirp-sync") { setView("settings"); return; }590    };591    window.addEventListener("peach:back", handlePeachBack);592    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));593594    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that595    // peeks from the bottom (search bar handle visible) and drags up to fill596    // the screen. dragOffset is the LIVE finger offset during a drag, in px,597    // 0 when no drag in progress. The wrapper element computes transform =598    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.599    if (isNativePlatform()) {600      let touchStartY = 0;601      let touchStartX = 0;602      let lastY = 0;603      let lastT = 0;604      let dragging = false;605      let captured = false;606      const HORIZONTAL_TOLERANCE = 16;607      const ACTIVATION_DY = 8;608      const PEEK_PX = 60;609610      const onTouchStart = (e: TouchEvent) => {611        const t = e.touches[0];612        if (!t) return;613        const v = view();614        if (v !== "entry" && v !== "list") return;615        // Entry view: only intercept drags starting in the bottom 40%.616        // List view: intercept drags starting in the top 35% (the search/handle row).617        const inBand = v === "entry"618          ? t.clientY > window.innerHeight * 0.6619          : t.clientY < window.innerHeight * 0.35;620        if (!inBand) return;621        touchStartY = lastY = t.clientY;622        touchStartX = t.clientX;623        lastT = e.timeStamp;624        dragging = true;625        captured = false;626      };627628      const onTouchMove = (e: TouchEvent) => {629        if (!dragging) return;630        const t = e.touches[0];631        if (!t) return;632        const dy = t.clientY - touchStartY;633        const dx = Math.abs(t.clientX - touchStartX);634635        if (!captured) {636          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {637            // Looks like a horizontal swipe — release.638            dragging = false;639            return;640          }641          if (Math.abs(dy) < ACTIVATION_DY) return;642          captured = true;643        }644645        // Translate the sheet by dy from its rest (peek) position. Peek is646        // (viewport height - PEEK_PX). Open is 0.647        const v = view();648        const restClosed = window.innerHeight - PEEK_PX;649        const baseTranslate = v === "list" ? 0 : restClosed;650        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));651        setSheetTranslate(next);652        lastY = t.clientY;653        lastT = e.timeStamp;654      };655656      const onTouchEnd = (e: TouchEvent) => {657        if (!dragging) { return; }658        const t = e.changedTouches[0];659        const elapsed = Math.max(1, e.timeStamp - lastT);660        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms661        const wasCaptured = captured;662        dragging = false;663        captured = false;664        const v = view();665666        if (!wasCaptured) {667          // Tap in the peek strip while in entry view → open the vault list.668          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");669          setSheetTranslate(null);670          return;671        }672673        const restClosed = window.innerHeight - PEEK_PX;674        const current = sheetTranslate() ?? restClosed;675676        // Snap rules:677        //   - Strong upward velocity → open678        //   - Strong downward velocity → close679        //   - Otherwise snap to whichever rest is closer680        let nextOpen: boolean;681        if (velocity < -0.05) nextOpen = true;682        else if (velocity > 0.05) nextOpen = false;683        else nextOpen = current < restClosed * 0.5;684685        if (nextOpen && v !== "list") setView("list");686        if (!nextOpen && v !== "entry") setView("entry");687        // Release the live offset so CSS transition handles the snap.688        setSheetTranslate(null);689      };690691      document.addEventListener("touchstart", onTouchStart, { passive: true });692      document.addEventListener("touchmove",  onTouchMove,  { passive: true });693      document.addEventListener("touchend",   onTouchEnd,   { passive: true });694      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });695      onCleanup(() => {696        document.removeEventListener("touchstart", onTouchStart);697        document.removeEventListener("touchmove",  onTouchMove);698        document.removeEventListener("touchend",   onTouchEnd);699      });700    }701702    // Action handlers — keyed by ShortcutAction. The dispatcher below tests703    // each binding against the event and runs the matching handler. New704    // shortcuts only need an entry here; the binding is data, not code.705    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {706      copy_password: () => {707        const entry = selectedEntry();708        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });709      },710      copy_username: () => {711        const entry = selectedEntry();712        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });713      },714      copy_totp: () => {715        const entry = selectedEntry();716        if (!entry?.totp) return;717        try {718          const { code } = generateTOTP(entry.totp);719          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });720        } catch { /* invalid TOTP secret — silent */ }721      },722      new_entry: () => handleAdd(),723      edit_entry: () => {724        const entry = selectedEntry();725        // Passkey-only entries have nothing user-editable in the Add view; the726        // passkey credential itself is opaque. Skip the edit action for them.727        if (!entry || isPasskeyOnly(entry)) return;728        setEditEntry(entry);729        setView("add");730      },731      delete_entry: () => {732        if (selectedEntry()) void handleDelete();733      },734      lock_vault: () => { void handleHeaderLock(); },735      search: () => openList(),736      nav_prev: () => navigate(-1),737      nav_next: () => navigate(1),738      jump_vault: () => setView("entry"),739      jump_settings: () => setView("settings"),740      show_help: () => setShowShortcutsHelp(true),741    };742743    // Actions that are MEANINGFUL only on the entry-detail view. Outside744    // that scope the binding is dormant — pressing C while on Settings745    // does nothing rather than awkwardly copying from a now-stale entry.746    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([747      "copy_password", "copy_username", "copy_totp",748      "edit_entry", "delete_entry", "nav_prev", "nav_next",749    ]);750751    const handleGlobalKeydown = (e: KeyboardEvent) => {752      const v = view();753      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"754        || (e.target as HTMLElement)?.tagName === "TEXTAREA"755        || (e.target as HTMLElement)?.isContentEditable;756      const isPrintableSearchKey =757        e.key.length === 1 &&758        !e.ctrlKey &&759        !e.metaKey &&760        !e.altKey;761762      // No input during the pro celebration sequence763      if (v === "pro-celebration") return;764765      // Help dialog: Escape closes it; eat the keypress so it doesn't766      // also navigate away from the underlying view.767      if (showShortcutsHelp()) {768        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }769        return;770      }771772      // ── Escape — fixed binding (not user-customizable) ───────773      if (e.key === "Escape") {774        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }775        if (v === "list") { setView("entry"); return; }776        if (v === "settings" || v === "add") { handleBack(); return; }777        if (v === "import" || v === "health") { setView("settings"); return; }778        if (v === "export") { handleExportBack(); return; }779        if (v === "chirp-sync") { setView("settings"); return; }780      }781782      // Bindings-driven dispatch. Single-key letter bindings without783      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is784      // inside an input, so users can type into search/forms normally.785      const bindings = shortcutBindings();786      for (const action of Object.keys(bindings) as ShortcutAction[]) {787        const binding = bindings[action];788        if (!matchKeybinding(e, binding)) continue;789        // Single-key letter bindings need the input-focus guard. Bindings790        // with any modifier are safe — Ctrl+L doesn't conflict with typing.791        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;792        if (!hasMod && binding.key.length === 1 && inInput) return;793        if (ENTRY_SCOPED.has(action) && v !== "entry") return;794        e.preventDefault();795        SHORTCUT_HANDLERS[action]?.();796        return;797      }798799      // Type-to-search: in entry view, any printable key not consumed by a800      // shortcut above primes the list search seed and opens the list.801      // Kept outside the bindings table because it's a behavior, not a802      // discrete action — every printable character can trigger it.803      if (v === "entry" && !inInput && isPrintableSearchKey) {804        e.preventDefault();805        primeListSearch(e.key);806        return;807      }808    };809    window.addEventListener("keydown", handleGlobalKeydown);810    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));811812    const handleStorageChanged = (813      changes: Record<string, chrome.storage.StorageChange>,814      areaName: string815    ) => {816      if (areaName !== "session") return;817      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {818        return;819      }820      void refreshPendingPasskey();821    };822    chrome.storage.onChanged.addListener(handleStorageChanged);823    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));824  });825826  async function refreshCurrentTab() {827    try {828      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });829      const url = tab?.url ?? tab?.pendingUrl ?? "";830      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");831      // Skip extension/internal URLs — adding chrome://, about:, or832      // chrome-extension:// to a vault entry is never what the user wants.833      const isWebUrl = /^https?:\/\//i.test(url);834      setCurrentTabUrl(isWebUrl ? url : "");835    } catch {836      setCurrentTabDomain("");837      setCurrentTabUrl("");838    }839  }840841  async function refreshPendingPasskey() {842    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });843    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);844  }845846  async function refreshProStatus() {847    const res = await sendMessage({ type: "GET_LICENSE" });848    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;849    setProStatus(Boolean(data?.valid && data?.plan === "pro"));850  }851852  async function restoreSettings() {853    const res = await sendMessage({ type: "GET_SETTINGS" });854    const s = (res as { ok: boolean; data?: any }).data ?? {};855    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {856      setAccentColor(s.accentColor as AccentColorName);857    }858    setTheme(s.theme === "light" ? "light" : "dark");859    if (s.textSize === "small" || s.textSize === "large") {860      setTextSize(s.textSize);861    } else {862      setTextSize("medium");863    }864    setReduceMotion(s.reduceMotion === true);865    setLockOnClose(s.lockOnClose !== false);866    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);867    setBreachMonitoring(s.breachMonitoring !== false);868    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);869    setShortcutBindings(getActiveBindings(s.shortcuts));870  }871872  async function applyTrashRetention(days: number) {873    setTrashRetentionDays(days);874    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });875  }876877  function primeListSearch(seed: string) {878    setListSearchSeed(seed);879    setListSearchSeedNonce((value) => value + 1);880    openList();881  }882883  // Returns null when it detected a dead service worker and triggered handleLock().884  // Callers that need to abort (e.g. openVault) check for null rather than relying885  // on view() state, which may already be "lock" during normal startup flows.886  async function loadEntries(): Promise<VaultEntry[] | null> {887    const response = await sendMessage({ type: "GET_ENTRIES" });888    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };889890    // If the service worker was killed and restarted (MV3 workers sleep), the891    // vault will be locked again — or the worker may not respond at all.892    // In either case, send the user to the lock screen rather than silently893    // showing an empty vault (which looks like data loss).894    if (!res.ok) {895      if (896        res.error === "vault_locked" ||897        res.error === "SERVICE_WORKER_UNAVAILABLE" ||898        (typeof res.error === "string" && res.error.includes("locked"))899      ) {900        handleLock();901        return null; // signal emergency lock to callers902      }903      return [];904    }905906    const loadedEntries = res.data ?? [];907    setEntries(loadedEntries);908909    const currentId = selectedEntry()?.id;910    if (currentId) {911      setSelectedEntry(912        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null913      );914    }915916    return loadedEntries;917  }918919  async function openVault(preferredEntryId?: string, skipViewSet = false) {920    // Purge expired trash entries on each vault open921    const retDays = trashRetentionDays();922    if (retDays > 0) {923      void sendMessage({924        type: "PURGE_EXPIRED_TRASH",925        payload: { retentionMs: retDays * 86_400_000 },926      });927    }928929    const loadedEntries = await loadEntries();930931    // null means loadEntries() triggered an emergency lock (service worker died).932    // Don't override it by setting view back to "entry" with an empty vault.933    if (loadedEntries === null) return;934935    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry936    let nextSelectedEntry: VaultEntry | null = null;937    if (preferredEntryId) {938      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;939    }940    if (!nextSelectedEntry) {941      const tabDomain = currentTabDomain();942      if (tabDomain) {943        nextSelectedEntry = loadedEntries.find((e) => {944          if (e.type === "login") {945            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;946            for (const extra of e.additionalUrls ?? []) {947              if ((extractDomain(extra) ?? "") === tabDomain) return true;948            }949            return false;950          }951          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;952          return false;953        }) ?? null;954      }955    }956    nextSelectedEntry ??= loadedEntries[0] ?? null;957958    setSelectedEntry(nextSelectedEntry);959    setEditEntry(undefined);960    setContentTransitioning(false);961    setContentPhase("enter");962    queueContentIdle();963    if (!skipViewSet) setView("entry");964  }965966  async function handleUnlock() {967    // If the user previously created a vault but hadn't yet confirmed their968    // recovery words (and the browser was closed before they could), the969    // peach_recovery_pending flag is still set in storage.local. Re-route970    // back to the recovery surface so they finish the confirmation step971    // before reaching the entries view — the words can be re-derived now972    // that the vault is unlocked again.973    let recoveryPending = false;974    try {975      const out = await chrome.storage.local?.get("peach_recovery_pending");976      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";977    } catch { /* best-effort */ }978    if (recoveryPending) {979      setForceRecoveryWords(true);980      setView("lock");981      triggerPipPulse();982      await restoreSettings();983      return;984    }985    setHasVault(true);986    triggerPipPulse();987    await restoreSettings();988    const celebrating = pendingCelebration();989    if (celebrating) {990      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });991      setPendingCelebration(false);992    }993    await openVault(undefined, celebrating);994    if (celebrating) {995      setView("pro-celebration");996      window.setTimeout(() => setView("entry"), 2500);997    }998    // Popup was opened from the inline "Open Peach to unlock" button — close it999    // now so the user lands back on the page with the autofill selector ready.1000    if (openedForInlineUnlock) {1001      openedForInlineUnlock = false;1002      window.close();1003    }1004  }10051006  function handleSelectEntry(entry: VaultEntry) {1007    if (entry.type === "note") {1008      setOpenNoteId(entry.id);1009      setShowNotes(true);1010      return;1011    }1012    setSelectedEntry(entry);1013    setContentTransitioning(false);1014    setContentPhase("enter");1015    queueContentIdle();1016    setView("entry");1017  }10181019  function handleAdd() {1020    setEditEntry(undefined);1021    setView("add");1022  }10231024  async function handleDelete() {1025    const entry = selectedEntry();1026    if (!entry) return;1027    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1028    const loadedEntries = await loadEntries() ?? [];1029    setSelectedEntry(loadedEntries[0] ?? null);1030    setView("entry");1031  }10321033  async function handleDeleteMany(ids: string[]) {1034    for (const id of ids) {1035      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1036    }1037    const loadedEntries = await loadEntries() ?? [];1038    // If the currently selected entry was among the deleted, move to first1039    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1040    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);1041  }10421043  async function handleSave(savedEntry?: VaultEntry) {1044    await openVault(savedEntry?.id);1045  }10461047  function handleBack() {1048    const dest = editBackView();1049    setEditBackView("entry");1050    setEditEntry(undefined);1051    setView(dest);1052  }10531054  function handleExportBack() {1055    if (returnToPanic()) {1056      setReturnToPanic(false);1057      setView("panic");1058      return;1059    }1060    setView("settings");1061  }10621063  function handleLock() {1064    clearCanarySuppressions();1065    setEntries([]);1066    setSelectedEntry(null);1067    setEditEntry(undefined);1068    setContentPhase("idle");1069    setView("lock");1070  }10711072  function handleHeaderLock() {1073    // Lock the UI immediately — do not wait for the service worker. If the SW1074    // is dead or slow, the 5s sendMessage timeout would create a dead-click1075    // window. The SW will lock on its next wake regardless.1076    handleLock();1077    void sendMessage({ type: "LOCK" });1078  }10791080  function navigate(dir: number) {1081    const allEntries = entries();1082    if (allEntries.length === 0) return;1083    const currentIndex = selectedIndex();1084    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1085    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;1086    setSelectedEntry(allEntries[nextIndex]);1087    setContentPhase("enter");1088    queueContentIdle();1089  }10901091  function openList() {1092    setView("list");1093  }10941095  function openHealth() {1096    setEditEntry(undefined);1097    setView("health");1098  }10991100  function handleOpenFileImport() {1101    setRestoreView("file");1102  }11031104  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;11051106  function handleFixEntry(entry: VaultEntry) {1107    setSelectedEntry(entry);1108    // Passkey-only entries have no editable surface — drop into view mode1109    // instead of opening the Add editor.1110    if (isPasskeyOnly(entry)) {1111      setView("entry");1112      return;1113    }1114    setEditBackView(view()); // preserve caller view so back returns here1115    setEditEntry(entry);1116    setView("add");1117  }11181119  const isLockedView = () => view() === "lock";11201121  async function handleApprovePendingPasskey() {1122    const pending = pendingPasskey();1123    if (!pending) return;1124    if (pending.browser === "firefox" && pending.type === "create") {1125      // Firefox path: popup itself runs navigator.credentials.create. The1126      // background never approved/rejected anything — it just stashed1127      // intent. After the popup-driven flow resolves (success or cancel),1128      // clear the pending key so the popup doesn't re-show this on next open.1129      const { createFirefoxPasskey } = await import("./firefox-passkey");1130      const result = await createFirefoxPasskey(pending);1131      if (!result.ok) {1132        console.warn("Peach Firefox passkey create failed:", result.error);1133      }1134      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1135      setPendingPasskey(null);1136      void loadEntries();1137      window.close();1138      return;1139    }1140    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1141    window.close();1142  }11431144  async function handleDenyPendingPasskey() {1145    const pending = pendingPasskey();1146    if (!pending) return;1147    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1148    window.close();1149  }11501151  function queueContentIdle(after?: () => void) {1152    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1153    contentPhaseTimer = window.setTimeout(() => {1154      setContentPhase("idle");1155      after?.();1156    }, ENTRY_TRANSITION_SETTLE_MS);1157  }11581159  return (1160    <div class="popup-root peach-theme">1161      <Show when={bootState() === "ready"}>1162        <Show1163          when={!pendingPasskey()}1164          fallback={1165            <PasskeyApprovalView1166              type={pendingPasskey()!.type}1167              rpName={pendingPasskey()!.rpName}1168              rpId={pendingPasskey()!.rpId}1169              userName={pendingPasskey()!.userName}1170              userDisplayName={pendingPasskey()!.userDisplayName}1171              onApprove={handleApprovePendingPasskey}1172              onDeny={handleDenyPendingPasskey}1173            />1174          }1175        >1176          <Show1177            when={!isLockedView()}1178            fallback={1179              <Show1180                when={onboarded() || hasVault()}1181                fallback={1182                  <Onboarding1183                    onComplete={() => { setOnboarded(true); }}1184                  />1185                }1186              >1187                <LockView1188                  hasVault={hasVault()}1189                  ready={bootState() === "ready"}1190                  isPro={proStatus()}1191                  forceRecoveryWords={forceRecoveryWords()}1192                  onUnlock={() => {1193                    // RecoveryWordDisplay clears the storage flag before1194                    // calling onDone, so handleUnlock will see no pending1195                    // confirmation and proceed through the normal path.1196                    if (forceRecoveryWords()) setForceRecoveryWords(false);1197                    return handleUnlock();1198                  }}1199                  onBackToOnboarding={1200                    !hasVault()1201                      ? () => setOnboarded(false)1202                      : undefined1203                  }1204                  onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1205                />1206              </Show>1207            }1208          >1209            <Show1210              when={view() !== "pro-celebration"}1211              fallback={<ProCelebration />}1212            >1213            <section1214              id="hd-shell"1215              class="peach-shell peach-theme"1216              data-surface="extension"1217            >1218            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1219              <PeachWordmark unlocked />1220              <div class="peach-chrome-actions">1221                <button1222                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1223                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1224                  aria-label="Notes"1225                  title="Notes"1226                >1227                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1228                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1229                    <line x1="4" y1="5" x2="10" y2="5" />1230                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1231                    <line x1="4" y1="10" x2="7" y2="10" />1232                  </svg>1233                </button>1234                <button1235                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1236                  onClick={() => setView("settings")}1237                  aria-label="Settings"1238                >1239                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1240                    <path1241                      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"1242                      stroke="currentColor"1243                      stroke-width="0.9"1244                    />1245                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1246                  </svg>1247                </button>1248                <button1249                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1250                  onClick={handleAdd}1251                  aria-label="New entry"1252                >1253                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1254                    <path d="M5.5 1v9M1 5.5h9" />1255                  </svg>1256                </button>1257                <button1258                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1259                  onClick={() => void handleHeaderLock()}1260                  aria-label="Lock vault"1261                >1262                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1263                    <path1264                      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"1265                      stroke="currentColor"1266                      stroke-width="1"1267                      stroke-linecap="round"1268                    />1269                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1270                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1271                  </svg>1272                </button>1273              </div>1274            </header>12751276            <Show when={pendingProNotice() !== null}>1277              <div class="peach-pro-notice-banner">1278                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1279                <button1280                  class="peach-pro-notice-link"1281                  onClick={() => {1282                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1283                    setSettingsInitialSection("license");1284                    setView("settings");1285                    setPendingProNotice(null);1286                  }}1287                >1288                  Learn more →1289                </button>1290                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1291              </div>1292            </Show>12931294            <div class="peach-shell-body">1295              <div class="peach-shell-veil"></div>1296              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1297                <EntryView1298                  entry={selectedEntry()}1299                  currentTabUrl={currentTabUrl()}1300                  entries={entries()}1301                  isPro={proStatus()}1302                  onDelete={handleDelete}1303                  onFieldSaved={() => void loadEntries()}1304                  onEscape={() => { setView("list"); }}1305                  onProGate={(feature) => {1306                    setUpgradeHighlight(feature);1307                    setSettingsInitialSection("license");1308                    setView("settings");1309                  }}1310                />1311              </div>13121313              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "chirp-sync" }}>1314                <div class="peach-search-bar">1315                  <span class="peach-search-icon">1316                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1317                      <circle cx="5.5" cy="5.5" r="3.75" />1318                      <path d="M8.75 8.75L11.5 11.5" />1319                    </svg>1320                  </span>1321                  <input1322                    class="peach-search-input"1323                    placeholder="search vault..."1324                    autocomplete="off"1325                    aria-label="Search vault entries"1326                    onClick={openList}1327                    onFocus={openList}1328                    readOnly1329                  />1330                  <div class="peach-search-meta">1331                    <span class="peach-search-counter">1332                      {entries().length > 01333                        ? `${selectedIndex() + 1} / ${entries().length}`1334                        : "0 entries"}1335                    </span>1336                    <span class="peach-divider"></span>1337                    <button1338                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1339                      onClick={() => navigate(-1)}1340                      aria-label="Previous entry"1341                      disabled={entries().length === 0}1342                    >1343                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1344                        <path d="M5 1L1 5.5L5 10" />1345                      </svg>1346                    </button>1347                    <button1348                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1349                      onClick={() => navigate(1)}1350                      aria-label="Next entry"1351                      disabled={entries().length === 0}1352                    >1353                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1354                        <path d="M1 1L5 5.5L1 10" />1355                      </svg>1356                    </button>1357                  </div>1358                </div>1359              </section>1360            </div>13611362            {/* Desktop: shown on demand via Show. Native sheet is rendered1363                via Portal below at the document root so its position:fixed1364                isn't trapped by .peach-shell's transform-based animations. */}1365            <Show when={!isNativePlatform() && view() === "list"}>1366              <VaultView1367                entries={entries()}1368                selectedEntryId={selectedEntry()?.id}1369                currentTabDomain={currentTabDomain()}1370                sortOrder={sortOrder()}1371                searchSeed={listSearchSeed()}1372                searchSeedNonce={listSearchSeedNonce()}1373                onSelectEntry={handleSelectEntry}1374                onSortOrderChange={setSortOrder}1375                onAdd={handleAdd}1376                onClose={() => setView("entry")}1377                onOpenTrash={() => setView("trash")}1378                onDeleteMany={handleDeleteMany}1379              />1380            </Show>1381            <Show when={isNativePlatform() && hasVault()}>1382              <Portal>1383                <div1384                  class="peach-vault-sheet"1385                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1386                  style={(() => {1387                    const live = sheetTranslate();1388                    if (live === null) return undefined;1389                    return { transform: `translateY(${live}px)` };1390                  })()}1391                >1392                  <VaultView1393                    entries={entries()}1394                    selectedEntryId={selectedEntry()?.id}1395                    currentTabDomain={currentTabDomain()}1396                    sortOrder={sortOrder()}1397                    searchSeed={listSearchSeed()}1398                    searchSeedNonce={listSearchSeedNonce()}1399                    isNative={true}1400                    onSelectEntry={handleSelectEntry}1401                    onSortOrderChange={setSortOrder}1402                    onAdd={handleAdd}1403                    onClose={() => setView("entry")}1404                    onOpenTrash={() => setView("trash")}1405                    onDeleteMany={handleDeleteMany}1406                  />1407                </div>1408              </Portal>1409            </Show>1410            <Show when={view() === "settings" || settingsExiting()}>1411              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1412                <SettingsView1413                  entriesCount={entries().length}1414                  breachMonitoring={breachMonitoring()}1415                  lockOnClose={lockOnClose()}1416                  autoLockMinutes={autoLockMinutes()}1417                  trashRetentionDays={trashRetentionDays()}1418                  theme={theme()}1419                  accentColor={accentColor()}1420                  textSize={textSize()}1421                  reduceMotion={reduceMotion()}1422                  isPro={proStatus()}1423                  initialSection={settingsInitialSection()}1424                  upgradeHighlight={upgradeHighlight()}1425                  isExiting={settingsExiting()}1426                  onBreachMonitoringChange={applyBreachMonitoring}1427                  onLockOnCloseChange={applyLockOnClose}1428                  onAutoLockMinutesChange={applyAutoLockMinutes}1429                  onTrashRetentionChange={applyTrashRetention}1430                  onThemeChange={applyTheme}1431                  onAccentChange={applyAccentColor}1432                  onTextSizeChange={applyTextSize}1433                  onReduceMotionChange={applyReduceMotion}1434                  shortcuts={shortcutBindings()}1435                  onShortcutsChange={applyShortcuts}1436                  onLicenseChange={async () => {1437                    // After activation/deactivation: refresh Pro status,1438                    // re-load entries (defensive — signal state can drift if1439                    // the SW briefly restarts during the verify+save round-trip),1440                    // and replay the Pro celebration if this is the first time1441                    // a valid Pro license is seen on this device.1442                    await refreshProStatus();1443                    void loadEntries();1444                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1445                    if ((should as { ok: boolean; data?: boolean }).data === true) {1446                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1447                      setView("pro-celebration");1448                      window.setTimeout(() => setView("settings"), 2500);1449                    }1450                  }}1451                  onBack={() => {1452                    setSettingsExiting(true);1453                    window.setTimeout(() => {1454                      setSettingsExiting(false);1455                      setSettingsInitialSection(null);1456                      setUpgradeHighlight(null);1457                      handleBack();1458                    }, 200);1459                  }}1460                  onImport={() => setView("import")}1461                  onExport={() => setView("export")}1462                  onBreachCheckDone={loadEntries}1463                  onOpenHealth={openHealth}1464                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("chirp-sync"); }}1465                  onOpenFileImport={handleOpenFileImport}1466                  onOpenPanic={() => setView("panic")}1467                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1468                  onOpenCodexRestore={() => setView("codex-restore")}1469                  onCardChange={setSettingsActiveCard}1470                  onProGate={(feature) => {1471                    setUpgradeHighlight(feature);1472                    setSettingsInitialSection("license");1473                  }}1474                />1475              </Suspense>1476            </Show>1477            <Show when={view() === "codex-generate"}>1478              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1479                <CodexGenerateView1480                  isPro={proStatus()}1481                  onBack={() => setView("settings")}1482                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1483                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1484                  onVaultLocked={() => handleLock()}1485                />1486              </Suspense>1487            </Show>1488            <Show when={view() === "codex-restore"}>1489              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1490                <CodexRestoreView1491                  onBack={() => setView("lock")}1492                  onRestoreSuccess={async () => {1493                    // After restore the vault is unlocked; refresh entries1494                    // and route to the main vault list. handleUnlock is the1495                    // canonical post-unlock setup path.1496                    await handleUnlock();1497                  }}1498                />1499              </Suspense>1500            </Show>1501            <Show when={view() === "chirp-sync"}>1502              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1503                <ChirpSyncView1504                  isPro={proStatus()}1505                  onBack={() => setView("settings")}1506                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1507                />1508              </Suspense>1509            </Show>1510            <Show when={view() === "add"}>1511              <AddView1512                entry={editEntry()}1513                entries={entries()}1514                onBack={handleBack}1515                onSave={handleSave}1516              />1517            </Show>1518            <Show when={view() === "import"}>1519              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1520                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1521              </Suspense>1522            </Show>1523            <Show when={view() === "export"}>1524              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1525                <ExportView onBack={handleExportBack} />1526              </Suspense>1527            </Show>1528            <Show when={view() === "panic"}>1529              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1530                <PanicView1531                  onCancel={() => setView("settings")}1532                  onOpenExport={() => {1533                    setReturnToPanic(true);1534                    setView("export");1535                  }}1536                  onDestroyed={async () => {1537                    clearCanarySuppressions();1538                    setEntries([]);1539                    setSelectedEntry(null);1540                    setEditEntry(undefined);1541                    setHasVault(false);1542                    setOnboarded(false);1543                    setProStatus(false);1544                    setPendingPasskey(null);1545                    setUpgradeHighlight(null);1546                    setSettingsInitialSection(null);1547                    setPendingProNotice(null);1548                    setPendingCelebration(false);1549                    setReturnToPanic(false);1550                    setContentPhase("idle");1551                    setView("lock");1552                  }}1553                />1554              </Suspense>1555            </Show>1556            {/* Health stays mounted while editing an entry from it so1557                computeReused() doesn't rerun on every cancel/back. */}1558            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1559              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1560                <HealthView1561                  entries={entries()}1562                  isPro={proStatus()}1563                  onFixEntry={handleFixEntry}1564                  onBack={() => setView("settings")}1565                  onRefresh={loadEntries}1566                  hidden={view() !== "health"}1567                />1568              </Suspense>1569            </Show>1570            <Show when={view() === "trash"}>1571              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1572                <TrashView1573                  onBack={() => setView("list")}1574                  onRestored={() => void loadEntries()}1575                />1576              </Suspense>1577            </Show>1578            <Show when={showNotes()}>1579              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1580                <NotesMode1581                  notes={entries().filter((e) => e.type === "note")}1582                  initialNoteId={openNoteId()}1583                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1584                  onNoteListChanged={() => void loadEntries()}1585                />1586              </div>1587            </Show>1588            <Show when={restoreView() === "file"}>1589              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1590                <ImportView1591                  mode="onboarding"1592                  replacesExistingVault={true}1593                  onBack={() => setRestoreView(null)}1594                  onImport={async () => {1595                    setRestoreView(null);1596                    await handleUnlock();1597                  }}1598                />1599              </Suspense>1600            </Show>1601            </section>1602            </Show>1603          </Show>1604        </Show>1605      </Show>1606      <Show when={showShortcutsHelp()}>1607        <ShortcutsHelpOverlay1608          bindings={shortcutBindings()}1609          onClose={() => setShowShortcutsHelp(false)}1610        />1611      </Show>1612    </div>1613  );1614}16151616function ShortcutsHelpOverlay(props: {1617  bindings: Record<ShortcutAction, Keybinding>;1618  onClose: () => void;1619}) {1620  return (1621    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1622      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1623        <div class="peach-shortcuts-help-head">1624          <h3>Keyboard shortcuts</h3>1625          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1626        </div>1627        <div class="peach-shortcuts-help-body">1628          <p class="peach-settings-sub-label">ENTRY VIEW</p>1629          <ul>1630            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1631              <li>1632                <span>{d.label}</span>1633                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1634              </li>1635            ))}1636          </ul>1637          <p class="peach-settings-sub-label">ANYWHERE</p>1638          <ul>1639            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1640              <li>1641                <span>{d.label}</span>1642                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1643              </li>1644            ))}1645          </ul>1646        </div>1647      </div>1648    </div>1649  );1650}