@blackbelt-technology/pi-dashboard-flows-plugin 0.11.0 → 0.12.1

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
@@ -1,258 +1,65 @@
1
- import { usePluginConfig, usePluginSend, useSessionData, useSessionEvents, useT, useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
1
+ import { useT } from "@blackbelt-technology/dashboard-plugin-runtime";
2
2
  import { ActionList } from "@blackbelt-technology/pi-dashboard-client-utils/ActionList";
3
- import type { UiSelectOption as SelectOption } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
4
- import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
5
- import type {
6
- CommandInfo,
7
- DashboardSession,
8
- FlowInfo,
9
- FlowState,
10
- } from "@blackbelt-technology/pi-dashboard-shared/types.js";
11
- import React, { useEffect, useMemo, useRef, useState } from "react";
12
- import { FlowAuthorPromptDialog } from "./FlowAuthorPromptDialog.js";
13
- import { FlowLaunchDialog } from "./FlowLaunchDialog.js";
14
- import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
15
- import type { FlowsPluginConfig } from "./FlowsSettings.js";
16
- import { newAttachmentId, setAttachment } from "./flow-attach-store.js";
17
- import { hasFlowsCommand } from "./flowsActionsGate.js";
18
- import { sessionHasFlowEvents } from "./flowsAvailability.js";
19
- import { makeSafeSend } from "./send-safe.js";
3
+ import { ActionListMenuContext } from "@blackbelt-technology/pi-dashboard-client-utils/ActionListMenuContext";
4
+ import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
5
+ import { useContext, useEffect, useRef } from "react";
6
+ import { FlowActionDialogs, type FlowActions, useFlowActions } from "./useFlowActions.js";
20
7
 
21
- function isAnyFlowRunning(
22
- flowState: FlowState | null | undefined,
23
- flowStates: ReadonlyMap<string, FlowState> | undefined,
24
- ): boolean {
25
- if (flowState?.status === "running") return true;
26
- return flowStates ? Array.from(flowStates.values()).some((s) => s.status === "running") : false;
8
+ /**
9
+ * Pure menu gate: the session actions menu items this plugin contributes.
10
+ * Nothing while the catalog or edit mode is unknown, or when the catalog lists
11
+ * flows (the dock chip and panel headers own flow actions then). A flowless
12
+ * session gets exactly one item: New flow… (edit mode on) or "Turn on edit
13
+ * mode for this project" (off). See change: flows-dock-chip-and-panel-actions.
14
+ */
15
+ export function flowMenuItems(
16
+ t: ReturnType<typeof useT>,
17
+ a: Pick<FlowActions, "catalogKnown" | "hasFlows" | "editMode" | "newFlow" | "setEditMode">,
18
+ ) {
19
+ if (!a.catalogKnown || a.hasFlows || a.editMode === undefined) return [];
20
+ if (a.editMode) return [{ label: t("newFlowItem", undefined, "New flow…"), icon: "mdiPlus", onClick: a.newFlow }];
21
+ return [
22
+ {
23
+ label: t("projectEditModeOn", undefined, "Turn on edit mode for this project"),
24
+ icon: "mdiPencilOutline",
25
+ tooltip: t(
26
+ "projectEditModeHint",
27
+ undefined,
28
+ "Writes flows.editFlow to this project's .pi/settings.json. The project value then overrides the global default.",
29
+ ),
30
+ onClick: () => a.setEditMode(true),
31
+ },
32
+ ];
27
33
  }
28
34
 
29
35
  /**
30
- * `session-card-action-bar` claim: the flow ACTIONS (Run Flow…, Open flow…,
31
- * New / Edit…, Delete) rendered as an `ActionList` for the session actions menu,
32
- * plus the dialogs they open and the edit-mode reconcile. Flow STATUS stays in
33
- * the FLOWS subcard (`SessionFlowActionsClaim`).
36
+ * `session-card-action-bar` claim: the flowless entry point in the session
37
+ * actions menu (see `flowMenuItems`), plus the dialogs it opens (portaled; the
38
+ * claim stays mounted for the card's lifetime so they survive the menu
39
+ * closing). Opening the menu asks the session for its catalog and re-reads the
40
+ * effective edit mode. It never sends an edit-mode message on its own.
34
41
  *
35
- * The claim stays mounted for the card's lifetime (dialogs portal to body and
36
- * survive the menu closing; the reconcile runs without the menu being opened).
37
- * Gated by availability — a `flows` / `flows:*` command (not `flows:new` alone)
38
- * or any flow event; never by `flowsList` length.
39
- *
40
- * See change: add-session-actions-flyout (D7, D12).
42
+ * See change: add-session-actions-flyout; stop-flows-edit-mode-project-writes;
43
+ * flows-dock-chip-and-panel-actions (D6).
41
44
  */
42
45
  export function SessionFlowMenuClaim({ session }: { session: DashboardSession }) {
43
46
  const t = useT();
44
- const ConfirmDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.confirmDialog);
45
- const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
46
- const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
47
- const commands = useSessionData<CommandInfo[]>(session.id, "commandsList") ?? [];
48
- const { flowState, flowStates, lastFlowStartedAt } = useFlowsSessionState(session.id);
49
- const events = useSessionEvents(session.id);
50
- const send = usePluginSend();
51
- // The edit-mode reconcile and author-prompt handlers cannot own the send
52
- // promise — discard it explicitly. See change: cleanup-client-plugin-promises.
53
- const dispatch = useMemo(() => makeSafeSend(send), [send]);
54
- const config = usePluginConfig<FlowsPluginConfig>();
55
- const editMode = config.editFlow ?? false;
56
-
57
- // commandsList (subscribed above) + the event stream drive re-evaluation; the
58
- // gate reads the same sources as `flowsActionsAvailable`.
59
- const available = hasFlowsCommand(commands) || sessionHasFlowEvents(session.id);
60
- const hasFlowsDelete = commands.some((c) => c.name === "flows:delete");
61
-
62
- const [pickerOpen, setPickerOpen] = useState(false);
63
- const [openPickerOpen, setOpenPickerOpen] = useState(false);
64
- const [editPickerOpen, setEditPickerOpen] = useState(false);
65
- // After picking from the edit launcher, capture intent before launching the skill.
66
- const [authorTarget, setAuthorTarget] = useState<{ mode: "new" | "edit"; flowName?: string } | null>(null);
67
- const [deletePickerOpen, setDeletePickerOpen] = useState(false);
68
- const [deleteFlowName, setDeleteFlowName] = useState<string | null>(null);
69
- const [selectedFlow, setSelectedFlow] = useState<FlowInfo | null>(null);
47
+ const menuOpen = useContext(ActionListMenuContext)?.open;
48
+ const actions = useFlowActions(session.id, { editModeWhen: "flowless", menuOpen });
70
49
 
71
- // Reconcile the GLOBAL edit-mode default down to this session once flows is
72
- // available. pi-flows persists it to the project .pi/settings.json. Idempotent
73
- // — re-emits only when the default changes. See change:
74
- // rework-flows-plugin-for-new-pi-flows (D4), add-session-actions-flyout (D12).
75
- const reconciledRef = useRef<boolean | null>(null);
50
+ // Ask for the catalog on each menu closed → open transition.
51
+ const wasOpen = useRef(menuOpen);
52
+ const { refreshCatalog } = actions;
76
53
  useEffect(() => {
77
- if (!available) return; // wait until flows is available
78
- if (reconciledRef.current === editMode) return;
79
- reconciledRef.current = editMode;
80
- dispatch({ type: "flow_management", sessionId: session.id, action: "set-edit-mode", enabled: editMode });
81
- }, [available, editMode, session.id, dispatch]);
82
-
83
- if (!available) return null;
84
-
85
- const anyRunning = isAnyFlowRunning(flowState, flowStates);
86
- const hasFlows = flows.length > 0;
87
-
88
- const flowOptions: SelectOption[] = flows.map((f) => ({
89
- value: f.name,
90
- label: f.name,
91
- description: f.description,
92
- }));
93
- // Edit launcher options: existing flows + a "new flow" sentinel.
94
- const editOptions: SelectOption[] = [
95
- { value: "__new__", label: t("newFlowOption", undefined, "+ New flow"), description: t("newFlowOptionDesc", undefined, "Author a new flow with the edit-flow skill") },
96
- ...flowOptions,
97
- ];
98
-
99
- const actions = [
100
- ...(hasFlows
101
- ? [{ label: t("runFlowButton", undefined, "Run Flow..."), icon: "mdiPlay", onClick: () => setPickerOpen(true) }]
102
- : []),
103
- ...(hasFlows
104
- ? [{
105
- label: t("openFlowButton", undefined, "Open flow…"),
106
- icon: "mdiEyeOutline",
107
- disabled: anyRunning,
108
- tooltip: anyRunning ? t("openFlowDisabledRunning", undefined, "A flow is running") : undefined,
109
- onClick: () => setOpenPickerOpen(true),
110
- }]
111
- : []),
112
- ...(editMode
113
- ? [{ label: t("newEditButton", undefined, "New / Edit…"), icon: "mdiPencil", onClick: () => setEditPickerOpen(true) }]
114
- : []),
115
- ...(hasFlowsDelete && hasFlows
116
- ? [{ label: `${t("delete", undefined, "Delete")}…`, icon: "mdiDeleteOutline", onClick: () => setDeletePickerOpen(true) }]
117
- : []),
118
- ];
119
-
120
- const onFlowAction = (action: string, opts?: { flowName?: string; task?: string }) =>
121
- dispatch({
122
- type: "flow_management",
123
- sessionId: session.id,
124
- action,
125
- flowName: opts?.flowName,
126
- task: opts?.task,
127
- });
128
-
129
- const onEditFlow = (flowName: string | undefined, instruction: string) => {
130
- const intent = instruction.trim();
131
- // New flow: instruction describes what to build. Edit: flow name is
132
- // token-1 (the skill reads that file), instruction follows on a new line.
133
- const text = flowName
134
- ? intent
135
- ? `/skill:manage-flows ${flowName}\n\n${intent}`
136
- : `/skill:manage-flows ${flowName}`
137
- : `/skill:manage-flows ${intent}`;
138
- dispatch({ type: "send_prompt", sessionId: session.id, text });
139
- };
54
+ if (menuOpen && !wasOpen.current) refreshCatalog();
55
+ wasOpen.current = menuOpen;
56
+ }, [menuOpen, refreshCatalog]);
140
57
 
