Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 10 additions & 2 deletions packages/backend/src/db/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,15 +141,23 @@ 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)})
ORDER BY s.started_at DESC`;
}
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'
Expand Down
16 changes: 16 additions & 0 deletions packages/backend/src/routes/__tests__/sessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down
3 changes: 3 additions & 0 deletions packages/backend/src/routes/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
17 changes: 9 additions & 8 deletions packages/dashboard/src/components/flow/DetailPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -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 (
<div className="space-y-5">
Expand Down Expand Up @@ -83,7 +78,13 @@ function SessionDetails({ data, nodes }: { data: SessionNodeData; nodes: Node[]
{session.model ? <Fact label="Model">{session.model}</Fact> : null}
{hasUsage ? (
<Fact label="Tokens">
{formatTokenCount(totalTokens)} · {formatCost(session.estimatedCostUsd ?? 0)}
{formatTokenCount(sessionTokenTotal(session))} · {formatCost(session.estimatedCostUsd ?? 0)}
</Fact>
) : null}
{toolCalls != null ? (
<Fact label="Tool calls">
{toolCalls}
{toolFailures ? <span className="text-red-400"> · {toolFailures} failed</span> : null}
</Fact>
) : null}
</dl>
Expand Down
52 changes: 49 additions & 3 deletions packages/dashboard/src/components/flow/FlowView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<
Expand Down Expand Up @@ -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<FlowFilters>) } : 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 {
Expand All @@ -53,7 +73,13 @@ function selectionFor(node: Node): string | null {
}

export function FlowView() {
const { nodes: layoutNodes, edges: layoutEdges } = useFlowLayout();
const [filters, setFilters] = useState<FlowFilters>(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<string | null>(null);
Expand Down Expand Up @@ -119,16 +145,36 @@ 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)"
/>
</ReactFlow>
<div className="absolute left-3 top-3 z-10 flex gap-2">
<FilterToggle label="Hide inactive" active={filters.hideInactive} onClick={() => toggleFilter("hideInactive")} />
<FilterToggle label="Hide finished subagents" active={filters.hideDoneAgents} onClick={() => toggleFilter("hideDoneAgents")} />
</div>
{selectedNode ? (
<DetailPanel node={selectedNode} nodes={layoutNodes} onClose={() => setSelectedId(null)} />
) : null}
</FlowErrorBoundary>
</div>
);
}

function FilterToggle({ label, active, onClick }: { label: string; active: boolean; onClick: () => void }) {
return (
<button
onClick={onClick}
aria-pressed={active}
className={`rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
active
? "border-blue-500/50 bg-blue-500/15 text-blue-300"
: "border-gray-700 bg-gray-900/80 text-gray-400 hover:text-gray-200"
}`}
>
{label}
</button>
);
}
25 changes: 25 additions & 0 deletions packages/dashboard/src/components/flow/ProjectNode.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ type: "spring", stiffness: 500, damping: 35 }}
className="flex items-center gap-2 rounded-full border border-gray-700 bg-gray-900 px-3 py-2 shadow-lg"
style={{ width: 200 }}
>
<Handle type="target" position={Position.Top} className="!bg-gray-600" />
<Folder className="h-3.5 w-3.5 shrink-0 text-gray-400" />
<ProjectLabel name={projectName} className="min-w-0 flex-1 truncate text-sm font-medium text-gray-200" />
<span className="shrink-0 text-xs text-gray-500">{sessionCount} sessions</span>
<Handle type="source" position={Position.Bottom} className="!bg-gray-600" />
</motion.div>
);
}
25 changes: 21 additions & 4 deletions packages/dashboard/src/components/flow/SessionNode.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {
Expand Down Expand Up @@ -58,8 +58,18 @@ const EVENT_COLORS: Record<string, string> = {
"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";

Expand Down Expand Up @@ -143,9 +153,16 @@ export function SessionNode({ data, selected }: NodeProps & { data: SessionNodeD
</span>
</div>

<div className="mt-1 text-xs text-gray-600">
active {timeAgo(lastActivityAt)}
<div className="mt-1 flex items-center justify-between gap-2 text-xs text-gray-600">
<span>active {timeAgo(lastActivityAt)}</span>
{toolCalls != null ? (
<span>
{toolCalls} tools
{toolFailures ? <span className="text-red-400"> · {toolFailures} failed</span> : null}
</span>
) : null}
</div>
{meta ? <div className="truncate text-xs text-gray-500">{meta}</div> : null}

<ActivityBadge
isToolRunning={debounced.isToolRunning}
Expand Down
10 changes: 10 additions & 0 deletions packages/dashboard/src/components/flow/flowTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,16 @@ export interface SessionNodeData {
activityState: SessionActivityState;
/** Latest event of the session or its subagents, else its start. */
lastActivityAt: string;
/** Finished tool calls and failures; null when the API does not share them. */
toolCalls: number | null;
toolFailures: number | null;
}

/** Groups a developer's sessions that share a project. */
export interface ProjectNodeData {
[key: string]: unknown;
projectName: string;
sessionCount: number;
}

export interface AgentNodeData {
Expand Down
4 changes: 4 additions & 0 deletions packages/dashboard/src/components/flow/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,17 @@ const NODE_HEIGHT_SESSION = 160;
const NODE_WIDTH_AGENT = 240;
const NODE_HEIGHT_AGENT = 110;
const NODE_HEIGHT_AGENT_SUMMARY = 64;
const NODE_WIDTH_PROJECT = 200;
const NODE_HEIGHT_PROJECT = 48;

function getNodeDimensions(type: string): { width: number; height: number } {
switch (type) {
case "developer":
return { width: NODE_WIDTH_DEVELOPER, height: NODE_HEIGHT_DEVELOPER };
case "agent":
return { width: NODE_WIDTH_AGENT, height: NODE_HEIGHT_AGENT };
case "project":
return { width: NODE_WIDTH_PROJECT, height: NODE_HEIGHT_PROJECT };
case "agentSummary":
return { width: NODE_WIDTH_AGENT, height: NODE_HEIGHT_AGENT_SUMMARY };
default:
Expand Down
2 changes: 2 additions & 0 deletions packages/dashboard/src/components/flow/nodeTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import { DeveloperNode } from "./DeveloperNode";
import { SessionNode } from "./SessionNode";
import { AgentNode } from "./AgentNode";
import { AgentSummaryNode } from "./AgentSummaryNode";
import { ProjectNode } from "./ProjectNode";

/** Node components of the topology graph, shared by the dashboard and the landing demo. */
export const nodeTypes = {
developer: DeveloperNode,
project: ProjectNode,
session: SessionNode,
agent: AgentNode,
agentSummary: AgentSummaryNode,
Expand Down
Loading