@blackbelt-technology/pi-dashboard-flows-plugin 0.11.0 → 0.12.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 (71) hide show
  1. package/README.md +5 -1
  2. package/package.json +23 -4
  3. package/src/bridge/flow-catalog-publisher.ts +138 -0
  4. package/src/bridge/flow-event-forward.ts +132 -0
  5. package/src/bridge/flow-files-reporter.ts +16 -14
  6. package/src/bridge/flow-open-tool.ts +124 -0
  7. package/src/bridge/flow-probe.ts +20 -0
  8. package/src/bridge/flow-tool-registry.ts +298 -0
  9. package/src/bridge/flow-tools-guideline.ts +52 -0
  10. package/src/bridge/index.ts +67 -10
  11. package/src/bridge/run-snapshot-reporter.ts +146 -0
  12. package/src/catalog-timings.ts +70 -0
  13. package/src/client/AskSession.tsx +82 -0
  14. package/src/client/FlowActionDialogs.tsx +143 -0
  15. package/src/client/FlowActivityBadge.tsx +42 -4
  16. package/src/client/FlowAgentCard.tsx +63 -8
  17. package/src/client/FlowAgentDetail.tsx +3 -5
  18. package/src/client/FlowDashboard.tsx +381 -273
  19. package/src/client/FlowEditMenu.tsx +69 -0
  20. package/src/client/FlowEditPopover.tsx +130 -0
  21. package/src/client/FlowGraph.tsx +127 -44
  22. package/src/client/FlowHeaderActions.tsx +83 -0
  23. package/src/client/FlowInputWiring.tsx +1 -1
  24. package/src/client/FlowOpenListener.tsx +82 -0
  25. package/src/client/FlowQuestionBlock.tsx +226 -0
  26. package/src/client/FlowStepCards.tsx +189 -0
  27. package/src/client/FlowSummary.tsx +72 -240
  28. package/src/client/FlowWriteToolRenderer.tsx +46 -17
  29. package/src/client/FlowYamlPopoverButton.tsx +2 -2
  30. package/src/client/FlowsContextGroup.tsx +156 -0
  31. package/src/client/FlowsSessionStateContext.tsx +202 -54
  32. package/src/client/FlowsSettings.tsx +145 -17
  33. package/src/client/SessionFlowActions.tsx +65 -10
  34. package/src/client/SessionFlowMenuClaim.tsx +48 -241
  35. package/src/client/ask-session-store.ts +243 -0
  36. package/src/client/flow-attach-store.ts +2 -0
  37. package/src/client/flow-card-grid.ts +2 -2
  38. package/src/client/flow-collapse-storage.ts +36 -6
  39. package/src/client/flow-edges.ts +91 -35
  40. package/src/client/flow-files.ts +16 -4
  41. package/src/client/flow-idle-state.ts +93 -37
  42. package/src/client/flowsActionsGate.ts +1 -1
  43. package/src/client/flowsAvailability.ts +8 -2
  44. package/src/client/index.tsx +13 -11
  45. package/src/client/shouldRender.ts +1 -1
  46. package/src/client/useEditModeState.ts +78 -0
  47. package/src/client/useFlowActions.tsx +191 -0
  48. package/src/client/useFlowCatalog.ts +69 -0
  49. package/src/client/useMinuteClock.ts +21 -0
  50. package/src/client/useRunReattach.ts +50 -0
  51. package/src/configSchema.json +37 -2
  52. package/src/flow-catalog-contract.ts +65 -0
  53. package/src/flow-questions.ts +138 -0
  54. package/src/flow-reducer.ts +434 -13
  55. package/src/flow-state-serialize.ts +132 -0
  56. package/src/i18n.ts +144 -6
  57. package/src/server/automation-actions.ts +4 -3
  58. package/src/server/edit-mode.ts +307 -0
  59. package/src/server/flow-catalog.ts +127 -0
  60. package/src/server/flow-control.ts +263 -0
  61. package/src/server/flow-files.ts +140 -14
  62. package/src/server/flow-open.ts +385 -0
  63. package/src/server/index.ts +112 -34
  64. package/src/server/render-actions.ts +3 -2
  65. package/src/server/state-store.ts +11 -5
  66. package/src/types.ts +180 -0
  67. package/src/bridge/flow-question-adapter.ts +0 -93
  68. package/src/client/FlowQuestionCard.tsx +0 -218
  69. package/src/client/FlowQuestionTranscriptPill.tsx +0 -58
  70. package/src/client/FlowsCommandRoutes.tsx +0 -245
  71. package/src/client/flow-yaml-parse.ts +0 -140
@@ -26,11 +26,11 @@
26
26
  */
27
27
 
28
28
  import { useSessionEvents } from "@blackbelt-technology/dashboard-plugin-runtime";
