@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,67 @@
1
+ /**
2
+ * Content-view claim renderer for the flow YAML preview, gated by the
3
+ * `isFlowYamlPreviewActive` predicate.
4
+ *
5
+ * Replaces the shell's `flowYamlPreview` state + MarkdownPreviewView
6
+ * call site that App.tsx used to have. The content (yaml string +
7
+ * title) is set by the plugin's UI-state actions (see Part F.4 / F.5
8
+ * callbacks) when the user clicks "view yaml" or "view agent source".
9
+ *
10
+ * See change: pluginize-flows-via-registry (design.md Decision 3
11
+ * RECONSIDERED — predicates over routes).
12
+ */
13
+
14
+ import { useT, useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
15
+ import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
16
+ import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
17
+ import { mdiArrowLeft } from "@mdi/js";
18
+ import { Icon } from "@mdi/react";
19
+ import React from "react";
20
+ import { useFlowsUiActions, useFlowsUiState } from "./FlowsUiStateContext.js";
21
+
22
+ /**
23
+ * Slot-consumer wrapper for the `content-view` claim. Reads the
24
+ * preview content from the plugin's internal UI-state context. On
25
+ * dismiss, clears `flowYamlPreview` and `sourceOpenAgent` and calls
26
+ * the slot's `onClose`.
27
+ */
28
+ export function FlowYamlPreviewClaim({
29
+ onClose,
30
+ }: {
31
+ // session prop is part of the slot contract but unused here \u2014 the
32
+ // preview content is already in the plugin's UI-state context.
33
+ session: DashboardSession;
34
+ routeParams: Record<string, string>;
35
+ onClose: () => void;
36
+ }) {
37
+ const t = useT();
38
+ const MarkdownContent = useUiPrimitive(UI_PRIMITIVE_KEYS.markdownContent);
39
+ const { flowYamlPreview } = useFlowsUiState();
40
+ const actions = useFlowsUiActions();
41
+
42
+ if (!flowYamlPreview) return null;
43
+
44
+ const handleBack = () => {
45
+ actions.setFlowYamlPreview(null);
46
+ actions.setSourceOpenAgent(null);
47
+ onClose();
48
+ };
49
+
50
+ return (
51
+ <div className="flex flex-col h-full overflow-hidden">
52
+ <div className="px-3 py-2 border-b border-[var(--border-subtle)] bg-[var(--bg-secondary)] flex items-center gap-2">
53
+ <button
54
+ onClick={handleBack}
55
+ className="text-[var(--text-tertiary)] hover:text-[var(--text-primary)] transition-colors"
56
+ title={t("back", undefined, "Back")}
57
+ >
58
+ <Icon path={mdiArrowLeft} size={0.7} />
59
+ </button>
60
+ <div className="font-medium text-sm truncate">{flowYamlPreview.title}</div>
61
+ </div>
62
+ <div className="flex-1 overflow-auto p-3">
63
+ <MarkdownContent content={flowYamlPreview.content} />
64
+ </div>
65
+ </div>
66
+ );
67
+ }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Slash-command route components for /flows, /flows:new,
3
+ * /flows:edit, /flows:delete. Each renders the appropriate launcher /
4
+ * picker / dialog, dispatches via pluginContext.send, and calls
5
+ * `onClose` on dismissal so the shell's command-route slot consumer
6
+ * navigates back.
7
+ *
8
+ * Replaces the four flow dialog blocks in App.tsx (lines 1199-1313)
9
+ * once the shell deletes them in Part H.
10
+ *
11
+ * See change: pluginize-flows-via-registry.
12
+ */
13
+ import React, { useState } from "react";
14
+ import type {
15
+ CommandInfo,
16
+ DashboardSession,
17
+ FlowInfo,
18
+ } from "@blackbelt-technology/pi-dashboard-shared/types.js";
19
+ import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
20
+ import type { UiSelectOption as SelectOption } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
21
+ import {
22
+ useUiPrimitive,
23
+ usePluginSend,
24
+ useSessionData,
25
+ } from "@blackbelt-technology/dashboard-plugin-runtime";
26
+ import { FlowLaunchDialog } from "./FlowLaunchDialog.js";
27
+
28
+ // ── Helpers ────────────────────────────────────────────────────────
29
+
30
+ function dispatchFlowAction(
31
+ send: (msg: unknown) => void,
32
+ sessionId: string,
33
+ action: string,
34
+ opts?: { flowName?: string; task?: string; description?: string },
35
+ ): void {
36
+ send({
37
+ type: "flow_management",
38
+ sessionId,
39
+ action,
40
+ flowName: opts?.flowName,
41
+ task: opts?.task,
42
+ description: opts?.description,
43
+ });
44
+ }
45
+
46
+ interface RouteProps {
47
+ session: DashboardSession;
48
+ routeParams: Record<string, string>;
49
+ onClose: () => void;
50
+ }
51
+
52
+ // ── /flows — main picker ───────────────────────────────────────────
53
+
54
+ /**
55
+ * Three-state machine: pick → launch (taskRequired) | direct-run.
56
+ * When the user picks a flow, either run it (no task required) and
57
+ * close, or open the launch dialog to capture a task.
58
+ */
59
+ export function FlowsListRoute({ session, onClose }: RouteProps) {
60
+ const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
61
+ const send = usePluginSend();
62
+ const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
63
+ const commands = useSessionData<CommandInfo[]>(session.id, "commandsList") ?? [];
64
+ const [launchTarget, setLaunchTarget] = useState<FlowInfo | null>(null);
65
+
66
+ const hasFlowsNew = commands.some((c) => c.name === "flows:new");
67
+ const hasFlowsEdit = commands.some((c) => c.name === "flows:edit");
68
+ const hasFlowsDelete = commands.some((c) => c.name === "flows:delete");
69
+
70
+ if (launchTarget) {
71
+ return (
72
+ <FlowLaunchDialog
73
+ flowName={launchTarget.name}
74
+ description={launchTarget.description}
75
+ session={session}
76
+ onSubmit={(task) => {
77
+ dispatchFlowAction(send, session.id, "run", {
78
+ flowName: launchTarget.name,
79
+ task: task || undefined,
80
+ });
81
+ onClose();
82
+ }}
83
+ onCancel={() => {
84
+ setLaunchTarget(null);
85
+ onClose();
86
+ }}
87
+ />
88
+ );
89
+ }
90
+
91
+ const flowOptions: SelectOption[] = [
92
+ ...(hasFlowsNew
93
+ ? [{ value: "__new__", label: "+ New Flow", description: "Design a new flow with the Flow Architect" }]
94
+ : []),
95
+ ...(hasFlowsEdit && flows.length > 0
96
+ ? [{ value: "__edit__", label: "\u270E\uFE0E Edit Flow...", description: "Edit an existing flow" }]
97
+ : []),
98
+ ...(hasFlowsDelete && flows.length > 0
99
+ ? [{ value: "__delete__", label: "\u00D7 Delete Flow...", description: "Delete a saved flow" }]
100
+ : []),
101
+ ...flows.map((f) => ({ value: f.name, label: f.name, description: f.description })),
102
+ ];
103
+
104
+ return (
105
+ <SearchableSelectDialog
106
+ title="Flows"
107
+ options={flowOptions}
108
+ placeholder="Search flows..."
109
+ emptyMessage="No flows available"
110
+ onSelect={(value) => {
111
+ if (value === "__new__") {
112
+ // Send the user to the /flows:new route via pluginRouter.
113
+ // Until pluginRouter wiring lands, just open the new dialog
114
+ // inline by closing this and dispatching the new command.
115
+ send({ type: "send_prompt", sessionId: session.id, text: "/flows:new" });
116
+ onClose();
117
+ return;
118
+ }
119
+ if (value === "__edit__") {
120
+ send({ type: "send_prompt", sessionId: session.id, text: "/flows:edit" });
121
+ onClose();
122
+ return;
123
+ }
124
+ if (value === "__delete__") {
125
+ send({ type: "send_prompt", sessionId: session.id, text: "/flows:delete" });
126
+ onClose();
127
+ return;
128
+ }
129
+ const flow = flows.find((f) => f.name === value);
130
+ if (!flow) {
131
+ onClose();
132
+ return;
133
+ }
134
+ if (flow.taskRequired) {
135
+ setLaunchTarget(flow);
136
+ return;
137
+ }
138
+ dispatchFlowAction(send, session.id, "run", { flowName: flow.name });
139
+ onClose();
140
+ }}
141
+ onCancel={onClose}
142
+ />
143
+ );
144
+ }
145
+
146
+ // ── /flows:new ─────────────────────────────────────────────────────
147
+
148
+ export function FlowsNewRoute({ session, onClose }: RouteProps) {
149
+ const send = usePluginSend();
150
+ return (
151
+ <FlowLaunchDialog
152
+ flowName="flows:new"
153
+ description="Design a new flow with the Flow Architect"
154
+ onSubmit={(task) => {
155
+ if (task.trim()) {
156
+ dispatchFlowAction(send, session.id, "new", { description: task.trim() });
157
+ }
158
+ onClose();
159
+ }}
160
+ onCancel={onClose}
161
+ />
162
+ );
163
+ }
164
+
165
+ // ── /flows:edit ────────────────────────────────────────────────────
166
+
167
+ export function FlowsEditRoute({ session, onClose }: RouteProps) {
168
+ const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
169
+ const send = usePluginSend();
170
+ const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
171
+ const [editTarget, setEditTarget] = useState<string | null>(null);
172
+
173
+ if (editTarget) {
174
+ return (
175
+ <FlowLaunchDialog
176
+ flowName={editTarget}
177
+ description="Describe how this flow should be updated"
178
+ onSubmit={(desc) => {
179
+ if (desc.trim()) {
180
+ dispatchFlowAction(send, session.id, "edit", {
181
+ flowName: editTarget,
182
+ description: desc.trim(),
183
+ });
184
+ }
185
+ onClose();
186
+ }}
187
+ onCancel={onClose}
188
+ />
189
+ );
190
+ }
191
+
192
+ return (
193
+ <SearchableSelectDialog
194
+ title="Edit Flow"
195
+ options={flows.map((f) => ({ value: f.name, label: f.name, description: f.description }))}
196
+ placeholder="Search flows..."
197
+ emptyMessage="No flows available"
198
+ onSelect={(value) => setEditTarget(value)}
199
+ onCancel={onClose}
200
+ />
201
+ );
202
+ }
203
+
204
+ // ── /flows:delete ──────────────────────────────────────────────────
205
+
206
+ export function FlowsDeleteRoute({ session, onClose }: RouteProps) {
207
+ const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
208
+ const ConfirmDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.confirmDialog);
209
+ const send = usePluginSend();
210
+ const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
211
+ const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
212
+
213
+ if (deleteTarget) {
214
+ return (
215
+ <ConfirmDialog
216
+ message={`Delete flow "${deleteTarget}"? This will remove the flow file and any associated agents.`}
217
+ confirmLabel="Delete"
218
+ onConfirm={() => {
219
+ dispatchFlowAction(send, session.id, "delete", { flowName: deleteTarget });
220
+ onClose();
221
+ }}
222
+ onCancel={onClose}
223
+ />
224
+ );
225
+ }
226
+
227
+ return (
228
+ <SearchableSelectDialog
229
+ title="Delete Flow"
230
+ options={flows.map((f) => ({ value: f.name, label: f.name, description: f.description }))}
231
+ placeholder="Search flows..."
232
+ emptyMessage="No flows available"
233
+ onSelect={(value) => setDeleteTarget(value)}
234
+ onCancel={onClose}
235
+ />
236
+ );
237
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Plugin-internal per-session flow state.
3
+ *
4
+ * Replaces what `packages/client/src/lib/event-reducer.ts` does today
5
+ * for `flowState` and `flowStates` — but lives inside flows-plugin so
6
+ * 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` over the events, producing
13
+ * `{ flowState, flowStates }`.
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
+ FlowState,
30
+ DashboardEvent,
31
+ } from "@blackbelt-technology/pi-dashboard-shared/types.js";
32
+ import { useSessionEvents } from "@blackbelt-technology/dashboard-plugin-runtime";
33
+ import { isFlowEvent, reduceFlowEvent } from "../reducer.js";
34
+
35
+ /** Shape exposed to flows-plugin components for a single session. */
36
+ export interface FlowsSessionState {
37
+ /** The currently-displayed flow's state, or null when no flow is active. */
38
+ flowState: FlowState | null;
39
+ /**
40
+ * All flows seen for this session keyed by `flow.flowName`. Used by
41
+ * components that need to render multiple concurrent flows
42
+ * (FlowDashboard's multi-flow tab bar).
43
+ */
44
+ flowStates: ReadonlyMap<string, FlowState>;
45
+ }
46
+
47
+ const EMPTY_STATE: FlowsSessionState = Object.freeze({
48
+ flowState: null,
49
+ flowStates: new Map() as ReadonlyMap<string, FlowState>,
50
+ });
51
+
52
+ /**
53
+ * Reduce a session's event stream into flow state. Pure
54
+ * function — no React, no side effects. Exported for tests and for
55
+ * future server-side rendering. The reduction matches the shell's
56
+ * current behavior in `event-reducer.ts` exactly:
57
+ *
58
+ * - flow events → reduceFlowEvent updates flowState; flowStates is
59
+ * resynced after each flow event so the active flow is also stored
60
+ * under its name. `flow_summary_dismissed` clears flowStates.
61
+ *
62
+ * Iterating the full event stream on every render is fine: the event
63
+ * stream's reference is stable (returned from `useSessionEvents`) and
64
+ * the calling hook is wrapped in `useMemo` keyed on that reference,
65
+ * so the reduction only re-runs when a new event arrives.
66
+ */
67
+ export function reduceFlowsSessionState(
68
+ events: readonly DashboardEvent[],
69
+ ): FlowsSessionState {
70
+ let flowState: FlowState | null = null;
71
+ let flowStates: Map<string, FlowState> = new Map();
72
+ let flowStatesMutated = false;
73
+
74
+ // Diagnostic counter for C1 — see fix-flows-plugin-polish. Gated to dev.
75
+ let flowEventCount = 0;
76
+
77
+ for (const event of events) {
78
+ if (isFlowEvent(event.eventType)) {
79
+ flowEventCount++;
80
+ flowState = reduceFlowEvent(flowState, event);
81
+ if (flowState) {
82
+ if (!flowStatesMutated) {
83
+ flowStates = new Map(flowStates);
84
+ flowStatesMutated = true;
85
+ }
86
+ flowStates.set(flowState.flowName, flowState);
87
+ } else if (event.eventType === "flow_summary_dismissed") {
88
+ if (flowStates.size > 0) {
89
+ flowStates = new Map();
90
+ flowStatesMutated = true;
91
+ }
92
+ }
93
+ }
94
+ }
95
+
96
+ if (typeof import.meta !== "undefined" && (import.meta as { env?: { DEV?: boolean } }).env?.DEV) {
97
+ if (flowEventCount > 0) {
98
+ // eslint-disable-next-line no-console
99
+ console.debug(
100
+ "[flows] reduceFlowsSessionState",
101
+ {
102
+ totalEvents: events.length,
103
+ flowEvents: flowEventCount,
104
+ resolvedFlowName: flowState?.flowName,
105
+ resolvedFlowStatus: flowState?.status,
106
+ flowsCount: flowStates.size,
107
+ },
108
+ );
109
+ }
110
+ }
111
+
112
+ if (flowState === null && flowStates.size === 0) {
113
+ return EMPTY_STATE;
114
+ }
115
+
116
+ return {
117
+ flowState,
118
+ flowStates,
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Hook — derive flow state for a session from its event
124
+ * stream. Result is `useMemo`-stable across renders that don't bring
125
+ * a new event for this session.
126
+ *
127
+ * Plugin components SHALL call this with their `session.id` (from the
128
+ * standard slot prop contract) and self-gate on null returns:
129
+ *
130
+ * ```tsx
131
+ * const { flowState } = useFlowsSessionState(session.id);
132
+ * if (!flowState) return null;
133
+ * ```
134
+ *
135
+ * Returns the frozen `EMPTY_STATE` constant when no flow activity has
136
+ * happened for this session, so the same reference is shared across
137
+ * many same-state renders.
138
+ */
139
+ export function useFlowsSessionState(sessionId: string): FlowsSessionState {
140
+ const events = useSessionEvents(sessionId);
141
+ return useMemo(() => reduceFlowsSessionState(events), [events]);
142
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Settings-section for the flows plugin: a global edit-mode default.
3
+ *
4
+ * Edit-mode on → the main session sees the `edit-flow` skill and the
5
+ * `flow_agents` / `flow_write` authoring tools. The global default here is
6
+ * reconciled down to each session (via `flow:set-edit-mode`) when that
7
+ * session's flows plugin becomes available — see SessionFlowActionsClaim.
8
+ *
9
+ * Uses the unified buffered-draft save contract (commits via the host Settings
10
+ * panel's Save). See change: rework-flows-plugin-for-new-pi-flows.
11
+ */
12
+
13
+ import { useSettingsDraftSource, useT } from "@blackbelt-technology/dashboard-plugin-runtime";
14
+ import { usePluginConfig, usePluginSend } from "@blackbelt-technology/dashboard-plugin-runtime/context";
15
+ import type React from "react";
16
+ import { useCallback, useRef, useState } from "react";
17
+
18
+ export interface FlowsPluginConfig {
19
+ /** Global default for pi-flows `flows.editFlow`. Default off. */
20
+ editFlow?: boolean;
21
+ }
22
+
23
+ export function FlowsSettings(): React.ReactElement {
24
+ const t = useT();
25
+ const config = usePluginConfig<FlowsPluginConfig>();
26
+ const send = usePluginSend();
27
+
28
+ const [editFlow, setEditFlow] = useState<boolean>(config.editFlow ?? false);
29
+ const base = config.editFlow ?? false;
30
+ const isDirty = editFlow !== base;
31
+
32
+ const valuesRef = useRef(editFlow);
33
+ valuesRef.current = editFlow;
34
+ const baseRef = useRef(base);
35
+ baseRef.current = base;
36
+
37
+ const commit = useCallback(async () => {
38
+ await send({ type: "plugin_config_write", id: "flows", config: { editFlow: valuesRef.current } });
39
+ }, [send]);
40
+ const reset = useCallback(() => setEditFlow(baseRef.current), []);
41
+ useSettingsDraftSource({ id: "plugin:flows", page: "plugins", isDirty, commit, reset });
42
+
43
+ return (
44
+ <section className="border border-[var(--border-primary)] rounded-lg p-4">
45
+ <h3 className="text-sm font-semibold mb-0.5">{t("flowsHeading", undefined, "Flows")}</h3>
46
+ <p className="text-xs text-[var(--text-tertiary)] mb-3">
47
+ Multi-agent workflow orchestration. Applies globally; sessions inherit this default.
48
+ </p>
49
+ <label className="flex gap-2.5 items-start text-[13px] cursor-pointer">
50
+ <input
51
+ type="checkbox"
52
+ checked={editFlow}
53
+ onChange={(e) => setEditFlow(e.target.checked)}
54
+ className="mt-0.5"
55
+ data-testid="flows-edit-mode-toggle"
56
+ />
57
+ <span>
58
+ <span className="font-medium">{t("editModeLabel", undefined, "Edit mode")}</span>
59
+ {" — allow the main session to author flows & agents"}
60
+ <span className="block text-[11px] text-[var(--text-muted)] mt-0.5">
61
+ Activates <code>flow_agents</code> / <code>flow_write</code> and makes the
62
+ edit-flow skill model-visible. Off by default.
63
+ </span>
64
+ </span>
65
+ </label>
66
+ </section>
67
+ );
68
+ }
@@ -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
+ }