@blackbelt-technology/pi-dashboard-flows-plugin 0.8.0 → 0.10.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.
@@ -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,23 +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
- import { makeSafeSend } from "./send-safe.js";
19
21
  import { FlowQuestionTranscriptPill } from "./FlowQuestionTranscriptPill.js";
20
22
  import { FlowSummary } from "./FlowSummary.js";
21
- import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
23
+ import { type FlowsSessionState, useFlowsSessionState } from "./FlowsSessionStateContext.js";
22
24
  import { type FlowTab, FlowTabBar } from "./FlowTabBar.js";
23
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";
24
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";
25
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
+ }
26
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
+ }
27
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
+ }
28
107
 
29
108
  export function FlowDashboard({
30
109
  flowState,
@@ -35,6 +114,8 @@ export function FlowDashboard({
35
114
  onSendPrompt,
36
115
  session,
37
116
  sessionId,
117
+ idle,
118
+ nodeFiles,
38
119
  }: {
39
120
  flowState: FlowState;
40
121
  /** All flow states (one per distinct flow run this session) for tab navigation */
@@ -48,6 +129,11 @@ export function FlowDashboard({
48
129
  /** Session id — threaded so child cards can render popout URLs and the
49
130
  upper-slot question card can submit responses. See change: add-flow-agent-popout. */
50
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;
51
137
  }) {
52
138
  const isMobile = useMobile();
53
139
  const t = useT();
@@ -67,13 +153,13 @@ export function FlowDashboard({
67
153
 
68
154
  // Build tab list from flowStates
69
155
  const tabs: FlowTab[] = useMemo(() => {
70
- if (!flowStates || flowStates.size <= 1) return [];
156
+ if (idle || !flowStates || flowStates.size <= 1) return [];
71
157
  return Array.from(flowStates.keys()).map(name => ({
72
158
  id: name,
73
159
  label: name,
74
160
  isActive: name === flowState.flowName,
75
161
  }));
76
- }, [flowStates, flowState.flowName]);
162
+ }, [idle, flowStates, flowState.flowName]);
77
163
 
78
164
  // Follow mode: auto-switch to latest active flow
79
165
  useEffect(() => {
@@ -85,22 +171,31 @@ export function FlowDashboard({
85
171
 
86
172
  // Determine which flow state to display based on active tab
87
173
  const displayState = useMemo(() => {
88
- if (flowStates && activeTabId !== flowState.flowName) {
174
+ if (!idle && flowStates && activeTabId !== flowState.flowName) {
89
175
  return flowStates.get(activeTabId) || flowState;
90
176
  }
91
177
  return flowState;
92
- }, [flowStates, activeTabId, flowState]);
178
+ }, [idle, flowStates, activeTabId, flowState]);
93
179
 
94
- 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());
95
183
  const allAgents = Array.from(flowState.agents.values());
96
184
 
97
185
  const handleSelectStep = useCallback((stepId: string) => {
98
186
  setSelectedStepId((prev) => (prev === stepId ? null : stepId));
99
187
  }, []);
100
- // Selection is ephemeral; reset when the displayed agent set changes.
101
- 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(() => {
102
193
  setSelectedStepId(null);
103
- }, [displayState.agents]);
194
+ setGraphOpen(false);
195
+ setActiveTabId(flowName);
196
+ setFollowMode(true);
197
+ }, [flowName]);
198
+ useOnEnterIdle(!!idle, resetOnEnterIdle);
104
199
  // Esc clears selection (Dialog handles its own Esc independently).
105
200
  useEffect(() => {
106
201
  if (!selectedStepId) return;
@@ -122,8 +217,11 @@ export function FlowDashboard({
122
217
  }, [selectedStepId]);
123
218
  const doneCount = allAgents.filter(a => a.status === "complete" || a.status === "error" || a.status === "blocked").length;
124
219
  const totalCount = allAgents.length;
125
- const isRunning = flowState.status === "running";
126
- 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`);
127
225
 
128
226
  // After completion, show summary. Forward sessionId so the summary's per-session
129
227
  // collapse state persists (the hook no-ops without a session id).
@@ -162,7 +260,7 @@ export function FlowDashboard({
162
260
  >
163
261
  <span className="text-blue-400 text-sm">π</span>
164
262
  <span className="text-sm text-[var(--text-primary)] truncate flex-1">
165
- {flowState.flowName} · {doneCount}/{totalCount} steps
263
+ {flowState.flowName} · {progressText}
166
264
  </span>
167
265
  <span className="text-[10px] text-[var(--text-tertiary)]">tap to expand</span>
168
266
  </div>
@@ -170,7 +268,12 @@ export function FlowDashboard({
170
268
  }
171
269
 
172
270
  return (
173
- <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
+ >
174
277
  {/* Header */}
175
278
  <div className="flex items-center gap-2 mb-2">
176
279
  <span
@@ -186,7 +289,7 @@ export function FlowDashboard({
186
289
  )}
187
290
  <span className="text-sm text-[var(--text-primary)] truncate flex-1">
188
291
  {flowState.flowName}
189
- <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>
190
293
  </span>
191
294
 
192
295
  {/* Controls */}
@@ -201,6 +304,7 @@ export function FlowDashboard({
201
304
  >
202
305
  <Icon path={mdiRobotOutline} size={0.4} className="inline mr-0.5" />AUTO
203
306
  </button>
307
+ {idle && <IdleControls idle={idle} />}
204
308
  {isRunning && (
205
309
  <button
206
310
  onClick={(e) => { e.stopPropagation(); onAbort(); }}
@@ -241,6 +345,7 @@ export function FlowDashboard({
241
345
  <FlowQuestionsSection
242
346
  sessionId={sessionId}
243
347
  flowId={displayState.flowName}
348
+ pendingOnly={!!idle}
244
349
  />
245
350
  )}
246
351
 
@@ -256,6 +361,7 @@ export function FlowDashboard({
256
361
  <FlowYamlPopoverButton
257
362
  flowSource={displayState.flowSource}
258
363
  flowName={displayState.flowName}
364
+ sessionId={sessionId}
259
365
  />
260
366
  </div>
261
367
  )}
@@ -279,21 +385,21 @@ export function FlowDashboard({
279
385
  </Dialog>
280
386
  )}
281
387
 
282
- {/* Agent card grid — detailed per-agent info */}
283
- <div
284
- className="grid gap-2 mt-2"
285
- style={{ gridTemplateColumns: `repeat(auto-fill, minmax(200px, 1fr))` }}
286
- >
287
- {agents.map(agent => (
288
- <FlowAgentCard
289
- key={agent.stepId || agent.agentName}
290
- agent={agent}
291
- session={session}
292
- sessionId={sessionId}
293
- selected={selectedStepId === (agent.stepId || agent.agentName)}
294
- onSelect={handleSelectStep}
295
- />
296
- ))}
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>
297
403
  </div>
298
404
  </div>
299
405
  </div>
@@ -332,9 +438,13 @@ const FLOW_QUESTION_TRANSCRIPT_CAP = 10;
332
438
  function FlowQuestionsSection({
333
439
  sessionId,
334
440
  flowId,
441
+ pendingOnly = false,
335
442
  }: {
336
443
  sessionId: string;
337
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;
338
448
  }) {
339
449
  const requests = useSessionInteractiveRequests(sessionId);
340
450
  const send = usePluginSend();
@@ -350,10 +460,11 @@ function FlowQuestionsSection({
350
460
  | undefined;
351
461
  if (cmp?.type !== "flow-question") continue;
352
462
  if (cmp?.props?.flowId !== flowId) continue;
463
+ if (pendingOnly && req.status !== "pending") continue;
353
464
  out.push(req);
354
465
  }
355
466
  return out.slice(-FLOW_QUESTION_TRANSCRIPT_CAP);
356
- }, [requests, flowId]);
467
+ }, [requests, flowId, pendingOnly]);
357
468
 
358
469
  if (queue.length === 0) return null;
359
470
 
@@ -413,50 +524,297 @@ function FlowQuestionsSection({
413
524
 
414
525
  type FlowQuestionCardType = "select" | "input" | "confirm" | "editor" | "multiselect";
415
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
+
416
679
  /**
417
680
  * Slot-consumer wrapper for the `content-header-sticky` claim.
418
- * Self-derives flow state from useFlowsSessionState; selection state
419
- * and callbacks come from useFlowsUiState / pluginContext.send.
420
- * Returns null when no flow is active. See change:
421
- * 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).
422
687
  */
423
688
  export function FlowDashboardClaim({ session }: { session: DashboardSession }) {
424
- 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);
425
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
+ );
426
740
 
427
- // Diagnostic logging — helps trace why the upper slot might be empty when
428
- // a flow is running. Gated to dev builds. See change: fix-flows-plugin-polish (C1).
429
741
  if (typeof import.meta !== "undefined" && (import.meta as { env?: { DEV?: boolean } }).env?.DEV) {
430
742
  // eslint-disable-next-line no-console
431
- console.debug(
432
- "[flows] FlowDashboardClaim render",
433
- {
434
- sessionId: session.id,
435
- hasFlowState: !!flowState,
436
- flowName: flowState?.flowName,
437
- flowStatus: flowState?.status,
438
- flowsCount: flowStates.size,
439
- },
440
- );
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
+ });
441
750
  }
442
751
 
443
- 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
+ }
444
769
 
445
- const flowControl = (action: string) =>
446
- send({ type: "flow_control", sessionId: session.id, action });
770
+ const shown = idleDisplayState ?? slot.flowState!;
771
+ const flowInfo = flowsList.find((f) => f.name === shown.flowName);
447
772
 
448
773
  return (
449
- <FlowDashboard
450
- flowState={flowState}
451
- flowStates={flowStates as Map<string, FlowState>}
452
- session={session}
453
- sessionId={session.id}
454
- onAbort={() => flowControl("abort")}
455
- onToggleAutonomous={() => flowControl("toggle_autonomous")}
456
- onDismiss={() => flowControl("dismiss_summary")}
457
- onSendPrompt={(text: string, images?: ImageContent[]) =>
458
- send({ type: "send_prompt", sessionId: session.id, text, images })
459
- }
460
- />
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
+ </>
461
819
  );
462
820
  }
@@ -49,6 +49,8 @@ export function FlowQuestionCard({
49
49
  return (
50
50
  <div
51
51
  data-testid="flow-question-card"
52
+ data-widget-bar-slot=""
53
+ tabIndex={-1}
52
54
  className="mt-2 mb-2 p-3 border border-purple-500/40 bg-purple-500/5 rounded"
53
55
  >
54
56
  <div className="flex items-start gap-2 mb-2">