ChirpSync.tsx

14.8 KB · raw

1// ChirpSync — the v3 Settings → Sync surface.2//3// Three modes the user can be in:4//5//   1. Locked behind Pro (free user) — soft upsell card, "Learn more" routes6//      to the License section.7//   2. Idle — list of paired devices + "Pair a device" hero button. Stale8//      devices (>7 days since last sync) show a soft warning indicator;9//      vouched devices (received via device manifest, v2 brief §4.2) show10//      an "Added automatically" badge.11//   3. Pairing — ChirpPairingFlow takes over the full surface and drives12//      the three-act bird animation in lockstep with the audio protocol.13//14// The pairing orchestrator lives in `popup/chirp-pair.ts`; this view is15// the binding between that orchestrator, the background-message16// CHIRP_* handlers, and the Settings navigation surrounding it.1718import {19  Component,20  Show,21  createMemo,22  createSignal,23  For,24  onMount,25} from "solid-js";26import { sendMessage } from "../../shared/bridge";27import type {28  DeviceType,29  PairedDevice,30  PairingProgress,31} from "../../shared/sync-types";32import { ChirpPairingFlow, DesktopBird, MobileBird } from "../components/ChirpPairingFlow";33import {34  ChirpPairingFailure,35  runChirpPairing,36  type ChirpPairingDeps,37} from "../chirp-pair";38import { getLocalSubnet } from "../../shared/local-network";39import { PeachMark } from "../components/PeachMark";4041export interface ChirpSyncViewProps {42  isPro: boolean;43  onBack(): void;44  onLearnPro(): void;45}4647const STALE_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000;4849type Mode = "rest" | "pairing";5051export const ChirpSyncView: Component<ChirpSyncViewProps> = (props) => {52  const [devices, setDevices] = createSignal<PairedDevice[]>([]);53  const [mode, setMode] = createSignal<Mode>("rest");54  const [pairing, setPairing] = createSignal<PairingProgress>({ phase: "idle" });55  const [error, setError] = createSignal<string | null>(null);56  const [confirmUnpair, setConfirmUnpair] = createSignal<string | null>(null);5758  onMount(() => {59    void refresh();60  });6162  async function refresh(): Promise<void> {63    if (!props.isPro) return;64    const res = await sendMessage({ type: "CHIRP_LIST_PAIRED_DEVICES" });65    const data = (res as { ok: boolean; data?: { devices: PairedDevice[] } }).data;66    setDevices(data?.devices ?? []);67  }6869  async function handleStartPairing(): Promise<void> {70    setError(null);71    setPairing({ phase: "idle" });72    setMode("pairing");7374    const deps: ChirpPairingDeps = {75      onProgress: (p) => setPairing(p),76      fetchLocalIdentity: async () => {77        const res = await sendMessage({ type: "CHIRP_GET_LOCAL_IDENTITY" });78        const r = res as { ok: boolean; data?: Parameters<ChirpPairingDeps["onProgress"]>[0] & object; error?: string };79        if (!r.ok || !r.data) throw new Error(r.error ?? "identity_unavailable");80        // The handler returns a LocalIdentity; we trust the background's shape.81        return r.data as unknown as Awaited<ReturnType<ChirpPairingDeps["fetchLocalIdentity"]>>;82      },83      completePairing: async (paired) => {84        const res = await sendMessage({85          type: "CHIRP_COMPLETE_PAIRING",86          payload: { paired },87        });88        const r = res as { ok: boolean; error?: string };89        if (!r.ok) throw new Error(r.error ?? "complete_pairing_failed");90      },91      getLocalSubnet,92      openPairingTransport: async (endpoint) => {93        // Native WebSocket transport for the pairing-mode peer scan. The94        // chirp-pair orchestrator only uses send/receive/close, so a thin95        // adapter over the platform WebSocket suffices.96        return new Promise((resolve, reject) => {97          let ws: WebSocket;98          try {99            ws = new WebSocket(`ws://${endpoint.ip}:${endpoint.port}/`);100          } catch (err) {101            reject(err);102            return;103          }104          const inbox: Uint8Array[] = [];105          const waiters: Array<(b: Uint8Array) => void> = [];106          let closed = false;107          ws.binaryType = "arraybuffer";108          const timer = setTimeout(() => {109            try { ws.close(); } catch { /* ignore */ }110            reject(new Error("pairing_transport_timeout"));111          }, 2_000);112          ws.onopen = () => {113            clearTimeout(timer);114            resolve({115              async send(data: Uint8Array) {116                ws.send(data as Uint8Array<ArrayBuffer>);117              },118              receive(): Promise<Uint8Array> {119                if (closed) return Promise.reject(new Error("closed"));120                const v = inbox.shift();121                if (v) return Promise.resolve(v);122                return new Promise<Uint8Array>((res) => waiters.push(res));123              },124              async close() {125                try { ws.close(); } catch { /* ignore */ }126              },127            });128          };129          ws.onmessage = (ev) => {130            if (!(ev.data instanceof ArrayBuffer)) return;131            const bytes = new Uint8Array(ev.data);132            const w = waiters.shift();133            if (w) w(bytes); else inbox.push(bytes);134          };135          ws.onerror = () => {136            clearTimeout(timer);137            reject(new Error("pairing_transport_error"));138          };139          ws.onclose = () => {140            closed = true;141            while (waiters.length > 0) waiters.shift()!(new Uint8Array(0));142          };143        });144      },145    };146147    try {148      await runChirpPairing(deps);149      await refresh();150    } catch (err) {151      if (err instanceof ChirpPairingFailure) {152        // The orchestrator already pushed the terminal phase into153        // `pairing()`; the inline error copy will render. No further154        // action needed — the user can tap "Try again" or "Cancel".155        return;156      }157      setError((err as Error).message);158      setMode("rest");159    }160  }161162  async function handleUnpair(deviceId: string): Promise<void> {163    await sendMessage({ type: "CHIRP_UNPAIR_DEVICE", payload: { deviceId } });164    setConfirmUnpair(null);165    await refresh();166  }167168  function relativeTime(when: number | undefined): string {169    if (!when) return "Not synced yet";170    const elapsed = Date.now() - when;171    if (elapsed < 60_000) return "Just now";172    const minutes = Math.floor(elapsed / 60_000);173    if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;174    const hours = Math.floor(minutes / 60);175    if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;176    const days = Math.floor(hours / 24);177    if (days < 7) return `${days} day${days === 1 ? "" : "s"} ago`;178    return "Not seen recently";179  }180181  function isStale(d: PairedDevice): boolean {182    if (d.lastSyncedAt === undefined) return false;183    return Date.now() - d.lastSyncedAt > STALE_THRESHOLD_MS;184  }185186  // --- Sub-views --------------------------------------------------187188  const proGateView = () => (189    <div class="peach-chirp-settings peach-chirp-settings--gated">190      <header class="peach-chirp-settings-header">191        <button class="peach-icon-btn" aria-label="Back" onClick={() => props.onBack()}>192          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">193            <path d="M11 4 L5 9 L11 14" />194          </svg>195        </button>196        <h1 class="peach-chirp-settings-title">Sync</h1>197      </header>198      <div class="peach-chirp-pro-card">199        <div class="peach-chirp-pro-illustration">200          <PeachMark class="peach-chirp-pro-mark" />201          <svg class="peach-chirp-pro-waves" width="200" height="80" viewBox="0 0 200 80" fill="none" stroke="currentColor" stroke-width="1.4">202            <path d="M 30 40 Q 100 10 170 40" />203            <path d="M 30 50 Q 100 20 170 50" opacity="0.6" />204            <path d="M 30 60 Q 100 30 170 60" opacity="0.3" />205          </svg>206        </div>207        <h2 class="peach-chirp-pro-headline">Chirp Sync is a Peach Pro feature</h2>208        <p class="peach-chirp-pro-body">209          Pair your phone with your laptop using a quick inaudible chirp —210          then your vault stays in sync across devices on your local network.211          No QR codes, no relay servers, no cloud accounts.212        </p>213        <button class="peach-btn peach-btn-primary" onClick={() => props.onLearnPro()}>214          Learn more about Peach Pro215        </button>216      </div>217    </div>218  );219220  const restView = () => (221    <div class="peach-chirp-pair" data-phase="idle" role="region" aria-label="Sync">222      <header class="peach-chirp-head">223        <button class="peach-chirp-back" aria-label="Back" onClick={() => props.onBack()}>224          <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">225            <path d="M10 3 L5 8 L10 13" />226          </svg>227        </button>228        <div class="peach-chirp-title">Sync</div>229        <div class="peach-chirp-head-spacer" />230      </header>231232      <div class="peach-chirp-chip-row">233        <div class="peach-chirp-chip" data-phase="idle">234          <span class="peach-chirp-chip-dot" />235          <span class="peach-chirp-chip-text">ready</span>236        </div>237      </div>238239      <Show when={error()}>240        <div class="peach-chirp-settings-error" role="alert">{error()}</div>241      </Show>242243      <div class="peach-chirp-stage act-idle" aria-hidden="true">244        <div class="peach-chirp-bird-slot peach-chirp-bird-slot-desktop">245          <DesktopBird pose="idle" />246        </div>247        <div class="peach-chirp-bird-slot peach-chirp-bird-slot-mobile">248          <MobileBird pose="hidden" />249        </div>250      </div>251252      <div class="peach-chirp-copy-host">253        <div class="peach-chirp-copy peach-chirp-copy-rest">254          <div class="peach-chirp-headline">255            {devices().length === 0 ? "Pair your phone with this Peach" : "Sync is ready"}256          </div>257          <div class="peach-chirp-sub">258            {devices().length === 0259              ? "Hold your phone near your laptop. Peach will chirp once, inaudibly, and pair automatically."260              : "Pair another device, or manage the devices already connected below."}261          </div>262        </div>263      </div>264265      <div class="peach-chirp-action">266        <button class="peach-chirp-pair-start" onClick={() => void handleStartPairing()}>267          <svg width="16" height="16" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">268            <path d="M3 9 L9 3 L15 9" />269            <path d="M3 13 L9 7 L15 13" opacity="0.5" />270          </svg>271          <span>{devices().length === 0 ? "Pair a device" : "Pair another device"}</span>272        </button>273      </div>274275      <Show when={devices().length > 0}>276        <section class="peach-chirp-paired-section">277          <h2 class="peach-chirp-paired-heading">Paired devices</h2>278          <ul class="peach-chirp-device-list">279            <For each={devices()}>280              {(d) => (281                <li class="peach-chirp-device-row" data-stale={isStale(d) ? "true" : "false"}>282                  <DeviceTypeIcon type={d.deviceType ?? "extension"} />283                  <div class="peach-chirp-device-info">284                    <span class="peach-chirp-device-name">{d.deviceName ?? "Unnamed device"}</span>285                    <span class="peach-chirp-device-meta">286                      {relativeTime(d.lastSyncedAt)}287                      <Show when={d.trustSource === "vouched"}>288                        <span class="peach-chirp-device-badge">Added automatically</span>289                      </Show>290                      <Show when={isStale(d)}>291                        <span class="peach-chirp-device-stale">Not seen recently</span>292                      </Show>293                    </span>294                  </div>295                  <Show296                    when={confirmUnpair() !== d.deviceId}297                    fallback={298                      <div class="peach-chirp-unpair-confirm">299                        <button class="peach-btn peach-btn-ghost peach-btn-sm" onClick={() => setConfirmUnpair(null)}>300                          Cancel301                        </button>302                        <button class="peach-btn peach-btn-destructive peach-btn-sm" onClick={() => void handleUnpair(d.deviceId)}>303                          Remove304                        </button>305                      </div>306                    }307                  >308                    <button309                      class="peach-icon-btn peach-chirp-device-remove"310                      aria-label={`Unpair ${d.deviceName}`}311                      onClick={() => setConfirmUnpair(d.deviceId)}312                    >313                      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round">314                        <path d="M3 3 L11 11 M11 3 L3 11" />315                      </svg>316                    </button>317                  </Show>318                </li>319              )}320            </For>321          </ul>322        </section>323      </Show>324325      <footer class="peach-chirp-foot">326        <div class="peach-chirp-foot-divider" />327        <div class="peach-chirp-foot-text">328          Chirp Sync stays on your local network. No relay servers, no cloud329          accounts — just your devices in the same room.330        </div>331      </footer>332    </div>333  );334335  const pairingView = () => (336    <ChirpPairingFlow337      progress={pairing()}338      onCancel={() => setMode("rest")}339      onRetry={() => void handleStartPairing()}340      onDismiss={() => {341        setMode("rest");342        void refresh();343      }}344    />345  );346347  const currentMode = createMemo(() => {348    if (!props.isPro) return "gated";349    if (mode() === "pairing") return "pairing";350    return "rest";351  });352353  return (354    <Show355      when={currentMode() === "gated"}356      fallback={357        <Show when={currentMode() === "pairing"} fallback={restView()}>358          {pairingView()}359        </Show>360      }361    >362      {proGateView()}363    </Show>364  );365};366367const DeviceTypeIcon: Component<{ type: DeviceType }> = (props) => {368  return (369    <div class="peach-chirp-device-icon" data-type={props.type}>370      <Show when={props.type === "android" || props.type === "ios"}>371        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round">372          <rect x="6" y="2" width="8" height="16" rx="1.5" />373          <circle cx="10" cy="15.4" r="0.6" fill="currentColor" />374        </svg>375      </Show>376      <Show when={props.type === "extension" || props.type === "desktop"}>377        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round">378          <rect x="2" y="4" width="16" height="10" rx="1.4" />379          <path d="M7 17 L13 17" />380          <path d="M9 14 L9 17 M11 14 L11 17" />381        </svg>382      </Show>383    </div>384  );385};386