Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

13.1 KB
Raw Blame
/**
 * SyncToPeerButton — dropdown of federated PortOS peers that toggles per-record
 * peer-sync subscriptions for supported creative records.
 *
 * Sibling of `ShareToButton` (which targets cloud-synced share buckets); this
 * targets *other PortOS instances over Tailnet*. The contract is the same:
 *   - Filled CheckCircle when (recordKind, recordId) is subscribed to that peer.
 *   - Empty Circle otherwise.
 *   - Clicking checked → unsubscribe; clicking unchecked → subscribe (which
 *     triggers an initial push and then auto-pushes on every subsequent edit).
 *
 * Bidirectional sync: when this peer subscribes to a record on our end, the
 * receiver-side `applyIncomingPush` on the peer auto-creates a *reverse*
 * subscription (when their `directions` config allows it). The button doesn't
 * expose the reverse state — the user only manages the *outbound* direction
 * from this UI; the Instances page shows the bidirectional picture.
 *
 * Props:
 *   recordKind: 'universe' | 'series' | 'fableLoom'
 *   recordId: string  (required — the record's id)
 *   label?: string
 *   compact?: boolean
 */

import { useCallback, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { Cloud, Circle, CheckCircle2, Loader2 } from 'lucide-react';
import toast from '../ui/Toast';
import ListLoadError from '../ui/ListLoadError';
import useListResource from '../../hooks/useListResource.js';
import useClickOutside from '../../hooks/useClickOutside.js';
import usePopoverPosition, { VIEWPORT_PADDING } from '../../hooks/usePopoverPosition.js';
import {
  getInstances,
  listPeerSubscriptions,
  subscribeToPeer,
  unsubscribeFromPeer,
} from '../../services/api';

const MENU_WIDTH = 288; // w-72

// Only show enabled, online-or-connectable peers — Tailnet peers that are
// marked enabled but currently offline are still listed so the user can
// create the subscription now and let the push pipeline retry on reconnect.
const fetchPeers = () => getInstances({ silent: true })
  .then((instances) => (instances?.peers || []).filter((p) => p.enabled && p.instanceId));

export default function SyncToPeerButton({
  recordKind,
  recordId,
  label = 'Sync',
  compact = false,
  className = '',
}) {
  const [open, setOpen] = useState(false);
  const [busyPeerId, setBusyPeerId] = useState(null);
  const wrapperRef = useRef(null);
  // Peers + subscriptions reload on every open. A failed read of either is an
  // error row, never "no peers" / "not subscribed" — an unchecked row would let
  // a click create a duplicate subscription.
  const fetchSubscriptions = useCallback(
    () => listPeerSubscriptions({ recordKind, recordId }, { silent: true }).then((r) => r?.subscriptions || []),
    [recordKind, recordId],
  );
  const peersList = useListResource(fetchPeers, { enabled: open });
  const subscriptionsList = useListResource(fetchSubscriptions, { enabled: open });
  const peers = peersList.items;
  const subscriptions = subscriptionsList.items; // [{id, peerId, ...}]
  const setSubscriptions = subscriptionsList.setItems;
  const loading = peersList.state === 'loading' || subscriptionsList.state === 'loading';
  const loadFailed = peersList.state === 'error' ? peersList : subscriptionsList.state === 'error' ? subscriptionsList : null;
  const retryLoad = () => {
    if (peersList.state === 'error') peersList.retry();
    if (subscriptionsList.state === 'error') subscriptionsList.retry();
  };
  // The dropdown is portaled to <body> so it escapes each series/universe
  // card's stacking context (the cards have their own compositing layer, so an
  // in-card `absolute z-30` popover is painted UNDER the next card).
  // `usePopoverPosition` owns the fixed placement: right-aligned to the trigger,
  // clamped into the viewport, flipped above when there is no room below, and
  // re-flowed on capture-phase scroll. The peer list changes the menu's height
  // as it loads, so it re-measures via contentDeps.
  const { triggerRef, popoverRef, style: menuStyle } = usePopoverPosition({
    open,
    width: MENU_WIDTH,
    minWidth: 220,
    gap: 4,
    position: 'below',
    contentDeps: [loading, loadFailed, peers.length, subscriptions.length]
  });

  // Per-record subscribability — mirrors server-side guards in peerSync.js
  // (peerAllowsOutbound + peerHasCategory). Without this triple gate the
  // UI would let the user subscribe to a peer that silently rejects every
  // push (with peer-disabled, peer-disallows-outbound, or
  // category-disabled), leaving the row checked but no records ever landing.
  const categoryMeta = {
    universe: { key: 'universe', label: 'Universe' },
    series: { key: 'pipeline', label: 'Pipeline' },
    fableLoom: { key: 'fableLoom', label: 'FableLoom' },
  }[recordKind] || { key: recordKind, label: recordKind };
  const requiredCategory = categoryMeta.key;
  const peerCanReceiveOutbound = (peer) => {
    if (!peer) return false;
    // Global sync flag off → server's pushRecordToPeer refuses.
    if (peer.syncEnabled === false) return false;
    // Inbound-only direction → outbound pushes silently dropped.
    if (Array.isArray(peer.directions) && peer.directions.length > 0
        && !peer.directions.includes('outbound')) return false;
    // A full-sync peer mirrors every category, so it can always receive.
    if (peer.fullSync === true) return true;
    const cats = peer.syncCategories;
    return !!cats && typeof cats === 'object' && cats[requiredCategory] === true;
  };

  // Close on Escape and return focus to the trigger so keyboard users don't
  // have to Tab back through the popover content.
  useEffect(() => {
    if (!open) return undefined;
    const onKey = (e) => {
      if (e.key === 'Escape') {
        setOpen(false);
        triggerRef.current?.focus();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open]);

  // Both refs: the menu lives in a portal outside wrapperRef, so a trigger-only
  // containment check would read clicks on the menu as outside.
  useClickOutside([wrapperRef, popoverRef], open, () => setOpen(false));

  const subscriptionForPeer = (peerInstanceId) =>
    subscriptions.find((s) => s.peerId === peerInstanceId) || null;


  const handleToggle = async (peer) => {
    setBusyPeerId(peer.instanceId);
    const existing = subscriptionForPeer(peer.instanceId);
    if (existing) {
      // silent:true — the catch below already owns the error toast, so the
      // apiCore helper must not fire its own (per AGENTS.md "Custom catch ⇒
      // silent: true" rule). Otherwise the user sees two toasts on failure.
      const ok = await unsubscribeFromPeer(existing.id, { silent: true }).catch((err) => {
        toast.error(err.message || `Unsync from ${peer.name} failed`);
        return null;
      });
      if (ok) {
        setSubscriptions((prev) => prev.filter((s) => s.id !== existing.id));
        toast.success(`Stopped syncing to ${peer.name}`);
      }
    } else {
      const result = await subscribeToPeer({
        peerId: peer.instanceId,
        recordKind,
        recordId,
      }, { silent: true }).catch((err) => {
        toast.error(err.message || `Sync to ${peer.name} failed`);
        return null;
      });
      if (result?.subscription) {
        setSubscriptions((prev) => [...prev, result.subscription]);
        toast.success(`Syncing to ${peer.name} — edits will push automatically`);
      }
    }
    setBusyPeerId(null);
  };

  const nothingToSync = !recordId;

  return (
    <div ref={wrapperRef} className={`relative inline-block ${className}`}>
      <button
        ref={triggerRef}
        type="button"
        onClick={() => setOpen((v) => !v)}
        disabled={nothingToSync}
        aria-expanded={open}
        aria-haspopup="true"
        className={`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs border border-port-border hover:border-port-accent/40 text-gray-300 hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${compact ? 'min-h-[44px] min-w-[44px] justify-center p-1.5' : ''}`}
        title={nothingToSync ? 'Nothing to sync' : 'Sync to a peer instance'}
      >
        <Cloud size={12} />
        {!compact && <span>{label}</span>}
      </button>

      {open && createPortal(
        <div
          ref={popoverRef}
          style={{
            position: 'fixed',
            left: menuStyle?.left ?? `${VIEWPORT_PADDING}px`,
            top: menuStyle?.top ?? `${VIEWPORT_PADDING}px`,
            width: menuStyle?.width ?? `${MENU_WIDTH}px`,
            visibility: menuStyle ? 'visible' : 'hidden'
          }}
          className="z-50 bg-port-card border border-port-border rounded-lg shadow-lg overflow-hidden"
        >
          <div className="px-3 py-2 text-[10px] uppercase tracking-wider text-gray-500 border-b border-port-border">
            Subscribe to peer
          </div>
          {loading ? (
            <div className="px-3 py-3 text-xs text-gray-500 flex items-center gap-2">
              <Loader2 size={12} className="animate-spin" /> Loading peers…
            </div>
          ) : loadFailed ? (
            <ListLoadError what={loadFailed === peersList ? 'peers' : 'subscriptions'} error={loadFailed.error} onRetry={retryLoad} className="m-2" />
          ) : peers.length === 0 ? (
            <div className="px-3 py-3 text-xs text-gray-500">
              No peers configured. <a href="/instances" className="text-port-accent hover:underline">Add one</a>.
            </div>
          ) : (
            <ul className="max-h-72 overflow-y-auto">
              {peers.map((p) => {
                const subscribed = !!subscriptionForPeer(p.instanceId);
                const busy = busyPeerId === p.instanceId;
                // Disable when the peer can't actually receive outbound
                // pushes for this record kind — global sync off, inbound-
                // only directions, or the per-record category is off. UI
                // mirrors server-side guards in pushRecordToPeer.
                const canSync = peerCanReceiveOutbound(p);
                const categoryLabel = categoryMeta.label;
                // Compute the most-specific reason for the inline hint.
                const disabledReason = !canSync
                  ? (p.syncEnabled === false
                      ? 'Sync disabled for this peer'
                      : (Array.isArray(p.directions) && p.directions.length > 0
                          && !p.directions.includes('outbound')
                          ? 'Peer is inbound-only'
                          : `${categoryLabel} sync off`))
                  : null;
                // Allow UNSUBSCRIBE even when the peer can no longer receive
                // outbound pushes — the user may have a stranded subscription
                // from when sync was on, and disabling the row would leave
                // them unable to remove it. Subscribe-from-scratch still
                // requires canSync.
                const rowDisabled = busy || (!canSync && !subscribed);
                const titleHint = subscribed && !canSync
                  ? `Unsubscribe — pushes are currently blocked (${disabledReason || 'sync disabled'}), but you can still remove the subscription.`
                  : (disabledReason ? `${disabledReason}. Enable on the Instances page first.` : undefined);
                return (
                  <li key={p.instanceId}>
                    <button
                      type="button"
                      onClick={() => handleToggle(p)}
                      disabled={rowDisabled}
                      title={titleHint}
                      className="w-full text-left px-3 py-2 hover:bg-port-bg disabled:opacity-50 disabled:cursor-not-allowed flex items-start gap-2"
                    >
                      <span className="mt-0.5 shrink-0">
                        {busy
                          ? <Loader2 size={14} className="animate-spin text-port-accent" />
                          : subscribed
                            ? <CheckCircle2 size={14} className="text-port-success" />
                            : <Circle size={14} className="text-gray-600" />}
                      </span>
                      <div className="flex-1 min-w-0">
                        <div className="text-sm text-white truncate">{p.name || p.host || p.address || 'Unnamed peer'}</div>
                        <div className="text-[10px] text-gray-500 truncate">
                          {p.status === 'online' ? 'online' : p.status || 'offline'}
                          {p.host ? ` · ${p.host}` : p.address ? ` · ${p.address}` : ''}
                          {disabledReason && ` · ${disabledReason}`}
                        </div>
                      </div>
                    </button>
                  </li>
                );
              })}
            </ul>
          )}
          {subscriptions.length > 0 && (
            <div className="px-3 py-2 text-[10px] text-gray-500 border-t border-port-border">
              Subscribed peers receive your edits automatically; their edits flow back if their config allows.
            </div>
          )}
        </div>,
        document.body,
      )}
    </div>
  );
}