@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
@@ -1,6 +1,8 @@
1
1
  import {
2
2
  type InteractiveUiRequestSnapshot,
3
3
  usePluginSend,
4
+ useSessionData,
5
+ useSessionEvents,
4
6
  useSessionInteractiveRequests,
5
7
  useT,
6
8
  useUiPrimitiveOrNull,
@@ -8,22 +10,100 @@ import {
8
10
  import { BreadcrumbSlot } from "@blackbelt-technology/pi-dashboard-client-utils/extension-ui/BreadcrumbSlot";
9
11
  import { useMobile } from "@blackbelt-technology/pi-dashboard-client-utils/useMobile";
10
12
  import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
11
- import type { DashboardSession, FlowState, ImageContent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
12
- import { mdiChevronDown, mdiChevronRight, mdiChevronUp, mdiFileDocumentOutline, mdiLoading, mdiRobotOutline, mdiStop } from "@mdi/js";
13
+ import type { DashboardSession, FlowInfo, FlowState, ImageContent } from "@blackbelt-technology/pi-dashboard-shared/types.js";
14
+ import { mdiChevronDown, mdiChevronRight, mdiChevronUp, mdiClose, mdiLoading, mdiPlay, mdiRobotOutline, mdiStop } from "@mdi/js";
13
15
  import { Icon } from "@mdi/react";
14
16
  import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
15
17
  import { FlowAgentCard } from "./FlowAgentCard.js";
16
18
  import { FlowGraph, flowStateToGraphSteps } from "./FlowGraph.js";
19
+ import { FlowLaunchDialog } from "./FlowLaunchDialog.js";
17
20
  import { FlowQuestionCard } from "./FlowQuestionCard.js";
18
21
  import { FlowQuestionTranscriptPill } from "./FlowQuestionTranscriptPill.js";
19
22
  import { FlowSummary } from "./FlowSummary.js";
20
- import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
23
+ import { type FlowsSessionState, useFlowsSessionState } from "./FlowsSessionStateContext.js";
21
24
  import { type FlowTab, FlowTabBar } from "./FlowTabBar.js";
22
25
  import { FlowYamlPopoverButton } from "./FlowYamlPopoverButton.js";
26
+ import { clearAttachment, resolveBaseline, useFlowAttachment } from "./flow-attach-store.js";
27
+ import { FLOW_CARD_GRID_CLASS, FLOW_CARD_GRID_CONTAINER_CLASS } from "./flow-card-grid.js";
23
28
  import { useFlowCollapsePersisted } from "./flow-collapse-storage.js";
29
+ import { fetchFlowFile, type FlowNodeFiles, useFlowNodeFiles, withNodeFiles } from "./flow-files.js";
30
+ import { buildIdleFlowState, type FlowAttachment, type FlowSlot, type IdleLoad, resolveFlowSlot } from "./flow-idle-state.js";
31
+ import { makeSafeSend } from "./send-safe.js";
24
32
 
33
+ /**
34
+ * Selection survives run progress; it resets only when the displayed flow
35
+ * changes (tab switch / replacement) or the selected step no longer exists.
36
+ * See change: attach-flow-before-run (D9).
37
+ */
38
+ function useSelectionReset(
39
+ displayState: FlowState,
40
+ selectedStepId: string | null,
41
+ setSelectedStepId: (id: string | null) => void,
42
+ ) {
43
+ const prevNameRef = useRef(displayState.flowName);
44
+ useEffect(() => {
45
+ if (prevNameRef.current !== displayState.flowName) {
46
+ prevNameRef.current = displayState.flowName;
47
+ setSelectedStepId(null);
48
+ return;
49
+ }
50
+ if (selectedStepId && !hasStep(displayState, selectedStepId)) setSelectedStepId(null);
51
+ }, [displayState, selectedStepId, setSelectedStepId]);
52
+ }
25
53
 
54
+ function hasStep(state: FlowState, stepId: string): boolean {
55
+ if (state.agents.has(stepId)) return true;
56
+ if (state.dagSteps?.some((s) => s.id === stepId)) return true;
57
+ return Array.from(state.agents.values()).some((a) => (a.stepId || a.agentName) === stepId);
58
+ }
26
59
 
60
+ /** Run `onEnter` when `isIdle` flips false → true (not on first mount). */
61
+ function useOnEnterIdle(isIdle: boolean, onEnter: () => void) {
62
+ const prevRef = useRef(isIdle);
63
+ useEffect(() => {
64
+ if (isIdle && !prevRef.current) onEnter();
65
+ prevRef.current = isIdle;
66
+ }, [isIdle, onEnter]);
67
+ }
68
+
69
+ /** Idle header controls: rejection reason, Run, Close. */
70
+ function IdleControls({ idle }: { idle: FlowDashboardIdle }) {
71
+ const t = useT();
72
+ return (
73
+ <>
74
+ {idle.rejectionReason && (
75
+ <span className="text-[10px] text-red-400 truncate" data-testid="flow-run-rejected">
76
+ {idle.rejectionReason}
77
+ </span>
78
+ )}
79
+ <button
80
+ onClick={(e) => { e.stopPropagation(); idle.onRun(); }}
81
+ disabled={idle.runDisabled}
82
+ className="text-[10px] px-1.5 py-0.5 rounded border border-blue-500/30 text-blue-400 hover:bg-blue-500/10 disabled:opacity-50 disabled:cursor-not-allowed"
83
+ data-testid="flow-idle-run"
84
+ >
85
+ <Icon path={mdiPlay} size={0.4} className="inline mr-0.5" />{t("runFlow", undefined, "Run")}
86
+ </button>
87
+ <button
88
+ onClick={(e) => { e.stopPropagation(); idle.onClose(); }}
89
+ className="text-[10px] px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-tertiary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-hover)]"
90
+ data-testid="flow-idle-close"
91
+ >
92
+ <Icon path={mdiClose} size={0.4} className="inline mr-0.5" />{t("closeAttachedFlow", undefined, "Close")}
93
+ </button>
94
+ </>
95
+ );
96
+ }
97
+
98
+ /** Not-started (attached) mode controls. See change: attach-flow-before-run (D2). */
99
+ interface FlowDashboardIdle {
100
+ onRun: () => void;
101
+ onClose: () => void;
102
+ /** Run submitted and not yet started/rejected. */
103
+ runDisabled?: boolean;
104
+ /** Reason of the latest rejected start for this flow, shown inline. */
105
+ rejectionReason?: string;
106
+ }
27
107
 
28
108
  export function FlowDashboard({
29
109
  flowState,
@@ -34,6 +114,8 @@ export function FlowDashboard({
34
114
  onSendPrompt,
35
115
  session,
36
116
  sessionId,
117
+ idle,
118
+ nodeFiles,
37
119
  }: {
38
120
  flowState: FlowState;
39
121
  /** All flow states (one per distinct flow run this session) for tab navigation */
@@ -47,6 +129,11 @@ export function FlowDashboard({
47
129
  /** Session id — threaded so child cards can render popout URLs and the
48
130
  upper-slot question card can submit responses. See change: add-flow-agent-popout. */
49
131
  sessionId?: string;
132
+ /** Set → render the not-started (attached) panel; never forwards to the
133
+ * summary, no Abort, no tabs. See change: attach-flow-before-run (D2). */
134
+ idle?: FlowDashboardIdle;
135
+ /** Reported agent / handler file paths, from the claim's poll. */
136
+ nodeFiles?: FlowNodeFiles | null;
50
137
  }) {
51
138
  const isMobile = useMobile();
52
139
  const t = useT();
@@ -66,13 +153,13 @@ export function FlowDashboard({
66
153
 
67
154
  // Build tab list from flowStates
68
155
  const tabs: FlowTab[] = useMemo(() => {
69
- if (!flowStates || flowStates.size <= 1) return [];
156
+ if (idle || !flowStates || flowStates.size <= 1) return [];
70
157
  return Array.from(flowStates.keys()).map(name => ({
71
158
  id: name,
72
159
  label: name,
73
160
  isActive: name === flowState.flowName,
74
161
  }));
75
- }, [flowStates, flowState.flowName]);
162
+ }, [idle, flowStates, flowState.flowName]);
76
163
 
77
164
  // Follow mode: auto-switch to latest active flow
78
165
  useEffect(() => {
@@ -84,22 +171,31 @@ export function FlowDashboard({
84
171
 
85
172
  // Determine which flow state to display based on active tab
86
173
  const displayState = useMemo(() => {
87
- if (flowStates && activeTabId !== flowState.flowName) {
174
+ if (!idle && flowStates && activeTabId !== flowState.flowName) {
88
175
  return flowStates.get(activeTabId) || flowState;
89
176
  }
90
177
  return flowState;
91
- }, [flowStates, activeTabId, flowState]);
178
+ }, [idle, flowStates, activeTabId, flowState]);
92
179
 
93
- const agents = Array.from(displayState.agents.values());
180
+ // Agent / handler file paths so every card (idle, pending, running) can open
181
+ // its file. See change: attach-flow-before-run.
182
+ const agents = Array.from(withNodeFiles(displayState, nodeFiles ?? null).agents.values());
94
183
  const allAgents = Array.from(flowState.agents.values());
95
184
 
96
185
  const handleSelectStep = useCallback((stepId: string) => {
97
186
  setSelectedStepId((prev) => (prev === stepId ? null : stepId));
98
187
  }, []);
99
- // Selection is ephemeral; reset when the displayed agent set changes.
100
- useEffect(() => {
188
+ useSelectionReset(displayState, selectedStepId, setSelectedStepId);
189
+ // Entering idle (new attach / re-attach) starts fresh; leaving idle for live
190
+ // keeps everything (same instance). See change: attach-flow-before-run (D2).
191
+ const flowName = flowState.flowName;
192
+ const resetOnEnterIdle = useCallback(() => {
101
193
  setSelectedStepId(null);
102
- }, [displayState.agents]);
194
+ setGraphOpen(false);
195
+ setActiveTabId(flowName);
196
+ setFollowMode(true);
197
+ }, [flowName]);
198
+ useOnEnterIdle(!!idle, resetOnEnterIdle);
103
199
  // Esc clears selection (Dialog handles its own Esc independently).
104
200
  useEffect(() => {
105
201
  if (!selectedStepId) return;
@@ -121,8 +217,11 @@ export function FlowDashboard({
121
217
  }, [selectedStepId]);
122
218
  const doneCount = allAgents.filter(a => a.status === "complete" || a.status === "error" || a.status === "blocked").length;
123
219
  const totalCount = allAgents.length;
124
- const isRunning = flowState.status === "running";
125
- const isComplete = !isRunning;
220
+ const isRunning = !idle && flowState.status === "running";
221
+ const isComplete = !idle && !isRunning;
222
+ const progressText = idle
223
+ ? t("flowNotStarted", undefined, "not started")
224
+ : t("stepsCount", { done: doneCount, total: totalCount }, `${doneCount}/${totalCount} steps`);
126
225
 
127
226
  // After completion, show summary. Forward sessionId so the summary's per-session
128
227
  // collapse state persists (the hook no-ops without a session id).
@@ -161,7 +260,7 @@ export function FlowDashboard({
161
260
  >
162
261
  <span className="text-blue-400 text-sm">π</span>
163
262
  <span className="text-sm text-[var(--text-primary)] truncate flex-1">
164
- {flowState.flowName} · {doneCount}/{totalCount} steps
263
+ {flowState.flowName} · {progressText}
165
264
  </span>
166
265
  <span className="text-[10px] text-[var(--text-tertiary)]">tap to expand</span>
167
266
  </div>
@@ -169,7 +268,12 @@ export function FlowDashboard({
169
268
  }
170
269
 
171
270
  return (
172
- <div ref={rootRef} className="bg-[var(--bg-secondary)] border-b border-[var(--border-subtle)] px-3 py-2">
271
+ <div
272
+ ref={rootRef}
273
+ data-testid="flow-dashboard"
274
+ data-flow-mode={idle ? "idle" : "live"}
275
+ className="bg-[var(--bg-secondary)] border-b border-[var(--border-subtle)] px-3 py-2"
276
+ >
173
277
  {/* Header */}
174
278
  <div className="flex items-center gap-2 mb-2">
175
279
  <span
@@ -185,7 +289,7 @@ export function FlowDashboard({
185
289
  )}
186
290
  <span className="text-sm text-[var(--text-primary)] truncate flex-1">
187
291
  {flowState.flowName}
188
- <span className="text-[var(--text-tertiary)] ml-1.5">{t("stepsCount", { done: doneCount, total: totalCount }, `${doneCount}/${totalCount} steps`)}</span>
292
+ <span className="text-[var(--text-tertiary)] ml-1.5">{progressText}</span>
189
293
  </span>
190
294
 
191
295
  {/* Controls */}
@@ -200,6 +304,7 @@ export function FlowDashboard({
200
304
  >
201
305
  <Icon path={mdiRobotOutline} size={0.4} className="inline mr-0.5" />AUTO
202
306
  </button>
307
+ {idle && <IdleControls idle={idle} />}
203
308
  {isRunning && (
204
309
  <button
205
310
  onClick={(e) => { e.stopPropagation(); onAbort(); }}
@@ -240,6 +345,7 @@ export function FlowDashboard({
240
345
  <FlowQuestionsSection
241
346
  sessionId={sessionId}
242
347
  flowId={displayState.flowName}
348
+ pendingOnly={!!idle}
243
349
  />
244
350
  )}
245
351
 
@@ -255,6 +361,7 @@ export function FlowDashboard({
255
361
  <FlowYamlPopoverButton
256
362
  flowSource={displayState.flowSource}
257
363
  flowName={displayState.flowName}
364
+ sessionId={sessionId}
258
365
  />
259
366
  </div>
260
367
  )}
@@ -278,21 +385,21 @@ export function FlowDashboard({
278
385
  </Dialog>
279
386
  )}
280
387
 
281
- {/* Agent card grid — detailed per-agent info */}
282
- <div
283
- className="grid gap-2 mt-2"
284
- style={{ gridTemplateColumns: `repeat(auto-fill, minmax(200px, 1fr))` }}
285
- >
286
- {agents.map(agent => (
287
- <FlowAgentCard
288
- key={agent.stepId || agent.agentName}
289
- agent={agent}
290
- session={session}
291
- sessionId={sessionId}
292
- selected={selectedStepId === (agent.stepId || agent.agentName)}
293
- onSelect={handleSelectStep}
294
- />
295
- ))}
388
+ {/* Agent card grid — detailed per-agent info. Geometry comes from the
389
+ shared helper; the wrapper is the query container (design D1/D5). */}
390
+ <div className={`${FLOW_CARD_GRID_CONTAINER_CLASS} mt-2`}>
391
+ <div className={FLOW_CARD_GRID_CLASS}>
392
+ {agents.map(agent => (
393
+ <FlowAgentCard
394
+ key={agent.stepId || agent.agentName}
395
+ agent={agent}
396
+ session={session}
397
+ sessionId={sessionId}
398
+ selected={selectedStepId === (agent.stepId || agent.agentName)}
399
+ onSelect={handleSelectStep}
400
+ />
401
+ ))}
402
+ </div>
296
403
  </div>
297
404
  </div>
298
405
  </div>
@@ -331,12 +438,19 @@ const FLOW_QUESTION_TRANSCRIPT_CAP = 10;
331
438
  function FlowQuestionsSection({
332
439
  sessionId,
333
440
  flowId,
441
+ pendingOnly = false,
334
442
  }: {
335
443
  sessionId: string;
336
444
  flowId: string;
445
+ /** Idle panel: only still-pending questions (no earlier-run transcript).
446
+ * See change: attach-flow-before-run (D2). */
447
+ pendingOnly?: boolean;
337
448
  }) {
338
449
  const requests = useSessionInteractiveRequests(sessionId);
339
450
  const send = usePluginSend();
451
+ // Card callbacks cannot own the send promise — discard it explicitly.
452
+ // See change: cleanup-client-plugin-promises.
453
+ const dispatch = useMemo(() => makeSafeSend(send), [send]);
340
454
 
341
455
  const queue = useMemo<InteractiveUiRequestSnapshot[]>(() => {
342
456
  const out: InteractiveUiRequestSnapshot[] = [];
@@ -346,10 +460,11 @@ function FlowQuestionsSection({
346
460
  | undefined;
347
461
  if (cmp?.type !== "flow-question") continue;
348
462
  if (cmp?.props?.flowId !== flowId) continue;
463
+ if (pendingOnly && req.status !== "pending") continue;
349
464
  out.push(req);
350
465
  }
351
466
  return out.slice(-FLOW_QUESTION_TRANSCRIPT_CAP);
352
- }, [requests, flowId]);
467
+ }, [requests, flowId, pendingOnly]);
353
468
 
354
469
  if (queue.length === 0) return null;
355
470
 
@@ -363,7 +478,7 @@ function FlowQuestionsSection({
363
478
  const question = typeof props.question === "string" ? props.question : "";
364
479
  if (req.status === "pending") {
365
480
  const submit = (answer: string) => {
366
- send({
481
+ dispatch({
367
482
  type: "prompt_response",
368
483
  sessionId,
369
484
  promptId: req.requestId,
@@ -372,7 +487,7 @@ function FlowQuestionsSection({
372
487
  });
373
488
  };
374
489
  const dismiss = () => {
375
- send({ type: "prompt_cancel", sessionId, promptId: req.requestId });
490
+ dispatch({ type: "prompt_cancel", sessionId, promptId: req.requestId });
376
491
  };
377
492
  return (
378
493
  <FlowQuestionCard
@@ -409,50 +524,297 @@ function FlowQuestionsSection({
409
524
 
410
525
  type FlowQuestionCardType = "select" | "input" | "confirm" | "editor" | "multiselect";
411
526
 
527
+ const EMPTY_FLOWS: FlowInfo[] = [];
528
+ const LOADING: IdleLoad = Object.freeze({ kind: "loading" }) as IdleLoad;
529
+
530
+ /**
531
+ * Fetch + build the attached flow's idle state once per attach (id + source),
532
+ * cancel-safe on unmount (FlowAgentCard fetch pattern). The built state is kept
533
+ * in React state, so its `agents` / `dagSteps` references are stable.
534
+ *
535
+ * Retries once when the bridge's report arrives (`reportReady` false → true):
536
+ * a runtime-registered flow dir 403s on the host fallback until then, and that
537
+ * failure must not outlive the report. Bounded — the report flips at most once
538
+ * per session. See change: attach-flow-before-run (D6, D11).
539
+ */
540
+ function useAttachedFlowState(attachment: FlowAttachment | null, sessionId: string, reportReady: boolean): IdleLoad {
541
+ const t = useT();
542
+ const name = attachment?.name ?? "";
543
+ const source = attachment?.source;
544
+ const key = attachment ? `${attachment.id}\u0000${source ?? ""}` : "";
545
+ const [state, setState] = useState<{ key: string; load: IdleLoad } | null>(null);
546
+
547
+ useEffect(() => {
548
+ if (!key || !source) return;
549
+ let cancelled = false;
550
+ const fail = (message: string) => {
551
+ if (!cancelled) setState({ key, load: { kind: "error", message } });
552
+ };
553
+ // Plugin file endpoint (runtime-registered flow dirs) → host fallback.
554
+ fetchFlowFile(sessionId, source)
555
+ .then((content) => {
556
+ if (!cancelled) setState({ key, load: buildIdleFlowState(content, { name, source }) });
557
+ })
558
+ .catch((err: unknown) => fail(err instanceof Error ? err.message : String(err)));
559
+ return () => {
560
+ cancelled = true;
561
+ };
562
+ }, [key, name, source, sessionId, reportReady]);
563
+
564
+ if (!attachment) return LOADING;
565
+ if (!source) {
566
+ return { kind: "error", message: t("flowDefinitionLoadError", undefined, "Flow definition file unavailable") };
567
+ }
568
+ if (!state || state.key !== key) return LOADING;
569
+ return state.load;
570
+ }
571
+
572
+ type Translate = ReturnType<typeof useT>;
573
+
574
+ function slotMessage(slot: FlowSlot, t: Translate): string {
575
+ if (slot.mode === "loading") return t("flowLoading", undefined, "loading…");
576
+ if (slot.error?.kind === "unavailable") return t("flowNoLongerAvailable", undefined, "no longer available");
577
+ return slot.error?.message ?? "";
578
+ }
579
+
580
+ /**
581
+ * Idle Run state: launch dialog → pending until the panel leaves idle or a
582
+ * rejection for this flow newer than the submit arrives (compared on the event
583
+ * clock, never the browser clock). A new attach starts fresh.
584
+ * See change: attach-flow-before-run (D7).
585
+ */
586
+ function useIdleRun(
587
+ isIdle: boolean,
588
+ attachmentId: string | undefined,
589
+ flowName: string | undefined,
590
+ lastRejection: FlowsSessionState["lastRejection"],
591
+ ) {
592
+ const t = useT();
593
+ const [launchOpen, setLaunchOpen] = useState(false);
594
+ const [pendingAfter, setPendingAfter] = useState<number | null>(null);
595
+ const [rejectionReason, setRejectionReason] = useState<string | undefined>(undefined);
596
+ // Identity of the latest submission; a stale send failure must not touch a
597
+ // newer submission (or a new attach). Bumped on every submit and reset.
598
+ const submissionRef = useRef(0);
599
+ const reset = useCallback(() => {
600
+ submissionRef.current++;
601
+ setLaunchOpen(false);
602
+ setPendingAfter(null);
603
+ setRejectionReason(undefined);
604
+ }, []);
605
+ useEffect(() => {
606
+ if (!isIdle) reset();
607
+ }, [isIdle, reset]);
608
+ const attachRef = useRef(attachmentId);
609
+ useEffect(() => {
610
+ if (attachRef.current !== attachmentId) reset();
611
+ attachRef.current = attachmentId;
612
+ }, [attachmentId, reset]);
613
+ useEffect(() => {
614
+ if (pendingAfter === null || !lastRejection) return;
615
+ if (lastRejection.flowName !== flowName || lastRejection.timestamp <= pendingAfter) return;
616
+ setPendingAfter(null);
617
+ setRejectionReason(lastRejection.reason ?? t("flowRunRejected", undefined, "Start rejected"));
618
+ }, [lastRejection, pendingAfter, flowName, t]);
619
+ return {
620
+ launchOpen,
621
+ pending: pendingAfter !== null,
622
+ rejectionReason,
623
+ open: () => {
624
+ setRejectionReason(undefined);
625
+ setLaunchOpen(true);
626
+ },
627
+ cancel: () => setLaunchOpen(false),
628
+ /** Returns the submission id to pass to `sendFailed`. */
629
+ submitted: (): number => {
630
+ setLaunchOpen(false);
631
+ setPendingAfter(lastRejection?.timestamp ?? Number.NEGATIVE_INFINITY);
632
+ return ++submissionRef.current;
633
+ },
634
+ /** The run request never reached the server — no rejection will arrive.
635
+ * Ignored when a newer submission / attach superseded `submission`. */
636
+ sendFailed: (submission: number) => {
637
+ if (submission !== submissionRef.current) return;
638
+ setPendingAfter(null);
639
+ setRejectionReason(t("flowRunSendFailed", undefined, "Could not start the flow"));
640
+ },
641
+ };
642
+ }
643
+
644
+ /** Minimal header for an attached flow that is loading or failed to load. */
645
+ function FlowSlotMessage({
646
+ name,
647
+ message,
648
+ tone,
649
+ onClose,
650
+ }: {
651
+ name: string;
652
+ message: string;
653
+ tone: "muted" | "error";
654
+ onClose: () => void;
655
+ }) {
656
+ const t = useT();
657
+ return (
658
+ <div
659
+ data-testid="flow-slot-message"
660
+ data-tone={tone}
661
+ className="bg-[var(--bg-secondary)] border-b border-[var(--border-subtle)] px-3 py-2 flex items-center gap-2"
662
+ >
663
+ <span className="text-blue-400 text-sm font-medium">π</span>
664
+ <span className="text-sm text-[var(--text-primary)] truncate">{name}</span>
665
+ <span className={`text-[11px] truncate flex-1 ${tone === "error" ? "text-red-400" : "text-[var(--text-tertiary)]"}`}>
666
+ {message}
667
+ </span>
668
+ <button
669
+ onClick={(e) => { e.stopPropagation(); onClose(); }}
670
+ className="text-[10px] px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-tertiary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-hover)]"
671
+ data-testid="flow-idle-close"
672
+ >
673
+ <Icon path={mdiClose} size={0.4} className="inline mr-0.5" />{t("closeAttachedFlow", undefined, "Close")}
674
+ </button>
675
+ </div>
676
+ );
677
+ }
678
+
412
679
  /**
413
680
  * Slot-consumer wrapper for the `content-header-sticky` claim.
414
- * Self-derives flow state from useFlowsSessionState; selection state
415
- * and callbacks come from useFlowsUiState / pluginContext.send.
416
- * Returns null when no flow is active. See change:
417
- * pluginize-flows-via-registry.
681
+ * Self-derives flow state from useFlowsSessionState and the per-session
682
+ * attachment store, then resolves the slot: running flow → attached
683
+ * (not-started) flow → completed summary → nothing. One
684
+ * `<FlowDashboard key={flowName}>` keeps the instance across idle → live of the
685
+ * same flow and remounts for a different one. See changes:
686
+ * pluginize-flows-via-registry, attach-flow-before-run (D3, D4, D6-D8).
418
687
  */
419
688
  export function FlowDashboardClaim({ session }: { session: DashboardSession }) {
420
- const { flowState, flowStates } = useFlowsSessionState(session.id);
689
+ const sessionId = session.id;
690
+ const { flowState, flowStates, lastFlowStartedAt, lastAutonomousMode, lastRejection } =
691
+ useFlowsSessionState(sessionId);
692
+ const events = useSessionEvents(sessionId);
693
+ const flowsList = useSessionData<FlowInfo[]>(sessionId, "flowsList") ?? EMPTY_FLOWS;
694
+ const attachment = useFlowAttachment(sessionId);
695
+ // Reported agent / handler file paths. Polling lives here (not in the panel)
696
+ // because the panel does not render while the attached flow is loading or has
697
+ // failed; a late report must still be able to resolve that failure.
698
+ // See change: attach-flow-before-run (D11).
699
+ const nodeFiles = useFlowNodeFiles(sessionId);
700
+ const idleLoad = useAttachedFlowState(attachment, sessionId, nodeFiles !== null);
421
701
  const send = usePluginSend();
702
+ const t = useT();
703
+
704
+ const slot = resolveFlowSlot({
705
+ live: flowState,
706
+ liveStates: flowStates,
707
+ attachment,
708
+ idle: idleLoad,
709
+ lastFlowStartedAt,
710
+ flowsList,
711
+ });
712
+
713
+ // Baseline from the first non-empty snapshot when attached on an empty
714
+ // stream (replay arrives as one batch = the pre-attach history). (D4)
715
+ const hasEvents = events.length > 0;
716
+ useEffect(() => {
717
+ if (attachment && attachment.baselineStartedAt === null && hasEvents) {
718
+ resolveBaseline(sessionId, attachment.id, lastFlowStartedAt ?? 0);
719
+ }
720
+ }, [attachment, hasEvents, lastFlowStartedAt, sessionId]);
721
+
722
+ // A consumed attachment never lingers in storage; the delete is conditional
723
+ // on the id judged consumed, so another tab's fresh attach survives. (D4)
724
+ useEffect(() => {
725
+ if (attachment && slot.attachmentConsumed) clearAttachment(sessionId, attachment.id);
726
+ }, [attachment, slot.attachmentConsumed, sessionId]);
727
+
728
+ const attachedName = attachment?.name;
729
+ const isIdle = slot.mode === "idle";
730
+ const run = useIdleRun(isIdle, attachment?.id, attachedName, lastRejection);
731
+
732
+ // AUTO shows the last known value (engine default on). Shallow override keeps
733
+ // the memoized agents / dagSteps references. (D8)
734
+ const idleFlowState = isIdle ? slot.flowState : undefined;
735
+ const autonomousMode = lastAutonomousMode ?? true;
736
+ const idleDisplayState = useMemo(
737
+ () => (idleFlowState ? { ...idleFlowState, autonomousMode } : undefined),
738
+ [idleFlowState, autonomousMode],
739
+ );
422
740
 
423
- // Diagnostic logging — helps trace why the upper slot might be empty when
424
- // a flow is running. Gated to dev builds. See change: fix-flows-plugin-polish (C1).
425
741
  if (typeof import.meta !== "undefined" && (import.meta as { env?: { DEV?: boolean } }).env?.DEV) {
426
742
  // eslint-disable-next-line no-console
427
- console.debug(
428
- "[flows] FlowDashboardClaim render",
429
- {
430
- sessionId: session.id,
431
- hasFlowState: !!flowState,
432
- flowName: flowState?.flowName,
433
- flowStatus: flowState?.status,
434
- flowsCount: flowStates.size,
435
- },
436
- );
743
+ console.debug("[flows] FlowDashboardClaim render", {
744
+ sessionId,
745
+ mode: slot.mode,
746
+ flowName: slot.flowState?.flowName,
747
+ flowStatus: slot.flowState?.status,
748
+ flowsCount: flowStates.size,
749
+ });
437
750
  }
438
751
 
439
- if (!flowState) return null;
752
+ const flowControl = (action: string) => send({ type: "flow_control", sessionId, action });
753
+ const detach = () => {
754
+ if (attachment) clearAttachment(sessionId, attachment.id);
755
+ };
756
+
757
+ if (slot.mode === "none") return null;
758
+
759
+ if (slot.mode === "loading" || slot.mode === "error") {
760
+ return (
761
+ <FlowSlotMessage
762
+ name={attachedName ?? ""}
763
+ message={slotMessage(slot, t)}
764
+ tone={slot.mode === "error" ? "error" : "muted"}
765
+ onClose={detach}
766
+ />
767
+ );
768
+ }
440
769
 
441
- const flowControl = (action: string) =>
442
- send({ type: "flow_control", sessionId: session.id, action });
770
+ const shown = idleDisplayState ?? slot.flowState!;
771
+ const flowInfo = flowsList.find((f) => f.name === shown.flowName);
443
772
 
444
773
  return (
445
- <FlowDashboard
446
- flowState={flowState}
447
- flowStates={flowStates as Map<string, FlowState>}
448
- session={session}
449
- sessionId={session.id}
450
- onAbort={() => flowControl("abort")}
451
- onToggleAutonomous={() => flowControl("toggle_autonomous")}
452
- onDismiss={() => flowControl("dismiss_summary")}
453
- onSendPrompt={(text: string, images?: ImageContent[]) =>
454
- send({ type: "send_prompt", sessionId: session.id, text, images })
455
- }
456
- />
774
+ <>
775
+ <FlowDashboard
776
+ key={shown.flowName}
777
+ flowState={shown}
778
+ flowStates={isIdle ? undefined : (flowStates as Map<string, FlowState>)}
779
+ session={session}
780
+ sessionId={sessionId}
781
+ nodeFiles={nodeFiles}
782
+ idle={
783
+ isIdle
784
+ ? {
785
+ onRun: run.open,
786
+ onClose: detach,
787
+ runDisabled: run.pending,
788
+ rejectionReason: run.rejectionReason,
789
+ }
790
+ : undefined
791
+ }
792
+ onAbort={() => flowControl("abort")}
793
+ onToggleAutonomous={() => flowControl("toggle_autonomous")}
794
+ onDismiss={() => flowControl("dismiss_summary")}
795
+ onSendPrompt={(text: string, images?: ImageContent[]) =>
796
+ send({ type: "send_prompt", sessionId, text, images })
797
+ }
798
+ />
799
+ {isIdle && run.launchOpen && (
800
+ <FlowLaunchDialog
801
+ flowName={shown.flowName}
802
+ description={flowInfo?.description}
803
+ session={session}
804
+ onSubmit={(task) => {
805
+ const submission = run.submitted();
806
+ // Own the promise: a failed send yields no rejection event, so
807
+ // re-enable Run here. See change: attach-flow-before-run (D7).
808
+ void Promise.resolve(
809
+ send({ type: "flow_management", sessionId, action: "run", flowName: shown.flowName, task: task || undefined }),
810
+ ).catch((err: unknown) => {
811
+ console.error("[flows-plugin] plugin send failed:", err);
812
+ run.sendFailed(submission);
813
+ });
814
+ }}
815
+ onCancel={run.cancel}
816
+ />
817
+ )}
818
+ </>
457
819
  );
458
820
  }