@blackbelt-technology/pi-dashboard-flows-plugin 0.7.0 → 0.9.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 (54) hide show
  1. package/package.json +18 -7
  2. package/src/bridge/flow-files-reporter.ts +113 -0
  3. package/src/bridge/index.ts +5 -1
  4. package/src/client/FlowAgentCard.tsx +82 -213
  5. package/src/client/FlowAgentDetail.tsx +1 -1
  6. package/src/client/FlowDashboard.tsx +428 -66
  7. package/src/client/FlowInputWiring.tsx +2 -2
  8. package/src/client/FlowSummary.tsx +22 -16
  9. package/src/client/FlowYamlPopoverButton.tsx +27 -92
  10. package/src/client/FlowsCommandRoutes.tsx +13 -5
  11. package/src/client/FlowsSessionStateContext.tsx +40 -4
  12. package/src/client/FlowsSettings.tsx +4 -4
  13. package/src/client/SessionFlowActions.tsx +80 -6
  14. package/src/client/flow-attach-store.ts +140 -0
  15. package/src/client/flow-card-grid.ts +36 -0
  16. package/src/client/flow-files.ts +152 -0
  17. package/src/client/flow-idle-state.ts +230 -0
  18. package/src/client/format-cost.ts +21 -0
  19. package/src/client/send-safe.ts +19 -0
  20. package/src/flow-files-contract.ts +21 -0
  21. package/src/flow-reducer.ts +4 -0
  22. package/src/i18n.ts +28 -0
  23. package/src/server/automation-actions.ts +3 -0
  24. package/src/server/flow-files.ts +264 -0
  25. package/src/server/index.ts +15 -0
  26. package/src/AGENTS.md +0 -8
  27. package/src/__tests__/FlowGraph.test.ts +0 -305
  28. package/src/__tests__/FlowInputWiring.test.tsx +0 -97
  29. package/src/__tests__/FlowSummary.test.tsx +0 -331
  30. package/src/__tests__/FlowYamlPreview.test.tsx +0 -75
  31. package/src/__tests__/FlowsSessionStateContext.test.tsx +0 -223
  32. package/src/__tests__/FlowsUiStateContext.test.tsx +0 -140
  33. package/src/__tests__/authoring-renderers.test.tsx +0 -190
  34. package/src/__tests__/automation-actions.test.ts +0 -117
  35. package/src/__tests__/flow-agent-card-code-source.test.tsx +0 -190
  36. package/src/__tests__/flow-agent-cost.test.tsx +0 -160
  37. package/src/__tests__/flow-agent-error.test.ts +0 -60
  38. package/src/__tests__/flow-collapse-storage.test.ts +0 -90
  39. package/src/__tests__/flow-edges.test.ts +0 -195
  40. package/src/__tests__/flow-inputs.test.ts +0 -69
  41. package/src/__tests__/flow-reducer-bridge-contract.test.ts +0 -108
  42. package/src/__tests__/flow-reducer-seed-on-start.test.ts +0 -61
  43. package/src/__tests__/flow-yaml-parse.test.ts +0 -124
  44. package/src/__tests__/flows-for-cwd.test.ts +0 -51
  45. package/src/__tests__/flowsAvailability.test.ts +0 -79
  46. package/src/__tests__/manifest-discoverability.test.ts +0 -97
  47. package/src/__tests__/node-kind-reducer.test.ts +0 -135
  48. package/src/__tests__/plugin-action-handler.test.ts +0 -54
  49. package/src/__tests__/reducer-parity.test.ts +0 -106
  50. package/src/__tests__/render-actions.test.ts +0 -63
  51. package/src/__tests__/session-flow-actions-edit.test.tsx +0 -98
  52. package/src/bridge/AGENTS.md +0 -8
  53. package/src/client/AGENTS.md +0 -32
  54. package/src/server/AGENTS.md +0 -10