58
+ const items = flowMenuItems(t, actions);
141
59
  return (
142
60
  <>
143
- {actions.length > 0 && <ActionList actions={actions} />}
144
-
145
- {/* Run: pick flow → task dialog */}
146
- {pickerOpen && (
147
- <SearchableSelectDialog
148
- title={t("runFlowDialogTitle", undefined, "Run Flow")}
149
- options={flowOptions}
150
- placeholder={t("searchFlows", undefined, "Search flows...")}
151
- emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
152
- onSelect={(value) => {
153
- const flow = flows.find((f) => f.name === value);
154
- if (flow) setSelectedFlow(flow);
155
- setPickerOpen(false);
156
- }}
157
- onCancel={() => setPickerOpen(false)}
158
- />
159
- )}
160
-
161
- {selectedFlow && (
162
- <FlowLaunchDialog
163
- flowName={selectedFlow.name}
164
- description={selectedFlow.description}
165
- onSubmit={(task) => {
166
- onFlowAction("run", { flowName: selectedFlow.name, task: task || undefined });
167
- setSelectedFlow(null);
168
- }}
169
- onCancel={() => setSelectedFlow(null)}
170
- />
171
- )}
172
-
173
- {/* Open: pick flow → attach it to the flow slot (not started). See change:
174
- attach-flow-before-run (D7). */}
175
- {openPickerOpen && (
176
- <SearchableSelectDialog
177
- title={t("openFlowDialogTitle", undefined, "Open flow")}
178
- options={flowOptions}
179
- placeholder={t("searchFlows", undefined, "Search flows...")}
180
- emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
181
- onSelect={(value) => {
182
- const flow = flows.find((f) => f.name === value);
183
- if (flow) {
184
- // Baseline = newest flow_started seen now; null on an empty (not yet
185
- // replayed) stream — the flow slot resolves it from the first batch.
186
- // See change: attach-flow-before-run (D4).
187
- setAttachment(session.id, {
188
- id: newAttachmentId(),
189
- name: flow.name,
190
- source: flow.source,
191
- baselineStartedAt: events.length > 0 ? (lastFlowStartedAt ?? 0) : null,
192
- });
193
- }
194
- setOpenPickerOpen(false);
195
- }}
196
- onCancel={() => setOpenPickerOpen(false)}
197
- />
198
- )}
199
-
200
- {/* New / Edit: pick an existing flow or "new" → launch the edit-flow skill */}
201
- {editPickerOpen && (
202
- <SearchableSelectDialog
203
- title={t("newEditFlowTitle", undefined, "New / Edit flow")}
204
- options={editOptions}
205
- placeholder={t("pickFlowToEdit", undefined, "Pick a flow to edit, or + New flow…")}
206
- emptyMessage={t("noFlowsYet", undefined, "No flows yet — pick + New flow")}
207
- onSelect={(value) => {
208
- setAuthorTarget(
209
- value === "__new__" ? { mode: "new" } : { mode: "edit", flowName: value },
210
- );
211
- setEditPickerOpen(false);
212
- }}
213
- onCancel={() => setEditPickerOpen(false)}
214
- />
215
- )}
216
-
217
- {/* New / Edit: capture intent → launch the manage-flows skill */}
218
- {authorTarget && (
219
- <FlowAuthorPromptDialog
220
- mode={authorTarget.mode}
221
- flowName={authorTarget.flowName}
222
- onSubmit={(instruction) => {
223
- onEditFlow(authorTarget.flowName, instruction);
224
- setAuthorTarget(null);
225
- }}
226
- onCancel={() => setAuthorTarget(null)}
227
- />
228
- )}
229
-
230
- {/* Delete: pick flow → confirm dialog */}
231
- {deletePickerOpen && (
232
- <SearchableSelectDialog
233
- title={t("deleteFlowTitle", undefined, "Delete Flow")}
234
- options={flowOptions}
235
- placeholder={t("searchFlows", undefined, "Search flows...")}
236
- emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
237
- onSelect={(value) => {
238
- setDeleteFlowName(value);
239
- setDeletePickerOpen(false);
240
- }}
241
- onCancel={() => setDeletePickerOpen(false)}
242
- />
243
- )}
244
-
245
- {deleteFlowName && (
246
- <ConfirmDialog
247
- message={t("deleteFlowConfirm", { name: deleteFlowName }, `Delete flow "${deleteFlowName}"? This will remove the flow file and any associated agents.`)}
248
- confirmLabel={t("delete", undefined, "Delete")}
249
- onConfirm={() => {
250
- onFlowAction("delete", { flowName: deleteFlowName });
251
- setDeleteFlowName(null);
252
- }}
253
- onCancel={() => setDeleteFlowName(null)}
254
- />
255
- )}
61
+ {items.length > 0 && <ActionList actions={items} />}
62
+ <FlowActionDialogs actions={actions} />
256
63
  </>
257
64
  );
