@blackbelt-technology/pi-dashboard-flows-plugin 0.5.3 → 0.5.4

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 (35) hide show
  1. package/package.json +39 -4
  2. package/src/__tests__/FlowsSessionStateContext.test.tsx +260 -0
  3. package/src/__tests__/FlowsUiStateContext.test.tsx +140 -0
  4. package/src/__tests__/flowsAvailability.test.ts +92 -0
  5. package/src/__tests__/manifest-discoverability.test.ts +97 -0
  6. package/src/__tests__/render-actions.test.ts +63 -0
  7. package/src/bridge/flow-question-adapter.ts +93 -0
  8. package/src/bridge/index.ts +30 -0
  9. package/src/client/FlowActivityBadge.tsx +36 -9
  10. package/src/client/FlowAgentCard.tsx +180 -41
  11. package/src/client/FlowAgentDetail.tsx +95 -154
  12. package/src/client/FlowAgentPopoutClaim.tsx +66 -0
  13. package/src/client/FlowAgentPopoutPage.tsx +177 -0
  14. package/src/client/FlowArchitect.tsx +297 -220
  15. package/src/client/FlowArchitectPopoutClaim.tsx +52 -0
  16. package/src/client/FlowArchitectPopoutPage.tsx +133 -0
  17. package/src/client/FlowDashboard.tsx +194 -31
  18. package/src/client/FlowGraph.tsx +6 -2
  19. package/src/client/FlowLaunchDialog.tsx +8 -2
  20. package/src/client/FlowQuestionCard.tsx +213 -0
  21. package/src/client/FlowQuestionTranscriptPill.tsx +58 -0
  22. package/src/client/FlowSummary.tsx +43 -21
  23. package/src/client/FlowYamlPopoverButton.tsx +109 -0
  24. package/src/client/FlowYamlPreview.tsx +65 -0
  25. package/src/client/FlowsCommandRoutes.tsx +237 -0
  26. package/src/client/FlowsSessionStateContext.tsx +161 -0
  27. package/src/client/FlowsUiStateContext.tsx +169 -0
  28. package/src/client/SessionFlowActions.tsx +96 -5
  29. package/src/client/flowsAvailability.ts +103 -0
  30. package/src/client/index.tsx +94 -7
  31. package/src/client/popout-url.ts +59 -0
  32. package/src/client/shouldRender.ts +26 -0
  33. package/src/server/index.ts +87 -0
  34. package/src/server/render-actions.ts +88 -0
  35. package/src/server/state-store.ts +85 -0
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Plugin-internal per-session flow/architect state.
3
+ *
4
+ * Replaces what `packages/client/src/lib/event-reducer.ts` does today
5
+ * for `flowState`, `flowStates`, and `architectState` — but lives
6
+ * inside flows-plugin so the dashboard shell carries no flow knowledge.
7
+ *
8
+ * Wiring:
9
+ * - `useSessionEvents(sessionId)` (from dashboard-plugin-runtime) is
10
+ * the only read into shell state. It returns the raw event stream
11
+ * for the session.
12
+ * - `useMemo` runs `reduceFlowEvent` and `reduceArchitectEvent` over
13
+ * the events, producing `{ flowState, flowStates, architectState }`.
14
+ * - The hook `useFlowsSessionState(sessionId)` returns the derived
15
+ * state. Components self-gate on null returns.
16
+ *
17
+ * Per-session caching is handled by React's natural per-component
18
+ * memo: each consumer component calls `useFlowsSessionState(session.id)`
19
+ * inside its own render and gets a `useMemo`-stable reference. There
20
+ * is intentionally no shared `Map<sessionId, ...>` because such a cache
21
+ * would either leak (unbounded growth as sessions come and go) or
22
+ * require eviction, neither of which is necessary when the reducer is
23
+ * cheap and React already memoizes per-render.
24
+ *
25
+ * See change: pluginize-flows-via-registry.
26
+ */
27
+ import { useMemo } from "react";
28
+ import type {
29
+ ArchitectState,
30
+ FlowState,
31
+ DashboardEvent,
32
+ } from "@blackbelt-technology/pi-dashboard-shared/types.js";
33
+ import { useSessionEvents } from "@blackbelt-technology/dashboard-plugin-runtime";
34
+ import {
35
+ isFlowEvent,
36
+ reduceFlowEvent,
37
+ isArchitectEvent,
38
+ reduceArchitectEvent,
39
+ } from "../reducer.js";
40
+
41
+ /** Shape exposed to flows-plugin components for a single session. */
42
+ export interface FlowsSessionState {
43
+ /** The currently-displayed flow's state, or null when no flow is active. */
44
+ flowState: FlowState | null;
45
+ /**
46
+ * All flows seen for this session keyed by `flow.flowName`. Used by
47
+ * components that need to render multiple concurrent flows
48
+ * (FlowDashboard's multi-flow tab bar).
49
+ */
50
+ flowStates: ReadonlyMap<string, FlowState>;
51
+ /** Active architect state, or null when no architect is running. */
52
+ architectState: ArchitectState | null;
53
+ }
54
+
55
+ const EMPTY_STATE: FlowsSessionState = Object.freeze({
56
+ flowState: null,
57
+ flowStates: new Map() as ReadonlyMap<string, FlowState>,
58
+ architectState: null,
59
+ });
60
+
61
+ /**
62
+ * Reduce a session's event stream into flow + architect state. Pure
63
+ * function — no React, no side effects. Exported for tests and for
64
+ * future server-side rendering. The reduction matches the shell's
65
+ * current behavior in `event-reducer.ts` exactly:
66
+ *
67
+ * - flow events → reduceFlowEvent updates flowState; flowStates is
68
+ * resynced after each flow event so the active flow is also stored
69
+ * under its name. `flow_summary_dismissed` clears flowStates.
70
+ * - architect events → reduceArchitectEvent updates architectState.
71
+ *
72
+ * Iterating the full event stream on every render is fine: the event
73
+ * stream's reference is stable (returned from `useSessionEvents`) and
74
+ * the calling hook is wrapped in `useMemo` keyed on that reference,
75
+ * so the reduction only re-runs when a new event arrives.
76
+ */
77
+ export function reduceFlowsSessionState(
78
+ events: readonly DashboardEvent[],
79
+ ): FlowsSessionState {
80
+ let flowState: FlowState | null = null;
81
+ let architectState: ArchitectState | null = null;
82
+ let flowStates: Map<string, FlowState> = new Map();
83
+ let flowStatesMutated = false;
84
+
85
+ // Diagnostic counters for C1 — see fix-flows-plugin-polish. Gated to dev.
86
+ let flowEventCount = 0;
87
+ let architectEventCount = 0;
88
+
89
+ for (const event of events) {
90
+ if (isFlowEvent(event.eventType)) {
91
+ flowEventCount++;
92
+ flowState = reduceFlowEvent(flowState, event);
93
+ if (flowState) {
94
+ if (!flowStatesMutated) {
95
+ flowStates = new Map(flowStates);
96
+ flowStatesMutated = true;
97
+ }
98
+ flowStates.set(flowState.flowName, flowState);
99
+ } else if (event.eventType === "flow_summary_dismissed") {
100
+ if (flowStates.size > 0) {
101
+ flowStates = new Map();
102
+ flowStatesMutated = true;
103
+ }
104
+ }
105
+ }
106
+ if (isArchitectEvent(event.eventType)) {
107
+ architectEventCount++;
108
+ architectState = reduceArchitectEvent(architectState, event);
109
+ }
110
+ }
111
+
112
+ if (typeof import.meta !== "undefined" && (import.meta as { env?: { DEV?: boolean } }).env?.DEV) {
113
+ if (flowEventCount > 0 || architectEventCount > 0) {
114
+ // eslint-disable-next-line no-console
115
+ console.debug(
116
+ "[flows] reduceFlowsSessionState",
117
+ {
118
+ totalEvents: events.length,
119
+ flowEvents: flowEventCount,
120
+ architectEvents: architectEventCount,
121
+ resolvedFlowName: flowState?.flowName,
122
+ resolvedFlowStatus: flowState?.status,
123
+ flowsCount: flowStates.size,
124
+ architectPhase: architectState?.phase,
125
+ },
126
+ );
127
+ }
128
+ }
129
+
130
+ if (flowState === null && architectState === null && flowStates.size === 0) {
131
+ return EMPTY_STATE;
132
+ }
133
+
134
+ return {
135
+ flowState,
136
+ flowStates,
137
+ architectState,
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Hook — derive flow + architect state for a session from its event
143
+ * stream. Result is `useMemo`-stable across renders that don't bring
144
+ * a new event for this session.
145
+ *
146
+ * Plugin components SHALL call this with their `session.id` (from the
147
+ * standard slot prop contract) and self-gate on null returns:
148
+ *
149
+ * ```tsx
150
+ * const { flowState } = useFlowsSessionState(session.id);
151
+ * if (!flowState) return null;
152
+ * ```
153
+ *
154
+ * Returns the frozen `EMPTY_STATE` constant when no flow / architect
155
+ * activity has happened for this session, so the same reference is
156
+ * shared across many same-state renders.
157
+ */
158
+ export function useFlowsSessionState(sessionId: string): FlowsSessionState {
159
+ const events = useSessionEvents(sessionId);
160
+ return useMemo(() => reduceFlowsSessionState(events), [events]);
161
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Plugin-internal UI selection state shared across flow components.
3
+ *
4
+ * Today these flags live in `App.tsx` as `useState` declarations
5
+ * threaded down as props (lines 232, 233, 244, 243 in pre-deletion
6
+ * App.tsx). After Part F's component refactor + Part H's shell
7
+ * deletions, this context becomes the sole owner of these flags.
8
+ *
9
+ * Scope: per dashboard mount (NOT per session). Selecting an agent in
10
+ * one flow detail view doesn't affect another session's selection
11
+ * because the user can only view one session at a time — the slot
12
+ * consumer's `session` prop tells each component which session it's
13
+ * rendering for, but the selection flags themselves are global to the
14
+ * "currently focused content view." This matches the shell's current
15
+ * behavior; no per-session state is needed.
16
+ *
17
+ * The provider lives at the root of the flows-plugin contribution
18
+ * tree. Per the proposal Decision 5 alternative (rejected the
19
+ * `PluginRoot` runtime convention), the provider is mounted by
20
+ * wrapping each top-level claim's exported component. A single shared
21
+ * provider is acceptable because React contexts mount once and then
22
+ * any descendant consumer reads from that one instance — multiple
23
+ * mount points only cost a few extra Provider wrappers, not duplicate
24
+ * state.
25
+ *
26
+ * Actually, Decision 5 was DROPPED. Without `PluginRoot`, multiple
27
+ * mount points would create multiple providers with independent state.
28
+ * Solution: hoist into a module-level store (the pattern used by
29
+ * `session-events-store.ts` in plugin-runtime). React `useSyncExternalStore`
30
+ * subscribes; setters mutate the module-level state and notify
31
+ * subscribers.
32
+ *
33
+ * See change: pluginize-flows-via-registry.
34
+ */
35
+ import { useSyncExternalStore } from "react";
36
+
37
+ /** UI selection state shared across the plugin's content-view contributions. */
38
+ export interface FlowsUiState {
39
+ /**
40
+ * When non-null, the user has clicked an agent's "view source"
41
+ * action; the agent's source is displayed in the YAML preview.
42
+ */
43
+ sourceOpenAgent: string | null;
44
+ /**
45
+ * When non-null, the YAML preview is showing the supplied content
46
+ * with the supplied title. Used for both flow YAML and architect
47
+ * agent source previews.
48
+ */
49
+ flowYamlPreview: { content: string; title: string } | null;
50
+ }
51
+
52
+ const INITIAL_STATE: FlowsUiState = Object.freeze({
53
+ sourceOpenAgent: null,
54
+ flowYamlPreview: null,
55
+ });
56
+
57
+ let state: FlowsUiState = INITIAL_STATE;
58
+ const subscribers = new Set<() => void>();
59
+
60
+ function notify(): void {
61
+ for (const cb of subscribers) cb();
62
+ }
63
+
64
+ function subscribe(cb: () => void): () => void {
65
+ subscribers.add(cb);
66
+ return () => subscribers.delete(cb);
67
+ }
68
+
69
+ function getSnapshot(): FlowsUiState {
70
+ return state;
71
+ }
72
+
73
+ /**
74
+ * Imperative read of the current UI state from outside React. Used by
75
+ * the plugin's manifest predicates (see `index.tsx`'s
76
+ * `isFlow*Active` exports) so the shell's slot consumer can check
77
+ * "does this claim want to render right now?" without hooks. The
78
+ * returned value is the same frozen snapshot React would see; it's
79
+ * safe to read in any context.
80
+ *
81
+ * See change: pluginize-flows-via-registry (design.md Decision 3
82
+ * RECONSIDERED — predicates over routes).
83
+ */
84
+ export function getFlowsUiStateSnapshot(): FlowsUiState {
85
+ return state;
86
+ }
87
+
88
+ /**
89
+ * Apply a partial update to the UI state. The new snapshot reference
90
+ * changes only when at least one field actually differs (`Object.is`),
91
+ * so consumers that read a single field via `useFlowsUiStateSelector`
92
+ * don't re-render on no-op updates to other fields.
93
+ */
94
+ function setState(patch: Partial<FlowsUiState>): void {
95
+ let mutated = false;
96
+ const next: FlowsUiState = { ...state };
97
+ for (const key of Object.keys(patch) as Array<keyof FlowsUiState>) {
98
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
99
+ const nextRec = next as unknown as Record<string, any>;
100
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
101
+ const patchRec = patch as unknown as Record<string, any>;
102
+ if (!Object.is(nextRec[key], patchRec[key])) {
103
+ nextRec[key] = patchRec[key];
104
+ mutated = true;
105
+ }
106
+ }
107
+ if (mutated) {
108
+ state = Object.freeze(next);
109
+ notify();
110
+ }
111
+ }
112
+
113
+ /** Setters API exposed via the hook. Stable function references — never re-created. */
114
+ export interface FlowsUiActions {
115
+ /** Set the agent whose source is currently open in the YAML preview. */
116
+ setSourceOpenAgent(agent: string | null): void;
117
+ /** Set the YAML preview content (or close it with null). */
118
+ setFlowYamlPreview(value: { content: string; title: string } | null): void;
119
+ /**
120
+ * Unified dismiss called by the shared FlowArchitect dismiss path.
121
+ * Closes architect detail, clears flow detail agent, clears source
122
+ * open agent, clears YAML preview. The shell's previous `onDismiss`
123
+ * had subtly different cleanup at three different call sites
124
+ * (App.tsx lines 1023, 1043, 1084 + 1057, 1098); this unifies them
125
+ * per the proposal's Decision 4 (FC-1 in the validation report).
126
+ */
127
+ dismissAll(): void;
128
+ }
129
+
130
+ const ACTIONS: FlowsUiActions = Object.freeze({
131
+ setSourceOpenAgent: (agent: string | null) => setState({ sourceOpenAgent: agent }),
132
+ setFlowYamlPreview: (value: { content: string; title: string } | null) => setState({ flowYamlPreview: value }),
133
+ dismissAll: () =>
134
+ setState({
135
+ sourceOpenAgent: null,
136
+ flowYamlPreview: null,
137
+ }),
138
+ });
139
+
140
+ /**
141
+ * Hook — read the entire UI selection state. Most components only
142
+ * need one or two fields; selector hooks (e.g. via `useMemo` over the
143
+ * returned object) can narrow down. The state reference is stable
144
+ * across no-op updates so React.memo bails on stable cases.
145
+ */
146
+ export function useFlowsUiState(): FlowsUiState {
147
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
148
+ }
149
+
150
+ /**
151
+ * Hook — get the actions API. Returns the same frozen object on every
152
+ * call — no React hooks involved, just a constant. Exported as a hook
153
+ * (rather than a constant) for symmetry with `useFlowsUiState` and so
154
+ * future versions can swap the implementation without breaking
155
+ * consumers.
156
+ */
157
+ export function useFlowsUiActions(): FlowsUiActions {
158
+ return ACTIONS;
159
+ }
160
+
161
+ /**
162
+ * Test-only helper to reset the module-level state between tests.
163
+ *
164
+ * @internal
165
+ */
166
+ export function __resetFlowsUiStateForTests(): void {
167
+ state = INITIAL_STATE;
168
+ subscribers.clear();
169
+ }
@@ -1,10 +1,22 @@
1
1
  import React, { useState } from "react";
2
2
  import { Icon } from "@mdi/react";
3
3
  import { mdiPlay, mdiPlus } from "@mdi/js";
4
- import type { FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
4
+ import type {
5
+ CommandInfo,
6
+ DashboardSession,
7
+ FlowInfo,
8
+ FlowState,
9
+ } from "@blackbelt-technology/pi-dashboard-shared/types.js";
5
10
  import { FlowLaunchDialog } from "./FlowLaunchDialog.js";
6
- import { ConfirmDialog } from "../../../client/src/components/ConfirmDialog.js";
7
- import { SearchableSelectDialog, type SelectOption } from "../../../client/src/components/SearchableSelectDialog.js";
11
+ import { FlowActivityBadge } from "./FlowActivityBadge.js";
12
+ import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
13
+ import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
14
+ import type { UiSelectOption as SelectOption } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
15
+ import {
16
+ useUiPrimitive,
17
+ usePluginSend,
18
+ useSessionData,
19
+ } from "@blackbelt-technology/dashboard-plugin-runtime";
8
20
 
9
21
  export function SessionFlowActions({
10
22
  flows,
@@ -12,13 +24,21 @@ export function SessionFlowActions({
12
24
  hasFlowsEdit,
13
25
  hasFlowsDelete,
14
26
  onFlowAction,
27
+ flowState,
28
+ onAbortFlow,
15
29
  }: {
16
30
  flows: FlowInfo[];
17
31
  hasFlowsNew: boolean;
18
32
  hasFlowsEdit?: boolean;
19
33
  hasFlowsDelete?: boolean;
20
34
  onFlowAction: (action: string, opts?: { flowName?: string; task?: string; description?: string }) => void;
35
+ /** Current flow state for this session. Drives the status pill rendered above the action buttons. */
36
+ flowState?: FlowState | null;
37
+ /** Dispatch flow_control abort. Called by the running-flow pill's Abort button. */
38
+ onAbortFlow?: () => void;
21
39
  }) {
40
+ const ConfirmDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.confirmDialog);
41
+ const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
22
42
  const [pickerOpen, setPickerOpen] = useState(false);
23
43
  const [editPickerOpen, setEditPickerOpen] = useState(false);
24
44
  const [editFlowName, setEditFlowName] = useState<string | null>(null);
@@ -27,7 +47,25 @@ export function SessionFlowActions({
27
47
  const [selectedFlow, setSelectedFlow] = useState<FlowInfo | null>(null);
28
48
  const [newFlowOpen, setNewFlowOpen] = useState(false);
29
49
 
30
- if (flows.length === 0 && !hasFlowsNew) return null;
50
+ // Compute running-flow badge inputs from flowState (when present).
51
+ // See change: fix-flows-plugin-polish (A5 + A6).
52
+ const badgeProps = flowState
53
+ ? (() => {
54
+ const agents = flowState.agents;
55
+ const total = agents.size;
56
+ const done = Array.from(agents.values()).filter(
57
+ (a) => a.status === "complete" || a.status === "error" || a.status === "blocked",
58
+ ).length;
59
+ return {
60
+ flowName: flowState.flowName,
61
+ agentsDone: done,
62
+ agentsTotal: total,
63
+ status: flowState.status,
64
+ };
65
+ })()
66
+ : null;
67
+
68
+ if (flows.length === 0 && !hasFlowsNew && !badgeProps) return null;
31
69
 
32
70
  const flowOptions: SelectOption[] = flows.map((f) => ({
33
71
  value: f.name,
@@ -37,7 +75,13 @@ export function SessionFlowActions({
37
75
 
38
76
  return (
39
77
  <>
40
- <div>
78
+ <div className="flex flex-col gap-1.5">
79
+ {badgeProps && (
80
+ <FlowActivityBadge
81
+ {...badgeProps}
82
+ onAbort={badgeProps.status === "running" ? onAbortFlow : undefined}
83
+ />
84
+ )}
41
85
  <div className="flex items-center gap-1.5 flex-wrap">
42
86
  {flows.length > 0 && (
43
87
  <button
@@ -175,3 +219,50 @@ export function SessionFlowActions({
175
219
  </>
176
220
  );
177
221
  }
222
+
223
+ /**
224
+ * Slot-consumer wrapper for the `session-card-action-bar` claim.
225
+ * Reads per-session `flows_list` and `commands_list` from the plugin-
226
+ * runtime per-session-data store (mirrored by the shell on every
227
+ * `flows_list` / `commands_list` browser-protocol message). Dispatches
228
+ * via pluginContext.send. See change: pluginize-flows-via-registry.
229
+ *
230
+ * Returns null when the session has no flows AND no `flows:new`
231
+ * command — this matches the shell's previous gate at
232
+ * SessionCard.tsx:651 (`flows && onFlowAction && ...`).
233
+ */
234
+ export function SessionFlowActionsClaim({ session }: { session: DashboardSession }) {
235
+ const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
236
+ const commands = useSessionData<CommandInfo[]>(session.id, "commandsList") ?? [];
237
+ const { flowState } = useFlowsSessionState(session.id);
238
+ const send = usePluginSend();
239
+
240
+ const hasFlowsNew = commands.some((c) => c.name === "flows:new");
241
+ const hasFlowsEdit = commands.some((c) => c.name === "flows:edit");
242
+ const hasFlowsDelete = commands.some((c) => c.name === "flows:delete");
243
+
244
+ // Render when there's a flow active OR action buttons are available.
245
+ // See change: fix-flows-plugin-polish (A5).
246
+ if (flows.length === 0 && !hasFlowsNew && !flowState) return null;
247
+
248
+ return (
249
+ <SessionFlowActions
250
+ flows={flows}
251
+ hasFlowsNew={hasFlowsNew}
252
+ hasFlowsEdit={hasFlowsEdit}
253
+ hasFlowsDelete={hasFlowsDelete}
254
+ flowState={flowState}
255
+ onAbortFlow={() => send({ type: "flow_control", sessionId: session.id, action: "abort" })}
256
+ onFlowAction={(action, opts) =>
257
+ send({
258
+ type: "flow_management",
259
+ sessionId: session.id,
260
+ action,
261
+ flowName: opts?.flowName,
262
+ task: opts?.task,
263
+ description: opts?.description,
264
+ })
265
+ }
266
+ />
267
+ );
268
+ }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Per-session sync availability cache for flows-plugin's
3
+ * `shouldRenderFlowsSubcard` predicate.
4
+ *
5
+ * The MEMORY/honcho path uses a global boolean (extension installed or not).
6
+ * Flow availability is per-session: session A may have `flowsList`, session
7
+ * B may not. The cache is therefore keyed by sessionId.
8
+ *
9
+ * Population is driven by a module-level subscriber attached to the runtime's
10
+ * `subscribeSessionDataKey` API at plugin-client-entry load. Each
11
+ * `publishSessionData` for `flowsList` or `commandsList` recomputes
12
+ * availability for that session and writes to the cache.
13
+ *
14
+ * The cache is closed-by-default: `getFlowsAvailabilitySync` returns `false`
15
+ * for sessions the subscriber hasn't observed yet. This prevents a
16
+ * subcard-flicker on first paint (hidden → visible is fine, visible → hidden
17
+ * would be jarring). See change: add-flows-subcard (design.md Decision 3).
18
+ */
19
+ import {
20
+ getSessionData,
21
+ subscribeSessionDataKey,
22
+ } from "@blackbelt-technology/dashboard-plugin-runtime";
23
+ import type { CommandInfo, FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
24
+
25
+ const availability = new Map<string, boolean>();
26
+
27
+ /**
28
+ * Sync readable accessor for `shouldRenderFlowsSubcard`. Returns `false`
29
+ * for sessions whose availability has not been observed yet.
30
+ */
31
+ export function getFlowsAvailabilitySync(sessionId: string): boolean {
32
+ return availability.get(sessionId) ?? false;
33
+ }
34
+
35
+ /**
36
+ * Set the cached availability for a session. Exposed for tests and for the
37
+ * module-level subscriber installed by `installFlowsAvailabilitySubscriber`.
38
+ */
39
+ export function setFlowsAvailability(sessionId: string, has: boolean): void {
40
+ availability.set(sessionId, has);
41
+ }
42
+
43
+ /**
44
+ * Compute availability from the published per-session-data store values.
45
+ * Pure helper — no side effects.
46
+ */
47
+ function computeAvailability(
48
+ flows: FlowInfo[] | undefined,
49
+ commands: CommandInfo[] | undefined,
50
+ ): boolean {
51
+ const hasFlows = Array.isArray(flows) && flows.length > 0;
52
+ const hasFlowsNew = Array.isArray(commands) && commands.some((c) => c.name === "flows:new");
53
+ return hasFlows || hasFlowsNew;
54
+ }
55
+
56
+ let installed = false;
57
+ let unsubscribers: Array<() => void> = [];
58
+
59
+ /**
60
+ * Install a module-level subscriber that updates the availability cache on
61
+ * every `flowsList` / `commandsList` publish. Idempotent: subsequent calls
62
+ * return the same unsubscribe function and do not multiply listeners.
63
+ *
64
+ * Called once at flows-plugin client-entry load.
65
+ */
66
+ export function installFlowsAvailabilitySubscriber(): () => void {
67
+ if (installed) {
68
+ return uninstall;
69
+ }
70
+ installed = true;
71
+
72
+ const recompute = (sessionId: string): void => {
73
+ const flows = getSessionData<FlowInfo[]>(sessionId, "flowsList");
74
+ const commands = getSessionData<CommandInfo[]>(sessionId, "commandsList");
75
+ setFlowsAvailability(sessionId, computeAvailability(flows, commands));
76
+ };
77
+
78
+ unsubscribers.push(
79
+ subscribeSessionDataKey("flowsList", (sessionId) => recompute(sessionId)),
80
+ );
81
+ unsubscribers.push(
82
+ subscribeSessionDataKey("commandsList", (sessionId) => recompute(sessionId)),
83
+ );
84
+
85
+ return uninstall;
86
+ }
87
+
88
+ function uninstall(): void {
89
+ for (const u of unsubscribers) u();
90
+ unsubscribers = [];
91
+ installed = false;
92
+ }
93
+
94
+ /**
95
+ * Test-only: reset cache + install guard so test cases can re-install the
96
+ * subscriber from scratch.
97
+ *
98
+ * @internal
99
+ */
100
+ export function __resetFlowsAvailabilityForTests(): void {
101
+ availability.clear();
102
+ uninstall();
103
+ }
@@ -7,11 +7,17 @@
7
7
  * Also exports the `hasActiveFlow` predicate consumed by the
8
8
  * `pi-dashboard-plugin` manifest's `session-card-badge` claim.
9
9
  */
10
- import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
11
10
 
11
+
12
+ // Existing presentation components — still used directly by App.tsx
13
+ // during the cutover (Part H removes those call sites).
12
14
  export { FlowDashboard } from "./FlowDashboard.js";
13
15
  export { FlowAgentCard } from "./FlowAgentCard.js";
14
16
  export { FlowAgentDetail } from "./FlowAgentDetail.js";
17
+ export { FlowAgentPopoutPage } from "./FlowAgentPopoutPage.js";
18
+ export { FlowAgentPopoutClaim } from "./FlowAgentPopoutClaim.js";
19
+ export { FlowArchitectPopoutPage } from "./FlowArchitectPopoutPage.js";
20
+ export { FlowArchitectPopoutClaim } from "./FlowArchitectPopoutClaim.js";
15
21
  export { FlowSummary } from "./FlowSummary.js";
16
22
  export { FlowGraph, flowStateToGraphSteps, architectStepsToGraphSteps, computeLayout } from "./FlowGraph.js";
17
23
  export { FlowArchitect, FlowArchitectDetail, ArchitectInputPrompt } from "./FlowArchitect.js";
@@ -20,10 +26,91 @@ export { FlowLaunchDialog } from "./FlowLaunchDialog.js";
20
26
  export { FlowTabBar } from "./FlowTabBar.js";
21
27
  export { SessionFlowActions } from "./SessionFlowActions.js";
22
28
 
23
- /**
24
- * Predicate for the `session-card-badge` slot claim.
25
- * The slot consumer skips claims whose predicate returns false.
26
- */
27
- export function hasActiveFlow(session: DashboardSession): boolean {
28
- return Boolean(session.activeFlowName);
29
+ // Slot-claim wrappers — the plugin's manifest references these.
30
+ // Each derives state from the plugin-internal contexts and dispatches
31
+ // via pluginContext.send. See change: pluginize-flows-via-registry.
32
+ // FlowActivityBadgeClaim removed in fix-flows-plugin-polish (A5) — the
33
+ // session-card-badge claim was dropped because the badge belongs in the
34
+ // FLOWS subcard, not WORKSPACE. SessionFlowActions now renders the badge
35
+ // directly via the FlowActivityBadge component.
36
+ export { FlowDashboardClaim } from "./FlowDashboard.js";
37
+ export { FlowArchitectClaim } from "./FlowArchitect.js";
38
+
39
+ export { FlowSummaryClaim } from "./FlowSummary.js";
40
+ export { FlowYamlPreviewClaim } from "./FlowYamlPreview.js";
41
+ export { SessionFlowActionsClaim } from "./SessionFlowActions.js";
42
+
43
+ // Manifest-level shouldRender predicate for the `session-card-flows` claim.
44
+ // See change: add-flows-subcard.
45
+ export { shouldRenderFlowsSubcard } from "./shouldRender.js";
46
+
47
+ // Flow slash commands (`/flows`, `/flows:new`, `/flows:edit`, `/flows:delete`)
48
+ // are no longer claimed by the dashboard plugin manifest. Flow operations
49
+ // surface through buttons only (`SessionFlowActions`, `FlowLaunchDialog`,
50
+ // `FlowDashboard` Abort). pi-flows itself continues to register the slash
51
+ // commands for TUI users. See change: fix-pi-flows-end-to-end (Group 8).
52
+ //
53
+ // The FlowsCommandRoutes module is no longer exported from this barrel.
54
+ // Restore the exports here if/when the dashboard re-introduces command-route
55
+ // claims for flows.
56
+
57
+ // Plugin-internal state hooks. Components consume these in place of
58
+ // props that previously came from App.tsx. See change:
59
+ // pluginize-flows-via-registry.
60
+ export {
61
+ useFlowsSessionState,
62
+ reduceFlowsSessionState,
63
+ } from "./FlowsSessionStateContext.js";
64
+ export type { FlowsSessionState } from "./FlowsSessionStateContext.js";
65
+ import { getFlowsUiStateSnapshot } from "./FlowsUiStateContext.js";
66
+ import { installFlowsAvailabilitySubscriber } from "./flowsAvailability.js";
67
+ import { registerPromptComponent } from "@blackbelt-technology/dashboard-plugin-runtime";
68
+
69
+ // Register the `flow-question` prompt component type so the shell knows to
70
+ // route flow-tagged prompts to the widget-bar placement instead of inline
71
+ // chat. Idempotent under HMR — `registerPromptComponent` replaces prior
72
+ // entries without throwing. See change: route-flow-asks-to-upper-slot.
73
+ registerPromptComponent({ type: "flow-question", placement: "widget-bar" });
74
+
75
+ // Install the per-session flows-availability subscriber once at module
76
+ // load. The subscriber populates the sync cache that
77
+ // `shouldRenderFlowsSubcard` reads. Idempotent (guarded inside the
78
+ // installer). See change: add-flows-subcard (design.md Decision 3 —
79
+ // module-level subscriber breaks the chicken-and-egg cycle between
80
+ // the predicate and the component it gates).
81
+ installFlowsAvailabilitySubscriber();
82
+ export {
83
+ useFlowsUiState,
84
+ useFlowsUiActions,
85
+ } from "./FlowsUiStateContext.js";
86
+ export { getFlowsUiStateSnapshot } from "./FlowsUiStateContext.js";
87
+ export type { FlowsUiState, FlowsUiActions } from "./FlowsUiStateContext.js";
88
+
89
+ // hasActiveFlow predicate removed: the manifest no longer references
90
+ // it because FlowActivityBadgeClaim self-gates inside the component
91
+ // body via useFlowsSessionState. See change:
92
+ // pluginize-flows-via-registry.
93
+
94
+ // ── content-view claim predicates ─────────────────────────────────
95
+ //
96
+ // Each `content-view` claim in the manifest references one of these
97
+ // predicates via the `predicate` field. The slot consumer calls the
98
+ // predicate at render time; the first claim (priority order) whose
99
+ // predicate returns `true` renders. If none return `true`, the slot
100
+ // renders nothing and the shell's fallback shows the chat.
101
+ //
102
+ // Each predicate reads the plugin's UI-state store imperatively (via
103
+ // `getFlowsUiStateSnapshot` — not a hook, safe outside React) so it
104
+ // can run from the slot-registry filter. The `_session` argument is
105
+ // passed by the slot system per the predicate contract
106
+ // (`(props) => boolean`) but is unused here because activation lives
107
+ // in plugin state, not session state.
108
+ //
109
+ // See change: pluginize-flows-via-registry (design.md Decision 3
110
+ // RECONSIDERED — predicates over routes).
111
+
112
+
113
+
114
+ export function isFlowYamlPreviewActive(_session?: unknown): boolean {
115
+ return getFlowsUiStateSnapshot().flowYamlPreview !== null;
29
116
  }