@blackbelt-technology/pi-dashboard-flows-plugin 0.5.3 β†’ 0.6.0

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.
Files changed (70) hide show
  1. package/package.json +48 -4
  2. package/src/AGENTS.md +8 -0
  3. package/src/__tests__/FlowGraph.test.ts +151 -5
  4. package/src/__tests__/FlowInputWiring.test.tsx +97 -0
  5. package/src/__tests__/FlowSummary.test.tsx +331 -0
  6. package/src/__tests__/FlowYamlPreview.test.tsx +75 -0
  7. package/src/__tests__/FlowsSessionStateContext.test.tsx +223 -0
  8. package/src/__tests__/FlowsUiStateContext.test.tsx +140 -0
  9. package/src/__tests__/authoring-renderers.test.tsx +190 -0
  10. package/src/__tests__/automation-actions.test.ts +117 -0
  11. package/src/__tests__/flow-agent-card-code-source.test.tsx +154 -0
  12. package/src/__tests__/flow-agent-cost.test.tsx +160 -0
  13. package/src/__tests__/flow-agent-error.test.ts +60 -0
  14. package/src/__tests__/flow-collapse-storage.test.ts +90 -0
  15. package/src/__tests__/flow-edges.test.ts +195 -0
  16. package/src/__tests__/flow-inputs.test.ts +69 -0
  17. package/src/__tests__/flow-reducer-bridge-contract.test.ts +108 -0
  18. package/src/__tests__/flow-reducer-seed-on-start.test.ts +61 -0
  19. package/src/__tests__/flow-yaml-parse.test.ts +124 -0
  20. package/src/__tests__/flows-for-cwd.test.ts +51 -0
  21. package/src/__tests__/flowsAvailability.test.ts +79 -0
  22. package/src/__tests__/manifest-discoverability.test.ts +97 -0
  23. package/src/__tests__/node-kind-reducer.test.ts +135 -0
  24. package/src/__tests__/plugin-action-handler.test.ts +54 -0
  25. package/src/__tests__/render-actions.test.ts +63 -0
  26. package/src/__tests__/session-flow-actions-edit.test.tsx +98 -0
  27. package/src/bridge/AGENTS.md +8 -0
  28. package/src/bridge/flow-question-adapter.ts +93 -0
  29. package/src/bridge/index.ts +30 -0
  30. package/src/client/AGENTS.md +32 -0
  31. package/src/client/FlowActivityBadge.tsx +41 -11
  32. package/src/client/FlowAgentCard.tsx +321 -61
  33. package/src/client/FlowAgentDetail.tsx +103 -154
  34. package/src/client/FlowAgentsToolRenderer.tsx +228 -0
  35. package/src/client/FlowAuthorPromptDialog.tsx +92 -0
  36. package/src/client/FlowDashboard.tsx +271 -43
  37. package/src/client/FlowGraph.tsx +425 -276
  38. package/src/client/FlowInputWiring.tsx +243 -0
  39. package/src/client/FlowLaunchDialog.tsx +52 -52
  40. package/src/client/FlowQuestionCard.tsx +216 -0
  41. package/src/client/FlowQuestionTranscriptPill.tsx +58 -0
  42. package/src/client/FlowSummary.tsx +285 -80
  43. package/src/client/FlowWriteToolRenderer.tsx +127 -0
  44. package/src/client/FlowYamlPopoverButton.tsx +110 -0
  45. package/src/client/FlowYamlPreview.tsx +67 -0
  46. package/src/client/FlowsCommandRoutes.tsx +237 -0
  47. package/src/client/FlowsSessionStateContext.tsx +142 -0
  48. package/src/client/FlowsSettings.tsx +68 -0
  49. package/src/client/FlowsUiStateContext.tsx +169 -0
  50. package/src/client/SessionFlowActions.tsx +172 -65
  51. package/src/client/flow-collapse-storage.ts +79 -0
  52. package/src/client/flow-edges.ts +173 -0
  53. package/src/client/flow-yaml-parse.ts +140 -0
  54. package/src/client/flowsAvailability.ts +44 -0
  55. package/src/client/index.tsx +95 -13
  56. package/src/client/shouldRender.ts +38 -0
  57. package/src/configSchema.json +14 -0
  58. package/src/flow-reducer.ts +94 -13
  59. package/src/i18n.ts +90 -0
  60. package/src/reducer.ts +5 -5
  61. package/src/server/AGENTS.md +10 -0
  62. package/src/server/automation-actions.ts +162 -0
  63. package/src/server/flow-inputs.ts +58 -0
  64. package/src/server/index.ts +171 -0
  65. package/src/server/render-actions.ts +88 -0
  66. package/src/server/state-store.ts +74 -0
  67. package/src/__tests__/ArchitectInputPrompt.test.tsx +0 -81
  68. package/src/__tests__/architect-reducer.test.ts +0 -307
  69. package/src/architect-reducer.ts +0 -386
  70. package/src/client/FlowArchitect.tsx +0 -622
