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.5 KB
Raw Blame
import TabPills from '../ui/TabPills';
import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { Link, useParams, useNavigate } from 'react-router';
import { ArrowLeft } from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
import * as api from '../../services/api';
import { AGENT_DETAIL_TABS } from './constants';
import { DEFAULT_AVATAR_COLOR } from '../../themes/portosThemes';
import OverviewTab from './tabs/OverviewTab';
import ToolsTab from './tabs/ToolsTab';
import WorldTab from './tabs/WorldTab';
import PublishedTab from './tabs/PublishedTab';
import SchedulesTab from './tabs/SchedulesTab';
import ActivityTab from './tabs/ActivityTab';

const NAV_TABS = AGENT_DETAIL_TABS.map(({ icon, ...tab }) => ({
  ...tab, icon: () => <span aria-hidden="true">{icon}</span>,
}));

export default function AgentDetail() {
  const { agentId } = useParams();
  return <AgentDetailContent key={agentId} />;
}

function AgentDetailContent() {
  const { agentId, tab } = useParams();
  const navigate = useNavigate();
  const activeTab = tab || 'overview';

  const [agent, setAgent] = useState(null);
  const [loading, setLoading] = useState(true);
  const [notFound, setNotFound] = useState(false);
  const [platformAccounts, setPlatformAccounts] = useState([]);
  const mountedRef = useRef(false);
  const latestAgentIdRef = useRef(agentId);
  const agentRequestRef = useRef(0);
  const platformRequestRef = useRef(0);

  latestAgentIdRef.current = agentId;

  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);

  const fetchAgent = useCallback(async (isCurrent = () => true) => {
    const requestId = ++agentRequestRef.current;
    const requestedAgentId = agentId;
    const data = await api.getAgentPersonality(requestedAgentId).catch(() => null);
    if (
      !isCurrent() ||
      !mountedRef.current ||
      requestId !== agentRequestRef.current ||
      latestAgentIdRef.current !== requestedAgentId
    ) {
      return;
    }
    if (!data) {
      setNotFound(true);
      setLoading(false);
      return;
    }
    setAgent(data);
    setLoading(false);
  }, [agentId]);

  useEffect(() => {
    let cancelled = false;
    setAgent(null);
    setPlatformAccounts([]);
    setLoading(true);
    setNotFound(false);
    fetchAgent(() => !cancelled);
    return () => {
      cancelled = true;
    };
  }, [fetchAgent]);

  useEffect(() => {
    let cancelled = false;
    const requestId = ++platformRequestRef.current;
    const requestedAgentId = agentId;
    api.getPlatformAccounts(requestedAgentId).then(accounts => {
      if (
        cancelled ||
        !mountedRef.current ||
        requestId !== platformRequestRef.current ||
        latestAgentIdRef.current !== requestedAgentId
      ) {
        return;
      }
      setPlatformAccounts(accounts);
    }).catch(() => {});
    return () => {
      cancelled = true;
    };
  }, [agentId]);

  const hasMoltbookAccount = useMemo(
    () => platformAccounts.some(a => a.platform === 'moltbook'),
    [platformAccounts]
  );

  const hasMoltworldAccount = useMemo(
    () => platformAccounts.some(a => a.platform === 'moltworld'),
    [platformAccounts]
  );

  const visibleTabs = useMemo(
    () => NAV_TABS.filter(t =>
      (t.id !== 'tools' || hasMoltbookAccount) &&
      (t.id !== 'world' || hasMoltworldAccount)
    ),
    [hasMoltbookAccount, hasMoltworldAccount]
  );

  // Redirect bare /agents/:id to /agents/:id/overview
  useEffect(() => {
    if (!tab && agentId) {
      navigate(`/agents/${agentId}/overview`, { replace: true });
    }
  }, [tab, agentId, navigate]);

  const handleToggle = async () => {
    await api.toggleAgentPersonality(agent.id, !agent.enabled);
    fetchAgent();
  };

  if (loading) {
    return <div className="p-6"><BrailleSpinner text="Loading agent" /></div>;
  }

  if (notFound) {
    return (
      <div className="p-6 text-center">
        <p className="text-lg text-gray-400 mb-4">Agent not found</p>
        <Link to="/agents" className="text-port-accent hover:text-port-accent/80">
          Back to Agents
        </Link>
      </div>
    );
  }

  const renderTab = () => {
    switch (activeTab) {
      case 'overview':
        return <OverviewTab agentId={agentId} agent={agent} onAgentUpdate={fetchAgent} />;
      case 'tools':
        return <ToolsTab agentId={agentId} agent={agent} />;
      case 'world':
        return <WorldTab agentId={agentId} agent={agent} />;
      case 'published':
        return <PublishedTab agentId={agentId} />;
      case 'schedules':
        return <SchedulesTab agentId={agentId} />;
      case 'activity':
        return <ActivityTab agentId={agentId} />;
      default:
        return <OverviewTab agentId={agentId} agent={agent} onAgentUpdate={fetchAgent} />;
    }
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b border-port-border px-6 py-4">
        <div className="flex items-center gap-4">
          <Link
            to="/agents"
            className="p-1.5 text-gray-400 hover:text-white transition-colors rounded hover:bg-port-border/50"
          >
            <ArrowLeft size={20} />
          </Link>
          <div
            className="w-10 h-10 rounded-full flex items-center justify-center text-xl shrink-0"
            style={{ backgroundColor: agent.avatar?.color || DEFAULT_AVATAR_COLOR }}
          >
            {agent.avatar?.emoji || '🤖'}
          </div>
          <div className="flex-1 min-w-0">
            <h1 className="line-clamp-2 break-words text-xl font-bold text-white" title={agent.name}>
              {agent.name}
            </h1>
            {agent.description && (
              <p className="text-sm text-gray-400 truncate">{agent.description}</p>
            )}
          </div>
          <button
            onClick={handleToggle}
            className={`px-3 py-1.5 text-sm rounded ${
              agent.enabled
                ? 'bg-port-success/20 text-port-success hover:bg-port-success/30'
                : 'bg-port-border text-gray-400 hover:bg-port-border/80'
            }`}
          >
            {agent.enabled ? 'Enabled' : 'Disabled'}
          </button>
        </div>
      </div>

      <TabPills tabs={visibleTabs} activeTab={activeTab} onChange={(tab) => navigate(`/agents/${agentId}/${tab}`)}
        ariaLabel="Social agent sections" mobileCompact className="shrink-0 min-w-0" />

      {/* Tab Content */}
      <div className="flex-1 overflow-auto bg-port-bg">
        {renderTab()}
      </div>
    </div>
  );
}