App.tsx

48.5 KB · raw

1import { createEffect, createMemo, createSignal, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { ACCENT_COLORS } from "../shared/types";3import type { AccentColorName, PendingPasskeyRequest, ProFeature, VaultEntry } from "../shared/types";4import { isPasskeyOnly } from "../shared/types";5import { LockView } from "./views/Lock";6import { Onboarding } from "./views/Onboarding";7import { ProCelebration } from "./views/ProCelebration";8import { VaultView, type SortOrder } from "./views/Vault";9import { EntryView } from "./views/Entry";10import { AddView } from "./views/Add";11import { PeachWordmark } from "./components/PeachMark";12import { PasskeyApprovalView } from "./views/PasskeyApproval";13import { extractDomain } from "../shared/domain";14import { popupCopy } from "./copy";15import {16  DEFAULT_BINDINGS,17  formatKeybinding,18  getActiveBindings,19  matchKeybinding,20  SHORTCUT_DESCRIPTORS,21  type Keybinding,22  type ShortcutAction,23} from "../shared/shortcuts";24import { generateTOTP } from "../crypto/totp";2526const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));27const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));28const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));29const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));30const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));31const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));3233type View =34  | "lock"35  | "pro-celebration"36  | "entry"37  | "list"38  | "add"39  | "settings"40  | "import"41  | "export"42  | "health"43  | "trash"44  | "panic";45type BootState = "loading" | "ready";4647const canarySuppressMap = new Map<string, boolean>();48let shellRingAnimation: Animation | null = null;4950export function isCanarySuppressed(entryId: string): boolean {51  return canarySuppressMap.get(entryId) ?? false;52}5354export function setCanarySuppressed(entryId: string, suppressed: boolean): void {55  canarySuppressMap.set(entryId, suppressed);56}5758export function clearCanarySuppressions(): void {59  canarySuppressMap.clear();60}6162export function triggerRing() {63  const shell = document.getElementById("hd-shell");64  if (!shell) return;6566  shellRingAnimation?.cancel();67  shell.dataset.glowing = "true";68  const animation = shell.animate(69    [70      { offset: 0, boxShadow: "var(--copy-shadow)" },71      {72        offset: 0.3,73        boxShadow:74          "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)",75      },76      { offset: 1, boxShadow: "var(--copy-shadow)" },77    ],78    {79      duration: 720,80      easing: "cubic-bezier(0.4, 0, 0.2, 1)",81      fill: "none",82    }83  );84  shellRingAnimation = animation;85  const clearGlow = () => {86    if (shellRingAnimation !== animation) return;87    shellRingAnimation = null;88    delete shell.dataset.glowing;89  };90  animation.onfinish = clearGlow;91  animation.oncancel = clearGlow;92}939495export function triggerPipPulse() {96  const pip = document.querySelector(".peach-status-pip, .pip");97  if (pip) {98    pip.classList.remove("pulse");99    void (pip as HTMLElement).offsetWidth;100    pip.classList.add("pulse");101  }102}103104function humanizeError(error: string | undefined): string | undefined {105  if (!error) return error;106  if (error === "STORAGE_QUOTA_EXCEEDED") {107    return "Peach has run out of browser storage. Delete some entries or clear browser storage to continue.";108  }109  return error;110}111112async function sendMessage(msg: any): Promise<any> {113  const MESSAGE_TIMEOUT_MS = 5000;114115  return new Promise((resolve) => {116    let settled = false;117    const timeoutId = window.setTimeout(() => {118      if (settled) return;119      settled = true;120      resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });121    }, MESSAGE_TIMEOUT_MS);122123    try {124      chrome.runtime.sendMessage(msg, (response) => {125        if (settled) return;126        settled = true;127        window.clearTimeout(timeoutId);128129        if (chrome.runtime.lastError) {130          resolve({131            ok: false,132            error:133              chrome.runtime.lastError.message ?? "SERVICE_WORKER_UNAVAILABLE",134          });135          return;136        }137138        if (response === undefined) {139          resolve({ ok: false, error: "SERVICE_WORKER_UNAVAILABLE" });140          return;141        }142143        if (response && response.ok === false) {144          response.error = humanizeError(response.error);145        }146        resolve(response);147      });148    } catch (error) {149      if (settled) return;150      settled = true;151      window.clearTimeout(timeoutId);152      resolve({153        ok: false,154        error:155          error instanceof Error ? error.message : "SERVICE_WORKER_UNAVAILABLE",156      });157    }158  });159}160161export { sendMessage };162163const ENTRY_TRANSITION_EXIT_MS = 95;164const ENTRY_TRANSITION_SETTLE_MS = 135;165166export default function App() {167  const [bootState, setBootState] = createSignal<BootState>("loading");168  const [view, setView] = createSignal<View>("lock");169  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(170    "enter"171  );172  const [contentTransitioning, setContentTransitioning] = createSignal(false);173  const [hasVault, setHasVault] = createSignal(false);174  const [onboarded, setOnboarded] = createSignal(true);175  const [entries, setEntries] = createSignal<VaultEntry[]>([]);176  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);177  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);178  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");179  const [theme, setTheme] = createSignal<"dark" | "light">("dark");180  const [displayFont, setDisplayFont] = createSignal<"cormorant-italic" | "cormorant" | "inter" | "system">("cormorant-italic");181  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");182  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);183  const [lockOnClose, setLockOnClose] = createSignal(true);184  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);185  const [breachMonitoring, setBreachMonitoring] = createSignal(true);186  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);187  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);188  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);189  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);190  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);191  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");192  // Cached Pro status — synchronous for render paths. Background's193  // GET_LICENSE is async, but render-time reads of isPro() must not block.194  // Refreshed at boot, after activate/deactivate, and whenever the popup195  // re-opens onto a stored license that has changed via another window.196  const [proStatus, setProStatus] = createSignal(false);197  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);198  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);199  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");200  const [listSearchSeed, setListSearchSeed] = createSignal("");201  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);202  const [pendingCelebration, setPendingCelebration] = createSignal(false);203  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);204  // True while Panic Step 1 has bounced the user out to Export. When Export's205  // onBack fires we return to Panic instead of Settings so the user keeps the206  // destruction context they came from.207  const [returnToPanic, setReturnToPanic] = createSignal(false);208209  let contentPhaseTimer: number | undefined;210211  function applyAccent(name: AccentColorName) {212    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;213    const hex = color.hex;214    document.documentElement.style.setProperty("--peach-accent", hex);215    // Ambient surface variables — derived from the accent so surfaces shift216    // subtly toward the accent hue rather than staying fixed warm-brown.217    document.documentElement.style.setProperty("--peach-glow", hex + "2A");218    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");219    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");220  }221222  createEffect(() => {223    applyAccent(accentColor());224  });225226  createEffect(() => {227    document.documentElement.classList.toggle("light", theme() === "light");228    document.body.classList.toggle("light", theme() === "light");229  });230231  createEffect(() => {232    document.documentElement.setAttribute("data-display-font", displayFont());233  });234235  createEffect(() => {236    document.documentElement.setAttribute("data-text-size", textSize());237  });238239  createEffect(() => {240    if (reduceMotion()) {241      document.documentElement.setAttribute("data-motion", "reduce");242    } else {243      document.documentElement.removeAttribute("data-motion");244    }245  });246247  const selectedIndex = createMemo(() => {248    const currentId = selectedEntry()?.id;249    if (!currentId) return entries().length > 0 ? 0 : -1;250    return entries().findIndex((entry) => entry.id === currentId);251  });252253  async function applyAccentColor(name: AccentColorName) {254    applyAccent(name);255    setAccentColor(name);256    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });257  }258259  async function applyTheme(t: "dark" | "light") {260    setTheme(t);261    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });262  }263264  async function applyDisplayFont(f: "cormorant-italic" | "cormorant" | "inter" | "system") {265    setDisplayFont(f);266    await sendMessage({ type: "UPDATE_SETTINGS", payload: { displayFont: f } });267  }268269  async function applyTextSize(size: "small" | "medium" | "large") {270    setTextSize(size);271    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });272  }273274  async function applyReduceMotion(enabled: boolean) {275    setReduceMotion(enabled);276    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });277  }278279  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload280  // small and lets future default updates land for actions the user hasn't281  // touched. Settings sends us the full active map; we filter and store.282  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {283    setShortcutBindings(active);284    const overrides: Record<string, Keybinding> = {};285    for (const action of Object.keys(active) as ShortcutAction[]) {286      const a = active[action];287      const d = DEFAULT_BINDINGS[action];288      const same = a.key === d.key289        && Boolean(a.ctrl)  === Boolean(d.ctrl)290        && Boolean(a.meta)  === Boolean(d.meta)291        && Boolean(a.shift) === Boolean(d.shift)292        && Boolean(a.alt)   === Boolean(d.alt);293      if (!same) overrides[action] = a;294    }295    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });296  }297298  async function applyLockOnClose(enabled: boolean) {299    setLockOnClose(enabled);300    await sendMessage({301      type: "UPDATE_SETTINGS",302      payload: { lockOnClose: enabled },303    });304  }305306  async function applyAutoLockMinutes(minutes: number) {307    setAutoLockMinutes(minutes);308    await sendMessage({309      type: "UPDATE_SETTINGS",310      payload: { autoLockMinutes: minutes },311    });312  }313314  async function applyBreachMonitoring(enabled: boolean) {315    setBreachMonitoring(enabled);316    await sendMessage({317      type: "UPDATE_SETTINGS",318      payload: { breachMonitoring: enabled },319    });320  }321322  onMount(async () => {323    // Resolve the active tab in parallel with the unlock/has-vault queries —324    // openVault()'s smart selection picks the entry matching currentTabDomain,325    // so it must be populated before openVault runs. Previously refreshCurrentTab326    // ran after openVault, leaving popups that booted already-unlocked falling327    // back to loadedEntries[0] instead of the domain match.328    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([329      sendMessage({ type: "IS_UNLOCKED" }),330      sendMessage({ type: "HAS_VAULT" }),331      refreshCurrentTab(),332      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),333    ]);334    const unlocked = Boolean(335      (unlockResponse as { ok: boolean; data?: boolean }).data336    );337    const vaultExists = Boolean(338      (vaultResponse as { ok: boolean; data?: boolean }).data339    );340    const shouldCelebrate = Boolean(341      (celebrationResponse as { ok: boolean; data?: boolean }).data342    );343    setHasVault(vaultExists);344    // Onboarding gate — show once on first install, never again. Existing345    // users (vaultExists) are auto-marked onboarded so they skip the flow346    // even on the very first popup open after this feature ships.347    try {348      const onboardingState = await chrome.storage.local.get("peach_onboarded");349      const seen = onboardingState.peach_onboarded === true;350      if (vaultExists && !seen) {351        await chrome.storage.local.set({ peach_onboarded: true });352        setOnboarded(true);353      } else {354        setOnboarded(seen);355      }356    } catch {357      // storage unavailable — default to onboarded so we never block boot358      setOnboarded(true);359    }360    await Promise.all([restoreSettings(), refreshProStatus()]);361362    // Mark played before any animation so a crash mid-sequence never replays it363    if (shouldCelebrate) {364      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });365    }366367    if (unlocked && vaultExists) {368      await openVault(undefined, shouldCelebrate);369      if (shouldCelebrate) {370        setView("pro-celebration");371        window.setTimeout(() => setView("entry"), 2500);372      }373    } else if (shouldCelebrate) {374      setPendingCelebration(true);375    }376377    await refreshPendingPasskey();378379    // Track tab changes so smart sort stays current380    const handleTabActivated = () => { void refreshCurrentTab(); };381    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {382      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();383    };384    try {385      chrome.tabs.onActivated.addListener(handleTabActivated);386      chrome.tabs.onUpdated.addListener(handleTabUpdated);387      onCleanup(() => {388        chrome.tabs.onActivated.removeListener(handleTabActivated);389        chrome.tabs.onUpdated.removeListener(handleTabUpdated);390      });391    } catch {392      // tabs permission may not be available in all contexts393    }394395    setBootState("ready");396    document.getElementById("pre-lock")?.setAttribute("hidden", "true");397398    // Check for pending session-storage notices from the background.399    if (chrome.storage.session) {400      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as401        Record<string, { feature?: string } | undefined>;402      if (session.pendingProGate?.feature) {403        await chrome.storage.session.remove("pendingProGate");404        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);405        setSettingsInitialSection("license");406        setView("settings");407      } else if (session.pendingProNotice?.feature) {408        await chrome.storage.session.remove("pendingProNotice");409        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });410      }411    }412413    // Warm the lazy-module cache so the Suspense fallback never shows for414    // locally-bundled extension views. Without this, the first navigation to415    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which416    // covers the shell and absorbs clicks on the header.417    void Promise.all([418      import("./views/Settings").catch(() => {}),419      import("./views/Import").catch(() => {}),420      import("./views/Export").catch(() => {}),421      import("./views/Health").catch(() => {}),422      import("./views/TrashView").catch(() => {}),423    ]);424425    // Lock-on-close via a persistent port. sendMessage in pagehide is426    // unreliable — the popup context tears down before the message lands.427    // The SW's onConnect listener locks when this port disconnects.428    let popupPort: chrome.runtime.Port | null = null;429    try {430      popupPort = chrome.runtime.connect({ name: "popup" });431    } catch { /* extension context invalidated — ignore */ }432    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });433434    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale435    // entries instead of waiting for the next GET_ENTRIES round-trip.436    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {437      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();438      if (msg?.type === "PRO_GATE_TRIGGERED") {439        // Background never navigates UI directly — it asks; the popup decides.440        // Land on Settings → License with the triggering feature highlighted.441        setUpgradeHighlight(msg.payload?.feature ?? null);442        setSettingsInitialSection("license");443        setView("settings");444      }445    };446    chrome.runtime.onMessage.addListener(handleRuntimeMessage);447    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));448449    // Action handlers — keyed by ShortcutAction. The dispatcher below tests450    // each binding against the event and runs the matching handler. New451    // shortcuts only need an entry here; the binding is data, not code.452    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {453      copy_password: () => {454        const entry = selectedEntry();455        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });456      },457      copy_username: () => {458        const entry = selectedEntry();459        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });460      },461      copy_totp: () => {462        const entry = selectedEntry();463        if (!entry?.totp) return;464        try {465          const { code } = generateTOTP(entry.totp);466          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });467        } catch { /* invalid TOTP secret — silent */ }468      },469      new_entry: () => handleAdd(),470      edit_entry: () => {471        const entry = selectedEntry();472        // Passkey-only entries have nothing user-editable in the Add view; the473        // passkey credential itself is opaque. Skip the edit action for them.474        if (!entry || isPasskeyOnly(entry)) return;475        setEditEntry(entry);476        setView("add");477      },478      delete_entry: () => {479        if (selectedEntry()) void handleDelete();480      },481      lock_vault: () => { void handleHeaderLock(); },482      search: () => openList(),483      nav_prev: () => navigate(-1),484      nav_next: () => navigate(1),485      jump_vault: () => setView("entry"),486      jump_settings: () => setView("settings"),487      show_help: () => setShowShortcutsHelp(true),488    };489490    // Actions that are MEANINGFUL only on the entry-detail view. Outside491    // that scope the binding is dormant — pressing C while on Settings492    // does nothing rather than awkwardly copying from a now-stale entry.493    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([494      "copy_password", "copy_username", "copy_totp",495      "edit_entry", "delete_entry", "nav_prev", "nav_next",496    ]);497498    const handleGlobalKeydown = (e: KeyboardEvent) => {499      const v = view();500      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"501        || (e.target as HTMLElement)?.tagName === "TEXTAREA"502        || (e.target as HTMLElement)?.isContentEditable;503      const isPrintableSearchKey =504        e.key.length === 1 &&505        !e.ctrlKey &&506        !e.metaKey &&507        !e.altKey;508509      // No input during the pro celebration sequence510      if (v === "pro-celebration") return;511512      // Help dialog: Escape closes it; eat the keypress so it doesn't513      // also navigate away from the underlying view.514      if (showShortcutsHelp()) {515        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }516        return;517      }518519      // ── Escape — fixed binding (not user-customizable) ───────520      if (e.key === "Escape") {521        if (v === "list") { setView("entry"); return; }522        if (v === "settings" || v === "import" || v === "export" || v === "add" || v === "health") { handleBack(); return; }523      }524525      // Bindings-driven dispatch. Single-key letter bindings without526      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is527      // inside an input, so users can type into search/forms normally.528      const bindings = shortcutBindings();529      for (const action of Object.keys(bindings) as ShortcutAction[]) {530        const binding = bindings[action];531        if (!matchKeybinding(e, binding)) continue;532        // Single-key letter bindings need the input-focus guard. Bindings533        // with any modifier are safe — Ctrl+L doesn't conflict with typing.534        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;535        if (!hasMod && binding.key.length === 1 && inInput) return;536        if (ENTRY_SCOPED.has(action) && v !== "entry") return;537        e.preventDefault();538        SHORTCUT_HANDLERS[action]?.();539        return;540      }541542      // Type-to-search: in entry view, any printable key not consumed by a543      // shortcut above primes the list search seed and opens the list.544      // Kept outside the bindings table because it's a behavior, not a545      // discrete action — every printable character can trigger it.546      if (v === "entry" && !inInput && isPrintableSearchKey) {547        e.preventDefault();548        primeListSearch(e.key);549        return;550      }551    };552    window.addEventListener("keydown", handleGlobalKeydown);553    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));554555    const handleStorageChanged = (556      changes: Record<string, chrome.storage.StorageChange>,557      areaName: string558    ) => {559      if (areaName !== "session") return;560      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {561        return;562      }563      void refreshPendingPasskey();564    };565566    chrome.storage.onChanged.addListener(handleStorageChanged);567    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));568  });569570  async function refreshCurrentTab() {571    try {572      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });573      const url = tab?.url ?? tab?.pendingUrl ?? "";574      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");575    } catch {576      setCurrentTabDomain("");577    }578  }579580  async function refreshPendingPasskey() {581    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });582    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);583  }584585  async function refreshProStatus() {586    const res = await sendMessage({ type: "GET_LICENSE" });587    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;588    setProStatus(Boolean(data?.valid && data?.plan === "pro"));589  }590591  async function restoreSettings() {592    const res = await sendMessage({ type: "GET_SETTINGS" });593    const s = (res as { ok: boolean; data?: any }).data ?? {};594    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {595      setAccentColor(s.accentColor as AccentColorName);596    }597    setTheme(s.theme === "light" ? "light" : "dark");598    if (s.displayFont === "cormorant" || s.displayFont === "inter" || s.displayFont === "system") {599      setDisplayFont(s.displayFont);600    } else {601      setDisplayFont("cormorant-italic");602    }603    if (s.textSize === "small" || s.textSize === "large") {604      setTextSize(s.textSize);605    } else {606      setTextSize("medium");607    }608    setReduceMotion(s.reduceMotion === true);609    setLockOnClose(s.lockOnClose !== false);610    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);611    setBreachMonitoring(s.breachMonitoring !== false);612    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);613    setShortcutBindings(getActiveBindings(s.shortcuts));614  }615616  async function applyTrashRetention(days: number) {617    setTrashRetentionDays(days);618    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });619  }620621  function primeListSearch(seed: string) {622    setListSearchSeed(seed);623    setListSearchSeedNonce((value) => value + 1);624    openList();625  }626627  // Returns null when it detected a dead service worker and triggered handleLock().628  // Callers that need to abort (e.g. openVault) check for null rather than relying629  // on view() state, which may already be "lock" during normal startup flows.630  async function loadEntries(): Promise<VaultEntry[] | null> {631    const response = await sendMessage({ type: "GET_ENTRIES" });632    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };633634    // If the service worker was killed and restarted (MV3 workers sleep), the635    // vault will be locked again — or the worker may not respond at all.636    // In either case, send the user to the lock screen rather than silently637    // showing an empty vault (which looks like data loss).638    if (!res.ok) {639      if (640        res.error === "vault locked" ||641        res.error === "SERVICE_WORKER_UNAVAILABLE" ||642        (typeof res.error === "string" && res.error.includes("locked"))643      ) {644        handleLock();645        return null; // signal emergency lock to callers646      }647      return [];648    }649650    const loadedEntries = res.data ?? [];651    setEntries(loadedEntries);652653    const currentId = selectedEntry()?.id;654    if (currentId) {655      setSelectedEntry(656        loadedEntries.find((entry) => entry.id === currentId) ?? loadedEntries[0] ?? null657      );658    }659660    return loadedEntries;661  }662663  async function openVault(preferredEntryId?: string, skipViewSet = false) {664    // Purge expired trash entries on each vault open665    const retDays = trashRetentionDays();666    if (retDays > 0) {667      void sendMessage({668        type: "PURGE_EXPIRED_TRASH",669        payload: { retentionMs: retDays * 86_400_000 },670      });671    }672673    const loadedEntries = await loadEntries();674675    // null means loadEntries() triggered an emergency lock (service worker died).676    // Don't override it by setting view back to "entry" with an empty vault.677    if (loadedEntries === null) return;678679    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry680    let nextSelectedEntry: VaultEntry | null = null;681    if (preferredEntryId) {682      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;683    }684    if (!nextSelectedEntry) {685      const tabDomain = currentTabDomain();686      if (tabDomain) {687        nextSelectedEntry = loadedEntries.find((e) => {688          if (e.type === "login") {689            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;690            for (const extra of e.additionalUrls ?? []) {691              if ((extractDomain(extra) ?? "") === tabDomain) return true;692            }693            return false;694          }695          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;696          return false;697        }) ?? null;698      }699    }700    nextSelectedEntry ??= loadedEntries[0] ?? null;701702    setSelectedEntry(nextSelectedEntry);703    setEditEntry(undefined);704    setContentTransitioning(false);705    setContentPhase("enter");706    queueContentIdle();707    if (!skipViewSet) setView("entry");708  }709710  async function handleUnlock() {711    setHasVault(true);712    triggerPipPulse();713    await restoreSettings();714    const celebrating = pendingCelebration();715    if (celebrating) {716      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });717      setPendingCelebration(false);718    }719    await openVault(undefined, celebrating);720    if (celebrating) {721      setView("pro-celebration");722      window.setTimeout(() => setView("entry"), 2500);723    }724  }725726  function handleSelectEntry(entry: VaultEntry) {727    setSelectedEntry(entry);728    setContentTransitioning(false);729    setContentPhase("enter");730    queueContentIdle();731    setView("entry");732  }733734  function handleAdd() {735    setEditEntry(undefined);736    setView("add");737  }738739  async function handleDelete() {740    const entry = selectedEntry();741    if (!entry) return;742    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });743    const loadedEntries = await loadEntries() ?? [];744    setSelectedEntry(loadedEntries[0] ?? null);745    setView("entry");746  }747748  async function handleDeleteMany(ids: string[]) {749    for (const id of ids) {750      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });751    }752    const loadedEntries = await loadEntries() ?? [];753    // If the currently selected entry was among the deleted, move to first754    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);755    if (!stillExists) setSelectedEntry(loadedEntries[0] ?? null);756  }757758  async function handleSave(savedEntry?: VaultEntry) {759    await openVault(savedEntry?.id);760  }761762  function handleBack() {763    setEditEntry(undefined);764    setView("entry");765  }766767  function handleLock() {768    clearCanarySuppressions();769    setEntries([]);770    setSelectedEntry(null);771    setEditEntry(undefined);772    setContentPhase("idle");773    setView("lock");774  }775776  function handleHeaderLock() {777    // Lock the UI immediately — do not wait for the service worker. If the SW778    // is dead or slow, the 5s sendMessage timeout would create a dead-click779    // window. The SW will lock on its next wake regardless.780    handleLock();781    void sendMessage({ type: "LOCK" });782  }783784  function navigate(dir: number) {785    const allEntries = entries();786    if (allEntries.length === 0) return;787    const currentIndex = selectedIndex();788    const baseIndex = currentIndex >= 0 ? currentIndex : 0;789    const nextIndex = (baseIndex + dir + allEntries.length) % allEntries.length;790    setSelectedEntry(allEntries[nextIndex]);791    setContentPhase("enter");792    queueContentIdle();793  }794795  function openList() {796    setView("list");797  }798799  function openHealth() {800    setEditEntry(undefined);801    setView("health");802  }803804  function handleOpenFileImport() {805    setRestoreView("file");806  }807808  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;809810  function handleFixEntry(entry: VaultEntry) {811    // Passkey-only entries have no editable surface — drop into view mode812    // instead of opening the Add editor.813    if (isPasskeyOnly(entry)) {814      setSelectedEntry(entry);815      setView("entry");816      return;817    }818    setEditEntry(entry);819    setView("add");820  }821822  const isLockedView = () => view() === "lock";823824  async function handleApprovePendingPasskey() {825    const pending = pendingPasskey();826    if (!pending) return;827    if (pending.browser === "firefox" && pending.type === "create") {828      // Firefox path: popup itself runs navigator.credentials.create. The829      // background never approved/rejected anything — it just stashed830      // intent. After the popup-driven flow resolves (success or cancel),831      // clear the pending key so the popup doesn't re-show this on next open.832      const { createFirefoxPasskey } = await import("./firefox-passkey");833      const result = await createFirefoxPasskey(pending);834      if (!result.ok) {835        console.warn("Peach Firefox passkey create failed:", result.error);836      }837      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });838      setPendingPasskey(null);839      void loadEntries();840      return;841    }842    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });843    setPendingPasskey(null);844  }845846  async function handleDenyPendingPasskey() {847    const pending = pendingPasskey();848    if (!pending) return;849    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });850    setPendingPasskey(null);851  }852853  function queueContentIdle(after?: () => void) {854    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);855    contentPhaseTimer = window.setTimeout(() => {856      setContentPhase("idle");857      after?.();858    }, ENTRY_TRANSITION_SETTLE_MS);859  }860861  return (862    <div class="popup-root peach-theme">863      <Show when={bootState() === "ready"}>864        <Show865          when={!pendingPasskey()}866          fallback={867            <PasskeyApprovalView868              type={pendingPasskey()!.type}869              rpName={pendingPasskey()!.rpName}870              rpId={pendingPasskey()!.rpId}871              userName={pendingPasskey()!.userName}872              userDisplayName={pendingPasskey()!.userDisplayName}873              onApprove={handleApprovePendingPasskey}874              onDeny={handleDenyPendingPasskey}875            />876          }877        >878          <Show879            when={!isLockedView()}880            fallback={881              <Show882                when={onboarded() || hasVault()}883                fallback={884                  <Onboarding885                    onComplete={() => { setOnboarded(true); }}886                  />887                }888              >889                <LockView890                  hasVault={hasVault()}891                  ready={bootState() === "ready"}892                  isPro={proStatus()}893                  onUnlock={handleUnlock}894                  onBackToOnboarding={895                    !hasVault()896                      ? () => setOnboarded(false)897                      : undefined898                  }899                />900              </Show>901            }902          >903            <Show904              when={view() !== "pro-celebration"}905              fallback={<ProCelebration />}906            >907            <section908              id="hd-shell"909              class="peach-shell peach-theme"910              data-surface="extension"911            >912            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>913              <PeachWordmark unlocked />914              <div class="peach-chrome-actions">915                <button916                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"917                  onClick={() => setView("settings")}918                  aria-label="Settings"919                >920                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">921                    <path922                      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"923                      stroke="currentColor"924                      stroke-width="0.9"925                    />926                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />927                  </svg>928                </button>929                <button930                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"931                  onClick={handleAdd}932                  aria-label="New entry"933                >934                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">935                    <path d="M5.5 1v9M1 5.5h9" />936                  </svg>937                </button>938                <button939                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"940                  onClick={() => void handleHeaderLock()}941                  aria-label="Lock vault"942                >943                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">944                    <path945                      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"946                      stroke="currentColor"947                      stroke-width="1"948                      stroke-linecap="round"949                    />950                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />951                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />952                  </svg>953                </button>954              </div>955            </header>956957            <Show when={pendingProNotice() !== null}>958              <div class="peach-pro-notice-banner">959                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>960                <button961                  class="peach-pro-notice-link"962                  onClick={() => {963                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);964                    setSettingsInitialSection("license");965                    setView("settings");966                    setPendingProNotice(null);967                  }}968                >969                  Learn more →970                </button>971                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>972              </div>973            </Show>974975            <div class="peach-shell-body">976              <div class="peach-shell-veil"></div>977              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>978                <EntryView979                  entry={selectedEntry()}980                  onDelete={handleDelete}981                  onFieldSaved={() => void loadEntries()}982                  onEscape={() => { setView("list"); }}983                />984              </div>985986              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen() }}>987                <div class="peach-search-bar">988                  <span class="peach-search-icon">989                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">990                      <circle cx="5.5" cy="5.5" r="3.75" />991                      <path d="M8.75 8.75L11.5 11.5" />992                    </svg>993                  </span>994                  <input995                    class="peach-search-input"996                    placeholder="search vault..."997                    autocomplete="off"998                    aria-label="Search vault entries"999                    onClick={openList}1000                    onFocus={openList}1001                    readOnly1002                  />1003                  <div class="peach-search-meta">1004                    <span class="peach-search-counter">1005                      {entries().length > 01006                        ? `${selectedIndex() + 1} / ${entries().length}`1007                        : "0 entries"}1008                    </span>1009                    <span class="peach-divider"></span>1010                    <button1011                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1012                      onClick={() => navigate(-1)}1013                      aria-label="Previous entry"1014                      disabled={entries().length === 0}1015                    >1016                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1017                        <path d="M5 1L1 5.5L5 10" />1018                      </svg>1019                    </button>1020                    <button1021                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1022                      onClick={() => navigate(1)}1023                      aria-label="Next entry"1024                      disabled={entries().length === 0}1025                    >1026                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1027                        <path d="M1 1L5 5.5L1 10" />1028                      </svg>1029                    </button>1030                  </div>1031                </div>1032              </section>1033            </div>10341035            <Show when={view() === "list"}>1036              <VaultView1037                entries={entries()}1038                selectedEntryId={selectedEntry()?.id}1039                currentTabDomain={currentTabDomain()}1040                sortOrder={sortOrder()}1041                searchSeed={listSearchSeed()}1042                searchSeedNonce={listSearchSeedNonce()}1043                onSelectEntry={handleSelectEntry}1044                onSortOrderChange={setSortOrder}1045                onAdd={handleAdd}1046                onClose={() => setView("entry")}1047                onOpenTrash={() => setView("trash")}1048                onDeleteMany={handleDeleteMany}1049              />1050            </Show>1051            <Show when={view() === "settings"}>1052              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1053                <SettingsView1054                  entriesCount={entries().length}1055                  breachMonitoring={breachMonitoring()}1056                  lockOnClose={lockOnClose()}1057                  autoLockMinutes={autoLockMinutes()}1058                  trashRetentionDays={trashRetentionDays()}1059                  theme={theme()}1060                  accentColor={accentColor()}1061                  displayFont={displayFont()}1062                  textSize={textSize()}1063                  reduceMotion={reduceMotion()}1064                  isPro={proStatus()}1065                  initialSection={settingsInitialSection()}1066                  upgradeHighlight={upgradeHighlight()}1067                  onBreachMonitoringChange={applyBreachMonitoring}1068                  onLockOnCloseChange={applyLockOnClose}1069                  onAutoLockMinutesChange={applyAutoLockMinutes}1070                  onTrashRetentionChange={applyTrashRetention}1071                  onThemeChange={applyTheme}1072                  onAccentChange={applyAccentColor}1073                  onDisplayFontChange={applyDisplayFont}1074                  onTextSizeChange={applyTextSize}1075                  onReduceMotionChange={applyReduceMotion}1076                  shortcuts={shortcutBindings()}1077                  onShortcutsChange={applyShortcuts}1078                  onLicenseChange={async () => {1079                    // After activation/deactivation: refresh Pro status,1080                    // re-load entries (defensive — signal state can drift if1081                    // the SW briefly restarts during the verify+save round-trip),1082                    // and replay the Pro celebration if this is the first time1083                    // a valid Pro license is seen on this device.1084                    await refreshProStatus();1085                    void loadEntries();1086                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1087                    if ((should as { ok: boolean; data?: boolean }).data === true) {1088                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1089                      setView("pro-celebration");1090                      window.setTimeout(() => setView("settings"), 2500);1091                    }1092                  }}1093                  onBack={() => { setSettingsInitialSection(null); setUpgradeHighlight(null); handleBack(); }}1094                  onImport={() => setView("import")}1095                  onExport={() => setView("export")}1096                  onBreachCheckDone={loadEntries}1097                  onOpenHealth={openHealth}1098                  onOpenFileImport={handleOpenFileImport}1099                  onOpenPanic={() => setView("panic")}1100                />1101              </Suspense>1102            </Show>1103            <Show when={view() === "add"}>1104              <AddView1105                entry={editEntry()}1106                entries={entries()}1107                onBack={handleBack}1108                onSave={handleSave}1109              />1110            </Show>1111            <Show when={view() === "import"}>1112              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1113                <ImportView onBack={handleBack} onImport={handleSave} />1114              </Suspense>1115            </Show>1116            <Show when={view() === "export"}>1117              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1118                <ExportView1119                  onBack={() => {1120                    if (returnToPanic()) {1121                      setReturnToPanic(false);1122                      setView("panic");1123                    } else {1124                      handleBack();1125                    }1126                  }}1127                />1128              </Suspense>1129            </Show>1130            <Show when={view() === "panic"}>1131              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1132                <PanicView1133                  onCancel={() => setView("settings")}1134                  onOpenExport={() => {1135                    setReturnToPanic(true);1136                    setView("export");1137                  }}1138                  onDestroyed={async () => {1139                    clearCanarySuppressions();1140                    setEntries([]);1141                    setSelectedEntry(null);1142                    setEditEntry(undefined);1143                    setHasVault(false);1144                    setOnboarded(false);1145                    setProStatus(false);1146                    setPendingPasskey(null);1147                    setUpgradeHighlight(null);1148                    setSettingsInitialSection(null);1149                    setPendingProNotice(null);1150                    setPendingCelebration(false);1151                    setReturnToPanic(false);1152                    setContentPhase("idle");1153                    setView("lock");1154                  }}1155                />1156              </Suspense>1157            </Show>1158            <Show when={view() === "health"}>1159              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1160                <HealthView1161                  entries={entries()}1162                  isPro={proStatus()}1163                  onFixEntry={handleFixEntry}1164                  onBack={() => setView("settings")}1165                  onRefresh={loadEntries}1166                />1167              </Suspense>1168            </Show>1169            <Show when={view() === "trash"}>1170              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1171                <TrashView1172                  onBack={() => setView("list")}1173                  onRestored={() => void loadEntries()}1174                />1175              </Suspense>1176            </Show>1177            <Show when={restoreView() === "file"}>1178              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1179                <ImportView1180                  mode="onboarding"1181                  replacesExistingVault={true}1182                  onBack={() => setRestoreView(null)}1183                  onImport={async () => {1184                    setRestoreView(null);1185                    await handleUnlock();1186                  }}1187                />1188              </Suspense>1189            </Show>1190            </section>1191            </Show>1192          </Show>1193        </Show>1194      </Show>1195      <Show when={showShortcutsHelp()}>1196        <ShortcutsHelpOverlay1197          bindings={shortcutBindings()}1198          onClose={() => setShowShortcutsHelp(false)}1199        />1200      </Show>1201    </div>1202  );1203}12041205function ShortcutsHelpOverlay(props: {1206  bindings: Record<ShortcutAction, Keybinding>;1207  onClose: () => void;1208}) {1209  return (1210    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>1211      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>1212        <div class="peach-shortcuts-help-head">1213          <h3>Keyboard shortcuts</h3>1214          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>1215        </div>1216        <div class="peach-shortcuts-help-body">1217          <p class="peach-settings-sub-label">ENTRY VIEW</p>1218          <ul>1219            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (1220              <li>1221                <span>{d.label}</span>1222                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1223              </li>1224            ))}1225          </ul>1226          <p class="peach-settings-sub-label">ANYWHERE</p>1227          <ul>1228            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (1229              <li>1230                <span>{d.label}</span>1231                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>1232              </li>1233            ))}1234          </ul>1235        </div>1236      </div>1237    </div>1238  );1239}