@blackbelt-technology/pi-dashboard-flows-plugin 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Parity test pinning the moved reducer's behavior post-extraction.
3
+ *
4
+ * The reducer logic was moved from `packages/client/src/lib/flow-reducer.ts`
5
+ * to `packages/flows-plugin/src/flow-reducer.ts` by the OpenSpec change
6
+ * `extract-flows-as-plugin`. The contract — `(state, event) → newState` —
7
+ * is unchanged. This test dispatches a representative `flow_started →
8
+ * flow_agent_started → flow_complete` sequence and snapshots the resulting
9
+ * `FlowState` so a future contract drift fails loudly here.
10
+ */
11
+ import { describe, it, expect } from "vitest";
12
+ import { isFlowEvent, reduceFlowEvent } from "../reducer.js";
13
+ import type { DashboardEvent, FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
14
+
15
+ function ev(type: string, data: Record<string, unknown>): DashboardEvent {
16
+ return {
17
+ seq: 1,
18
+ timestamp: 0,
19
+ sessionId: "s1",
20
+ eventType: type,
21
+ data,
22
+ } as unknown as DashboardEvent;
23
+ }
24
+
25
+ describe("flow-reducer parity (post-extract-flows-as-plugin)", () => {
26
+ it("recognizes every flow_* event type via isFlowEvent", () => {
27
+ expect(isFlowEvent("flow_started")).toBe(true);
28
+ expect(isFlowEvent("flow_agent_started")).toBe(true);
29
+ expect(isFlowEvent("flow_agent_complete")).toBe(true);
30
+ expect(isFlowEvent("flow_tool_call")).toBe(true);
31
+ expect(isFlowEvent("flow_tool_result")).toBe(true);
32
+ expect(isFlowEvent("flow_assistant_text")).toBe(true);
33
+ expect(isFlowEvent("flow_thinking_text")).toBe(true);
34
+ expect(isFlowEvent("flow_loop_iteration")).toBe(true);
35
+ expect(isFlowEvent("flow_complete")).toBe(true);
36
+ expect(isFlowEvent("flow_summary_dismissed")).toBe(true);
37
+ // negative
38
+ expect(isFlowEvent("message_start")).toBe(false);
39
+ expect(isFlowEvent("turn_end")).toBe(false);
40
+ expect(isFlowEvent("architect_started")).toBe(false);
41
+ });
42
+
43
+ it("reduces flow_started → creates FlowState with pending agents", () => {
44
+ const state: FlowState | null = null;
45
+ const next = reduceFlowEvent(
46
+ state,
47
+ ev("flow_started", {
48
+ flowName: "research",
49
+ task: "Find bugs",
50
+ steps: [
51
+ { id: "r", agent: "researcher", blockedBy: [] },
52
+ { id: "d", agent: "developer", blockedBy: ["r"] },
53
+ ],
54
+ }),
55
+ );
56
+ expect(next).not.toBeNull();
57
+ expect(next!.flowName).toBe("research");
58
+ expect(next!.task).toBe("Find bugs");
59
+ expect(next!.status).toBe("running");
60
+ expect(next!.agents.size).toBe(2);
61
+ const r = next!.agents.get("r")!;
62
+ const d = next!.agents.get("d")!;
63
+ expect(r.agentName).toBe("researcher");
64
+ expect(r.status).toBe("pending");
65
+ expect(d.blockedBy).toEqual(["r"]);
66
+ });
67
+
68
+ it("reduces flow_agent_started → agent transitions to running", () => {
69
+ let s = reduceFlowEvent(
70
+ null,
71
+ ev("flow_started", {
72
+ flowName: "f",
73
+ task: "t",
74
+ steps: [{ id: "r", agent: "researcher", blockedBy: [] }],
75
+ }),
76
+ );
77
+ s = reduceFlowEvent(
78
+ s,
79
+ ev("flow_agent_started", {
80
+ agentName: "researcher",
81
+ config: { model: "@research", card: { label: "Research" } },
82
+ }),
83
+ );
84
+ const r = s!.agents.get("r")!;
85
+ expect(r.status).toBe("running");
86
+ expect(r.label).toBe("Research");
87
+ expect(r.model).toBe("@research");
88
+ });
89
+
90
+ it("reduces flow_complete → status updates and flowResult stored", () => {
91
+ let s = reduceFlowEvent(
92
+ null,
93
+ ev("flow_started", { flowName: "f", task: "t", steps: [{ id: "r", agent: "r", blockedBy: [] }] }),
94
+ );
95
+ s = reduceFlowEvent(
96
+ s,
97
+ ev("flow_complete", {
98
+ status: "success",
99
+ flowName: "f",
100
+ results: { totalAgents: 1, successCount: 1 },
101
+ }),
102
+ );
103
+ expect(s!.status).toBe("success");
104
+ expect(s!.flowResult).toBeDefined();
105
+ });
106
+ });
@@ -0,0 +1,386 @@
1
+ /**
2
+ * Architect state machine reducer.
3
+ * Handles all architect_* events and returns updated ArchitectState.
4
+ */
5
+ import type {
6
+ DashboardEvent,
7
+ ArchitectState,
8
+ ArchitectAgentEntry,
9
+ ArchitectDagStep,
10
+ ArchitectParsedFlow,
11
+ ArchitectPrompt,
12
+ FlowRecentTool,
13
+ FlowDetailEntry,
14
+ } from "@blackbelt-technology/pi-dashboard-shared/types.js";
15
+
16
+ const MAX_RECENT_TOOLS = 3;
17
+
18
+ /** Extract a short input preview for tool call display */
19
+ function extractInputPreview(toolName: string, input: unknown): string {
20
+ if (!input || typeof input !== "object") return "";
21
+ const inp = input as Record<string, unknown>;
22
+ switch (toolName.toLowerCase()) {
23
+ case "read":
24
+ case "write":
25
+ case "edit":
26
+ return String(inp.file_path || inp.path || "").split("/").pop() || "";
27
+ case "grep":
28
+ return String(inp.pattern || "").slice(0, 20);
29
+ case "bash":
30
+ return String(inp.command || "").slice(0, 20);
31
+ case "flow_write":
32
+ return String(inp.name || "");
33
+ case "agent_write":
34
+ return extractAgentName(inp);
35
+ default:
36
+ return JSON.stringify(input).slice(0, 20);
37
+ }
38
+ }
39
+
40
+ /** Extract agent name from agent_write tool input */
41
+ function extractAgentName(input: Record<string, unknown>): string {
42
+ if (input.path) {
43
+ const seg = String(input.path).split("/").pop() || "";
44
+ return seg.replace(/\.md$/, "") || "unknown";
45
+ }
46
+ if (input.content) {
47
+ const m = String(input.content).match(/^name:\s*(.+)$/m);
48
+ if (m) return m[1].trim();
49
+ }
50
+ return "unknown";
51
+ }
52
+
53
+ /** Extract step IDs from flow YAML content via regex (approximate, for live progress) */
54
+ function extractStepsFromYaml(content: string): ArchitectDagStep[] {
55
+ const steps: ArchitectDagStep[] = [];
56
+ // Match step entries: " - id: <name>"
57
+ const idMatches = content.matchAll(/^\s+-\s*id:\s*(.+)$/gm);
58
+ for (const m of idMatches) {
59
+ const id = m[1].trim();
60
+ steps.push({ id, blockedBy: [] });
61
+ }
62
+ // Try to extract fields for each step (simple regex, may miss complex cases)
63
+ const stepBlocks = content.split(/^\s+-\s*id:/m).slice(1);
64
+ for (let i = 0; i < stepBlocks.length && i < steps.length; i++) {
65
+ const block = stepBlocks[i];
66
+ const agentMatch = block.match(/^\s+agent:\s*(.+)$/m);
67
+ if (agentMatch) steps[i].agentName = agentMatch[1].trim();
68
+ const blockedMatch = block.match(/^\s+blockedBy:\s*\[([^\]]*)\]/m);
69
+ if (blockedMatch) {
70
+ steps[i].blockedBy = blockedMatch[1].split(",").map(s => s.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
71
+ }
72
+ const stepTypeMatch = block.match(/^\s+stepType:\s*(.+)$/m);
73
+ if (stepTypeMatch) steps[i].stepType = stepTypeMatch[1].trim() as ArchitectDagStep["stepType"];
74
+ const loopTargetMatch = block.match(/^\s+loop_target:\s*(.+)$/m);
75
+ if (loopTargetMatch) steps[i].loopTarget = loopTargetMatch[1].trim();
76
+ const exitTargetMatch = block.match(/^\s+exit_target:\s*(.+)$/m);
77
+ if (exitTargetMatch) steps[i].exitTarget = exitTargetMatch[1].trim();
78
+ }
79
+ return steps;
80
+ }
81
+
82
+ /** Extract flow name from flow YAML content */
83
+ function extractFlowName(content: string): string {
84
+ const m = content.match(/^name:\s*(.+)$/m);
85
+ return m ? m[1].trim() : "";
86
+ }
87
+
88
+ /**
89
+ * Returns true if the event type is an architect event handled by this reducer.
90
+ */
91
+ export function isArchitectEvent(eventType: string): boolean {
92
+ return eventType.startsWith("architect_");
93
+ }
94
+
95
+ /**
96
+ * Reduce an architect event into the current ArchitectState.
97
+ * Returns null to clear the state (e.g., on complete/cancelled).
98
+ */
99
+ export function reduceArchitectEvent(
100
+ state: ArchitectState | null,
101
+ event: DashboardEvent,
102
+ ): ArchitectState | null {
103
+ const data = event.data;
104
+
105
+ switch (event.eventType) {
106
+ case "architect_prompt_request": {
107
+ if (!state) return null;
108
+ const prompt: ArchitectPrompt = {
109
+ id: data.id as string,
110
+ type: (data.promptType as "select" | "input" | "confirm") || "select",
111
+ question: (data.question as string) || "",
112
+ options: data.options as string[] | undefined,
113
+ defaultValue: data.defaultValue as string | undefined,
114
+ };
115
+ return { ...state, pendingPrompt: prompt };
116
+ }
117
+
118
+ case "architect_context_generating": {
119
+ return {
120
+ phase: "context",
121
+ architectMode: (data.mode as "new" | "edit") || "new",
122
+ flowName: "",
123
+ agents: [],
124
+ dagSteps: [],
125
+ parsedFlows: [],
126
+ lastToolCall: null,
127
+ recentTools: [],
128
+ detailHistory: [],
129
+ iteration: 1,
130
+ pendingPrompt: null,
131
+ };
132
+ }
133
+
134
+ case "architect_started": {
135
+ const mode = (data.mode as "new" | "edit") || "new";
136
+ const iteration = (data.iteration as number) || 1;
137
+ const resolvedModel = data.resolvedModel as string | undefined;
138
+ const modelAlias = data.modelAlias as string | undefined;
139
+ // If we already have state (from context_generating), just update phase
140
+ if (state) {
141
+ return {
142
+ ...state,
143
+ phase: "designing",
144
+ architectMode: mode,
145
+ iteration,
146
+ resolvedModel,
147
+ modelAlias,
148
+ pendingPrompt: null,
149
+ };
150
+ }
151
+ return {
152
+ phase: "designing",
153
+ architectMode: mode,
154
+ flowName: "",
155
+ resolvedModel,
156
+ modelAlias,
157
+ agents: [],
158
+ dagSteps: [],
159
+ parsedFlows: [],
160
+ lastToolCall: null,
161
+ recentTools: [],
162
+ detailHistory: [],
163
+ iteration,
164
+ pendingPrompt: null,
165
+ };
166
+ }
167
+
168
+ case "architect_tool_call": {
169
+ if (!state) return null;
170
+ const toolName = data.toolName as string;
171
+ const input = data.input as Record<string, unknown> | undefined;
172
+ const next = { ...state };
173
+
174
+ const inputPreview = extractInputPreview(toolName, input);
175
+
176
+ // Update last tool call for display
177
+ next.lastToolCall = { toolName, inputPreview };
178
+
179
+ // Append to recent tools (rolling window)
180
+ next.recentTools = [...state.recentTools, { toolName, inputPreview } as FlowRecentTool].slice(-MAX_RECENT_TOOLS);
181
+
182
+ // Append to detail history
183
+ next.detailHistory = [...state.detailHistory, { kind: "tool", toolName, input, isError: false } as FlowDetailEntry];
184
+
185
+ switch (toolName) {
186
+ case "agent_catalog":
187
+ next.catalogSummary = "Reading catalog…";
188
+ break;
189
+
190
+ case "agent_write": {
191
+ const name = input ? extractAgentName(input) : "unknown";
192
+ const source = input ? String(input.content || "") : "";
193
+ const agents = [...next.agents];
194
+ const existing = agents.find(a => a.name === name);
195
+ if (existing) {
196
+ existing.type = "custom";
197
+ existing.status = "creating";
198
+ existing.statusText = "Writing…";
199
+ if (source) existing.source = source;
200
+ } else {
201
+ agents.push({ name, type: "custom", status: "creating", statusText: "Writing…", ...(source ? { source } : {}) });
202
+ }
203
+ next.agents = agents;
204
+ break;
205
+ }
206
+
207
+ case "flow_write": {
208
+ if (input?.content) {
209
+ const content = String(input.content);
210
+ const name = extractFlowName(content);
211
+ if (name) next.flowName = name;
212
+ const steps = extractStepsFromYaml(content);
213
+ if (steps.length > 0) {
214
+ next.dagSteps = steps;
215
+ // Register agents from steps that aren't already in the list
216
+ const agents = [...next.agents];
217
+ for (const step of steps) {
218
+ const agentName = step.agentName || step.id;
219
+ if (!agents.find(a => a.name === agentName)) {
220
+ agents.push({ name: agentName, type: "built-in", status: "done" });
221
+ }
222
+ }
223
+ next.agents = agents;
224
+ }
225
+ }
226
+ break;
227
+ }
228
+ }
229
+
230
+ return next;
231
+ }
232
+
233
+ case "architect_tool_result": {
234
+ if (!state) return null;
235
+ const toolName = data.toolName as string;
236
+ const isError = (data.isError as boolean) || false;
237
+ const next = { ...state };
238
+
239
+ // Update last tool entry in detail history with output
240
+ const detailHistory = [...state.detailHistory];
241
+ for (let i = detailHistory.length - 1; i >= 0; i--) {
242
+ const entry = detailHistory[i];
243
+ if (entry.kind === "tool" && entry.output === undefined) {
244
+ detailHistory[i] = { ...entry, output: data.output, isError };
245
+ break;
246
+ }
247
+ }
248
+ next.detailHistory = detailHistory;
249
+
250
+ switch (toolName) {
251
+ case "agent_catalog": {
252
+ // Parse catalog output for summary
253
+ try {
254
+ const output = data.output;
255
+ const catalog = typeof output === "string" ? JSON.parse(output) : output;
256
+ if (Array.isArray(catalog)) {
257
+ next.catalogSummary = `Catalog: ${catalog.length} agents`;
258
+ }
259
+ } catch {
260
+ next.catalogSummary = "Catalog loaded";
261
+ }
262
+ break;
263
+ }
264
+
265
+ case "flow_write": {
266
+ // The tool result output is { written: boolean, path, diagnostics? }
267
+ // Already parsed by execution.ts (JSON.parse on content[0].text)
268
+ const output = data.output;
269
+ if (output && typeof output === "object" && "written" in output) {
270
+ next.flowWriteStatus = output.written ? "written" : "validation-error";
271
+ } else if (isError) {
272
+ next.flowWriteStatus = "validation-error";
273
+ }
274
+ break;
275
+ }
276
+
277
+ case "agent_write": {
278
+ // Find the agent that was being created and mark done/error
279
+ const agents = [...next.agents];
280
+ const creating = agents.find(a => a.status === "creating");
281
+ if (creating) {
282
+ creating.status = isError ? "error" : "done";
283
+ creating.statusText = isError ? "Failed" : undefined;
284
+ }
285
+ next.agents = agents;
286
+ break;
287
+ }
288
+ }
289
+
290
+ return next;
291
+ }
292
+
293
+ case "architect_text": {
294
+ if (!state) return null;
295
+ const kind = data.kind as string;
296
+ const text = data.text as string;
297
+ if (!text) return state;
298
+ const entry: FlowDetailEntry = kind === "thinking"
299
+ ? { kind: "thinking", text }
300
+ : { kind: "text", text };
301
+ return {
302
+ ...state,
303
+ detailHistory: [...state.detailHistory, entry],
304
+ };
305
+ }
306
+
307
+ case "architect_preview": {
308
+ if (!state) return null;
309
+ const parsedFlows = data.parsedFlows as ArchitectParsedFlow[] | undefined;
310
+ // Store raw YAML content for the YAML viewer
311
+ const flows = data.flows as Array<{ name: string; content: string }> | undefined;
312
+ const next: ArchitectState = {
313
+ ...state,
314
+ phase: "preview",
315
+ flowYamlContent: flows?.[0]?.content,
316
+ };
317
+
318
+ if (parsedFlows && parsedFlows.length > 0) {
319
+ next.parsedFlows = parsedFlows;
320
+ // Use first flow's data for display
321
+ const first = parsedFlows[0];
322
+ if (first.name) next.flowName = first.name;
323
+ if (first.steps.length > 0) next.dagSteps = first.steps;
324
+ // Register agents from parsed steps
325
+ const agents = [...next.agents];
326
+ for (const flow of parsedFlows) {
327
+ for (const step of flow.steps) {
328
+ const agentName = step.agentName || step.id;
329
+ if (!agents.find(a => a.name === agentName)) {
330
+ agents.push({ name: agentName, type: "built-in", status: "done" });
331
+ }
332
+ }
333
+ }
334
+ next.agents = agents;
335
+ }
336
+
337
+ return next;
338
+ }
339
+
340
+ case "architect_replan": {
341
+ const iteration = (data.iteration as number) || ((state?.iteration ?? 1) + 1);
342
+ return {
343
+ phase: "designing",
344
+ architectMode: state?.architectMode || "new",
345
+ flowName: state?.flowName || "",
346
+ agents: [],
347
+ dagSteps: [],
348
+ parsedFlows: [],
349
+ lastToolCall: null,
350
+ recentTools: [],
351
+ detailHistory: [],
352
+ iteration,
353
+ pendingPrompt: null,
354
+ };
355
+ }
356
+
357
+ case "architect_complete":
358
+ case "architect_cancelled": {
359
+ return null;
360
+ }
361
+
362
+ case "architect_error": {
363
+ if (!state) return null;
364
+ const summary = (data.summary as string) || (data.error as string) || "Unknown error";
365
+ return { ...state, error: summary };
366
+ }
367
+
368
+ case "architect_saved": {
369
+ // Keep state alive — architect_complete will clear it
370
+ return state;
371
+ }
372
+
373
+ case "architect_run_handoff": {
374
+ // Flow execution is about to start — clear architect state
375
+ return null;
376
+ }
377
+
378
+ case "architect_context_ready": {
379
+ // Context generation finished, architect will start soon
380
+ return state;
381
+ }
382
+
383
+ default:
384
+ return state;
385
+ }
386
+ }
@@ -0,0 +1,41 @@
1
+ import React, { type ReactNode } from "react";
2
+ import { Icon } from "@mdi/react";
3
+ import { mdiLoading, mdiCheckCircle, mdiAlertCircle, mdiStopCircle } from "@mdi/js";
4
+ import type { FlowStatus } from "@blackbelt-technology/pi-dashboard-shared/types.js";
5
+
6
+ const statusConfig: Record<string, { icon: ReactNode; color: string }> = {
7
+ running: { icon: <Icon path={mdiLoading} size={0.45} className="animate-spin" />, color: "text-blue-400" },
8
+ success: { icon: <Icon path={mdiCheckCircle} size={0.45} />, color: "text-green-400" },
9
+ error: { icon: <Icon path={mdiAlertCircle} size={0.45} />, color: "text-red-400" },
10
+ aborted: { icon: <Icon path={mdiStopCircle} size={0.45} />, color: "text-orange-400" },
11
+ };
12
+
13
+ export function FlowActivityBadge({
14
+ flowName,
15
+ agentsDone,
16
+ agentsTotal,
17
+ status,
18
+ }: {
19
+ flowName: string;
20
+ agentsDone?: number;
21
+ agentsTotal?: number;
22
+ status?: FlowStatus;
23
+ }) {
24
+ const { icon, color } = statusConfig[status ?? "running"] ?? statusConfig.running;
25
+ const isRunning = status === "running";
26
+
27
+ return (
28
+ <div className={`text-[11px] mt-0.5 ml-4 flex items-center gap-1 ${color}`}>
29
+ <span className="inline-flex">{icon}</span>
30
+ <span className="truncate">
31
+ {flowName}
32
+ {isRunning && agentsTotal != null && agentsTotal > 0 && (
33
+ <span className="text-[var(--text-secondary)]"> · {agentsDone ?? 0}/{agentsTotal} agents</span>
34
+ )}
35
+ {!isRunning && (
36
+ <span className="text-[var(--text-secondary)]"> · {status}</span>
37
+ )}
38
+ </span>
39
+ </div>
40
+ );
41
+ }
@@ -0,0 +1,133 @@
1
+ import React from "react";
2
+ import { Icon } from "@mdi/react";
3
+ import { mdiRefresh, mdiEyeOutline, mdiEyeOffOutline, mdiFileDocumentOutline } from "@mdi/js";
4
+ import type { DashboardSession, FlowAgentState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
5
+ import { AgentCardShell } from "../../../client/src/components/AgentCardShell.js";
6
+ import { formatTokens, formatDuration } from "../../../client/src/components/agent-card-utils.js";
7
+ import { AgentMetricSlot } from "../../../client/src/components/extension-ui/AgentMetricSlot.js";
8
+
9
+ export function FlowAgentCard({
10
+ agent,
11
+ onClick,
12
+ onViewSource,
13
+ selected,
14
+ isDetailOpen,
15
+ isSourceOpen,
16
+ session,
17
+ }: {
18
+ agent: FlowAgentState;
19
+ onClick?: () => void;
20
+ onViewSource?: () => void;
21
+ selected?: boolean;
22
+ isDetailOpen?: boolean;
23
+ isSourceOpen?: boolean;
24
+ /** Phase-2 decorator host — used for `agent-metric` filtering by agentId. */
25
+ session?: Pick<DashboardSession, "uiDecorators">;
26
+ }) {
27
+ const displayName = agent.label || agent.stepId || agent.agentName;
28
+ const displayRole = agent.cardRole || agent.model || "";
29
+ const isComplete = agent.status === "complete" || agent.status === "error" || agent.status === "blocked";
30
+ // Strip provider prefix for display (e.g., "anthropic/claude-opus-4-6" → "claude-opus-4-6")
31
+ const displayModel = agent.resolvedModel
32
+ ? (agent.resolvedModel.split("/").pop() ?? agent.resolvedModel)
33
+ : "";
34
+ const rawModel = agent.model || "";
35
+ const hasAlias = rawModel.startsWith("@");
36
+
37
+ // Step type badge for non-agent steps
38
+ const stepTypeBadge = agent.stepType === "fork" || agent.stepType === "agent-decision"
39
+ ? <span className="text-[9px] text-amber-400/70 bg-amber-400/10 px-1 rounded flex-shrink-0">◇ fork</span>
40
+ : agent.stepType === "agent-loop-decision"
41
+ ? <span className="text-[9px] text-purple-400/70 bg-purple-400/10 px-1 rounded flex-shrink-0">↻ loop</span>
42
+ : null;
43
+
44
+ const headerRight = agent.loopIteration != null && agent.loopIteration > 0 ? (
45
+ <span className="text-[10px] text-blue-400 flex-shrink-0 inline-flex items-center gap-0.5">
46
+ <Icon path={mdiRefresh} size={0.4} />{agent.loopIteration}/{agent.loopMax}
47
+ </span>
48
+ ) : (agent.runCount ?? 1) > 1 ? (
49
+ <span className="text-[10px] text-blue-400 flex-shrink-0 inline-flex items-center gap-0.5">
50
+ <Icon path={mdiRefresh} size={0.4} />{agent.runCount}
51
+ </span>
52
+ ) : stepTypeBadge;
53
+
54
+ const stats = isComplete && agent.tokens ? (
55
+ <span>↑{formatTokens(agent.tokens.input)} ↓{formatTokens(agent.tokens.output)} · {formatDuration(agent.duration ?? 0)}</span>
56
+ ) : displayModel ? (
57
+ <span>{displayModel}</span>
58
+ ) : displayRole ? (
59
+ <span>{displayRole}</span>
60
+ ) : null;
61
+
62
+ return (
63
+ <AgentCardShell
64
+ name={displayName}
65
+ status={agent.status}
66
+ headerRight={headerRight}
67
+ stats={stats}
68
+ selected={selected}
69
+ >
70
+ <div className="flex flex-col flex-1">
71
+ {/* Model alias line (when model uses @role alias) */}
72
+ {hasAlias && (
73
+ <div className="text-[10px] text-[var(--text-tertiary)] truncate">{rawModel}</div>
74
+ )}
75
+
76
+ {/* Metric / waiting line */}
77
+ <div className="text-[11px] text-[var(--text-muted)] mt-0.5 truncate">
78
+ {agent.status === "pending" && agent.blockedBy.length > 0 ? (
79
+ <span>waiting: {agent.blockedBy.join(", ")}</span>
80
+ ) : null}
81
+ </div>
82
+
83
+ {/* Phase-2 agent-metric decorator slot. See change: add-extension-ui-decorations. */}
84
+ <AgentMetricSlot session={session} agentId={agent.agentName} />
85
+
86
+ {/* Recent tools */}
87
+ <div className="mt-1 space-y-0">
88
+ {agent.recentTools.map((tool, i) => (
89
+ <div key={i} className="text-[10px] text-[var(--text-tertiary)] truncate">
90
+ {i === agent.recentTools.length - 1 ? "▸" : "·"} {tool.toolName} {tool.inputPreview}
91
+ </div>
92
+ ))}
93
+ {/* Pad to 3 lines for consistent height */}
94
+ {Array.from({ length: Math.max(0, 3 - agent.recentTools.length) }).map((_, i) => (
95
+ <div key={`pad-${i}`} className="text-[10px]">&nbsp;</div>
96
+ ))}
97
+ </div>
98
+
99
+ {/* View source / detail icons — bottom-right of card */}
100
+ {(onViewSource || onClick) && (
101
+ <div className="flex justify-end mt-auto pt-1 gap-1">
102
+ {onViewSource && (
103
+ <button
104
+ onClick={(e) => { e.stopPropagation(); onViewSource(); }}
105
+ className={`transition-colors p-0.5 rounded inline-flex items-center ${
106
+ isSourceOpen
107
+ ? "text-blue-400 bg-blue-400/10"
108
+ : "text-[var(--text-tertiary)] hover:text-blue-400 hover:bg-[var(--bg-surface)]"
109
+ }`}
110
+ title={isSourceOpen ? `Close ${displayName} source` : `View ${displayName} source`}
111
+ >
112
+ <Icon path={mdiFileDocumentOutline} size={0.45} />
113
+ </button>
114
+ )}
115
+ {onClick && (
116
+ <button
117
+ onClick={(e) => { e.stopPropagation(); onClick(); }}
118
+ className={`transition-colors p-0.5 rounded inline-flex items-center ${
119
+ isDetailOpen
120
+ ? "text-blue-400 bg-blue-400/10"
121
+ : "text-[var(--text-tertiary)] hover:text-blue-400 hover:bg-[var(--bg-surface)]"
122
+ }`}
123
+ title={isDetailOpen ? `Close ${displayName} detail` : `View ${displayName} detail`}
124
+ >
125
+ <Icon path={isDetailOpen ? mdiEyeOffOutline : mdiEyeOutline} size={0.45} />
126
+ </button>
127
+ )}
128
+ </div>
129
+ )}
130
+ </div>
131
+ </AgentCardShell>
132
+ );
133
+ }