diff --git a/apps/web/src/components/AgentsPanel.tsx b/apps/web/src/components/AgentsPanel.tsx new file mode 100644 index 0000000000..89d50e9340 --- /dev/null +++ b/apps/web/src/components/AgentsPanel.tsx @@ -0,0 +1,319 @@ +import { memo, useEffect, useRef, useState } from "react"; +import type { ThreadAgentSnapshot } from "@t3tools/contracts"; +import { + deriveAgentPanelState, + formatAgentTokenCount, + isTerminalAgentStatus, + type AgentPanelGroup, + type AgentPanelPhase, +} from "@t3tools/client-runtime/state/thread-agents"; +import { BotIcon, BracesIcon, CheckIcon, ChevronDownIcon, ChevronRightIcon } from "lucide-react"; +import { cn } from "~/lib/utils"; +import { Badge } from "./ui/badge"; +import { ScrollArea } from "./ui/scroll-area"; +import { formatDuration } from "../session-logic"; + +interface AgentsPanelProps { + agents: ReadonlyArray; + onOpenScript?: (scriptPath: string) => void; + mode?: "sheet" | "sidebar" | "embedded"; +} + +const STATUS_DOT_CLASS: Record = { + pending: "bg-muted-foreground/40", + running: "bg-sky-500 animate-status-pulse", + waiting: "bg-warning animate-status-pulse", + idle: "bg-sky-500/50", + completed: "bg-success", + failed: "bg-destructive", + stopped: "bg-muted-foreground/60", +}; + +const STATUS_LABEL: Record = { + pending: "Queued", + running: "Running", + waiting: "Waiting", + idle: "Idle · resumable", + completed: "Completed", + failed: "Failed", + stopped: "Stopped", +}; + +function AgentStatusDot({ status }: { status: ThreadAgentSnapshot["status"] }) { + return ( + + ); +} + +/** + * Self-ticking elapsed label (WorkingTimer pattern): writes its own text node + * so per-second updates never cause React commits. Frozen once `endedAt` is + * set or the agent settles. + */ +function AgentElapsed({ agent }: { agent: ThreadAgentSnapshot }) { + const textRef = useRef(null); + const settled = isTerminalAgentStatus(agent.status) || agent.status === "idle"; + const startMs = Date.parse(agent.firstStartedAt); + const endMs = agent.endedAt + ? Date.parse(agent.endedAt) + : settled + ? Date.parse(agent.lastActivityAt) + : null; + const initialText = formatDuration((endMs ?? Date.now()) - startMs); + + useEffect(() => { + if (endMs !== null) return; + const update = () => { + if (textRef.current) { + textRef.current.textContent = formatDuration(Date.now() - startMs); + } + }; + update(); + const id = setInterval(update, 1000); + return () => clearInterval(id); + }, [startMs, endMs]); + + return ( + + {initialText} + + ); +} + +function AgentCard({ agent }: { agent: ThreadAgentSnapshot }) { + const [expanded, setExpanded] = useState(false); + const settled = isTerminalAgentStatus(agent.status); + const activity = + agent.status === "waiting" + ? "Waiting on approval" + : (agent.currentActivity ?? + (agent.lastToolName ? `▸ ${agent.lastToolName}` : null) ?? + agent.resultSummary ?? + agent.errorMessage); + const hasFeed = agent.recentActivity.length > 0; + + return ( + + ); +} + +function PhaseHeader({ phase }: { phase: AgentPanelPhase }) { + const runningCount = phase.agents.filter((agent) => agent.status === "running").length; + const doneCount = phase.agents.filter((agent) => isTerminalAgentStatus(agent.status)).length; + return ( +
+ + {phase.status === "done" ? "✓ " : ""} + {phase.title} + + {phase.status === "running" ? ( + + {runningCount} running{doneCount > 0 ? ` · ${doneCount} done` : ""} + + ) : phase.status === "pending" ? ( + pending + ) : null} + +
+ ); +} + +function AgentGroup({ + group, + onOpenScript, +}: { + group: AgentPanelGroup; + onOpenScript?: ((scriptPath: string) => void) | undefined; +}) { + const scriptPath = group.workflow?.scriptPath; + return ( +
+
+ {group.workflow ? ( + <> + Workflow · {group.workflow.name} + {scriptPath && onOpenScript ? ( + { + event.stopPropagation(); + onOpenScript(scriptPath); + }} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.stopPropagation(); + onOpenScript(scriptPath); + } + }} + className="inline-flex cursor-pointer items-center gap-1 font-mono text-[10px] font-medium tracking-normal text-primary normal-case hover:underline" + > + script + + ) : null} + + ) : ( + Direct spawns + )} + +
+ {group.phases.map((phase) => ( +
+ +
+ {phase.agents.map((agent) => ( + + ))} +
+
+ ))} + {group.rest.length > 0 ? ( +
0 && "pt-2")}> + {group.rest.map((agent) => ( + + ))} +
+ ) : null} +
+ ); +} + +const AgentsPanel = memo(function AgentsPanel({ agents, onOpenScript, mode }: AgentsPanelProps) { + const state = deriveAgentPanelState(agents); + + if (agents.length === 0) { + return ( +
+ +

No agents yet

+

+ When this thread spawns subagents or runs a workflow, they show up here with live status + and token usage. +

+
+ ); + } + + return ( +
+ +
+ {state.groups.map((group, index) => ( + + ))} +
+
+
+ {state.runningCount > 0 ? ( + + + {state.runningCount} running + + ) : null} + {state.waitingCount > 0 ? {state.waitingCount} waiting : null} + {state.settledCount > 0 ? {state.settledCount} settled : null} + + Σ {formatAgentTokenCount(state.totalTokens)} tok + +
+
+ ); +}); + +export default AgentsPanel; diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index c296c71706..8648ad7fe7 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -85,6 +85,7 @@ import { hasActionableProposedPlan, isLatestTurnSettled, } from "../session-logic"; +import { deriveLatestAgentSnapshot } from "@t3tools/client-runtime/state/thread-agents"; import { type LegendListRef } from "@legendapp/list/react"; import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring"; import { @@ -136,6 +137,8 @@ import { RightPanelTabs } from "./RightPanelTabs"; import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider"; import { BranchToolbar } from "./BranchToolbar"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; +import AgentsPanel from "./AgentsPanel"; +import AgentsLiveStrip from "./chat/AgentsLiveStrip"; import PlanSidebar from "./PlanSidebar"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; import { ChevronDownIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react"; @@ -1862,6 +1865,10 @@ function ChatViewContent(props: ChatViewProps) { const phase = derivePhase(activeThread?.session ?? null); const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]); + const threadAgents = useMemo( + () => deriveLatestAgentSnapshot(threadActivities), + [threadActivities], + ); const pendingApprovals = useMemo( () => derivePendingApprovals(threadActivities), [threadActivities], @@ -2926,6 +2933,10 @@ function ChatViewContent(props: ChatViewProps) { if (!activeThreadRef || !activeProject) return; useRightPanelStore.getState().open(activeThreadRef, "files"); }, [activeProject, activeThreadRef]); + const addAgentsSurface = useCallback(() => { + if (!activeThreadRef) return; + useRightPanelStore.getState().open(activeThreadRef, "agents"); + }, [activeThreadRef]); const openFileSurface = useCallback( (relativePath: string) => { if (!activeThreadRef || !activeProject) return; @@ -2933,6 +2944,21 @@ function ChatViewContent(props: ChatViewProps) { }, [activeProject, activeThreadRef], ); + // Workflow scripts live in the provider's session directory, outside the + // workspace root the file surface can read. Open in-workspace paths in the + // file surface; copy the absolute path otherwise. + const openAgentScript = useCallback( + (scriptPath: string) => { + if (activeWorkspaceRoot && scriptPath.startsWith(`${activeWorkspaceRoot}/`)) { + openFileSurface(scriptPath.slice(activeWorkspaceRoot.length + 1)); + return; + } + void navigator.clipboard.writeText(scriptPath).then(() => { + toastManager.add({ title: "Script path copied", description: scriptPath }); + }); + }, + [activeWorkspaceRoot, openFileSurface], + ); const togglePreviewPanel = useCallback(() => { if (!activeThreadRef || !isPreviewSupportedInRuntime()) return; if (previewPanelOpen) { @@ -5150,6 +5176,8 @@ function ChatViewContent(props: ChatViewProps) { initialGitScope={initialDiffPanelGitScope} /> + ) : activeRightPanelSurface?.kind === "agents" ? ( + ) : activeRightPanelSurface?.kind === "plan" ? ( )} + {threadAgents.length > 0 ? ( +
+ +
+ ) : null}
void; onAddDiff: () => void; onAddFiles: () => void; + onAddAgents: () => void; browserAvailable: boolean; diffAvailable: boolean; filesAvailable: boolean; @@ -91,6 +92,7 @@ function RightPanelEmptyState(props: { onAddTerminal: () => void; onAddDiff: () => void; onAddFiles: () => void; + onAddAgents: () => void; browserAvailable: boolean; diffAvailable: boolean; filesAvailable: boolean; @@ -128,6 +130,14 @@ function RightPanelEmptyState(props: { disabledReason: SURFACE_DISABLED_REASONS.diff, onClick: props.onAddDiff, }, + { + label: "Agents", + description: "Watch subagents and workflows run.", + icon: Bot, + available: true, + disabledReason: null, + onClick: props.onAddAgents, + }, ] as const; return ( @@ -205,6 +215,8 @@ function surfaceTitle( ); case "plan": return "Plan"; + case "agents": + return "Agents"; case "preview": { const snapshot = surface.resourceId ? sessions[surface.resourceId] : null; if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser"; @@ -266,6 +278,8 @@ function SurfaceIcon({ return ; case "plan": return ; + case "agents": + return ; } } @@ -470,6 +484,10 @@ export function RightPanelTabs(props: RightPanelTabsProps) { Diff + + + Agents + ) : null} @@ -484,6 +502,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { onAddTerminal={props.onAddTerminal} onAddDiff={props.onAddDiff} onAddFiles={props.onAddFiles} + onAddAgents={props.onAddAgents} browserAvailable={props.browserAvailable} diffAvailable={props.diffAvailable} filesAvailable={props.filesAvailable} diff --git a/apps/web/src/components/chat/AgentsLiveStrip.tsx b/apps/web/src/components/chat/AgentsLiveStrip.tsx new file mode 100644 index 0000000000..0c158be439 --- /dev/null +++ b/apps/web/src/components/chat/AgentsLiveStrip.tsx @@ -0,0 +1,63 @@ +import { memo } from "react"; +import type { ThreadAgentSnapshot } from "@t3tools/contracts"; +import { + deriveAgentPanelState, + formatAgentTokenCount, +} from "@t3tools/client-runtime/state/thread-agents"; +import { BotIcon, ChevronRightIcon } from "lucide-react"; +import { cn } from "~/lib/utils"; + +/** + * Collapsed one-line agent roster shown near the composer while agents are + * live. Clicking opens the Agents panel — this strip is awareness only. + */ +const AgentsLiveStrip = memo(function AgentsLiveStrip({ + agents, + onOpen, +}: { + agents: ReadonlyArray; + onOpen: () => void; +}) { + const state = deriveAgentPanelState(agents); + const liveCount = state.runningCount + state.waitingCount; + if (liveCount === 0) { + return null; + } + + const runningPhase = state.groups + .flatMap((group) => group.phases) + .find((phase) => phase.status === "running"); + + return ( + + ); +}); + +export default AgentsLiveStrip; diff --git a/apps/web/src/rightPanelStore.ts b/apps/web/src/rightPanelStore.ts index 70d163306c..cccb7238ca 100644 --- a/apps/web/src/rightPanelStore.ts +++ b/apps/web/src/rightPanelStore.ts @@ -14,7 +14,15 @@ import { createJSONStorage, persist } from "zustand/middleware"; import { resolveStorage } from "./lib/storage"; -export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const; +export const RIGHT_PANEL_KINDS = [ + "plan", + "diff", + "files", + "file", + "preview", + "terminal", + "agents", +] as const; export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number]; export type RightPanelSurface = @@ -37,10 +45,11 @@ export type RightPanelSurface = revealLine: number | null; revealRequestId: number; } - | { id: "plan"; kind: "plan" }; + | { id: "plan"; kind: "plan" } + | { id: "agents"; kind: "agents" }; const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2"; -const RIGHT_PANEL_STORAGE_VERSION = 7; +const RIGHT_PANEL_STORAGE_VERSION = 8; export interface ThreadRightPanelState { isOpen: boolean; @@ -92,6 +101,8 @@ const singletonSurface = ( return { id: "files", kind }; case "plan": return { id: "plan", kind }; + case "agents": + return { id: "agents", kind }; } }; diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 5d5051f748..8ee996c84d 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -633,6 +633,7 @@ export function deriveWorkLogEntries( if (activity.kind === "tool.started") continue; if (activity.kind === "task.started") continue; if (activity.kind === "context-window.updated") continue; + if (activity.kind === "agent.snapshot") continue; if (activity.summary === "Checkpoint captured") continue; if (isPlanBoundaryToolActivity(activity)) continue; entries.push(toDerivedWorkLogEntry(activity)); diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index d9e1988972..07707217c9 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -119,6 +119,10 @@ "types": "./src/state/terminal.ts", "default": "./src/state/terminal.ts" }, + "./state/thread-agents": { + "types": "./src/state/threadAgents.ts", + "default": "./src/state/threadAgents.ts" + }, "./state/threads": { "types": "./src/state/threads.ts", "default": "./src/state/threads.ts" diff --git a/packages/client-runtime/src/state/threadAgents.ts b/packages/client-runtime/src/state/threadAgents.ts new file mode 100644 index 0000000000..276f3f379c --- /dev/null +++ b/packages/client-runtime/src/state/threadAgents.ts @@ -0,0 +1,137 @@ +/** + * Derivation helpers for the thread agent roster. + * + * The server ships the full per-thread roster latest-wins in the payload of + * `agent.snapshot` activities (see `@t3tools/contracts` ThreadAgentsActivityPayload). + * Mirrors the `context-window.updated` pattern: scan activities newest-first, + * decode tolerantly, ignore rows that fail to decode. + */ +import { + THREAD_AGENT_TERMINAL_STATUSES, + THREAD_AGENTS_ACTIVITY_KIND, + ThreadAgentsActivityPayload, + type OrchestrationThreadActivity, + type ThreadAgentSnapshot, +} from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; + +const decodePayload = Schema.decodeUnknownOption(ThreadAgentsActivityPayload); + +export function deriveLatestAgentSnapshot( + activities: ReadonlyArray, +): ReadonlyArray { + for (let index = activities.length - 1; index >= 0; index -= 1) { + const activity = activities[index]; + if (!activity || activity.kind !== THREAD_AGENTS_ACTIVITY_KIND) { + continue; + } + const decoded = decodePayload(activity.payload); + if (decoded._tag === "Some") { + return decoded.value.agents; + } + } + return []; +} + +export function isTerminalAgentStatus(status: ThreadAgentSnapshot["status"]): boolean { + return THREAD_AGENT_TERMINAL_STATUSES.has(status); +} + +export interface AgentPanelGroup { + /** The workflow snapshot this group belongs to, or null for direct spawns. */ + readonly workflow: ThreadAgentSnapshot | null; + /** Phase sections in declared order; agents without a phase land in `rest`. */ + readonly phases: ReadonlyArray; + readonly rest: ReadonlyArray; +} + +export interface AgentPanelPhase { + readonly index: number; + readonly title: string; + readonly status: "pending" | "running" | "done"; + readonly agents: ReadonlyArray; +} + +export interface AgentPanelState { + readonly groups: ReadonlyArray; + readonly runningCount: number; + readonly waitingCount: number; + readonly settledCount: number; + readonly totalTokens: number; +} + +function phaseStatus(agents: ReadonlyArray): "pending" | "running" | "done" { + if (agents.length === 0) return "pending"; + if (agents.every((agent) => isTerminalAgentStatus(agent.status))) return "done"; + return "running"; +} + +export function deriveAgentPanelState(agents: ReadonlyArray): AgentPanelState { + const workflows = agents.filter((agent) => agent.kind === "workflow"); + const byParent = new Map(); + const direct: ThreadAgentSnapshot[] = []; + for (const agent of agents) { + if (agent.kind === "workflow") continue; + if (agent.parentAgentId) { + const list = byParent.get(agent.parentAgentId) ?? []; + list.push(agent); + byParent.set(agent.parentAgentId, list); + } else { + direct.push(agent); + } + } + + const groups: AgentPanelGroup[] = []; + for (const workflow of workflows) { + const members = byParent.get(workflow.agentId) ?? []; + byParent.delete(workflow.agentId); + const declaredPhases = workflow.phases ?? []; + const phases: AgentPanelPhase[] = declaredPhases.map((phase) => { + const phaseAgents = members.filter((agent) => agent.phaseIndex === phase.index); + return { + index: phase.index, + title: phase.title, + status: phaseStatus(phaseAgents), + agents: phaseAgents, + }; + }); + const inDeclaredPhase = new Set( + phases.flatMap((phase) => phase.agents.map((agent) => agent.agentId)), + ); + groups.push({ + workflow, + phases, + rest: members.filter((agent) => !inDeclaredPhase.has(agent.agentId)), + }); + } + // Orphaned parent groups (parent never materialized) fold into direct spawns. + for (const list of byParent.values()) { + direct.push(...list); + } + if (direct.length > 0) { + groups.push({ workflow: null, phases: [], rest: direct }); + } + + let runningCount = 0; + let waitingCount = 0; + let settledCount = 0; + let totalTokens = 0; + for (const agent of agents) { + if (agent.status === "running" || agent.status === "pending") runningCount += 1; + else if (agent.status === "waiting") waitingCount += 1; + else if (isTerminalAgentStatus(agent.status)) settledCount += 1; + totalTokens += agent.usage?.totalTokens ?? 0; + } + + return { groups, runningCount, waitingCount, settledCount, totalTokens }; +} + +export function formatAgentTokenCount(totalTokens: number): string { + if (totalTokens >= 1_000_000) { + return `${(totalTokens / 1_000_000).toFixed(1).replace(/\.0$/, "")}M`; + } + if (totalTokens >= 1_000) { + return `${(totalTokens / 1_000).toFixed(1).replace(/\.0$/, "")}k`; + } + return `${totalTokens}`; +}