/** * @file SessionComplexityScatter.tsx * @description A React component that renders a scatter plot visualization of session complexity using D3.js. Each session is represented as a bubble, where the x-axis represents the session duration, the y-axis represents the number of agents involved, and the size of the bubble corresponds to the total tokens used. The color of each bubble indicates the session status (e.g., completed, active, error, abandoned). The component also includes tooltips for detailed information on hover and a legend for status colors. It is designed to be responsive and provides an empty state when no data is available. * @author Nguyễn Ngọc Trí Vĩ */ /* ============================================================================= * MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed) * ============================================================================= * **Purpose:** Workflow analytics visualization built on D3; consumes aggregated session/run metrics from the workflows API. * * ## Design constraints * - Local-first: no telemetry leaves the machine unless the user configures webhooks. * - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that * philosophy by degrading gracefully (empty states, stale badges, reconnect loops). * - Destructive flows stay behind explicit confirmation modals and server-side gates. * - Internationalization: user-visible strings belong in i18n JSON, not literals here. * * ## Remote data & SSH * Remote Data Sources let operators aggregate multiple machines. SSH entries describe * how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every * scoped GET via `?sources=`. Health checks and import history surface in Settings. * * ## Observability * Prometheus scrapes `GET /api/metrics` (see `monitoring/`). Grafana ships four * provisioned boards (overview, sessions, tools, alerts). Native npm scripts and * Docker Compose profiles are documented in `monitoring/README.md`. * * ## Internal dependencies * - `../../lib/types` * - `../../lib/format` * * ## Public surface * - `SessionComplexityScatterProps` — exported API; see TSDoc on the symbol for behavior. * - `SessionComplexityScatter` — exported API; see TSDoc on the symbol for behavior. * * ## Testing pointers * - Prefer colocated `__tests__` with Vitest + Testing Library for UI. * - Server contract changes require `npm run test:server` and OpenAPI sync. * - MCP edits: `npm run mcp:typecheck` and `npm run mcp:build`. * * ## Related docs * - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline. * - `docs/API.md` — REST reference. * - `.claude/skills/file-headers/` — mandatory `@author` header policy. * ============================================================================= */ /* ----------------------------------------------------------------------------- * EXPORT CATALOG — quick index of symbols defined below (documentation only). * ----------------------------------------------------------------------------- * **SessionComplexityScatterProps** * Part of this module's public contract. Downstream imports should treat * the signature and return type as stable unless release notes say otherwise. * When behavior changes, update the `@file` overview and relevant tests. * * **SessionComplexityScatter** * Part of this module's public contract. Downstream imports should treat * the signature and return type as stable unless release notes say otherwise. * When behavior changes, update the `@file` overview and relevant tests. * * ----------------------------------------------------------------------------- */ import { useRef, useEffect, useState, useCallback } from "react"; import { useTranslation } from "react-i18next"; import * as d3 from "d3"; import type { SessionComplexityItem } from "../../lib/types"; import { formatModelName } from "../../lib/format"; // ── Constants ───────────────────────────────────────────────────────────────── const MARGIN = { top: 20, right: 24, bottom: 60, left: 52 }; const MIN_BUBBLE_R = 4; const MAX_BUBBLE_R = 32; const STATUS_COLOR: Record = { completed: "#22c55e", error: "#ef4444", active: "#6366f1", abandoned: "#eab308", }; function statusColor(status: string): string { return STATUS_COLOR[status] ?? "#6b7280"; } // ── Duration formatting ─────────────────────────────────────────────────────── function formatDurationSec(sec: number): string { if (sec < 60) return `${Math.round(sec)}s`; const h = Math.floor(sec / 3600); const m = Math.floor((sec % 3600) / 60); if (h > 0) return `${h}h ${m}m`; const s = Math.round(sec % 60); return s > 0 ? `${m}m ${s}s` : `${m}m`; } function fmtXTick(sec: number): string { if (sec === 0) return "0"; if (sec < 60) return `${Math.round(sec)}s`; const h = Math.floor(sec / 3600); const m = Math.floor((sec % 3600) / 60); if (h > 0) return `${h}h ${m > 0 ? `${m}m` : ""}`; return `${m}m`; } function fmtTokens(n: number): string { if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; if (n >= 1_000) return `${(n / 1_000).toFixed(0)}K`; return String(n); } // ── Tooltip ─────────────────────────────────────────────────────────────────── interface TooltipState { x: number; y: number; item: SessionComplexityItem; } function Tooltip({ state }: { state: TooltipState }) { const { t } = useTranslation("workflows"); const nearRight = state.x > window.innerWidth - 220; return (

{state.item.name ?? state.item.id.slice(0, 12)}

{t("complexity.tooltip.duration")} {formatDurationSec(state.item.duration)} {t("complexity.tooltip.agents")} {state.item.agentCount} {t("complexity.tooltip.subagents")} {state.item.subagentCount} {t("complexity.tooltip.tokens")} {fmtTokens(state.item.totalTokens)} {state.item.model && ( {t("complexity.tooltip.model")} {formatModelName(state.item.model)} )}
{t(`common:status.${state.item.status}`, { defaultValue: state.item.status })}
); } // ── Legend ──────────────────────────────────────────────────────────────────── const LEGEND_STATUSES = ["completed", "active", "error", "abandoned"] as const; function Legend() { const { t } = useTranslation("workflows"); return (
{LEGEND_STATUSES.map((s) => (
{t(`common:status.${s}`, { defaultValue: s })}
))}
); } // ── Empty state ─────────────────────────────────────────────────────────────── function EmptyState() { const { t } = useTranslation("workflows"); return (