258
65
  }
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Ask session — per-session external store of the `flow.ask-session` requests
3
+ * this page sent and the questions pi-flows confirmed it posted. Read with
4
+ * `useSyncExternalStore`, so the panel, the agent cards and the FLOWS badge
5
+ * (different trees) share one state, and collapsing the cards keeps it.
6
+ *
7
+ * A click records a request (`requestId` = `a-` + 12 `[a-z0-9]`), sends
8
+ * `plugin_action flow.ask-session { questionId, requestId }` and disables the
9
+ * button. A `flow_ask_session_result` for a known `requestId` marks its
10
+ * `posted` ids sent (late results within 60 s count). No result after 5 s →
11
+ * `no confirmation`; the button re-enables 30 s after the click (the server
12
+ * throttle). Closed questions are pruned, a session is dropped once it has no
13
+ * open question, and every timer is cleared on prune. Page-scoped: never
14
+ * persisted. See change: adopt-flow-parent-mailbox (D5).
15
+ */
16
+ import { usePluginSend, useSessionEvents } from "@blackbelt-technology/dashboard-plugin-runtime";
17
+ import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
18
+ import { openQuestions } from "../flow-questions.js";
19
+ import type { FlowState } from "../types.js";
20
+
21
+ const ASK_NO_CONFIRMATION_MS = 5_000;
22
+ const ASK_RETRY_MS = 30_000;
23
+ const ASK_REQUEST_TTL_MS = 60_000;
24
+
25
+ type Phase = "pending" | "unconfirmed" | "retry";
26
+
27
+ interface AskRequest {
28
+ questionId: string;
29
+ at: number;
30
+ phase: Phase;
31
+ timers: ReturnType<typeof setTimeout>[];
32
+ }
33
+
34
+ /** Immutable per-session snapshot (a new object on every change). */
35
+ export interface AskSnapshot {
36
+ readonly sent: ReadonlySet<string>;
37
+ /** Latest request phase per question id. */
38
+ readonly phase: ReadonlyMap<string, Phase>;
39
+ }
40
+
41
+ export type AskNote = "unread" | "sent" | "no-confirmation";
42
+ export interface AskView {
43
+ note: AskNote;
44
+ disabled: boolean;
45
+ sent: boolean;
46
+ }
47
+
48
+ interface SessionAsk {
49
+ sent: Set<string>;
50
+ requests: Map<string, AskRequest>;
51
+ snapshot: AskSnapshot;
52
+ }
53
+
54
+ const EMPTY: AskSnapshot = Object.freeze({ sent: new Set<string>(), phase: new Map<string, Phase>() });
55
+ const sessions = new Map<string, SessionAsk>();
56
+ const listeners = new Map<string, Set<() => void>>();
57
+
58
+ function rebuild(sessionId: string, s: SessionAsk): void {
59
+ const phase = new Map<string, Phase>();
60
+ const latest = new Map<string, number>();
61
+ for (const r of s.requests.values()) {
62
+ if ((latest.get(r.questionId) ?? -1) <= r.at) {
63
+ latest.set(r.questionId, r.at);
64
+ phase.set(r.questionId, r.phase);
65
+ }
66
+ }
67
+ s.snapshot = { sent: new Set(s.sent), phase };
68
+ for (const l of listeners.get(sessionId) ?? []) l();
69
+ }
70
+
71
+ function sessionOf(sessionId: string): SessionAsk {
72
+ let s = sessions.get(sessionId);
73
+ if (!s) {
74
+ s = { sent: new Set(), requests: new Map(), snapshot: EMPTY };
75
+ sessions.set(sessionId, s);
76
+ }
77
+ return s;
78
+ }
79
+
80
+ function dropRequest(s: SessionAsk, requestId: string): void {
81
+ const r = s.requests.get(requestId);
82
+ if (!r) return;
83
+ for (const t of r.timers) clearTimeout(t);
84
+ s.requests.delete(requestId);
85
+ }
86
+
87
+ /** Fresh request id: `a-` + 12 lowercase letters / digits. */
88
+ export function newRequestId(): string {
89
+ const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
90
+ const bytes = new Uint8Array(12);
91
+ crypto.getRandomValues(bytes);
92
+ let out = "a-";
93
+ for (const b of bytes) out += alphabet[b % alphabet.length];
94
+ return out;
95
+ }
96
+
97
+ export function getAskSnapshot(sessionId: string): AskSnapshot {
98
+ return sessions.get(sessionId)?.snapshot ?? EMPTY;
99
+ }
100
+
101
+ function subscribeAsk(sessionId: string, fn: () => void): () => void {
102
+ let set = listeners.get(sessionId);
103
+ if (!set) {
104
+ set = new Set();
105
+ listeners.set(sessionId, set);
106
+ }
107
+ set.add(fn);
108
+ return () => {
109
+ set?.delete(fn);
110
+ };
111
+ }
112
+
113
+ /** Button / note state of one question. */
114
+ function askView(snap: AskSnapshot, questionId: string): AskView {
115
+ if (snap.sent.has(questionId)) return { note: "sent", disabled: true, sent: true };
116
+ const p = snap.phase.get(questionId);
117
+ if (p === "pending") return { note: "unread", disabled: true, sent: false };
118
+ if (p === "unconfirmed") return { note: "no-confirmation", disabled: true, sent: false };
119
+ if (p === "retry") return { note: "no-confirmation", disabled: false, sent: false };
120
+ return { note: "unread", disabled: false, sent: false };
121
+ }
122
+
123
+ /** Send one `flow.ask-session` per id (one request each). */
124
+ export function askSession(sessionId: string, questionIds: readonly string[], send: (msg: unknown) => unknown): void {
125
+ if (questionIds.length === 0) return;
126
+ const s = sessionOf(sessionId);
127
+ for (const questionId of questionIds) {
128
+ const requestId = newRequestId();
129
+ const req: AskRequest = { questionId, at: Date.now(), phase: "pending", timers: [] };
130
+ const setPhase = (phase: Phase) => () => {
131
+ if (!s.requests.has(requestId)) return;
132
+ req.phase = phase;
133
+ rebuild(sessionId, s);
134
+ };
135
+ req.timers.push(
136
+ setTimeout(setPhase("unconfirmed"), ASK_NO_CONFIRMATION_MS),
137
+ setTimeout(setPhase("retry"), ASK_RETRY_MS),
138
+ setTimeout(() => {
139
+ dropRequest(s, requestId);
140
+ rebuild(sessionId, s);
141
+ }, ASK_REQUEST_TTL_MS),
142
+ );
143
+ s.requests.set(requestId, req);
144
+ try {
145
+ void Promise.resolve(
146
+ send({ type: "plugin_action", pluginId: "flows", sessionId, action: "flow.ask-session", payload: { questionId, requestId } }),
147
+ ).catch((err: unknown) => console.error("[flows-plugin] ask-session send failed:", err));
148
+ } catch (err) {
149
+ console.error("[flows-plugin] ask-session send failed:", err);
150
+ }
151
+ }
152
+ rebuild(sessionId, s);
153
+ }
154
+
155
+ /** Fold a `flow_ask_session_result { posted, requestId }`; unknown ids are ignored. */
156
+ export function handleAskResult(sessionId: string, data: Record<string, unknown> | undefined): void {
157
+ const s = sessions.get(sessionId);
158
+ const requestId = data?.requestId;
159
+ if (!s || typeof requestId !== "string" || !s.requests.has(requestId)) return;
160
+ const posted = Array.isArray(data?.posted) ? data.posted.filter((x): x is string => typeof x === "string") : [];
161
+ for (const id of posted) s.sent.add(id);
162
+ if (posted.length > 0) dropRequest(s, requestId);
163
+ rebuild(sessionId, s);
164
+ }
165
+
166
+ /** Keep only the still-open questions; none open → drop the session. */
167
+ function pruneAsk(sessionId: string, openIds: ReadonlySet<string>): void {
168
+ const s = sessions.get(sessionId);
169
+ if (!s) return;
170
+ if (openIds.size === 0) {
171
+ for (const id of [...s.requests.keys()]) dropRequest(s, id);
172
+ sessions.delete(sessionId);
173
+ for (const l of listeners.get(sessionId) ?? []) l();
174
+ return;
175
+ }
176
+ let changed = false;
177
+ for (const [id, r] of [...s.requests]) {
178
+ if (!openIds.has(r.questionId)) {
179
+ dropRequest(s, id);
180
+ changed = true;
181
+ }
182
+ }
183
+ for (const q of [...s.sent]) {
184
+ if (!openIds.has(q)) {
185
+ s.sent.delete(q);
186
+ changed = true;
187
+ }
188
+ }
189
+ if (changed) rebuild(sessionId, s);
190
+ }
191
+
192
+ /** Open question ids across runs (deduped). */
193
+ export function openQuestionIds(states: Iterable<FlowState | null | undefined>): string[] {
194
+ const ids = new Set<string>();
195
+ for (const st of states) for (const q of openQuestions(st)) ids.add(q.id);
196
+ return [...ids];
197
+ }
198
+
199
+ /** Tests: clear every session and timer. */
200
+ export function __resetAskStoreForTests(): void {
201
+ for (const s of sessions.values()) for (const id of [...s.requests.keys()]) dropRequest(s, id);
202
+ sessions.clear();
203
+ listeners.clear();
204
+ }
205
+
206
+ /**
207
+ * The session's Ask session state: the snapshot, `view(id)`, `ask(ids)` (sends
208
+ * only ids that are neither sent nor pending) and `unsent(ids)`. Folds
209
+ * `flow_ask_session_result` from the session stream and prunes closed
210
+ * questions (`openIds`: the union of every shown run's open questions; see
211
+ * `openQuestionIds`). The caller supplies them so no second flow reduction runs.
212
+ */
213
+ export function useAskSession(sessionId: string | undefined, openIds: readonly string[]) {
214
+ const sid = sessionId ?? "";
215
+ const send = usePluginSend();
216
+ const subscribe = useCallback((fn: () => void) => subscribeAsk(sid, fn), [sid]);
217
+ const snap = useSyncExternalStore(subscribe, () => getAskSnapshot(sid), () => EMPTY);
218
+ const events = useSessionEvents(sid);
219
+
220
+ useEffect(() => {
221
+ if (!sid) return;
222
+ for (const e of events) {
223
+ if (e.eventType === "flow_ask_session_result") handleAskResult(sid, e.data as Record<string, unknown>);
224
+ }
225
+ }, [sid, events]);
226
+
227
+ const openKey = useMemo(() => [...new Set(openIds)].sort().join("\u0000"), [openIds]);
228
+ useEffect(() => {
229
+ if (!sid) return;
230
+ pruneAsk(sid, new Set(openKey ? openKey.split("\u0000") : []));
231
+ }, [sid, openKey]);
232
+
233
+ const unsent = useCallback((ids: readonly string[]) => ids.filter((id) => !askView(snap, id).disabled), [snap]);
234
+ const ask = useCallback(
235
+ (ids: readonly string[]) => {
236
+ if (!sid) return;
237
+ askSession(sid, unsent(ids), send);
238
+ },
239
+ [sid, send, unsent],
240
+ );
241
+ const view = useCallback((id: string) => askView(snap, id), [snap]);
242
+ return { snap, view, ask, unsent };
243
+ }
@@ -37,6 +37,8 @@ function parse(raw: string | null): FlowAttachment | null {
37
37
  source: typeof v.source === "string" ? v.source : undefined,
38
38
  baselineStartedAt:
39
39
  typeof v.baselineStartedAt === "number" && Number.isFinite(v.baselineStartedAt) ? v.baselineStartedAt : null,
40
+ // Only a literal `true` keeps the view-only flag. See change: add-flow-open-tool.
41
+ ...(v.viewOnly === true ? { viewOnly: true as const } : {}),
40
42
  };
