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

73.4 KB
Raw Blame
import PageHeader from '../components/PageHeader';
import PageLayout from '../components/PageLayout';
import { useState, useEffect, useCallback, useMemo, useRef, lazy, Suspense } from 'react';
import { useParams, useNavigate, useSearchParams } from 'react-router';
import { useSocket } from '../hooks/useSocket';
import { useSocketSubscription } from '../hooks/useSocketSubscription';
import { useLocalStorageBool } from '../hooks/useLocalStorageBool';
import { useValidTab } from '../hooks/useValidTab';
import { useInstanceFeatures } from '../hooks/useInstanceFeatures.js';
import { filterNavByFeatures } from '../lib/navFeatures.js';
import * as api from '../services/api';
import { isRiggedAvatarStyle, riggedRecordForStyle, useAvatarCapabilities } from '../hooks/useAvatarCapabilities';
import { coalesce } from '../utils/coalesce';
import { sameJsonShape } from '../lib/sameJsonShape';
import { isAgentHandoff } from '../lib/agentOutcome';
import { runningAgentsByTaskId, withoutSpawningTasks } from '../lib/cosSpawnWindow';
import { WEBGL_AVATAR_STYLE_IDS } from '../lib/avatarStyles';
import { Play, Pause, Square, Clock, CheckCircle, AlertCircle, Cpu, ChevronDown, ChevronUp, Brain, PanelLeftClose, PanelLeftOpen } from 'lucide-react';
import toast from '../components/ui/Toast';
import BrailleSpinner from '../components/BrailleSpinner';
import TabPills from '../components/ui/TabPills';
import PageSkeleton from '../components/ui/PageSkeleton';

// Import from modular components
import {
  TABS,
  STATE_MESSAGES,
  summarizeHealthIssues,
  healthIssueTone,
  fresherHealth,
  resolveDynamicAvatar,
} from '../components/cos/constants';
import CoSCharacter from '../components/cos/CoSCharacter';
import StateLabel from '../components/cos/StateLabel';
import TerminalCoSPanel from '../components/cos/TerminalCoSPanel';
import StatusIndicator from '../components/cos/StatusIndicator';
import StatCard from '../components/cos/StatCard';
import StatusBubble, { StatusPill, isGenericStatusMessage } from '../components/cos/StatusBubble';
import EventLog from '../components/cos/EventLog';
import ActionableInsightsBanner from '../components/cos/ActionableInsightsBanner';
// cos:subscribe task-list modes (server/services/socket.js registerSubscriber):
// the page fetches its own lists on invalidation; everyone else gets full lists.
const COS_PAGE_SUBSCRIBE = { taskLists: 'invalidate' };
const COS_PAGE_RELEASE = { taskLists: 'full' };

const AgentsTab = lazy(() => import('../components/cos/tabs/AgentsTab'));

// Task editing is not needed to view agents, so keep its forms and drag/drop
// dependencies out of the agents page's initial download.
const TasksTab = lazy(() => import('../components/cos/tabs/TasksTab'));

// The Runs tab (full AI run history + its log modal) is lazy-loaded so its weight
// stays out of the eager CoS chunk every /cos/* visit pays for — same reason the
// avatars below are not re-exported from the components/cos barrel.
const RunsTab = lazy(() => import('../components/cos/tabs/RunsTab'));
// The run-event diagnostic is lazy for the same reason as Runs: it is a
// post-mortem surface nobody opens on a normal day, and it pulls the whole
// ledger read path with it.
const RunEventsTab = lazy(() => import('../components/cos/tabs/RunEventsTab'));
const MindTab = lazy(() => import('../components/cos/tabs/MindTab'));
// Collection views and editors load only on their selected tab.
// Every other tab is loaded only when selected so the common queue view does
// not pay for charts, memory graphs, briefing readers, or configuration forms.
const JobsTab = lazy(() => import('../components/cos/tabs/JobsTab'));
const ScheduleTab = lazy(() => import('../components/cos/tabs/ScheduleTab'));
const WorkflowTab = lazy(() => import('../components/cos/tabs/WorkflowTab'));
const DigestTab = lazy(() => import('../components/cos/tabs/DigestTab'));
const GsdTab = lazy(() => import('../components/cos/tabs/GsdTab'));
const LearningTab = lazy(() => import('../components/cos/tabs/LearningTab'));
const MemoryTab = lazy(() => import('../components/cos/tabs/MemoryTab'));
const HealthTab = lazy(() => import('../components/cos/tabs/HealthTab'));
const ConfigTab = lazy(() => import('../components/cos/tabs/ConfigTab'));
const BriefingTab = lazy(() => import('../components/cos/tabs/BriefingTab'));

// Three.js-based avatars lazy-loaded so the R3F stack isn't bundled unless the
// user's chosen avatar style actually needs it. `core` is a plain 2D canvas
// (no three.js) but stays lazy so the default SVG path loads nothing extra.
// Every registry id (`lib/avatarStyles.js`) EXCEPT `svg`/`ascii` renders through
// a lazily-loaded component here — those two fall through to the inline
// `CoSCharacter` default below. `ChiefOfStaff.avatarStyles.test.jsx` fails if a
// registry id is missing from this map (or from the inline-rendered pair).
export const INLINE_RENDERED_AVATAR_STYLES = new Set(['svg', 'ascii']);

export const LAZY_AVATARS = {
  cyber:    lazy(() => import('../components/cos/CyberCoSAvatar')),
  sigil:    lazy(() => import('../components/cos/SigilCoSAvatar')),
  esoteric: lazy(() => import('../components/cos/EsotericCoSAvatar')),
  nexus:    lazy(() => import('../components/cos/NexusCoSAvatar')),
  muse:     lazy(() => import('../components/cos/MuseCoSAvatar')),
  core:     lazy(() => import('../components/cos/CoreCoSAvatar')),
  // Bundled CC0 Kenney Mini Characters — animated rigged GLB avatars.
  miniMaleC:   lazy(() => import('../components/cos/MiniCharMaleC')),
  miniFemaleD: lazy(() => import('../components/cos/MiniCharFemaleD')),
};

// A verified animated record renders through the same mini-character stage —
// the variant URL resolves to the record's GLB via /api/avatar, and playback
// falls back to a present clip per its coverage. Lazy like every other 3D
// avatar so three.js stays out of the main chunk until it is picked.
const LazyRiggedAvatar = lazy(() => import('../components/cos/MiniCharacterCoSAvatar'));

// `CANVAS_AVATAR_STYLES` means "needs the WebGL/three.js stage" — derives
// directly from the registry's `webgl` flag (`lib/avatarStyles.js`).
const CANVAS_AVATAR_STYLES = WEBGL_AVATAR_STYLE_IDS;

// Shared brand gradient for the "CoS" wordmark headings (clipped to text).
const COS_TITLE_GRADIENT = 'linear-gradient(135deg, #6366f1, #8b5cf6, #06b6d4)';

// How long the avatar keeps "speaking" after an event that gives it something to
// say. Exported so tests drain the timer by this value rather than a literal —
// a hardcoded drain that no longer covers the timer lets a state update escape
// act() again.
export const SPEAKING_MS = 2000;

function TabLoadFallback({ label }) {
  return <div className="flex items-center justify-center py-12"><BrailleSpinner text={`Loading ${label}`} /></div>;
}

// Keep stable reference data until an explicit invalidation. A replaced read
// cannot overwrite the newer cache or clear it when the old request fails.
function readReference(cache, read, apply) {
  if (cache.current) return cache.current;
  const pending = read().then(data => {
    if (cache.current === pending) apply(data);
    return data;
  }).catch(() => { if (cache.current === pending) cache.current = null; });
  cache.current = pending;
  return pending;
}

