diff --git a/CHANGELOG.md b/CHANGELOG.md index dfd53a7..8e8ad01 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- **Richer topology cards, project groups and filters.** Your own session cards + show the model, tokens and cost; every visible session shows its tool calls and + failures (`toolCalls` / `toolFailures` on `/api/sessions/active`, counted live + between fetches; not for activity-only viewers). Two or more of a developer's + sessions in one project hang under a project node. "Hide inactive" and "Hide + finished subagents" toggles are remembered per browser. + - **Topology detail panel.** Clicking a session or subagent opens a live side panel instead of leaving the page: state, branch, title, last active, model, tokens and cost (own sessions only), its subagents, the last 15 events, and a diff --git a/packages/backend/src/db/queries.ts b/packages/backend/src/db/queries.ts index 1f45c80..c3e4e04 100644 --- a/packages/backend/src/db/queries.ts +++ b/packages/backend/src/db/queries.ts @@ -141,7 +141,11 @@ export async function getActiveSessions(sql: SQL, developerIds?: string[]) { if (developerIds !== undefined) { return await sql` SELECT s.*, d.name as developer_name, d.email as developer_email, d.share_details as owner_share_details, - LEAST((SELECT MAX(e.created_at) FROM events e WHERE e.session_id = s.id), NOW()) as last_event_at + LEAST((SELECT MAX(e.created_at) FROM events e WHERE e.session_id = s.id), NOW()) as last_event_at, + (SELECT COUNT(*)::INT FROM events e + WHERE e.session_id = s.id AND e.event_type IN ('tool.complete', 'tool.fail')) as tool_calls, + (SELECT COUNT(*)::INT FROM events e + WHERE e.session_id = s.id AND e.event_type = 'tool.fail') as tool_failures FROM sessions s JOIN developers d ON s.developer_id = d.id WHERE s.status = 'active' AND s.developer_id IN (${inList(developerIds)}) @@ -149,7 +153,11 @@ export async function getActiveSessions(sql: SQL, developerIds?: string[]) { } return await sql` SELECT s.*, d.name as developer_name, d.email as developer_email, d.share_details as owner_share_details, - LEAST((SELECT MAX(e.created_at) FROM events e WHERE e.session_id = s.id), NOW()) as last_event_at + LEAST((SELECT MAX(e.created_at) FROM events e WHERE e.session_id = s.id), NOW()) as last_event_at, + (SELECT COUNT(*)::INT FROM events e + WHERE e.session_id = s.id AND e.event_type IN ('tool.complete', 'tool.fail')) as tool_calls, + (SELECT COUNT(*)::INT FROM events e + WHERE e.session_id = s.id AND e.event_type = 'tool.fail') as tool_failures FROM sessions s JOIN developers d ON s.developer_id = d.id WHERE s.status = 'active' diff --git a/packages/backend/src/routes/__tests__/sessions.test.ts b/packages/backend/src/routes/__tests__/sessions.test.ts index 3cf4c0f..f69a7d1 100644 --- a/packages/backend/src/routes/__tests__/sessions.test.ts +++ b/packages/backend/src/routes/__tests__/sessions.test.ts @@ -325,6 +325,22 @@ describe("GET /sessions/active", () => { expect(body.find((s: any) => s.id === "sess-2").activeAgents).toEqual([]); }); + test("returns tool counts for visible sessions only", async () => { + const own = makeSessionRow({ id: "sess-1", tool_calls: 12, tool_failures: 2 }); + const teammate = makeSessionRow({ id: "sess-2", developer_id: "dev-bbb", owner_share_details: false, tool_calls: 7, tool_failures: 1 }); + mockGetActiveSessions.mockImplementation(() => Promise.resolve([own, teammate])); + mockGetActiveAgents.mockImplementation(() => Promise.resolve([])); + mockGetAllDeveloperIdsForUser.mockImplementation(() => Promise.resolve(["dev-aaa"])); + + const app = buildApp({ orgDeveloperIds: ["dev-aaa", "dev-bbb"], user: { id: "user-1" } }); + const body = await (await app.request("/sessions/active")).json(); + + expect(body.find((s: any) => s.id === "sess-1")).toMatchObject({ toolCalls: 12, toolFailures: 2 }); + const s2 = body.find((s: any) => s.id === "sess-2"); + expect(s2.toolCalls).toBeUndefined(); + expect(s2.toolFailures).toBeUndefined(); + }); + test("passes orgDeveloperIds to getActiveSessions", async () => { const devIds = ["dev-aaa"]; const app = buildApp({ orgDeveloperIds: devIds }); diff --git a/packages/backend/src/routes/sessions.ts b/packages/backend/src/routes/sessions.ts index e350247..e68fdaf 100644 --- a/packages/backend/src/routes/sessions.ts +++ b/packages/backend/src/routes/sessions.ts @@ -21,6 +21,9 @@ function mapSession(row: any) { startedAt: row.started_at, endedAt: row.ended_at, lastEventAt: row.last_event_at ?? null, + // Only /active selects these; absent keys stay out of the JSON. + toolCalls: row.tool_calls != null ? Number(row.tool_calls) : undefined, + toolFailures: row.tool_failures != null ? Number(row.tool_failures) : undefined, status: row.status, permissionMode: row.permission_mode ?? null, privacyMode: row.privacy_mode ?? null, diff --git a/packages/dashboard/src/components/flow/DetailPanel.tsx b/packages/dashboard/src/components/flow/DetailPanel.tsx index c85165f..71fc9e3 100644 --- a/packages/dashboard/src/components/flow/DetailPanel.tsx +++ b/packages/dashboard/src/components/flow/DetailPanel.tsx @@ -6,7 +6,7 @@ import type { FeedEvent } from "@devscope/shared"; import type { SessionNodeData, AgentNodeData, AgentSummaryNodeData } from "./flowTypes"; import { STATE_CONFIG } from "./sessionStates"; import { EVENT_LABELS, getEventSummary } from "@/lib/eventDisplay"; -import { formatCost, formatTokenCount, timeAgo } from "@/lib/utils"; +import { formatCost, formatTokenCount, sessionTokenTotal, timeAgo } from "@/lib/utils"; import { ProjectLabel } from "@/components/ProjectLabel"; interface DetailPanelProps { @@ -41,7 +41,7 @@ export function DetailPanel({ node, nodes, onClose }: DetailPanelProps) { } function SessionDetails({ data, nodes }: { data: SessionNodeData; nodes: Node[] }) { - const { session, activityState, lastActivityAt, recentEvents } = data; + const { session, activityState, lastActivityAt, recentEvents, toolCalls, toolFailures } = data; const state = STATE_CONFIG[activityState]; const agents = nodes.filter( (n) => n.type === "agent" && (n.data as AgentNodeData).sessionId === session.id, @@ -51,11 +51,6 @@ function SessionDetails({ data, nodes }: { data: SessionNodeData; nodes: Node[] )?.data as AgentSummaryNodeData | undefined; // Usage is only returned for the viewer's own sessions. const hasUsage = session.tokenSource != null; - const totalTokens = - (session.totalInputTokens ?? 0) + - (session.totalOutputTokens ?? 0) + - (session.totalCacheCreationTokens ?? 0) + - (session.totalCacheReadTokens ?? 0); return (
@@ -83,7 +78,13 @@ function SessionDetails({ data, nodes }: { data: SessionNodeData; nodes: Node[] {session.model ? {session.model} : null} {hasUsage ? ( - {formatTokenCount(totalTokens)} · {formatCost(session.estimatedCostUsd ?? 0)} + {formatTokenCount(sessionTokenTotal(session))} · {formatCost(session.estimatedCostUsd ?? 0)} + + ) : null} + {toolCalls != null ? ( + + {toolCalls} + {toolFailures ? · {toolFailures} failed : null} ) : null} diff --git a/packages/dashboard/src/components/flow/FlowView.tsx b/packages/dashboard/src/components/flow/FlowView.tsx index 6afab5c..edcd4cb 100644 --- a/packages/dashboard/src/components/flow/FlowView.tsx +++ b/packages/dashboard/src/components/flow/FlowView.tsx @@ -10,7 +10,7 @@ import "@xyflow/react/dist/style.css"; import type { AgentSummaryNodeData } from "./flowTypes"; import { DetailPanel } from "./DetailPanel"; import { nodeTypes } from "./nodeTypes"; -import { useFlowLayout } from "./useFlowLayout"; +import { useFlowLayout, type FlowFilters } from "./useFlowLayout"; import { useActivityStore } from "@/stores/activityStore"; class FlowErrorBoundary extends Component< @@ -44,6 +44,26 @@ class FlowErrorBoundary extends Component< } const CLEANUP_INTERVAL_MS = 10_000; +const FILTERS_STORAGE_KEY = "devscope.topology.filters"; +const DEFAULT_FILTERS: FlowFilters = { hideInactive: false, hideDoneAgents: false }; + +/** Filters are a per-viewer convenience; storage may be unavailable. */ +function loadFilters(): FlowFilters { + try { + const stored = localStorage.getItem(FILTERS_STORAGE_KEY); + return stored ? { ...DEFAULT_FILTERS, ...(JSON.parse(stored) as Partial) } : DEFAULT_FILTERS; + } catch { + return DEFAULT_FILTERS; + } +} + +function saveFilters(filters: FlowFilters): void { + try { + localStorage.setItem(FILTERS_STORAGE_KEY, JSON.stringify(filters)); + } catch { + // Not remembered this time; the filters still apply. + } +} /** The node whose details a click opens: sessions and agents; the done card opens its session. */ function selectionFor(node: Node): string | null { @@ -53,7 +73,13 @@ function selectionFor(node: Node): string | null { } export function FlowView() { - const { nodes: layoutNodes, edges: layoutEdges } = useFlowLayout(); + const [filters, setFilters] = useState(loadFilters); + const { nodes: layoutNodes, edges: layoutEdges } = useFlowLayout(filters); + const toggleFilter = (key: keyof FlowFilters) => { + const next = { ...filters, [key]: !filters[key] }; + setFilters(next); + saveFilters(next); + }; const connected = useActivityStore((s) => s.connected); const cleanupStale = useActivityStore((s) => s.cleanupStale); const [selectedId, setSelectedId] = useState(null); @@ -119,12 +145,16 @@ export function FlowView() { nodeColor={(node) => { if (node.type === "developer") return "#10b981"; if (node.type === "agent") return "#a855f7"; - if (node.type === "agentSummary") return "#374151"; + if (node.type === "agentSummary" || node.type === "project") return "#374151"; return "#6b7280"; }} maskColor="rgba(0, 0, 0, 0.7)" /> +
+ toggleFilter("hideInactive")} /> + toggleFilter("hideDoneAgents")} /> +
{selectedNode ? ( setSelectedId(null)} /> ) : null} @@ -132,3 +162,19 @@ export function FlowView() {
); } + +function FilterToggle({ label, active, onClick }: { label: string; active: boolean; onClick: () => void }) { + return ( + + ); +} diff --git a/packages/dashboard/src/components/flow/ProjectNode.tsx b/packages/dashboard/src/components/flow/ProjectNode.tsx new file mode 100644 index 0000000..8cfed45 --- /dev/null +++ b/packages/dashboard/src/components/flow/ProjectNode.tsx @@ -0,0 +1,25 @@ +import { Handle, Position, type NodeProps } from "@xyflow/react"; +import { motion } from "motion/react"; +import { Folder } from "lucide-react"; +import type { ProjectNodeData } from "./flowTypes"; +import { ProjectLabel } from "@/components/ProjectLabel"; + +export function ProjectNode({ data }: NodeProps & { data: ProjectNodeData }) { + const { projectName, sessionCount } = data; + + return ( + + + + + {sessionCount} sessions + + + ); +} diff --git a/packages/dashboard/src/components/flow/SessionNode.tsx b/packages/dashboard/src/components/flow/SessionNode.tsx index 896cc87..3f6aea9 100644 --- a/packages/dashboard/src/components/flow/SessionNode.tsx +++ b/packages/dashboard/src/components/flow/SessionNode.tsx @@ -7,7 +7,7 @@ import type { PromptEventPayload, AgentEventPayload } from "@devscope/shared"; import { ShieldOff, Lock, GitBranch } from "lucide-react"; import { ActivityBadge } from "./ActivityBadge"; import { useDebouncedToolState } from "@/hooks/useDebouncedToolState"; -import { timeAgo } from "@/lib/utils"; +import { formatCost, formatTokenCount, sessionTokenTotal, timeAgo } from "@/lib/utils"; import { ProjectLabel } from "@/components/ProjectLabel"; const EVENT_LABELS: Record = { @@ -58,8 +58,18 @@ const EVENT_COLORS: Record = { "teammate.idle": "text-gray-400 bg-gray-500/15", }; +/** "claude-opus-5-5" → "opus-5-5", short enough for a card. */ +function shortModel(model: string | null | undefined): string | null { + return model ? model.replace(/^claude-/, "") : null; +} + export function SessionNode({ data, selected }: NodeProps & { data: SessionNodeData }) { - const { session, latestEvent, isToolRunning, currentToolName, activityState, lastActivityAt } = data; + const { session, latestEvent, isToolRunning, currentToolName, activityState, lastActivityAt, toolCalls, toolFailures } = data; + // Usage is only returned for the viewer's own sessions. + const usage = session.tokenSource != null + ? `${formatTokenCount(sessionTokenTotal(session))} tok · ${formatCost(session.estimatedCostUsd ?? 0)}` + : null; + const meta = [shortModel(session.model), usage].filter(Boolean).join(" · "); const isDangerousMode = session.permissionMode === "dangerously-skip-permissions"; const isRedactedMode = session.privacyMode === "private"; @@ -143,9 +153,16 @@ export function SessionNode({ data, selected }: NodeProps & { data: SessionNodeD -
- active {timeAgo(lastActivityAt)} +
+ active {timeAgo(lastActivityAt)} + {toolCalls != null ? ( + + {toolCalls} tools + {toolFailures ? · {toolFailures} failed : null} + + ) : null}
+ {meta ?
{meta}
: null} b.count - a.count); } -export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { - const { developers, activeSessions, activeAgents, stoppedAgents, events, latestSessionEvents } = +export interface FlowFilters { + hideInactive: boolean; + hideDoneAgents: boolean; +} + +interface SessionActivity { + ownEvents: FeedEvent[]; + latestEvent: FeedEvent | null; + lastActivityAt: string; + state: SessionActivityState; +} + +/** Edges carry the sessions below them, so an edge animates while any of them works. */ +interface FlowEdgeData { + [key: string]: unknown; + sessionIds: string[]; +} + +export function useFlowLayout(filters: FlowFilters): { nodes: Node[]; edges: Edge[] } { + const { developers, activeSessions, activeAgents, stoppedAgents, events, latestSessionEvents, toolCounts } = useActivityStore( useShallow((s) => ({ developers: s.developers, @@ -171,6 +190,7 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { stoppedAgents: s.stoppedAgents, events: s.events, latestSessionEvents: s.latestSessionEvents, + toolCounts: s.toolCounts, })), ); const now = useNow(NOW_REFRESH_MS); @@ -184,9 +204,52 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { [activeAgents, stoppedAgents], ); + // Stage 0: each session's own events and state. Feeds both the filters and stage 2. + const sessionActivity = useMemo(() => { + const activity = new Map(); + for (const session of activeSessions) { + const allSessionEvents = events.filter((e) => e.sessionId === session.id); + const sessionAgents = allAgents.filter( + (a) => a.sessionId === session.id && a.agentId != null, + ); + const { sessionEvents: ownEvents } = + attributeEventsToAgents(allSessionEvents, sessionAgents, events); + const latestEvent = ownEvents[0] ?? latestSessionEvents[session.id] ?? null; + const lastActivityAt = clampToNow( + latestTimestamp( + session.startedAt, + session.lastEventAt, + allSessionEvents[0]?.timestamp, + latestSessionEvents[session.id]?.timestamp, + ), + now, + ); + activity.set(session.id, { + ownEvents, + latestEvent, + lastActivityAt, + state: deriveSessionState(session, latestEvent, lastActivityAt, now), + }); + } + return activity; + }, [activeSessions, events, latestSessionEvents, allAgents, now]); + + // A string, so the layout re-runs only when the set of hidden sessions changes. + const hiddenSessionKey = filters.hideInactive + ? activeSessions + .filter((s) => sessionActivity.get(s.id)?.state === "inactive") + .map((s) => s.id) + .sort() + .join(",") + : ""; + const { hideDoneAgents } = filters; + // Stage 1: Build graph structure and run dagre layout. // Only re-runs when the topology changes (nodes added/removed), not on every event. const { positionedNodes, layoutEdges } = useMemo(() => { + const hidden = new Set(hiddenSessionKey ? hiddenSessionKey.split(",") : []); + const visibleSessions = activeSessions.filter((s) => !hidden.has(s.id)); + // Developers stay visible with their counts even when every session is hidden. const developerIds = new Set(activeSessions.map((s) => s.developerId)); const activeDevelopers = developers.filter((d) => developerIds.has(d.id)); @@ -208,10 +271,36 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { }); } - // Session + agent nodes (placeholder event data — filled in stage 2) - for (const session of activeSessions) { - const devId = session.developerId; + // A developer's sessions sharing a project hang under one project node. + const projectGroups = new Map(); + for (const session of visibleSessions) { + if (!session.projectName) continue; + const key = `project-${session.developerId}-${session.projectName}`; + projectGroups.set(key, [...(projectGroups.get(key) ?? []), session]); + } + const parentNodeId = new Map(); + for (const [projectNodeId, sessions] of projectGroups) { + if (sessions.length < 2) continue; + const devId = sessions[0].developerId; + const data: ProjectNodeData = { + projectName: sessions[0].projectName!, + sessionCount: sessions.length, + }; + nodes.push({ id: projectNodeId, type: "project", position: { x: 0, y: 0 }, data }); + const edgeData: FlowEdgeData = { sessionIds: sessions.map((s) => s.id) }; + edges.push({ + id: `edge-${devId}-${projectNodeId}`, + source: `dev-${devId}`, + target: projectNodeId, + type: "smoothstep", + data: edgeData, + style: { stroke: "#4b5563" }, + }); + for (const session of sessions) parentNodeId.set(session.id, projectNodeId); + } + // Session + agent nodes (placeholder event data — filled in stage 2) + for (const session of visibleSessions) { const data: SessionNodeData = { session, recentEvents: [], @@ -220,6 +309,8 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { currentToolName: null, activityState: "idle", lastActivityAt: session.startedAt, + toolCalls: null, + toolFailures: null, }; nodes.push({ @@ -229,12 +320,14 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { data, }); + const source = parentNodeId.get(session.id) ?? `dev-${session.developerId}`; + const edgeData: FlowEdgeData = { sessionIds: [session.id] }; edges.push({ - id: `edge-${devId}-${session.id}`, - source: `dev-${devId}`, + id: `edge-${source}-${session.id}`, + source, target: `session-${session.id}`, type: "smoothstep", - data: { sessionId: session.id }, + data: edgeData, style: { stroke: "#4b5563" }, }); @@ -273,7 +366,7 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { } const doneAgents = sessionAgents.filter((a) => a.stopped); - if (doneAgents.length > 0) { + if (doneAgents.length > 0 && !hideDoneAgents) { const summaryData: AgentSummaryNodeData = { sessionId: session.id, total: doneAgents.length, @@ -303,7 +396,7 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { const laid = getLayoutedElements(nodes, edges); return { positionedNodes: laid.nodes, layoutEdges: laid.edges }; - }, [developers, activeSessions, allAgents]); + }, [developers, activeSessions, allAgents, hiddenSessionKey, hideDoneAgents]); // Stage 2: Decorate positioned nodes with event- and time-derived data. // Runs on event changes and clock ticks but skips the expensive dagre layout. @@ -312,24 +405,13 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { return { nodes: [], edges: layoutEdges }; } - const sessionStates = new Map(); - - const decorated = positionedNodes.map((node) => { + const nodes = positionedNodes.map((node) => { if (node.type === "session") { const data = node.data as SessionNodeData; const sessionId = data.session.id; - - const allSessionEvents = events.filter( - (e) => e.sessionId === sessionId, - ); - const sessionAgents = allAgents.filter( - (a) => a.sessionId === sessionId && a.agentId != null, - ); - const { sessionEvents: ownEvents } = - attributeEventsToAgents(allSessionEvents, sessionAgents, events); - - const recentEvents = ownEvents.slice(0, RECENT_EVENT_LIMIT); - const latestEvent = ownEvents[0] ?? latestSessionEvents[sessionId] ?? null; + const activity = sessionActivity.get(sessionId); + if (!activity) return node; + const { latestEvent } = activity; let isToolRunning = false; let currentToolName: string | null = null; @@ -339,28 +421,18 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { currentToolName = payload.toolName ?? null; } - const lastActivityAt = clampToNow( - latestTimestamp( - data.session.startedAt, - data.session.lastEventAt, - allSessionEvents[0]?.timestamp, - latestSessionEvents[sessionId]?.timestamp, - ), - now, - ); - const activityState = deriveSessionState(data.session, latestEvent, lastActivityAt, now); - sessionStates.set(sessionId, activityState); - return { ...node, data: { ...data, - recentEvents, + recentEvents: activity.ownEvents.slice(0, RECENT_EVENT_LIMIT), latestEvent, isToolRunning, currentToolName, - activityState, - lastActivityAt, + activityState: activity.state, + lastActivityAt: activity.lastActivityAt, + toolCalls: toolCounts[sessionId]?.calls ?? null, + toolFailures: toolCounts[sessionId]?.failures ?? null, }, }; } @@ -399,30 +471,32 @@ export function useFlowLayout(): { nodes: Node[]; edges: Edge[] } { }; } - return node; - }); - - const nodes = decorated.map((node) => { - if (node.type !== "developer") return node; - const data = node.data as DeveloperNodeData; - let activeCount = 0; - let inactiveCount = 0; - for (const session of activeSessions) { - if (session.developerId !== data.developer.id) continue; - const state = sessionStates.get(session.id); - if (state === "inactive") inactiveCount++; - else if (state !== "ended") activeCount++; + if (node.type === "developer") { + const data = node.data as DeveloperNodeData; + let activeCount = 0; + let inactiveCount = 0; + for (const session of activeSessions) { + if (session.developerId !== data.developer.id) continue; + const state = sessionActivity.get(session.id)?.state; + if (state === "inactive") inactiveCount++; + else if (state !== "ended") activeCount++; + } + return { ...node, data: { ...data, activeCount, inactiveCount } }; } - return { ...node, data: { ...data, activeCount, inactiveCount } }; + + return node; }); const edges = layoutEdges.map((edge) => { - const sessionId = (edge.data as { sessionId?: string } | undefined)?.sessionId; - if (!sessionId) return edge; - const state = sessionStates.get(sessionId); - return { ...edge, animated: state !== undefined && WORKING_STATES.has(state) }; + const sessionIds = (edge.data as FlowEdgeData | undefined)?.sessionIds; + if (!sessionIds) return edge; + const working = sessionIds.some((id) => { + const state = sessionActivity.get(id)?.state; + return state !== undefined && WORKING_STATES.has(state); + }); + return { ...edge, animated: working }; }); return { nodes, edges }; - }, [positionedNodes, layoutEdges, events, latestSessionEvents, allAgents, activeSessions, now]); + }, [positionedNodes, layoutEdges, events, allAgents, activeSessions, sessionActivity, toolCounts]); } diff --git a/packages/dashboard/src/components/landing/demoTopologyData.ts b/packages/dashboard/src/components/landing/demoTopologyData.ts index 6592869..591ebe6 100644 --- a/packages/dashboard/src/components/landing/demoTopologyData.ts +++ b/packages/dashboard/src/components/landing/demoTopologyData.ts @@ -136,6 +136,8 @@ export function buildDemoLayout(): { nodes: Node[]; edges: Edge[] } { currentToolName: null, activityState: "idle", lastActivityAt: minutesAgo(0), + toolCalls: null, + toolFailures: null, }; nodes.push({ id: `session-${s.session.id}`, type: "session", position: { x: 0, y: 0 }, data }); edges.push({ diff --git a/packages/dashboard/src/hooks/useWebSocket.ts b/packages/dashboard/src/hooks/useWebSocket.ts index d985f10..582e3fa 100644 --- a/packages/dashboard/src/hooks/useWebSocket.ts +++ b/packages/dashboard/src/hooks/useWebSocket.ts @@ -1,5 +1,5 @@ import { useEffect, useRef } from "react"; -import { useActivityStore, type ActiveAgent } from "@/stores/activityStore"; +import { useActivityStore, toolCountsFrom, type ActiveAgent } from "@/stores/activityStore"; import { apiFetch } from "@/lib/api"; import type { Developer, Session } from "@devscope/shared"; @@ -86,6 +86,7 @@ export function useDevscopeSocket() { developers: devs, activeAgents: [...apiAgents, ...realtimeOnly], activeSessions: sessions, + toolCounts: toolCountsFrom(sessions), }); }).catch(() => { // Fetch failures are expected during backend restarts; diff --git a/packages/dashboard/src/lib/utils.ts b/packages/dashboard/src/lib/utils.ts index 489d486..fde0fff 100644 --- a/packages/dashboard/src/lib/utils.ts +++ b/packages/dashboard/src/lib/utils.ts @@ -27,6 +27,21 @@ export function formatCost(usd: number): string { return `$${usd.toFixed(2)}`; } +/** All tokens a session used: input, output and cache writes and reads. */ +export function sessionTokenTotal(session: { + totalInputTokens?: number; + totalOutputTokens?: number; + totalCacheCreationTokens?: number; + totalCacheReadTokens?: number; +}): number { + return ( + (session.totalInputTokens ?? 0) + + (session.totalOutputTokens ?? 0) + + (session.totalCacheCreationTokens ?? 0) + + (session.totalCacheReadTokens ?? 0) + ); +} + /** Human-friendly relative time string. */ export function timeAgo(timestamp: string): string { const diff = Date.now() - parseUTC(timestamp).getTime(); diff --git a/packages/dashboard/src/stores/activityStore.ts b/packages/dashboard/src/stores/activityStore.ts index a289ecd..f6d8db8 100644 --- a/packages/dashboard/src/stores/activityStore.ts +++ b/packages/dashboard/src/stores/activityStore.ts @@ -18,6 +18,33 @@ export interface StoppedAgent extends ActiveAgent { const MAX_STOPPED_AGENTS = 100; +export interface ToolCounts { + calls: number; + failures: number; +} + +/** Counts as the API returned them; sessions without them (activity-only) are left out. */ +export function toolCountsFrom(sessions: Session[]): Record { + const counts: Record = {}; + for (const s of sessions) { + if (s.toolCalls != null) counts[s.id] = { calls: s.toolCalls, failures: s.toolFailures ?? 0 }; + } + return counts; +} + +/** Counts a finished tool call live, until the next /api/sessions/active fetch resets them. */ +function withToolEvent(counts: Record, event: FeedEvent): Record { + const current = counts[event.sessionId]; + if (!current || (event.eventType !== "tool.complete" && event.eventType !== "tool.fail")) return counts; + return { + ...counts, + [event.sessionId]: { + calls: current.calls + 1, + failures: current.failures + (event.eventType === "tool.fail" ? 1 : 0), + }, + }; +} + /** An event of the session itself, not one of its subagents' tool calls. */ function isSessionOwnEvent(event: FeedEvent): boolean { if (event.eventType === "agent.start" || event.eventType === "agent.stop") return true; @@ -44,6 +71,7 @@ export interface ActivityState { events: FeedEvent[]; /** Newest own event per session, kept beyond the `events` window. */ latestSessionEvents: Record; + toolCounts: Record; developers: (Developer & { activeSessions?: number })[]; activeSessions: Session[]; activeAgents: ActiveAgent[]; @@ -77,6 +105,7 @@ const MAX_EVENTS = 200; export const useActivityStore = create((set) => ({ events: [], latestSessionEvents: {}, + toolCounts: {}, developers: [], activeSessions: [], activeAgents: [], @@ -93,6 +122,7 @@ export const useActivityStore = create((set) => ({ return { events: [event, ...state.events].slice(0, MAX_EVENTS), latestSessionEvents: withLatestSessionEvents(state.latestSessionEvents, [event]), + toolCounts: withToolEvent(state.toolCounts, event), }; }), @@ -100,7 +130,9 @@ export const useActivityStore = create((set) => ({ // failed fetch can never replace a list with something that crashes `.map`. setDevelopers: (developers) => set((state) => (Array.isArray(developers) ? { developers } : state)), setActiveSessions: (activeSessions) => - set((state) => (Array.isArray(activeSessions) ? { activeSessions } : state)), + set((state) => + Array.isArray(activeSessions) ? { activeSessions, toolCounts: toolCountsFrom(activeSessions) } : state, + ), setActiveAgents: (activeAgents) => set((state) => (Array.isArray(activeAgents) ? { activeAgents } : state)), addActiveAgent: (agent) => set((state) => { diff --git a/packages/shared/src/models.ts b/packages/shared/src/models.ts index 1d12745..9a10352 100644 --- a/packages/shared/src/models.ts +++ b/packages/shared/src/models.ts @@ -24,6 +24,9 @@ export interface Session { endedAt: string | null; /** Time of the session's latest event; only set by /api/sessions/active. */ lastEventAt?: string | null; + /** Finished tool calls and failures so far; only set by /api/sessions/active, not for activity-only viewers. */ + toolCalls?: number; + toolFailures?: number; status: "active" | "ended"; permissionMode: string | null; privacyMode: PrivacyMode;