@@ -181,7 +181,7 @@ export function FlowInputWiring({ payload, onChange, cwd }: FlowInputWiringProps
181
181
  className={`px-2 text-[10px] ${
182
182
  boundToTrigger
183
183
  ? "text-[var(--text-secondary)]"
184
- : "bg-[var(--accent,#6366f1)] text-white"
184
+ : "bg-[var(--accent-solid)] text-white"
185
185
  }`}
186
186
  >
187
187
  literal
@@ -192,7 +192,7 @@ export function FlowInputWiring({ payload, onChange, cwd }: FlowInputWiringProps
192
192
  onClick={() => setInput(f.name, TRIGGER_TOKEN)}
193
193
  className={`border-l border-[var(--border-secondary)] px-2 text-[10px] ${
194
194
  boundToTrigger
195
- ? "bg-[var(--accent,#6366f1)] text-white"
195
+ ? "bg-[var(--accent-solid)] text-white"
196
196
  : "text-[var(--text-secondary)]"
197
197
  }`}
198
198
  >
@@ -8,6 +8,8 @@ import { FlowAgentCard } from "./FlowAgentCard.js";
8
8
  import { FlowGraph, flowStateToGraphSteps } from "./FlowGraph.js";
9
9
  import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
10
10
  import { FlowYamlPopoverButton } from "./FlowYamlPopoverButton.js";
11
+ import { FLOW_CARD_GRID_CLASS, FLOW_CARD_GRID_CONTAINER_CLASS } from "./flow-card-grid.js";
12
+ import { useFlowNodeFiles, withNodeFiles } from "./flow-files.js";
11
13
  import { useFlowCollapsePersisted } from "./flow-collapse-storage.js";
12
14
 
13
15
 
@@ -52,7 +54,10 @@ export function FlowSummary({
52
54
  // improve-flow-graph-dialog-and-card-interaction.
53
55
  const [selectedStepId, setSelectedStepId] = useState<string | null>(null);
54
56
  const rootRef = useRef<HTMLDivElement>(null);
55
- const agents = Array.from(flowState.agents.values());
57
+ // Agent / handler file paths for the frozen cards' file buttons.
58
+ // See change: attach-flow-before-run.
59
+ const nodeFiles = useFlowNodeFiles(sessionId ?? session?.id);
60
+ const agents = Array.from(withNodeFiles(flowState, nodeFiles).agents.values());
56
61
  // Only summary-bearing agents are listed in the Summaries subsection (others
57
62
  // stay in the frozen cards + graph). See change: fix-flow-ui-graph-zoom-summary.
58
63
  const summarised = agents.filter(a => a.summary);
@@ -137,6 +142,7 @@ export function FlowSummary({
137
142
  <FlowYamlPopoverButton
138
143
  flowSource={flowState.flowSource}
139
144
  flowName={flowState.flowName}
145
+ sessionId={sessionId ?? session?.id}
140
146
  />
141
147
  </div>
142
148
  )}
@@ -145,22 +151,22 @@ export function FlowSummary({
145
151
  the whole panel always fits the viewport (no page scroll). The summaries
146
152
  section and each agent row stay independently collapsible inside it. */}
147
153
  <div className="mt-2 overflow-y-auto" style={{ maxHeight: "48vh" }} data-testid="flow-summary-scrollbox">
148
- {/* Frozen agent cards — read-only. */}
154
+ {/* Frozen agent cards — read-only. Same grid geometry as the live panel
155
+ (shared helper); the wrapper is the query container (design D1/D5). */}
149
156
  {agents.length > 0 && (
150
- <div
151
- className="grid gap-2"
152
- style={{ gridTemplateColumns: `repeat(auto-fill, minmax(200px, 1fr))` }}
153
- >
154
- {agents.map(agent => (
155
- <FlowAgentCard
156
- key={agent.stepId || agent.agentName}
157
- agent={agent}
158
- session={session}
159
- sessionId={sessionId ?? session?.id}
160
- selected={selectedStepId === (agent.stepId || agent.agentName)}
161
- onSelect={handleSelectStep}
162
- />
163
- ))}
157
+ <div className={FLOW_CARD_GRID_CONTAINER_CLASS}>
158
+ <div className={FLOW_CARD_GRID_CLASS}>
159
+ {agents.map(agent => (
160
+ <FlowAgentCard
161
+ key={agent.stepId || agent.agentName}
162
+ agent={agent}
163
+ session={session}
164
+ sessionId={sessionId ?? session?.id}
165
+ selected={selectedStepId === (agent.stepId || agent.agentName)}
166
+ onSelect={handleSelectStep}
167
+ />
168
+ ))}
169
+ </div>
164
170
  </div>
165
171
  )}
166
172
 
@@ -1,110 +1,45 @@
1
1
  /**
2
- * FlowYamlPopoverButton — paper-icon button that opens a popover anchored
3
- * to itself, fetches the flow's YAML at `/api/pi-resource-file?path=...`,
4
- * and renders it inside the popover via the `ui:markdown-content` primitive
5
- * (wrapped in a `yaml` code fence for syntax highlighting).
2
+ * FlowYamlPopoverButton — paper-icon button that opens the flow's YAML in the
3
+ * host's built-in editor (Split view) via `useOpenFileInEditor`. Hidden without
4
+ * a session (no editor to target).
6
5
  *
7
- * Used by `FlowDashboard` (live flow) and `FlowSummary` (completed flow).
6
+ * Used by `FlowDashboard` (live / idle flow) and `FlowSummary` (completed flow).
8
7
  *
9
8
  * The flow's YAML path is emitted by pi-flows in the `flow:flow-started`
10
- * event (see `packages/pi-flows/extensions/flow-engine/flow-tui.ts:487` —
11
- * `source: flow.source`) and stored on `FlowState.flowSource` by the flow
12
- * reducer.
9
+ * event (`source: flow.source`) and stored on `FlowState.flowSource` by the
10
+ * flow reducer; an attached idle flow carries it from `flowsList`.
13
11
  *
14
- * See change: add-ui-popover-primitive.
12
+ * See change: add-ui-popover-primitive, attach-flow-before-run.
15
13
  */
16
- import React, { useEffect, useState } from "react";
17
- import { Icon } from "@mdi/react";
14
+ import { useT } from "@blackbelt-technology/dashboard-plugin-runtime";
18
15
  import { mdiFileDocumentOutline } from "@mdi/js";
19
- import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
20
- import { useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
21
-
22
- type YamlFetchState =
23
- | { kind: "idle" }
24
- | { kind: "loading" }
25
- | { kind: "loaded"; content: string }
26
- | { kind: "error"; error: string };
16
+ import { Icon } from "@mdi/react";
17
+ import { useOpenFileInEditor } from "./flow-files.js";
27
18
 
28
19
  export function FlowYamlPopoverButton({
29
20
  flowSource,
30
21
  flowName,
22
+ sessionId,
31
23
  }: {
32
24
  flowSource: string;
33
25
  flowName: string;
26
+ /** Owning session — the editor to open the YAML in. */
27
+ sessionId?: string;
34
28
  }) {
35
- const Dialog = useUiPrimitive(UI_PRIMITIVE_KEYS.dialog);
36
- const MarkdownContent = useUiPrimitive(UI_PRIMITIVE_KEYS.markdownContent);
37
- const [open, setOpen] = useState(false);
38
- const [state, setState] = useState<YamlFetchState>({ kind: "idle" });
39
-
40
- // Deps include only `open` + `flowSource`. Including state.kind would
41
- // cause cleanup to fire on the idle→loading transition, self-cancelling
42
- // the fetch. Same pattern as `usePiResourceFileFetch` in the client.
43
- useEffect(() => {
44
- if (!open) return;
45
- let cancelled = false;
46
- setState({ kind: "loading" });
47
- fetch(`/api/pi-resource-file?path=${encodeURIComponent(flowSource)}`)
48
- .then(async (r) => {
49
- const json = await r.json();
50
- if (cancelled) return;
51
- if (json?.success && typeof json?.data?.content === "string") {
52
- setState({ kind: "loaded", content: json.data.content });
53
- } else {
54
- setState({
55
- kind: "error",
56
- error: typeof json?.error === "string" ? json.error : "Failed to read flow YAML",
57
- });
58
- }
59
- })
60
- .catch((err) => {
61
- if (!cancelled) setState({ kind: "error", error: String(err) });
62
- });
63
- return () => {
64
- cancelled = true;
65
- };
66
- }, [open, flowSource]);
67
-
29
+ const t = useT();
30
+ const openInEditor = useOpenFileInEditor(sessionId);
31
+ if (!openInEditor) return null;
68
32
  return (
69
- <>
70
- <button
71
- onClick={(e) => {
72
- e.stopPropagation();
73
- setOpen((prev) => !prev);
74
- }}
75
- className={`transition-colors p-0.5 rounded inline-flex items-center ${
76
- open
77
- ? "text-blue-400 bg-blue-400/10"
78
- : "text-[var(--text-tertiary)] hover:text-blue-400 hover:bg-[var(--bg-surface)]"
79
- }`}
80
- title={open ? "Close flow YAML" : `View ${flowName} YAML`}
81
- >
82
- <Icon path={mdiFileDocumentOutline} size={0.5} />
83
- </button>
84
- <Dialog
85
- open={open}
86
- onClose={() => setOpen(false)}
87
- title={`${flowName} · YAML`}
88
- size="lg"
89
- >
90
- {/* Pinned path header; YAML scrolls inside a fixed-height region so the
91
- dialog stays a fixed size. See change:
92
- improve-flow-graph-dialog-and-card-interaction. */}
93
- <div className="text-[11px] text-[var(--text-tertiary)] font-mono break-all" title={flowSource}>
94
- {flowSource}
95
- </div>
96
- <div className="h-[60vh] overflow-y-auto">
97
- {state.kind === "loading" && (
98
- <div className="text-xs text-[var(--text-muted)]">Loading…</div>
99
- )}
100
- {state.kind === "error" && (
101
- <div className="text-xs text-red-400">⚠ {state.error}</div>
102
- )}
103
- {state.kind === "loaded" && (
104
- <MarkdownContent content={"```yaml\n" + state.content + "\n```"} />
105
- )}
106
- </div>
107
- </Dialog>
108
- </>
33
+ <button
34
+ type="button"
35
+ onClick={(e) => {
36
+ e.stopPropagation();
37
+ openInEditor(flowSource);
38
+ }}
39
+ className="transition-colors p-0.5 rounded inline-flex items-center text-[var(--text-tertiary)] hover:text-blue-400 hover:bg-[var(--bg-surface)]"
40
+ title={t("openFlowYamlInEditor", { name: flowName }, `Open ${flowName} YAML in editor`)}
41
+ >
42
+ <Icon path={mdiFileDocumentOutline} size={0.5} />
43
+ </button>
109
44
  );
110
45
  }
@@ -24,16 +24,21 @@ import {
24
24
  useSessionData,
25
25
  } from "@blackbelt-technology/dashboard-plugin-runtime";
26
26
  import { FlowLaunchDialog } from "./FlowLaunchDialog.js";
27
+ import { makeSafeSend, type PluginSend } from "./send-safe.js";
27
28
 
28
29
  // ── Helpers ────────────────────────────────────────────────────────
29
30
 
31
+ // Every flow action routes through here, so the discard is stated once at the
32
+ // shared seam rather than at each of the five call sites. A dropped
33
+ // `flow_management` message otherwise leaves the UI showing a run the server
34
+ // never started. See change: cleanup-client-plugin-promises.
30
35
  function dispatchFlowAction(
31
- send: (msg: unknown) => void,
36
+ send: PluginSend,
32
37
  sessionId: string,
33
38
  action: string,
34
39
  opts?: { flowName?: string; task?: string; description?: string },
35
40
  ): void {
36
- send({
41
+ makeSafeSend(send)({
37
42
  type: "flow_management",
38
43
  sessionId,
39
44
  action,
@@ -59,6 +64,9 @@ interface RouteProps {
59
64
  export function FlowsListRoute({ session, onClose }: RouteProps) {
60
65
  const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
61
66
  const send = usePluginSend();
67
+ // Dialog `onSelect` cannot own the send promise — discard it explicitly.
68
+ // See change: cleanup-client-plugin-promises.
69
+ const dispatch = makeSafeSend(send);
62
70
  const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
63
71
  const commands = useSessionData<CommandInfo[]>(session.id, "commandsList") ?? [];
64
72
  const [launchTarget, setLaunchTarget] = useState<FlowInfo | null>(null);
@@ -112,17 +120,17 @@ export function FlowsListRoute({ session, onClose }: RouteProps) {
112
120
  // Send the user to the /flows:new route via pluginRouter.
113
121
  // Until pluginRouter wiring lands, just open the new dialog
114
122
  // inline by closing this and dispatching the new command.
115
- send({ type: "send_prompt", sessionId: session.id, text: "/flows:new" });
123
+ dispatch({ type: "send_prompt", sessionId: session.id, text: "/flows:new" });
116
124
  onClose();
117
125
  return;
118
126
  }
119
127
  if (value === "__edit__") {
120
- send({ type: "send_prompt", sessionId: session.id, text: "/flows:edit" });
128
+ dispatch({ type: "send_prompt", sessionId: session.id, text: "/flows:edit" });
121
129
  onClose();
122
130
  return;
123
131
  }
124
132
  if (value === "__delete__") {
125
- send({ type: "send_prompt", sessionId: session.id, text: "/flows:delete" });
133
+ dispatch({ type: "send_prompt", sessionId: session.id, text: "/flows:delete" });
126
134
  onClose();
127
135
  return;
128
136
  }
@@ -24,13 +24,15 @@
24
24
  *
25
25
  * See change: pluginize-flows-via-registry.
26
26
  */
27
- import { useMemo } from "react";
27
+
28
+ import { useSessionEvents } from "@blackbelt-technology/dashboard-plugin-runtime";
28
29
  import type {
29
- FlowState,
30
30
  DashboardEvent,
31
+ FlowState,
31
32
  } from "@blackbelt-technology/pi-dashboard-shared/types.js";
32
- import { useSessionEvents } from "@blackbelt-technology/dashboard-plugin-runtime";
33
+ import { useMemo } from "react";
33
34
  import { isFlowEvent, reduceFlowEvent } from "../reducer.js";
35
+ import { toEventTime } from "./flow-idle-state.js";
34
36
 
35
37
  /** Shape exposed to flows-plugin components for a single session. */
36
38
  export interface FlowsSessionState {
@@ -42,6 +44,14 @@ export interface FlowsSessionState {
42
44
  * (FlowDashboard's multi-flow tab bar).
43
45
  */
44
46
  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
+ 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
+ /** Latest start pi-flows refused (`flow_complete` status `rejected`) (D7). */
54
+ lastRejection?: { flowName: string; reason?: string; timestamp: number };
45
55
  }
46
56
 
47
57
  const EMPTY_STATE: FlowsSessionState = Object.freeze({
@@ -70,6 +80,9 @@ export function reduceFlowsSessionState(
70
80
  let flowState: FlowState | null = null;
71
81
  let flowStates: Map<string, FlowState> = new Map();
72
82
  let flowStatesMutated = false;
83
+ let lastFlowStartedAt: number | undefined;
84
+ let lastAutonomousMode: boolean | undefined;
85
+ let lastRejection: FlowsSessionState["lastRejection"];
73
86
 
74
87
  // Diagnostic counter for C1 — see fix-flows-plugin-polish. Gated to dev.
75
88
  let flowEventCount = 0;
@@ -77,6 +90,20 @@ export function reduceFlowsSessionState(
77
90
  for (const event of events) {
78
91
  if (isFlowEvent(event.eventType)) {
79
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
+ };
106
+ }
80
107
  flowState = reduceFlowEvent(flowState, event);
81
108
  if (flowState) {
82
109
  if (!flowStatesMutated) {
@@ -109,13 +136,22 @@ export function reduceFlowsSessionState(
109
136
  }
110
137
  }
111
138
 
112
- if (flowState === null && flowStates.size === 0) {
139
+ if (
140
+ flowState === null &&
141
+ flowStates.size === 0 &&
142
+ lastFlowStartedAt === undefined &&
143
+ lastAutonomousMode === undefined &&
144
+ lastRejection === undefined
145
+ ) {
113
146
  return EMPTY_STATE;
114
147
  }
115
148
 
116
149
  return {
117
150
  flowState,
118
151
  flowStates,
152
+ lastFlowStartedAt,
153
+ lastAutonomousMode,
154
+ lastRejection,
119
155
  };
120
156
  }
121
157
 
@@ -38,11 +38,11 @@ export function FlowsSettings(): React.ReactElement {
38
38
  await send({ type: "plugin_config_write", id: "flows", config: { editFlow: valuesRef.current } });
39
39
  }, [send]);
40
40
  const reset = useCallback(() => setEditFlow(baseRef.current), []);
41
- useSettingsDraftSource({ id: "plugin:flows", page: "plugins", isDirty, commit, reset });
41
+ useSettingsDraftSource({ id: "plugin:flows", isDirty, commit, reset });
42
42
 
43
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>
44
+ // No self-header: the host owns identity + status chrome (design D1).
45
+ <div>
46
46
  <p className="text-xs text-[var(--text-tertiary)] mb-3">
47
47
  Multi-agent workflow orchestration. Applies globally; sessions inherit this default.
48
48
  </p>
@@ -63,6 +63,6 @@ export function FlowsSettings(): React.ReactElement {
63
63
  </span>
64
64
  </span>
65
65
  </label>
66
- </section>
66
+ </div>
67
67
  );
68
68
  }
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  usePluginSend,
3
3
  useSessionData,
4
+ useSessionEvents,
4
5
  useT,
5
6
  useUiPrimitive,
6
7
  } from "@blackbelt-technology/dashboard-plugin-runtime";
@@ -13,14 +14,41 @@ import type {
13
14
  FlowInfo,
14
15
  FlowState,
15
16
  } from "@blackbelt-technology/pi-dashboard-shared/types.js";
16
- import { mdiPencil, mdiPlay } from "@mdi/js";
17
+ import { mdiEyeOutline, mdiPencil, mdiPlay } from "@mdi/js";
17
18
  import { Icon } from "@mdi/react";
18
- import React, { useEffect, useRef, useState } from "react";
19
+ import React, { useEffect, useMemo, useRef, useState } from "react";
19
20
  import { FlowActivityBadge } from "./FlowActivityBadge.js";
20
21
  import { FlowAuthorPromptDialog } from "./FlowAuthorPromptDialog.js";
21
22
  import { FlowLaunchDialog } from "./FlowLaunchDialog.js";
22
23
  import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
23
24
  import type { FlowsPluginConfig } from "./FlowsSettings.js";
25
+ import { newAttachmentId, setAttachment } from "./flow-attach-store.js";
26
+ import { makeSafeSend } from "./send-safe.js";
27
+
28
+ /** Open flow… — disabled (with tooltip) while any flow runs. See change:
29
+ * attach-flow-before-run (D7). */
30
+ function OpenFlowButton({ disabled, onClick }: { disabled: boolean; onClick: () => void }) {
31
+ const t = useT();
32
+ return (
33
+ <button
34
+ onClick={(e) => { e.stopPropagation(); onClick(); }}
35
+ disabled={disabled}
36
+ title={disabled ? t("openFlowDisabledRunning", undefined, "A flow is running") : undefined}
37
+ className="text-[10px] px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-secondary)] hover:bg-[var(--bg-hover)] disabled:opacity-50 disabled:cursor-not-allowed"
38
+ data-testid="flows-open-button"
39
+ >
40
+ <Icon path={mdiEyeOutline} size={0.4} className="inline mr-0.5" />{t("openFlowButton", undefined, "Open flow…")}
41
+ </button>
42
+ );
43
+ }
44
+
45
+ function isAnyFlowRunning(
46
+ flowState: FlowState | null | undefined,
47
+ flowStates: ReadonlyMap<string, FlowState> | undefined,
48
+ ): boolean {
49
+ if (flowState?.status === "running") return true;
50
+ return flowStates ? Array.from(flowStates.values()).some((s) => s.status === "running") : false;
51
+ }
24
52
 
25
53
  export function SessionFlowActions({
26
54
  flows,
@@ -29,7 +57,9 @@ export function SessionFlowActions({
29
57
  onFlowAction,
30
58
  onEditFlow,
31
59
  flowState,
60
+ flowStates,
32
61
  onAbortFlow,
62
+ onOpenFlow,
33
63
  }: {
34
64
  flows: FlowInfo[];
35
65
  /** Edit-mode on → show the New / Edit launcher (authoring via the skill). */
@@ -46,11 +76,17 @@ export function SessionFlowActions({
46
76
  flowState?: FlowState | null;
47
77
  /** Dispatch flow_control abort. Called by the running-flow pill's Abort button. */
48
78
  onAbortFlow?: () => void;
79
+ /** All flow states this session — Open is disabled while any is running. */
80
+ flowStates?: ReadonlyMap<string, FlowState>;
81
+ /** Attach a flow to the session flow slot before it runs. See change:
82
+ * attach-flow-before-run (D7). */
83
+ onOpenFlow?: (flow: FlowInfo) => void;
49
84
  }) {
50
85
  const t = useT();
51
86
  const ConfirmDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.confirmDialog);
52
87
  const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
53
88
  const [pickerOpen, setPickerOpen] = useState(false);
89
+ const [openPickerOpen, setOpenPickerOpen] = useState(false);
54
90
  const [editPickerOpen, setEditPickerOpen] = useState(false);
55
91
  // After picking from the edit launcher, capture intent before launching the skill.
56
92
  const [authorTarget, setAuthorTarget] = useState<{ mode: "new" | "edit"; flowName?: string } | null>(null);
@@ -78,6 +114,8 @@ export function SessionFlowActions({
78
114
 
79
115
  if (flows.length === 0 && !editMode && !badgeProps) return null;
80
116
 
117
+ const anyRunning = isAnyFlowRunning(flowState, flowStates);
118
+
81
119
  const flowOptions: SelectOption[] = flows.map((f) => ({
82
120
  value: f.name,
83
121
  label: f.name,
@@ -107,6 +145,9 @@ export function SessionFlowActions({
107
145
  <Icon path={mdiPlay} size={0.4} className="inline mr-0.5" />{t("runFlowButton", undefined, "Run Flow...")}
108
146
  </button>
109
147
  )}
148
+ {onOpenFlow && flows.length > 0 && (
149
+ <OpenFlowButton disabled={anyRunning} onClick={() => setOpenPickerOpen(true)} />
150
+ )}
110
151
  {editMode && (
111
152
  <button
112
153
  onClick={(e) => { e.stopPropagation(); setEditPickerOpen(true); }}
@@ -155,6 +196,22 @@ export function SessionFlowActions({
155
196
  />
156
197
  )}
157
198
 
199
+ {/* Open: pick flow → attach it to the flow slot (not started). */}
200
+ {openPickerOpen && onOpenFlow && (
201
+ <SearchableSelectDialog
202
+ title={t("openFlowDialogTitle", undefined, "Open flow")}
203
+ options={flowOptions}
204
+ placeholder={t("searchFlows", undefined, "Search flows...")}
205
+ emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
206
+ onSelect={(value) => {
207
+ const flow = flows.find((f) => f.name === value);
208
+ if (flow) onOpenFlow(flow);
209
+ setOpenPickerOpen(false);
210
+ }}
211
+ onCancel={() => setOpenPickerOpen(false)}
212
+ />
213
+ )}
214
+
158
215
  {/* New / Edit: pick an existing flow or "new" → launch the edit-flow skill */}
159
216
  {editPickerOpen && (
160
217
  <SearchableSelectDialog
@@ -229,8 +286,13 @@ export function SessionFlowActions({
229
286
  export function SessionFlowActionsClaim({ session }: { session: DashboardSession }) {
230
287
  const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
231
288
  const commands = useSessionData<CommandInfo[]>(session.id, "commandsList") ?? [];
232
- const { flowState } = useFlowsSessionState(session.id);
289
+ const { flowState, flowStates, lastFlowStartedAt } = useFlowsSessionState(session.id);
290
+ const events = useSessionEvents(session.id);
233
291
  const send = usePluginSend();
292
+ // The edit-mode reconcile effect and the author-prompt handler cannot own the
293
+ // send promise — discard it explicitly.
294
+ // See change: cleanup-client-plugin-promises.
295
+ const dispatch = useMemo(() => makeSafeSend(send), [send]);
234
296
  const config = usePluginConfig<FlowsPluginConfig>();
235
297
  const editMode = config.editFlow ?? false;
236
298
 
@@ -245,8 +307,8 @@ export function SessionFlowActionsClaim({ session }: { session: DashboardSession
245
307
  if (flows.length === 0) return; // wait until flows-plugin is available
246
308
  if (reconciledRef.current === editMode) return;
247
309
  reconciledRef.current = editMode;
248
- send({ type: "flow_management", sessionId: session.id, action: "set-edit-mode", enabled: editMode });
249
- }, [flows.length, editMode, session.id, send]);
310
+ dispatch({ type: "flow_management", sessionId: session.id, action: "set-edit-mode", enabled: editMode });
311
+ }, [flows.length, editMode, session.id, dispatch]);
250
312
 
251
313
  // Render when there's a flow active OR action buttons are available.
252
314
  if (flows.length === 0 && !editMode && !flowState) return null;
@@ -257,6 +319,18 @@ export function SessionFlowActionsClaim({ session }: { session: DashboardSession
257
319
  editMode={editMode}
258
320
  hasFlowsDelete={hasFlowsDelete}
259
321
  flowState={flowState}
322
+ flowStates={flowStates}
323
+ onOpenFlow={(flow) =>
324
+ // Baseline = newest flow_started seen now; null on an empty (not yet
325
+ // replayed) stream — the flow slot resolves it from the first batch.
326
+ // See change: attach-flow-before-run (D4).
327
+ setAttachment(session.id, {
328
+ id: newAttachmentId(),
329
+ name: flow.name,
330
+ source: flow.source,
331
+ baselineStartedAt: events.length > 0 ? (lastFlowStartedAt ?? 0) : null,
332
+ })
333
+ }
260
334
  onAbortFlow={() => send({ type: "flow_control", sessionId: session.id, action: "abort" })}
261
335
  onEditFlow={(flowName, instruction) => {
262
336
  const intent = instruction.trim();
@@ -267,7 +341,7 @@ export function SessionFlowActionsClaim({ session }: { session: DashboardSession
267
341
  ? `/skill:manage-flows ${flowName}\n\n${intent}`
268
342
  : `/skill:manage-flows ${flowName}`
269
343
  : `/skill:manage-flows ${intent}`;
270
- send({ type: "send_prompt", sessionId: session.id, text });
344
+ dispatch({ type: "send_prompt", sessionId: session.id, text });
271
345
  }}
272
346
  onFlowAction={(action, opts) =>
273
347
  send({