{t("complexity.noData")}

{t("complexity.noDataDesc")}

); } // ── Main chart ──────────────────────────────────────────────────────────────── export interface SessionComplexityScatterProps { data: SessionComplexityItem[]; onSessionClick?: (id: string) => void; } export function SessionComplexityScatter({ data, onSessionClick }: SessionComplexityScatterProps) { const { t } = useTranslation("workflows"); const svgRef = useRef(null); const containerRef = useRef(null); const [tooltip, setTooltip] = useState(null); const [width, setWidth] = useState(600); // Track container width for responsiveness useEffect(() => { const el = containerRef.current; if (!el) return; const obs = new ResizeObserver((entries) => { const w = entries[0]?.contentRect.width; if (w) setWidth(w); }); obs.observe(el); setWidth(el.clientWidth); return () => obs.disconnect(); }, []); const height = Math.max(280, Math.min(420, width * 0.5)); const handleMouseLeave = useCallback(() => setTooltip(null), []); useEffect(() => { if (!svgRef.current || data.length === 0) return; const svg = d3.select(svgRef.current); svg.selectAll("*").remove(); const innerW = width - MARGIN.left - MARGIN.right; const innerH = height - MARGIN.top - MARGIN.bottom; const g = svg.append("g").attr("transform", `translate(${MARGIN.left},${MARGIN.top})`); // Scales const xScale = d3 .scaleLinear() .domain([0, d3.max(data, (d) => d.duration) ?? 1]) .nice() .range([0, innerW]); const yScale = d3 .scaleLinear() .domain([0, (d3.max(data, (d) => d.agentCount) ?? 1) + 1]) .nice() .range([innerH, 0]); const rScale = d3 .scaleSqrt() .domain([0, d3.max(data, (d) => d.totalTokens) ?? 1]) .range([MIN_BUBBLE_R, MAX_BUBBLE_R]); // Grid lines const gridColor = "#2a2a3d"; g.append("g") .attr("class", "grid-x") .call( d3 .axisBottom(xScale) .ticks(5) .tickSize(-innerH) .tickFormat(() => "") ) .attr("transform", `translate(0,${innerH})`) .call((sel) => { sel.select(".domain").remove(); sel.selectAll(".tick line").attr("stroke", gridColor).attr("stroke-dasharray", "3,3"); }); g.append("g") .attr("class", "grid-y") .call( d3 .axisLeft(yScale) .ticks(5) .tickSize(-innerW) .tickFormat(() => "") ) .call((sel) => { sel.select(".domain").remove(); sel.selectAll(".tick line").attr("stroke", gridColor).attr("stroke-dasharray", "3,3"); }); // X axis g.append("g") .attr("transform", `translate(0,${innerH})`) .call( d3 .axisBottom(xScale) .ticks(5) .tickFormat((d) => fmtXTick(d as number)) ) .call((sel) => { sel.select(".domain").attr("stroke", "#363650"); sel.selectAll(".tick line").attr("stroke", "#363650"); sel.selectAll(".tick text").attr("fill", "#6b7280").attr("font-size", "11"); }); // X axis label g.append("text") .attr("x", innerW / 2) .attr("y", innerH + 44) .attr("text-anchor", "middle") .attr("fill", "#6b7280") .attr("font-size", "11") .text(t("complexity.duration")); // Y axis g.append("g") .call(d3.axisLeft(yScale).ticks(5).tickFormat(d3.format("d"))) .call((sel) => { sel.select(".domain").attr("stroke", "#363650"); sel.selectAll(".tick line").attr("stroke", "#363650"); sel.selectAll(".tick text").attr("fill", "#6b7280").attr("font-size", "11"); }); // Y axis label g.append("text") .attr("transform", "rotate(-90)") .attr("x", -innerH / 2) .attr("y", -40) .attr("text-anchor", "middle") .attr("fill", "#6b7280") .attr("font-size", "11") .text(t("complexity.agentCount")); // Bubbles - sort largest to back so small ones are clickable const sorted = [...data].sort((a, b) => b.totalTokens - a.totalTokens); g.selectAll("circle") .data(sorted) .join("circle") .attr("cx", (d) => xScale(d.duration)) .attr("cy", (d) => yScale(d.agentCount)) .attr("r", (d) => rScale(d.totalTokens)) .attr("fill", (d) => statusColor(d.status)) .attr("fill-opacity", 0.75) .attr("stroke", (d) => statusColor(d.status)) .attr("stroke-width", 1.5) .attr("stroke-opacity", 0.9) .style("cursor", onSessionClick ? "pointer" : "default") .on("mouseenter", (event: MouseEvent, d) => { d3.select(event.currentTarget as SVGCircleElement) .attr("fill-opacity", 1) .attr("stroke-width", 2.5); setTooltip({ x: event.clientX, y: event.clientY, item: d }); }) .on("mousemove", (event: MouseEvent) => { setTooltip((prev) => (prev ? { ...prev, x: event.clientX, y: event.clientY } : null)); }) .on("mouseleave", (event: MouseEvent) => { d3.select(event.currentTarget as SVGCircleElement) .attr("fill-opacity", 0.75) .attr("stroke-width", 1.5); setTooltip(null); }) .on("click", (_event: MouseEvent, d) => { onSessionClick?.(d.id); }); }, [data, width, height, onSessionClick, t]); if (data.length === 0) return ; return (
{tooltip && }
); }