@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,10 @@
1
+ # DOX — packages/flows-plugin/src/server
2
+
3
+ Files in this directory. One row per source file.
4
+
5
+ | File | Purpose |
6
+ |------|---------|
7
+ | `automation-actions.ts` | Flows→automation action registration. `discoverFlows(cwd)` scans `<cwd>/.pi/flows/flows/<ns>/<name>/flow.yaml` → `<ns>:<name>`. `registerFlowAutomationActions` registers flows.run/resume/cancel, available=hasFlows(cwd), flows.run payload {flow enum, task multiline}, buildPrompt `/<ns>:<name> <task>`. `wireFlowAutomationActions(consume,...)` consumes `automation.action-registry` service, no-op when absent. See change: register-plugin-automation-events. `flows.run` emits `flow:run` event `{flowName,task}` via buildEvent (was slash-command prompt); `flows.resume`+`flows.cancel` removed. See change: automation-emit-configured-event. Rewritten as pure publisher: `flowsActionContributions()` + `provideFlowsActions(provide)` publish under `automation.action.flows`. Drops consume, registry, ACTION_REGISTRY_SERVICE. See change: decouple-automation-action-registry. `flows.run` availability + `flow` enum options now derive from an injected `FlowsForCwd` resolver (live per-session flows list), NOT a `.pi/flows/flows` scan; static `discoverFlows`/`hasFlows` + fs/path imports removed. `flowsActionContributions(flowsForCwd)` + `provideFlowsActions(provide,log,flowsForCwd)`. Reflects package-bundled + event-registered flows; empty (disabled) when no running session for the cwd. See change: fix-automation-flow-detection. |
8
+ | `index.ts` | registerPlugin calls wireFlowAutomationActions(ctx.consume,...). See change: register-plugin-automation-events. registerPlugin calls `provideFlowsActions(ctx.provide,…)` instead of `wireFlowAutomationActions(ctx.consume,…)`. See change: decouple-automation-action-registry. Exports `makeFlowsForCwd(sessionManager, store)` → `(cwd)=>string[]`: maps cwd to running session(s) via `sessionManager.listActive()` (exact cwd match), unions `stateStore.getState(id).flows[].name` (`<ns>:<name>`), sorted-unique; injected into `provideFlowsActions`. See change: fix-automation-flow-detection. `plugin_action` handler is now production (replaced the v1 stub): `flow.run` emits `flow:run` `{flowName,task?,inputs?}` into the target session via `ctx.emitEventToSession` (same event `flow_management run` + the automation `flows.run` action dispatch); `flow.new` launches `/skill:manage-flows` via `sendToSession`; missing sessionId / flow name are guarded no-ops. See change: fix-plugin-action-fanout-and-handlers. |
9
+ | `render-actions.ts` | Pure render fn for `SessionFlowActions` intent. Exports `RenderActionsInput`, `RenderedActionItem`, `renderSessionFlowActions`. Translates (flows, commands) into `ui:action-list` IntentNode; each item carries `dataAction` descriptor (`flow.run`/`flow.new`). Returns null when no flows and no `/flows:new`. |
10
+ | `state-store.ts` | Per-session server-side flow state holder. Exports `FlowsSessionServerState`, `stateStore` singleton. Holds `flows`, `commands`, `flowState`. Methods: `ensure`, `getState`, `applyEvent` (runs `reduceFlowEvent`), `setFlows`, `setCommands`, `clearSession`, `__resetForTests`. |
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Flows → automation action contribution (publish/collect).
3
+ *
4
+ * Flows PUBLISHES an immutable action contribution under
5
+ * `automation.action.flows` via `ctx.provide`. It does NOT consume an
6
+ * automation-owned registry, import the automation package, or depend on load
7
+ * order — the automation plugin collects published contributions lazily. If
8
+ * flows is disabled, it publishes nothing and `flows.run` never appears.
9
+ *
10
+ * The contribution is typed structurally so flows needs no compile dependency
11
+ * on automation. See change: decouple-automation-action-registry.
12
+ *
13
+ * Flow availability + the `flow` enum options come from the LIVE per-session
14
+ * flows list the server already holds (`stateStore`, populated by the
15
+ * bridge-forwarded `flows_list`), resolved by mapping a cwd to its running
16
+ * session(s). NOT a static `.pi/flows/flows/` scan — so package-bundled and
17
+ * event-registered flows (which pi-flows discovers at runtime) are reflected.
18
+ * See change: fix-automation-flow-detection.
19
+ */
20
+
21
+ /** Publish key automation collects under (`automation.action.<source>`). */
22
+ export const ACTION_CONTRIBUTION_KEY = "automation.action.flows";
23
+
24
+ /** Structural mirror of one automation payload-schema field. */
25
+ interface ActionFieldSpecLike {
26
+ key: string;
27
+ label: string;
28
+ type: "string" | "multiline" | "text" | "enum";
29
+ help?: string;
30
+ options?: (cwd: string) => string[];
31
+ }
32
+
33
+ /** Structural mirror of an automation action contribution. */
34
+ export interface ActionContributionLike {
35
+ id: string;
36
+ source: string;
37
+ label: string;
38
+ description?: string;
39
+ available?: (cwd: string) => boolean;
40
+ unavailableReason?: string;
41
+ payloadSchema?: ActionFieldSpecLike[];
42
+ /**
43
+ * Event-dispatch: emit a configured event into the run session. May also
44
+ * declare `completion` — how a run of this action FINISHES — so the
45
+ * automation engine can finalize an event-dispatched run (which emits no
46
+ * `agent_end`) without knowing anything action-specific.
47
+ * See change: finalize-event-dispatched-automation-runs.
48
+ */
49
+ buildEvent?: (args: { payload: Record<string, unknown>; automation: unknown }) =>
50
+ | {
51
+ eventType: string;
52
+ data?: Record<string, unknown>;
53
+ completion?: {
54
+ eventType: string;
55
+ summarize?: (data: Record<string, unknown> | undefined) => string;
56
+ };
57
+ }
58
+ | null;
59
+ }
60
+
61
+ /**
62
+ * Resolve the flows available in a cwd: `<ns>:<name>` ids from the live
63
+ * per-session flows list. Injected by the server entry (see index.ts) so this
64
+ * module stays free of server/session dependencies.
65
+ */
66
+ export type FlowsForCwd = (cwd: string) => string[];
67
+
68
+ /**
69
+ * A flow id is `<ns>:<name>`. It is placed into the
70
+ * `flow:run` event payload, so a malformed value is rejected (emit nothing).
71
+ */
72
+ const FLOW_ID_RE = /^[\w.-]+:[\w.-]+$/;
73
+
74
+ /** A plain-object `payload.inputs` with at least one key, else undefined.
75
+ * Values are forwarded as-is (already per-fire resolved, types preserved). */
76
+ function normalizeInputs(raw: unknown): Record<string, unknown> | undefined {
77
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
78
+ const obj = raw as Record<string, unknown>;
79
+ return Object.keys(obj).length > 0 ? obj : undefined;
80
+ }
81
+
82
+ /**
83
+ * Derive an automation run-result line from a pi-flows `flow_complete` payload
84
+ * (the forwarded `FlowResult`: `status`, `flowName`, `lastResult.result.summary`).
85
+ * An event-dispatched flows.run has no assistant turn to capture, so this line
86
+ * IS the run result. Owns the FlowResult shape so the automation plugin does
87
+ * not. See change: finalize-event-dispatched-automation-runs.
88
+ */
89
+ export function summarizeFlowResult(data: Record<string, unknown> | undefined): string {
90
+ const d = data as
91
+ | { status?: string; flowName?: string; lastResult?: { result?: { summary?: string } } }
92
+ | undefined;
93
+ const summary = d?.lastResult?.result?.summary;
94
+ return `flow ${d?.flowName ?? ""} ${d?.status ?? "finished"}${summary ? `: ${summary}` : ""}`
95
+ .replace(/\s+/g, " ")
96
+ .trim();
97
+ }
98
+
99
+ /**
100
+ * Build the flows action contribution(s): flows.run only. Availability and the
101
+ * `flow` enum options derive from the injected `flowsForCwd` resolver (live
102
+ * per-session flows list). See change: fix-automation-flow-detection.
103
+ */
104
+ export function flowsActionContributions(flowsForCwd: FlowsForCwd): ActionContributionLike[] {
105
+ const hasFlows = (cwd: string) => flowsForCwd(cwd).length > 0;
106
+ return [
107
+ {
108
+ id: "flows.run",
109
+ source: "flows",
110
+ label: "Run a flow",
111
+ description: "Run a flow with a task.",
112
+ available: hasFlows,
113
+ unavailableReason: "no flows in this folder (no running session, or the session reports no flows)",
114
+ payloadSchema: [
115
+ { key: "flow", label: "Flow", type: "enum", options: flowsForCwd, help: "Flows reported by the running session for this folder" },
116
+ { key: "task", label: "Task", type: "multiline", help: "Passed as the flow's initial task." },
117
+ ],
118
+ // Emit flow:run into the run session (the event pi-flows listens for),
119
+ // not a slash-command prompt. A flows.run run produces NO agent turn in
120
+ // the host session (pi-flows consumes flow:run headlessly), so it emits
121
+ // no `agent_end`. Declare `completion` so the automation engine finalizes
122
+ // it on the forwarded `flow_complete` event instead (the extension's
123
+ // FLOW_EVENT_MAP forwards pi-flows' `flow:complete` → `flow_complete`).
124
+ // All flows knowledge — the event name and the FlowResult shape — stays
125
+ // here; the automation plugin stays generic.
126
+ //
127
+ // `payload` is already per-fire interpolated by the engine (the
128
+ // `${{trigger}}` token in `payload.inputs` is resolved to the fired
129
+ // value, type preserved). We forward `payload.inputs` as `data.inputs`,
130
+ // which pi-flows consumes as `flowInput` → `${{flow.input.<name>}}`.
131
+ // `task` stays optional and may coexist with `inputs`.
132
+ // See change: finalize-event-dispatched-automation-runs, wire-flow-inputs-in-automation.
133
+ buildEvent: ({ payload }) => {
134
+ const flow = String(payload.flow ?? "").trim();
135
+ if (!FLOW_ID_RE.test(flow)) return null;
136
+ const task = String(payload.task ?? "").trim();
137
+ const inputs = normalizeInputs(payload.inputs);
138
+ const data: Record<string, unknown> = { flowName: flow };
139
+ if (task) data.task = task;
140
+ if (inputs) data.inputs = inputs;
141
+ return {
142
+ eventType: "flow:run",
143
+ data,
144
+ completion: { eventType: "flow_complete", summarize: summarizeFlowResult },
145
+ };
146
+ },
147
+ },
148
+ ];
149
+ }
150
+
151
+ /**
152
+ * Publish the flows action contribution for automation to collect. Pure
153
+ * publisher: consumes nothing, references no automation code, order-agnostic.
154
+ */
155
+ export function provideFlowsActions(
156
+ provide: (name: string, value: unknown) => void,
157
+ log: (m: string) => void,
158
+ flowsForCwd: FlowsForCwd,
159
+ ): void {
160
+ provide(ACTION_CONTRIBUTION_KEY, flowsActionContributions(flowsForCwd));
161
+ log("[flows] published automation action: flows.run");
162
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Read-only reader for a flow's declared `inputs:` schema.
3
+ *
4
+ * Parses `<cwd>/.pi/flows/flows/<ns>/<name>/flow.yaml` and returns the
5
+ * declared flow-level inputs (name + type + required). This is the source of
6
+ * truth the automation input-wiring UI renders from. It NEVER writes a flow
7
+ * file — the automation side only reads the flow's input contract.
8
+ *
9
+ * Mirrors pi-flows' `FlowInputDecl` shape (`flow-typed-io-and-run-state`)
10
+ * without a compile dependency on the pi-flows package.
11
+ *
12
+ * See change: wire-flow-inputs-in-automation.
13
+ */
14
+ import fs from "node:fs";
15
+ import path from "node:path";
16
+ import { parse as parseYaml } from "yaml";
17
+
18
+ export type FlowInputType = "string" | "number" | "boolean" | "object" | "array";
19
+ const VALID_TYPES: readonly FlowInputType[] = ["string", "number", "boolean", "object", "array"];
20
+
21
+ export interface FlowInputField {
22
+ name: string;
23
+ type: FlowInputType;
24
+ required: boolean;
25
+ }
26
+
27
+ /** Resolve a `<ns>:<name>` flow id to its `flow.yaml` path under `cwd`. */
28
+ export function flowYamlPath(cwd: string, flowId: string): string | null {
29
+ const m = /^([\w.-]+):([\w.-]+)$/.exec(flowId);
30
+ if (!m) return null;
31
+ return path.join(cwd, ".pi", "flows", "flows", m[1], m[2], "flow.yaml");
32
+ }
33
+
34
+ /**
35
+ * Read a flow's declared inputs (read-only). Returns `[]` for a missing file,
36
+ * unparseable yaml, or a flow with no `inputs:`. Invalid input entries are
37
+ * skipped rather than throwing (isolate bad rows, keep good ones).
38
+ */
39
+ export function readFlowInputs(cwd: string, flowId: string): FlowInputField[] {
40
+ const p = flowYamlPath(cwd, flowId);
41
+ if (!p) return [];
42
+ let doc: unknown;
43
+ try {
44
+ doc = parseYaml(fs.readFileSync(p, "utf-8"));
45
+ } catch {
46
+ return [];
47
+ }
48
+ const raw = (doc as Record<string, unknown> | null)?.inputs;
49
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return [];
50
+ const out: FlowInputField[] = [];
51
+ for (const [name, decl] of Object.entries(raw as Record<string, unknown>)) {
52
+ const d = decl as Record<string, unknown> | null;
53
+ const type = d?.type;
54
+ if (typeof type !== "string" || !(VALID_TYPES as readonly string[]).includes(type)) continue;
55
+ out.push({ name, type: type as FlowInputType, required: d?.required === true });
56
+ }
57
+ return out;
58
+ }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * flows-plugin SERVER entry.
3
+ *
4
+ * Owns canonical per-session flow state, emits intent broadcasts to all
5
+ * connected clients via the bridge, handles plugin_action messages from
6
+ * any client.
7
+ *
8
+ * See change: adopt-server-driven-intent-rendering.
9
+ */
10
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
11
+ import { provideFlowsActions } from "./automation-actions.js";
12
+ import { readFlowInputs } from "./flow-inputs.js";
13
+ import { renderSessionFlowActions } from "./render-actions.js";
14
+ import { stateStore } from "./state-store.js";
15
+
16
+ const PLUGIN_ID = "flows";
17
+
18
+ /**
19
+ * Resolve the flows available in a folder from the LIVE per-session flows list
20
+ * (`stateStore`, populated by the bridge-forwarded `flows_list`), by mapping
21
+ * the cwd to its running session(s) and unioning their reported `<ns>:<name>`
22
+ * ids. Reflects package-bundled and event-registered flows that a static
23
+ * `.pi/flows/flows` scan would miss; empty when no running session matches the
24
+ * cwd. See change: fix-automation-flow-detection.
25
+ */
26
+ export function makeFlowsForCwd(
27
+ sessionManager: { listActive(): unknown[] },
28
+ store: { getState(id: string): { flows?: Array<{ name?: unknown }> } | undefined },
29
+ ): (cwd: string) => string[] {
30
+ return (cwd: string): string[] => {
31
+ const sessions = sessionManager.listActive() as Array<{ id?: unknown; cwd?: unknown }>;
32
+ const ids = new Set<string>();
33
+ for (const s of sessions) {
34
+ if (!s || typeof s.id !== "string" || s.cwd !== cwd) continue;
35
+ const flows = store.getState(s.id)?.flows;
36
+ if (!flows) continue;
37
+ for (const f of flows) {
38
+ if (f && typeof f.name === "string") ids.add(f.name);
39
+ }
40
+ }
41
+ return [...ids].sort();
42
+ };
43
+ }
44
+
45
+ /**
46
+ * Plugin entrypoint called by the dashboard plugin loader at boot.
47
+ */
48
+ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
49
+ const { logger, broadcastToSubscribers, registerBrowserHandler, emitEventToSession, sendToSession } = ctx;
50
+ logger.info("flows-plugin server entry activated (server-driven intents)");
51
+
52
+ // Publish the flows automation action (flows.run) for the automation plugin
53
+ // to collect. Pure publisher: no consume, no automation dependency, no load
54
+ // order requirement. See change: decouple-automation-action-registry.
55
+ // Availability + enum options resolve from the LIVE per-session flows list.
56
+ // See change: fix-automation-flow-detection.
57
+ const flowsForCwd = makeFlowsForCwd(ctx.sessionManager, stateStore);
58
+ provideFlowsActions((name, value) => ctx.provide(name, value), (m) => logger.info(m), flowsForCwd);
59
+
60
+ // Read-only endpoint: a flow's declared `inputs:` schema, for the automation
61
+ // input-wiring UI. Never writes a flow file. See change:
62
+ // wire-flow-inputs-in-automation.
63
+ ctx.fastify.get("/api/plugins/flows/flow-inputs", async (req) => {
64
+ const q = (req.query ?? {}) as Record<string, unknown>;
65
+ const cwd = typeof q.cwd === "string" ? q.cwd : process.cwd();
66
+ const flow = typeof q.flow === "string" ? q.flow : "";
67
+ return { inputs: flow ? readFlowInputs(cwd, flow) : [] };
68
+ });
69
+
70
+ /**
71
+ * Broadcast the current intent tree for one session's slot.
72
+ * Called from action handlers AND in response to event-store changes
73
+ * (wired below).
74
+ */
75
+ function publishSessionFlowActions(sessionId: string): void {
76
+ const state = stateStore.getState(sessionId);
77
+ const intent = renderSessionFlowActions(state ?? { flows: [], commands: [] });
78
+ broadcastToSubscribers({
79
+ type: "plugin_intents",
80
+ pluginId: PLUGIN_ID,
81
+ sessionId,
82
+ slot: "session-card-action-bar",
83
+ intent,
84
+ });
85
+ }
86
+
87
+ // Action handler: dispatched from any connected client (or a bus script).
88
+ // The gateway fans out plugin_action by pluginId, so this only fires for
89
+ // pluginId==="flows"; the guard below is defense-in-depth.
90
+ // See change: fix-plugin-action-fanout-and-handlers.
91
+ registerBrowserHandler("plugin_action", (msg) => {
92
+ const m = msg as {
93
+ pluginId?: string;
94
+ sessionId?: string | null;
95
+ action?: string;
96
+ payload?: Record<string, unknown>;
97
+ };
98
+ if (m.pluginId !== PLUGIN_ID) return;
99
+ if (!m.sessionId) {
100
+ logger.warn(`flows ${m.action ?? "(no action)"}: missing sessionId`);
101
+ return;
102
+ }
103
+ const payload = m.payload ?? {};
104
+
105
+ switch (m.action) {
106
+ case "flow.run": {
107
+ // Accept `flow` (intent path) or `flowName`; run in the target session
108
+ // by emitting the `flow:run` event pi-flows consumes headlessly — the
109
+ // same event the `flow_management run` client path and the automation
110
+ // `flows.run` action dispatch.
111
+ const flowName = String(payload.flow ?? payload.flowName ?? "").trim();
112
+ if (!flowName) {
113
+ logger.warn(`flow.run from session=${m.sessionId}: missing flow name`);
114
+ return;
115
+ }
116
+ const task = typeof payload.task === "string" ? payload.task.trim() : "";
117
+ // Reject a non-object / array `inputs` (typeof [] === "object") — pi-flows
118
+ // consumes it as a keyed record, so an array would be malformed.
119
+ if (
120
+ payload.inputs !== undefined &&
121
+ (payload.inputs === null ||
122
+ typeof payload.inputs !== "object" ||
123
+ Array.isArray(payload.inputs))
124
+ ) {
125
+ logger.warn(`flow.run session=${m.sessionId}: invalid inputs (expected object)`);
126
+ return;
127
+ }
128
+ const inputs = payload.inputs as Record<string, unknown> | undefined;
129
+ const data: Record<string, unknown> = { flowName };
130
+ if (task) data.task = task;
131
+ if (inputs) data.inputs = inputs;
132
+ const delivered = emitEventToSession(m.sessionId, "flow:run", data);
133
+ logger.info(`flow.run "${flowName}" session=${m.sessionId} delivered=${delivered}`);
134
+ break;
135
+ }
136
+ case "flow.new": {
137
+ // No dedicated server core — authoring is the manage-flows skill,
138
+ // launched via a slash prompt into the session (mirrors the client's
139
+ // New/Edit path). An optional `instruction` is appended.
140
+ const instruction =
141
+ typeof payload.instruction === "string" ? payload.instruction.trim() : "";
142
+ const command = instruction ? `/skill:manage-flows ${instruction}` : "/skill:manage-flows";
143
+ const delivered = sendToSession(m.sessionId, command);
144
+ logger.info(`flow.new session=${m.sessionId} delivered=${delivered}`);
145
+ break;
146
+ }
147
+ default:
148
+ logger.warn(`unknown flows action: ${m.action}`);
149
+ }
150
+ });
151
+
152
+ // ServerPluginContext has no native event-stream subscription API yet —
153
+ // PluginEventStore is poll-based, not push. Live wiring (subscribe to
154
+ // every pi event, apply to stateStore, publishSessionFlowActions on
155
+ // change) is OUT OF SCOPE for this change and tracked as a follow-up:
156
+ // see openspec/changes/adopt-server-driven-intent-rendering/tasks.md
157
+ // section 29 FOLLOW-UP for the design needed to expose `subscribeAll`
158
+ // or `onEvent(handler)` on ServerPluginContext.
159
+ //
160
+ // For now: the action handler is wired (browser → server round-trip
161
+ // works), the state-store + render function are pure-tested, and intent
162
+ // broadcasts CAN be emitted via `publishSessionFlowActions(sessionId)`
163
+ // when something triggers a state change. End-to-end coherence will
164
+ // become observable once the event-subscription hookup lands.
165
+ logger.info("flows-plugin: server entry active. Event-stream subscription deferred to follow-up.");
166
+
167
+ // Suppress unused-warning until wired.
168
+ void publishSessionFlowActions;
169
+ }
170
+
171
+ export default registerPlugin;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Pure render function: SessionFlowActions intent.
3
+ *
4
+ * Translates (flows, commands) into an intent tree for the
5
+ * session-card-action-bar slot. No React, no DOM — just JSON.
6
+ *
7
+ * The intent uses a `ui:action-list` whose items each emit their own
8
+ * action descriptor in the intent format. Items are NOT IntentNodes
9
+ * themselves — they're plain data; the ActionList primitive turns
10
+ * `onClick: ActionDescriptor` data into a real function via the
11
+ * `IntentRenderer.actions` wiring.
12
+ *
13
+ * For per-item action wiring without IntentNode wrapping, we emit a
14
+ * `data-action` field on the item, and the registered ActionList
15
+ * primitive translates it to onClick. Alternatively, each button could
16
+ * be its own IntentNode — but `ui:action-list` is meant as a high-
17
+ * affinity primitive that takes a flat data array.
18
+ *
19
+ * See change: adopt-server-driven-intent-rendering.
20
+ */
21
+ import type { IntentNode } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/intent-types.js";
22
+ import type { FlowInfo, CommandInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
23
+
24
+ export interface RenderActionsInput {
25
+ flows: FlowInfo[];
26
+ commands: CommandInfo[];
27
+ }
28
+
29
+ /**
30
+ * Action item shape as emitted by the plugin. The dashboard's ActionList
31
+ * primitive component reads `dataAction` and calls a registered dispatcher
32
+ * (set up by the shell via plugin-action-bridge) when clicked. This keeps
33
+ * the data wire pure JSON.
34
+ */
35
+ export interface RenderedActionItem {
36
+ label: string;
37
+ tooltip?: string;
38
+ icon?: string;
39
+ /** Server-side action descriptor. The shell wires this to a click. */
40
+ dataAction?: {
41
+ pluginId: string;
42
+ action: string;
43
+ payload?: Record<string, unknown>;
44
+ };
45
+ disabled?: boolean;
46
+ }
47
+
48
+ /**
49
+ * Build the SessionFlowActions intent.
50
+ *
51
+ * Returns null when there are no flows AND no `/flows:new` command — the
52
+ * slot stays empty in that case, matching legacy behaviour.
53
+ */
54
+ export function renderSessionFlowActions(input: RenderActionsInput): IntentNode | null {
55
+ const { flows, commands } = input;
56
+ const hasNew = commands.some((c) => c.name === "flows:new");
57
+
58
+ if (flows.length === 0 && !hasNew) return null;
59
+
60
+ const actions: RenderedActionItem[] = [];
61
+
62
+ for (const flow of flows) {
63
+ actions.push({
64
+ label: flow.name,
65
+ tooltip: flow.description,
66
+ dataAction: {
67
+ pluginId: "flows",
68
+ action: "flow.run",
69
+ payload: { flow: flow.name },
70
+ },
71
+ });
72
+ }
73
+
74
+ if (hasNew) {
75
+ actions.push({
76
+ label: "+ New Flow",
77
+ dataAction: {
78
+ pluginId: "flows",
79
+ action: "flow.new",
80
+ },
81
+ });
82
+ }
83
+
84
+ return {
85
+ primitive: "ui:action-list",
86
+ props: { actions } as unknown as Record<string, unknown>,
87
+ };
88
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Per-session flow state holder on the server.
3
+ *
4
+ * Holds Map<sessionId, FlowsSessionServerState>. Subscribes (TODO 17.3)
5
+ * to event broadcasts and applies the pure reducer from flow-reducer.ts.
6
+ *
7
+ * See change: adopt-server-driven-intent-rendering.
8
+ */
9
+ import type { FlowState, FlowInfo, CommandInfo, DashboardEvent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
10
+ import { isFlowEvent, reduceFlowEvent } from "../flow-reducer.js";
11
+
12
+ export interface FlowsSessionServerState {
13
+ /** Available flows for this session (from pi-flows extension). */
14
+ flows: FlowInfo[];
15
+ /** Available commands for this session. */
16
+ commands: CommandInfo[];
17
+ /** Current flow state derived from event stream. Null when no flow active. */
18
+ flowState?: FlowState | null;
19
+ }
20
+
21
+ class StateStore {
22
+ private map = new Map<string, FlowsSessionServerState>();
23
+
24
+ /** Initialize state for a session if it doesn't exist. */
25
+ ensure(sessionId: string): FlowsSessionServerState {
26
+ let s = this.map.get(sessionId);
27
+ if (!s) {
28
+ s = { flows: [], commands: [] };
29
+ this.map.set(sessionId, s);
30
+ }
31
+ return s;
32
+ }
33
+
34
+ getState(sessionId: string): FlowsSessionServerState | undefined {
35
+ return this.map.get(sessionId);
36
+ }
37
+
38
+ /** Apply an event from pi (flow_*, etc.) to the session's state. */
39
+ applyEvent(sessionId: string, event: DashboardEvent): boolean {
40
+ const s = this.ensure(sessionId);
41
+ let changed = false;
42
+ if (isFlowEvent(event.eventType)) {
43
+ const next = reduceFlowEvent(s.flowState ?? null, event);
44
+ if (next !== s.flowState) {
45
+ s.flowState = next;
46
+ changed = true;
47
+ }
48
+ }
49
+ return changed;
50
+ }
51
+
52
+ /** Update available flows list (from pi flows_list message). */
53
+ setFlows(sessionId: string, flows: FlowInfo[]): void {
54
+ const s = this.ensure(sessionId);
55
+ s.flows = flows;
56
+ }
57
+
58
+ /** Update available commands list. */
59
+ setCommands(sessionId: string, commands: CommandInfo[]): void {
60
+ const s = this.ensure(sessionId);
61
+ s.commands = commands;
62
+ }
63
+
64
+ clearSession(sessionId: string): void {
65
+ this.map.delete(sessionId);
66
+ }
67
+
68
+ /** Test-only: reset all state. */
69
+ __resetForTests(): void {
70
+ this.map.clear();
71
+ }
72
+ }
73
+
74
+ export const stateStore = new StateStore();
@@ -1,81 +0,0 @@
1
- import { describe, it, expect, vi, afterEach } from "vitest";
2
- import { render, screen, fireEvent, cleanup } from "@testing-library/react";
3
- import React from "react";
4
- import { ArchitectInputPrompt } from "../client/FlowArchitect.js";
5
-
6
- afterEach(cleanup);
7
-
8
- const basePrompt = {
9
- id: "prompt-1",
10
- type: "input" as const,
11
- question: "What should be changed?",
12
- };
13
-
14
- describe("ArchitectInputPrompt", () => {
15
- it("renders question and input field", () => {
16
- render(
17
- <ArchitectInputPrompt prompt={basePrompt} onRespond={vi.fn()} />,
18
- );
19
-
20
- expect(screen.getByText("What should be changed?")).toBeTruthy();
21
- expect(screen.getByRole("textbox")).toBeTruthy();
22
- });
23
-
24
- it("submits empty string via Enter key", () => {
25
- const onRespond = vi.fn();
26
- render(
27
- <ArchitectInputPrompt prompt={basePrompt} onRespond={onRespond} />,
28
- );
29
-
30
- fireEvent.keyDown(screen.getByRole("textbox"), { key: "Enter" });
31
-
32
- expect(onRespond).toHaveBeenCalledWith("");
33
- });
34
-
35
- it("submits empty string via button click", () => {
36
- const onRespond = vi.fn();
37
- render(
38
- <ArchitectInputPrompt prompt={basePrompt} onRespond={onRespond} />,
39
- );
40
-
41
- fireEvent.click(screen.getByText("Submit"));
42
-
43
- expect(onRespond).toHaveBeenCalledWith("");
44
- });
45
-
46
- it("submits entered text via Enter key", () => {
47
- const onRespond = vi.fn();
48
- render(
49
- <ArchitectInputPrompt prompt={basePrompt} onRespond={onRespond} />,
50
- );
51
-
52
- fireEvent.change(screen.getByRole("textbox"), { target: { value: "Fix the bug" } });
53
- fireEvent.keyDown(screen.getByRole("textbox"), { key: "Enter" });
54
-
55
- expect(onRespond).toHaveBeenCalledWith("Fix the bug");
56
- });
57
-
58
- it("trims whitespace from submitted text", () => {
59
- const onRespond = vi.fn();
60
- render(
61
- <ArchitectInputPrompt prompt={basePrompt} onRespond={onRespond} />,
62
- );
63
-
64
- fireEvent.change(screen.getByRole("textbox"), { target: { value: " hello " } });
65
- fireEvent.click(screen.getByText("Submit"));
66
-
67
- expect(onRespond).toHaveBeenCalledWith("hello");
68
- });
69
-
70
- it("uses defaultValue from prompt", () => {
71
- const onRespond = vi.fn();
72
- render(
73
- <ArchitectInputPrompt
74
- prompt={{ ...basePrompt, defaultValue: "prefilled" }}
75
- onRespond={onRespond}
76
- />,
77
- );
78
-
79
- expect(screen.getByRole("textbox")).toHaveProperty("value", "prefilled");
80
- });
81
- });