ChirpSync.tsx

14.9 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  type PairingRole,38} from "../chirp-pair";39import { getLocalSubnet } from "../../shared/local-network";40import { isNativePlatform } from "../../shared/native";41import { openCapacitorPairingServer } from "../chirp-pair-capacitor";4243export interface ChirpSyncViewProps {44  isPro: boolean;45  onBack(): void;46  onLearnPro(): void;47}4849const STALE_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000;5051type Mode = "rest" | "pairing";5253export const ChirpSyncView: Component<ChirpSyncViewProps> = (props) => {54  const [devices, setDevices] = createSignal<PairedDevice[]>([]);55  const [mode, setMode] = createSignal<Mode>("rest");56  const [pairing, setPairing] = createSignal<PairingProgress>({ phase: "idle" });57  const [error, setError] = createSignal<string | null>(null);58  const [confirmUnpair, setConfirmUnpair] = createSignal<string | null>(null);5960  onMount(() => {61    void refresh();62  });6364  async function refresh(): Promise<void> {65    if (!props.isPro) return;66    const res = await sendMessage({ type: "CHIRP_LIST_PAIRED_DEVICES" });67    const data = (res as { ok: boolean; data?: { devices: PairedDevice[] } }).data;68    setDevices(data?.devices ?? []);69  }7071  async function handleStartPairing(): Promise<void> {72    setError(null);73    setPairing({ phase: "idle" });74    setMode("pairing");7576    const deps: ChirpPairingDeps = {77      onProgress: (p) => setPairing(p),78      fetchLocalIdentity: async () => {79        const res = await sendMessage({ type: "CHIRP_GET_LOCAL_IDENTITY" });80        const r = res as { ok: boolean; data?: Parameters<ChirpPairingDeps["onProgress"]>[0] & object; error?: string };81        if (!r.ok || !r.data) throw new Error(r.error ?? "identity_unavailable");82        // The handler returns a LocalIdentity; we trust the background's shape.83        return r.data as unknown as Awaited<ReturnType<ChirpPairingDeps["fetchLocalIdentity"]>>;84      },85      completePairing: async (paired) => {86        const res = await sendMessage({87          type: "CHIRP_COMPLETE_PAIRING",88          payload: { paired },89        });90        const r = res as { ok: boolean; error?: string };91        if (!r.ok) throw new Error(r.error ?? "complete_pairing_failed");92      },93      getLocalSubnet,94      openPairingTransport: async (endpoint) => {95        // Native WebSocket transport for the pairing-mode peer scan. The96        // chirp-pair orchestrator only uses send/receive/close, so a thin97        // adapter over the platform WebSocket suffices.98        return new Promise((resolve, reject) => {99          let ws: WebSocket;100          try {101            ws = new WebSocket(`ws://${endpoint.ip}:${endpoint.port}/`);102          } catch (err) {103            reject(err);104            return;105          }106          const inbox: Uint8Array[] = [];107          const waiters: Array<(b: Uint8Array) => void> = [];108          let closed = false;109          ws.binaryType = "arraybuffer";110          const timer = setTimeout(() => {111            try { ws.close(); } catch { /* ignore */ }112            reject(new Error("pairing_transport_timeout"));113          }, 2_000);114          ws.onopen = () => {115            clearTimeout(timer);116            resolve({117              async send(data: Uint8Array) {118                ws.send(data as Uint8Array<ArrayBuffer>);119              },120              receive(): Promise<Uint8Array> {121                if (closed) return Promise.reject(new Error("closed"));122                const v = inbox.shift();123                if (v) return Promise.resolve(v);124                return new Promise<Uint8Array>((res) => waiters.push(res));125              },126              async close() {127                try { ws.close(); } catch { /* ignore */ }128              },129            });130          };131          ws.onmessage = (ev) => {132            if (!(ev.data instanceof ArrayBuffer)) return;133            const bytes = new Uint8Array(ev.data);134            const w = waiters.shift();135            if (w) w(bytes); else inbox.push(bytes);136          };137          ws.onerror = () => {138            clearTimeout(timer);139            reject(new Error("pairing_transport_error"));140          };141          ws.onclose = () => {142            closed = true;143            while (waiters.length > 0) waiters.shift()!(new Uint8Array(0));144          };145        });146      },147    };148149    const role: PairingRole = isNativePlatform() ? "initiator" : "responder";150    if (role === "initiator") deps.openPairingServer = openCapacitorPairingServer;151152    try {153      await runChirpPairing(deps, role);154      await refresh();155    } catch (err) {156      if (err instanceof ChirpPairingFailure) {157        // The orchestrator already pushed the terminal phase into158        // `pairing()`; the inline error copy will render. No further159        // action needed — the user can tap "Try again" or "Cancel".160        return;161      }162      setError((err as Error).message);163      setMode("rest");164    }165  }166167  async function handleUnpair(deviceId: string): Promise<void> {168    await sendMessage({ type: "CHIRP_UNPAIR_DEVICE", payload: { deviceId } });169    setConfirmUnpair(null);170    await refresh();171  }172173  function relativeTime(when: number | undefined): string {174    if (!when) return "Not synced yet";175    const elapsed = Date.now() - when;176    if (elapsed < 60_000) return "Just now";177    const minutes = Math.floor(elapsed / 60_000);178    if (minutes < 60) return `${minutes} minute${minutes === 1 ? "" : "s"} ago`;179    const hours = Math.floor(minutes / 60);180    if (hours < 24) return `${hours} hour${hours === 1 ? "" : "s"} ago`;181    const days = Math.floor(hours / 24);182    if (days < 7) return `${days} day${days === 1 ? "" : "s"} ago`;183    return "Not seen recently";184  }185186  function isStale(d: PairedDevice): boolean {187    if (d.lastSyncedAt === undefined) return false;188    return Date.now() - d.lastSyncedAt > STALE_THRESHOLD_MS;189  }190191  // --- Sub-views --------------------------------------------------192193  const proGateView = () => (194    <div class="peach-chirp-settings peach-chirp-settings--gated">195      <header class="peach-chirp-settings-header">196        <button class="peach-icon-btn" aria-label="Back" onClick={() => props.onBack()}>197          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">198            <path d="M11 4 L5 9 L11 14" />199          </svg>200        </button>201        <h1 class="peach-chirp-settings-title">Sync</h1>202      </header>203      <div class="peach-chirp-pro-card">204        <div class="peach-chirp-pro-stage" aria-hidden="true">205          <svg class="peach-chirp-pro-chirp" viewBox="0 0 200 120" fill="none" stroke="currentColor"206               stroke-linecap="round" stroke-linejoin="round">207            <path d="M 124 36 Q 150 30 168 44" stroke-width="1.6" opacity="0.9" />208            <path d="M 128 52 Q 162 50 184 64" stroke-width="1.3" opacity="0.55" />209            <path d="M 124 68 Q 158 76 178 92" stroke-width="1.1" opacity="0.32" />210          </svg>211          <div class="peach-chirp-pro-bird-slot">212            <MobileBird pose="idle" />213          </div>214        </div>215        <h2 class="peach-chirp-pro-headline">A little bird that carries your vault</h2>216        <p class="peach-chirp-pro-body">217          Pairs over an inaudible chirp. Syncs locally across your devices.218          No codes, no servers, no cloud.219        </p>220        <button class="peach-btn peach-btn-primary peach-chirp-pro-cta" onClick={() => props.onLearnPro()}>221          Unlock with Peach Pro222        </button>223        <p class="peach-chirp-pro-foot">Peach Pro · one-time purchase</p>224      </div>225    </div>226  );227228  const restView = () => (229    <div class="peach-chirp-pair" data-phase="idle" role="region" aria-label="Sync">230      <header class="peach-chirp-head">231        <button class="peach-chirp-back" aria-label="Back" onClick={() => props.onBack()}>232          <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">233            <path d="M10 3 L5 8 L10 13" />234          </svg>235        </button>236        <div class="peach-chirp-title">Sync</div>237        <div class="peach-chirp-head-spacer" />238      </header>239240      <div class="peach-chirp-chip-row">241        <div class="peach-chirp-chip" data-phase="idle">242          <span class="peach-chirp-chip-dot" />243          <span class="peach-chirp-chip-text">ready</span>244        </div>245      </div>246247      <Show when={error()}>248        <div class="peach-chirp-settings-error" role="alert">{error()}</div>249      </Show>250251      <div class="peach-chirp-stage act-idle" aria-hidden="true">252        <div class="peach-chirp-bird-slot peach-chirp-bird-slot-desktop">253          <DesktopBird pose="idle" />254        </div>255        <div class="peach-chirp-bird-slot peach-chirp-bird-slot-mobile">256          <MobileBird pose="hidden" />257        </div>258      </div>259260      <div class="peach-chirp-copy-host">261        <div class="peach-chirp-copy peach-chirp-copy-rest">262          <div class="peach-chirp-headline">263            {devices().length === 0 ? "Bring your phone close" : "Sync is ready"}264          </div>265          <div class="peach-chirp-sub">266            {devices().length === 0267              ? "Peach pairs over a short, inaudible chirp — no codes, no servers."268              : "Pair another device, or manage the ones already connected below."}269          </div>270        </div>271      </div>272273      <Show when={devices().length > 0}>274        <section class="peach-chirp-paired-section">275          <h2 class="peach-chirp-paired-heading">Paired devices</h2>276          <ul class="peach-chirp-device-list">277            <For each={devices()}>278              {(d) => (279                <li class="peach-chirp-device-row" data-stale={isStale(d) ? "true" : "false"}>280                  <DeviceTypeIcon type={d.deviceType ?? "extension"} />281                  <div class="peach-chirp-device-info">282                    <span class="peach-chirp-device-name">{d.deviceName ?? "Unnamed device"}</span>283                    <span class="peach-chirp-device-meta">284                      {relativeTime(d.lastSyncedAt)}285                      <Show when={d.trustSource === "vouched"}>286                        <span class="peach-chirp-device-badge">Added automatically</span>287                      </Show>288                      <Show when={isStale(d)}>289                        <span class="peach-chirp-device-stale">Not seen recently</span>290                      </Show>291                    </span>292                  </div>293                  <Show294                    when={confirmUnpair() !== d.deviceId}295                    fallback={296                      <div class="peach-chirp-unpair-confirm">297                        <button class="peach-btn peach-btn-ghost peach-btn-sm" onClick={() => setConfirmUnpair(null)}>298                          Cancel299                        </button>300                        <button class="peach-btn peach-btn-destructive peach-btn-sm" onClick={() => void handleUnpair(d.deviceId)}>301                          Remove302                        </button>303                      </div>304                    }305                  >306                    <button307                      class="peach-icon-btn peach-chirp-device-remove"308                      aria-label={`Unpair ${d.deviceName}`}309                      onClick={() => setConfirmUnpair(d.deviceId)}310                    >311                      <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round">312                        <path d="M3 3 L11 11 M11 3 L3 11" />313                      </svg>314                    </button>315                  </Show>316                </li>317              )}318            </For>319          </ul>320        </section>321      </Show>322323      <div class="peach-chirp-action">324        <button class="peach-chirp-pair-start" onClick={() => void handleStartPairing()}>325          <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">326            <path d="M3 9 L9 3 L15 9" />327            <path d="M3 13 L9 7 L15 13" opacity="0.5" />328          </svg>329          <span>{devices().length === 0 ? "Pair a device" : "Pair another device"}</span>330        </button>331      </div>332333    </div>334  );335336  const pairingView = () => (337    <ChirpPairingFlow338      progress={pairing()}339      onCancel={() => setMode("rest")}340      onRetry={() => void handleStartPairing()}341      onDismiss={() => {342        setMode("rest");343        void refresh();344      }}345    />346  );347348  const currentMode = createMemo(() => {349    if (!props.isPro) return "gated";350    if (mode() === "pairing") return "pairing";351    return "rest";352  });353354  return (355    <Show356      when={currentMode() === "gated"}357      fallback={358        <Show when={currentMode() === "pairing"} fallback={restView()}>359          {pairingView()}360        </Show>361      }362    >363      {proGateView()}364    </Show>365  );366};367368const DeviceTypeIcon: Component<{ type: DeviceType }> = (props) => {369  return (370    <div class="peach-chirp-device-icon" data-type={props.type}>371      <Show when={props.type === "android" || props.type === "ios"}>372        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round">373          <rect x="6" y="2" width="8" height="16" rx="1.5" />374          <circle cx="10" cy="15.4" r="0.6" fill="currentColor" />375        </svg>376      </Show>377      <Show when={props.type === "extension" || props.type === "desktop"}>378        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round">379          <rect x="2" y="4" width="16" height="10" rx="1.4" />380          <path d="M7 17 L13 17" />381          <path d="M9 14 L9 17 M11 14 L11 17" />382        </svg>383      </Show>384    </div>385  );386};387