App.tsx

84.5 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 { Onboarding } from "./views/Onboarding";15import { NotesMode } from "./views/NotesMode";16import { ProCelebration } from "./views/ProCelebration";17import { InitialSyncView } from "./views/InitialSyncView";18import { VaultView, type SortOrder } from "./views/Vault";19import { EntryView } from "./views/Entry";20import { AddView } from "./views/Add";21import { PeachWordmark } from "./components/PeachMark";22import { PasskeyApprovalView } from "./views/PasskeyApproval";23import { extractDomain } from "../shared/domain";24import {25  syncIndicator,26  syncIndicatorLabel,27  type SyncOutcomeSummary,28} from "../shared/sync-outcome";29import { popupCopy } from "./copy";30import {31  DEFAULT_BINDINGS,32  formatKeybinding,33  getActiveBindings,34  matchKeybinding,35  SHORTCUT_DESCRIPTORS,36  type Keybinding,37  type ShortcutAction,38} from "../shared/shortcuts";39import { generateTOTP } from "../crypto/totp";40import { isNativePlatform, nativePlugin } from "../shared/native";4142export { sendMessage } from "../shared/bridge";4344const ImportView    = lazy(() => import("./views/Import").then(m => ({ default: m.ImportView })));45const ExportView    = lazy(() => import("./views/Export").then(m => ({ default: m.ExportView })));46const SettingsView  = lazy(() => import("./views/Settings").then(m => ({ default: m.SettingsView })));47const HealthView    = lazy(() => import("./views/Health").then(m => ({ default: m.HealthView })));48const TrashView     = lazy(() => import("./views/TrashView").then(m => ({ default: m.TrashView })));49const PanicView     = lazy(() => import("./views/Panic").then(m => ({ default: m.PanicView })));50const PairDeviceView   = lazy(() => import("./views/PairDevice").then(m => ({ default: m.PairDeviceView })));51const CodexGenerateView = lazy(() => import("./views/CodexGenerateView").then(m => ({ default: m.CodexGenerateView })));52const CodexRestoreView  = lazy(() => import("./views/CodexRestoreView").then(m => ({ default: m.CodexRestoreView })));53const AdoptVaultView = lazy(() => import("./views/AdoptVaultView").then(m => ({ default: m.AdoptVaultView })));5455type View =56  | "lock"57  | "pro-celebration"58  | "entry"59  | "list"60  | "add"61  | "settings"62  | "pair-device"63  | "import"64  | "export"65  | "health"66  | "trash"67  | "panic"68  | "adopting"69  | "initial-sync"70  | "codex-generate"71  | "codex-restore";72type BootState = "loading" | "ready";7374const INITIAL_SYNC_POLL_MS = 500;75const INITIAL_SYNC_SLOW_MS = 15_000;7677const canarySuppressMap = new Map<string, boolean>();78let shellRingAnimation: Animation | null = null;7980export function isCanarySuppressed(entryId: string): boolean {81  return canarySuppressMap.get(entryId) ?? false;82}8384export function setCanarySuppressed(entryId: string, suppressed: boolean): void {85  canarySuppressMap.set(entryId, suppressed);86}8788export function clearCanarySuppressions(): void {89  canarySuppressMap.clear();90}9192export function triggerRing() {93  const shell = document.getElementById("hd-shell");94  if (!shell) return;9596  shellRingAnimation?.cancel();97  shell.dataset.glowing = "true";98  const animation = shell.animate(99    [100      { offset: 0, boxShadow: "var(--copy-shadow)" },101      {102        offset: 0.3,103        boxShadow:104          "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)",105      },106      { offset: 1, boxShadow: "var(--copy-shadow)" },107    ],108    {109      duration: 720,110      easing: "cubic-bezier(0.4, 0, 0.2, 1)",111      fill: "none",112    }113  );114  shellRingAnimation = animation;115  const clearGlow = () => {116    if (shellRingAnimation !== animation) return;117    shellRingAnimation = null;118    delete shell.dataset.glowing;119  };120  animation.onfinish = clearGlow;121  animation.oncancel = clearGlow;122}123124125export function triggerPipPulse() {126  const pip = document.querySelector(".peach-status-pip, .pip");127  if (pip) {128    pip.classList.remove("pulse");129    void (pip as HTMLElement).offsetWidth;130    pip.classList.add("pulse");131  }132}133134const ENTRY_TRANSITION_SETTLE_MS = 135;135136export default function App() {137  const [bootState, setBootState] = createSignal<BootState>("loading");138  const [view, setView] = createSignal<View>("lock");139  // Mobile bottom-sheet live drag offset in px (null = not actively dragging,140  // CSS transition takes over for snap animation).141  const [sheetTranslate, setSheetTranslate] = createSignal<number | null>(null);142  const [contentPhase, setContentPhase] = createSignal<"enter" | "exit" | "idle">(143    "enter"144  );145  const [contentTransitioning, setContentTransitioning] = createSignal(false);146  const [hasVault, setHasVault] = createSignal(false);147  const [onboarded, setOnboarded] = createSignal(true);148  const [startOnboardingRestore, setStartOnboardingRestore] = createSignal(false);149  const [entries, setEntries] = createSignal<VaultEntry[]>([]);150  const [selectedEntry, setSelectedEntry] = createSignal<VaultEntry | null>(null);151  const [editEntry, setEditEntry] = createSignal<VaultEntry | undefined>(undefined);152153  // Rare device-trust alerts stay visible; routine entry sync is silent.154  interface SyncAlert {155    type: "DEVICE_KEY_ROTATED" | "DEVICE_REVOKED";156    entryId: string;157    entryTitle: string;158    deviceName: string;159    timestamp: number;160  }161  const [syncAlerts, setSyncAlerts] = createSignal<SyncAlert[]>([]);162  // Per-group flip index: which alert within a type-group is currently shown.163  const [alertFlipIdx, setAlertFlipIdx] = createSignal<Record<string, number>>({});164  async function loadSyncAlerts() {165    const r = (await sendMessage({ type: "GET_SYNC_ALERTS" })) as {166      ok: boolean;167      data?: SyncAlert[];168    };169    if (r.ok && (r.data?.length ?? 0) > 0) {170      setSyncAlerts(r.data ?? []);171      // Acknowledge so a crash between read and render doesn't lose them —172      // they remain on screen until the user dismisses each.173      void sendMessage({ type: "GET_SYNC_ALERTS", payload: { consume: true } });174    }175  }176  function dismissAlertGroup(type: string) {177    setSyncAlerts((arr) => arr.filter((a) => a.type !== type));178    setAlertFlipIdx((m) => { const n = { ...m }; delete n[type]; return n; });179  }180  function flipAlert(type: string, dir: 1 | -1) {181    const group = syncAlerts().filter((a) => a.type === type);182    if (group.length <= 1) return;183    setAlertFlipIdx((m) => {184      const cur = m[type] ?? 0;185      return { ...m, [type]: (cur + dir + group.length) % group.length };186    });187  }188  /** Grouped alert types in display order, each with its alerts. */189  const alertGroups = createMemo(() => {190    const map = new Map<string, SyncAlert[]>();191    for (const a of syncAlerts()) {192      const g = map.get(a.type);193      if (g) g.push(a); else map.set(a.type, [a]);194    }195    return [...map.entries()];196  });197  function syncAlertText(a: SyncAlert): string {198    if (a.type === "DEVICE_REVOKED") {199      return `${a.deviceName} revoked a paired device — review your devices in Settings`;200    }201    return `${a.deviceName}'s sync key changed — if you didn't reinstall Peach on that device, rotate your sync identity`;202  }203  const [accentColor, setAccentColor] = createSignal<AccentColorName>("peach");204  const [theme, setTheme] = createSignal<"dark" | "light">("dark");205  const [textSize, setTextSize] = createSignal<"small" | "medium" | "large">("medium");206  const [reduceMotion, setReduceMotion] = createSignal<boolean>(false);207  const [lockOnClose, setLockOnClose] = createSignal(false);208  const [autoLockMinutes, setAutoLockMinutes] = createSignal(5);209  const [breachMonitoring, setBreachMonitoring] = createSignal(true);210  const [shortcutBindings, setShortcutBindings] = createSignal<Record<ShortcutAction, Keybinding>>(DEFAULT_BINDINGS);211  const [showShortcutsHelp, setShowShortcutsHelp] = createSignal(false);212  const [trashRetentionDays, setTrashRetentionDays] = createSignal(30);213  const [restoreView, setRestoreView] = createSignal<"file" | null>(null);214  const [pendingPasskey, setPendingPasskey] = createSignal<PendingPasskeyRequest | null>(null);215  const [currentTabDomain, setCurrentTabDomain] = createSignal<string>("");216  const [currentTabUrl, setCurrentTabUrl] = createSignal<string>("");217  // Cached Pro status — synchronous for render paths. Background's218  // GET_LICENSE is async, but render-time reads of isPro() must not block.219  // Refreshed at boot, after activate/deactivate, and whenever the popup220  // re-opens onto a stored license that has changed via another window.221  const [proStatus, setProStatus] = createSignal(false);222  const [settingsInitialSection, setSettingsInitialSection] = createSignal<string | null>(null);223  // When the sync card's pairing button opens the pairing view, deep-link224  // straight into that pairing path instead of the rest screen.225  const [settingsActiveCard, setSettingsActiveCard] = createSignal<string>("protection");226  const [upgradeHighlight, setUpgradeHighlight] = createSignal<ProFeature | null>(null);227  const [sortOrder, setSortOrder] = createSignal<SortOrder>("url-first");228  const [listSearchSeed, setListSearchSeed] = createSignal("");229  const [listSearchSeedNonce, setListSearchSeedNonce] = createSignal(0);230  const [pendingCelebration, setPendingCelebration] = createSignal(false);231  const [pendingProNotice, setPendingProNotice] = createSignal<{ feature: string } | null>(null);232  // True while Panic Step 1 has bounced the user out to Export. When Export's233  // onBack fires we return to Panic instead of Settings so the user keeps the234  // destruction context they came from.235  const [returnToPanic, setReturnToPanic] = createSignal(false);236  // The view to return to when the add/edit view is dismissed. Normally "entry"237  // but "health" when the user arrives via the fix-entry path from Vault Health.238  const [editBackView, setEditBackView] = createSignal<View>("entry");239  const [settingsExiting, setSettingsExiting] = createSignal(false);240  const [showNotes, setShowNotes] = createSignal(false);241  // Topbar sync affordance. Always present: gating it on having a paired device242  // meant it never appeared for the person trying to set pairing up, which is243  // exactly when you reach for it.244  const [syncBusy, setSyncBusy] = createSignal(false);245  const [syncFlash, setSyncFlash] = createSignal<"ok" | "error" | null>(null);246  // The indicator light + its spoken-word equivalent. Colour alone is not the247  // signal; the title/aria-label always carries the same claim in English.248  const [syncSummary, setSyncSummary] = createSignal<SyncOutcomeSummary>({});249  const [pairedCount, setPairedCount] = createSignal(0);250  const [initialSyncDeviceId, setInitialSyncDeviceId] = createSignal<string | null>(null);251  const [initialSyncSlow, setInitialSyncSlow] = createSignal(false);252  let initialSyncWaitGeneration = 0;253  const syncLight = () =>254    syncBusy() ? "busy" : syncIndicator(syncSummary(), pairedCount());255  const syncLabel = () => syncIndicatorLabel(syncLight(), syncSummary());256  async function loadSyncIndicator() {257    const [stateRes, devicesRes] = await Promise.all([258      sendMessage({ type: "GET_SYNC_STATE" }),259      sendMessage({ type: "LIST_PAIRED_DEVICES" }),260    ]);261    const s = stateRes as { ok: boolean; data?: SyncOutcomeSummary };262    if (s.ok && s.data) setSyncSummary(s.data);263    const d = devicesRes as { ok: boolean; data?: { devices?: unknown[] } };264    if (d.ok) setPairedCount(d.data?.devices?.length ?? 0);265  }266267  interface InitialSyncPairedDevice extends InitialSyncDevice {268    pairedAt?: number;269  }270271  async function listInitialSyncDevices(): Promise<InitialSyncPairedDevice[]> {272    const response = (await sendMessage({273      type: "LIST_PAIRED_DEVICES",274    })) as {275      ok: boolean;276      data?: { devices?: InitialSyncPairedDevice[] };277    };278    return response.ok ? response.data?.devices ?? [] : [];279  }280281  async function resolveInitialSyncDeviceId(): Promise<string | null> {282    const stored = await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(283      () => null,284    );285    const devices = await listInitialSyncDevices().catch(() => []);286    if (stored && devices.some((device) => device.deviceId === stored)) {287      return stored;288    }289290    // Fresh adoption has exactly one direct source, but choosing the newest row291    // also repairs the marker if storage failed after the pair itself committed.292    const newest = [...devices].sort(293      (a, b) => (b.pairedAt ?? 0) - (a.pairedAt ?? 0),294    )[0];295    if (!newest) return stored;296    await storageSet(INITIAL_SYNC_PENDING_DEVICE_KEY, newest.deviceId).catch(297      () => undefined,298    );299    return newest.deviceId;300  }301302  async function finishInitialSync(generation: number): Promise<void> {303    if (generation !== initialSyncWaitGeneration) return;304    await storageRemove(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => undefined);305    setInitialSyncDeviceId(null);306    setInitialSyncSlow(false);307    await refreshProStatus();308309    // A license transferred during pairing intentionally leaves the one-shot310    // celebration pending. Consume it only now: sync readiness → celebration311    // → populated vault, never celebration → temporarily empty vault.312    const celebration = (await sendMessage({313      type: "SHOULD_PLAY_CELEBRATION",314    })) as { ok: boolean; data?: boolean };315    const shouldCelebrate = celebration.ok && celebration.data === true;316    if (shouldCelebrate) {317      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });318    }319320    const opened = await openVault(undefined, shouldCelebrate);321    if (!opened || generation !== initialSyncWaitGeneration) return;322    if (shouldCelebrate) {323      setView("pro-celebration");324      window.setTimeout(() => {325        if (generation === initialSyncWaitGeneration) setView("entry");326      }, 2500);327    }328  }329330  async function beginInitialSyncWait(deviceId: string): Promise<void> {331    const generation = ++initialSyncWaitGeneration;332    setInitialSyncDeviceId(deviceId);333    setInitialSyncSlow(false);334    setView("initial-sync");335    const startedAt = Date.now();336337    // Best effort: the pairing write already wakes the mesh listener, while338    // this trigger covers the key-order case where this receiver is the dialer.339    void sendMessage({340      type: "TRIGGER_SYNC",341      payload: { reason: "foreground" },342    }).catch(() => undefined);343344    while (345      generation === initialSyncWaitGeneration &&346      view() === "initial-sync"347    ) {348      try {349        const devices = await listInitialSyncDevices();350        if (hasCompletedInitialSync(devices, deviceId)) {351          await finishInitialSync(generation);352          return;353        }354      } catch {355        // A sleeping MV3 worker may miss one poll. The next poll wakes it again.356      }357      if (Date.now() - startedAt >= INITIAL_SYNC_SLOW_MS) {358        setInitialSyncSlow(true);359      }360      await new Promise((resolve) =>361        window.setTimeout(resolve, INITIAL_SYNC_POLL_MS),362      );363    }364  }365366  async function retryInitialSync(): Promise<void> {367    const deviceId =368      initialSyncDeviceId() ?? (await resolveInitialSyncDeviceId());369    if (deviceId) {370      await beginInitialSyncWait(deviceId);371    } else {372      setInitialSyncSlow(true);373    }374  }375376  const [openNoteId, setOpenNoteId] = createSignal<string | undefined>(undefined);377  // Set on popup boot when peach_recovery_pending flag is found in session378  // storage — instructs LockView to skip the unlock UI and open the recovery379  // words confirmation surface instead. Cleared via handleUnlock once the380  // user has typed the 3 confirmation words.381  const [forceRecoveryWords, setForceRecoveryWords] = createSignal(false);382383  let contentPhaseTimer: number | undefined;384  // Set when the popup was opened from the inline "Open Peach to unlock" button.385  // handleUnlock() closes the popup after unlock so the user returns to the page.386  let openedForInlineUnlock = false;387388  onCleanup(() => {389    initialSyncWaitGeneration += 1;390  });391392  function applyAccent(name: AccentColorName) {393    const color = ACCENT_COLORS.find(c => c.name === name) ?? ACCENT_COLORS[0]!;394    const hex = color.hex;395    document.documentElement.style.setProperty("--peach-accent", hex);396    // Ambient surface variables — derived from the accent so surfaces shift397    // subtly toward the accent hue rather than staying fixed warm-brown.398    document.documentElement.style.setProperty("--peach-glow", hex + "2A");399    document.documentElement.style.setProperty("--peach-surface-tint", hex + "09");400    document.documentElement.style.setProperty("--peach-border-accent", hex + "24");401  }402403  createEffect(() => {404    applyAccent(accentColor());405  });406407  createEffect(() => {408    document.documentElement.classList.toggle("light", theme() === "light");409    document.body.classList.toggle("light", theme() === "light");410  });411412  createEffect(() => {413    document.documentElement.setAttribute("data-text-size", textSize());414  });415416  createEffect(() => {417    if (reduceMotion()) {418      document.documentElement.setAttribute("data-motion", "reduce");419    } else {420      document.documentElement.removeAttribute("data-motion");421    }422  });423424  // Notes are not a destination of the Entry view; selecting a note opens the425  // notes surface instead (handleSelectEntry). Anything that walks or counts426  // the Entry view's neighbours (counter, prev/next, index) must use this427  // filtered list, otherwise the user can arrow into a note and is stuck —428  // the Entry view can't render a note and the prev/next buttons stop moving.429  const nonNoteEntries = createMemo(() => entries().filter((e) => e.type !== "note"));430431  const selectedIndex = createMemo(() => {432    const currentId = selectedEntry()?.id;433    if (!currentId) return nonNoteEntries().length > 0 ? 0 : -1;434    return nonNoteEntries().findIndex((entry) => entry.id === currentId);435  });436437  async function applyAccentColor(name: AccentColorName) {438    applyAccent(name);439    setAccentColor(name);440    await sendMessage({ type: "UPDATE_SETTINGS", payload: { accentColor: name } });441  }442443  async function applyTheme(t: "dark" | "light") {444    setTheme(t);445    await sendMessage({ type: "UPDATE_SETTINGS", payload: { theme: t } });446  }447448  async function applyTextSize(size: "small" | "medium" | "large") {449    setTextSize(size);450    await sendMessage({ type: "UPDATE_SETTINGS", payload: { textSize: size } });451  }452453  async function applyReduceMotion(enabled: boolean) {454    setReduceMotion(enabled);455    await sendMessage({ type: "UPDATE_SETTINGS", payload: { reduceMotion: enabled } });456  }457458  // Persist only the deltas vs DEFAULT_BINDINGS — keeps the vault payload459  // small and lets future default updates land for actions the user hasn't460  // touched. Settings sends us the full active map; we filter and store.461  async function applyShortcuts(active: Record<ShortcutAction, Keybinding>) {462    setShortcutBindings(active);463    const overrides: Record<string, Keybinding> = {};464    for (const action of Object.keys(active) as ShortcutAction[]) {465      const a = active[action];466      const d = DEFAULT_BINDINGS[action];467      const same = a.key === d.key468        && Boolean(a.ctrl)  === Boolean(d.ctrl)469        && Boolean(a.meta)  === Boolean(d.meta)470        && Boolean(a.shift) === Boolean(d.shift)471        && Boolean(a.alt)   === Boolean(d.alt);472      if (!same) overrides[action] = a;473    }474    await sendMessage({ type: "UPDATE_SETTINGS", payload: { shortcuts: overrides } });475  }476477  async function applyLockOnClose(enabled: boolean) {478    setLockOnClose(enabled);479    await sendMessage({480      type: "UPDATE_SETTINGS",481      payload: { lockOnClose: enabled },482    });483  }484485  async function applyAutoLockMinutes(minutes: number) {486    setAutoLockMinutes(minutes);487    await sendMessage({488      type: "UPDATE_SETTINGS",489      payload: { autoLockMinutes: minutes },490    });491  }492493  async function applyBreachMonitoring(enabled: boolean) {494    setBreachMonitoring(enabled);495    await sendMessage({496      type: "UPDATE_SETTINGS",497      payload: { breachMonitoring: enabled },498    });499  }500501  onMount(async () => {502    // Resolve the active tab in parallel with the unlock/has-vault queries —503    // openVault()'s smart selection picks the entry matching currentTabDomain,504    // so it must be populated before openVault runs. Previously refreshCurrentTab505    // ran after openVault, leaving popups that booted already-unlocked falling506    // back to loadedEntries[0] instead of the domain match.507    const [unlockResponse, vaultResponse, , celebrationResponse] = await Promise.all([508      sendMessage({ type: "IS_UNLOCKED" }),509      sendMessage({ type: "HAS_VAULT" }),510      refreshCurrentTab(),511      sendMessage({ type: "SHOULD_PLAY_CELEBRATION" }),512    ]);513    const unlocked = Boolean(514      (unlockResponse as { ok: boolean; data?: boolean }).data515    );516    const vaultExists = Boolean(517      (vaultResponse as { ok: boolean; data?: boolean }).data518    );519    const shouldCelebrate = Boolean(520      (celebrationResponse as { ok: boolean; data?: boolean }).data521    );522    setHasVault(vaultExists);523    // Onboarding gate — show once on first install, never again. Existing524    // users (vaultExists) are auto-marked onboarded so they skip the flow525    // even on the very first popup open after this feature ships.526    try {527      const onboarded = await storageGet("peach_onboarded");528      const seen = onboarded === "true";529      if (vaultExists && !seen) {530        await storageSet("peach_onboarded", "true");531        setOnboarded(true);532      } else {533        setOnboarded(seen);534      }535    } catch {536      // storage unavailable — default to onboarded so we never block boot537      setOnboarded(true);538    }539    await Promise.all([restoreSettings(), refreshProStatus()]);540541    const pendingInitialSyncMarker =542      unlocked && vaultExists543        ? await storageGet(INITIAL_SYNC_PENDING_DEVICE_KEY).catch(() => null)544        : null;545    const pendingInitialSyncDeviceId = pendingInitialSyncMarker546      ? await resolveInitialSyncDeviceId()547      : null;548549    // Mark played before any animation so a crash mid-sequence never replays550    // it. A newly adopted receiver deliberately defers this until its first551    // real sync finishes, preserving initial sync → celebration → vault.552    if (shouldCelebrate && !pendingInitialSyncDeviceId) {553      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });554    }555556    // Popup-foreground sync trigger (SEV-1-A). Fire-and-forget — the outcome557    // arrives on the SYNC_STATE_CHANGED broadcast the indicator listens to.558    if (unlocked && vaultExists) {559      void sendMessage({560        type: "TRIGGER_SYNC",561        payload: { reason: "foreground" },562      });563      void loadSyncIndicator();564      // Rare device-trust alerts only; routine entry sync stays quiet.565      void loadSyncAlerts();566    }567568    // If the user created a vault but hasn't yet confirmed their recovery569    // words, route back to the recovery-words screen instead of opening the570    // entries view. The flag lives in chrome.storage.local so it survives571    // both popup close (SW suppresses lock-on-close) and full browser572    // restart (handleUnlock checks the same flag after a fresh password573    // unlock). Cleared when confirmation succeeds.574    let recoveryPending = false;575    try {576      const out = await chrome.storage.local?.get("peach_recovery_pending");577      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";578    } catch { /* best-effort */ }579580    // If this popup was opened from the inline "Open Peach to unlock" button,581    // the background set a session flag. Read and clear it so handleUnlock()582    // can close the popup after unlock and return the user to the page.583    if (chrome.storage.session) {584      try {585        const s = await chrome.storage.session.get("peach_inline_unlock");586        if ((s as { peach_inline_unlock?: boolean }).peach_inline_unlock) {587          openedForInlineUnlock = true;588          await chrome.storage.session.remove("peach_inline_unlock");589        }590      } catch { /* best-effort */ }591    }592593    // Native: closing the app before recovery-words confirmation means the594    // user didn't finish vault creation. Throw the partial vault away and595    // restart onboarding rather than asking them to unlock a vault they596    // never finished creating. Desktop keeps the existing "unlock to597    // resume" flow because closing the popup there is much more casual.598    if (recoveryPending && !unlocked && vaultExists && isNativePlatform()) {599      try {600        await chrome.storage.local?.remove([601          "peach_vault_a",602          "peach_vault_b",603          "peach_recovery_pending",604          "peach_onboarded",605          "peach_vault_history",606        ]);607      } catch { /* best-effort */ }608      setHasVault(false);609      setOnboarded(false);610      setView("lock");611      setBootState("ready");612      return;613    }614615    if (recoveryPending && unlocked) {616      // forceRecoveryWords overrides LockView's hasVault gate so the617      // recovery surface renders even though the vault now exists.618      setForceRecoveryWords(true);619      setView("lock");620    } else if (unlocked && vaultExists && pendingInitialSyncDeviceId) {621      void beginInitialSyncWait(pendingInitialSyncDeviceId);622    } else if (unlocked && vaultExists) {623      await openVault(undefined, shouldCelebrate);624      if (shouldCelebrate) {625        setView("pro-celebration");626        window.setTimeout(() => setView("entry"), 2500);627      }628    } else if (shouldCelebrate) {629      setPendingCelebration(true);630    }631632    await refreshPendingPasskey();633634    // Track tab changes so smart sort stays current635    const handleTabActivated = () => { void refreshCurrentTab(); };636    const handleTabUpdated = (_tabId: number, changeInfo: { url?: string; status?: string }) => {637      if (changeInfo.url || changeInfo.status === "complete") void refreshCurrentTab();638    };639    try {640      chrome.tabs.onActivated.addListener(handleTabActivated);641      chrome.tabs.onUpdated.addListener(handleTabUpdated);642      onCleanup(() => {643        chrome.tabs.onActivated.removeListener(handleTabActivated);644        chrome.tabs.onUpdated.removeListener(handleTabUpdated);645      });646    } catch {647      // tabs permission may not be available in all contexts648    }649650    setBootState("ready");651652    // Deep-link: ?codex=pdf opens a detached window straight into the653    // Codex restore flow with auto-picked PDF. The action popup can't host654    // a file dialog without dismissing itself, so this is the only way the655    // PDF import path survives. See CodexRestoreView.openPdfPicker().656    try {657      const route = new URLSearchParams(window.location.search).get("codex");658      if (route === "pdf" || route === "restore") {659        setView("codex-restore");660      }661    } catch {662      // location.search unavailable — ignore.663    }664665    // Check for pending session-storage notices from the background.666    if (chrome.storage.session) {667      const session = await chrome.storage.session.get(["pendingProGate", "pendingProNotice"]) as668        Record<string, { feature?: string } | undefined>;669      if (session.pendingProGate?.feature) {670        await chrome.storage.session.remove("pendingProGate");671        setUpgradeHighlight((session.pendingProGate.feature as ProFeature) ?? null);672        setSettingsInitialSection("license");673        setView("settings");674      } else if (session.pendingProNotice?.feature) {675        await chrome.storage.session.remove("pendingProNotice");676        setPendingProNotice({ feature: session.pendingProNotice.feature ?? "" });677      }678    }679680    // Warm the lazy-module cache so the Suspense fallback never shows for681    // locally-bundled extension views. Without this, the first navigation to682    // Settings/Import/Export/etc can briefly mount `.peach-loading`, which683    // covers the shell and absorbs clicks on the header.684    void Promise.all([685      import("./views/Settings").catch(() => {}),686      import("./views/Import").catch(() => {}),687      import("./views/Export").catch(() => {}),688      import("./views/Health").catch(() => {}),689      import("./views/TrashView").catch(() => {}),690    ]);691692    // Lock-on-close via a persistent port. sendMessage in pagehide is693    // unreliable — the popup context tears down before the message lands.694    // The SW's onConnect listener locks when this port disconnects.695    let popupPort: chrome.runtime.Port | null = null;696    try {697      // UI-6 / LV-5: nonce the port name per popup open. The SW's onConnect698      // listener accepts the "popup-" prefix; the random suffix is defence in699      // depth against a port named exactly "popup" from anything but our popup.700      popupPort = chrome.runtime.connect({ name: `popup-${crypto.randomUUID()}` });701    } catch { /* extension context invalidated — ignore */ }702    onCleanup(() => { try { popupPort?.disconnect(); } catch {} });703704    // Android autolock. chrome.alarms is no-op'd on Capacitor, so the only705    // reliable signal is appStateChange — setTimeout is killed when the OS706    // backgrounds the app. We measure elapsed background time on resume.707    if (isNativePlatform()) {708      let backgroundedAt: number | null = null;709710      const CapApp = nativePlugin<{711        addListener: (712          ev: string,713          cb: (s: { isActive: boolean }) => void,714        ) => Promise<{ remove: () => Promise<void> }> | { remove: () => Promise<void> };715      }>("App");716      if (CapApp?.addListener) {717        const sub = CapApp.addListener(718          "appStateChange",719          ({ isActive }: { isActive: boolean }) => {720            if (!isActive) {721              backgroundedAt = Date.now();722              return;723            }724            if (backgroundedAt !== null && autoLockMinutes() > 0) {725              const elapsed = Date.now() - backgroundedAt;726              if (elapsed >= autoLockMinutes() * 60_000) handleHeaderLock();727            }728            backgroundedAt = null;729          }730        );731        // Capacitor 6 listeners return a Promise<{ remove: () => Promise<void> }>.732        onCleanup(() => {733          Promise.resolve(sub).then((s) => s?.remove?.()).catch(() => {});734        });735      }736737      // L12/COR-011: foreground idle autolock. appStateChange only fires when738      // the OS backgrounds the app — if the user idles with the screen on,739      // chrome.alarms is no-op'd in Capacitor so the vault would stay open740      // indefinitely. Poll every 30s and lock if elapsed since last user741      // interaction exceeds autoLockMinutes.742      let lastUserActivityAt = Date.now();743      const bumpActivity = () => { lastUserActivityAt = Date.now(); };744      const ACTIVITY_EVENTS = ["touchstart", "click", "keydown", "input"] as const;745      for (const ev of ACTIVITY_EVENTS) {746        document.addEventListener(ev, bumpActivity, { passive: true, capture: true });747      }748      const idleLockInterval = setInterval(() => {749        const minutes = autoLockMinutes();750        if (!minutes || minutes <= 0) return;751        const elapsed = Date.now() - lastUserActivityAt;752        if (elapsed >= minutes * 60_000) {753          lastUserActivityAt = Date.now();754          handleHeaderLock();755        }756      }, 30_000);757      onCleanup(() => {758        clearInterval(idleLockInterval);759        for (const ev of ACTIVITY_EVENTS) {760          document.removeEventListener(ev, bumpActivity, { capture: true });761        }762      });763764      // The retired native peer-discovery trigger went with the old Capacitor765      // pairing plugin. Reconnection is address-cache first, subnet probe second766      // (sync-runner.ts); relocating a peer that changed networks is an767      // Android-side discovery concern now.768      if (isNativePlatform()) {769        // Android runs the background/sync dispatcher in-process with the770        // popup, so the production runner has to be registered from the771        // UI bootstrap path instead of the MV3 service-worker entry.772        void import("../background/sync-trigger").then(({ hydratePersistedSyncState, setSyncRunner }) =>773          import("../background/sync-runner").then(({ productionSyncRunner }) => {774            setSyncRunner(productionSyncRunner);775            void hydratePersistedSyncState();776          })777        );778      }779    }780781    // Background auto-lock broadcasts VAULT_LOCKED so the popup drops stale782    // entries instead of waiting for the next GET_ENTRIES round-trip.783    const handleRuntimeMessage = (msg: { type?: string; payload?: { feature?: ProFeature } }) => {784      if (msg?.type === "VAULT_LOCKED" && view() !== "lock") handleLock();785      if (msg?.type === "SYNC_STATE_CHANGED") {786        setSyncSummary((msg.payload ?? {}) as SyncOutcomeSummary);787      }788      if (msg?.type === "PRO_GATE_TRIGGERED") {789        setUpgradeHighlight(msg.payload?.feature ?? null);790        setSettingsInitialSection("license");791        setView("settings");792      }793    };794    chrome.runtime.onMessage.addListener(handleRuntimeMessage);795    onCleanup(() => chrome.runtime.onMessage.removeListener(handleRuntimeMessage));796797    // Android hardware/gesture back. MainActivity fires peach:back; the popup798    // decides what "back" means per surface. Lock+no-vault is the common case799    // — return to onboarding rather than letting the OS dismiss the activity.800    const handlePeachBack = () => {801      // Notes mode captures back first802      if (showNotes()) {803        setShowNotes(false);804        setOpenNoteId(undefined);805        return;806      }807      const v = view();808      if (v === "lock" && !hasVault() && onboarded()) {809        setOnboarded(false);810        return;811      }812      if (v === "list") { setView("entry"); return; }813      if (v === "settings") {814        window.dispatchEvent(new Event("peach:settings-back"));815        return;816      }817      if (v === "import" || v === "health") { setView("settings"); return; }818      if (v === "export") { handleExportBack(); return; }819      if (v === "add") { handleBack(); return; }820      if (v === "pair-device") { setView("settings"); return; }821    };822    window.addEventListener("peach:back", handlePeachBack);823    onCleanup(() => window.removeEventListener("peach:back", handlePeachBack));824825    // Mobile bottom-sheet drag tracking. The vault list sits as a sheet that826    // peeks from the bottom (search bar handle visible) and drags up to fill827    // the screen. dragOffset is the LIVE finger offset during a drag, in px,828    // 0 when no drag in progress. The wrapper element computes transform =829    // (rest position) + dragOffset, so the user sees 1:1 finger tracking.830    if (isNativePlatform()) {831      let touchStartY = 0;832      let touchStartX = 0;833      let lastY = 0;834      let lastT = 0;835      let dragging = false;836      let captured = false;837      const HORIZONTAL_TOLERANCE = 16;838      const ACTIVATION_DY = 8;839      const PEEK_PX = 60;840841      const onTouchStart = (e: TouchEvent) => {842        const t = e.touches[0];843        if (!t) return;844        const v = view();845        if (v !== "entry" && v !== "list") return;846        // Entry view: only intercept drags starting in the bottom 40%.847        // List view: intercept drags starting in the top 35% (the search/handle row).848        const inBand = v === "entry"849          ? t.clientY > window.innerHeight * 0.6850          : t.clientY < window.innerHeight * 0.35;851        if (!inBand) return;852        touchStartY = lastY = t.clientY;853        touchStartX = t.clientX;854        lastT = e.timeStamp;855        dragging = true;856        captured = false;857      };858859      const onTouchMove = (e: TouchEvent) => {860        if (!dragging) return;861        const t = e.touches[0];862        if (!t) return;863        const dy = t.clientY - touchStartY;864        const dx = Math.abs(t.clientX - touchStartX);865866        if (!captured) {867          if (dx > HORIZONTAL_TOLERANCE && Math.abs(dy) < dx) {868            // Looks like a horizontal swipe — release.869            dragging = false;870            return;871          }872          if (Math.abs(dy) < ACTIVATION_DY) return;873          captured = true;874        }875876        // Translate the sheet by dy from its rest (peek) position. Peek is877        // (viewport height - PEEK_PX). Open is 0.878        const v = view();879        const restClosed = window.innerHeight - PEEK_PX;880        const baseTranslate = v === "list" ? 0 : restClosed;881        const next = Math.max(0, Math.min(restClosed, baseTranslate + dy));882        setSheetTranslate(next);883        lastY = t.clientY;884        lastT = e.timeStamp;885      };886887      const onTouchEnd = (e: TouchEvent) => {888        if (!dragging) { return; }889        const t = e.changedTouches[0];890        const elapsed = Math.max(1, e.timeStamp - lastT);891        const velocity = t ? (t.clientY - lastY) / elapsed : 0; // px/ms892        const wasCaptured = captured;893        dragging = false;894        captured = false;895        const v = view();896897        if (!wasCaptured) {898          // Tap in the peek strip while in entry view → open the vault list.899          if (v === "entry" && touchStartY > window.innerHeight - PEEK_PX) setView("list");900          setSheetTranslate(null);901          return;902        }903904        const restClosed = window.innerHeight - PEEK_PX;905        const current = sheetTranslate() ?? restClosed;906907        // Snap rules:908        //   - Strong upward velocity → open909        //   - Strong downward velocity → close910        //   - Otherwise snap to whichever rest is closer911        let nextOpen: boolean;912        if (velocity < -0.05) nextOpen = true;913        else if (velocity > 0.05) nextOpen = false;914        else nextOpen = current < restClosed * 0.5;915916        if (nextOpen && v !== "list") setView("list");917        if (!nextOpen && v !== "entry") setView("entry");918        // Release the live offset so CSS transition handles the snap.919        setSheetTranslate(null);920      };921922      document.addEventListener("touchstart", onTouchStart, { passive: true });923      document.addEventListener("touchmove",  onTouchMove,  { passive: true });924      document.addEventListener("touchend",   onTouchEnd,   { passive: true });925      document.addEventListener("touchcancel", () => { dragging = false; captured = false; setSheetTranslate(null); }, { passive: true });926      onCleanup(() => {927        document.removeEventListener("touchstart", onTouchStart);928        document.removeEventListener("touchmove",  onTouchMove);929        document.removeEventListener("touchend",   onTouchEnd);930      });931    }932933    // Action handlers — keyed by ShortcutAction. The dispatcher below tests934    // each binding against the event and runs the matching handler. New935    // shortcuts only need an entry here; the binding is data, not code.936    const SHORTCUT_HANDLERS: Partial<Record<ShortcutAction, () => void>> = {937      copy_password: () => {938        const entry = selectedEntry();939        if (entry?.password) void popupCopy(entry.password, "Password").then((ok) => { if (ok) triggerRing(); });940      },941      copy_username: () => {942        const entry = selectedEntry();943        if (entry?.username) void popupCopy(entry.username, "Username").then((ok) => { if (ok) triggerRing(); });944      },945      copy_totp: () => {946        const entry = selectedEntry();947        if (!entry?.totp) return;948        try {949          const { code } = generateTOTP(entry.totp);950          void popupCopy(code, "2FA").then((ok) => { if (ok) triggerRing(); });951        } catch { /* invalid TOTP secret — silent */ }952      },953      new_entry: () => handleAdd(),954      edit_entry: () => {955        const entry = selectedEntry();956        // Passkey-only entries have nothing user-editable in the Add view; the957        // passkey credential itself is opaque. Skip the edit action for them.958        if (!entry || isPasskeyOnly(entry)) return;959        setEditEntry(entry);960        setView("add");961      },962      delete_entry: () => {963        if (selectedEntry()) void handleDelete();964      },965      lock_vault: () => { void handleHeaderLock(); },966      search: () => openList(),967      nav_prev: () => navigate(-1),968      nav_next: () => navigate(1),969      jump_vault: () => setView("entry"),970      jump_settings: () => setView("settings"),971      show_help: () => setShowShortcutsHelp(true),972    };973974    // Actions that are MEANINGFUL only on the entry-detail view. Outside975    // that scope the binding is dormant — pressing C while on Settings976    // does nothing rather than awkwardly copying from a now-stale entry.977    const ENTRY_SCOPED: ReadonlySet<ShortcutAction> = new Set([978      "copy_password", "copy_username", "copy_totp",979      "edit_entry", "delete_entry", "nav_prev", "nav_next",980    ]);981982    const handleGlobalKeydown = (e: KeyboardEvent) => {983      const v = view();984      const inInput = (e.target as HTMLElement)?.tagName === "INPUT"985        || (e.target as HTMLElement)?.tagName === "TEXTAREA"986        || (e.target as HTMLElement)?.isContentEditable;987      const isPrintableSearchKey =988        e.key.length === 1 &&989        !e.ctrlKey &&990        !e.metaKey &&991        !e.altKey;992993      // No shortcuts while a full-screen surface owns the whole viewport:994      // the lock screen, the post-pairing readiness sequence, or the Pro995      // celebration. Without this the lock screen is at the mercy of whatever996      // single-key binding is active — e.g. typing "n" in a password that997      // slips out of focus triggers `new_entry` and escapes the lock screen.998      if (v === "lock" || v === "adopting" || v === "pro-celebration" || v === "initial-sync") return;9991000      // Help dialog: Escape closes it; eat the keypress so it doesn't1001      // also navigate away from the underlying view.1002      if (showShortcutsHelp()) {1003        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }1004        return;1005      }10061007      // ── Escape — fixed binding (not user-customizable) ───────1008      if (e.key === "Escape") {1009        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }1010        if (v === "list") { setView("entry"); return; }1011        if (v === "settings" || v === "add") { handleBack(); return; }1012        if (v === "import" || v === "health") { setView("settings"); return; }1013        if (v === "export") { handleExportBack(); return; }1014        if (v === "pair-device") { setView("settings"); return; }1015      }10161017      // Bindings-driven dispatch. Single-key letter bindings without1018      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is1019      // inside an input, so users can type into search/forms normally.1020      const bindings = shortcutBindings();1021      for (const action of Object.keys(bindings) as ShortcutAction[]) {1022        const binding = bindings[action];1023        if (!matchKeybinding(e, binding)) continue;1024        // Single-key letter bindings need the input-focus guard. Bindings1025        // with any modifier are safe — Ctrl+L doesn't conflict with typing.1026        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;1027        if (!hasMod && binding.key.length === 1 && inInput) return;1028        if (ENTRY_SCOPED.has(action) && v !== "entry") return;1029        e.preventDefault();1030        SHORTCUT_HANDLERS[action]?.();1031        return;1032      }10331034      // Type-to-search: in entry view, any printable key not consumed by a1035      // shortcut above primes the list search seed and opens the list.1036      // Kept outside the bindings table because it's a behavior, not a1037      // discrete action — every printable character can trigger it.1038      if (v === "entry" && !inInput && isPrintableSearchKey) {1039        e.preventDefault();1040        primeListSearch(e.key);1041        return;1042      }1043    };1044    window.addEventListener("keydown", handleGlobalKeydown);1045    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));10461047    const handleStorageChanged = (1048      changes: Record<string, chrome.storage.StorageChange>,1049      areaName: string1050    ) => {1051      if (areaName !== "session") return;1052      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {1053        return;1054      }1055      void refreshPendingPasskey();1056    };1057    chrome.storage.onChanged.addListener(handleStorageChanged);1058    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));1059  });10601061  async function refreshCurrentTab() {1062    try {1063      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1064      const url = tab?.url ?? tab?.pendingUrl ?? "";1065      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");1066      // Skip extension/internal URLs — adding chrome://, about:, or1067      // chrome-extension:// to a vault entry is never what the user wants.1068      const isWebUrl = /^https?:\/\//i.test(url);1069      setCurrentTabUrl(isWebUrl ? url : "");1070    } catch {1071      setCurrentTabDomain("");1072      setCurrentTabUrl("");1073    }1074  }10751076  async function refreshPendingPasskey() {1077    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });1078    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);1079  }10801081  async function refreshProStatus() {1082    const res = await sendMessage({ type: "GET_LICENSE" });1083    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;1084    setProStatus(Boolean(data?.valid && data?.plan === "pro"));1085  }10861087  async function restoreSettings() {1088    const res = await sendMessage({ type: "GET_SETTINGS" });1089    const s = (res as { ok: boolean; data?: any }).data ?? {};1090    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {1091      setAccentColor(s.accentColor as AccentColorName);1092    }1093    setTheme(s.theme === "light" ? "light" : "dark");1094    if (s.textSize === "small" || s.textSize === "large") {1095      setTextSize(s.textSize);1096    } else {1097      setTextSize("medium");1098    }1099    setReduceMotion(s.reduceMotion === true);1100    setLockOnClose(s.lockOnClose === true);1101    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);1102    setBreachMonitoring(s.breachMonitoring !== false);1103    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);1104    setShortcutBindings(getActiveBindings(s.shortcuts));1105  }11061107  async function applyTrashRetention(days: number) {1108    setTrashRetentionDays(days);1109    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });1110  }11111112  function primeListSearch(seed: string) {1113    setListSearchSeed(seed);1114    setListSearchSeedNonce((value) => value + 1);1115    openList();1116  }11171118  // Returns null when it detected a dead service worker and triggered handleLock().1119  // Callers that need to abort (e.g. openVault) check for null rather than relying1120  // on view() state, which may already be "lock" during normal startup flows.1121  async function loadEntries(): Promise<VaultEntry[] | null> {1122    const response = await sendMessage({ type: "GET_ENTRIES" });1123    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };11241125    // If the service worker was killed and restarted (MV3 workers sleep), the1126    // vault will be locked again — or the worker may not respond at all.1127    // In either case, send the user to the lock screen rather than silently1128    // showing an empty vault (which looks like data loss).1129    if (!res.ok) {1130      if (1131        res.error === "vault_locked" ||1132        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1133        (typeof res.error === "string" && res.error.includes("locked"))1134      ) {1135        handleLock();1136        return null; // signal emergency lock to callers1137      }1138      return [];1139    }11401141    const loadedEntries = res.data ?? [];1142    setEntries(loadedEntries);11431144    const currentId = selectedEntry()?.id;1145    if (currentId) {1146      setSelectedEntry(1147        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1148      );1149    }11501151    return loadedEntries;1152  }11531154  async function openVault(preferredEntryId?: string, skipViewSet = false) {1155    // Purge expired trash entries on each vault open1156    const retDays = trashRetentionDays();1157    if (retDays > 0) {1158      void sendMessage({1159        type: "PURGE_EXPIRED_TRASH",1160        payload: { retentionMs: retDays * 86_400_000 },1161      });1162    }11631164    const loadedEntries = await loadEntries();11651166    // null means loadEntries() triggered an emergency lock (service worker died).1167    // Don't override it by setting view back to "entry" with an empty vault.1168    if (loadedEntries === null) return false;11691170    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1171    let nextSelectedEntry: VaultEntry | null = null;1172    if (preferredEntryId) {1173      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1174    }1175    if (!nextSelectedEntry) {1176      const tabDomain = currentTabDomain();1177      if (tabDomain) {1178        nextSelectedEntry = loadedEntries.find((e) => {1179          if (e.type === "login") {1180            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1181            for (const extra of e.additionalUrls ?? []) {1182              if ((extractDomain(extra) ?? "") === tabDomain) return true;1183            }1184            return false;1185          }1186          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1187          return false;1188        }) ?? null;1189      }1190    }1191    nextSelectedEntry ??= pickNavigable(loadedEntries);11921193    setSelectedEntry(nextSelectedEntry);1194    setEditEntry(undefined);1195    setContentTransitioning(false);1196    setContentPhase("enter");1197    queueContentIdle();1198    if (!skipViewSet) setView("entry");1199    return true;1200  }12011202  async function handleUnlock() {1203    // If the user previously created a vault but hadn't yet confirmed their1204    // recovery words (and the browser was closed before they could), the1205    // peach_recovery_pending flag is still set in storage.local. Re-route1206    // back to the recovery surface so they finish the confirmation step1207    // before reaching the entries view — the words can be re-derived now1208    // that the vault is unlocked again.1209    let recoveryPending = false;1210    try {1211      const out = await chrome.storage.local?.get("peach_recovery_pending");1212      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1213    } catch { /* best-effort */ }1214    if (recoveryPending) {1215      setForceRecoveryWords(true);1216      setView("lock");1217      triggerPipPulse();1218      await restoreSettings();1219      return;1220    }1221    setHasVault(true);1222    triggerPipPulse();1223    await restoreSettings();1224    const celebrating = pendingCelebration();1225    if (celebrating) {1226      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1227      setPendingCelebration(false);1228    }1229    await openVault(undefined, celebrating);1230    if (celebrating) {1231      setView("pro-celebration");1232      window.setTimeout(() => setView("entry"), 2500);1233    }1234    // Popup was opened from the inline "Open Peach to unlock" button — close it1235    // now so the user lands back on the page with the autofill selector ready.1236    if (openedForInlineUnlock) {1237      openedForInlineUnlock = false;1238      window.close();1239    }1240  }12411242  function handleSelectEntry(entry: VaultEntry) {1243    if (entry.type === "note") {1244      setOpenNoteId(entry.id);1245      setShowNotes(true);1246      return;1247    }1248    setSelectedEntry(entry);1249    setContentTransitioning(false);1250    setContentPhase("enter");1251    queueContentIdle();1252    setView("entry");1253  }12541255  function handleAdd() {1256    setEditEntry(undefined);1257    setView("add");1258  }12591260  async function handleDelete() {1261    const entry = selectedEntry();1262    if (!entry) return;1263    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1264    const loadedEntries = await loadEntries() ?? [];1265    setSelectedEntry(pickNavigable(loadedEntries));1266    setView("entry");1267  }12681269  async function handleDeleteMany(ids: string[]) {1270    for (const id of ids) {1271      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1272    }1273    const loadedEntries = await loadEntries() ?? [];1274    // If the currently selected entry was among the deleted, move to first1275    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1276    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1277  }12781279  async function handleSave(savedEntry?: VaultEntry) {1280    await openVault(savedEntry?.id);1281  }12821283  function handleBack() {1284    const dest = editBackView();1285    setEditBackView("entry");1286    setEditEntry(undefined);1287    setView(dest);1288  }12891290  function handleExportBack() {1291    if (returnToPanic()) {1292      setReturnToPanic(false);1293      setView("panic");1294      return;1295    }1296    setView("settings");1297  }12981299  function handleLock() {1300    clearCanarySuppressions();1301    setEntries([]);1302    setSelectedEntry(null);1303    setEditEntry(undefined);1304    setContentPhase("idle");1305    setView("lock");1306  }13071308  function handleHeaderLock() {1309    // Lock the UI immediately — do not wait for the service worker. If the SW1310    // is dead or slow, the 5s sendMessage timeout would create a dead-click1311    // window. The SW will lock on its next wake regardless.1312    handleLock();1313    void sendMessage({ type: "LOCK" });1314  }13151316  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1317  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1318  // the trigger's own reply.1319  async function handleHeaderSync(): Promise<void> {1320    if (syncBusy()) return;1321    setSyncBusy(true);1322    setSyncFlash(null);1323    try {1324      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1325      let state: SyncOutcomeSummary = { status: "syncing" };1326      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1327        await new Promise((r) => setTimeout(r, 250));1328        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1329          ok: boolean;1330          data?: SyncOutcomeSummary;1331        };1332        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1333      }1334      setSyncSummary(state);1335      setSyncFlash(state.status === "error" ? "error" : "ok");1336      await loadSyncAlerts();1337      await loadEntries();1338      await loadSyncIndicator();1339    } catch {1340      setSyncSummary({ status: "error", outcome: "run_failed" });1341      setSyncFlash("error");1342    } finally {1343      setSyncBusy(false);1344      setTimeout(() => setSyncFlash(null), 2_000);1345    }1346  }13471348  function navigate(dir: number) {1349    const navigable = nonNoteEntries();1350    if (navigable.length === 0) return;1351    const currentIndex = selectedIndex();1352    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1353    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1354    setSelectedEntry(navigable[nextIndex]);1355    setContentPhase("enter");1356    queueContentIdle();1357  }13581359  /**1360   * The Entry view's selection invariant: never select a note. Notes are a1361   * separate surface (handleSelectEntry opens the notes view), so any code path1362   * that picks a default — vault open, post-delete, refresh — must skip them1363   * and return null if the only entries are notes.1364   */1365  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1366    return list.find((e) => e.type !== "note") ?? null;1367  }13681369  function openList() {1370    setView("list");1371  }13721373  function openHealth() {1374    setEditEntry(undefined);1375    setView("health");1376  }13771378  function handleOpenFileImport() {1379    setRestoreView("file");1380  }13811382  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;13831384  function handleFixEntry(entry: VaultEntry) {1385    setSelectedEntry(entry);1386    // Passkey-only entries have no editable surface — drop into view mode1387    // instead of opening the Add editor.1388    if (isPasskeyOnly(entry)) {1389      setView("entry");1390      return;1391    }1392    setEditBackView(view()); // preserve caller view so back returns here1393    setEditEntry(entry);1394    setView("add");1395  }13961397  const isLockedView = () => view() === "lock" || view() === "adopting";13981399  async function handleAdoptionDone() {1400    await storageSet("peach_onboarded", "true").catch(() => {});1401    setOnboarded(true);1402    setHasVault(true);1403    setView("initial-sync");1404    // The background applies a Pro license and persists the source-device1405    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1406    // celebration pending until that exact peer records a completed sync.1407    await refreshProStatus();1408    const deviceId = await resolveInitialSyncDeviceId();1409    if (deviceId) {1410      void beginInitialSyncWait(deviceId);1411    } else {1412      // Pairing completion without a durable peer row should be impossible.1413      // Stay on the honest waiting surface and expose retry instead of falling1414      // through to an empty vault.1415      setInitialSyncSlow(true);1416    }1417  }14181419  async function handleApprovePendingPasskey() {1420    const pending = pendingPasskey();1421    if (!pending) return;1422    if (pending.browser === "firefox" && pending.type === "create") {1423      // Firefox path: popup itself runs navigator.credentials.create. The1424      // background never approved/rejected anything — it just stashed1425      // intent. After the popup-driven flow resolves (success or cancel),1426      // clear the pending key so the popup doesn't re-show this on next open.1427      const { createFirefoxPasskey } = await import("./firefox-passkey");1428      const result = await createFirefoxPasskey(pending);1429      if (!result.ok) {1430        console.warn("Peach Firefox passkey create failed:", result.error);1431      }1432      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1433      setPendingPasskey(null);1434      void loadEntries();1435      window.close();1436      return;1437    }1438    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1439    window.close();1440  }14411442  async function handleDenyPendingPasskey() {1443    const pending = pendingPasskey();1444    if (!pending) return;1445    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1446    window.close();1447  }14481449  function queueContentIdle(after?: () => void) {1450    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1451    contentPhaseTimer = window.setTimeout(() => {1452      setContentPhase("idle");1453      after?.();1454    }, ENTRY_TRANSITION_SETTLE_MS);1455  }14561457  return (1458    <div class="popup-root peach-theme">1459      <Show when={bootState() === "ready"}>1460        <Show1461          when={!pendingPasskey()}1462          fallback={1463            <PasskeyApprovalView1464              type={pendingPasskey()!.type}1465              rpName={pendingPasskey()!.rpName}1466              rpId={pendingPasskey()!.rpId}1467              userName={pendingPasskey()!.userName}1468              userDisplayName={pendingPasskey()!.userDisplayName}1469              onApprove={handleApprovePendingPasskey}1470              onDeny={handleDenyPendingPasskey}1471            />1472          }1473        >1474          <Show1475            when={!isLockedView()}1476            fallback={1477              <Show1478                when={view() !== "adopting"}1479                fallback={1480                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1481                    <AdoptVaultView1482                      onCancel={() => {1483                        setOnboarded(false);1484                        setView("lock");1485                      }}1486                      onDone={handleAdoptionDone}1487                    />1488                  </Suspense>1489                }1490              >1491                <Show1492                  when={onboarded() || hasVault()}1493                  fallback={1494                    <Onboarding1495                      onComplete={() => {1496                        setStartOnboardingRestore(false);1497                        setOnboarded(true);1498                      }}1499                      onRestore={() => {1500                        setStartOnboardingRestore(true);1501                        setOnboarded(true);1502                      }}1503                      onAdopt={() => {1504                        setStartOnboardingRestore(false);1505                        setOnboarded(true);1506                        setView("adopting");1507                      }}1508                    />1509                  }1510                >1511                  <LockView1512                    hasVault={hasVault()}1513                    ready={bootState() === "ready"}1514                    isPro={proStatus()}1515                    forceRecoveryWords={forceRecoveryWords()}1516                    initialRestore={startOnboardingRestore()}1517                    onUnlock={() => {1518                      // RecoveryWordDisplay clears the storage flag before1519                      // calling onDone, so handleUnlock will see no pending1520                      // confirmation and proceed through the normal path.1521                      if (forceRecoveryWords()) setForceRecoveryWords(false);1522                      return handleUnlock();1523                    }}1524                    onBackToOnboarding={1525                      !hasVault()1526                        ? () => {1527                            setStartOnboardingRestore(false);1528                            setOnboarded(false);1529                          }1530                        : undefined1531                    }1532                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1533                  />1534                </Show>1535              </Show>1536            }1537          >1538            <Show1539              when={1540                view() !== "pro-celebration" &&1541                view() !== "initial-sync"1542              }1543              fallback={1544                <Show1545                  when={view() === "initial-sync"}1546                  fallback={<ProCelebration />}1547                >1548                  <InitialSyncView1549                    slow={initialSyncSlow()}1550                    onRetry={() => void retryInitialSync()}1551                  />1552                </Show>1553              }1554            >1555            <section1556              id="hd-shell"1557              class="peach-shell peach-theme"1558              data-surface="extension"1559            >1560            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1561              <PeachWordmark unlocked />1562              <div class="peach-chrome-actions">1563                <button1564                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1565                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1566                  aria-label="Notes"1567                  title="Notes"1568                >1569                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1570                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1571                    <line x1="4" y1="5" x2="10" y2="5" />1572                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1573                    <line x1="4" y1="10" x2="7" y2="10" />1574                  </svg>1575                </button>1576                <button1577                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1578                    classList={{1579                      "is-syncing": syncBusy(),1580                      "is-ok": syncFlash() === "ok",1581                      "is-error": syncFlash() === "error",1582                    }}1583                    onClick={() => void handleHeaderSync()}1584                    disabled={syncBusy()}1585                    aria-label={`Sync now. ${syncLabel()}`}1586                    title={syncLabel()}1587                  >1588                    <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">1589                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1590                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1591                      <path d="M2.6 1v2.4h2.4" />1592                      <path d="M11.4 13v-2.4H9" />1593                    </svg>1594                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1595                  </button>1596                <button1597                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1598                  onClick={() => setView("settings")}1599                  aria-label="Settings"1600                >1601                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1602                    <path1603                      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"1604                      stroke="currentColor"1605                      stroke-width="0.9"1606                    />1607                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1608                  </svg>1609                </button>1610                <button1611                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1612                  onClick={handleAdd}1613                  aria-label="New entry"1614                >1615                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1616                    <path d="M5.5 1v9M1 5.5h9" />1617                  </svg>1618                </button>1619                <button1620                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1621                  onClick={() => void handleHeaderLock()}1622                  aria-label="Lock vault"1623                >1624                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1625                    <path1626                      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"1627                      stroke="currentColor"1628                      stroke-width="1"1629                      stroke-linecap="round"1630                    />1631                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1632                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1633                  </svg>1634                </button>1635              </div>1636            </header>16371638            <Show when={pendingProNotice() !== null}>1639              <div class="peach-pro-notice-banner">1640                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1641                <button1642                  class="peach-pro-notice-link"1643                  onClick={() => {1644                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1645                    setSettingsInitialSection("license");1646                    setView("settings");1647                    setPendingProNotice(null);1648                  }}1649                >1650                  Learn more →1651                </button>1652                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1653              </div>1654            </Show>16551656            <div class="peach-shell-body">1657              <div class="peach-shell-veil"></div>1658              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1659                <EntryView1660                  entry={selectedEntry()}1661                  currentTabUrl={currentTabUrl()}1662                  entries={entries()}1663                  isPro={proStatus()}1664                  onDelete={handleDelete}1665                  onFieldSaved={() => void loadEntries()}1666                  onEscape={() => { setView("list"); }}1667                  onProGate={(feature) => {1668                    setUpgradeHighlight(feature);1669                    setSettingsInitialSection("license");1670                    setView("settings");1671                  }}1672                />1673              </div>16741675              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1676                <div class="peach-search-bar">1677                  <span class="peach-search-icon">1678                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1679                      <circle cx="5.5" cy="5.5" r="3.75" />1680                      <path d="M8.75 8.75L11.5 11.5" />1681                    </svg>1682                  </span>1683                  <input1684                    class="peach-search-input"1685                    placeholder="search vault..."1686                    autocomplete="off"1687                    aria-label="Search vault entries"1688                    onClick={openList}1689                    onFocus={openList}1690                    readOnly1691                  />1692                  <div class="peach-search-meta">1693                    <span class="peach-search-counter">1694                      {nonNoteEntries().length > 01695                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1696                        : "0 entries"}1697                    </span>1698                    <span class="peach-divider"></span>1699                    <button1700                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1701                      onClick={() => navigate(-1)}1702                      aria-label="Previous entry"1703                      disabled={nonNoteEntries().length === 0}1704                    >1705                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1706                        <path d="M5 1L1 5.5L5 10" />1707                      </svg>1708                    </button>1709                    <button1710                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1711                      onClick={() => navigate(1)}1712                      aria-label="Next entry"1713                      disabled={nonNoteEntries().length === 0}1714                    >1715                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1716                        <path d="M1 1L5 5.5L1 10" />1717                      </svg>1718                    </button>1719                  </div>1720                </div>1721              </section>1722            </div>17231724            {/* Desktop: shown on demand via Show. Native sheet is rendered1725                via Portal below at the document root so its position:fixed1726                isn't trapped by .peach-shell's transform-based animations. */}1727            {/* Rare device-trust alerts; normal sync changes are silent. */}1728            <Show when={alertGroups().length > 0}>1729              <div class="peach-sync-alerts">1730                <For each={alertGroups()}>1731                  {([type, group]) => {1732                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1733                    return (1734                      <div class="peach-sync-alert">1735                        <Show when={group.length > 1}>1736                          <button1737                            class="peach-sync-alert-flip"1738                            type="button"1739                            aria-label="Previous"1740                            onClick={() => flipAlert(type, -1)}1741                          >‹</button>1742                        </Show>1743                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1744                        <Show when={group.length > 1}>1745                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1746                          <button1747                            class="peach-sync-alert-flip"1748                            type="button"1749                            aria-label="Next"1750                            onClick={() => flipAlert(type, 1)}1751                          >›</button>1752                        </Show>1753                        <button1754                          class="peach-sync-alert-dismiss"1755                          type="button"1756                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1757                          onClick={() => dismissAlertGroup(type)}1758                        >×</button>1759                      </div>1760                    );1761                  }}1762                </For>1763              </div>1764            </Show>17651766            <Show when={!isNativePlatform() && view() === "list"}>1767              <VaultView1768                entries={entries()}1769                selectedEntryId={selectedEntry()?.id}1770                currentTabDomain={currentTabDomain()}1771                sortOrder={sortOrder()}1772                searchSeed={listSearchSeed()}1773                searchSeedNonce={listSearchSeedNonce()}1774                onSelectEntry={handleSelectEntry}1775                onSortOrderChange={setSortOrder}1776                onAdd={handleAdd}1777                onClose={() => setView("entry")}1778                onOpenTrash={() => setView("trash")}1779                onDeleteMany={handleDeleteMany}1780              />1781            </Show>1782            <Show when={isNativePlatform() && hasVault()}>1783              <Portal>1784                <div1785                  class="peach-vault-sheet"1786                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1787                  style={(() => {1788                    const live = sheetTranslate();1789                    if (live === null) return undefined;1790                    return { transform: `translateY(${live}px)` };1791                  })()}1792                >1793                  <VaultView1794                    entries={entries()}1795                    selectedEntryId={selectedEntry()?.id}1796                    currentTabDomain={currentTabDomain()}1797                    sortOrder={sortOrder()}1798                    searchSeed={listSearchSeed()}1799                    searchSeedNonce={listSearchSeedNonce()}1800                    isNative={true}1801                    onSelectEntry={handleSelectEntry}1802                    onSortOrderChange={setSortOrder}1803                    onAdd={handleAdd}1804                    onClose={() => setView("entry")}1805                    onOpenTrash={() => setView("trash")}1806                    onDeleteMany={handleDeleteMany}1807                  />1808                </div>1809              </Portal>1810            </Show>1811            <Show when={view() === "settings" || settingsExiting()}>1812              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1813                <SettingsView1814                  entriesCount={entries().length}1815                  breachMonitoring={breachMonitoring()}1816                  lockOnClose={lockOnClose()}1817                  autoLockMinutes={autoLockMinutes()}1818                  trashRetentionDays={trashRetentionDays()}1819                  theme={theme()}1820                  accentColor={accentColor()}1821                  textSize={textSize()}1822                  reduceMotion={reduceMotion()}1823                  isPro={proStatus()}1824                  initialSection={settingsInitialSection()}1825                  upgradeHighlight={upgradeHighlight()}1826                  isExiting={settingsExiting()}1827                  onBreachMonitoringChange={applyBreachMonitoring}1828                  onLockOnCloseChange={applyLockOnClose}1829                  onAutoLockMinutesChange={applyAutoLockMinutes}1830                  onTrashRetentionChange={applyTrashRetention}1831                  onThemeChange={applyTheme}1832                  onAccentChange={applyAccentColor}1833                  onTextSizeChange={applyTextSize}1834                  onReduceMotionChange={applyReduceMotion}1835                  shortcuts={shortcutBindings()}1836                  onShortcutsChange={applyShortcuts}1837                  onLicenseChange={async () => {1838                    // After activation/deactivation: refresh Pro status,1839                    // re-load entries (defensive — signal state can drift if1840                    // the SW briefly restarts during the verify+save round-trip),1841                    // and replay the Pro celebration if this is the first time1842                    // a valid Pro license is seen on this device.1843                    await refreshProStatus();1844                    void loadEntries();1845                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1846                    if ((should as { ok: boolean; data?: boolean }).data === true) {1847                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1848                      setView("pro-celebration");1849                      window.setTimeout(() => setView("settings"), 2500);1850                    }1851                  }}1852                  onBack={() => {1853                    setSettingsExiting(true);1854                    window.setTimeout(() => {1855                      setSettingsExiting(false);1856                      setSettingsInitialSection(null);1857                      setUpgradeHighlight(null);1858                      handleBack();1859                    }, 200);1860                  }}1861                  onImport={() => setView("import")}1862                  onExport={() => setView("export")}1863                  onBreachCheckDone={loadEntries}1864                  onOpenHealth={openHealth}1865                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1866                  onOpenFileImport={handleOpenFileImport}1867                  onOpenPanic={() => setView("panic")}1868                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1869                  onOpenCodexRestore={() => setView("codex-restore")}1870                  onCardChange={setSettingsActiveCard}1871                  onProGate={(feature) => {1872                    setUpgradeHighlight(feature);1873                    setSettingsInitialSection("license");1874                  }}1875                />1876              </Suspense>1877            </Show>1878            <Show when={view() === "codex-generate"}>1879              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1880                <CodexGenerateView1881                  isPro={proStatus()}1882                  onBack={() => setView("settings")}1883                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1884                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1885                  onVaultLocked={() => handleLock()}1886                />1887              </Suspense>1888            </Show>1889            <Show when={view() === "codex-restore"}>1890              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1891                <CodexRestoreView1892                  onBack={() => setView("lock")}1893                  onRestoreSuccess={async () => {1894                    // After restore the vault is unlocked; refresh entries1895                    // and route to the main vault list. handleUnlock is the1896                    // canonical post-unlock setup path.1897                    await handleUnlock();1898                  }}1899                />1900              </Suspense>1901            </Show>1902            <Show when={view() === "pair-device"}>1903              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1904                <PairDeviceView1905                  isPro={proStatus()}1906                  onProChanged={() => { void refreshProStatus(); }}1907                  onBack={() => setView("settings")}1908                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1909                />1910              </Suspense>1911            </Show>1912            <Show when={view() === "add"}>1913              <AddView1914                entry={editEntry()}1915                entries={entries()}1916                onBack={handleBack}1917                onSave={handleSave}1918              />1919            </Show>1920            <Show when={view() === "import"}>1921              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1922                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1923              </Suspense>1924            </Show>1925            <Show when={view() === "export"}>1926              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1927                <ExportView onBack={handleExportBack} />1928              </Suspense>1929            </Show>1930            <Show when={view() === "panic"}>1931              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1932                <PanicView1933                  onCancel={() => setView("settings")}1934                  onOpenExport={() => {1935                    setReturnToPanic(true);1936                    setView("export");1937                  }}1938                  onDestroyed={async () => {1939                    clearCanarySuppressions();1940                    setEntries([]);1941                    setSelectedEntry(null);1942                    setEditEntry(undefined);1943                    setHasVault(false);1944                    setOnboarded(false);1945                    setProStatus(false);1946                    setPendingPasskey(null);1947                    setUpgradeHighlight(null);1948                    setSettingsInitialSection(null);1949                    setPendingProNotice(null);1950                    setPendingCelebration(false);1951                    setReturnToPanic(false);1952                    setContentPhase("idle");1953                    setView("lock");1954                  }}1955                />1956              </Suspense>1957            </Show>1958            {/* Health stays mounted while editing an entry from it so1959                computeReused() doesn't rerun on every cancel/back. */}1960            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1961              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1962                <HealthView1963                  entries={entries()}1964                  isPro={proStatus()}1965                  onFixEntry={handleFixEntry}1966                  onBack={() => setView("settings")}1967                  onRefresh={loadEntries}1968                  hidden={view() !== "health"}1969                />1970              </Suspense>1971            </Show>1972            <Show when={view() === "trash"}>1973              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1974                <TrashView1975                  onBack={() => setView("list")}1976                  onRestored={() => void loadEntries()}1977                />1978              </Suspense>1979            </Show>1980            <Show when={showNotes()}>1981              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1982                <NotesMode1983                  notes={entries().filter((e) => e.type === "note")}1984                  initialNoteId={openNoteId()}1985                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1986                  onNoteListChanged={() => void loadEntries()}1987                />1988              </div>1989            </Show>1990            <Show when={restoreView() === "file"}>1991              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1992                <ImportView1993                  mode="onboarding"1994                  replacesExistingVault={true}1995                  onBack={() => setRestoreView(null)}1996                  onImport={async () => {1997                    setRestoreView(null);1998                    await handleUnlock();1999                  }}2000                />2001              </Suspense>2002            </Show>2003            </section>2004            </Show>2005          </Show>2006        </Show>2007      </Show>2008      <Show when={showShortcutsHelp()}>2009        <ShortcutsHelpOverlay2010          bindings={shortcutBindings()}2011          onClose={() => setShowShortcutsHelp(false)}2012        />2013      </Show>2014    </div>2015  );2016}20172018function ShortcutsHelpOverlay(props: {2019  bindings: Record<ShortcutAction, Keybinding>;2020  onClose: () => void;2021}) {2022  return (2023    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>2024      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>2025        <div class="peach-shortcuts-help-head">2026          <h3>Keyboard shortcuts</h3>2027          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>2028        </div>2029        <div class="peach-shortcuts-help-body">2030          <p class="peach-settings-sub-label">ENTRY VIEW</p>2031          <ul>2032            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (2033              <li>2034                <span>{d.label}</span>2035                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2036              </li>2037            ))}2038          </ul>2039          <p class="peach-settings-sub-label">ANYWHERE</p>2040          <ul>2041            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (2042              <li>2043                <span>{d.label}</span>2044                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2045              </li>2046            ))}2047          </ul>2048        </div>2049      </div>2050    </div>2051  );2052}