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

25.5 KB
Raw Blame
import { useState, useEffect, useCallback } from 'react';
import { RefreshCw, Download, XCircle, Check, Loader, Loader2, AlertTriangle, Trash2, ExternalLink, Tag, GitFork, GitBranch } from 'lucide-react';
import toast from '../../ui/Toast';
import BrailleSpinner from '../../BrailleSpinner';
import MarkdownOutput from '../../cos/MarkdownOutput';
import Banner from '../../ui/Banner';
import AutoUpdatePanel from './AutoUpdatePanel';
import NodeRuntimePanel from './NodeRuntimePanel';
import * as api from '../../../services/api';
import socket from '../../../services/socket';
import { formatDateTime, formatDateNumeric, formatTimeOfDaySeconds } from '../../../utils/formatters';
import { useSocketResource } from '../../../hooks/useSocketResource';
import { usePortosRestartWatch } from '../../../hooks/usePortosRestartWatch';

const STATUS_EVENTS = ['portos:update:checked', 'portos:update:available', 'portos:auto-update:changed', 'system:activity'];

const STEP_LABELS = {
  starting: 'Starting update',
  'node-install': 'Installing Node.js',
  'node-default': 'Setting nvm default',
  'pm2-cli': 'Installing pm2 CLI',
  'node-pin': 'Pinning PortOS to Node',
  'git-pull': 'Pulling latest changes',
  'pm2-stop': 'Stopping apps',
  'npm-install': 'Installing dependencies',
  setup: 'Running setup',
  ffmpeg: 'Checking ffmpeg',
  migrations: 'Running migrations',
  'network-setup': 'Checking secure access',
  build: 'Building client',
  restart: 'Restarting PortOS',
  restarting: 'Restarting PortOS',
  verify: 'Verifying PortOS is back',
  complete: 'Complete'
};

function StepIndicator({ status }) {
  if (status === 'running') return <Loader size={14} className="text-port-accent animate-spin" />;
  if (status === 'done') return <Check size={14} className="text-port-success" />;
  if (status === 'error') return <XCircle size={14} className="text-port-error" />;
  // The post-restart health check reports 'warning' when it could not confirm
  // the server came back — the update finished, but the install may be down.
  if (status === 'warning') return <AlertTriangle size={14} className="text-port-warning" />;
  return <span className="w-3.5 h-3.5 rounded-full border border-gray-600 inline-block" />;
}