@@ -0,0 +1,331 @@
1
+ /**
2
+ * Tests for expandable per-agent rows in FlowSummary.
3
+ * Collapsed rows show a truncated peek; expanding reveals full summary
4
+ * (markdown), typed-output chips, and the file list. Failed steps
5
+ * auto-expand. Rows without detail are not interactive. Per-row state
6
+ * is independent. See change: expandable-flow-summary-rows.
7
+ */
8
+
9
+ import { cleanup, fireEvent, render, within } from "@testing-library/react";
10
+ import type React from "react";
11
+ import { afterEach, beforeAll, describe, expect, it } from "vitest";
12
+
13
+ // jsdom does not implement scrollIntoView; the selection effect calls it.
14
+ beforeAll(() => {
15
+ Element.prototype.scrollIntoView = () => {};
16
+ });
17
+
18
+ import {
19
+ createUiPrimitiveRegistry,
20
+ registerUiPrimitive,
21
+ UiPrimitiveProvider,
22
+ } from "@blackbelt-technology/dashboard-plugin-runtime";
23
+ import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
24
+ import type { FlowAgentState, FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
25
+ import { FlowSummary } from "../client/FlowSummary.js";
26
+
27
+ const registry = createUiPrimitiveRegistry();
28
+ registerUiPrimitive(
29
+ registry,
30
+ UI_PRIMITIVE_KEYS.markdownContent,
31
+ (({ content }: { content: string }) => <div data-testid="md">{content}</div>) as never,
32
+ );
33
+ registerUiPrimitive(
34
+ registry,
35
+ UI_PRIMITIVE_KEYS.formatDuration,
36
+ (((ms: number) => `${ms}ms`) as never),
37
+ );
38
+ // FlowGraph (rendered inside FlowSummary) consumes the zoom-controls primitive.
39
+ registerUiPrimitive(
40
+ registry,
41
+ UI_PRIMITIVE_KEYS.zoomControls,
42
+ ((() => null) as never),
43
+ );
44
+ // FlowAgentCard (frozen cards) primitives. See change: show-flow-cards-in-summary.
45
+ registerUiPrimitive(
46
+ registry,
47
+ UI_PRIMITIVE_KEYS.agentCard,
48
+ (({ children, selected, onClick }: { children?: React.ReactNode; selected?: boolean; onClick?: () => void }) => (
49
+ <div data-testid="agent-card" data-selected={selected ? "true" : "false"} onClick={onClick}>{children}</div>
50
+ )) as never,
51
+ );
52
+ // ui:dialog is required by FlowAgentCard (detail) + FlowSummary (graph expand).
53
+ registerUiPrimitive(
54
+ registry,
55
+ UI_PRIMITIVE_KEYS.dialog,
56
+ (({ open, children, title, size }: { open: boolean; children?: React.ReactNode; title?: string; size?: string }) =>
57
+ open ? <div data-testid="dialog" data-size={size}>{title}{children}</div> : null) as never,
58
+ );
59
+ registerUiPrimitive(
60
+ registry,
61
+ UI_PRIMITIVE_KEYS.formatTokens,
62
+ (((n: number) => `${n}`) as never),
63
+ );
64
+ registerUiPrimitive(
65
+ registry,
66
+ UI_PRIMITIVE_KEYS.popover,
67
+ (({ children }: { children?: React.ReactNode }) => <>{children}</>) as never,
68
+ );
69
+
70
+ function agent(over: Partial<FlowAgentState>): FlowAgentState {
71
+ return {
72
+ agentName: over.stepId ?? "a",
73
+ stepId: over.stepId ?? "a",
74
+ status: "complete",
75
+ blockedBy: [],
76
+ recentTools: [],
77
+ detailHistory: [],
78
+ ...over,
79
+ };
80
+ }
81
+
82
+ function makeState(agents: FlowAgentState[]): FlowState {
83
+ return {
84
+ flowName: "demo-flow",
85
+ task: "t",
86
+ status: "success",
87
+ autonomousMode: false,
88
+ agents: new Map(agents.map((a) => [a.stepId, a])),
89
+ };
90
+ }
91
+
92
+ function renderSummary(state: FlowState) {
93
+ return render(
94
+ <UiPrimitiveProvider value={registry}>
95
+ <FlowSummary flowState={state} onDismiss={() => {}} sessionId="s1" />
96
+ </UiPrimitiveProvider>,
97
+ );
98
+ }
99
+
100
+ afterEach(() => cleanup());
101
+
102
+ describe("FlowSummary frozen cards (show-flow-cards-in-summary)", () => {
103
+ it("renders one frozen agent card per agent, above the collapsible summary section", () => {
104
+ const state = makeState([
105
+ agent({ stepId: "one", label: "step-one", status: "complete", summary: "S1" }),
106
+ agent({ stepId: "two", label: "step-two", status: "complete", summary: "S2" }),
107
+ ]);
108
+ const { getAllByTestId, getByTestId } = renderSummary(state);
109
+ const cards = getAllByTestId("agent-card");
110
+ expect(cards).toHaveLength(2);
111
+ // Cards precede the collapsible summaries section in DOM order.
112
+ const section = getByTestId("flow-summaries");
113
+ expect(cards[0].compareDocumentPosition(section) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
114
+ });
115
+
116
+ it("collapsing the summary section keeps the cards visible", () => {
117
+ const state = makeState([
118
+ agent({ stepId: "one", label: "step-one", status: "complete", summary: "S1" }),
119
+ ]);
120
+ const { getByTestId, getAllByTestId, queryByTestId } = renderSummary(state);
121
+ expect(getByTestId("flow-summaries")).toBeTruthy();
122
+ fireEvent.click(getByTestId("flow-summary-toggle"));
123
+ // Collapsing removes the summaries rows; cards stay visible.
124
+ expect(queryByTestId("flow-summaries")).toBeNull();
125
+ expect(getAllByTestId("agent-card")).toHaveLength(1);
126
+ });
127
+ });
128
+
129
+ describe("FlowSummary fit-window scroll box (improve-flow-graph-fidelity)", () => {
130
+ it("wraps cards + summaries in one bounded, scrollable box so the panel fits the viewport", () => {
131
+ const state = makeState([
132
+ agent({ stepId: "one", label: "step-one", status: "complete", summary: "S1" }),
133
+ ]);
134
+ const { getByTestId } = renderSummary(state);
135
+ const box = getByTestId("flow-summary-scrollbox");
136
+ expect(box.style.maxHeight).toBe("48vh");
137
+ expect(box.className).toMatch(/overflow-y-auto/);
138
+ // cards + summaries live INSIDE the scroll box
139
+ expect(box.querySelector("[data-testid='flow-summaries']")).toBeTruthy();
140
+ expect(box.querySelector("[data-testid='agent-card']")).toBeTruthy();
141
+ });
142
+ });
143
+
144
+ describe("FlowSummary whole-panel collapse (improve-flow-graph-fidelity)", () => {
145
+ it("collapses the whole panel to its header bar, hiding the body but keeping the name", () => {
146
+ const state = makeState([
147
+ agent({ stepId: "one", label: "step-one", status: "complete", summary: "S1" }),
148
+ ]);
149
+ const { getByTestId, queryByTestId, queryAllByTestId, getByText } = renderSummary(state);
150
+ // Body present initially (cards + summaries footer).
151
+ expect(queryAllByTestId("agent-card")).toHaveLength(1);
152
+ expect(queryByTestId("flow-summaries")).toBeTruthy();
153
+ // Collapse the whole panel.
154
+ fireEvent.click(getByTestId("flow-summary-panel-toggle"));
155
+ // Body gone; header (flow name) still shown β€” shrink-to-header, not dismiss.
156
+ expect(queryAllByTestId("agent-card")).toHaveLength(0);
157
+ expect(queryByTestId("flow-summaries")).toBeNull();
158
+ expect(getByText(/demo-flow/)).toBeTruthy();
159
+ // Toggling back restores the body.
160
+ fireEvent.click(getByTestId("flow-summary-panel-toggle"));
161
+ expect(queryAllByTestId("agent-card")).toHaveLength(1);
162
+ });
163
+ });
164
+
165
+ describe("FlowSummary graph⇄card selection (improve-flow-graph-dialog-and-card-interaction)", () => {
166
+ function selectionState() {
167
+ return makeState([
168
+ agent({ stepId: "one", label: "step-one", status: "complete", summary: "S1" }),
169
+ agent({ stepId: "two", label: "step-two", status: "complete", summary: "S2" }),
170
+ ]);
171
+ }
172
+
173
+ it("clicking a graph node selects the matching card", () => {
174
+ const { container } = renderSummary(selectionState());
175
+ const node = container.querySelector("[data-node='one']") as SVGGElement;
176
+ expect(node).toBeTruthy();
177
+ fireEvent.click(node);
178
+ const card = container.querySelector("[data-step='one'] [data-testid='agent-card']");
179
+ expect(card?.getAttribute("data-selected")).toBe("true");
180
+ });
181
+
182
+ it("clicking a card selects the matching graph node", () => {
183
+ const { container } = renderSummary(selectionState());
184
+ const card = container.querySelector("[data-step='two'] [data-testid='agent-card']") as HTMLElement;
185
+ fireEvent.click(card);
186
+ const node = container.querySelector("[data-node='two']");
187
+ expect(node?.getAttribute("class") ?? "").toContain("flow-node-selected");
188
+ });
189
+
190
+ it("re-clicking the selected node clears selection", () => {
191
+ const { container } = renderSummary(selectionState());
192
+ const node = container.querySelector("[data-node='one']") as SVGGElement;
193
+ fireEvent.click(node);
194
+ fireEvent.click(node);
195
+ const card = container.querySelector("[data-step='one'] [data-testid='agent-card']");
196
+ expect(card?.getAttribute("data-selected")).toBe("false");
197
+ });
198
+
199
+ it("Esc clears selection", () => {
200
+ const { container } = renderSummary(selectionState());
201
+ fireEvent.click(container.querySelector("[data-node='one']") as SVGGElement);
202
+ expect(container.querySelector("[data-step='one'] [data-testid='agent-card']")?.getAttribute("data-selected")).toBe("true");
203
+ fireEvent.keyDown(document, { key: "Escape" });
204
+ expect(container.querySelector("[data-step='one'] [data-testid='agent-card']")?.getAttribute("data-selected")).toBe("false");
205
+ });
206
+ });
207
+
208
+ describe("FlowSummary graph expand dialog (full size)", () => {
209
+ it("β€’ Expand opens the graph dialog at size=full", () => {
210
+ const state = makeState([agent({ stepId: "one", label: "step-one", status: "complete" })]);
211
+ const { container, getByText, queryByTestId } = renderSummary(state);
212
+ expect(queryByTestId("dialog")).toBeNull();
213
+ fireEvent.click(getByText(/Expand/));
214
+ const dialog = container.querySelector("[data-testid='dialog']");
215
+ expect(dialog).toBeTruthy();
216
+ expect(dialog?.getAttribute("data-size")).toBe("full");
217
+ });
218
+ });
219
+
220
+ describe("FlowAgentCard detail dialog (replaces popover)", () => {
221
+ it("clicking Details opens a dialog and there is no Popout button", () => {
222
+ const state = makeState([agent({ stepId: "one", label: "step-one", status: "complete" })]);
223
+ const { queryByText, queryByTestId, getAllByText } = renderSummary(state);
224
+ expect(queryByText("Popout")).toBeNull();
225
+ expect(queryByTestId("dialog")).toBeNull();
226
+ // "Details" appears once per card; click the card's detail button.
227
+ fireEvent.click(getAllByText("Details")[0]);
228
+ const dialog = queryByTestId("dialog");
229
+ expect(dialog).toBeTruthy();
230
+ expect(dialog?.textContent).toContain("step-one"); // dialog title = displayName
231
+ });
232
+ });
233
+
234
+ describe("FlowSummary expandable rows", () => {
235
+ it("collapsed complete row shows truncated peek; clicking reveals full summary, chips, files", () => {
236
+ const state = makeState([
237
+ agent({
238
+ stepId: "classify",
239
+ label: "classify-intent",
240
+ status: "complete",
241
+ summary: "Decided the request was a refactor of the reducer module.",
242
+ files: ["flow-reducer.ts", "flow-reducer.test.ts"],
243
+ typedOutputs: { intent: "refactor", branch: "refactor" },
244
+ }),
245
+ ]);
246
+ const { container } = renderSummary(state);
247
+ // Scope row assertions to the collapsible summary section (the frozen cards
248
+ // above also surface summary/outputs, so global queries are ambiguous now).
249
+ const section = within(container.querySelector("[data-testid='flow-summaries']") as HTMLElement);
250
+
251
+ // Collapsed: full summary not yet rendered through markdown primitive.
252
+ expect(section.queryByTestId("md")).toBeNull();
253
+
254
+ fireEvent.click(section.getByText("classify-intent", { selector: "span" }));
255
+
256
+ // Expanded: full summary via markdown primitive.
257
+ expect(section.getByTestId("md").textContent).toContain("refactor of the reducer module");
258
+ // Typed-output chip (branch filtered out, intent shown).
259
+ expect(section.getByText("intent")).toBeTruthy();
260
+ // File list rendered.
261
+ expect(section.getByText(/flow-reducer\.test\.ts/)).toBeTruthy();
262
+ });
263
+
264
+ it("failed step renders expanded on mount", () => {
265
+ const state = makeState([
266
+ agent({
267
+ stepId: "verify",
268
+ label: "verify-change",
269
+ status: "error",
270
+ outcome: "hard",
271
+ summary: "Coverage gate failed on the new branch path.",
272
+ }),
273
+ ]);
274
+ const { getByTestId } = renderSummary(state);
275
+ // Auto-expanded β†’ markdown primitive rendered without any click.
276
+ expect(getByTestId("md").textContent).toContain("Coverage gate failed");
277
+ });
278
+
279
+ it("row without summary text is omitted from the list; section hidden when it is the only agent", () => {
280
+ const state = makeState([
281
+ agent({ stepId: "bare", label: "bare-step", status: "complete" }),
282
+ ]);
283
+ const { queryByText, queryByTestId, getAllByTestId } = renderSummary(state);
284
+ // The bare step has no summary text β†’ not listed, and as the only agent the
285
+ // whole Summaries subsection is hidden.
286
+ expect(queryByTestId("flow-summaries")).toBeNull();
287
+ expect(queryByTestId("flow-summary-toggle")).toBeNull();
288
+ expect(queryByText("bare-step", { selector: "span" })).toBeNull();
289
+ // Frozen agent card still present (the filter only affects the Summaries list).
290
+ expect(getAllByTestId("agent-card")).toHaveLength(1);
291
+ });
292
+
293
+ it("Summaries count reflects only summary-bearing agents", () => {
294
+ const state = makeState([
295
+ agent({ stepId: "one", label: "step-one", status: "complete", summary: "S1" }),
296
+ agent({ stepId: "two", label: "step-two", status: "complete" }),
297
+ agent({ stepId: "three", label: "step-three", status: "complete", summary: "S3" }),
298
+ ]);
299
+ const { getByText, queryByText } = renderSummary(state);
300
+ expect(getByText("Summaries (2)")).toBeTruthy();
301
+ // The summary-less middle step is not rendered as a row.
302
+ expect(queryByText("step-two", { selector: "span" })).toBeNull();
303
+ });
304
+
305
+ it("hides the whole Summaries section when no agent has summary text", () => {
306
+ const state = makeState([
307
+ agent({ stepId: "a", label: "a", status: "complete", typedOutputs: { verdict: "pass" } }),
308
+ agent({ stepId: "b", label: "b", status: "complete" }),
309
+ ]);
310
+ const { queryByTestId, getAllByTestId } = renderSummary(state);
311
+ expect(queryByTestId("flow-summaries")).toBeNull();
312
+ expect(queryByTestId("flow-summary-toggle")).toBeNull();
313
+ // Both still appear as frozen cards.
314
+ expect(getAllByTestId("agent-card")).toHaveLength(2);
315
+ });
316
+
317
+ it("expanding one row leaves siblings collapsed", () => {
318
+ const state = makeState([
319
+ agent({ stepId: "one", label: "step-one", status: "complete", summary: "Summary one." }),
320
+ agent({ stepId: "two", label: "step-two", status: "complete", summary: "Summary two." }),
321
+ ]);
322
+ const { getByText, getAllByTestId, queryAllByTestId } = renderSummary(state);
323
+
324
+ expect(queryAllByTestId("md")).toHaveLength(0);
325
+ fireEvent.click(getByText("step-one", { selector: "span" }));
326
+
327
+ const mds = getAllByTestId("md");
328
+ expect(mds).toHaveLength(1);
329
+ expect(mds[0].textContent).toContain("Summary one.");
330
+ });
331
+ });
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Tests for the flow YAML preview content-view claim's dismissal contract.
3
+ *
4
+ * The claim overlays the chat at the current /session/:id URL, gated by the
5
+ * plugin UI-state predicate. On back it MUST clear its own UI state (revealing
6
+ * the chat) AND invoke the shell-provided onClose. The shell wires onClose to a
7
+ * no-op so dismissal stays on the session instead of navigating to "/".
8
+ *
9
+ * See change: fix-settings-back-to-launching-route.
10
+ */
11
+ import React from "react";
12
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
13
+ import { render, act, cleanup, fireEvent } from "@testing-library/react";
14
+ import {
15
+ UiPrimitiveProvider,
16
+ createUiPrimitiveRegistry,
17
+ registerUiPrimitive,
18
+ } from "@blackbelt-technology/dashboard-plugin-runtime";
19
+ import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
20
+ import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
21
+ import { FlowYamlPreviewClaim } from "../client/FlowYamlPreview.js";
22
+ import {
23
+ useFlowsUiActions,
24
+ getFlowsUiStateSnapshot,
25
+ __resetFlowsUiStateForTests,
26
+ } from "../client/FlowsUiStateContext.js";
27
+
28
+ const registry = createUiPrimitiveRegistry();
29
+ // Stub markdownContent primitive β€” the preview body renders through it.
30
+ registerUiPrimitive(
31
+ registry,
32
+ UI_PRIMITIVE_KEYS.markdownContent,
33
+ (({ content }: { content: string }) => <div data-testid="md">{content}</div>) as never,
34
+ );
35
+
36
+ const session = { id: "abc" } as unknown as DashboardSession;
37
+
38
+ function Harness({ onClose }: { onClose: () => void }) {
39
+ const actions = useFlowsUiActions();
40
+ // Seed the preview content so the claim renders.
41
+ React.useEffect(() => {
42
+ actions.setFlowYamlPreview({ content: "name: demo", title: "demo.yaml" });
43
+ }, [actions]);
44
+ return (
45
+ <UiPrimitiveProvider value={registry}>
46
+ <FlowYamlPreviewClaim session={session} routeParams={{}} onClose={onClose} />
47
+ </UiPrimitiveProvider>
48
+ );
49
+ }
50
+
51
+ describe("FlowYamlPreviewClaim dismissal", () => {
52
+ beforeEach(() => __resetFlowsUiStateForTests());
53
+ afterEach(() => {
54
+ cleanup();
55
+ __resetFlowsUiStateForTests();
56
+ });
57
+
58
+ it("back clears UI state AND calls the shell onClose", () => {
59
+ const onClose = vi.fn();
60
+ const { getByTitle } = render(<Harness onClose={onClose} />);
61
+
62
+ // Preview is active before back.
63
+ expect(getFlowsUiStateSnapshot().flowYamlPreview).not.toBeNull();
64
+
65
+ act(() => {
66
+ fireEvent.click(getByTitle("Back"));
67
+ });
68
+
69
+ // Plugin cleared its own state β†’ predicate goes false β†’ chat reappears.
70
+ expect(getFlowsUiStateSnapshot().flowYamlPreview).toBeNull();
71
+ expect(getFlowsUiStateSnapshot().sourceOpenAgent).toBeNull();
72
+ // Shell onClose invoked (wired to a no-op in App; never navigates to "/").
73
+ expect(onClose).toHaveBeenCalledOnce();
74
+ });
75
+ });
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Tests for `reduceFlowsSessionState` and `useFlowsSessionState`.
3
+ *
4
+ * The pure reducer is tested with synthesized event sequences to verify
5
+ * it matches the shell's pre-deletion behavior (event-reducer.ts:1292-1313)
6
+ * exactly. The hook is smoke-tested via React rendering with a live
7
+ * `useSessionEvents` subscription and direct calls to
8
+ * `publishSessionEvent` to drive the event stream.
9
+ *
10
+ * See change: pluginize-flows-via-registry.
11
+ */
12
+ import React from "react";
13
+ import { describe, it, expect, afterEach } from "vitest";
14
+ import { render, act, cleanup } from "@testing-library/react";
15
+ import {
16
+ PluginContextProvider,
17
+ publishSessionEvent,
18
+ clearSessionEvents,
19
+ } from "@blackbelt-technology/dashboard-plugin-runtime";
20
+
21
+ // We don't import __resetSessionEventsStoreForTests across the package
22
+ // boundary (it's marked @internal). Each test scopes events to a unique
23
+ // session id, so isolation comes from the session-id namespace itself.
24
+ let __testCounter = 0;
25
+ function nextSessionId(): string { return `S-${++__testCounter}`; }
26
+ import type { DashboardEvent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
27
+ import {
28
+ reduceFlowsSessionState,
29
+ useFlowsSessionState,
30
+ type FlowsSessionState,
31
+ } from "../client/FlowsSessionStateContext.js";
32
+
33
+ // ── Event factories matching the real protocol shapes ──────────────
34
+
35
+ function flowStartedEvent(seq: number, flowName = "build"): DashboardEvent {
36
+ return {
37
+ seq,
38
+ timestamp: new Date(seq * 1000).toISOString(),
39
+ eventType: "flow_started",
40
+ data: {
41
+ flowName,
42
+ task: "test task",
43
+ steps: [
44
+ { id: "s1", stepType: "agent", agent: "alpha", blockedBy: [] },
45
+ { id: "s2", stepType: "agent", agent: "beta", blockedBy: ["s1"] },
46
+ ],
47
+ },
48
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
+ } as any;
50
+ }
51
+
52
+ function flowSummaryDismissedEvent(seq: number): DashboardEvent {
53
+ return {
54
+ seq,
55
+ timestamp: new Date(seq * 1000).toISOString(),
56
+ eventType: "flow_summary_dismissed",
57
+ data: {},
58
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
59
+ } as any;
60
+ }
61
+
62
+ function unrelatedEvent(seq: number): DashboardEvent {
63
+ return {
64
+ seq,
65
+ timestamp: new Date(seq * 1000).toISOString(),
66
+ eventType: "tool_start",
67
+ data: { toolName: "Read" },
68
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
69
+ } as any;
70
+ }
71
+
72
+ // ── Pure reducer tests ─────────────────────────────────────────────
73
+
74
+ describe("reduceFlowsSessionState (pure)", () => {
75
+ it("returns the same EMPTY_STATE reference for empty input", () => {
76
+ const a = reduceFlowsSessionState([]);
77
+ const b = reduceFlowsSessionState([]);
78
+ expect(a).toBe(b);
79
+ expect(a.flowState).toBeNull();
80
+ expect(a.flowStates.size).toBe(0);
81
+ });
82
+
83
+ it("returns EMPTY_STATE when no flow events are present", () => {
84
+ const result = reduceFlowsSessionState([
85
+ unrelatedEvent(1),
86
+ unrelatedEvent(2),
87
+ ]);
88
+ expect(result.flowState).toBeNull();
89
+ });
90
+
91
+ it("derives flowState from a flow_started event", () => {
92
+ const result = reduceFlowsSessionState([flowStartedEvent(1, "build")]);
93
+ expect(result.flowState).not.toBeNull();
94
+ expect(result.flowState!.flowName).toBe("build");
95
+ expect(result.flowStates.size).toBe(1);
96
+ expect(result.flowStates.get("build")).toBe(result.flowState);
97
+ });
98
+
99
+ it("clears flowStates on flow_summary_dismissed", () => {
100
+ const result = reduceFlowsSessionState([
101
+ flowStartedEvent(1, "build"),
102
+ flowSummaryDismissedEvent(2),
103
+ ]);
104
+ // flow_summary_dismissed clears flowStates per
105
+ // event-reducer.ts:1298-1300 behavior.
106
+ expect(result.flowStates.size).toBe(0);
107
+ });
108
+
109
+ it("ignores unrelated events between flow events", () => {
110
+ const result = reduceFlowsSessionState([
111
+ flowStartedEvent(1, "build"),
112
+ unrelatedEvent(2),
113
+ unrelatedEvent(3),
114
+ ]);
115
+ expect(result.flowState!.flowName).toBe("build");
116
+ });
117
+ });
118
+
119
+ // ── Hook tests (live useSessionEvents subscription) ────────────────
120
+
121
+ function Probe({ sessionId, onSnapshot }: {
122
+ sessionId: string;
123
+ onSnapshot: (state: FlowsSessionState) => void;
124
+ }) {
125
+ const state = useFlowsSessionState(sessionId);
126
+ onSnapshot(state);
127
+ return (
128
+ <div data-testid="probe">
129
+ flow={state.flowState?.flowName ?? "(none)"}
130
+ </div>
131
+ );
132
+ }
133
+
134
+ describe("useFlowsSessionState (hook)", () => {
135
+ afterEach(() => cleanup());
136
+
137
+ it("returns EMPTY_STATE for a session with no events", () => {
138
+ const snaps: FlowsSessionState[] = [];
139
+ const sid = nextSessionId();
140
+ render(
141
+ <PluginContextProvider>
142
+ <Probe sessionId={sid} onSnapshot={(s) => snaps.push(s)} />
143
+ </PluginContextProvider>,
144
+ );
145
+ expect(snaps[0].flowState).toBeNull();
146
+ });
147
+
148
+ it("re-renders with derived state when a flow event arrives", () => {
149
+ const snaps: FlowsSessionState[] = [];
150
+ const sid = nextSessionId();
151
+ const { getByTestId } = render(
152
+ <PluginContextProvider>
153
+ <Probe sessionId={sid} onSnapshot={(s) => snaps.push(s)} />
154
+ </PluginContextProvider>,
155
+ );
156
+ expect(getByTestId("probe").textContent).toContain("flow=(none)");
157
+
158
+ act(() => publishSessionEvent(sid, flowStartedEvent(1, "build")));
159
+ expect(getByTestId("probe").textContent).toContain("flow=build");
160
+ });
161
+
162
+ it("scopes derived state per session", () => {
163
+ const snapsA: FlowsSessionState[] = [];
164
+ const snapsB: FlowsSessionState[] = [];
165
+ const sidA = nextSessionId();
166
+ const sidB = nextSessionId();
167
+ render(
168
+ <PluginContextProvider>
169
+ <Probe sessionId={sidA} onSnapshot={(s) => snapsA.push(s)} />
170
+ <Probe sessionId={sidB} onSnapshot={(s) => snapsB.push(s)} />
171
+ </PluginContextProvider>,
172
+ );
173
+
174
+ act(() => publishSessionEvent(sidA, flowStartedEvent(1, "alpha-flow")));
175
+ act(() => publishSessionEvent(sidB, flowStartedEvent(2, "beta-flow")));
176
+
177
+ const lastA = snapsA[snapsA.length - 1];
178
+ const lastB = snapsB[snapsB.length - 1];
179
+ expect(lastA.flowState!.flowName).toBe("alpha-flow");
180
+ expect(lastB.flowState!.flowName).toBe("beta-flow");
181
+ });
182
+
183
+ it("returns a stable state reference across renders that don't change events", () => {
184
+ const snaps: FlowsSessionState[] = [];
185
+ const sid = nextSessionId();
186
+ const { rerender } = render(
187
+ <PluginContextProvider>
188
+ <Probe sessionId={sid} onSnapshot={(s) => snaps.push(s)} />
189
+ </PluginContextProvider>,
190
+ );
191
+
192
+ act(() => publishSessionEvent(sid, flowStartedEvent(1, "build")));
193
+ const refAfterPublish = snaps[snaps.length - 1];
194
+
195
+ // Force re-render without publishing.
196
+ rerender(
197
+ <PluginContextProvider>
198
+ <Probe sessionId={sid} onSnapshot={(s) => snaps.push(s)} />
199
+ </PluginContextProvider>,
200
+ );
201
+ const refAfterRerender = snaps[snaps.length - 1];
202
+
203
+ expect(refAfterRerender).toBe(refAfterPublish);
204
+ });
205
+
206
+ it("clears flowStates when the events store is cleared", () => {
207
+ const snaps: FlowsSessionState[] = [];
208
+ const sid = nextSessionId();
209
+ render(
210
+ <PluginContextProvider>
211
+ <Probe sessionId={sid} onSnapshot={(s) => snaps.push(s)} />
212
+ </PluginContextProvider>,
213
+ );
214
+
215
+ act(() => publishSessionEvent(sid, flowStartedEvent(1, "build")));
216
+ expect(snaps[snaps.length - 1].flowState).not.toBeNull();
217
+
218
+ act(() => clearSessionEvents(sid));
219
+ const last = snaps[snaps.length - 1];
220
+ expect(last.flowState).toBeNull();
221
+ expect(last.flowStates.size).toBe(0);
222
+ });
223
+ });