App.tsx

85.8 KB · raw

1import { createEffect, createMemo, createSignal, For, lazy, onCleanup, onMount, Show, Suspense } from "solid-js";2import { Portal } from "solid-js/web";3import { storageGet, storageRemove, 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 {9  hasCompletedInitialSync,10  INITIAL_SYNC_PENDING_DEVICE_KEY,11  type InitialSyncDevice,12} from "../shared/initial-sync";13import { LockView } from "./views/Lock";14import {15  ONBOARDING_CARD_STORAGE_KEY,16  ONBOARDING_LAST_CARD,17  Onboarding,18} from "./views/Onboarding";19import { NotesMode } from "./views/NotesMode";20import { ProCelebration } from "./views/ProCelebration";21import { InitialSyncView } from "./views/InitialSyncView";22import { VaultView, type SortOrder } from "./views/Vault";23import { EntryView } from "./views/Entry";24import { AddView } from "./views/Add";25import { PeachWordmark } from "./components/PeachMark";26import { PasskeyApprovalView } from "./views/PasskeyApproval";27import { extractDomain } from "../shared/domain";28import {29  syncIndicator,30  syncIndicatorLabel,31  type SyncOutcomeSummary,32} from "../shared/sync-outcome";33import { popupCopy } from "./copy";34import {35  DEFAULT_BINDINGS,36  formatKeybinding,37  getActiveBindings,38  matchKeybinding,39  SHORTCUT_DESCRIPTORS,40  type Keybinding,41  type ShortcutAction,42} from "../shared/shortcuts";43import { generateTOTP } from "../crypto/totp";44import { isNativePlatform, nativePlugin } from "../shared/native";4546export { sendMessage } from "../shared/bridge";4748const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));49const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));50const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));51const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));52const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));53const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));54const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));55const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));56const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));57const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));5859type View =60  | "lock"61  | "pro-celebration"62  | "entry"63  | "list"64  | "add"65  | "settings"66  | "pair-device"67  | "import"68  | "export"69  | "health"70  | "trash"71  | "panic"72  | "adopting"73  | "initial-sync"74  | "codex-generate"75  | "codex-restore";76type BootState = "loading" | "ready";7778const INITIAL_SYNC_POLL_MS = 500;79const INITIAL_SYNC_SLOW_MS = 15_000;8081const canarySuppressMap = new Map<string, boolean>();82let shellRingAnimation: Animation | null = null;8384export function isCanarySuppressed(entryId: string): boolean {85  return canarySuppressMap.get(entryId) ?? false;86}8788export function setCanarySuppressed(entryId: string, suppressed: boolean): void {89  canarySuppressMap.set(entryId, suppressed);90}9192export function clearCanarySuppressions(): void {93  canarySuppressMap.clear();94}9596export function triggerRing() {97  const shell = document.getElementById("hd-shell");98  if (!shell) return;99100  shellRingAnimation?.cancel();101  shell.dataset.glowing = "true";102  const animation = shell.animate(103    [104      { offset: 0, boxShadow: "var(--copy-shadow)" },105      {106        offset: 0.3,107        boxShadow:108          "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)",109      },110      { offset: 1, boxShadow: "var(--copy-shadow)" },111    ],112    {113      duration: 720,114      easing: "cubic-bezier(0.4, 0, 0.2, 1)",115      fill: "none",116    }117  );118  shellRingAnimation = animation;119  const clearGlow = () => {120    if (shellRingAnimation !== animation) return;121    shellRingAnimation = null;122    delete shell.dataset.glowing;123  };124  animation.onfinish = clearGlow;125  animation.oncancel = clearGlow;126}127128129export function triggerPipPulse() {130  const pip = document.querySelector(".peach-status-pip, .pip");131  if (pip) {132    pip.classList.remove("pulse");133    void (pip as HTMLElement).offsetWidth;134    pip.classList.add("pulse");135  }136}137138const ENTRY_TRANSITION_SETTLE_MS = 135;139140export default function App() {141  const [bootState, setBootState] = createSignal<BootState>("loading");142  const [view, setView] = createSignal<View>("lock");143  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,144  // CSS transition takes over for snap animation).145  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);146  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(147    "enter"148  );149  const [contentTransitioning, setContentTransitioning] = createSignal(false);150  const [hasVault, setHasVault] = createSignal(false);151  const [onboarded, setOnboarded] = createSignal(true);152  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);153  // Onboarding remounts whenever it leaves (create/adopt/restore) and comes154  // back. Those flows all exit from the final card, so resume there — a fresh155  // install's first mount stays at 0.156  const [onboardingCardAtExit, setOnboardingCardAtExit] = createSignal(0);157  const [entries, setEntries] = createSignal<VaultEntry[]>([]);158  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);159  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);160161  // Rare device-trust alerts stay visible; routine entry sync is silent.162  interface SyncAlert {163    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";164    entryId: string;165    entryTitle: string;166    deviceName: string;167    timestamp: number;168  }169  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);170  // Per-group flip index: which alert within a type-group is currently shown.171  const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});172  async function loadSyncAlerts() {173    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {174      ok: boolean;175      data?: SyncAlert[];176    };177    if (r.ok && (r.data?.length ?? 0) > 0) {178      setSyncAlerts(r.data ?? []);179      // Acknowledge so a crash between read and render doesn't lose them —180      // they remain on screen until the user dismisses each.181      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });182    }183  }184  function dismissAlertGroup(type: string) {185    setSyncAlerts((arr) => arr.filter((a) => a.type !== type));186    setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });187  }188  function flipAlert(type: string, dir: 1 | -1) {189    const group = syncAlerts().filter((a) => a.type === type);190    if (group.length <= 1) return;191    setAlertFlipIdx((m) => {192      const cur = m[type] ?? 0;193      return { ...m, [type]: (cur + dir + group.length) % group.length };194    });195  }196  /** Grouped alert types in display order, each with its alerts. */197  const alertGroups = createMemo(() => {198    const map = new Map<string, SyncAlert[]>();199    for (const a of syncAlerts()) {200      const g = map.get(a.type);201      if (g) g.push(a); else map.set(a.type, [a]);202    }203    return [...map.entries()];204  });205  function syncAlertText(a: SyncAlert): string {206    if (a.type === "DEVICE_REVOKED") {207      return `${a.deviceName} revoked a paired device — review your devices in Settings`;208    }209    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;210  }211  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");212  const [theme, setTheme] = createSignal<"dark" | "light">("dark");213  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");214  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);215  const [lockOnClose, setLockOnClose] = createSignal(false);216  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);217  const [breachMonitoring, setBreachMonitoring] = createSignal(true);218  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);219  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);220  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);221  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);222  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);223  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");224  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");225  // Cached Pro status — synchronous for render paths. Background's226  // GET_LICENSE is async, but render-time reads of isPro() must not block.227  // Refreshed at boot, after activate/deactivate, and whenever the popup228  // re-opens onto a stored license that has changed via another window.229  const [proStatus, setProStatus] = createSignal(false);230  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);231  // When the sync card's pairing button opens the pairing view, deep-link232  // straight into that pairing path instead of the rest screen.233  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");234  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);235  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");236  const [listSearchSeed, setListSearchSeed] = createSignal("");237  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);238  const [pendingCelebration, setPendingCelebration] = createSignal(false);239  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);240  // True while Panic Step 1 has bounced the user out to Export. When Export's241  // onBack fires we return to Panic instead of Settings so the user keeps the242  // destruction context they came from.243  const [returnToPanic, setReturnToPanic] = createSignal(false);244  // The view to return to when the add/edit view is dismissed. Normally "entry"245  // but "health" when the user arrives via the fix-entry path from Vault Health.246  const [editBackView, setEditBackView] = createSignal<View>("entry");247  const [settingsExiting, setSettingsExiting] = createSignal(false);248  const [showNotes, setShowNotes] = createSignal(false);249  // Topbar sync affordance. Always present: gating it on having a paired device250  // meant it never appeared for the person trying to set pairing up, which is251  // exactly when you reach for it.252  const [syncBusy, setSyncBusy] = createSignal(false);253  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);254  // The indicator light + its spoken-word equivalent. Colour alone is not the255  // signal; the title/aria-label always carries the same claim in English.256  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});257  const [pairedCount, setPairedCount] = createSignal(0);258  const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);259  const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);260  let initialSyncWaitGeneration = 0;261  const syncLight = () =>262    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());263  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());264  async function loadSyncIndicator() {265    const [stateRes, devicesRes] = await Promise.all([266      sendMessage({ type: "GET_SYNC_STATE" }),267      sendMessage({ type: "LIST_PAIRED_DEVICES" }),268    ]);269    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };270    if (s.ok && s.data) setSyncSummary(s.data);271    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };272    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);273  }274275  interface InitialSyncPairedDevice extends InitialSyncDevice {276    pairedAt?: number;277  }278279  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {280    const response = (await sendMessage({281      type: "LIST_PAIRED_DEVICES",282    })) as {283      ok: boolean;284      data?: { devices?: InitialSyncPairedDevice[] };285    };286    return response.ok ? response.data?.devices ?? [] : [];287  }288289  async function resolveInitialSyncDeviceId(): Promise<string | null> {290    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(291      () => null,292    );293    const devices = await listInitialSyncDevices().catch(() => []);294    if (stored && devices.some((device) => device.deviceId === stored)) {295      return stored;296    }297298    // Fresh adoption has exactly one direct source, but choosing the newest row299    // also repairs the marker if storage failed after the pair itself committed.300    const newest = [...devices].sort(301      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),302    )[0];303    if (!newest) return stored;304    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(305      () => undefined,306    );307    return newest.deviceId;308  }309310  async function finishInitialSync(generation: number): Promise<void> {311    if (generation !== initialSyncWaitGeneration) return;312    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);313    setInitialSyncDeviceId(null);314    setInitialSyncSlow(false);315    await refreshProStatus();316317    // A license transferred during pairing intentionally leaves the one-shot318    // celebration pending. Consume it only now: sync readiness → celebration319    // → populated vault, never celebration → temporarily empty vault.320    const celebration = (await sendMessage({321      type: "SHOULD_PLAY_CELEBRATION",322    })) as { ok: boolean; data?: boolean };323    const shouldCelebrate = celebration.ok && celebration.data === true;324    if (shouldCelebrate) {325      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });326    }327328    const opened = await openVault(undefined, shouldCelebrate);329    if (!opened || generation !== initialSyncWaitGeneration) return;330    if (shouldCelebrate) {331      setView("pro-celebration");332      window.setTimeout(() => {333        if (generation === initialSyncWaitGeneration) setView("entry");334      }, 2500);335    }336  }337338  async function beginInitialSyncWait(deviceId: string): Promise<void> {339    const generation = ++initialSyncWaitGeneration;340    setInitialSyncDeviceId(deviceId);341    setInitialSyncSlow(false);342    setView("initial-sync");343    const startedAt = Date.now();344345    // Best effort: the pairing write already wakes the mesh listener, while346    // this trigger covers the key-order case where this receiver is the dialer.347    void sendMessage({348      type: "TRIGGER_SYNC",349      payload: { reason: "foreground" },350    }).catch(() => undefined);351352    while (353      generation === initialSyncWaitGeneration &&354      view() === "initial-sync"355    ) {356      try {357        const devices = await listInitialSyncDevices();358        if (hasCompletedInitialSync(devices, deviceId)) {359          await finishInitialSync(generation);360          return;361        }362      } catch {363        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.364      }365      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {366        setInitialSyncSlow(true);367      }368      await new Promise((resolve) =>369        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),370      );371    }372  }373374  async function retryInitialSync(): Promise<void> {375    const deviceId =376      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());377    if (deviceId) {378      await beginInitialSyncWait(deviceId);379    } else {380      setInitialSyncSlow(true);381    }382  }383384  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);385  // Set on popup boot when peach_recovery_pending flag is found in session386  // storage — instructs LockView to skip the unlock UI and open the recovery387  // words confirmation surface instead. Cleared via handleUnlock once the388  // user has typed the 3 confirmation words.389  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);390391  let contentPhaseTimer: number | undefined;392  // Set when the popup was opened from the inline "Open Peach to unlock" button.393  // handleUnlock() closes the popup after unlock so the user returns to the page.394  let openedForInlineUnlock = false;395396  onCleanup(() => {397    initialSyncWaitGeneration += 1;398  });399400  function applyAccent(name: AccentColorName) {401    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;402    const hex = color.hex;403    document.documentElement.style.setProperty("--peach-accent", hex);404    // Ambient surface variables — derived from the accent so surfaces shift405    // subtly toward the accent hue rather than staying fixed warm-brown.406    document.documentElement.style.setProperty("--peach-glow", hex + "2A");407    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");408    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");409  }410411  createEffect(() => {412    applyAccent(accentColor());413  });414415  createEffect(() => {416    document.documentElement.classList.toggle("light", theme() === "light");417    document.body.classList.toggle("light", theme() === "light");418  });419420  createEffect(() => {421    document.documentElement.setAttribute("data-text-size", textSize());422  });423424  createEffect(() => {425    if (reduceMotion()) {426      document.documentElement.setAttribute("data-motion", "reduce");427    } else {428      document.documentElement.removeAttribute("data-motion");429    }430  });431432  // Notes are not a destination of the Entry view; selecting a note opens the433  // notes surface instead (handleSelectEntry). Anything that walks or counts434  // the Entry view's neighbours (counter, prev/next, index) must use this435  // filtered list, otherwise the user can arrow into a note and is stuck —436  // the Entry view can't render a note and the prev/next buttons stop moving.437  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));438439  const selectedIndex = createMemo(() => {440    const currentId = selectedEntry()?.id;441    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;442    return nonNoteEntries().findIndex((entry) => entry.id === currentId);443  });444445  async function applyAccentColor(name: AccentColorName) {446    applyAccent(name);447    setAccentColor(name);448    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });449  }450451  async function applyTheme(t: "dark" | "light") {452    setTheme(t);453    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });454  }455456  async function applyTextSize(size: "small" | "medium" | "large") {457    setTextSize(size);458    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });459  }460461  async function applyReduceMotion(enabled: boolean) {462    setReduceMotion(enabled);463    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });464  }465466  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload467  // small and lets future default updates land for actions the user hasn't468  // touched. Settings sends us the full active map; we filter and store.469  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {470    setShortcutBindings(active);471    const overrides: Record<string, Keybinding> = {};472    for (const action of Object.keys(active) as ShortcutAction[]) {473      const a = active[action];474      const d = DEFAULT_BINDINGS[action];475      const same = a.key === d.key476        && Boolean(a.ctrl)  === Boolean(d.ctrl)477        && Boolean(a.meta)  === Boolean(d.meta)478        && Boolean(a.shift) === Boolean(d.shift)479        && Boolean(a.alt)   === Boolean(d.alt);480      if (!same) overrides[action] = a;481    }482    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });483  }484485  async function applyLockOnClose(enabled: boolean) {486    setLockOnClose(enabled);487    await sendMessage({488      type: "UPDATE_SETTINGS",489      payload: { lockOnClose: enabled },490    });491  }492493  async function applyAutoLockMinutes(minutes: number) {494    setAutoLockMinutes(minutes);495    await sendMessage({496      type: "UPDATE_SETTINGS",497      payload: { autoLockMinutes: minutes },498    });499  }500501  async function applyBreachMonitoring(enabled: boolean) {502    setBreachMonitoring(enabled);503    await sendMessage({504      type: "UPDATE_SETTINGS",505      payload: { breachMonitoring: enabled },506    });507  }508509  onMount(async () => {510    // Resolve the active tab in parallel with the unlock/has-vault queries —511    // openVault()'s smart selection picks the entry matching currentTabDomain,512    // so it must be populated before openVault runs. Previously refreshCurrentTab513    // ran after openVault, leaving popups that booted already-unlocked falling514    // back to loadedEntries[0] instead of the domain match.515    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([516      sendMessage({ type: "IS_UNLOCKED" }),517      sendMessage({ type: "HAS_VAULT" }),518      refreshCurrentTab(),519      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),520    ]);521    const unlocked = Boolean(522      (unlockResponse as { ok: boolean; data?: boolean }).data523    );524    const vaultExists = Boolean(525      (vaultResponse as { ok: boolean; data?: boolean }).data526    );527    const shouldCelebrate = Boolean(528      (celebrationResponse as { ok: boolean; data?: boolean }).data529    );530    setHasVault(vaultExists);531    // Onboarding gate — show once on first install, never again. Existing532    // users (vaultExists) are auto-marked onboarded so they skip the flow533    // even on the very first popup open after this feature ships.534    try {535      const onboarded = await storageGet("peach_onboarded");536      const seen = onboarded === "true";537      if (vaultExists && !seen) {538        await storageSet("peach_onboarded", "true");539        await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});540        setOnboarded(true);541      } else {542        setOnboarded(seen);543        if (!seen) {544          // Resume mid-onboarding where the user left off instead of545          // rewinding to the opening card after a popup close.546          const stored = Number(547            await storageGet(ONBOARDING_CARD_STORAGE_KEY).catch(() => null),548          );549          if (550            Number.isInteger(stored) &&551            stored > 0 &&552            stored <= ONBOARDING_LAST_CARD553          ) {554            setOnboardingCardAtExit(stored);555          }556        }557      }558    } catch {559      // storage unavailable — default to onboarded so we never block boot560      setOnboarded(true);561    }562    await Promise.all([restoreSettings(), refreshProStatus()]);563564    const pendingInitialSyncMarker =565      unlocked && vaultExists566        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)567        : null;568    const pendingInitialSyncDeviceId = pendingInitialSyncMarker569      ? await resolveInitialSyncDeviceId()570      : null;571572    // Mark played before any animation so a crash mid-sequence never replays573    // it. A newly adopted receiver deliberately defers this until its first574    // real sync finishes, preserving initial sync → celebration → vault.575    if (shouldCelebrate && !pendingInitialSyncDeviceId) {576      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });577    }578579    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome580    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.581    if (unlocked && vaultExists) {582      void sendMessage({583        type: "TRIGGER_SYNC",584        payload: { reason: "foreground" },585      });586      void loadSyncIndicator();587      // Rare device-trust alerts only; routine entry sync stays quiet.588      void loadSyncAlerts();589    }590591    // If the user created a vault but hasn't yet confirmed their recovery592    // words, route back to the recovery-words screen instead of opening the593    // entries view. The flag lives in chrome.storage.local so it survives594    // both popup close (SW suppresses lock-on-close) and full browser595    // restart (handleUnlock checks the same flag after a fresh password596    // unlock). Cleared when confirmation succeeds.597    let recoveryPending = false;598    try {599      const out = await chrome.storage.local?.get("peach_recovery_pending");600      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";601    } catch { /* best-effort */ }602603    // If this popup was opened from the inline "Open Peach to unlock" button,604    // the background set a session flag. Read and clear it so handleUnlock()605    // can close the popup after unlock and return the user to the page.606    if (chrome.storage.session) {607      try {608        const s = await chrome.storage.session.get("peach_inline_unlock");609        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {610          openedForInlineUnlock = true;611          await chrome.storage.session.remove("peach_inline_unlock");612        }613      } catch { /* best-effort */ }614    }615616    // Native: closing the app before recovery-words confirmation means the617    // user didn't finish vault creation. Throw the partial vault away and618    // restart onboarding rather than asking them to unlock a vault they619    // never finished creating. Desktop keeps the existing "unlock to620    // resume" flow because closing the popup there is much more casual.621    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {622      try {623        await chrome.storage.local?.remove([624          "peach_vault_a",625          "peach_vault_b",626          "peach_recovery_pending",627          "peach_onboarded",628          "peach_vault_history",629          ONBOARDING_CARD_STORAGE_KEY,630        ]);631      } catch { /* best-effort */ }632      setHasVault(false);633      setOnboarded(false);634      setView("lock");635      setBootState("ready");636      return;637    }638639    if (recoveryPending && unlocked) {640      // forceRecoveryWords overrides LockView's hasVault gate so the641      // recovery surface renders even though the vault now exists.642      setForceRecoveryWords(true);643      setView("lock");644    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {645      void beginInitialSyncWait(pendingInitialSyncDeviceId);646    } else if (unlocked && vaultExists) {647      await openVault(undefined, shouldCelebrate);648      if (shouldCelebrate) {649        setView("pro-celebration");650        window.setTimeout(() => setView("entry"), 2500);651      }652    } else if (shouldCelebrate) {653      setPendingCelebration(true);654    }655656    await refreshPendingPasskey();657658    // Track tab changes so smart sort stays current659    const handleTabActivated = () => { void refreshCurrentTab(); };660    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {661      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();662    };663    try {664      chrome.tabs.onActivated.addListener(handleTabActivated);665      chrome.tabs.onUpdated.addListener(handleTabUpdated);666      onCleanup(() => {667        chrome.tabs.onActivated.removeListener(handleTabActivated);668        chrome.tabs.onUpdated.removeListener(handleTabUpdated);669      });670    } catch {671      // tabs permission may not be available in all contexts672    }673674    setBootState("ready");675676    // Deep-link: ?codex=pdf opens a detached window straight into the677    // Codex restore flow with auto-picked PDF. The action popup can't host678    // a file dialog without dismissing itself, so this is the only way the679    // PDF import path survives. See CodexRestoreView.openPdfPicker().680    try {681      const route = new URLSearchParams(window.location.search).get("codex");682      if (route === "pdf" || route === "restore") {683        setView("codex-restore");684      }685    } catch {686      // location.search unavailable — ignore.687    }688689    // Check for pending session-storage notices from the background.690    if (chrome.storage.session) {691      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as692        Record<string, { feature?: string } | undefined>;693      if (session.pendingProGate?.feature) {694        await chrome.storage.session.remove("pendingProGate");695        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);696        setSettingsInitialSection("license");697        setView("settings");698      } else if (session.pendingProNotice?.feature) {699        await chrome.storage.session.remove("pendingProNotice");700        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });701      }702    }703704    // Warm the lazy-module cache so the Suspense fallback never shows for705    // locally-bundled extension views. Without this, the first navigation to706    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which707    // covers the shell and absorbs clicks on the header.708    void Promise.all([709      import("./views/Settings").catch(() => {}),710      import("./views/Import").catch(() => {}),711      import("./views/Export").catch(() => {}),712      import("./views/Health").catch(() => {}),713      import("./views/TrashView").catch(() => {}),714    ]);715716    // Lock-on-close via a persistent port. sendMessage in pagehide is717    // unreliable — the popup context tears down before the message lands.718    // The SW's onConnect listener locks when this port disconnects.719    let popupPort: chrome.runtime.Port | null = null;720    try {721      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect722      // listener accepts the "popup-" prefix; the random suffix is defence in723      // depth against a port named exactly "popup" from anything but our popup.724      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });725    } catch { /* extension context invalidated — ignore */ }726    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });727728    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only729    // reliable signal is appStateChange — setTimeout is killed when the OS730    // backgrounds the app. We measure elapsed background time on resume.731    if (isNativePlatform()) {732      let backgroundedAt: number | null = null;733734      const CapApp = nativePlugin<{735        addListener: (736          ev: string,737          cb: (s: { isActive: boolean }) => void,738        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };739      }>("App");740      if (CapApp?.addListener) {741        const sub = CapApp.addListener(742          "appStateChange",743          ({ isActive }: { isActive: boolean }) => {744            if (!isActive) {745              backgroundedAt = Date.now();746              return;747            }748            if (backgroundedAt !== null && autoLockMinutes() > 0) {749              const elapsed = Date.now() - backgroundedAt;750              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();751            }752            backgroundedAt = null;753          }754        );755        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.756        onCleanup(() => {757          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});758        });759      }760761      // L12/COR-011: foreground idle autolock. appStateChange only fires when762      // the OS backgrounds the app — if the user idles with the screen on,763      // chrome.alarms is no-op'd in Capacitor so the vault would stay open764      // indefinitely. Poll every 30s and lock if elapsed since last user765      // interaction exceeds autoLockMinutes.766      let lastUserActivityAt = Date.now();767      const bumpActivity = () => { lastUserActivityAt = Date.now(); };768      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;769      for (const ev of ACTIVITY_EVENTS) {770        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });771      }772      const idleLockInterval = setInterval(() => {773        const minutes = autoLockMinutes();774        if (!minutes || minutes <= 0) return;775        const elapsed = Date.now() - lastUserActivityAt;776        if (elapsed >= minutes * 60_000) {777          lastUserActivityAt = Date.now();778          handleHeaderLock();779        }780      }, 30_000);781      onCleanup(() => {782        clearInterval(idleLockInterval);783        for (const ev of ACTIVITY_EVENTS) {784          document.removeEventListener(ev, bumpActivity, { capture: true });785        }786      });787788      // The retired native peer-discovery trigger went with the old Capacitor789      // pairing plugin. Reconnection is address-cache first, subnet probe second790      // (sync-runner.ts); relocating a peer that changed networks is an791      // Android-side discovery concern now.792      if (isNativePlatform()) {793        // Android runs the background/sync dispatcher in-process with the794        // popup, so the production runner has to be registered from the795        // UI bootstrap path instead of the MV3 service-worker entry.796        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>797          import("../background/sync-runner").then(({ productionSyncRunner }) => {798            setSyncRunner(productionSyncRunner);799            void hydratePersistedSyncState();800          })801        );802      }803    }804805    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale806    // entries instead of waiting for the next GET_ENTRIES round-trip.807    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {808      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();809      if (msg?.type === "SYNC_STATE_CHANGED") {810        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);811      }812      if (msg?.type === "PRO_GATE_TRIGGERED") {813        setUpgradeHighlight(msg.payload?.feature ?? null);814        setSettingsInitialSection("license");815        setView("settings");816      }817    };818    chrome.runtime.onMessage.addListener(handleRuntimeMessage);819    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));820821    // Android hardware/gesture back. MainActivity fires peach:back; the popup822    // decides what "back" means per surface. Lock+no-vault is the common case823    // — return to onboarding rather than letting the OS dismiss the activity.824    const handlePeachBack = () => {825      // Notes mode captures back first826      if (showNotes()) {827        setShowNotes(false);828        setOpenNoteId(undefined);829        return;830      }831      const v = view();832      if (v === "lock" && !hasVault() && onboarded()) {833        setOnboarded(false);834        return;835      }836      if (v === "list") { setView("entry"); return; }837      if (v === "settings") {838        window.dispatchEvent(new Event("peach:settings-back"));839        return;840      }841      if (v === "import" || v === "health") { setView("settings"); return; }842      if (v === "export") { handleExportBack(); return; }843      if (v === "add") { handleBack(); return; }844      if (v === "pair-device") { setView("settings"); return; }845    };846    window.addEventListener("peach:back", handlePeachBack);847    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));848849    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that850    // peeks from the bottom (search bar handle visible) and drags up to fill851    // the screen. dragOffset is the LIVE finger offset during a drag, in px,852    // 0 when no drag in progress. The wrapper element computes transform =853    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.854    if (isNativePlatform()) {855      let touchStartY = 0;856      let touchStartX = 0;857      let lastY = 0;858      let lastT = 0;859      let dragging = false;860      let captured = false;861      const HORIZONTAL_TOLERANCE = 16;862      const ACTIVATION_DY = 8;863      const PEEK_PX = 60;864865      const onTouchStart = (e: TouchEvent) => {866        const t = e.touches[0];867        if (!t) return;868        const v = view();869        if (v !== "entry" && v !== "list") return;870        // Entry view: only intercept drags starting in the bottom 40%.871        // List view: intercept drags starting in the top 35% (the search/handle row).872        const inBand = v === "entry"873          ? t.clientY > window.innerHeight * 0.6874          : t.clientY < window.innerHeight * 0.35;875        if (!inBand) return;876        touchStartY = lastY = t.clientY;877        touchStartX = t.clientX;878        lastT = e.timeStamp;879        dragging = true;880        captured = false;881      };882883      const onTouchMove = (e: TouchEvent) => {884        if (!dragging) return;885        const t = e.touches[0];886        if (!t) return;887        const dy = t.clientY - touchStartY;888        const dx = Math.abs(t.clientX - touchStartX);889890        if (!captured) {891          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {892            // Looks like a horizontal swipe — release.893            dragging = false;894            return;895          }896          if (Math.abs(dy) < ACTIVATION_DY) return;897          captured = true;898        }899900        // Translate the sheet by dy from its rest (peek) position. Peek is901        // (viewport height - PEEK_PX). Open is 0.902        const v = view();903        const restClosed = window.innerHeight - PEEK_PX;904        const baseTranslate = v === "list" ? 0 : restClosed;905        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));906        setSheetTranslate(next);907        lastY = t.clientY;908        lastT = e.timeStamp;909      };910911      const onTouchEnd = (e: TouchEvent) => {912        if (!dragging) { return; }913        const t = e.changedTouches[0];914        const elapsed = Math.max(1, e.timeStamp - lastT);915        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms916        const wasCaptured = captured;917        dragging = false;918        captured = false;919        const v = view();920921        if (!wasCaptured) {922          // Tap in the peek strip while in entry view → open the vault list.923          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");924          setSheetTranslate(null);925          return;926        }927928        const restClosed = window.innerHeight - PEEK_PX;929        const current = sheetTranslate() ?? restClosed;930931        // Snap rules:932        //   - Strong upward velocity → open933        //   - Strong downward velocity → close934        //   - Otherwise snap to whichever rest is closer935        let nextOpen: boolean;936        if (velocity < -0.05) nextOpen = true;937        else if (velocity > 0.05) nextOpen = false;938        else nextOpen = current < restClosed * 0.5;939940        if (nextOpen && v !== "list") setView("list");941        if (!nextOpen && v !== "entry") setView("entry");942        // Release the live offset so CSS transition handles the snap.943        setSheetTranslate(null);944      };945946      document.addEventListener("touchstart", onTouchStart, { passive: true });947      document.addEventListener("touchmove",  onTouchMove,  { passive: true });948      document.addEventListener("touchend",   onTouchEnd,   { passive: true });949      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });950      onCleanup(() => {951        document.removeEventListener("touchstart", onTouchStart);952        document.removeEventListener("touchmove",  onTouchMove);953        document.removeEventListener("touchend",   onTouchEnd);954      });955    }956957    // Action handlers — keyed by ShortcutAction. The dispatcher below tests958    // each binding against the event and runs the matching handler. New959    // shortcuts only need an entry here; the binding is data, not code.960    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {961      copy_password: () => {962        const entry = selectedEntry();963        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });964      },965      copy_username: () => {966        const entry = selectedEntry();967        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });968      },969      copy_totp: () => {970        const entry = selectedEntry();971        if (!entry?.totp) return;972        try {973          const { code } = generateTOTP(entry.totp);974          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });975        } catch { /* invalid TOTP secret — silent */ }976      },977      new_entry: () => handleAdd(),978      edit_entry: () => {979        const entry = selectedEntry();980        // Passkey-only entries have nothing user-editable in the Add view; the981        // passkey credential itself is opaque. Skip the edit action for them.982        if (!entry || isPasskeyOnly(entry)) return;983        setEditEntry(entry);984        setView("add");985      },986      delete_entry: () => {987        if (selectedEntry()) void handleDelete();988      },989      lock_vault: () => { void handleHeaderLock(); },990      search: () => openList(),991      nav_prev: () => navigate(-1),992      nav_next: () => navigate(1),993      jump_vault: () => setView("entry"),994      jump_settings: () => setView("settings"),995      show_help: () => setShowShortcutsHelp(true),996    };997998    // Actions that are MEANINGFUL only on the entry-detail view. Outside999    // that scope the binding is dormant — pressing C while on Settings1000    // does nothing rather than awkwardly copying from a now-stale entry.1001    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([1002      "copy_password", "copy_username", "copy_totp",1003      "edit_entry", "delete_entry", "nav_prev", "nav_next",1004    ]);10051006    const handleGlobalKeydown = (e: KeyboardEvent) => {1007      const v = view();1008      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"1009        || (e.target as HTMLElement)?.tagName === "TEXTAREA"1010        || (e.target as HTMLElement)?.isContentEditable;1011      const isPrintableSearchKey =1012        e.key.length === 1 &&1013        !e.ctrlKey &&1014        !e.metaKey &&1015        !e.altKey;10161017      // No shortcuts while a full-screen surface owns the whole viewport:1018      // the lock screen, the post-pairing readiness sequence, or the Pro1019      // celebration. Without this the lock screen is at the mercy of whatever1020      // single-key binding is active — e.g. typing "n" in a password that1021      // slips out of focus triggers `new_entry` and escapes the lock screen.1022      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;10231024      // Help dialog: Escape closes it; eat the keypress so it doesn't1025      // also navigate away from the underlying view.1026      if (showShortcutsHelp()) {1027        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }1028        return;1029      }10301031      // ── Escape — fixed binding (not user-customizable) ───────1032      if (e.key === "Escape") {1033        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }1034        if (v === "list") { setView("entry"); return; }1035        if (v === "settings" || v === "add") { handleBack(); return; }1036        if (v === "import" || v === "health") { setView("settings"); return; }1037        if (v === "export") { handleExportBack(); return; }1038        if (v === "pair-device") { setView("settings"); return; }1039      }10401041      // Bindings-driven dispatch. Single-key letter bindings without1042      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is1043      // inside an input, so users can type into search/forms normally.1044      const bindings = shortcutBindings();1045      for (const action of Object.keys(bindings) as ShortcutAction[]) {1046        const binding = bindings[action];1047        if (!matchKeybinding(e, binding)) continue;1048        // Single-key letter bindings need the input-focus guard. Bindings1049        // with any modifier are safe — Ctrl+L doesn't conflict with typing.1050        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;1051        if (!hasMod && binding.key.length === 1 && inInput) return;1052        if (ENTRY_SCOPED.has(action) && v !== "entry") return;1053        e.preventDefault();1054        SHORTCUT_HANDLERS[action]?.();1055        return;1056      }10571058      // Type-to-search: in entry view, any printable key not consumed by a1059      // shortcut above primes the list search seed and opens the list.1060      // Kept outside the bindings table because it's a behavior, not a1061      // discrete action — every printable character can trigger it.1062      if (v === "entry" && !inInput && isPrintableSearchKey) {1063        e.preventDefault();1064        primeListSearch(e.key);1065        return;1066      }1067    };1068    window.addEventListener("keydown", handleGlobalKeydown);1069    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));10701071    const handleStorageChanged = (1072      changes: Record<string, chrome.storage.StorageChange>,1073      areaName: string1074    ) => {1075      if (areaName !== "session") return;1076      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {1077        return;1078      }1079      void refreshPendingPasskey();1080    };1081    chrome.storage.onChanged.addListener(handleStorageChanged);1082    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));1083  });10841085  async function refreshCurrentTab() {1086    try {1087      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1088      const url = tab?.url ?? tab?.pendingUrl ?? "";1089      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");1090      // Skip extension/internal URLs — adding chrome://, about:, or1091      // chrome-extension:// to a vault entry is never what the user wants.1092      const isWebUrl = /^https?:\/\//i.test(url);1093      setCurrentTabUrl(isWebUrl ? url : "");1094    } catch {1095      setCurrentTabDomain("");1096      setCurrentTabUrl("");1097    }1098  }10991100  async function refreshPendingPasskey() {1101    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });1102    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);1103  }11041105  async function refreshProStatus() {1106    const res = await sendMessage({ type: "GET_LICENSE" });1107    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;1108    setProStatus(Boolean(data?.valid && data?.plan === "pro"));1109  }11101111  async function restoreSettings() {1112    const res = await sendMessage({ type: "GET_SETTINGS" });1113    const s = (res as { ok: boolean; data?: any }).data ?? {};1114    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {1115      setAccentColor(s.accentColor as AccentColorName);1116    }1117    setTheme(s.theme === "light" ? "light" : "dark");1118    if (s.textSize === "small" || s.textSize === "large") {1119      setTextSize(s.textSize);1120    } else {1121      setTextSize("medium");1122    }1123    setReduceMotion(s.reduceMotion === true);1124    setLockOnClose(s.lockOnClose === true);1125    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);1126    setBreachMonitoring(s.breachMonitoring !== false);1127    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);1128    setShortcutBindings(getActiveBindings(s.shortcuts));1129  }11301131  async function applyTrashRetention(days: number) {1132    setTrashRetentionDays(days);1133    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });1134  }11351136  function primeListSearch(seed: string) {1137    setListSearchSeed(seed);1138    setListSearchSeedNonce((value) => value + 1);1139    openList();1140  }11411142  // Returns null when it detected a dead service worker and triggered handleLock().1143  // Callers that need to abort (e.g. openVault) check for null rather than relying1144  // on view() state, which may already be "lock" during normal startup flows.1145  async function loadEntries(): Promise<VaultEntry[] | null> {1146    const response = await sendMessage({ type: "GET_ENTRIES" });1147    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };11481149    // If the service worker was killed and restarted (MV3 workers sleep), the1150    // vault will be locked again — or the worker may not respond at all.1151    // In either case, send the user to the lock screen rather than silently1152    // showing an empty vault (which looks like data loss).1153    if (!res.ok) {1154      if (1155        res.error === "vault_locked" ||1156        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1157        (typeof res.error === "string" && res.error.includes("locked"))1158      ) {1159        handleLock();1160        return null; // signal emergency lock to callers1161      }1162      return [];1163    }11641165    const loadedEntries = res.data ?? [];1166    setEntries(loadedEntries);11671168    const currentId = selectedEntry()?.id;1169    if (currentId) {1170      setSelectedEntry(1171        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1172      );1173    }11741175    return loadedEntries;1176  }11771178  async function openVault(preferredEntryId?: string, skipViewSet = false) {1179    // Purge expired trash entries on each vault open1180    const retDays = trashRetentionDays();1181    if (retDays > 0) {1182      void sendMessage({1183        type: "PURGE_EXPIRED_TRASH",1184        payload: { retentionMs: retDays * 86_400_000 },1185      });1186    }11871188    const loadedEntries = await loadEntries();11891190    // null means loadEntries() triggered an emergency lock (service worker died).1191    // Don't override it by setting view back to "entry" with an empty vault.1192    if (loadedEntries === null) return false;11931194    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1195    let nextSelectedEntry: VaultEntry | null = null;1196    if (preferredEntryId) {1197      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1198    }1199    if (!nextSelectedEntry) {1200      const tabDomain = currentTabDomain();1201      if (tabDomain) {1202        nextSelectedEntry = loadedEntries.find((e) => {1203          if (e.type === "login") {1204            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1205            for (const extra of e.additionalUrls ?? []) {1206              if ((extractDomain(extra) ?? "") === tabDomain) return true;1207            }1208            return false;1209          }1210          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1211          return false;1212        }) ?? null;1213      }1214    }1215    nextSelectedEntry ??= pickNavigable(loadedEntries);12161217    setSelectedEntry(nextSelectedEntry);1218    setEditEntry(undefined);1219    setContentTransitioning(false);1220    setContentPhase("enter");1221    queueContentIdle();1222    if (!skipViewSet) setView("entry");1223    return true;1224  }12251226  async function handleUnlock() {1227    // If the user previously created a vault but hadn't yet confirmed their1228    // recovery words (and the browser was closed before they could), the1229    // peach_recovery_pending flag is still set in storage.local. Re-route1230    // back to the recovery surface so they finish the confirmation step1231    // before reaching the entries view — the words can be re-derived now1232    // that the vault is unlocked again.1233    let recoveryPending = false;1234    try {1235      const out = await chrome.storage.local?.get("peach_recovery_pending");1236      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1237    } catch { /* best-effort */ }1238    if (recoveryPending) {1239      setForceRecoveryWords(true);1240      setView("lock");1241      triggerPipPulse();1242      await restoreSettings();1243      return;1244    }1245    setHasVault(true);1246    triggerPipPulse();1247    await restoreSettings();1248    const celebrating = pendingCelebration();1249    if (celebrating) {1250      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1251      setPendingCelebration(false);1252    }1253    await openVault(undefined, celebrating);1254    if (celebrating) {1255      setView("pro-celebration");1256      window.setTimeout(() => setView("entry"), 2500);1257    }1258    // Popup was opened from the inline "Open Peach to unlock" button — close it1259    // now so the user lands back on the page with the autofill selector ready.1260    if (openedForInlineUnlock) {1261      openedForInlineUnlock = false;1262      window.close();1263    }1264  }12651266  function handleSelectEntry(entry: VaultEntry) {1267    if (entry.type === "note") {1268      setOpenNoteId(entry.id);1269      setShowNotes(true);1270      return;1271    }1272    setSelectedEntry(entry);1273    setContentTransitioning(false);1274    setContentPhase("enter");1275    queueContentIdle();1276    setView("entry");1277  }12781279  function handleAdd() {1280    setEditEntry(undefined);1281    setView("add");1282  }12831284  async function handleDelete() {1285    const entry = selectedEntry();1286    if (!entry) return;1287    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1288    const loadedEntries = await loadEntries() ?? [];1289    setSelectedEntry(pickNavigable(loadedEntries));1290    setView("entry");1291  }12921293  async function handleDeleteMany(ids: string[]) {1294    for (const id of ids) {1295      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1296    }1297    const loadedEntries = await loadEntries() ?? [];1298    // If the currently selected entry was among the deleted, move to first1299    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1300    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1301  }13021303  async function handleSave(savedEntry?: VaultEntry) {1304    await openVault(savedEntry?.id);1305  }13061307  function handleBack() {1308    const dest = editBackView();1309    setEditBackView("entry");1310    setEditEntry(undefined);1311    setView(dest);1312  }13131314  function handleExportBack() {1315    if (returnToPanic()) {1316      setReturnToPanic(false);1317      setView("panic");1318      return;1319    }1320    setView("settings");1321  }13221323  function handleLock() {1324    clearCanarySuppressions();1325    setEntries([]);1326    setSelectedEntry(null);1327    setEditEntry(undefined);1328    setContentPhase("idle");1329    setView("lock");1330  }13311332  function handleHeaderLock() {1333    // Lock the UI immediately — do not wait for the service worker. If the SW1334    // is dead or slow, the 5s sendMessage timeout would create a dead-click1335    // window. The SW will lock on its next wake regardless.1336    handleLock();1337    void sendMessage({ type: "LOCK" });1338  }13391340  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1341  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1342  // the trigger's own reply.1343  async function handleHeaderSync(): Promise<void> {1344    if (syncBusy()) return;1345    setSyncBusy(true);1346    setSyncFlash(null);1347    try {1348      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1349      let state: SyncOutcomeSummary = { status: "syncing" };1350      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1351        await new Promise((r) => setTimeout(r, 250));1352        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1353          ok: boolean;1354          data?: SyncOutcomeSummary;1355        };1356        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1357      }1358      setSyncSummary(state);1359      setSyncFlash(state.status === "error" ? "error" : "ok");1360      await loadSyncAlerts();1361      await loadEntries();1362      await loadSyncIndicator();1363    } catch {1364      setSyncSummary({ status: "error", outcome: "run_failed" });1365      setSyncFlash("error");1366    } finally {1367      setSyncBusy(false);1368      setTimeout(() => setSyncFlash(null), 2_000);1369    }1370  }13711372  function navigate(dir: number) {1373    const navigable = nonNoteEntries();1374    if (navigable.length === 0) return;1375    const currentIndex = selectedIndex();1376    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1377    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1378    setSelectedEntry(navigable[nextIndex]);1379    setContentPhase("enter");1380    queueContentIdle();1381  }13821383  /**1384   * The Entry view's selection invariant: never select a note. Notes are a1385   * separate surface (handleSelectEntry opens the notes view), so any code path1386   * that picks a default — vault open, post-delete, refresh — must skip them1387   * and return null if the only entries are notes.1388   */1389  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1390    return list.find((e) => e.type !== "note") ?? null;1391  }13921393  function openList() {1394    setView("list");1395  }13961397  function openHealth() {1398    setEditEntry(undefined);1399    setView("health");1400  }14011402  function handleOpenFileImport() {1403    setRestoreView("file");1404  }14051406  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;14071408  function handleFixEntry(entry: VaultEntry) {1409    setSelectedEntry(entry);1410    // Passkey-only entries have no editable surface — drop into view mode1411    // instead of opening the Add editor.1412    if (isPasskeyOnly(entry)) {1413      setView("entry");1414      return;1415    }1416    setEditBackView(view()); // preserve caller view so back returns here1417    setEditEntry(entry);1418    setView("add");1419  }14201421  const isLockedView = () => view() === "lock" || view() === "adopting";14221423  async function handleAdoptionDone() {1424    await storageSet("peach_onboarded", "true").catch(() => {});1425    await storageRemove(ONBOARDING_CARD_STORAGE_KEY).catch(() => {});1426    setOnboarded(true);1427    setHasVault(true);1428    setView("initial-sync");1429    // The background applies a Pro license and persists the source-device1430    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1431    // celebration pending until that exact peer records a completed sync.1432    await refreshProStatus();1433    const deviceId = await resolveInitialSyncDeviceId();1434    if (deviceId) {1435      void beginInitialSyncWait(deviceId);1436    } else {1437      // Pairing completion without a durable peer row should be impossible.1438      // Stay on the honest waiting surface and expose retry instead of falling1439      // through to an empty vault.1440      setInitialSyncSlow(true);1441    }1442  }14431444  async function handleApprovePendingPasskey() {1445    const pending = pendingPasskey();1446    if (!pending) return;1447    if (pending.browser === "firefox" && pending.type === "create") {1448      // Firefox path: popup itself runs navigator.credentials.create. The1449      // background never approved/rejected anything — it just stashed1450      // intent. After the popup-driven flow resolves (success or cancel),1451      // clear the pending key so the popup doesn't re-show this on next open.1452      const { createFirefoxPasskey } = await import("./firefox-passkey");1453      const result = await createFirefoxPasskey(pending);1454      if (!result.ok) {1455        console.warn("Peach Firefox passkey create failed:", result.error);1456      }1457      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1458      setPendingPasskey(null);1459      void loadEntries();1460      window.close();1461      return;1462    }1463    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1464    window.close();1465  }14661467  async function handleDenyPendingPasskey() {1468    const pending = pendingPasskey();1469    if (!pending) return;1470    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1471    window.close();1472  }14731474  function queueContentIdle(after?: () => void) {1475    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1476    contentPhaseTimer = window.setTimeout(() => {1477      setContentPhase("idle");1478      after?.();1479    }, ENTRY_TRANSITION_SETTLE_MS);1480  }14811482  return (1483    <div class="popup-root peach-theme">1484      <Show when={bootState() === "ready"}>1485        <Show1486          when={!pendingPasskey()}1487          fallback={1488            <PasskeyApprovalView1489              type={pendingPasskey()!.type}1490              rpName={pendingPasskey()!.rpName}1491              rpId={pendingPasskey()!.rpId}1492              userName={pendingPasskey()!.userName}1493              userDisplayName={pendingPasskey()!.userDisplayName}1494              onApprove={handleApprovePendingPasskey}1495              onDeny={handleDenyPendingPasskey}1496            />1497          }1498        >1499          <Show1500            when={!isLockedView()}1501            fallback={1502              <Show1503                when={view() !== "adopting"}1504                fallback={1505                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1506                    <AdoptVaultView1507                      onCancel={() => {1508                        setOnboarded(false);1509                        setView("lock");1510                      }}1511                      onDone={handleAdoptionDone}1512                    />1513                  </Suspense>1514                }1515              >1516                <Show1517                  when={onboarded() || hasVault()}1518                  fallback={1519                    <Onboarding1520                      initialCard={onboardingCardAtExit()}1521                      onComplete={() => {1522                        setOnboardingCardAtExit(ONBOARDING_LAST_CARD);1523                        setStartOnboardingRestore(false);1524                        setOnboarded(true);1525                      }}1526                      onRestore={() => {1527                        setOnboardingCardAtExit(ONBOARDING_LAST_CARD);1528                        setStartOnboardingRestore(true);1529                        setOnboarded(true);1530                      }}1531                      onAdopt={() => {1532                        setOnboardingCardAtExit(ONBOARDING_LAST_CARD);1533                        setStartOnboardingRestore(false);1534                        setOnboarded(true);1535                        setView("adopting");1536                      }}1537                    />1538                  }1539                >1540                  <LockView1541                    hasVault={hasVault()}1542                    ready={bootState() === "ready"}1543                    isPro={proStatus()}1544                    forceRecoveryWords={forceRecoveryWords()}1545                    initialRestore={startOnboardingRestore()}1546                    onUnlock={() => {1547                      // RecoveryWordDisplay clears the storage flag before1548                      // calling onDone, so handleUnlock will see no pending1549                      // confirmation and proceed through the normal path.1550                      if (forceRecoveryWords()) setForceRecoveryWords(false);1551                      return handleUnlock();1552                    }}1553                    onBackToOnboarding={1554                      !hasVault()1555                        ? () => {1556                            setStartOnboardingRestore(false);1557                            setOnboarded(false);1558                          }1559                        : undefined1560                    }1561                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1562                  />1563                </Show>1564              </Show>1565            }1566          >1567            <Show1568              when={1569                view() !== "pro-celebration" &&1570                view() !== "initial-sync"1571              }1572              fallback={1573                <Show1574                  when={view() === "initial-sync"}1575                  fallback={<ProCelebration />}1576                >1577                  <InitialSyncView1578                    slow={initialSyncSlow()}1579                    onRetry={() => void retryInitialSync()}1580                  />1581                </Show>1582              }1583            >1584            <section1585              id="hd-shell"1586              class="peach-shell peach-theme"1587              data-surface="extension"1588            >1589            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1590              <PeachWordmark unlocked />1591              <div class="peach-chrome-actions">1592                <button1593                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1594                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1595                  aria-label="Notes"1596                  title="Notes"1597                >1598                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1599                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1600                    <line x1="4" y1="5" x2="10" y2="5" />1601                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1602                    <line x1="4" y1="10" x2="7" y2="10" />1603                  </svg>1604                </button>1605                <button1606                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1607                    classList={{1608                      "is-syncing": syncBusy(),1609                      "is-ok": syncFlash() === "ok",1610                      "is-error": syncFlash() === "error",1611                    }}1612                    onClick={() => void handleHeaderSync()}1613                    disabled={syncBusy()}1614                    aria-label={`Sync now. ${syncLabel()}`}1615                    title={syncLabel()}1616                  >1617                    <svg class="peach-sync-icon" width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1618                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1619                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1620                      <path d="M2.6 1v2.4h2.4" />1621                      <path d="M11.4 13v-2.4H9" />1622                    </svg>1623                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1624                  </button>1625                <button1626                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1627                  onClick={() => setView("settings")}1628                  aria-label="Settings"1629                >1630                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1631                    <path1632                      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"1633                      stroke="currentColor"1634                      stroke-width="0.9"1635                    />1636                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1637                  </svg>1638                </button>1639                <button1640                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1641                  onClick={handleAdd}1642                  aria-label="New entry"1643                >1644                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1645                    <path d="M5.5 1v9M1 5.5h9" />1646                  </svg>1647                </button>1648                <button1649                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1650                  onClick={() => void handleHeaderLock()}1651                  aria-label="Lock vault"1652                >1653                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1654                    <path1655                      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"1656                      stroke="currentColor"1657                      stroke-width="1"1658                      stroke-linecap="round"1659                    />1660                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1661                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1662                  </svg>1663                </button>1664              </div>1665            </header>16661667            <Show when={pendingProNotice() !== null}>1668              <div class="peach-pro-notice-banner">1669                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1670                <button1671                  class="peach-pro-notice-link"1672                  onClick={() => {1673                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1674                    setSettingsInitialSection("license");1675                    setView("settings");1676                    setPendingProNotice(null);1677                  }}1678                >1679                  Learn more →1680                </button>1681                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1682              </div>1683            </Show>16841685            <div class="peach-shell-body">1686              <div class="peach-shell-veil"></div>1687              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1688                <EntryView1689                  entry={selectedEntry()}1690                  currentTabUrl={currentTabUrl()}1691                  entries={entries()}1692                  isPro={proStatus()}1693                  onDelete={handleDelete}1694                  onFieldSaved={() => void loadEntries()}1695                  onEscape={() => { setView("list"); }}1696                  onProGate={(feature) => {1697                    setUpgradeHighlight(feature);1698                    setSettingsInitialSection("license");1699                    setView("settings");1700                  }}1701                />1702              </div>17031704              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1705                <div class="peach-search-bar">1706                  <span class="peach-search-icon">1707                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1708                      <circle cx="5.5" cy="5.5" r="3.75" />1709                      <path d="M8.75 8.75L11.5 11.5" />1710                    </svg>1711                  </span>1712                  <input1713                    class="peach-search-input"1714                    placeholder="search vault..."1715                    autocomplete="off"1716                    aria-label="Search vault entries"1717                    onClick={openList}1718                    onFocus={openList}1719                    readOnly1720                  />1721                  <div class="peach-search-meta">1722                    <span class="peach-search-counter">1723                      {nonNoteEntries().length > 01724                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1725                        : "0 entries"}1726                    </span>1727                    <span class="peach-divider"></span>1728                    <button1729                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1730                      onClick={() => navigate(-1)}1731                      aria-label="Previous entry"1732                      disabled={nonNoteEntries().length === 0}1733                    >1734                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1735                        <path d="M5 1L1 5.5L5 10" />1736                      </svg>1737                    </button>1738                    <button1739                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1740                      onClick={() => navigate(1)}1741                      aria-label="Next entry"1742                      disabled={nonNoteEntries().length === 0}1743                    >1744                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1745                        <path d="M1 1L5 5.5L1 10" />1746                      </svg>1747                    </button>1748                  </div>1749                </div>1750              </section>1751            </div>17521753            {/* Desktop: shown on demand via Show. Native sheet is rendered1754                via Portal below at the document root so its position:fixed1755                isn't trapped by .peach-shell's transform-based animations. */}1756            {/* Rare device-trust alerts; normal sync changes are silent. */}1757            <Show when={alertGroups().length > 0}>1758              <div class="peach-sync-alerts">1759                <For each={alertGroups()}>1760                  {([type, group]) => {1761                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1762                    return (1763                      <div class="peach-sync-alert">1764                        <Show when={group.length > 1}>1765                          <button1766                            class="peach-sync-alert-flip"1767                            type="button"1768                            aria-label="Previous"1769                            onClick={() => flipAlert(type, -1)}1770                          >‹</button>1771                        </Show>1772                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1773                        <Show when={group.length > 1}>1774                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1775                          <button1776                            class="peach-sync-alert-flip"1777                            type="button"1778                            aria-label="Next"1779                            onClick={() => flipAlert(type, 1)}1780                          >›</button>1781                        </Show>1782                        <button1783                          class="peach-sync-alert-dismiss"1784                          type="button"1785                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1786                          onClick={() => dismissAlertGroup(type)}1787                        >×</button>1788                      </div>1789                    );1790                  }}1791                </For>1792              </div>1793            </Show>17941795            <Show when={!isNativePlatform() && view() === "list"}>1796              <VaultView1797                entries={entries()}1798                selectedEntryId={selectedEntry()?.id}1799                currentTabDomain={currentTabDomain()}1800                sortOrder={sortOrder()}1801                searchSeed={listSearchSeed()}1802                searchSeedNonce={listSearchSeedNonce()}1803                onSelectEntry={handleSelectEntry}1804                onSortOrderChange={setSortOrder}1805                onAdd={handleAdd}1806                onClose={() => setView("entry")}1807                onOpenTrash={() => setView("trash")}1808                onDeleteMany={handleDeleteMany}1809              />1810            </Show>1811            <Show when={isNativePlatform() && hasVault()}>1812              <Portal>1813                <div1814                  class="peach-vault-sheet"1815                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1816                  style={(() => {1817                    const live = sheetTranslate();1818                    if (live === null) return undefined;1819                    return { transform: `translateY(${live}px)` };1820                  })()}1821                >1822                  <VaultView1823                    entries={entries()}1824                    selectedEntryId={selectedEntry()?.id}1825                    currentTabDomain={currentTabDomain()}1826                    sortOrder={sortOrder()}1827                    searchSeed={listSearchSeed()}1828                    searchSeedNonce={listSearchSeedNonce()}1829                    isNative={true}1830                    onSelectEntry={handleSelectEntry}1831                    onSortOrderChange={setSortOrder}1832                    onAdd={handleAdd}1833                    onClose={() => setView("entry")}1834                    onOpenTrash={() => setView("trash")}1835                    onDeleteMany={handleDeleteMany}1836                  />1837                </div>1838              </Portal>1839            </Show>1840            <Show when={view() === "settings" || settingsExiting()}>1841              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1842                <SettingsView1843                  entriesCount={entries().length}1844                  breachMonitoring={breachMonitoring()}1845                  lockOnClose={lockOnClose()}1846                  autoLockMinutes={autoLockMinutes()}1847                  trashRetentionDays={trashRetentionDays()}1848                  theme={theme()}1849                  accentColor={accentColor()}1850                  textSize={textSize()}1851                  reduceMotion={reduceMotion()}1852                  isPro={proStatus()}1853                  initialSection={settingsInitialSection()}1854                  upgradeHighlight={upgradeHighlight()}1855                  isExiting={settingsExiting()}1856                  onBreachMonitoringChange={applyBreachMonitoring}1857                  onLockOnCloseChange={applyLockOnClose}1858                  onAutoLockMinutesChange={applyAutoLockMinutes}1859                  onTrashRetentionChange={applyTrashRetention}1860                  onThemeChange={applyTheme}1861                  onAccentChange={applyAccentColor}1862                  onTextSizeChange={applyTextSize}1863                  onReduceMotionChange={applyReduceMotion}1864                  shortcuts={shortcutBindings()}1865                  onShortcutsChange={applyShortcuts}1866                  onLicenseChange={async () => {1867                    // After activation/deactivation: refresh Pro status,1868                    // re-load entries (defensive — signal state can drift if1869                    // the SW briefly restarts during the verify+save round-trip),1870                    // and replay the Pro celebration if this is the first time1871                    // a valid Pro license is seen on this device.1872                    await refreshProStatus();1873                    void loadEntries();1874                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1875                    if ((should as { ok: boolean; data?: boolean }).data === true) {1876                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1877                      setView("pro-celebration");1878                      window.setTimeout(() => setView("settings"), 2500);1879                    }1880                  }}1881                  onBack={() => {1882                    setSettingsExiting(true);1883                    window.setTimeout(() => {1884                      setSettingsExiting(false);1885                      setSettingsInitialSection(null);1886                      setUpgradeHighlight(null);1887                      handleBack();1888                    }, 200);1889                  }}1890                  onImport={() => setView("import")}1891                  onExport={() => setView("export")}1892                  onBreachCheckDone={loadEntries}1893                  onOpenHealth={openHealth}1894                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1895                  onOpenFileImport={handleOpenFileImport}1896                  onOpenPanic={() => setView("panic")}1897                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1898                  onOpenCodexRestore={() => setView("codex-restore")}1899                  onCardChange={setSettingsActiveCard}1900                  onProGate={(feature) => {1901                    setUpgradeHighlight(feature);1902                    setSettingsInitialSection("license");1903                  }}1904                />1905              </Suspense>1906            </Show>1907            <Show when={view() === "codex-generate"}>1908              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1909                <CodexGenerateView1910                  isPro={proStatus()}1911                  onBack={() => setView("settings")}1912                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1913                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1914                  onVaultLocked={() => handleLock()}1915                />1916              </Suspense>1917            </Show>1918            <Show when={view() === "codex-restore"}>1919              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1920                <CodexRestoreView1921                  onBack={() => setView("lock")}1922                  onRestoreSuccess={async () => {1923                    // After restore the vault is unlocked; refresh entries1924                    // and route to the main vault list. handleUnlock is the1925                    // canonical post-unlock setup path.1926                    await handleUnlock();1927                  }}1928                />1929              </Suspense>1930            </Show>1931            <Show when={view() === "pair-device"}>1932              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1933                <PairDeviceView1934                  isPro={proStatus()}1935                  onProChanged={() => { void refreshProStatus(); }}1936                  onBack={() => setView("settings")}1937                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1938                />1939              </Suspense>1940            </Show>1941            <Show when={view() === "add"}>1942              <AddView1943                entry={editEntry()}1944                entries={entries()}1945                onBack={handleBack}1946                onSave={handleSave}1947              />1948            </Show>1949            <Show when={view() === "import"}>1950              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1951                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1952              </Suspense>1953            </Show>1954            <Show when={view() === "export"}>1955              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1956                <ExportView onBack={handleExportBack} />1957              </Suspense>1958            </Show>1959            <Show when={view() === "panic"}>1960              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1961                <PanicView1962                  onCancel={() => setView("settings")}1963                  onOpenExport={() => {1964                    setReturnToPanic(true);1965                    setView("export");1966                  }}1967                  onDestroyed={async () => {1968                    clearCanarySuppressions();1969                    setEntries([]);1970                    setSelectedEntry(null);1971                    setEditEntry(undefined);1972                    setHasVault(false);1973                    setOnboarded(false);1974                    setProStatus(false);1975                    setPendingPasskey(null);1976                    setUpgradeHighlight(null);1977                    setSettingsInitialSection(null);1978                    setPendingProNotice(null);1979                    setPendingCelebration(false);1980                    setReturnToPanic(false);1981                    setContentPhase("idle");1982                    setView("lock");1983                  }}1984                />1985              </Suspense>1986            </Show>1987            {/* Health stays mounted while editing an entry from it so1988                computeReused() doesn't rerun on every cancel/back. */}1989            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1990              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1991                <HealthView1992                  entries={entries()}1993                  isPro={proStatus()}1994                  onFixEntry={handleFixEntry}1995                  onBack={() => setView("settings")}1996                  onRefresh={loadEntries}1997                  hidden={view() !== "health"}1998                />1999              </Suspense>2000            </Show>2001            <Show when={view() === "trash"}>2002              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2003                <TrashView2004                  onBack={() => setView("list")}2005                  onRestored={() => void loadEntries()}2006                />2007              </Suspense>2008            </Show>2009            <Show when={showNotes()}>2010              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>2011                <NotesMode2012                  notes={entries().filter((e) => e.type === "note")}2013                  initialNoteId={openNoteId()}2014                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}2015                  onNoteListChanged={() => void loadEntries()}2016                />2017              </div>2018            </Show>2019            <Show when={restoreView() === "file"}>2020              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>2021                <ImportView2022                  mode="onboarding"2023                  replacesExistingVault={true}2024                  onBack={() => setRestoreView(null)}2025                  onImport={async () => {2026                    setRestoreView(null);2027                    await handleUnlock();2028                  }}2029                />2030              </Suspense>2031            </Show>2032            </section>2033            </Show>2034          </Show>2035        </Show>2036      </Show>2037      <Show when={showShortcutsHelp()}>2038        <ShortcutsHelpOverlay2039          bindings={shortcutBindings()}2040          onClose={() => setShowShortcutsHelp(false)}2041        />2042      </Show>2043    </div>2044  );2045}20462047function ShortcutsHelpOverlay(props: {2048  bindings: Record<ShortcutAction, Keybinding>;2049  onClose: () => void;2050}) {2051  return (2052    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>2053      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>2054        <div class="peach-shortcuts-help-head">2055          <h3>Keyboard shortcuts</h3>2056          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>2057        </div>2058        <div class="peach-shortcuts-help-body">2059          <p class="peach-settings-sub-label">ENTRY VIEW</p>2060          <ul>2061            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (2062              <li>2063                <span>{d.label}</span>2064                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2065              </li>2066            ))}2067          </ul>2068          <p class="peach-settings-sub-label">ANYWHERE</p>2069          <ul>2070            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (2071              <li>2072                <span>{d.label}</span>2073                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2074              </li>2075            ))}2076          </ul>2077        </div>2078      </div>2079    </div>2080  );2081}