41
43
  } catch {
42
44
  return null;
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Shared geometry for the flow agent-card grid.
3
3
  *
4
- * One source for the live grid (`FlowDashboard`) and the frozen post-flow grid
5
- * (`FlowSummary`) so the two cannot drift in column minimum, row track or gap.
4
+ * One source for the Agent cards grid (`FlowStepCards`, every panel mode —
5
+ * idle, live, completed) so no grid can drift in column minimum, row track or gap.
6
6
  * The classes are written as literals (not interpolated from the constants) so
7
7
  * Tailwind's source scanner can see them; the constants stay the numeric truth
8
8
  * the specs pin against. See change: consolidate-flow-agent-cards (D1, D5).
@@ -1,18 +1,28 @@
1
1
  /**
2
- * Per-session persistence for the flow socket's collapse state. The whole-panel
3
- * (`FlowSummary`) and live-dashboard (`FlowDashboard`) collapses are stored in
2
+ * Per-session persistence for the flow socket's collapse state. The completed
3
+ * (`summary` kind) and idle/live (`dashboard` kind) `FlowDashboard` collapses are stored in
4
4
  * localStorage keyed by session id, so collapsing a session's flow panel sticks
5
5
  * across remounts/reloads instead of re-opening every time. Mirrors the
6
6
  * try/catch-swallow pattern of `useSidebarState.ts`; a localStorage failure
7
7
  * (quota / disabled / private mode) degrades to in-memory state and never throws.
8
8
  *
9
- * Default is expanded (false) for any session never collapsed.
9
+ * Default is COLLAPSED (true) for any session with no stored choice: the panel
10
+ * never expands on its own when a flow starts, completes or fails. Open flow…
11
+ * expands it via `setFlowCollapsed` (same-tab writes notify mounted toggles).
10
12
  *
11
- * See change: fix-flow-ui-graph-zoom-summary.
13
+ * See change: fix-flow-ui-graph-zoom-summary; flows-dock-chip-and-panel-actions (D10).
12
14
  */
13
15
  import { useCallback, useEffect, useState } from "react";
14
16
 
15
- export type FlowCollapseKind = "summary" | "dashboard";
17
+ /** Default for a session with no stored collapse choice. */
18
+ const FLOW_COLLAPSE_DEFAULT = true;
19
+
20
+ /** Same-tab listeners per key, so an explicit write reaches mounted toggles. */
21
+ const keyListeners = new Map<string, Set<(v: boolean) => void>>();
22
+
23
+ /** `cards` = the live panel's Agent cards section (graph-first panel, default
24
+ * collapsed). See change: update-flows-plugin (D7). */
25
+ export type FlowCollapseKind = "summary" | "dashboard" | "cards";
16
26
 
17
27
  /** localStorage key for a (kind, session) pair. */
18
28
  export function flowCollapseKey(kind: FlowCollapseKind, sessionId: string): string {
@@ -51,6 +61,14 @@ export function usePersistedToggle(
51
61
 
52
62
  useEffect(() => {
53
63
  setValue(key ? readBoolean(key, fallback) : fallback);
64
+ if (!key) return;
65
+ let set = keyListeners.get(key);
66
+ if (!set) keyListeners.set(key, (set = new Set()));
67
+ set.add(setValue);
68
+ return () => {
69
+ set.delete(setValue);
70
+ if (set.size === 0) keyListeners.delete(key);
71
+ };
54
72
  }, [key, fallback]);
55
73
 
56
74
  const toggle = useCallback(() => {
@@ -75,5 +93,17 @@ export function useFlowCollapsePersisted(
75
93
  sessionId: string | undefined,
76
94
  kind: FlowCollapseKind,
77
95
  ): [boolean, () => void] {
78
- return usePersistedToggle(sessionId ? flowCollapseKey(kind, sessionId) : null, false);
96
+ return usePersistedToggle(sessionId ? flowCollapseKey(kind, sessionId) : null, FLOW_COLLAPSE_DEFAULT);
97
+ }
98
+
99
+ /**
100
+ * Explicit write (Open flow… expands): persists `collapsed` for the session's
101
+ * panel kind(s) and updates every mounted toggle for that key in this tab.
102
+ */
103
+ export function setFlowCollapsed(sessionId: string, kinds: readonly FlowCollapseKind[], collapsed: boolean): void {
104
+ for (const kind of kinds) {
105
+ const key = flowCollapseKey(kind, sessionId);
106
+ writeBoolean(key, collapsed);
107
+ for (const fn of keyListeners.get(key) ?? []) fn(collapsed);
108
+ }
79
109
  }