29
- import type {
30
- DashboardEvent,
31
- FlowState,
32
- } from "@blackbelt-technology/pi-dashboard-shared/types.js";
29
+ import type { DashboardEvent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
30
+ import type { FlowState } from "../types.js";
33
31
  import { useMemo } from "react";
32
+ import { FLOW_CATALOG_EVENT, type FlowCatalogEntry, parseCatalogPayload } from "../flow-catalog-contract.js";
33
+ import { deserializeFlowState, FLOW_RUN_SNAPSHOT_EVENT } from "../flow-state-serialize.js";
34
34
  import { isFlowEvent, reduceFlowEvent } from "../reducer.js";
35
35
  import { toEventTime } from "./flow-idle-state.js";
36
36
 
@@ -39,19 +39,26 @@ export interface FlowsSessionState {
39
39
  /** The currently-displayed flow's state, or null when no flow is active. */
40
40
  flowState: FlowState | null;
41
41
  /**
42
- * All flows seen for this session keyed by `flow.flowName`. Used by
43
- * components that need to render multiple concurrent flows
44
- * (FlowDashboard's multi-flow tab bar).
42
+ * All flows seen for this session keyed by `flow.flowName` (each name's
43
+ * latest-started run). Iterates in ascending rank (start time, then
44
+ * first-seen order), so the last entry is the newest. Used by components
45
+ * that render multiple flows (FlowDashboard's tab bar).
46
+ * See change: fix-flow-reattach-per-run-state (D2).
45
47
  */
46
48
  flowStates: ReadonlyMap<string, FlowState>;
47
- /** Epoch ms of the newest `flow_started` in the stream (attach baseline /
48
- * consumption clock). See change: attach-flow-before-run (D4). */
49
+ /** Epoch ms of the newest `flow_started` (or run snapshot start) in the
50
+ * stream (attach baseline / consumption clock). See change:
51
+ * attach-flow-before-run (D4). */
49
52
  lastFlowStartedAt?: number;
50
- /** Latest autonomous mode seen (`flow_started.autonomousMode` or
51
- * `flow_autonomous_changed.enabled`), captured even with no flowState (D8). */
52
- lastAutonomousMode?: boolean;
53
53
  /** Latest start pi-flows refused (`flow_complete` status `rejected`) (D7). */
54
54
  lastRejection?: { flowName: string; reason?: string; timestamp: number };
55
+ /** Newest `flow_catalog` in the stream (replayed included); `undefined` =
56
+ * unknown (never seen). See change: flows-dock-chip-and-panel-actions (D1, D5). */
57
+ catalog?: readonly FlowCatalogEntry[];
58
+ /** Runs with an event but no state, no `flow_complete` and no close: their
59
+ * start fell outside the loaded events. Present only when non-empty.
60
+ * See change: fix-flow-reattach-per-run-state (D5). */
61
+ orphanRunIds?: readonly string[];
55
62
  }
56
63
 
57
64
  const EMPTY_STATE: FlowsSessionState = Object.freeze({
@@ -59,66 +66,205 @@ const EMPTY_STATE: FlowsSessionState = Object.freeze({
59
66
  flowStates: new Map() as ReadonlyMap<string, FlowState>,
60
67
  });
61
68
 
69
+ /** A run (or the legacy slot) competing for the flow slot. */
70
+ interface Candidate {
71
+ state: FlowState;
72
+ startedAt: number;
73
+ order: number;
74
+ closed: boolean;
75
+ runId?: string;
76
+ }
77
+
78
+ const ranksAbove = (a: Candidate, b: Candidate): boolean =>
79
+ a.startedAt !== b.startedAt ? a.startedAt > b.startedAt : a.order > b.order;
80
+
81
+ function top(cands: Iterable<Candidate>): Candidate | undefined {
82
+ let best: Candidate | undefined;
83
+ for (const c of cands) if (!best || ranksAbove(c, best)) best = c;
84
+ return best;
85
+ }
86
+
87
+ const runIdOf = (data: Record<string, unknown>): string | undefined =>
88
+ typeof data.runId === "string" && data.runId ? data.runId : undefined;
89
+
62
90
  /**
63
- * Reduce a session's event stream into flow state. Pure
64
- * function — no React, no side effects. Exported for tests and for
65
- * future server-side rendering. The reduction matches the shell's
66
- * current behavior in `event-reducer.ts` exactly:
91
+ * Reduce a session's event stream into flow state. Pure function — no React,
92
+ * no side effects. Exported for tests.
67
93
  *
68
- * - flow events → reduceFlowEvent updates flowState; flowStates is
69
- * resynced after each flow event so the active flow is also stored
70
- * under its name. `flow_summary_dismissed` clears flowStates.
94
+ * - Per-run reduction: an event with `data.runId` folds into that run's own
95
+ * state, so runs interleaved by seq (pi-flows restarts seq per process)
96
+ * never corrupt each other. The last `flow_run_snapshot` per run seeds its
97
+ * state; a malformed one is ignored.
98
+ * - Slot = latest-started run (`flow_started` / snapshot time, then
99
+ * first-seen order); `null` when that run is closed (no fallback).
100
+ * - `flow_summary_dismissed` with a `runId` closes that run, independent of
101
+ * event order (closed beats running); without one it clears everything.
102
+ * - `flow_summary_*` (no runId) apply to the slot run of the same name; a
103
+ * rejected `flow_complete` only sets `lastRejection`; any other runId-less
104
+ * event folds into a legacy slot exactly as before.
71
105
  *
72
106
  * Iterating the full event stream on every render is fine: the event
73
107
  * stream's reference is stable (returned from `useSessionEvents`) and
74
108
  * the calling hook is wrapped in `useMemo` keyed on that reference,
75
109
  * so the reduction only re-runs when a new event arrives.
110
+ *
111
+ * See changes: persist-flow-run-close, fix-flow-reattach-per-run-state (D1, D2, D5).
76
112
  */
77
113
  export function reduceFlowsSessionState(
78
114
  events: readonly DashboardEvent[],
79
115
  ): FlowsSessionState {
80
- let flowState: FlowState | null = null;
81
- let flowStates: Map<string, FlowState> = new Map();
82
- let flowStatesMutated = false;
116
+ const runs = new Map<string, FlowState>();
117
+ const startedAt = new Map<string, number>();
118
+ // First-seen index per runId (rank tie-break); keys = every runId seen.
119
+ const order = new Map<string, number>();
120
+ const terminal = new Set<string>();
121
+ let nextOrder = 0;
122
+ // Legacy slot (runId-less pi-flows): the previous single-slot fold, plus the
123
+ // per-name states it left behind.
124
+ let legacy: FlowState | null = null;
125
+ let legacyRank = { startedAt: Number.NEGATIVE_INFINITY, order: -1 };
126
+ const legacyStates = new Map<string, Candidate>();
83
127
  let lastFlowStartedAt: number | undefined;
84
- let lastAutonomousMode: boolean | undefined;
85
128
  let lastRejection: FlowsSessionState["lastRejection"];
129
+ let catalog: FlowCatalogEntry[] | undefined;
130
+ // Runs dismissed by runId (live or replayed `flow-run-close`). Applied after
131
+ // the loop: replay sorts close records by seq, so one may precede its run.
132
+ // See change: persist-flow-run-close (D2).
133
+ const closedRunIds = new Set<string>();
134
+
135
+ // Per run, the newest snapshot that deserializes seeds its state (found
136
+ // backwards, so a valid last snapshot is decoded once; a malformed one is
137
+ // skipped, leaving the previous valid one as the seed).
138
+ const seedAt = new Map<string, { index: number; state: FlowState }>();
139
+ for (let i = events.length - 1; i >= 0; i--) {
140
+ const e = events[i];
141
+ if (e.eventType !== FLOW_RUN_SNAPSHOT_EVENT) continue;
142
+ const id = runIdOf(e.data ?? {});
143
+ if (!id || seedAt.has(id)) continue;
144
+ const state = deserializeFlowState((e.data ?? {}).state);
145
+ if (state) seedAt.set(id, { index: i, state });
146
+ }
147
+
148
+ const noteStart = (ts: number) => {
149
+ if (lastFlowStartedAt === undefined || ts > lastFlowStartedAt) lastFlowStartedAt = ts;
150
+ };
151
+ const seen = (runId: string) => {
152
+ if (!order.has(runId)) order.set(runId, nextOrder++);
153
+ };
154
+ /** Candidates for the slot: every run, plus the legacy slot. */
155
+ const slotCandidates = (): Candidate[] => {
156
+ const out: Candidate[] = [...runs].map(([runId, state]) => ({
157
+ state,
158
+ startedAt: startedAt.get(runId) ?? Number.NEGATIVE_INFINITY,
159
+ order: order.get(runId) ?? -1,
160
+ closed: closedRunIds.has(runId),
161
+ runId,
162
+ }));
163
+ if (legacy) out.push({ state: legacy, ...legacyRank, closed: false });
164
+ return out;
165
+ };
166
+ const setLegacy = (s: FlowState | null) => {
167
+ legacy = s;
168
+ if (s) legacyStates.set(s.flowName, { state: s, ...legacyRank, closed: false });
169
+ };
86
170
 
87
171
  // Diagnostic counter for C1 — see fix-flows-plugin-polish. Gated to dev.
88
172
  let flowEventCount = 0;
89
173
 
90
- for (const event of events) {
91
- if (isFlowEvent(event.eventType)) {
92
- flowEventCount++;
93
- const data = event.data ?? {};
94
- if (event.eventType === "flow_started") {
95
- const ts = toEventTime(event.timestamp);
96
- if (lastFlowStartedAt === undefined || ts > lastFlowStartedAt) lastFlowStartedAt = ts;
97
- if (typeof data.autonomousMode === "boolean") lastAutonomousMode = data.autonomousMode;
98
- } else if (event.eventType === "flow_autonomous_changed") {
99
- if (typeof data.enabled === "boolean") lastAutonomousMode = data.enabled;
100
- } else if (event.eventType === "flow_complete" && data.status === "rejected") {
101
- lastRejection = {
102
- flowName: String(data.flowName ?? ""),
103
- reason: typeof data.reason === "string" ? data.reason : undefined,
104
- timestamp: toEventTime(event.timestamp),
105
- };
174
+ for (let i = 0; i < events.length; i++) {
175
+ const event = events[i];
176
+ if (event.eventType === FLOW_CATALOG_EVENT) {
177
+ // Catalog is session metadata, not flow progress: latest wins, never
178
+ // touches flowState / flowStates (no chat row, no panel).
179
+ const parsed = parseCatalogPayload(event.data);
180
+ if (parsed) catalog = parsed;
181
+ continue;
182
+ }
183
+ if (!isFlowEvent(event.eventType)) continue;
184
+ flowEventCount++;
185
+ const data = event.data ?? {};
186
+ const type = event.eventType;
187
+ const runId = runIdOf(data);
188
+ if (type === "flow_summary_dismissed") {
189
+ if (runId) {
190
+ closedRunIds.add(runId);
191
+ } else {
192
+ // Legacy clear-all: every run seen so far (orphans included) stays gone.
193
+ for (const id of order.keys()) closedRunIds.add(id);
194
+ runs.clear();
195
+ legacy = null;
196
+ legacyStates.clear();
106
197
  }
107
- flowState = reduceFlowEvent(flowState, event);
108
- if (flowState) {
109
- if (!flowStatesMutated) {
110
- flowStates = new Map(flowStates);
111
- flowStatesMutated = true;
112
- }
113
- flowStates.set(flowState.flowName, flowState);
114
- } else if (event.eventType === "flow_summary_dismissed") {
115
- if (flowStates.size > 0) {
116
- flowStates = new Map();
117
- flowStatesMutated = true;
118
- }
198
+ continue;
199
+ }
200
+ if (type === "flow_complete" && data.status === "rejected") {
201
+ // A refused start never refers to a held run. (attach-flow-before-run D10)
202
+ lastRejection = {
203
+ flowName: String(data.flowName ?? ""),
204
+ reason: typeof data.reason === "string" ? data.reason : undefined,
205
+ timestamp: toEventTime(event.timestamp),
206
+ };
207
+ continue;
208
+ }
209
+ if (type === FLOW_RUN_SNAPSHOT_EVENT) {
210
+ if (!runId) continue;
211
+ // First sight counts for the rank tie-break even when this snapshot is
212
+ // not the one that seeds the state.
213
+ seen(runId);
214
+ const seed = seedAt.get(runId);
215
+ if (seed?.index !== i) continue;
216
+ runs.set(runId, seed.state);
217
+ const ts = toEventTime(data.startedAt);
218
+ startedAt.set(runId, ts);
219
+ noteStart(ts);
220
+ continue;
221
+ }
222
+ if (runId) {
223
+ seen(runId);
224
+ if (type === "flow_started") {
225
+ const ts = toEventTime(event.timestamp);
226
+ startedAt.set(runId, ts);
227
+ noteStart(ts);
228
+ } else if (type === "flow_complete") {
229
+ terminal.add(runId);
119
230
  }
231
+ const next = reduceFlowEvent(runs.get(runId) ?? null, event);
232
+ if (next) runs.set(runId, next);
233
+ continue;
234
+ }
235
+ if (type === "flow_summary_started" || type === "flow_summary_ready") {
236
+ const slot = top(slotCandidates());
237
+ if (!slot || (typeof data.flowName === "string" && data.flowName !== slot.state.flowName)) continue;
238
+ const next = reduceFlowEvent(slot.state, event);
239
+ if (!slot.runId) setLegacy(next);
240
+ else if (next) runs.set(slot.runId, next);
241
+ continue;
120
242
  }
243
+ if (type === "flow_started") {
244
+ const ts = toEventTime(event.timestamp);
245
+ legacyRank = { startedAt: ts, order: nextOrder++ };
246
+ noteStart(ts);
247
+ }
248
+ setLegacy(reduceFlowEvent(legacy, event));
249
+ }
250
+
251
+ const cands = slotCandidates();
252
+ const slot = top(cands);
253
+ const flowState = slot && !slot.closed ? slot.state : null;
254
+ // Per name: its top run (legacy states included), dropped when that run is
255
+ // closed; built in ascending rank order (D2 contract).
256
+ const byName = new Map<string, Candidate>();
257
+ for (const c of [...cands, ...legacyStates.values()]) {
258
+ const cur = byName.get(c.state.flowName);
259
+ if (!cur || ranksAbove(c, cur)) byName.set(c.state.flowName, c);
121
260
  }
261
+ const flowStates = new Map<string, FlowState>(
262
+ [...byName.values()]
263
+ .filter((c) => !c.closed)
264
+ .sort((a, b) => (ranksAbove(a, b) ? 1 : ranksAbove(b, a) ? -1 : 0))
265
+ .map((c) => [c.state.flowName, c.state]),
266
+ );
267
+ const orphanRunIds = [...order.keys()].filter((id) => !runs.has(id) && !terminal.has(id) && !closedRunIds.has(id));
122
268
 
123
269
  if (typeof import.meta !== "undefined" && (import.meta as { env?: { DEV?: boolean } }).env?.DEV) {
124
270
  if (flowEventCount > 0) {
@@ -140,8 +286,9 @@ export function reduceFlowsSessionState(
140
286
  flowState === null &&
141
287
  flowStates.size === 0 &&
142
288
  lastFlowStartedAt === undefined &&
143
- lastAutonomousMode === undefined &&
144
- lastRejection === undefined
289
+ lastRejection === undefined &&
290
+ catalog === undefined &&
291
+ orphanRunIds.length === 0
145
292
  ) {
146
293
  return EMPTY_STATE;
147
294
  }
@@ -150,8 +297,9 @@ export function reduceFlowsSessionState(
150
297
  flowState,
151
298
  flowStates,
152
299
  lastFlowStartedAt,
153
- lastAutonomousMode,
154
300
  lastRejection,
301
+ ...(catalog !== undefined ? { catalog } : {}),
302
+ ...(orphanRunIds.length > 0 ? { orphanRunIds } : {}),
155
303
  };
156
304
  }
157
305
 
@@ -1,42 +1,137 @@
1
1
  /**
2
- * Settings-section for the flows plugin: a global edit-mode default.
2
+ * Settings-section for the flows plugin: the global edit-mode default.
3
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.
4
+ * Edit-mode on → the main session sees the `manage-flows` skill and the
5
+ * `flow_agents` / `flow_write` authoring tools. The toggle reads/writes
6
+ * `flows.editFlow` in the global pi settings file (`~/.pi/agent/settings.json`,
7
+ * which pi-flows reads) via `GET|PUT /api/plugins/flows/edit-mode-default`.
8
+ * It never writes a project `.pi/settings.json`; a project value set from the
9
+ * session menu overrides it. pi-flows picks the change up at the next turn.
8
10
  *
9
11
  * 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.
12
+ * panel's Save; a failed PUT rejects so the draft stays dirty, and a parse
13
+ * error is shown here). See change: rework-flows-plugin-for-new-pi-flows;
14
+ * stop-flows-edit-mode-project-writes (D2).
15
+ *
16
+ * Advanced group: the flow catalog timings (plugin config, `catalog-timings.ts`).
17
+ * An out-of-range value rejects the save with a message naming the range and
18
+ * leaves the stored value unchanged; a saved value applies without restart.
19
+ * See change: flows-dock-chip-and-panel-actions (D11).
11
20
  */
12
21
 
13
- import { ToggleField, usePluginConfig, usePluginSend, useSettingsDraftSource, useT } from "@blackbelt-technology/dashboard-plugin-runtime";
22
+ import { NumberField, SettingsGroup, ToggleField, usePluginConfig, usePluginSend, useSettingsDraftSource, useT } from "@blackbelt-technology/dashboard-plugin-runtime";
14
23
  import type React from "react";
15
- import { useCallback, useRef, useState } from "react";
24
+ import { useCallback, useEffect, useRef, useState } from "react";
25
+ import { CATALOG_TIMING_SPECS, type CatalogTimingKey, type CatalogTimingSpec, rangeLabel as rangeText, validateTiming } from "../catalog-timings.js";
26
+
27
+ const TIMING_LABELS: Record<CatalogTimingKey, [key: string, fallback: string]> = {
28
+ catalogAskLimitSec: ["catalogAskLimitLabel", "Catalog ask limit per session"],
29
+ catalogReaskIntervalSec: ["catalogReaskIntervalLabel", "Re-ask interval while unknown"],
30
+ catalogReaskAttempts: ["catalogReaskAttemptsLabel", "Re-ask attempts per view"],
31
+ catalogServerStartIntervalSec: ["catalogServerStartIntervalLabel", "Re-ask interval after server start"],
32
+ catalogServerStartWindowSec: ["catalogServerStartWindowLabel", "Re-ask window after server start"],
33
+ };
34
+
35
+ type TimingEdits = Partial<Record<CatalogTimingKey, number>>;
36
+
37
+ const URL = "/api/plugins/flows/edit-mode-default";
16
38
 
17
- export interface FlowsPluginConfig {
18
- /** Global default for pi-flows `flows.editFlow`. Default off. */
39
+ /** Stored plugin config. `editFlow` is LEGACY: migrated once to the global pi settings, then removed. */
40
+ export interface FlowsPluginConfig extends Partial<Record<CatalogTimingKey, number>> {
41
+ /** @deprecated Ignored; see `flows.editFlow` in `~/.pi/agent/settings.json`. */
19
42
  editFlow?: boolean;
20
43
  }
21
44
 
45
+ function storedTiming(config: FlowsPluginConfig, spec: CatalogTimingSpec): number {
46
+ const v = config[spec.key];
47
+ return validateTiming(spec, v) === null ? (v as number) : spec.default;
48
+ }
49
+
22
50
  export function FlowsSettings(): React.ReactElement {
23
51
  const t = useT();
24
52
  const config = usePluginConfig<FlowsPluginConfig>();
25
53
  const send = usePluginSend();
26
54
 
27
- const [editFlow, setEditFlow] = useState<boolean>(config.editFlow ?? false);
28
- const base = config.editFlow ?? false;
29
- const isDirty = editFlow !== base;
55
+ const [base, setBase] = useState<boolean>(false);
56
+ const [editFlow, setEditFlow] = useState<boolean>(false);
57
+ const [error, setError] = useState<string | null>(null);
58
+ const [timingEdits, setTimingEdits] = useState<TimingEdits>({});
59
+ const [timingErrors, setTimingErrors] = useState<Partial<Record<CatalogTimingKey, string>>>({});
60
+ const changedTimings: TimingEdits = {};
61
+ for (const spec of CATALOG_TIMING_SPECS) {
62
+ const v = timingEdits[spec.key];
63
+ if (v !== undefined && !Object.is(v, storedTiming(config, spec))) changedTimings[spec.key] = v;
64
+ }
65
+ const editFlowDirty = editFlow !== base;
66
+ const isDirty = editFlowDirty || Object.keys(changedTimings).length > 0;
67
+
68
+ // Load the global value once; a parse error is shown, not overwritten.
69
+ useEffect(() => {
70
+ let cancelled = false;
71
+ void (async () => {
72
+ try {
73
+ const r = await fetch(URL);
74
+ if (!r.ok) return;
75
+ const body = (await r.json()) as { enabled?: unknown; parseError?: unknown };
76
+ if (cancelled) return;
77
+ const v = body.enabled === true;
78
+ setBase(v);
79
+ setEditFlow(v);
80
+ setError(typeof body.parseError === "string" ? body.parseError : null);
81
+ } catch {
82
+ /* keep the default (off) */
83
+ }
84
+ })();
85
+ return () => {
86
+ cancelled = true;
87
+ };
88
+ }, []);
30
89
 
31
90
  const valuesRef = useRef(editFlow);
32
91
  valuesRef.current = editFlow;
33
92
  const baseRef = useRef(base);
34
93
  baseRef.current = base;
94
+ const timingsRef = useRef(changedTimings);
95
+ timingsRef.current = changedTimings;
35
96
 
36
97
  const commit = useCallback(async () => {
37
- await send({ type: "plugin_config_write", id: "flows", config: { editFlow: valuesRef.current } });
38
- }, [send]);
39
- const reset = useCallback(() => setEditFlow(baseRef.current), []);
98
+ // Validate every changed timing first: an out-of-range value rejects the
99
+ // whole save (stored values unchanged) with a message naming the range.
100
+ const timings = timingsRef.current;
101
+ const errs: Partial<Record<CatalogTimingKey, string>> = {};
102
+ for (const spec of CATALOG_TIMING_SPECS) {
103
+ if (!(spec.key in timings)) continue;
104
+ const range = validateTiming(spec, timings[spec.key]);
105
+ if (range) errs[spec.key] = t("timingRangeError", { range }, `Enter a value in ${range}.`);
106
+ }
107
+ setTimingErrors(errs);
108
+ const firstErr = Object.values(errs)[0];
109
+ if (firstErr) throw new Error(firstErr);
110
+ if (Object.keys(timings).length > 0) {
111
+ await send({ type: "plugin_config_write", id: "flows", config: timings });
112
+ setTimingEdits({});
113
+ }
114
+ const enabled = valuesRef.current;
115
+ if (enabled === baseRef.current) return;
116
+ const r = await fetch(URL, {
117
+ method: "PUT",
118
+ headers: { "content-type": "application/json" },
119
+ body: JSON.stringify({ enabled }),
120
+ });
121
+ if (!r.ok) {
122
+ const body = (await r.json().catch(() => ({}))) as { parseError?: unknown; error?: unknown };
123
+ const msg = typeof body.parseError === "string" ? body.parseError : typeof body.error === "string" ? body.error : `HTTP ${r.status}`;
124
+ setError(msg);
125
+ throw new Error(msg);
126
+ }
127
+ setError(null);
128
+ setBase(enabled);
129
+ }, [send, t]);
130
+ const reset = useCallback(() => {
131
+ setEditFlow(baseRef.current);
132
+ setTimingEdits({});
133
+ setTimingErrors({});
134
+ }, []);
40
135
  useSettingsDraftSource({ id: "plugin:flows", isDirty, commit, reset });
41
136
 
42
137
  const codeCls = "font-mono text-[12px] text-[var(--text-primary)]";
@@ -52,13 +147,46 @@ export function FlowsSettings(): React.ReactElement {
52
147
  <>
53
148
  {t("editModeHintPre", undefined, "Lets the main session create and change flows and agents. Turns on")}{" "}
54
149
  <code className={codeCls}>flow_agents</code> / <code className={codeCls}>flow_write</code>{" "}
55
- {t("editModeHintPost", undefined, "and the edit-flow skill. Off by default.")}
150
+ {t("editModeHintPost", undefined, "and the manage-flows skill. Off by default.")}{" "}
151
+ {t("editModeHintGlobal", undefined, "Saved to ~/.pi/agent/settings.json; project files are not changed. A project's own setting overrides it.")}
56
152
  </>
57
153
  }
58
154
  value={editFlow}
59
155
  onChange={setEditFlow}
60
156
  testIds={{ control: "flows-edit-mode-toggle" }}
61
157
  />
158
+ {error && (
159
+ <p role="alert" data-testid="flows-edit-mode-error" className="text-xs text-[var(--status-error)]">
160
+ {t("editModeSaveError", { error }, `Could not save: ${error}`)}
161
+ </p>
162
+ )}
163
+ <SettingsGroup title={t("advancedGroup", undefined, "Advanced")} defaultOpen={Object.values(timingErrors).some(Boolean)} testId="flows-advanced-group">
164
+ <p className="text-xs text-[var(--text-secondary)]">
165
+ {t("catalogTimingsIntro", undefined, "How the dashboard asks sessions for their flow list.")}
166
+ </p>
167
+ {CATALOG_TIMING_SPECS.map((spec) => {
168
+ const [key, fallback] = TIMING_LABELS[spec.key];
169
+ const value = timingEdits[spec.key] ?? storedTiming(config, spec);
170
+ return (
171
+ <NumberField
172
+ key={spec.key}
173
+ label={t(key, undefined, fallback)}
174
+ unit={spec.unit || undefined}
175
+ hint={t("timingRangeHint", { range: rangeText(spec), def: spec.default }, `${rangeText(spec)}, default ${spec.default}`)}
176
+ value={value}
177
+ decimal={!spec.integer}
178
+ allowEmpty
179
+ step={spec.integer ? 1 : "any"}
180
+ error={timingErrors[spec.key]}
181
+ onChange={(v) => {
182
+ setTimingEdits((prev) => ({ ...prev, [spec.key]: v }));
183
+ setTimingErrors((prev) => ({ ...prev, [spec.key]: undefined }));
184
+ }}
185
+ testIds={{ control: `flows-timing-${spec.key}` }}
186
+ />
187
+ );
188
+ })}
189
+ </SettingsGroup>
62
190
  </div>
63
191
  );
64
192
  }
@@ -1,38 +1,82 @@
1
- import { usePluginSend } from "@blackbelt-technology/dashboard-plugin-runtime";
2
- import type { DashboardSession, FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
3
- import React from "react";
1
+ import { usePluginSend, useT } from "@blackbelt-technology/dashboard-plugin-runtime";
2
+ import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
3
+ import React, { useMemo } from "react";
4
+ import { formatRemaining, nearestExpiry, openQuestions, waitingState } from "../flow-questions.js";
5
+ import type { FlowState } from "../types.js";
6
+ import { openQuestionIds } from "./ask-session-store.js";
4
7
  import { FlowActivityBadge } from "./FlowActivityBadge.js";
8
+ import { AskSessionButton, AskSessionProvider, useAskSessionApi } from "./AskSession.js";
5
9
  import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
10
+ import { makeSafeSend } from "./send-safe.js";
11
+ import { useMinuteClock } from "./useMinuteClock.js";
6
12
 
7
13
  /**
8
14
  * FLOWS-subcard body: flow STATUS only — `FlowActivityBadge` (with Abort while
9
- * running) when the session has a flow state, else null. The flow actions
15
+ * running, and the waiting variants plus **Ask session** while steps wait on
16
+ * parent questions) when the session has a flow state, else null. The flow actions
10
17
  * (Run / Open / New-Edit / Delete), their dialogs and the edit-mode reconcile
11
18
  * live in `SessionFlowMenuClaim`. See change: add-session-actions-flyout (D12).
12
19
  */
13
20
  export function SessionFlowActions({
14
21
  flowState,
15
22
  onAbortFlow,
23
+ sessionId,
24
+ flowStates,
16
25
  }: {
17
26
  /** Current flow state for this session. Drives the status pill. */
18
27
  flowState?: FlowState | null;
19
- /** Dispatch flow_control abort. Called by the running-flow pill's Abort button. */
28
+ /** Dispatch the `flow.abort` plugin_action. Called by the running-flow pill's Abort button. */
20
29
  onAbortFlow?: () => void;
30
+ /** Session id: enables **Ask session** for open parent questions. */
31
+ sessionId?: string;
32
+ /** Every run of the session (Ask session keeps their open questions). */
33
+ flowStates?: ReadonlyMap<string, FlowState>;
21
34
  }) {
22
- // Compute running-flow badge inputs from flowState (when present).
23
- // See change: fix-flows-plugin-polish (A5 + A6).
24
35
  if (!flowState) return null;
36
+ if (!sessionId) return <FlowBadge flowState={flowState} onAbortFlow={onAbortFlow} />;
37
+ return (
38
+ <AskSessionProvider sessionId={sessionId} openIds={openQuestionIds([flowState, ...(flowStates?.values() ?? [])])}>
39
+ <FlowBadge flowState={flowState} onAbortFlow={onAbortFlow} />
40
+ </AskSessionProvider>
41
+ );
42
+ }
43
+
44
+ /** The badge with the waiting / mixed variants and one 30 s clock.
45
+ * See change: adopt-flow-parent-mailbox (D6). */
46
+ function FlowBadge({ flowState, onAbortFlow }: { flowState: FlowState; onAbortFlow?: () => void }) {
47
+ const t = useT();
48
+ const api = useAskSessionApi();
49
+ // Compute running-flow badge inputs from flowState.
50
+ // See change: fix-flows-plugin-polish (A5 + A6).
25
51
  const agents = flowState.agents;
26
52
  const done = Array.from(agents.values()).filter(
27
53
  (a) => a.status === "complete" || a.status === "error" || a.status === "blocked",
28
54
  ).length;
55
+ const running = flowState.status === "running";
56
+ const open = running ? openQuestions(flowState) : [];
57
+ const expiry = running ? nearestExpiry(flowState) : undefined;
58
+ const now = useMinuteClock(expiry !== undefined);
59
+ const w = running ? waitingState(flowState) : null;
60
+ const ids = open.map((q) => q.id);
61
+ const unsent = api ? api.unsent(ids) : [];
29
62
  return (
30
63
  <FlowActivityBadge
31
64
  flowName={flowState.flowName}
32
65
  agentsDone={done}
33
66
  agentsTotal={agents.size}
34
67
  status={flowState.status}
35
- onAbort={flowState.status === "running" ? onAbortFlow : undefined}
68
+ onAbort={running ? onAbortFlow : undefined}
69
+ waiting={w ? { ...w, remaining: expiry !== undefined ? formatRemaining(expiry, now, t) : null } : null}
70
+ askSession={
71
+ api && ids.length > 0 ? (
72
+ <AskSessionButton
73
+ size="line"
74
+ testId="flow-badge-ask-session"
75
+ view={{ note: "unread", disabled: unsent.length === 0, sent: false }}
76
+ onAsk={() => api.ask(unsent)}
77
+ />
78
+ ) : null
79
+ }
36
80
  />
37
81
  );
38
82
  }
@@ -44,12 +88,23 @@ export function SessionFlowActions({
44
88
  * pluginize-flows-via-registry, add-session-actions-flyout.
45
89
  */
46
90
  export function SessionFlowActionsClaim({ session }: { session: DashboardSession }) {
47
- const { flowState } = useFlowsSessionState(session.id);
91
+ const { flowState, flowStates } = useFlowsSessionState(session.id);
48
92
  const send = usePluginSend();
93
+ const safeSend = useMemo(() => makeSafeSend(send), [send]);
49
94
  return (
50
95
  <SessionFlowActions
51
96
  flowState={flowState}
52
- onAbortFlow={() => send({ type: "flow_control", sessionId: session.id, action: "abort" })}
97
+ sessionId={session.id}
98
+ flowStates={flowStates}
99
+ onAbortFlow={() => {
100
+ // Abort also closes the running slot run by runId, so it never reopens.
101
+ // See change: fix-flow-reattach-per-run-state (D6).
102
+ const msgs: Record<string, unknown>[] = [{ type: "plugin_action", pluginId: "flows", sessionId: session.id, action: "flow.abort" }];
103
+ if (flowState?.status === "running" && flowState.runId) {
104
+ msgs.push({ type: "plugin_action", pluginId: "flows", sessionId: session.id, action: "flow.dismiss-summary", payload: { runId: flowState.runId } });
105
+ }
106
+ for (const m of msgs) safeSend(m);
107
+ }}
53
108
  />
54
109
  );
55
110
  }