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

6.8 KB
Raw Blame
import TabPills from '../components/ui/TabPills';
import { useState, useEffect, useCallback, useRef } from 'react';
import useMounted from '../hooks/useMounted';
import { useParams, useNavigate, Link } from 'react-router';
import { Wand2, ArrowLeft } from 'lucide-react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
import { TABS } from '../components/feature-agents/constants';
import { useValidTab } from '../hooks/useValidTab';
import OverviewTab from '../components/feature-agents/OverviewTab';
import ConfigTab from '../components/feature-agents/ConfigTab';
import RunsTab from '../components/feature-agents/RunsTab';
import OutputTab from '../components/feature-agents/OutputTab';
import GitTab from '../components/feature-agents/GitTab';
import PageSkeleton from '../components/ui/PageSkeleton';

export default function FeatureAgentDetail() {
  const { id } = useParams();
  const navigate = useNavigate();
  const isCreate = !id;
  const activeTab = useValidTab(TABS, 'overview');

  const [agent, setAgent] = useState(null);
  const [loading, setLoading] = useState(!isCreate);
  const [apps, setApps] = useState([]);

  // Unmount guard (StrictMode-safe: resets to true on mount) so an async agent
  // load that resolves after teardown doesn't setState on a dead component.
  const mountedRef = useMounted();
  // Monotonic load token: an A→B navigation fires a fresh fetch and bumps this,
  // so a slow response for A resolving after we've switched to B is ignored
  // instead of overwriting the displayed agent with the wrong record.
  const fetchSeqRef = useRef(0);

  useEffect(() => {
    api.getApps().then(data => { if (mountedRef.current) setApps((data || []).filter(a => !a.archived)); }).catch(() => {});
  }, []);

  const fetchAgent = useCallback(() => {
    if (isCreate) return;
    const seq = ++fetchSeqRef.current;
    const isCurrent = () => mountedRef.current && seq === fetchSeqRef.current;
    api.getFeatureAgent(id).then(data => {
      if (!isCurrent()) return;
      setAgent(data);
      setLoading(false);
    }).catch(() => { if (isCurrent()) setLoading(false); });
  }, [id, isCreate]);

  useEffect(() => {
    // On an A→B switch, drop A's record and show the spinner immediately so a
    // stale agent never flashes under the new id while B is still loading.
    if (!isCreate) { setAgent(null); setLoading(true); }
    fetchAgent();
    const handler = (data) => { if (data.id === id) fetchAgent(); };
    socket.on('cos:feature-agent:status', handler);
    socket.on('cos:feature-agent:run-complete', handler);
    return () => {
      socket.off('cos:feature-agent:status', handler);
      socket.off('cos:feature-agent:run-complete', handler);
    };
  }, [fetchAgent, id, isCreate]);

  const handleStart = useCallback((agentId) => {
    api.startFeatureAgent(agentId, { silent: true }).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Activated'); }).catch(err => toast.error(err.message || 'Action failed'));
  }, []);
  const handlePause = useCallback((agentId) => {
    api.pauseFeatureAgent(agentId, { silent: true }).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Paused'); }).catch(err => toast.error(err.message || 'Action failed'));
  }, []);
  const handleResume = useCallback((agentId) => {
    api.resumeFeatureAgent(agentId, { silent: true }).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Resumed'); }).catch(err => toast.error(err.message || 'Action failed'));
  }, []);
  const handleStop = useCallback((agentId) => {
    api.stopFeatureAgent(agentId, { silent: true }).then(data => { setAgent(prev => ({ ...prev, ...data })); toast.success('Stopped'); }).catch(err => toast.error(err.message || 'Action failed'));
  }, []);
  const handleTrigger = useCallback((agentId) => {
    api.triggerFeatureAgent(agentId, { silent: true }).then(result => {
      if (result?.triggered === false) {
        toast.error(result.reason || 'Run could not be started');
        return;
      }
      if (result?.agent) setAgent(prev => ({ ...prev, ...result.agent }));
      toast.success('Run started');
    }).catch(err => toast.error(err.message || 'Action failed'));
  }, []);

  const handleSave = useCallback((saved) => {
    if (isCreate) {
      navigate(`/feature-agents/${saved.id}/overview`);
    } else {
      setAgent(prev => ({ ...prev, ...saved }));
    }
  }, [isCreate, navigate]);

  if (loading) {
    return (
      <PageSkeleton
        header="bar"
        label="Loading agent"
        fullHeight
        padded
        bodyClassName="p-6"
        titleWidthClass="w-56"
        showSubtitle
        subtitleOnMobile
        showAction={false}
        tabs={isCreate ? 0 : TABS.length}
        cards={3}
        sidebar={false}
      />
    );
  }

  if (!isCreate && !agent) {
    return (
      <div className="flex flex-col h-full items-center justify-center">
        <p className="text-gray-400">Feature agent not found</p>
        <Link to="/feature-agents" className="text-port-accent text-sm mt-2 hover:underline">Back to list</Link>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="shrink-0 px-3 py-2 sm:px-4 sm:py-3 border-b border-port-border">
        <div className="flex items-center gap-3">
          <Link to="/feature-agents" className="p-1.5 text-gray-400 hover:text-white hover:bg-port-border/50 rounded-lg transition-colors">
            <ArrowLeft size={18} />
          </Link>
          <Wand2 size={22} className="text-port-accent" />
          <div>
            <h1 className="text-lg font-bold text-white">
              {isCreate ? 'Create Feature Agent' : agent.name}
            </h1>
            {!isCreate && (
              <p className="text-xs text-gray-500">{agent.id} &middot; {agent.appId}</p>
            )}
          </div>
        </div>
      </div>
      {!isCreate && (
        <TabPills tabs={TABS} activeTab={activeTab} onChange={(tab) => navigate(`/feature-agents/${id}/${tab}`)}
          ariaLabel="Feature agent sections" mobileCompact className="shrink-0 min-w-0" />
      )}

      {/* Content */}
      <div className="flex-1 overflow-auto p-6">
        {(isCreate || activeTab === 'config') && (
          <ConfigTab agent={agent} isCreate={isCreate} apps={apps} onSave={handleSave} />
        )}
        {!isCreate && activeTab === 'overview' && (
          <OverviewTab agent={agent} onStart={handleStart} onPause={handlePause} onResume={handleResume} onStop={handleStop} onTrigger={handleTrigger} />
        )}
        {!isCreate && activeTab === 'runs' && <RunsTab agent={agent} />}
        {!isCreate && activeTab === 'output' && <OutputTab agent={agent} />}
        {!isCreate && activeTab === 'git' && <GitTab agent={agent} />}
      </div>
    </div>
  );
}