export default function UpdateTab() {
  const { data: status, loading, refetch: fetchStatus, updateData: setStatus } = useSocketResource(
    () => api.getUpdateStatus({ silent: true }), { events: STATUS_EVENTS }
  );
  const [checking, setChecking] = useState(false);
  const [updating, setUpdating] = useState(false);
  const [steps, setSteps] = useState([]);
  const [updateError, setUpdateError] = useState(null);
  const [syncingFork, setSyncingFork] = useState(false);
  const [forkSyncError, setForkSyncError] = useState(null);

  // There is no completion event to wait for once update.sh pm2-deletes this
  // server, so the restart handoff — arming, health polling, the reload — lives
  // in the shared watch that every PortOS self-update surface uses.
  const { polling, captureBaseline } = usePortosRestartWatch({
    active: updating,
    onRestart: () => setUpdating(false),
    onFailure: ({ message }) => {
      setUpdating(false);
      if (message) setUpdateError(message);
    },
  });

  // Step frames for the activity list. The restart handoff these frames end in
  // is the shared watch's job, not this component's.
  useEffect(() => {
    const handleStep = ({ step, status: stepStatus, message }) => {
      setSteps(prev => {
        const existing = prev.findIndex(s => s.step === step);
        const entry = { step, status: stepStatus, message, timestamp: Date.now() };
        if (existing >= 0) {
          const updated = [...prev];
          updated[existing] = entry;
          return updated;
        }
        return [...prev, entry];
      });
    };

    socket.on('portos:update:step', handleStep);
    return () => socket.off('portos:update:step', handleStep);
  }, []);


  const handleCheck = async () => {
    setChecking(true);
    const result = await api.checkForUpdate().catch(() => null);
    if (result) setStatus(prev => ({ ...(prev ?? {}), ...result }));
    setChecking(false);
  };

  // `fromStatus` lets callers (e.g. handleSyncForkAndUpdate) pass the freshly
  // fetched status object instead of relying on the closure capture — `setStatus`
  // only schedules a render; the action passes its fresh response directly.
  // `launch` lets the Node runtime panel start its restart through the same
  // baseline, step list and restart watch as a release update.
  const runUpdate = useCallback(async (opts = {}, fromStatus = null, launch = api.executePortosUpdate) => {
    const s = fromStatus || status;
    // Record the version and uptime of the still-running server, so even an
    // instant restart (whose first post-restart poll already reports a small
    // uptime) is detected as a drop below this pre-update value.
    await captureBaseline(s?.currentVersion);
    setUpdating(true);
    setSteps([]);
    setUpdateError(null);
    const result = await launch(opts).catch(err => {
      setUpdateError(err.message);
      setUpdating(false);
      return null;
    });
    // A pm2 CLI refresh finishes without restarting PortOS.
    if (result?.restart === false) setUpdating(false);
    return result;
  }, [captureBaseline, status]);

  const handleUpdate = () => runUpdate();

  const handleUpdateFromForkAsIs = () => runUpdate({ acknowledgeFork: true });

  // Reconcile a half-updated install (issue #1779) — same machinery as a normal
  // update, but `reconcile: true` lets the server run update.sh even with no
  // newer release. Fork-aware variants mirror the release-update buttons.
  const handleReconcile = () => runUpdate({ reconcile: true });

  const handleReconcileFromForkAsIs = () => runUpdate({ acknowledgeFork: true, reconcile: true });

  // Shared fork-sync-then-run: syncs the fork, then runs update/reconcile with
  // the freshly fetched status. `extraOpts` distinguishes update vs reconcile.
  const syncForkThenRun = async (extraOpts = {}) => {
    setSyncingFork(true);
    setForkSyncError(null);
    const synced = await api.syncPortosFork({}, { silent: true }).catch(err => {
      setForkSyncError(err.message);
      return null;
    });
    setSyncingFork(false);
    if (!synced) return;
    if (synced.alreadyUpToDate) {
      toast.success(`Fork already up to date with ${status?.upstream?.fullName || 'upstream'}`);
    } else {
      toast.success(`Synced ${synced.fullName} from ${synced.source}`);
    }
    const fresh = await api.getUpdateStatus({ silent: true }).catch(() => null);
    if (!fresh) return;
    setStatus(fresh);
    await runUpdate(extraOpts, fresh);
  };

  const handleSyncForkAndUpdate = () => syncForkThenRun({});

  const handleSyncForkAndReconcile = () => syncForkThenRun({ reconcile: true });

  const handleSyncForkOnly = async () => {
    setSyncingFork(true);
    setForkSyncError(null);
    const synced = await api.syncPortosFork({}, { silent: true }).catch(err => {
      setForkSyncError(err.message);
      return null;
    });
    setSyncingFork(false);
    if (!synced) return;
    toast.success(
      synced.alreadyUpToDate
        ? `Fork already up to date with ${status?.upstream?.fullName || 'upstream'}`
        : `Synced ${synced.fullName} from ${synced.source}`
    );
    await fetchStatus();
  };

  const handleIgnore = async (version) => {
    const result = await api.ignoreUpdateVersion(version).catch(() => null);
    if (!result) return;
    fetchStatus();
    toast.success(`v${version} ignored`);
  };

  const handleClearIgnored = async () => {
    const result = await api.clearIgnoredVersions().catch(() => null);
    if (!result) return;
    fetchStatus();
    toast.success('Ignored versions cleared');
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <BrailleSpinner text="Loading update status" />
      </div>
    );
  }

  const release = status?.latestRelease;
  const hasUpdate = status?.updateAvailable;
  const remote = status?.remoteInfo;
  const upstreamName = status?.upstream?.fullName || 'atomantic/PortOS';
  const isFork = !!remote?.isFork;
  const lastForkSync = status?.lastForkSync;
  // Server is the source of truth for the freshness window — don't
  // re-implement the time math here.
  const forkSyncFresh = !!status?.forkSyncFresh;

  // Install-sync state (issue #1779) — surfaces a half-updated install (bare
  // `git pull`, no ./update.sh). Distinct from "a new release is available".
  const installState = status?.installState;
  const outOfSync = !!installState?.outOfSync;

  // Live CoS agents make a restart destructive — updating/reconciling pm2-restarts
  // PortOS and severs any in-flight agent. When agents are running we suppress the
  // reconcile prompt and the update actions (the server also hard-rejects with 409
  // AGENTS_ACTIVE) and show a notice instead.
  const activeCosAgents = status?.activeCosAgents || 0;
  const agentsActive = activeCosAgents > 0;
  const installIssues = [];
  if (installState?.runningStaleCode) {
    installIssues.push('Running code is older than what’s checked out — a restart/update is required.');
  }
  if (installState?.staleDeps?.stale) {
    const ws = (installState.staleDeps.workspaces || []).filter(w => w.stale).map(w => w.name);
    installIssues.push(`Dependencies are out of date${ws.length ? ` (${ws.join(', ')})` : ''} — run update.sh to npm install.`);
  }
  if (installState?.staleBuild === true) {
    installIssues.push('The served client build is older than the UI source — a rebuild is needed.');
  }
  if (installState?.pendingMigrations?.count > 0) {
    const n = installState.pendingMigrations.count;
    installIssues.push(`${n} pending data migration${n === 1 ? '' : 's'} not yet applied.`);
  }
  if (installState?.submodules?.stale) {
    const n = installState.submodules.paths?.length || 0;
    installIssues.push(`${n || 'One or more'} submodule checkout${n === 1 ? ' is' : 's are'} out of sync with the revisions pinned by PortOS.`);
  }

  return (
    <div className="space-y-6">
      {/* Current Version + Check Button */}
      <div className="flex items-end justify-between">
        <div>
          <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Current Version</div>
          <div className="flex items-center gap-2">
            <Tag size={16} className="text-port-accent shrink-0" />
            <span className="text-lg font-mono text-white">v{status?.currentVersion || '?'}</span>
          </div>
        </div>
        <button
          onClick={handleCheck}
          disabled={checking || updating}
          className="px-4 py-2 bg-port-border text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 disabled:opacity-50"
        >
          <RefreshCw size={14} className={checking ? 'animate-spin' : ''} />
          {checking ? 'Checking...' : 'Check for Updates'}
        </button>
      </div>

      {/* Origin / Fork status */}
      {remote?.hasOrigin && (
        <div className={`p-3 rounded-lg border text-sm ${
          isFork
            ? 'border-port-warning/40 bg-port-warning/5'
            : remote.isUpstream
              ? 'border-port-border bg-port-card'
              : 'border-port-border bg-port-card'
        }`}>
          <div className="flex items-start gap-2">
            {isFork ? <GitFork size={16} className="text-port-warning shrink-0 mt-0.5" /> : <GitBranch size={16} className="text-gray-400 shrink-0 mt-0.5" />}
            <div className="flex-1">
              <div className="text-white">
                {remote.isUpstream && <>Running from upstream <span className="font-mono">{remote.fullName}</span></>}
                {isFork && <>Running from fork <span className="font-mono">{remote.fullName}</span></>}
                {!remote.isUpstream && !isFork && <>Origin: <span className="font-mono">{remote.fullName || remote.originUrl}</span></>}
              </div>
              {isFork && (
                <div className="text-xs text-gray-400 mt-1 space-y-1">
                  <div>Updates pull from your fork's <span className="font-mono">main</span>. Sync it from <span className="font-mono">{upstreamName}</span> before updating, or apply upstream changes onto a working branch first to preserve customizations.</div>
                  <div>Tip: PR shareable fixes upstream; keep private changes on a separate branch and rebase that branch onto <span className="font-mono">main</span> after each sync.</div>
                  {forkSyncFresh && (
                    <div className="text-port-success">✓ Fork synced {formatTimeOfDaySeconds(lastForkSync.syncedAt)} — ready to update.</div>
                  )}
                </div>
              )}
              {forkSyncError && (
                <div role="alert" className="mt-2 text-xs text-port-error whitespace-pre-wrap">{forkSyncError}</div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* CoS agents live — updating/reconciling would restart PortOS and sever
          them, so the reconcile prompt and update actions below are suppressed. */}
      {agentsActive && (outOfSync || hasUpdate) && (
        <Banner tone="warning" icon={AlertTriangle} size="md" title="Update paused — CoS agents running">
          {activeCosAgents} CoS agent{activeCosAgents === 1 ? ' is' : 's are'} currently running.
          Updating or reconciling restarts PortOS, which would sever {activeCosAgents === 1 ? 'it' : 'them'} mid-task.
          Pause or wait for the agent{activeCosAgents === 1 ? '' : 's'} to finish — this notice clears automatically,
          then you can update.
        </Banner>
      )}

      {/* Install out of sync (issue #1779) — distinct from "new release available" */}
      {outOfSync && !agentsActive && (
        <div className="p-4 rounded-lg border border-port-warning/50 bg-port-warning/5">
          <div className="flex items-start gap-2">
            <AlertTriangle size={18} className="text-port-warning shrink-0 mt-0.5" />
            <div className="flex-1">
              <div className="text-sm text-white font-medium">Install out of sync</div>
              <div className="text-xs text-gray-400 mt-1">
                Your checked-out code is ahead of what’s running or installed — this happens after a
                manual <span className="font-mono">git pull</span> without <span className="font-mono">./update.sh</span>.
                Reconcile to finish the update (sync submodules, install dependencies, rebuild, run migrations, restart).
              </div>
              <ul className="text-xs text-gray-300 mt-2 space-y-1 list-disc list-inside">
                {installIssues.map((msg, i) => (
                  <li key={i}>{msg}</li>
                ))}
              </ul>
              <div className="flex flex-wrap gap-2 mt-3">
                {isFork ? (
                  <>
                    <button
                      onClick={handleSyncForkAndReconcile}
                      disabled={updating || polling || syncingFork}
                      className="px-4 py-2 bg-port-warning text-black rounded-lg text-sm flex items-center gap-2 hover:bg-port-warning/80 disabled:opacity-50"
                      title={`Fast-forwards ${remote?.fullName} main from ${upstreamName}, then runs update.sh to sync pinned submodules and reconcile the install.`}
                    >
                      <GitFork size={14} className={syncingFork ? 'animate-pulse' : ''} />
                      {syncingFork ? 'Syncing fork...' : updating ? 'Reconciling...' : polling ? 'Restarting...' : 'Sync Fork & Reconcile'}
                    </button>
                    <button
                      onClick={handleReconcileFromForkAsIs}
                      disabled={updating || polling || syncingFork}
                      className="px-4 py-2 bg-port-border text-gray-300 rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 hover:text-white disabled:opacity-50"
                      title="Skip the fork sync and reconcile from your fork's origin as-is."
                    >
                      <RefreshCw size={14} className={updating ? 'animate-spin' : ''} />
                      Reconcile from Fork As-Is
                    </button>
                  </>
                ) : (
                  <button
                    onClick={handleReconcile}
                    disabled={updating || polling || syncingFork}
                    className="px-4 py-2 bg-port-warning text-black rounded-lg text-sm flex items-center gap-2 hover:bg-port-warning/80 disabled:opacity-50"
                    title="Run update.sh to sync pinned submodules, install dependencies, rebuild the client, run migrations, and restart."
                  >
                    <RefreshCw size={14} className={updating ? 'animate-spin' : ''} />
                    {updating ? 'Reconciling...' : polling ? 'Restarting...' : 'Reconcile Now'}
                  </button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Available Update */}
      {release && (
        <div className={`p-4 rounded-lg border ${hasUpdate ? 'border-port-accent/50 bg-port-accent/5' : 'border-port-border bg-port-card'}`}>
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-400">Latest Release:</span>
              <span className="text-lg font-mono text-white">v{release.version}</span>
              {hasUpdate && (
                <span className="px-2 py-0.5 bg-port-accent/20 text-port-accent text-xs rounded-full">New</span>
              )}
            </div>
            {release.url && (
              <a
                href={release.url}
                target="_blank"
                rel="noopener noreferrer"
                className="text-gray-400 hover:text-white transition-colors flex items-center gap-1 text-xs"
              >
                <ExternalLink size={12} /> GitHub
              </a>
            )}
          </div>
          {release.publishedAt && (
            <div className="text-xs text-gray-500 mb-2">
              Released {formatDateNumeric(release.publishedAt)}
            </div>
          )}
          {release.body && (
            <div className="mt-3 p-3 bg-port-bg rounded border border-port-border">
              <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Release Notes</div>
              <div className="max-h-[32rem] overflow-y-auto">
                <MarkdownOutput content={release.body} />
              </div>
            </div>
          )}
        </div>
      )}

      {/* Update Actions. Only the restart-triggering buttons (Sync Fork & Update,
          Update from Fork As-Is, Update Now — all call runUpdate → update.sh →
          pm2 restart) are suppressed while CoS agents are live; the safe actions
          (Sync Fork Only = gh repo sync only, Ignore = no restart) stay available. */}
      {hasUpdate && (
        <div className="flex flex-wrap gap-2">
          {isFork ? (
            <>
              {!agentsActive && (
                <button
                  onClick={handleSyncForkAndUpdate}
                  disabled={updating || polling || syncingFork}
                  className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"
                  title={`Fast-forwards ${remote?.fullName} main from ${upstreamName} via gh repo sync, then runs the local update including pinned submodules. Refuses to overwrite divergent fork commits.`}
                >
                  <GitFork size={14} className={syncingFork ? 'animate-pulse' : ''} />
                  {syncingFork ? 'Syncing fork...' : updating ? 'Updating...' : polling ? 'Restarting...' : 'Sync Fork & Update'}
                </button>
              )}
              <button
                onClick={handleSyncForkOnly}
                disabled={updating || polling || syncingFork}
                className="px-4 py-2 bg-port-border text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 disabled:opacity-50"
                title={`Run gh repo sync ${remote?.fullName} only — useful if you want to merge upstream into a feature branch yourself before applying.`}
              >
                <GitFork size={14} />
                Sync Fork Only
              </button>
              {!agentsActive && (
                <button
                  onClick={handleUpdateFromForkAsIs}
                  disabled={updating || polling || syncingFork}
                  className="px-4 py-2 bg-port-border text-gray-400 rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 hover:text-white disabled:opacity-50"
                  title="Skip the fork sync and pull from your fork's origin as-is, then sync pinned submodules. Use this if you already merged upstream into your fork via your own workflow."
                >
                  {updating ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} />}
                  Update from Fork As-Is
                </button>
              )}
            </>
          ) : (
            !agentsActive && (
              <button
                onClick={handleUpdate}
                disabled={updating || polling}
                className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"
                title="Pull PortOS, sync pinned submodules, install dependencies, rebuild, run migrations, and restart."
              >
                {updating ? <Loader2 size={14} className="animate-spin" /> : <Download size={14} />}
                {updating ? 'Updating...' : polling ? 'Restarting...' : 'Update Now'}
              </button>
            )
          )}
          {release && (
            <button
              onClick={() => handleIgnore(release.version)}
              disabled={updating || syncingFork}
              className="px-4 py-2 bg-port-border text-gray-400 rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 hover:text-white disabled:opacity-50"
            >
              <XCircle size={14} />
              Ignore v{release.version}
            </button>
          )}
        </div>
      )}

      {/* Last Check */}
      {status?.lastCheck && (
        <div className="text-xs text-gray-500">
          Last checked: {formatDateTime(status.lastCheck)}
        </div>
      )}

      <NodeRuntimePanel
        busy={updating || polling || syncingFork}
        onLaunch={(call) => runUpdate({}, null, call)}
      />

      {/* Update Progress */}
      {steps.length > 0 && (
        <div>
          <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Update Progress</div>
          <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-2">
            {steps.map(({ step, status: stepStatus, message }) => (
              <div key={step} className="flex items-center gap-3">
                <StepIndicator status={stepStatus} />
                <span className="text-sm text-white font-medium">{STEP_LABELS[step] || step}</span>
                <span className="text-xs text-gray-500 flex-1 truncate">{message}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Update Error */}
      {updateError && (
        <Banner tone="error" size="md" icon={AlertTriangle}>{updateError}</Banner>
      )}

      {/* Automatic updates — configuration plus what the scheduler is waiting on */}
      <AutoUpdatePanel />

      {/* Last Update Result */}
      {status?.lastUpdateResult && (
        <div>
          <div className="text-xs text-gray-500 uppercase tracking-wide mb-2">Last Update</div>
          <div className={`p-3 rounded-lg border ${
            status.lastUpdateResult.success
              ? 'border-port-success/30 bg-port-success/5'
              : 'border-port-error/30 bg-port-error/5'
          }`}>
            <div className="flex items-center gap-2">
              {status.lastUpdateResult.success
                ? <Check size={14} className="text-port-success" />
                : <XCircle size={14} className="text-port-error" />
              }
              <span className="text-sm text-white">
                v{status.lastUpdateResult.version} — {status.lastUpdateResult.success ? 'Success' : 'Failed'}
              </span>
              {status.lastUpdateResult.completedAt && (
                <span className="text-xs text-gray-500">
                  {formatDateTime(status.lastUpdateResult.completedAt)}
                </span>
              )}
            </div>
            {status.lastUpdateResult.log && (
              <pre className="text-xs text-gray-400 mt-2 font-mono whitespace-pre-wrap break-all max-h-48 overflow-y-auto">{status.lastUpdateResult.log}</pre>
            )}
          </div>
        </div>
      )}

      {/* Ignored Versions */}
      {status?.ignoredVersions?.length > 0 && (
        <div>
          <div className="flex items-center justify-between mb-2">
            <div className="text-xs text-gray-500 uppercase tracking-wide">Ignored Versions</div>
            <button
              onClick={handleClearIgnored}
              className="text-xs text-gray-500 hover:text-white flex items-center gap-1"
            >
              <Trash2 size={12} /> Clear All
            </button>
          </div>
          <div className="flex flex-wrap gap-2">
            {status.ignoredVersions.map(v => (
              <span
                key={v}
                className="px-2 py-1 bg-port-card border border-port-border rounded text-sm text-gray-400 font-mono"
              >
                v{v}
              </span>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}