export default function ChiefOfStaff() {
  const { tab } = useParams();
  const [searchParams] = useSearchParams();
  const selectedTask = searchParams.get('task') || undefined;
  // The selection is read through a ref by the page-level reads and the socket
  // handlers, so changing it changes none of their identities: a click on a
  // task must not refetch the page or re-register fourteen listeners (#12032).
  const selectedTaskRef = useRef(selectedTask);
  selectedTaskRef.current = selectedTask;
  const navigate = useNavigate();
  const activeTab = useValidTab(TABS, 'tasks');
  const { isFeatureEnabled } = useInstanceFeatures();
  const visibleTabs = filterNavByFeatures(TABS, isFeatureEnabled);

  const needsTasks = activeTab === 'tasks';
  const needsAgents = needsTasks || activeTab === 'agents';
  const needsProviders = ['tasks', 'agents', 'schedule', 'workflow'].includes(activeTab);
  const needsApps = needsProviders || activeTab === 'memory';
  const routeRef = useRef(activeTab);
  routeRef.current = activeTab;
  // Page-level reads are keyed on the tab alone; the selection is not a page.
  const queryKey = activeTab;
  const queryRef = useRef(queryKey);
  queryRef.current = queryKey;
  const inFlight = useRef(null);
  const queuePending = useRef(null);
  const appsReadRef = useRef(null);

  const [status, setStatus] = useState(null);
  const [tasks, setTasks] = useState({ user: null, cos: null });
  const tasksRef = useRef(tasks);
  tasksRef.current = tasks;
  const [agents, setAgents] = useState([]);
  const [agentsLoaded, setAgentsLoaded] = useState(false);
  const [agentsError, setAgentsError] = useState(null);
  const agentReadRef = useRef(null);
  const [completedRevision, setCompletedRevision] = useState(0);
  const [taskHistoryRevision, setTaskHistoryRevision] = useState(0);
  const [health, setHealth] = useState(null);
  const [healthLoaded, setHealthLoaded] = useState(false);
  const [healthError, setHealthError] = useState(null);
  const [providers, setProviders] = useState([]);
  // Which provider an unpinned task actually runs on — the Schedule tab names it
  // on the "Default" option and resolves model/effort choices against it.
  const [activeProviderId, setActiveProviderId] = useState(null);
  // `[]` is ambiguous — "not fetched yet" vs "fetched, none configured". The
  // pickers below need the difference; see ProviderModelSelector's `loading`.
  const [providersLoaded, setProvidersLoaded] = useState(false);
  const [apps, setApps] = useState([]);
  const [loading, setLoading] = useState(true);
  const [agentState, setAgentState] = useState('sleeping');
  const [statusReadFailed, setStatusReadFailed] = useState(false);
  const [speaking, setSpeaking] = useState(false);
  // Socket events and manual checks share one visible speaking window. Each
  // burst owns a generation so a stale timer or request completion cannot end
  // a newer burst early.
  const speakingTimerRef = useRef(null);
  const speakingGenerationRef = useRef(0);
  const setSpeakingFor = useCallback((duration = SPEAKING_MS, generation) => {
    if (generation !== undefined && generation !== speakingGenerationRef.current) return null;
    if (speakingTimerRef.current !== null) {
      clearTimeout(speakingTimerRef.current);
      speakingTimerRef.current = null;
    }
    const nextGeneration = generation ?? speakingGenerationRef.current + 1;
    speakingGenerationRef.current = nextGeneration;
    if (duration <= 0) {
      setSpeaking(false);
      return nextGeneration;
    }
    setSpeaking(true);
    speakingTimerRef.current = setTimeout(() => {
      if (speakingGenerationRef.current !== nextGeneration) return;
      speakingTimerRef.current = null;
      setSpeaking(false);
    }, duration);
    return nextGeneration;
  }, []);
  useEffect(() => () => {
    speakingGenerationRef.current += 1;
    if (speakingTimerRef.current !== null) {
      clearTimeout(speakingTimerRef.current);
      speakingTimerRef.current = null;
    }
  }, []);
  const [statusMessage, setStatusMessage] = useState("Idle - waiting for tasks...");
  const [liveOutputs, setLiveOutputs] = useState({});
  const [eventLogs, setEventLogs] = useState([]);
  const [agentPanelCollapsed, setAgentPanelCollapsed] = useState(() => activeTab === 'tasks');
  const mobilePanelPreferenceSet = useRef(false);
  const toggleMobilePanel = () => {
    mobilePanelPreferenceSet.current = true;
    setAgentPanelCollapsed(value => !value);
  };
  useEffect(() => {
    if (!mobilePanelPreferenceSet.current) setAgentPanelCollapsed(activeTab === 'tasks');
  }, [activeTab]);
  const [desktopPanelCollapsed, setDesktopPanelCollapsed] = useLocalStorageBool(
    'cos-panel-collapsed',
    false,
    { format: 'true' },
  );
  const [activeAgentMeta, setActiveAgentMeta] = useState(null);
  const [learningSummary, setLearningSummary] = useState(null);
  // Actionable insights (blocked/approval/health counts) are fetched here in
  // fetchData and passed to ActionableInsightsBanner as a prop, so every trigger
  // that refetches CoS data — task mutations, socket-driven changes, health
  // checks, explicit refresh or reconnect — refreshes the banner without a separate signal. null
  // until the first fetch resolves; preserved across transient fetch failures.
  const [insights, setInsights] = useState(null);
  // Monotonic counter for queue/insight-state writes, so a slow fetchData cannot
  // overwrite a fresher optimistic mutation or fetchQueue result.
  const queueSeqRef = useRef(0);
  const socket = useSocket();
  // The cos:* room, refcounted with the always-mounted Layout consumers, in the
  // page's lighter "invalidate" task-list mode while it is open; the shared
  // socket goes back to full task lists when it unmounts.
  useSocketSubscription('cos', { payload: COS_PAGE_SUBSCRIBE, releasePayload: COS_PAGE_RELEASE });

  // Verified animated records for the avatar selector and rigged playback (#5894).
  const { records: riggedAvatars } = useAvatarCapabilities();

  // Derive avatar style from server config, with optional dynamic override
  const configAvatarStyle = status?.config?.avatarStyle || 'svg';
  const dynamicAvatarEnabled = status?.config?.dynamicAvatar || false;
  const dynamicStyle = dynamicAvatarEnabled ? resolveDynamicAvatar(activeAgentMeta) : null;
  const avatarStyle = dynamicStyle || configAvatarStyle;

  // Update avatar style via server config
  const setAvatarStyle = async (style) => {
    await api.updateCosConfig({ avatarStyle: style });
    fetchData();
  };

  const toggleDesktopPanel = useCallback(() => {
    setDesktopPanelCollapsed((prev) => !prev);
  }, [setDesktopPanelCollapsed]);

  // ONE writer for the health snapshot, so the Issues tile, the avatar state and
  // the status bubble can never describe different health checks. The ref is
  // written synchronously alongside the state, which is what lets fetchData run
  // the freshness rule and then derive from the value it actually committed —
  // with a functional updater the merged result was only visible inside the
  // updater, so the derivation below fell back to the raw (possibly older, or
  // null) read. HTTP responses merge by check time; socket events deliver the
  // completed check directly. Only a valid accepted observation clears errors.
  const healthRef = useRef(null);
  // A read started before a successful socket/manual observation cannot mark
  // that newer result unavailable when its own transport later fails.
  const healthObservationRef = useRef(0);
  const markHealthUnavailable = useCallback((observation = healthObservationRef.current) => {
    if (observation !== healthObservationRef.current) return;
    setHealthLoaded(true);
    setHealthError('Could not observe system health. Run Check to retry.');
  }, []);
  const applyHealth = useCallback((next, { merge = false } = {}) => {
    if (!Array.isArray(next?.issues)) {
      markHealthUnavailable();
      return healthRef.current;
    }
    const resolved = merge ? fresherHealth(healthRef.current, next) : next;
    if (resolved === next) {
      healthObservationRef.current += 1;
      setHealthError(null);
    }
    healthRef.current = resolved;
    setHealth(resolved);
    setHealthLoaded(true);
    return resolved;
  }, [markHealthUnavailable]);

  // The single write path for the provider list, mirroring `applyHealth` above:
  // stamping the settle flag anywhere else could set `providers` without it.
  // `sameJsonShape` keeps the array identity stable when the payload is
  // unchanged — which it is on essentially every refresh — so the early commit
  // that fixes first-paint latency doesn't cost a full-tree re-render each tick
  // (`providers` is an unmemoized prop down through every schedule card).
  const applyProviders = useCallback((data) => {
    setProviders(prev => (sameJsonShape(prev, data.providers || []) ? prev : data.providers || []));
    setActiveProviderId(data.activeProvider || null);
    setProvidersLoaded(true);
    return data;
  }, []);

  // Same self-committing-read fix as `applyProviders`, for the same reason: apps
  // feeds the Schedule/Tasks/Agents app pickers, so bundling it into
  // `secondaryRead`'s Promise.all held it hostage to `getCosActionableInsights`
  // (a server-side health check) and left those pickers showing an empty list
  // for seconds. `sameJsonShape` keeps the array identity stable on an unchanged
  // refresh payload so this doesn't cost a full-tree re-render each tick.
  const applyApps = useCallback((data) => {
    const filtered = (Array.isArray(data) ? data : []).filter(a => a.id !== 'portos-autofixer');
    setApps(prev => (sameJsonShape(prev, filtered) ? prev : filtered));
    return filtered;
  }, []);

  // Derive agent state from system status
  const deriveAgentState = useCallback((statusData, agentsData, healthData) => {
    if (!statusData?.running) return 'sleeping';
    if (statusData.paused) return 'sleeping';

    const activeAgents = agentsData.filter(a => a.status === 'running');
    if (activeAgents.length > 0 || statusData.activeAgents > 0) return 'coding';

    if (healthData?.issues?.length > 0) return 'investigating';

    // When running but idle, show as thinking (ready to work)
    return 'thinking';
  }, []);

  // Agent snapshots settle independently of status/tasks. Overlay socket changes
  // received during the read so a slow snapshot cannot undo a live transition.
  const readAgents = useCallback(async (controller) => {
    if (!needsAgents) return null;
    const request = { updates: new Map() };
    agentReadRef.current = request;
    setAgentsError(null);
    const data = await api.getCosAgents({ active: true, signal: controller.signal, silent: true }).catch(() => null);
    if (controller.signal.aborted || queryRef.current !== queryKey || agentReadRef.current !== request) return null;
    agentReadRef.current = null;
    if (Array.isArray(data)) {
      const merged = new Map(data.map(agent => [agent.id, agent]));
      for (const [id, agent] of request.updates) merged.set(id, { ...merged.get(id), ...agent });
      const snapshot = [...merged.values()].filter(agent => agent.status !== 'completed' || agent.deliveryPending);
      setAgents(snapshot);
      setAgentsLoaded(true);
    } else {
      setAgentsError('Could not load active agents.');
    }
    // Opening Agents must not wait for unrelated status or task summaries.
    if (activeTab === 'agents') setLoading(false);
    return data;
  }, [needsAgents, queryKey, activeTab]);

  const fetchData = useCallback(async function refreshPageData() {
    const route = activeTab;
    if (inFlight.current?.key === queryKey && !inFlight.current.controller.signal.aborted) {
      inFlight.current.dirty = true;
      return inFlight.current.promise;
    }
    inFlight.current?.controller.abort();
    const controller = new AbortController();
    const read = async () => {
      const queueSeq = queueSeqRef.current;
      // Paint the visible queue before ancillary summaries and references settle.
      const coreRead = Promise.all([
        api.getCosStatus().catch(() => null),
        needsTasks ? api.getCosTasks({ view: 'queue', selected: selectedTaskRef.current, signal: controller.signal, silent: true }).catch(() => null) : Promise.resolve(null),
        readAgents(controller),
      ]);
      const healthObservation = healthObservationRef.current;
      const healthRead = api.getCosHealth({ signal: controller.signal, silent: true }).catch(() => null).then((data) => {
        if (controller.signal.aborted || queryRef.current !== queryKey) return null;
        if (!Array.isArray(data?.issues)) {
          markHealthUnavailable(healthObservation);
          return null;
        }
        // Health is independently useful to the Health tab. Commit it as soon
        // as its own read settles instead of making that tab wait for the slower
        // actionable-insights request in the same batch.
        applyHealth(data, { merge: true });
        return data;
      });
      // The API shares its provider snapshot across all pages and pickers.
      const providersRead = needsProviders ? api.getProviders().then(applyProviders).catch(() => {}) : Promise.resolve();
      // Same rationale as providersRead above: apps commits on its own settle
      // instead of waiting on the slower siblings in secondaryRead.
      const appsRead = needsApps ? readReference(appsReadRef, api.getApps, applyApps) : Promise.resolve();
      const secondaryRead = Promise.all([
        api.getCosLearningSummary().catch(() => null),
        // Preserve the last good insights on a transient refresh failure.
        needsTasks ? api.getCosActionableInsights({ cachedHealth: true, silent: true }).catch(() => null) : Promise.resolve(null)
      ]);

      const [statusData, tasksData, agentResult] = await coreRead;
      if (controller.signal.aborted || queryRef.current !== queryKey) return;
      const agentsData = agentResult || [];
      setStatus(statusData);
      setStatusReadFailed(typeof statusData?.running !== 'boolean');
      // A queue refresh started later can still resolve first. Its task payload
      // must not be clobbered by this older, pre-flip read — otherwise the row
      // returns to the pending-AND-active state this guard exists to remove.
      if (queueSeqRef.current === queueSeq) {
        if (tasksData) setTasks(tasksData);
      }

      setLoading(false);

      // Paint the shell and queue before waiting for health, providers, apps,
      // learning, and insights. Those values fill in below without delaying the
      // tab the user asked to open.
      const initialHealth = healthRef.current;
      const initialState = deriveAgentState(statusData, agentsData, initialHealth);
      setAgentState(initialState);
      setStatusMessage(statusData?.paused
        ? `Paused${statusData.pauseReason ? ` — ${statusData.pauseReason}` : ''}`
        : (initialState === 'investigating' && summarizeHealthIssues(initialHealth?.issues)) || STATE_MESSAGES[initialState]);
      const runningAgent = agentsData.find(a => a.status === 'running');
      setActiveAgentMeta(runningAgent?.metadata || null);

      const [learningSummaryData, insightsData] = await secondaryRead;
      // All three self-committing reads are barriers, not values: `mergedHealth`
      // below reads what `healthRead` wrote, so it must not run before they settle.
      await Promise.all([healthRead, providersRead, appsRead]);
      // Health events may have delivered a newer snapshot while these reads settled.
      if (controller.signal.aborted || queryRef.current !== queryKey) return;
      const mergedHealth = healthRef.current;
      setLearningSummary(learningSummaryData);
      // Apply a real insights payload (including a legitimately-empty []); a null
      // from a failed/transient fetch preserves the last-good array so the banner
      // doesn't flicker empty on a blip.
      if (insightsData?.insights && queueSeqRef.current === queueSeq) setInsights(insightsData.insights);

      const newState = deriveAgentState(statusData, agentsData, mergedHealth);
      setAgentState(newState);
      // Default state message — richer messages come from socket events. The one
      // state whose default is useless is `investigating`: only a health issue
      // gets us here, so name it rather than saying "Investigating issue..." next
      // to an Active count of 0 with no agent to inspect.
      setStatusMessage(statusData?.paused
        ? `Paused${statusData.pauseReason ? ` — ${statusData.pauseReason}` : ''}`
        : (newState === 'investigating' && summarizeHealthIssues(mergedHealth?.issues)) || STATE_MESSAGES[newState]);

    };
    const pending = { route, key: queryKey, promise: null, controller, dirty: false };
    inFlight.current = pending;
    pending.promise = read().finally(() => {
      if (inFlight.current === pending) inFlight.current = null;
      if (pending.dirty && !controller.signal.aborted && queryRef.current === queryKey) refreshPageData();
    });
    return pending.promise;
  }, [activeTab, queryKey, needsTasks, needsAgents, needsProviders, needsApps, deriveAgentState, applyHealth, markHealthUnavailable, applyProviders, applyApps, readAgents]);

  // Coalesce event bursts into a read of the visible queue and scalar shell
  // status. Insights use persisted health; invalidation never runs PM2 repair.
  const fetchQueue = useCallback(async function refreshQueueData() {
    if (queuePending.current?.key === queryKey && !queuePending.current.controller.signal.aborted) {
      queuePending.current.dirty = true;
      return queuePending.current.promise;
    }
    queuePending.current?.controller.abort();
    const controller = new AbortController();
    const request = { key: queryKey, controller, dirty: false, promise: null };
    queuePending.current = request;
    const queueSeq = ++queueSeqRef.current;
    const insightsRead = needsTasks
      ? api.getCosActionableInsights({ cachedHealth: true, silent: true }).catch(() => null)
      : Promise.resolve(null);
    request.promise = Promise.all([
      api.getCosStatus().catch(() => null),
      needsTasks ? api.getCosTasks({ view: 'queue', selected: selectedTaskRef.current, signal: controller.signal, silent: true }).catch(() => null) : null,
      readAgents(controller),
    ]).then(async ([summary, tasksData]) => {
      if (controller.signal.aborted || queryRef.current !== queryKey || queueSeqRef.current !== queueSeq) return;
      if (summary) setStatus(summary);
      if (tasksData) setTasks(tasksData);
      const insightsData = await insightsRead;
      if (!controller.signal.aborted && queueSeqRef.current === queueSeq && insightsData?.insights) setInsights(insightsData.insights);
    }).finally(() => {
      if (queuePending.current === request) queuePending.current = null;
      if (request.dirty && !controller.signal.aborted && queryRef.current === queryKey) refreshQueueData();
    });
    return request.promise;
  }, [queryKey, needsTasks, readAgents]);

  // All page insight reads use cached health. Explicit Run Check owns repairs;
  // task invalidations must never trigger a health-check/socket feedback loop.

  // Redirect unknown tab IDs to the default tab — `activeTab !== tab` only
  // when the param failed validation and fell back.
  useEffect(() => {
    if (tab && tab !== activeTab) {
      navigate('/cos/tasks', { replace: true });
    }
  }, [tab, activeTab, navigate]);

  // Initial route load only. Socket invalidations and reconnect recover updates.
  useEffect(() => {
    fetchData();
    return () => { inFlight.current?.controller.abort(); queuePending.current?.controller.abort(); };
  }, [fetchData]);

  // The selection-dependent read. The mount read already carries `selected`,
  // so a deep link costs nothing extra; a later selection that is not in the
  // loaded lists (a historical task opened from a summary link) costs exactly
  // one record read, merged into the list it belongs to.
  useEffect(() => {
    if (!selectedTask || !needsTasks) return undefined;
    const { user, cos } = tasksRef.current;
    if (!user && !cos) return undefined;
    const loaded = [...(user?.tasks || []), ...(cos?.tasks || [])];
    if (loaded.some(task => task.id === selectedTask)) return undefined;
    let active = true;
    api.getCosTask(selectedTask, { silent: true }).then((found) => {
      if (!active || !found?.task) return;
      const key = found.source === 'internal' ? 'cos' : 'user';
      setTasks(prev => {
        const list = prev[key];
        if (!list) return prev;
        return { ...prev, [key]: { ...list, tasks: [...(list.tasks || []).filter(task => task.id !== found.task.id), found.task] } };
      });
    }).catch(() => {});
    return () => { active = false; };
  }, [selectedTask, needsTasks]);


  useEffect(() => {
    if (!socket) return;

    // Reconnect recovery; the subscription itself lives in useSocketSubscription above.
    const reconnect = () => {
      appsReadRef.current = null;
      fetchData();
      setCompletedRevision(value => value + 1);
      setTaskHistoryRevision(value => value + 1);
    };
    socket.on('connect', reconnect);

    const handleCosStatus = (data) => {
      setStatus(prev => ({ ...prev, running: data.running }));
      fetchQueue();
      if (!data.running) {
        setAgentState('sleeping');
        setStatusMessage("Stopped - daemon not running");
        setActiveAgentMeta(null);
      }
    };
    socket.on('cos:status', handleCosStatus);

    // The store's own per-mutation event, which fires the instant a task is added
    // or its status flips. It carries one task rather than the list, and also
    // fires for writes with nothing to
    // show here (every running task's federation lease heartbeat), so it drives
    // one coalesced queue refresh rather than a fetch per event. This is what
    // collapses the pending→in_progress lag: 'cos:agent:spawned' fires BEFORE
    // spawnAgentForTask flips the task off 'pending', so the fetch it triggers
    // always reads the task as still-queued.
    const refreshQueue = coalesce(fetchQueue, 400);
    const handleTaskMutation = data => {
      if (data?.completedChanged || data?.task?.status === 'completed' || data?.previousStatus === 'completed' || ['deleted', 'peer-merged'].includes(data?.action)) {
        setTaskHistoryRevision(value => value + 1);
      }
      refreshQueue();
    };
    socket.on('cos:tasks:changed', handleTaskMutation);

    const handleAgentSpawned = (data) => {
      if (needsAgents && data?.id) {
        agentReadRef.current?.updates.set(data.id, data);
        setAgents(prev => [...prev.filter(agent => agent.id !== data.id), data]);
      }
      setAgentState('coding');
      // Show actual task description if available
      const taskDesc = data?.metadata?.taskDescription;
      const shortDesc = taskDesc ? taskDesc.substring(0, 60) + (taskDesc.length > 60 ? '...' : '') : 'Working on task...';
      setStatusMessage(`Running: ${shortDesc}`);
      setSpeakingFor();
      // Track active agent metadata for dynamic avatar resolution
      if (data?.metadata) setActiveAgentMeta(data.metadata);
      // Initialize empty output buffer for new agent
      if (data?.agentId || data?.id) {
        setLiveOutputs(prev => ({ ...prev, [data.agentId || data.id]: [] }));
      }
      fetchQueue();
    };
    socket.on('cos:agent:spawned', handleAgentSpawned);

    const handleAgentUpdated = (updatedAgent) => {
      if (!needsAgents) return;
      const updates = agentReadRef.current?.updates;
      updates?.set(updatedAgent.id, { ...updates.get(updatedAgent.id), ...updatedAgent });
      // Update the specific agent in the agents list without fetching all data
      setAgents(prev => prev.map(agent =>
        agent.id === updatedAgent.id ? { ...agent, ...updatedAgent } : agent
      ).filter(agent => agent.status !== 'completed' || agent.deliveryPending));
    };
    socket.on('cos:agent:updated', handleAgentUpdated);

    const handleAgentOutput = (data) => {
      if (needsAgents && data?.agentId && data?.line) {
        setLiveOutputs(prev => {
          const existing = prev[data.agentId] || [];
          const updated = [...existing, { line: data.line, timestamp: Date.now() }];
          return { ...prev, [data.agentId]: updated.length > 500 ? updated.slice(-500) : updated };
        });
      }
    };
    socket.on('cos:agent:output', handleAgentOutput);

    const handleAgentCompleted = (data) => {
      const id = data?.id || data?.agentId;
      if (needsAgents && id) {
        agentReadRef.current?.updates.set(id, { ...data, id, status: 'completed' });
        setAgents(prev => prev.filter(agent => agent.id !== id));
      }
      setCompletedRevision(value => value + 1);
      setAgentState('reviewing');
      // Three outcomes, not two: a run retired by Resume/Relaunch never reached a
      // verdict, so announcing "Task failed" for it tells the user their own
      // provider swap broke something.
      setStatusMessage(
        isAgentHandoff(data) ? "Handed the task to a new run"
          : data?.result?.success ? "Task completed successfully"
            : "Task failed - checking errors..."
      );
      setSpeakingFor();
      // Clear active agent metadata so avatar reverts to default
      setActiveAgentMeta(null);
      // Clean up live output buffer for completed agent to prevent memory growth
      if (data?.agentId) {
        setLiveOutputs(prev => {
          const { [data.agentId]: _, ...rest } = prev;
          return rest;
        });
      }
      fetchQueue();
    };
    socket.on('cos:agent:completed', handleAgentCompleted);

    const handleHealthCheck = (data) => {
      applyHealth({ lastCheck: data.metrics?.timestamp, issues: data.issues });
      // The health snapshot is already in this event; no HTTP health read is needed.
      if (data.issues?.length > 0) {
        setAgentState('investigating');
        setStatusMessage(summarizeHealthIssues(data.issues));
        setSpeakingFor();
      }
    };
    socket.on('cos:health:check', handleHealthCheck);

    // Listen for detailed log events
    const handleCosLog = (data) => {
      setEventLogs(prev => {
        const newLogs = [...prev, data].slice(-20); // Keep last 20 logs
        return newLogs;
      });
      // Update status message with latest log
      if (data.message) {
        setStatusMessage(data.message);
        if (data.level === 'success' || data.level === 'error') {
          setSpeakingFor(1500);
        }
      }
    };
    socket.on('cos:log', handleCosLog);
    const handleRecoveryScheduleChanged = event => {
      if (needsAgents && event?.id === 'cos-pending-merge-sweep') refreshQueue();
    };
    socket.on('cos:scheduler:changed', handleRecoveryScheduleChanged);

    // Stable reference data has its own invalidation path, independent of the queue.
    const handleAppsChanged = coalesce(() => {
      appsReadRef.current = null;
      if (needsApps) readReference(appsReadRef, api.getApps, applyApps);
    }, 400);
    const handleProvidersChanged = coalesce(() => {
      if (needsProviders) api.getProviders().then(applyProviders).catch(() => {});
    }, 400);
    const handleConfigChanged = () => fetchData();
    socket.on('providers:changed', handleProvidersChanged);
    socket.on('cos:config:changed', handleConfigChanged);
    socket.on('cos:status:paused', handleConfigChanged);
    socket.on('cos:status:resumed', handleConfigChanged);
    socket.on('apps:changed', handleAppsChanged);

    return () => {
      socket.off('connect', reconnect);
      socket.off('providers:changed', handleProvidersChanged);
      socket.off('cos:config:changed', handleConfigChanged);
      socket.off('cos:status:paused', handleConfigChanged);
      socket.off('cos:status:resumed', handleConfigChanged);
      handleAppsChanged.cancel();
      handleProvidersChanged.cancel();
      socket.off('cos:status', handleCosStatus);
      socket.off('cos:tasks:changed', handleTaskMutation);
      socket.off('cos:agent:spawned', handleAgentSpawned);
      socket.off('cos:agent:updated', handleAgentUpdated);
      socket.off('cos:agent:output', handleAgentOutput);
      socket.off('cos:agent:completed', handleAgentCompleted);
      socket.off('cos:health:check', handleHealthCheck);
      socket.off('cos:log', handleCosLog);
      socket.off('cos:scheduler:changed', handleRecoveryScheduleChanged);
      socket.off('apps:changed', handleAppsChanged);
      refreshQueue.cancel();
    };
  }, [socket, fetchData, fetchQueue, needsAgents, needsTasks, needsApps, needsProviders, applyApps, applyProviders, setSpeakingFor]);

  const handleStart = async () => {
    const result = await api.startCos({ silent: true }).catch(err => {
      toast.error(err.message);
      return null;
    });
    if (result?.success) {
      toast.success('Chief of Staff started');
      setAgentState('thinking');
      setStatusMessage("Starting daemon - scanning for tasks...");
      setSpeakingFor();
      fetchData();
    }
  };

  const handleStop = async () => {
    const result = await api.stopCos({ silent: true }).catch(err => {
      toast.error(err.message);
      return null;
    });
    if (result?.success) {
      toast.success('Chief of Staff stopped');
      setAgentState('sleeping');
      setStatusMessage("Stopped - daemon not running");
      fetchData();
    }
  };

  const handlePause = async () => {
    const reason = 'Paused from Chief of Staff controls';
    const result = await api.pauseCos(reason, { silent: true }).catch(err => {
      toast.error(err.message);
      return null;
    });
    if (result?.success) {
      toast.success('Chief of Staff paused');
      setStatus(prev => ({ ...prev, paused: true, pausedAt: result.pausedAt, pauseReason: reason }));
      setAgentState('sleeping');
      setStatusMessage(`Paused — ${reason}`);
      fetchData();
    }
  };

  const handleResume = async () => {
    const result = await api.resumeCos({ silent: true }).catch(err => {
      toast.error(err.message);
      return null;
    });
    if (result?.success) {
      toast.success('Chief of Staff resumed');
      setStatus(prev => ({ ...prev, paused: false, pausedAt: null, pauseReason: null }));
      setAgentState('thinking');
      setStatusMessage('Resuming daemon - scanning for tasks...');
      fetchData();
    }
  };

  const handleForceEvaluate = async () => {
    // Only announce success / drive the "thinking" state after the request
    // actually resolves — a failed evaluate must not flash a success toast.
    try {
      await api.forceCosEvaluate({ silent: true });
      toast.success('Evaluation triggered');
      setAgentState('thinking');
      setStatusMessage("Evaluating tasks...");
      setSpeakingFor();
    } catch (err) {
      toast.error(err.message);
    }
  };

  const handleTaskUnblocked = useCallback((taskId) => {
    // A full refresh starts before its first await, so invalidate any read that
    // began before this confirmed mutation. Otherwise its pre-unblock snapshot
    // can put the task and insight back into the blocked state after our local
    // update has already rendered.
    queueSeqRef.current += 1;
    setTasks(prev => {
      const unblockSlice = (slice) => {
        if (!slice) return slice;
        const blockedTask = slice.grouped?.blocked?.find(t => t.id === taskId);
        const existingTask = slice.tasks?.find(t => t.id === taskId) || blockedTask;
        if (!existingTask) return slice;
        const unblocked = { ...existingTask, status: 'pending', metadata: { ...existingTask.metadata, blocker: undefined, blockedReason: undefined } };
        const currentPending = slice.grouped?.pending || [];
        const pending = currentPending.some(t => t.id === taskId)
          ? currentPending.map(t => t.id === taskId ? unblocked : t)
          : [...currentPending, unblocked];
        return {
          ...slice,
          tasks: slice.tasks?.map(t => t.id === taskId ? unblocked : t),
          grouped: {
            ...slice.grouped,
            blocked: slice.grouped?.blocked?.filter(t => t.id !== taskId) || [],
            pending
          }
        };
      };
      return {
        ...prev,
        user: unblockSlice(prev.user),
        cos: unblockSlice(prev.cos)
      };
    });
    setInsights(prev => {
      if (!Array.isArray(prev)) return prev;
      return prev.flatMap(insight => {
        if (insight.type !== 'blocked' || !Array.isArray(insight.tasks)) return [insight];
        const remaining = insight.tasks.filter(task => task.id !== taskId);
        if (remaining.length === insight.tasks.length) return [insight];
        if (remaining.length === 0) return [];
        const firstRemaining = remaining[0];
        return [{
          ...insight,
          title: `${remaining.length} blocked task${remaining.length > 1 ? 's' : ''}`,
          description: firstRemaining.blocker || firstRemaining.description || insight.description,
          count: remaining.length,
          tasks: remaining,
        }];
      });
    });
  }, []);

  const handleTaskDeleted = useCallback((taskId, taskSource) => {
    queueSeqRef.current += 1;
    setTasks(prev => {
      const deleteSlice = (slice) => {
        if (!slice) return slice;
        const tasks = slice.tasks?.filter(t => t.id !== taskId);
        const filterSlice = (list) => list?.filter(t => t.id !== taskId);
        const grouped = slice.grouped ? {
          pending: filterSlice(slice.grouped.pending),
          in_progress: filterSlice(slice.grouped.in_progress),
          challenged: filterSlice(slice.grouped.challenged),
          blocked: filterSlice(slice.grouped.blocked),
          completed: filterSlice(slice.grouped.completed),
        } : undefined;
        return {
          ...slice,
          tasks,
          ...(grouped ? { grouped } : {}),
        };
      };
      if (taskSource === 'internal' || taskSource === 'cos') {
        return { ...prev, cos: deleteSlice(prev.cos) };
      }
      if (taskSource === 'user') {
        return { ...prev, user: deleteSlice(prev.user) };
      }
      return { ...prev, user: deleteSlice(prev.user), cos: deleteSlice(prev.cos) };
    });
    setInsights(prev => {
      if (!Array.isArray(prev)) return prev;
      return prev.flatMap(insight => {
        if (insight.type !== 'blocked' || !Array.isArray(insight.tasks)) return [insight];
        const remaining = insight.tasks.filter(task => task.id !== taskId);
        if (remaining.length === insight.tasks.length) return [insight];
        if (remaining.length === 0) return [];
        const firstRemaining = remaining[0];
        return [{
          ...insight,
          title: `${remaining.length} blocked task${remaining.length > 1 ? 's' : ''}`,
          description: firstRemaining.blocker || firstRemaining.description || insight.description,
          count: remaining.length,
          tasks: remaining,
        }];
      });
    });
  }, []);

  // A successful task POST returns the persisted task synchronously. Insert it
  // into the queue right away so the user gets a durable pending indication
  // before the scheduler's socket updates report its active transition.
  const handleUserTaskAdded = useCallback((task, { position = 'bottom' } = {}) => {
    if (!task?.id) return;
    // A full-data read started before the POST resolved carries a queue snapshot
    // that cannot contain this task. Retire it before inserting the confirmed
    // record, just as fetchQueue does for socket-driven updates.
    queueSeqRef.current += 1;
    setTasks(prev => {
      const current = prev.user?.tasks || [];
      if (current.some(existing => existing.id === task.id)) return prev;
      const nextTasks = position === 'top' ? [task, ...current] : [...current, task];
      const grouped = {
        pending: nextTasks.filter(item => item.status === 'pending'),
        in_progress: nextTasks.filter(item => item.status === 'in_progress'),
        challenged: nextTasks.filter(item => item.status === 'challenged'),
        blocked: nextTasks.filter(item => item.status === 'blocked'),
        completed: nextTasks.filter(item => item.status === 'completed'),
      };
      return {
        ...prev,
        user: {
          ...(prev.user || { exists: true, type: 'user' }),
          tasks: nextTasks,
          grouped,
        },
      };
    });
  }, []);

  const handleHealthCheck = async () => {
    setAgentState('investigating');
    setStatusMessage("Running system health check...");
    const speakingGeneration = setSpeakingFor();
    const healthObservation = healthObservationRef.current;
    const result = await api.forceHealthCheck({ silent: true }).catch(err => {
      toast.error(err.message);
      return null;
    });
    setSpeakingFor(0, speakingGeneration);
    if (Array.isArray(result?.issues)) {
      const checkedHealth = applyHealth({ lastCheck: result.metrics?.timestamp, issues: result.issues }, { merge: true });
      // The Health route does not load the Tasks-only insights banner.
      toast.success('Health check complete');
      if (checkedHealth.issues.length > 0) {
        setStatusMessage(summarizeHealthIssues(checkedHealth.issues));
      } else {
        setAgentState('sleeping');
        setStatusMessage("Health check passed - all systems OK");
      }
    } else {
      markHealthUnavailable(healthObservation);
      if (healthObservation === healthObservationRef.current) setStatusMessage('System health unavailable');
    }
  };

  // Memoize expensive derived state to prevent recalculation on every render
  // Note: These must be before any early returns to follow React's Rules of Hooks
  const activeAgentCount = useMemo(() =>
    needsAgents ? agents.filter(a => a.status === 'running').length : status?.activeAgents || 0,
    [agents, needsAgents, status?.activeAgents]
  );

  // Memoize pending task count, settled against the live agent list.
  //
  // GET /api/cos/tasks already settles `grouped.pending` for the spawn window,
  // but `activeAgentCount` above reads the SOCKET-fed agent array, which lands on
  // 'cos:agent:spawned' — ahead of the next task fetch. Counting the payload raw
  // would tick Active to 1 while Pending still read 1 until that fetch returned,
  // which is the "1 pending and 1 active" this page is the headline surface for.
  // Same settlement TasksTab makes from the same two arrays, so the header cards
  // and the task list below them cannot disagree. See lib/cosSpawnWindow.js.
  const runningAgentByTaskId = useMemo(() => runningAgentsByTaskId(agents), [agents]);
  const pendingTaskCount = useMemo(() =>
    needsTasks ? withoutSpawningTasks(tasks.user?.grouped?.pending, runningAgentByTaskId).length
      + withoutSpawningTasks(tasks.cos?.grouped?.pending, runningAgentByTaskId).length : status?.pendingTasks || 0,
    [tasks.user?.grouped?.pending, tasks.cos?.grouped?.pending, runningAgentByTaskId, needsTasks, status?.pendingTasks]
  );

  const hasCanvasAvatar = CANVAS_AVATAR_STYLES.has(avatarStyle) || isRiggedAvatarStyle(avatarStyle);

  // Learning tile behaviour shared by the compact (sidebar/mobile) and mini
  // (ascii stats bar) renderings — only the icon scale and the empty-state
  // value differ between them. A skipped task type is critical on its own
  // terms: derive that here rather than trusting the server's status chain to
  // keep classifying `skipped > 0` as `critical`, or a reorder there would
  // silently drop the red signal while the tile still reads "N skipped".
  const learningSkipped = learningSummary?.skipped ?? 0;
  // `!= null`, not truthiness — a real 0% success rate is the highest-signal
  // state and must not render as the empty state. `null` is the sentinel each
  // tile falls back from to its own (differently sized) empty-state string.
  const learningRate = learningSummary?.overallSuccessRate != null ? `${learningSummary.overallSuccessRate}%` : null;
  const learningStatProps = {
    label: 'Learning',
    tone: learningSkipped > 0 ? 'critical' : (learningSummary?.status || 'default'),
    active: learningSkipped > 0,
    activeLabel: learningSkipped > 0 ? `${learningSkipped} skipped` : null,
    title: learningSummary?.statusMessage || 'View learning analytics',
    onClick: () => navigate('/cos/learning'),
  };

  // The Issues tile is the only place the UI admits CoS found something wrong,
  // so it has to click through to the detail. Without that, a warning-level
  // health issue parked the avatar on "Investigating" with Active 0, no agent
  // to open, and the offending message reachable only by guessing at the Health
  // tab. `title` surfaces the same summary on hover/touch-and-hold.
  const healthIssues = health?.issues || [];
  const issuesStatProps = {
    label: 'Issues',
    value: healthError || !healthLoaded ? '—' : healthIssues.length,
    tone: healthError ? 'warning' : healthIssueTone(healthIssues),
    title: healthError ? 'Health unavailable — view last results and retry'
      : !healthLoaded ? 'Health not observed yet — view system health'
        : summarizeHealthIssues(healthIssues) || 'No issues detected — view system health',
    onClick: () => navigate('/cos/health'),
  };

  // Compact stats card grid — rendered both inside the desktop CoS sidebar and
  // the mobile compressed header so the metrics always live "inside" CoS.
  const statsGridCards = (
    <>
      <StatCard
        label="Active"
        value={activeAgentCount}
        icon={<Cpu className="w-4 h-4 text-port-accent" />}
        active={activeAgentCount > 0}
        compact
      />
      <StatCard
        label="Pending"
        value={pendingTaskCount}
        icon={<Clock className="w-4 h-4 text-port-warning" />}
        compact
      />
      <StatCard
        label="Done"
        value={status?.stats?.tasksCompleted || 0}
        icon={<CheckCircle className="w-4 h-4 text-port-success" />}
        compact
      />
      <StatCard
        {...issuesStatProps}
        icon={<AlertCircle className="w-4 h-4" />}
        compact
      />
      <StatCard
        {...learningStatProps}
        value={learningRate ?? 'No data'}
        icon={<Brain className="w-4 h-4" />}
        compact
        className="hidden lg:flex"
      />
      {status?.running ? (
        <>
          <button
            type="button"
            onClick={status.paused ? handleResume : handlePause}
            className={`border rounded px-2 py-1.5 flex items-center gap-2 transition-colors min-h-[52px] ${
              status.paused
                ? 'bg-port-success/20 hover:bg-port-success/30 text-port-success border-port-success/30'
                : 'bg-port-warning/20 hover:bg-port-warning/30 text-port-warning border-port-warning/30'
            }`}
            aria-label={status.paused ? 'Resume Chief of Staff scheduling' : 'Pause Chief of Staff scheduling'}
            title={status.paused
              ? 'Resume task evaluation and dispatch'
              : 'Pause new task evaluation and dispatch; running agents keep their work'}
          >
            {status.paused
              ? <Play size={16} className="shrink-0" aria-hidden="true" />
              : <Pause size={16} className="shrink-0" aria-hidden="true" />}
            <div className="flex-1 min-w-0 text-left">
              <div className="text-[10px] text-gray-600">Queue</div>
              <div className={`${status.paused ? 'text-xs' : 'text-sm'} font-bold`}>{status.paused ? 'Resume' : 'Pause'}</div>
            </div>
          </button>
          <button
            type="button"
            onClick={handleStop}
            className="bg-port-error/20 hover:bg-port-error/30 text-port-error border border-port-error/30 rounded px-2 py-1.5 flex items-center gap-2 transition-colors min-h-[52px]"
            aria-label="Stop Chief of Staff agent"
          >
            <Square size={16} className="shrink-0" aria-hidden="true" />
            <div className="flex-1 min-w-0 text-left">
              <div className="text-[10px] text-gray-600">Agent</div>
              <div className="text-sm font-bold text-port-error">Stop</div>
            </div>
          </button>
        </>
      ) : (
        <button
          type="button"
          onClick={handleStart}
          className="bg-port-success/20 hover:bg-port-success/30 text-port-success border border-port-success/30 rounded px-2 py-1.5 flex items-center gap-2 transition-colors min-h-[52px]"
          aria-label="Start Chief of Staff agent"
        >
          <Play size={16} className="shrink-0" aria-hidden="true" />
          <div className="flex-1 min-w-0 text-left">
            <div className="text-[10px] text-port-success/80">Agent</div>
            <div className="text-sm font-bold">Start</div>
          </div>
        </button>
      )}
    </>
  );

  const renderAvatar = (background = false) => {
    // A rigged record plays on the mini-character stage: the variant URL
    // resolves to its animated GLB, and its coverage drives the fallback to
    // a present clip. A record deleted after being picked 404s its HEAD
    // probe, so the stage shows the missing-model hint instead of a canvas.
    if (isRiggedAvatarStyle(avatarStyle)) {
      const record = riggedRecordForStyle(riggedAvatars, avatarStyle);
      return (
        <Suspense fallback={<div className="flex items-center justify-center h-full"><BrailleSpinner /></div>}>
          <LazyRiggedAvatar state={agentState} speaking={speaking} background={background} variant={avatarStyle} coverage={record?.coverage || null} />
        </Suspense>
      );
    }
    const LazyAvatar = LAZY_AVATARS[avatarStyle];
    if (LazyAvatar) {
      return (
        <Suspense fallback={<div className="flex items-center justify-center h-full"><BrailleSpinner /></div>}>
          <LazyAvatar state={agentState} speaking={speaking} background={background} />
        </Suspense>
      );
    }
    return <CoSCharacter state={agentState} speaking={speaking} />;
  };

  const navigation = (
    <TabPills
      tabs={visibleTabs}
      activeTab={activeTab}
      onChange={(id) => navigate(`/cos/${id}`)}
      mobileCompact
      ariaLabel="Chief of Staff sections"
      controlsIdPrefix={loading ? undefined : 'tabpanel'}
      className="w-full min-w-0 shrink-0"
    />
  );

  if (loading) {
    // Reserve the loaded two-pane shell (#4144) — `/cos` is an `isFullWidth`
    // route, so a centered spinner reserved nothing and the whole page jumped
    // into place on first paint. `desktopPanelCollapsed` comes from
    // localStorage, so the skeleton already knows which rail width to hold.
    return (
      <PageLayout className="@container/cos" bodyClassName="overflow-hidden"
        header={<PageHeader icon={Brain} title="Chief of Staff" />}
        navigation={navigation}
      >
        <PageSkeleton
          layout="split"
          label="Loading Chief of Staff"
          padded
          fullHeight
          bodyClassName="p-3 lg:p-4"
          sideCollapsed={desktopPanelCollapsed}
          splitContainer
          splitColsClass={desktopPanelCollapsed ? 'cos-wide:grid-cols-[0px_1fr]' : 'cos-wide:grid-cols-[320px_1fr]'}
          sideClassName="flex flex-col gap-3 border-b cos-wide:border-b-0 cos-wide:border-r border-port-accent-2/20 bg-gradient-to-b from-port-card/80 to-port-card/40 p-3 cos-wide:px-4 cos-wide:py-6 cos-wide:h-full cos-wide:overflow-hidden"
          sideHero
          sideBlocks={4}
          sideBlockColsClass="grid-cols-2"
        />
      </PageLayout>
    );
  }

  const statusKnown = typeof status?.running === 'boolean';
  const statusPlaceholder = statusReadFailed ? (
    <div role="alert" className="p-3 text-sm text-gray-400">
      Could not load CoS status.
      <button type="button" onClick={fetchData} className="ml-2 text-port-accent">Retry CoS status</button>
    </div>
  ) : (
    <div role="status" aria-label="Loading CoS status" className="p-3">
      <BrailleSpinner text="Loading CoS status" />
    </div>
  );

  return (
    <PageLayout className="@container/cos" bodyClassName="overflow-hidden"
      header={<PageHeader icon={Brain} title="Chief of Staff" />}
      navigation={navigation}
    >
    <div className={`relative flex flex-col cos-wide:grid ${desktopPanelCollapsed ? 'cos-wide:grid-cols-[0px_1fr]' : 'cos-wide:grid-cols-[320px_1fr]'} h-full overflow-hidden transition-[grid-template-columns] duration-200`}>
      {/* Agent Panel */}
      {!statusKnown ? (
        <div className="min-w-0 overflow-hidden border-b cos-wide:border-r border-port-border">
          <div className={desktopPanelCollapsed ? 'cos-wide:hidden' : ''}>{statusPlaceholder}</div>
        </div>
      ) : avatarStyle === 'ascii' ? (
        <>
          {/* Desktop: collapsed placeholder or full panel */}
          {desktopPanelCollapsed ? (
            <div className="hidden cos-wide:block overflow-hidden min-w-0" />
          ) : (
            <div className="hidden cos-wide:block relative min-w-0 w-full max-w-full cos-wide:w-[320px] cos-wide:max-w-[320px]">
              <button
                onClick={toggleDesktopPanel}
                className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center absolute top-2 right-2 z-10 p-1.5 text-gray-500 hover:text-white transition-colors rounded-md hover:bg-white/5"
                aria-label="Collapse CoS panel"
                title="Collapse CoS panel"
              >
                <PanelLeftClose size={16} />
              </button>
              <TerminalCoSPanel
                state={agentState}
                speaking={speaking}
                statusMessage={statusMessage}
                eventLogs={eventLogs}
                running={status?.running}
                onStart={handleStart}
                onStop={handleStop}
                stats={status?.stats}
              />
            </div>
          )}
          {/* Keep the mobile queue reachable while retaining terminal identity. */}
          <div className="cos-wide:hidden">
            <button onClick={toggleMobilePanel}
              className="flex items-center justify-between gap-2 w-full px-3 py-2 min-h-[44px]"
              aria-expanded={!agentPanelCollapsed} aria-controls="cos-terminal-mobile">
              <span>CoS <StatusIndicator running={status?.running} paused={status?.paused} /></span>
              {agentPanelCollapsed ? <ChevronDown size={18} /> : <ChevronUp size={18} />}
            </button>
            <div id="cos-terminal-mobile" hidden={agentPanelCollapsed}>
            <TerminalCoSPanel
              state={agentState}
              speaking={speaking}
              statusMessage={statusMessage}
              eventLogs={eventLogs}
              running={status?.running}
              onStart={handleStart}
              onStop={handleStop}
              stats={status?.stats}
            />
            </div>
          </div>
        </>
      ) : desktopPanelCollapsed ? (
        /* Collapsed SVG - desktop placeholder, mobile shows compact header */
        <>
          <div className="hidden cos-wide:block overflow-hidden min-w-0" />
          {/* Mobile: still show the compact header */}
          <div className="cos-wide:hidden border-b border-port-accent-2/20 bg-gradient-to-b from-port-card/80 to-port-card/40">
            <button
              onClick={toggleMobilePanel}
              className="flex items-center justify-between w-full px-3 py-2 bg-port-card/60 border-b border-port-accent-2/20 min-h-[40px]"
              aria-expanded={!agentPanelCollapsed}
              aria-controls="cos-agent-panel"
            >
              <div className="flex items-center gap-2">
                <h2
                  className="text-base font-bold"
                  style={{
                    background: COS_TITLE_GRADIENT,
                    WebkitBackgroundClip: 'text',
                    WebkitTextFillColor: 'transparent',
                    backgroundClip: 'text'
                  }}
                >
                  CoS
                </h2>
                <StatusIndicator running={status?.running} paused={status?.paused} />
              </div>
              <div className="flex items-center gap-1.5 text-gray-400">
                <StateLabel state={agentState} compact />
                {agentPanelCollapsed ? <ChevronDown size={18} /> : <ChevronUp size={18} />}
              </div>
            </button>
            {!agentPanelCollapsed && (
              <div className="flex flex-1 min-w-0 p-2">
                {/* Mobile Stats Grid */}
                <div className="flex-1 grid grid-cols-2 gap-1.5 relative z-10 content-center">
                  <StatCard label="Active" value={activeAgentCount} icon={<Cpu className="w-4 h-4 text-port-accent" />} active={activeAgentCount > 0} compact />
                  <StatCard label="Pending" value={pendingTaskCount} icon={<Clock className="w-4 h-4 text-port-warning" />} compact />
                  <StatCard label="Done" value={status?.stats?.tasksCompleted || 0} icon={<CheckCircle className="w-4 h-4 text-port-success" />} compact />
                  <StatCard {...issuesStatProps} icon={<AlertCircle className="w-4 h-4" />} compact />
                </div>
              </div>
            )}
          </div>
        </>
      ) : (
        <div className="relative flex flex-col border-b cos-wide:border-b-0 cos-wide:border-r border-port-accent-2/20 bg-gradient-to-b from-port-card/80 to-port-card/40 shrink-0 w-full max-w-full min-w-0 cos-wide:w-[320px] cos-wide:max-w-[320px] overflow-x-hidden cos-wide:h-full cos-wide:overflow-y-auto scrollbar-hide">
          {/* Desktop Collapse Button */}
          <button
            onClick={toggleDesktopPanel}
            className="min-h-[44px] min-w-[44px] items-center justify-center hidden cos-wide:flex absolute top-2 right-2 z-20 p-1.5 text-gray-500 hover:text-white transition-colors rounded-md hover:bg-white/5"
            aria-label="Collapse CoS panel"
            title="Collapse CoS panel"
          >
            <PanelLeftClose size={16} />
          </button>

          {/* Mobile Collapse Toggle Header */}
          <button
            onClick={toggleMobilePanel}
            className="cos-wide:hidden flex items-center justify-between w-full px-3 py-2 bg-port-card/60 border-b border-port-accent-2/20 min-h-[40px]"
            aria-expanded={!agentPanelCollapsed}
            aria-controls="cos-agent-panel"
          >
            <div className="flex items-center gap-2">
              <h2
                className="text-base font-bold"
                style={{
                  background: COS_TITLE_GRADIENT,
                  WebkitBackgroundClip: 'text',
                  WebkitTextFillColor: 'transparent',
                  backgroundClip: 'text'
                }}
              >
                CoS
              </h2>
              <StatusIndicator running={status?.running} paused={status?.paused} />
            </div>
            <div className="flex items-center gap-1.5 text-gray-400">
              <StateLabel state={agentState} compact />
              {agentPanelCollapsed ? <ChevronDown size={18} /> : <ChevronUp size={18} />}
            </div>
          </button>

          {/* Collapsible Content */}
          <div
            id="cos-agent-panel"
            className={`${agentPanelCollapsed ? 'hidden' : 'flex'} cos-wide:flex min-w-0 w-full max-w-full relative overflow-hidden ${hasCanvasAvatar ? 'flex-none min-h-[180px] sm:min-h-[190px] md:min-h-[190px] cos-wide:min-h-dvh-cap cos-wide:[--dvh-cap:460px] cos-wide:[--dvh-inset:1rem] xl:[--dvh-cap:620px]' : 'flex-1'}`}
          >
            {/* Background Effects */}
            <div
              className="absolute inset-0 z-0 pointer-events-none"
              style={{
                background: `
                  radial-gradient(circle at 50% 20%, rgba(99, 102, 241, 0.1) 0%, transparent 50%),
                  repeating-linear-gradient(0deg, transparent, transparent 50px, rgba(99, 102, 241, 0.03) 50px, rgba(99, 102, 241, 0.03) 51px)
                `
              }}
            />

            {hasCanvasAvatar && (
              // Cap the full-bleed avatar canvas to the panel's BASE height
              // (the same min-h the panel starts at) and anchor it to the top.
              // The panel itself uses min-h so it can grow to fit the stats grid
              // + event log without clipping; without this cap the inset-0 canvas
              // grows with the panel on desktop, dragging the framed avatar down
              // into the stats grid below it.
              <div className="absolute inset-0 cos-wide:bottom-auto cos-wide:h-dvh-cap cos-wide:[--dvh-cap:460px] cos-wide:[--dvh-inset:1rem] xl:[--dvh-cap:620px] z-[1] -translate-x-16 -translate-y-1 sm:translate-x-0 sm:-translate-y-6 md:-translate-y-8 cos-wide:-translate-y-28 xl:-translate-y-36">
                {renderAvatar(true)}
              </div>
            )}

            {/* Avatar UI overlays the full-width canvas stage for 3D styles. */}
            <div
              className={`${
                hasCanvasAvatar
                  ? 'absolute inset-y-0 left-0 w-[46%] p-2 sm:p-3'
                  : 'relative flex-1 w-full p-2'
              } min-w-0 cos-wide:relative cos-wide:inset-auto cos-wide:w-full cos-wide:max-w-full cos-wide:flex-none cos-wide:min-h-full cos-wide:px-4 cos-wide:py-6 flex flex-col items-center z-10`}
            >
              <div className="hidden cos-wide:block text-sm font-semibold tracking-widest uppercase text-port-text-muted mb-1 font-mono">
                Digital Assistant
              </div>
              <h2
                className="hidden cos-wide:block text-lg sm:text-xl cos-wide:text-2xl xl:text-3xl font-bold mb-2 cos-wide:mb-4"
                style={{
                  background: COS_TITLE_GRADIENT,
                  WebkitBackgroundClip: 'text',
                  WebkitTextFillColor: 'transparent',
                  backgroundClip: 'text'
                }}
              >
                Chief of Staff
              </h2>

              {isGenericStatusMessage(statusMessage) && <StatusPill state={agentState} message={statusMessage} />}
              {!hasCanvasAvatar && renderAvatar()}
              {hasCanvasAvatar && <div className="flex-none h-[5.75rem] sm:h-[4rem] md:h-[3rem] cos-wide:h-[11rem] xl:h-[12rem]" aria-hidden="true" />}
              <div className="hidden cos-wide:block">
                <StateLabel state={agentState} />
              </div>
              <div className={`${hasCanvasAvatar ? 'sm:-mt-4 md:-mt-6 cos-wide:mt-0' : ''} hidden sm:block`}>
                {!isGenericStatusMessage(statusMessage) && <StatusBubble message={statusMessage} />}
              </div>

              {/* Desktop Stats Grid - integrated into CoS sidebar (matches mobile compressed layout) */}
              <div className="hidden cos-wide:grid grid-cols-2 gap-1.5 w-full min-w-0 mt-3 relative z-10">
                {statsGridCards}
              </div>

              {status?.running && (
                <div className="hidden cos-wide:flex flex-1 min-h-0 w-full min-w-0 flex-col">
                  <EventLog logs={eventLogs} />
                </div>
              )}
            </div>

            {/* Mobile Stats Grid - shows core stats in compact 2-column layout */}
            <div className={`${hasCanvasAvatar ? 'ml-[46%] w-[54%] flex-none self-start content-start' : 'flex-1 content-center'} grid grid-cols-2 gap-1.5 p-2 cos-wide:hidden relative z-10`}>
              {statsGridCards}
            </div>
          </div>
        </div>
      )}

      {/* Content Panel. Flex column so the Mind tab can fill leftover height
          on desktop (its chat pane owns the internal scroll); other tabs still
          grow this region and scroll here as before. */}
      <div className="flex flex-1 min-h-0 min-w-0 flex-col overflow-hidden">
        {desktopPanelCollapsed && (
          <div className="hidden cos-wide:flex shrink-0 bg-port-bg items-center flex-wrap gap-3 px-3 lg:px-4 border-b border-port-border">
            <button onClick={toggleDesktopPanel} aria-label="Expand CoS panel"
              className="min-h-[44px] flex items-center gap-2 px-2 text-sm text-port-text">
              <PanelLeftOpen size={16} aria-hidden="true" /> CoS
            </button>
            {statusKnown ? <>
              <StatusIndicator running={status.running} paused={status.paused} />
              <StateLabel state={agentState} compact />
            </> : statusPlaceholder}
          </div>
        )}
        <div className="flex flex-1 min-h-0 min-w-0 flex-col overflow-y-auto overflow-x-hidden p-3 lg:p-4">
        {/* Stats Bar - hidden for SVG/canvas modes (now integrated into CoS sidebar);
            ascii/terminal mode keeps it because TerminalCoSPanel doesn't host the cards. */}
        <div className={`grid shrink-0 grid-cols-3 gap-1.5 sm:grid-cols-5 sm:gap-2 lg:gap-3 mb-3 sm:mb-4 lg:mb-6 ${avatarStyle !== 'ascii' ? 'hidden' : ''}`}>
          <StatCard
            label="Active"
            value={activeAgentCount}
            icon={<Cpu className="w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5 text-port-accent" />}
            active={activeAgentCount > 0}
            mini
          />
          <StatCard
            label="Pending"
            value={pendingTaskCount}
            icon={<Clock className="w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5 text-port-warning" />}
            mini
          />
          <StatCard
            label="Done"
            value={status?.stats?.tasksCompleted || 0}
            icon={<CheckCircle className="w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5 text-port-success" />}
            mini
          />
          <StatCard
            {...issuesStatProps}
            icon={<AlertCircle className="w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5" />}
            mini
          />
          {/* Learning Health - clickable to go to Learning tab */}
          <StatCard
            {...learningStatProps}
            value={learningRate ?? '—'}
            icon={<Brain className="w-3 h-3 sm:w-4 sm:h-4 lg:w-5 lg:h-5" />}
            mini
          />
        </div>

        {/* Tab Content */}
        {activeTab === 'briefing' && (
          <div role="tabpanel" id="tabpanel-briefing" aria-labelledby="tab-briefing">
            <Suspense fallback={<TabLoadFallback label="briefing" />}>
              <BriefingTab />
            </Suspense>
          </div>
        )}
        {activeTab === 'tasks' && (
          <div role="tabpanel" id="tabpanel-tasks" aria-labelledby="tab-tasks">
            <ActionableInsightsBanner insights={insights} onTaskUnblocked={handleTaskUnblocked} onRefresh={fetchData} />
            <Suspense fallback={<TabLoadFallback label="tasks" />}>
              <TasksTab completionRecovery={status?.completionRecovery} completedRevision={taskHistoryRevision} tasks={tasks} agents={agents} liveOutputs={liveOutputs} onRefresh={fetchData} onTaskAdded={handleUserTaskAdded} onTaskUnblocked={handleTaskUnblocked} onTaskDeleted={handleTaskDeleted} providers={providers} providersLoaded={providersLoaded} apps={apps} />
            </Suspense>
          </div>
        )}
        {activeTab === 'agents' && (
          <div role="tabpanel" id="tabpanel-agents" aria-labelledby="tab-agents">
            <Suspense fallback={<TabLoadFallback label="agents" />}>
              <AgentsTab completionRecovery={status?.completionRecovery} agentsLoaded={agentsLoaded} agentsError={agentsError} onRetryAgents={fetchQueue} completedRevision={completedRevision} agents={agents} onRefresh={fetchData} liveOutputs={liveOutputs} providers={providers} providersLoaded={providersLoaded} apps={apps} />
            </Suspense>
          </div>
        )}
        {activeTab === 'jobs' && (
          <div role="tabpanel" id="tabpanel-jobs" aria-labelledby="tab-jobs">
            <Suspense fallback={<TabLoadFallback label="jobs" />}>
              <JobsTab />
            </Suspense>
          </div>
        )}
        {activeTab === 'runs' && (
          <div role="tabpanel" id="tabpanel-runs" aria-labelledby="tab-runs">
            <Suspense fallback={<TabLoadFallback label="runs" />}>
              <RunsTab />
            </Suspense>
          </div>
        )}
        {activeTab === 'run-events' && (
          <div role="tabpanel" id="tabpanel-run-events" aria-labelledby="tab-run-events">
            <Suspense fallback={<TabLoadFallback label="run events" />}>
              <RunEventsTab />
            </Suspense>
          </div>
        )}
        {activeTab === 'mind' && (
          <div role="tabpanel" id="tabpanel-mind" aria-labelledby="tab-mind" className="flex min-h-0 flex-col xl:flex-1">
            <Suspense fallback={<TabLoadFallback label="mind" />}>
              <MindTab />
            </Suspense>
          </div>
        )}
        {activeTab === 'schedule' && (
          <div role="tabpanel" id="tabpanel-schedule" aria-labelledby="tab-schedule">
            <Suspense fallback={<TabLoadFallback label="schedule" />}>
              <ScheduleTab apps={apps} providers={providers} activeProviderId={activeProviderId} providersLoaded={providersLoaded} daemonRunning={status?.running} />
            </Suspense>
          </div>
        )}
        {activeTab === 'workflow' && (
          <div role="tabpanel" id="tabpanel-workflow" aria-labelledby="tab-workflow">
            <Suspense fallback={<TabLoadFallback label="workflow" />}>
              <WorkflowTab apps={apps} providers={providers} providersLoaded={providersLoaded} />
            </Suspense>
          </div>
        )}
        {activeTab === 'digest' && (
          <div role="tabpanel" id="tabpanel-digest" aria-labelledby="tab-digest">
            <Suspense fallback={<TabLoadFallback label="digest" />}>
              <DigestTab />
            </Suspense>
          </div>
        )}
        {activeTab === 'gsd' && (
          <div role="tabpanel" id="tabpanel-gsd" aria-labelledby="tab-gsd">
            <Suspense fallback={<TabLoadFallback label="GSD" />}>
              <GsdTab />
            </Suspense>
          </div>
        )}
        {activeTab === 'learning' && (
          <div role="tabpanel" id="tabpanel-learning" aria-labelledby="tab-learning">
            <Suspense fallback={<TabLoadFallback label="learning" />}>
              <LearningTab />
            </Suspense>
          </div>
        )}
        {activeTab === 'memory' && (
          <div role="tabpanel" id="tabpanel-memory" aria-labelledby="tab-memory">
            <Suspense fallback={<TabLoadFallback label="memory" />}>
              <MemoryTab apps={apps} />
            </Suspense>
          </div>
        )}
        {activeTab === 'health' && (
          <div role="tabpanel" id="tabpanel-health" aria-labelledby="tab-health">
            <Suspense fallback={<TabLoadFallback label="health" />}>
              <HealthTab health={health} healthLoading={!healthLoaded} healthError={healthError} onCheck={handleHealthCheck} />
            </Suspense>
          </div>
        )}
        {activeTab === 'config' && (
          <div role="tabpanel" id="tabpanel-config" aria-labelledby="tab-config">
            <Suspense fallback={<TabLoadFallback label="configuration" />}>
              <ConfigTab config={status?.config} onUpdate={fetchData} onEvaluate={handleForceEvaluate} avatarStyle={configAvatarStyle} setAvatarStyle={setAvatarStyle} riggedAvatars={riggedAvatars} />
            </Suspense>
          </div>
        )}
        </div>
      </div>
    </div>
    </PageLayout>
  );
}