App.tsx

84.3 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(true);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 navigation shortcuts while the post-pairing readiness sequence or994      // Pro celebration owns the whole surface.995      if (v === "pro-celebration" || v === "initial-sync") return;996997      // Help dialog: Escape closes it; eat the keypress so it doesn't998      // also navigate away from the underlying view.999      if (showShortcutsHelp()) {1000        if (e.key === "Escape") { e.preventDefault(); setShowShortcutsHelp(false); }1001        return;1002      }10031004      // ── Escape — fixed binding (not user-customizable) ───────1005      if (e.key === "Escape") {1006        if (showNotes()) { setShowNotes(false); setOpenNoteId(undefined); return; }1007        if (v === "list") { setView("entry"); return; }1008        if (v === "settings" || v === "add") { handleBack(); return; }1009        if (v === "import" || v === "health") { setView("settings"); return; }1010        if (v === "export") { handleExportBack(); return; }1011        if (v === "pair-device") { setView("settings"); return; }1012      }10131014      // Bindings-driven dispatch. Single-key letter bindings without1015      // modifiers (c/u/t/n/e/d/?) are silently swallowed when focus is1016      // inside an input, so users can type into search/forms normally.1017      const bindings = shortcutBindings();1018      for (const action of Object.keys(bindings) as ShortcutAction[]) {1019        const binding = bindings[action];1020        if (!matchKeybinding(e, binding)) continue;1021        // Single-key letter bindings need the input-focus guard. Bindings1022        // with any modifier are safe — Ctrl+L doesn't conflict with typing.1023        const hasMod = binding.ctrl || binding.meta || binding.alt || binding.shift;1024        if (!hasMod && binding.key.length === 1 && inInput) return;1025        if (ENTRY_SCOPED.has(action) && v !== "entry") return;1026        e.preventDefault();1027        SHORTCUT_HANDLERS[action]?.();1028        return;1029      }10301031      // Type-to-search: in entry view, any printable key not consumed by a1032      // shortcut above primes the list search seed and opens the list.1033      // Kept outside the bindings table because it's a behavior, not a1034      // discrete action — every printable character can trigger it.1035      if (v === "entry" && !inInput && isPrintableSearchKey) {1036        e.preventDefault();1037        primeListSearch(e.key);1038        return;1039      }1040    };1041    window.addEventListener("keydown", handleGlobalKeydown);1042    onCleanup(() => window.removeEventListener("keydown", handleGlobalKeydown));10431044    const handleStorageChanged = (1045      changes: Record<string, chrome.storage.StorageChange>,1046      areaName: string1047    ) => {1048      if (areaName !== "session") return;1049      if (!Object.keys(changes).some((key) => key.startsWith("passkey_pending_"))) {1050        return;1051      }1052      void refreshPendingPasskey();1053    };1054    chrome.storage.onChanged.addListener(handleStorageChanged);1055    onCleanup(() => chrome.storage.onChanged.removeListener(handleStorageChanged));1056  });10571058  async function refreshCurrentTab() {1059    try {1060      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });1061      const url = tab?.url ?? tab?.pendingUrl ?? "";1062      setCurrentTabDomain(url ? (extractDomain(url) ?? "") : "");1063      // Skip extension/internal URLs — adding chrome://, about:, or1064      // chrome-extension:// to a vault entry is never what the user wants.1065      const isWebUrl = /^https?:\/\//i.test(url);1066      setCurrentTabUrl(isWebUrl ? url : "");1067    } catch {1068      setCurrentTabDomain("");1069      setCurrentTabUrl("");1070    }1071  }10721073  async function refreshPendingPasskey() {1074    const res = await sendMessage({ type: "GET_PENDING_PASSKEY" });1075    setPendingPasskey((res as { ok: boolean; data?: PendingPasskeyRequest | null }).data ?? null);1076  }10771078  async function refreshProStatus() {1079    const res = await sendMessage({ type: "GET_LICENSE" });1080    const data = (res as { ok: boolean; data?: { valid?: boolean; plan?: string } }).data;1081    setProStatus(Boolean(data?.valid && data?.plan === "pro"));1082  }10831084  async function restoreSettings() {1085    const res = await sendMessage({ type: "GET_SETTINGS" });1086    const s = (res as { ok: boolean; data?: any }).data ?? {};1087    if (s.accentColor && ACCENT_COLORS.some(c => c.name === s.accentColor)) {1088      setAccentColor(s.accentColor as AccentColorName);1089    }1090    setTheme(s.theme === "light" ? "light" : "dark");1091    if (s.textSize === "small" || s.textSize === "large") {1092      setTextSize(s.textSize);1093    } else {1094      setTextSize("medium");1095    }1096    setReduceMotion(s.reduceMotion === true);1097    setLockOnClose(s.lockOnClose !== false);1098    setAutoLockMinutes(typeof s.autoLockMinutes === "number" ? s.autoLockMinutes : 5);1099    setBreachMonitoring(s.breachMonitoring !== false);1100    setTrashRetentionDays(typeof s.trashRetentionDays === "number" ? s.trashRetentionDays : 30);1101    setShortcutBindings(getActiveBindings(s.shortcuts));1102  }11031104  async function applyTrashRetention(days: number) {1105    setTrashRetentionDays(days);1106    await sendMessage({ type: "UPDATE_SETTINGS", payload: { trashRetentionDays: days } });1107  }11081109  function primeListSearch(seed: string) {1110    setListSearchSeed(seed);1111    setListSearchSeedNonce((value) => value + 1);1112    openList();1113  }11141115  // Returns null when it detected a dead service worker and triggered handleLock().1116  // Callers that need to abort (e.g. openVault) check for null rather than relying1117  // on view() state, which may already be "lock" during normal startup flows.1118  async function loadEntries(): Promise<VaultEntry[] | null> {1119    const response = await sendMessage({ type: "GET_ENTRIES" });1120    const res = response as { ok: boolean; data?: VaultEntry[]; error?: string };11211122    // If the service worker was killed and restarted (MV3 workers sleep), the1123    // vault will be locked again — or the worker may not respond at all.1124    // In either case, send the user to the lock screen rather than silently1125    // showing an empty vault (which looks like data loss).1126    if (!res.ok) {1127      if (1128        res.error === "vault_locked" ||1129        res.error === "SERVICE_WORKER_UNAVAILABLE" ||1130        (typeof res.error === "string" && res.error.includes("locked"))1131      ) {1132        handleLock();1133        return null; // signal emergency lock to callers1134      }1135      return [];1136    }11371138    const loadedEntries = res.data ?? [];1139    setEntries(loadedEntries);11401141    const currentId = selectedEntry()?.id;1142    if (currentId) {1143      setSelectedEntry(1144        loadedEntries.find((entry) => entry.id === currentId) ?? pickNavigable(loadedEntries)1145      );1146    }11471148    return loadedEntries;1149  }11501151  async function openVault(preferredEntryId?: string, skipViewSet = false) {1152    // Purge expired trash entries on each vault open1153    const retDays = trashRetentionDays();1154    if (retDays > 0) {1155      void sendMessage({1156        type: "PURGE_EXPIRED_TRASH",1157        payload: { retentionMs: retDays * 86_400_000 },1158      });1159    }11601161    const loadedEntries = await loadEntries();11621163    // null means loadEntries() triggered an emergency lock (service worker died).1164    // Don't override it by setting view back to "entry" with an empty vault.1165    if (loadedEntries === null) return false;11661167    // Smart selection: prefer explicitly requested ID, then a domain match, then first entry1168    let nextSelectedEntry: VaultEntry | null = null;1169    if (preferredEntryId) {1170      nextSelectedEntry = loadedEntries.find((e) => e.id === preferredEntryId) ?? null;1171    }1172    if (!nextSelectedEntry) {1173      const tabDomain = currentTabDomain();1174      if (tabDomain) {1175        nextSelectedEntry = loadedEntries.find((e) => {1176          if (e.type === "login") {1177            if (e.url && (extractDomain(e.url) ?? "") === tabDomain) return true;1178            for (const extra of e.additionalUrls ?? []) {1179              if ((extractDomain(extra) ?? "") === tabDomain) return true;1180            }1181            return false;1182          }1183          if (e.passkey?.rpId) return e.passkey.rpId === tabDomain;1184          return false;1185        }) ?? null;1186      }1187    }1188    nextSelectedEntry ??= pickNavigable(loadedEntries);11891190    setSelectedEntry(nextSelectedEntry);1191    setEditEntry(undefined);1192    setContentTransitioning(false);1193    setContentPhase("enter");1194    queueContentIdle();1195    if (!skipViewSet) setView("entry");1196    return true;1197  }11981199  async function handleUnlock() {1200    // If the user previously created a vault but hadn't yet confirmed their1201    // recovery words (and the browser was closed before they could), the1202    // peach_recovery_pending flag is still set in storage.local. Re-route1203    // back to the recovery surface so they finish the confirmation step1204    // before reaching the entries view — the words can be re-derived now1205    // that the vault is unlocked again.1206    let recoveryPending = false;1207    try {1208      const out = await chrome.storage.local?.get("peach_recovery_pending");1209      recoveryPending = (out as { peach_recovery_pending?: string })?.peach_recovery_pending === "1";1210    } catch { /* best-effort */ }1211    if (recoveryPending) {1212      setForceRecoveryWords(true);1213      setView("lock");1214      triggerPipPulse();1215      await restoreSettings();1216      return;1217    }1218    setHasVault(true);1219    triggerPipPulse();1220    await restoreSettings();1221    const celebrating = pendingCelebration();1222    if (celebrating) {1223      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1224      setPendingCelebration(false);1225    }1226    await openVault(undefined, celebrating);1227    if (celebrating) {1228      setView("pro-celebration");1229      window.setTimeout(() => setView("entry"), 2500);1230    }1231    // Popup was opened from the inline "Open Peach to unlock" button — close it1232    // now so the user lands back on the page with the autofill selector ready.1233    if (openedForInlineUnlock) {1234      openedForInlineUnlock = false;1235      window.close();1236    }1237  }12381239  function handleSelectEntry(entry: VaultEntry) {1240    if (entry.type === "note") {1241      setOpenNoteId(entry.id);1242      setShowNotes(true);1243      return;1244    }1245    setSelectedEntry(entry);1246    setContentTransitioning(false);1247    setContentPhase("enter");1248    queueContentIdle();1249    setView("entry");1250  }12511252  function handleAdd() {1253    setEditEntry(undefined);1254    setView("add");1255  }12561257  async function handleDelete() {1258    const entry = selectedEntry();1259    if (!entry) return;1260    await sendMessage({ type: "DELETE_ENTRY", payload: { id: entry.id } });1261    const loadedEntries = await loadEntries() ?? [];1262    setSelectedEntry(pickNavigable(loadedEntries));1263    setView("entry");1264  }12651266  async function handleDeleteMany(ids: string[]) {1267    for (const id of ids) {1268      await sendMessage({ type: "DELETE_ENTRY", payload: { id } });1269    }1270    const loadedEntries = await loadEntries() ?? [];1271    // If the currently selected entry was among the deleted, move to first1272    const stillExists = loadedEntries.find(e => e.id === selectedEntry()?.id);1273    if (!stillExists) setSelectedEntry(pickNavigable(loadedEntries));1274  }12751276  async function handleSave(savedEntry?: VaultEntry) {1277    await openVault(savedEntry?.id);1278  }12791280  function handleBack() {1281    const dest = editBackView();1282    setEditBackView("entry");1283    setEditEntry(undefined);1284    setView(dest);1285  }12861287  function handleExportBack() {1288    if (returnToPanic()) {1289      setReturnToPanic(false);1290      setView("panic");1291      return;1292    }1293    setView("settings");1294  }12951296  function handleLock() {1297    clearCanarySuppressions();1298    setEntries([]);1299    setSelectedEntry(null);1300    setEditEntry(undefined);1301    setContentPhase("idle");1302    setView("lock");1303  }13041305  function handleHeaderLock() {1306    // Lock the UI immediately — do not wait for the service worker. If the SW1307    // is dead or slow, the 5s sendMessage timeout would create a dead-click1308    // window. The SW will lock on its next wake regardless.1309    handleLock();1310    void sendMessage({ type: "LOCK" });1311  }13121313  // Manual sync from the topbar. TRIGGER_SYNC returns as soon as the run is1314  // queued, so the outcome is read back from GET_SYNC_STATE rather than from1315  // the trigger's own reply.1316  async function handleHeaderSync(): Promise<void> {1317    if (syncBusy()) return;1318    setSyncBusy(true);1319    setSyncFlash(null);1320    try {1321      await sendMessage({ type: "TRIGGER_SYNC", payload: { reason: "manual", force: true } });1322      let state: SyncOutcomeSummary = { status: "syncing" };1323      for (let i = 0; i < 40 && state.status === "syncing"; i++) {1324        await new Promise((r) => setTimeout(r, 250));1325        const res = (await sendMessage({ type: "GET_SYNC_STATE" })) as {1326          ok: boolean;1327          data?: SyncOutcomeSummary;1328        };1329        state = res.ok ? res.data ?? { status: "idle" } : { status: "error" };1330      }1331      setSyncSummary(state);1332      setSyncFlash(state.status === "error" ? "error" : "ok");1333      await loadSyncAlerts();1334      await loadEntries();1335      await loadSyncIndicator();1336    } catch {1337      setSyncSummary({ status: "error", outcome: "run_failed" });1338      setSyncFlash("error");1339    } finally {1340      setSyncBusy(false);1341      setTimeout(() => setSyncFlash(null), 2_000);1342    }1343  }13441345  function navigate(dir: number) {1346    const navigable = nonNoteEntries();1347    if (navigable.length === 0) return;1348    const currentIndex = selectedIndex();1349    const baseIndex = currentIndex >= 0 ? currentIndex : 0;1350    const nextIndex = (baseIndex + dir + navigable.length) % navigable.length;1351    setSelectedEntry(navigable[nextIndex]);1352    setContentPhase("enter");1353    queueContentIdle();1354  }13551356  /**1357   * The Entry view's selection invariant: never select a note. Notes are a1358   * separate surface (handleSelectEntry opens the notes view), so any code path1359   * that picks a default — vault open, post-delete, refresh — must skip them1360   * and return null if the only entries are notes.1361   */1362  function pickNavigable(list: VaultEntry[]): VaultEntry | null {1363    return list.find((e) => e.type !== "note") ?? null;1364  }13651366  function openList() {1367    setView("list");1368  }13691370  function openHealth() {1371    setEditEntry(undefined);1372    setView("health");1373  }13741375  function handleOpenFileImport() {1376    setRestoreView("file");1377  }13781379  const isShellOverlayOpen = () => view() !== "entry" || restoreView() !== null;13801381  function handleFixEntry(entry: VaultEntry) {1382    setSelectedEntry(entry);1383    // Passkey-only entries have no editable surface — drop into view mode1384    // instead of opening the Add editor.1385    if (isPasskeyOnly(entry)) {1386      setView("entry");1387      return;1388    }1389    setEditBackView(view()); // preserve caller view so back returns here1390    setEditEntry(entry);1391    setView("add");1392  }13931394  const isLockedView = () => view() === "lock" || view() === "adopting";13951396  async function handleAdoptionDone() {1397    await storageSet("peach_onboarded", "true").catch(() => {});1398    setOnboarded(true);1399    setHasVault(true);1400    setView("initial-sync");1401    // The background applies a Pro license and persists the source-device1402    // readiness marker before it acknowledges adoption. Keep the one-shot Pro1403    // celebration pending until that exact peer records a completed sync.1404    await refreshProStatus();1405    const deviceId = await resolveInitialSyncDeviceId();1406    if (deviceId) {1407      void beginInitialSyncWait(deviceId);1408    } else {1409      // Pairing completion without a durable peer row should be impossible.1410      // Stay on the honest waiting surface and expose retry instead of falling1411      // through to an empty vault.1412      setInitialSyncSlow(true);1413    }1414  }14151416  async function handleApprovePendingPasskey() {1417    const pending = pendingPasskey();1418    if (!pending) return;1419    if (pending.browser === "firefox" && pending.type === "create") {1420      // Firefox path: popup itself runs navigator.credentials.create. The1421      // background never approved/rejected anything — it just stashed1422      // intent. After the popup-driven flow resolves (success or cancel),1423      // clear the pending key so the popup doesn't re-show this on next open.1424      const { createFirefoxPasskey } = await import("./firefox-passkey");1425      const result = await createFirefoxPasskey(pending);1426      if (!result.ok) {1427        console.warn("Peach Firefox passkey create failed:", result.error);1428      }1429      await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1430      setPendingPasskey(null);1431      void loadEntries();1432      window.close();1433      return;1434    }1435    await sendMessage({ type: "APPROVE_PASSKEY", payload: { requestId: pending.requestId } });1436    window.close();1437  }14381439  async function handleDenyPendingPasskey() {1440    const pending = pendingPasskey();1441    if (!pending) return;1442    await sendMessage({ type: "DENY_PASSKEY", payload: { requestId: pending.requestId } });1443    window.close();1444  }14451446  function queueContentIdle(after?: () => void) {1447    if (contentPhaseTimer) window.clearTimeout(contentPhaseTimer);1448    contentPhaseTimer = window.setTimeout(() => {1449      setContentPhase("idle");1450      after?.();1451    }, ENTRY_TRANSITION_SETTLE_MS);1452  }14531454  return (1455    <div class="popup-root peach-theme">1456      <Show when={bootState() === "ready"}>1457        <Show1458          when={!pendingPasskey()}1459          fallback={1460            <PasskeyApprovalView1461              type={pendingPasskey()!.type}1462              rpName={pendingPasskey()!.rpName}1463              rpId={pendingPasskey()!.rpId}1464              userName={pendingPasskey()!.userName}1465              userDisplayName={pendingPasskey()!.userDisplayName}1466              onApprove={handleApprovePendingPasskey}1467              onDeny={handleDenyPendingPasskey}1468            />1469          }1470        >1471          <Show1472            when={!isLockedView()}1473            fallback={1474              <Show1475                when={view() !== "adopting"}1476                fallback={1477                  <Suspense fallback={<div class="peach-loading">loading...</div>}>1478                    <AdoptVaultView1479                      onCancel={() => {1480                        setOnboarded(false);1481                        setView("lock");1482                      }}1483                      onDone={handleAdoptionDone}1484                    />1485                  </Suspense>1486                }1487              >1488                <Show1489                  when={onboarded() || hasVault()}1490                  fallback={1491                    <Onboarding1492                      onComplete={() => {1493                        setStartOnboardingRestore(false);1494                        setOnboarded(true);1495                      }}1496                      onRestore={() => {1497                        setStartOnboardingRestore(true);1498                        setOnboarded(true);1499                      }}1500                      onAdopt={() => {1501                        setStartOnboardingRestore(false);1502                        setOnboarded(true);1503                        setView("adopting");1504                      }}1505                    />1506                  }1507                >1508                  <LockView1509                    hasVault={hasVault()}1510                    ready={bootState() === "ready"}1511                    isPro={proStatus()}1512                    forceRecoveryWords={forceRecoveryWords()}1513                    initialRestore={startOnboardingRestore()}1514                    onUnlock={() => {1515                      // RecoveryWordDisplay clears the storage flag before1516                      // calling onDone, so handleUnlock will see no pending1517                      // confirmation and proceed through the normal path.1518                      if (forceRecoveryWords()) setForceRecoveryWords(false);1519                      return handleUnlock();1520                    }}1521                    onBackToOnboarding={1522                      !hasVault()1523                        ? () => {1524                            setStartOnboardingRestore(false);1525                            setOnboarded(false);1526                          }1527                        : undefined1528                    }1529                    onOpenCodexRestore={!hasVault() ? () => setView("codex-restore") : undefined}1530                  />1531                </Show>1532              </Show>1533            }1534          >1535            <Show1536              when={1537                view() !== "pro-celebration" &&1538                view() !== "initial-sync"1539              }1540              fallback={1541                <Show1542                  when={view() === "initial-sync"}1543                  fallback={<ProCelebration />}1544                >1545                  <InitialSyncView1546                    slow={initialSyncSlow()}1547                    onRetry={() => void retryInitialSync()}1548                  />1549                </Show>1550              }1551            >1552            <section1553              id="hd-shell"1554              class="peach-shell peach-theme"1555              data-surface="extension"1556            >1557            <header class="peach-chrome" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1558              <PeachWordmark unlocked />1559              <div class="peach-chrome-actions">1560                <button1561                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1562                  onClick={() => { setOpenNoteId(undefined); setShowNotes(true); }}1563                  aria-label="Notes"1564                  title="Notes"1565                >1566                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">1567                    <rect x="1.5" y="1.5" width="11" height="11" rx="2" />1568                    <line x1="4" y1="5" x2="10" y2="5" />1569                    <line x1="4" y1="7.5" x2="10" y2="7.5" />1570                    <line x1="4" y1="10" x2="7" y2="10" />1571                  </svg>1572                </button>1573                <button1574                    class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-sync-btn"1575                    classList={{1576                      "is-syncing": syncBusy(),1577                      "is-ok": syncFlash() === "ok",1578                      "is-error": syncFlash() === "error",1579                    }}1580                    onClick={() => void handleHeaderSync()}1581                    disabled={syncBusy()}1582                    aria-label={`Sync now. ${syncLabel()}`}1583                    title={syncLabel()}1584                  >1585                    <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">1586                      <path d="M12.5 6A5.5 5.5 0 0 0 2.7 3.3" />1587                      <path d="M1.5 8A5.5 5.5 0 0 0 11.3 10.7" />1588                      <path d="M2.6 1v2.4h2.4" />1589                      <path d="M11.4 13v-2.4H9" />1590                    </svg>1591                    <span class={`peach-sync-pip is-${syncLight()}`} aria-hidden="true" />1592                  </button>1593                <button1594                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1595                  onClick={() => setView("settings")}1596                  aria-label="Settings"1597                >1598                  <svg width="14" height="14" viewBox="0 0 14 14" fill="none">1599                    <path1600                      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"1601                      stroke="currentColor"1602                      stroke-width="0.9"1603                    />1604                    <circle cx="7" cy="7" r="2.1" stroke="currentColor" stroke-width="0.9" />1605                  </svg>1606                </button>1607                <button1608                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1609                  onClick={handleAdd}1610                  aria-label="New entry"1611                >1612                  <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round">1613                    <path d="M5.5 1v9M1 5.5h9" />1614                  </svg>1615                </button>1616                <button1617                  class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn peach-lock-btn"1618                  onClick={() => void handleHeaderLock()}1619                  aria-label="Lock vault"1620                >1621                  <svg class="peach-lock-icon" width="14" height="16" viewBox="0 0 14 16" fill="none">1622                    <path1623                      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"1624                      stroke="currentColor"1625                      stroke-width="1"1626                      stroke-linecap="round"1627                    />1628                    <rect x="1.5" y="6" width="11" height="8.5" rx="2.2" stroke="currentColor" stroke-width="1" />1629                    <circle cx="7" cy="10.25" r="1" fill="currentColor" />1630                  </svg>1631                </button>1632              </div>1633            </header>16341635            <Show when={pendingProNotice() !== null}>1636              <div class="peach-pro-notice-banner">1637                <span>✦ {pendingProNotice()?.feature === "sync" ? "Sync" : "A Pro feature"} requires Peach Pro</span>1638                <button1639                  class="peach-pro-notice-link"1640                  onClick={() => {1641                    setUpgradeHighlight((pendingProNotice()?.feature as ProFeature) ?? null);1642                    setSettingsInitialSection("license");1643                    setView("settings");1644                    setPendingProNotice(null);1645                  }}1646                >1647                  Learn more →1648                </button>1649                <button class="peach-pro-notice-close" onClick={() => setPendingProNotice(null)} aria-label="Dismiss">✕</button>1650              </div>1651            </Show>16521653            <div class="peach-shell-body">1654              <div class="peach-shell-veil"></div>1655              <div class="peach-content-frame" data-content-phase={contentPhase()} classList={{ navigating: contentTransitioning() }}>1656                <EntryView1657                  entry={selectedEntry()}1658                  currentTabUrl={currentTabUrl()}1659                  entries={entries()}1660                  isPro={proStatus()}1661                  onDelete={handleDelete}1662                  onFieldSaved={() => void loadEntries()}1663                  onEscape={() => { setView("list"); }}1664                  onProGate={(feature) => {1665                    setUpgradeHighlight(feature);1666                    setSettingsInitialSection("license");1667                    setView("settings");1668                  }}1669                />1670              </div>16711672              <section class="peach-search-wrap" classList={{ "is-hidden-for-overlay": isShellOverlayOpen(), "is-collapsed": view() === "pair-device" }}>1673                <div class="peach-search-bar">1674                  <span class="peach-search-icon">1675                    <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round">1676                      <circle cx="5.5" cy="5.5" r="3.75" />1677                      <path d="M8.75 8.75L11.5 11.5" />1678                    </svg>1679                  </span>1680                  <input1681                    class="peach-search-input"1682                    placeholder="search vault..."1683                    autocomplete="off"1684                    aria-label="Search vault entries"1685                    onClick={openList}1686                    onFocus={openList}1687                    readOnly1688                  />1689                  <div class="peach-search-meta">1690                    <span class="peach-search-counter">1691                      {nonNoteEntries().length > 01692                        ? `${selectedIndex() + 1} / ${nonNoteEntries().length}`1693                        : "0 entries"}1694                    </span>1695                    <span class="peach-divider"></span>1696                    <button1697                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1698                      onClick={() => navigate(-1)}1699                      aria-label="Previous entry"1700                      disabled={nonNoteEntries().length === 0}1701                    >1702                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1703                        <path d="M5 1L1 5.5L5 10" />1704                      </svg>1705                    </button>1706                    <button1707                      class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"1708                      onClick={() => navigate(1)}1709                      aria-label="Next entry"1710                      disabled={nonNoteEntries().length === 0}1711                    >1712                      <svg width="6" height="11" viewBox="0 0 6 11" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">1713                        <path d="M1 1L5 5.5L1 10" />1714                      </svg>1715                    </button>1716                  </div>1717                </div>1718              </section>1719            </div>17201721            {/* Desktop: shown on demand via Show. Native sheet is rendered1722                via Portal below at the document root so its position:fixed1723                isn't trapped by .peach-shell's transform-based animations. */}1724            {/* Rare device-trust alerts; normal sync changes are silent. */}1725            <Show when={alertGroups().length > 0}>1726              <div class="peach-sync-alerts">1727                <For each={alertGroups()}>1728                  {([type, group]) => {1729                    const idx = () => Math.min(alertFlipIdx()[type] ?? 0, group.length - 1);1730                    return (1731                      <div class="peach-sync-alert">1732                        <Show when={group.length > 1}>1733                          <button1734                            class="peach-sync-alert-flip"1735                            type="button"1736                            aria-label="Previous"1737                            onClick={() => flipAlert(type, -1)}1738                          >‹</button>1739                        </Show>1740                        <span class="peach-sync-alert-text">⚠ {syncAlertText(group[idx()])}</span>1741                        <Show when={group.length > 1}>1742                          <span class="peach-sync-alert-count">{idx() + 1}/{group.length}</span>1743                          <button1744                            class="peach-sync-alert-flip"1745                            type="button"1746                            aria-label="Next"1747                            onClick={() => flipAlert(type, 1)}1748                          >›</button>1749                        </Show>1750                        <button1751                          class="peach-sync-alert-dismiss"1752                          type="button"1753                          aria-label={group.length > 1 ? "Dismiss all" : "Dismiss"}1754                          onClick={() => dismissAlertGroup(type)}1755                        >×</button>1756                      </div>1757                    );1758                  }}1759                </For>1760              </div>1761            </Show>17621763            <Show when={!isNativePlatform() && view() === "list"}>1764              <VaultView1765                entries={entries()}1766                selectedEntryId={selectedEntry()?.id}1767                currentTabDomain={currentTabDomain()}1768                sortOrder={sortOrder()}1769                searchSeed={listSearchSeed()}1770                searchSeedNonce={listSearchSeedNonce()}1771                onSelectEntry={handleSelectEntry}1772                onSortOrderChange={setSortOrder}1773                onAdd={handleAdd}1774                onClose={() => setView("entry")}1775                onOpenTrash={() => setView("trash")}1776                onDeleteMany={handleDeleteMany}1777              />1778            </Show>1779            <Show when={isNativePlatform() && hasVault()}>1780              <Portal>1781                <div1782                  class="peach-vault-sheet"1783                  classList={{ "is-peeking": view() === "entry", "is-open": view() === "list", "is-dragging": sheetTranslate() !== null }}1784                  style={(() => {1785                    const live = sheetTranslate();1786                    if (live === null) return undefined;1787                    return { transform: `translateY(${live}px)` };1788                  })()}1789                >1790                  <VaultView1791                    entries={entries()}1792                    selectedEntryId={selectedEntry()?.id}1793                    currentTabDomain={currentTabDomain()}1794                    sortOrder={sortOrder()}1795                    searchSeed={listSearchSeed()}1796                    searchSeedNonce={listSearchSeedNonce()}1797                    isNative={true}1798                    onSelectEntry={handleSelectEntry}1799                    onSortOrderChange={setSortOrder}1800                    onAdd={handleAdd}1801                    onClose={() => setView("entry")}1802                    onOpenTrash={() => setView("trash")}1803                    onDeleteMany={handleDeleteMany}1804                  />1805                </div>1806              </Portal>1807            </Show>1808            <Show when={view() === "settings" || settingsExiting()}>1809              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1810                <SettingsView1811                  entriesCount={entries().length}1812                  breachMonitoring={breachMonitoring()}1813                  lockOnClose={lockOnClose()}1814                  autoLockMinutes={autoLockMinutes()}1815                  trashRetentionDays={trashRetentionDays()}1816                  theme={theme()}1817                  accentColor={accentColor()}1818                  textSize={textSize()}1819                  reduceMotion={reduceMotion()}1820                  isPro={proStatus()}1821                  initialSection={settingsInitialSection()}1822                  upgradeHighlight={upgradeHighlight()}1823                  isExiting={settingsExiting()}1824                  onBreachMonitoringChange={applyBreachMonitoring}1825                  onLockOnCloseChange={applyLockOnClose}1826                  onAutoLockMinutesChange={applyAutoLockMinutes}1827                  onTrashRetentionChange={applyTrashRetention}1828                  onThemeChange={applyTheme}1829                  onAccentChange={applyAccentColor}1830                  onTextSizeChange={applyTextSize}1831                  onReduceMotionChange={applyReduceMotion}1832                  shortcuts={shortcutBindings()}1833                  onShortcutsChange={applyShortcuts}1834                  onLicenseChange={async () => {1835                    // After activation/deactivation: refresh Pro status,1836                    // re-load entries (defensive — signal state can drift if1837                    // the SW briefly restarts during the verify+save round-trip),1838                    // and replay the Pro celebration if this is the first time1839                    // a valid Pro license is seen on this device.1840                    await refreshProStatus();1841                    void loadEntries();1842                    const should = await sendMessage({ type: "SHOULD_PLAY_CELEBRATION" });1843                    if ((should as { ok: boolean; data?: boolean }).data === true) {1844                      await sendMessage({ type: "MARK_CELEBRATION_PLAYED" });1845                      setView("pro-celebration");1846                      window.setTimeout(() => setView("settings"), 2500);1847                    }1848                  }}1849                  onBack={() => {1850                    setSettingsExiting(true);1851                    window.setTimeout(() => {1852                      setSettingsExiting(false);1853                      setSettingsInitialSection(null);1854                      setUpgradeHighlight(null);1855                      handleBack();1856                    }, 200);1857                  }}1858                  onImport={() => setView("import")}1859                  onExport={() => setView("export")}1860                  onBreachCheckDone={loadEntries}1861                  onOpenHealth={openHealth}1862                  onOpenSyncPairing={() => { setSettingsInitialSection(settingsActiveCard()); setView("pair-device"); }}1863                  onOpenFileImport={handleOpenFileImport}1864                  onOpenPanic={() => setView("panic")}1865                  onOpenCodexGenerate={() => { setSettingsInitialSection(settingsActiveCard()); setView("codex-generate"); }}1866                  onOpenCodexRestore={() => setView("codex-restore")}1867                  onCardChange={setSettingsActiveCard}1868                  onProGate={(feature) => {1869                    setUpgradeHighlight(feature);1870                    setSettingsInitialSection("license");1871                  }}1872                />1873              </Suspense>1874            </Show>1875            <Show when={view() === "codex-generate"}>1876              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1877                <CodexGenerateView1878                  isPro={proStatus()}1879                  onBack={() => setView("settings")}1880                  onUpgradePro={() => { setSettingsInitialSection("license"); setView("settings"); }}1881                  onOpenSecurity={() => { setSettingsInitialSection("security"); setView("settings"); }}1882                  onVaultLocked={() => handleLock()}1883                />1884              </Suspense>1885            </Show>1886            <Show when={view() === "codex-restore"}>1887              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1888                <CodexRestoreView1889                  onBack={() => setView("lock")}1890                  onRestoreSuccess={async () => {1891                    // After restore the vault is unlocked; refresh entries1892                    // and route to the main vault list. handleUnlock is the1893                    // canonical post-unlock setup path.1894                    await handleUnlock();1895                  }}1896                />1897              </Suspense>1898            </Show>1899            <Show when={view() === "pair-device"}>1900              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1901                <PairDeviceView1902                  isPro={proStatus()}1903                  onProChanged={() => { void refreshProStatus(); }}1904                  onBack={() => setView("settings")}1905                  onLearnPro={() => { setSettingsInitialSection("license"); setView("settings"); }}1906                />1907              </Suspense>1908            </Show>1909            <Show when={view() === "add"}>1910              <AddView1911                entry={editEntry()}1912                entries={entries()}1913                onBack={handleBack}1914                onSave={handleSave}1915              />1916            </Show>1917            <Show when={view() === "import"}>1918              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1919                <ImportView onBack={() => setView("settings")} onImport={handleSave} />1920              </Suspense>1921            </Show>1922            <Show when={view() === "export"}>1923              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1924                <ExportView onBack={handleExportBack} />1925              </Suspense>1926            </Show>1927            <Show when={view() === "panic"}>1928              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1929                <PanicView1930                  onCancel={() => setView("settings")}1931                  onOpenExport={() => {1932                    setReturnToPanic(true);1933                    setView("export");1934                  }}1935                  onDestroyed={async () => {1936                    clearCanarySuppressions();1937                    setEntries([]);1938                    setSelectedEntry(null);1939                    setEditEntry(undefined);1940                    setHasVault(false);1941                    setOnboarded(false);1942                    setProStatus(false);1943                    setPendingPasskey(null);1944                    setUpgradeHighlight(null);1945                    setSettingsInitialSection(null);1946                    setPendingProNotice(null);1947                    setPendingCelebration(false);1948                    setReturnToPanic(false);1949                    setContentPhase("idle");1950                    setView("lock");1951                  }}1952                />1953              </Suspense>1954            </Show>1955            {/* Health stays mounted while editing an entry from it so1956                computeReused() doesn't rerun on every cancel/back. */}1957            <Show when={view() === "health" || (view() === "add" && editBackView() === "health")}>1958              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1959                <HealthView1960                  entries={entries()}1961                  isPro={proStatus()}1962                  onFixEntry={handleFixEntry}1963                  onBack={() => setView("settings")}1964                  onRefresh={loadEntries}1965                  hidden={view() !== "health"}1966                />1967              </Suspense>1968            </Show>1969            <Show when={view() === "trash"}>1970              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1971                <TrashView1972                  onBack={() => setView("list")}1973                  onRestored={() => void loadEntries()}1974                />1975              </Suspense>1976            </Show>1977            <Show when={showNotes()}>1978              <div class={`peach-notes-overlay${showNotes() ? " is-visible" : ""}`}>1979                <NotesMode1980                  notes={entries().filter((e) => e.type === "note")}1981                  initialNoteId={openNoteId()}1982                  onBack={() => { setShowNotes(false); setOpenNoteId(undefined); }}1983                  onNoteListChanged={() => void loadEntries()}1984                />1985              </div>1986            </Show>1987            <Show when={restoreView() === "file"}>1988              <Suspense fallback={<div class="peach-loading"><PeachWordmark /></div>}>1989                <ImportView1990                  mode="onboarding"1991                  replacesExistingVault={true}1992                  onBack={() => setRestoreView(null)}1993                  onImport={async () => {1994                    setRestoreView(null);1995                    await handleUnlock();1996                  }}1997                />1998              </Suspense>1999            </Show>2000            </section>2001            </Show>2002          </Show>2003        </Show>2004      </Show>2005      <Show when={showShortcutsHelp()}>2006        <ShortcutsHelpOverlay2007          bindings={shortcutBindings()}2008          onClose={() => setShowShortcutsHelp(false)}2009        />2010      </Show>2011    </div>2012  );2013}20142015function ShortcutsHelpOverlay(props: {2016  bindings: Record<ShortcutAction, Keybinding>;2017  onClose: () => void;2018}) {2019  return (2020    <div class="peach-shortcuts-help-backdrop" onClick={props.onClose}>2021      <div class="peach-shortcuts-help-card" onClick={(e) => e.stopPropagation()}>2022        <div class="peach-shortcuts-help-head">2023          <h3>Keyboard shortcuts</h3>2024          <button class="peach-shortcuts-help-close" onClick={props.onClose} aria-label="Close">✕</button>2025        </div>2026        <div class="peach-shortcuts-help-body">2027          <p class="peach-settings-sub-label">ENTRY VIEW</p>2028          <ul>2029            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "entry").map((d) => (2030              <li>2031                <span>{d.label}</span>2032                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2033              </li>2034            ))}2035          </ul>2036          <p class="peach-settings-sub-label">ANYWHERE</p>2037          <ul>2038            {SHORTCUT_DESCRIPTORS.filter((d) => d.scope === "global").map((d) => (2039              <li>2040                <span>{d.label}</span>2041                <kbd>{formatKeybinding(props.bindings[d.action])}</kbd>2042              </li>2043            ))}2044          </ul>2045        </div>2046      </div>2047    </div>2048  );2049}