@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.
@@ -0,0 +1,265 @@
1
+ import {
2
+ usePluginSend,
3
+ useSessionData,
4
+ useSessionEvents,
5
+ useT,
6
+ useUiPrimitive,
7
+ } from "@blackbelt-technology/dashboard-plugin-runtime";
8
+ import { usePluginConfig } from "@blackbelt-technology/dashboard-plugin-runtime/context";
9
+ import { ActionList } from "@blackbelt-technology/pi-dashboard-client-utils/ActionList";
10
+ import type { UiSelectOption as SelectOption } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
11
+ import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
12
+ import type {
13
+ CommandInfo,
14
+ DashboardSession,
15
+ FlowInfo,
16
+ FlowState,
17
+ } from "@blackbelt-technology/pi-dashboard-shared/types.js";
18
+ import React, { useEffect, useMemo, useRef, useState } from "react";
19
+ import { FlowAuthorPromptDialog } from "./FlowAuthorPromptDialog.js";
20
+ import { FlowLaunchDialog } from "./FlowLaunchDialog.js";
21
+ import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
22
+ import type { FlowsPluginConfig } from "./FlowsSettings.js";
23
+ import { newAttachmentId, setAttachment } from "./flow-attach-store.js";
24
+ import { hasFlowsCommand } from "./flowsActionsGate.js";
25
+ import { sessionHasFlowEvents } from "./flowsAvailability.js";
26
+ import { makeSafeSend } from "./send-safe.js";
27
+
28
+ function isAnyFlowRunning(
29
+ flowState: FlowState | null | undefined,
30
+ flowStates: ReadonlyMap<string, FlowState> | undefined,
31
+ ): boolean {
32
+ if (flowState?.status === "running") return true;
33
+ return flowStates ? Array.from(flowStates.values()).some((s) => s.status === "running") : false;
34
+ }
35
+
36
+ /**
37
+ * `session-card-action-bar` claim: the flow ACTIONS (Run Flow…, Open flow…,
38
+ * New / Edit…, Delete) rendered as an `ActionList` for the session actions menu,
39
+ * plus the dialogs they open and the edit-mode reconcile. Flow STATUS stays in
40
+ * the FLOWS subcard (`SessionFlowActionsClaim`).
41
+ *
42
+ * The claim stays mounted for the card's lifetime (dialogs portal to body and
43
+ * survive the menu closing; the reconcile runs without the menu being opened).
44
+ * Gated by availability — a `flows` / `flows:*` command (not `flows:new` alone)
45
+ * or any flow event; never by `flowsList` length.
46
+ *
47
+ * See change: add-session-actions-flyout (D7, D12).
48
+ */
49
+ export function SessionFlowMenuClaim({ session }: { session: DashboardSession }) {
50
+ const t = useT();
51
+ const ConfirmDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.confirmDialog);
52
+ const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
53
+ const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
54
+ const commands = useSessionData<CommandInfo[]>(session.id, "commandsList") ?? [];
55
+ const { flowState, flowStates, lastFlowStartedAt } = useFlowsSessionState(session.id);
56
+ const events = useSessionEvents(session.id);
57
+ const send = usePluginSend();
58
+ // The edit-mode reconcile and author-prompt handlers cannot own the send
59
+ // promise — discard it explicitly. See change: cleanup-client-plugin-promises.
60
+ const dispatch = useMemo(() => makeSafeSend(send), [send]);
61
+ const config = usePluginConfig<FlowsPluginConfig>();
62
+ const editMode = config.editFlow ?? false;
63
+
64
+ // commandsList (subscribed above) + the event stream drive re-evaluation; the
65
+ // gate reads the same sources as `flowsActionsAvailable`.
66
+ const available = hasFlowsCommand(commands) || sessionHasFlowEvents(session.id);
67
+ const hasFlowsDelete = commands.some((c) => c.name === "flows:delete");
68
+
69
+ const [pickerOpen, setPickerOpen] = useState(false);
70
+ const [openPickerOpen, setOpenPickerOpen] = useState(false);
71
+ const [editPickerOpen, setEditPickerOpen] = useState(false);
72
+ // After picking from the edit launcher, capture intent before launching the skill.
73
+ const [authorTarget, setAuthorTarget] = useState<{ mode: "new" | "edit"; flowName?: string } | null>(null);
74
+ const [deletePickerOpen, setDeletePickerOpen] = useState(false);
75
+ const [deleteFlowName, setDeleteFlowName] = useState<string | null>(null);
76
+ const [selectedFlow, setSelectedFlow] = useState<FlowInfo | null>(null);
77
+
78
+ // Reconcile the GLOBAL edit-mode default down to this session once flows is
79
+ // available. pi-flows persists it to the project .pi/settings.json. Idempotent
80
+ // — re-emits only when the default changes. See change:
81
+ // rework-flows-plugin-for-new-pi-flows (D4), add-session-actions-flyout (D12).
82
+ const reconciledRef = useRef<boolean | null>(null);
83
+ useEffect(() => {
84
+ if (!available) return; // wait until flows is available
85
+ if (reconciledRef.current === editMode) return;
86
+ reconciledRef.current = editMode;
87
+ dispatch({ type: "flow_management", sessionId: session.id, action: "set-edit-mode", enabled: editMode });
88
+ }, [available, editMode, session.id, dispatch]);
89
+
90
+ if (!available) return null;
91
+
92
+ const anyRunning = isAnyFlowRunning(flowState, flowStates);
93
+ const hasFlows = flows.length > 0;
94
+
95
+ const flowOptions: SelectOption[] = flows.map((f) => ({
96
+ value: f.name,
97
+ label: f.name,
98
+ description: f.description,
99
+ }));
100
+ // Edit launcher options: existing flows + a "new flow" sentinel.
101
+ const editOptions: SelectOption[] = [
102
+ { value: "__new__", label: t("newFlowOption", undefined, "+ New flow"), description: t("newFlowOptionDesc", undefined, "Author a new flow with the edit-flow skill") },
103
+ ...flowOptions,
104
+ ];
105
+
106
+ const actions = [
107
+ ...(hasFlows
108
+ ? [{ label: t("runFlowButton", undefined, "Run Flow..."), icon: "mdiPlay", onClick: () => setPickerOpen(true) }]
109
+ : []),
110
+ ...(hasFlows
111
+ ? [{
112
+ label: t("openFlowButton", undefined, "Open flow…"),
113
+ icon: "mdiEyeOutline",
114
+ disabled: anyRunning,
115
+ tooltip: anyRunning ? t("openFlowDisabledRunning", undefined, "A flow is running") : undefined,
116
+ onClick: () => setOpenPickerOpen(true),
117
+ }]
118
+ : []),
119
+ ...(editMode
120
+ ? [{ label: t("newEditButton", undefined, "New / Edit…"), icon: "mdiPencil", onClick: () => setEditPickerOpen(true) }]
121
+ : []),
122
+ ...(hasFlowsDelete && hasFlows
123
+ ? [{ label: `${t("delete", undefined, "Delete")}…`, icon: "mdiDeleteOutline", onClick: () => setDeletePickerOpen(true) }]
124
+ : []),
125
+ ];
126
+
127
+ const onFlowAction = (action: string, opts?: { flowName?: string; task?: string }) =>
128
+ dispatch({
129
+ type: "flow_management",
130
+ sessionId: session.id,
131
+ action,
132
+ flowName: opts?.flowName,
133
+ task: opts?.task,
134
+ });
135
+
136
+ const onEditFlow = (flowName: string | undefined, instruction: string) => {
137
+ const intent = instruction.trim();
138
+ // New flow: instruction describes what to build. Edit: flow name is
139
+ // token-1 (the skill reads that file), instruction follows on a new line.
140
+ const text = flowName
141
+ ? intent
142
+ ? `/skill:manage-flows ${flowName}\n\n${intent}`
143
+ : `/skill:manage-flows ${flowName}`
144
+ : `/skill:manage-flows ${intent}`;
145
+ dispatch({ type: "send_prompt", sessionId: session.id, text });
146
+ };
147
+
148
+ return (
149
+ <>
150
+ {actions.length > 0 && <ActionList actions={actions} />}
151
+
152
+ {/* Run: pick flow → task dialog */}
153
+ {pickerOpen && (
154
+ <SearchableSelectDialog
155
+ title={t("runFlowDialogTitle", undefined, "Run Flow")}
156
+ options={flowOptions}
157
+ placeholder={t("searchFlows", undefined, "Search flows...")}
158
+ emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
159
+ onSelect={(value) => {
160
+ const flow = flows.find((f) => f.name === value);
161
+ if (flow) setSelectedFlow(flow);
162
+ setPickerOpen(false);
163
+ }}
164
+ onCancel={() => setPickerOpen(false)}
165
+ />
166
+ )}
167
+
168
+ {selectedFlow && (
169
+ <FlowLaunchDialog
170
+ flowName={selectedFlow.name}
171
+ description={selectedFlow.description}
172
+ onSubmit={(task) => {
173
+ onFlowAction("run", { flowName: selectedFlow.name, task: task || undefined });
174
+ setSelectedFlow(null);
175
+ }}
176
+ onCancel={() => setSelectedFlow(null)}
177
+ />
178
+ )}
179
+
180
+ {/* Open: pick flow → attach it to the flow slot (not started). See change:
181
+ attach-flow-before-run (D7). */}
182
+ {openPickerOpen && (
183
+ <SearchableSelectDialog
184
+ title={t("openFlowDialogTitle", undefined, "Open flow")}
185
+ options={flowOptions}
186
+ placeholder={t("searchFlows", undefined, "Search flows...")}
187
+ emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
188
+ onSelect={(value) => {
189
+ const flow = flows.find((f) => f.name === value);
190
+ if (flow) {
191
+ // Baseline = newest flow_started seen now; null on an empty (not yet
192
+ // replayed) stream — the flow slot resolves it from the first batch.
193
+ // See change: attach-flow-before-run (D4).
194
+ setAttachment(session.id, {
195
+ id: newAttachmentId(),
196
+ name: flow.name,
197
+ source: flow.source,
198
+ baselineStartedAt: events.length > 0 ? (lastFlowStartedAt ?? 0) : null,
199
+ });
200
+ }
201
+ setOpenPickerOpen(false);
202
+ }}
203
+ onCancel={() => setOpenPickerOpen(false)}
204
+ />
205
+ )}
206
+
207
+ {/* New / Edit: pick an existing flow or "new" → launch the edit-flow skill */}
208
+ {editPickerOpen && (
209
+ <SearchableSelectDialog
210
+ title={t("newEditFlowTitle", undefined, "New / Edit flow")}
211
+ options={editOptions}
212
+ placeholder={t("pickFlowToEdit", undefined, "Pick a flow to edit, or + New flow…")}
213
+ emptyMessage={t("noFlowsYet", undefined, "No flows yet — pick + New flow")}
214
+ onSelect={(value) => {
215
+ setAuthorTarget(
216
+ value === "__new__" ? { mode: "new" } : { mode: "edit", flowName: value },
217
+ );
218
+ setEditPickerOpen(false);
219
+ }}
220
+ onCancel={() => setEditPickerOpen(false)}
221
+ />
222
+ )}
223
+
224
+ {/* New / Edit: capture intent → launch the manage-flows skill */}
225
+ {authorTarget && (
226
+ <FlowAuthorPromptDialog
227
+ mode={authorTarget.mode}
228
+ flowName={authorTarget.flowName}
229
+ onSubmit={(instruction) => {
230
+ onEditFlow(authorTarget.flowName, instruction);
231
+ setAuthorTarget(null);
232
+ }}
233
+ onCancel={() => setAuthorTarget(null)}
234
+ />
235
+ )}
236
+
237
+ {/* Delete: pick flow → confirm dialog */}
238
+ {deletePickerOpen && (
239
+ <SearchableSelectDialog
240
+ title={t("deleteFlowTitle", undefined, "Delete Flow")}
241
+ options={flowOptions}
242
+ placeholder={t("searchFlows", undefined, "Search flows...")}
243
+ emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
244
+ onSelect={(value) => {
245
+ setDeleteFlowName(value);
246
+ setDeletePickerOpen(false);
247
+ }}
248
+ onCancel={() => setDeletePickerOpen(false)}
249
+ />
250
+ )}
251
+
252
+ {deleteFlowName && (
253
+ <ConfirmDialog
254
+ message={t("deleteFlowConfirm", { name: deleteFlowName }, `Delete flow "${deleteFlowName}"? This will remove the flow file and any associated agents.`)}
255
+ confirmLabel={t("delete", undefined, "Delete")}
256
+ onConfirm={() => {
257
+ onFlowAction("delete", { flowName: deleteFlowName });
258
+ setDeleteFlowName(null);
259
+ }}
260
+ onCancel={() => setDeleteFlowName(null)}
261
+ />
262
+ )}
263
+ </>
264
+ );
265
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Per-session "attached flow" store for the attach-before-run panel.
3
+ *
4
+ * Module-level `Map<sessionId, FlowAttachment | null>` persisted as JSON under
5
+ * `dashboard:flow-attached:<sessionId>` and exposed via `useSyncExternalStore`
6
+ * (pattern of `FlowsUiStateContext`). `getAttachment` returns the SAME cached
7
+ * object until that session's entry is written or cleared, so React does not
8
+ * loop. localStorage access is try/catch-swallowed (as in
9
+ * `flow-collapse-storage.ts`) — storage failure degrades to in-memory. A
10
+ * `window` `storage` listener keeps tabs of the same browser in sync.
11
+ *
12
+ * Shared by `SessionFlowActions` (writes on Open) and `FlowDashboardClaim`
13
+ * (reads, resolves baseline, deletes on consume / Close).
14
+ * See change: attach-flow-before-run (D5).
15
+ */
16
+ import { useCallback, useSyncExternalStore } from "react";
17
+ import type { FlowAttachment } from "./flow-idle-state.js";
18
+
19
+ const KEY_PREFIX = "dashboard:flow-attached:";
20
+
21
+ export function flowAttachKey(sessionId: string): string {
22
+ return `${KEY_PREFIX}${sessionId}`;
23
+ }
24
+
25
+ const cache = new Map<string, FlowAttachment | null>();
26
+ const subscribers = new Map<string, Set<() => void>>();
27
+
28
+ function parse(raw: string | null): FlowAttachment | null {
29
+ if (!raw) return null;
30
+ try {
31
+ const v = JSON.parse(raw) as Partial<FlowAttachment> | null;
32
+ if (!v || typeof v.id !== "string" || typeof v.name !== "string") return null;
33
+ // Coerce the rest so a legacy / hand-edited entry cannot strand the panel.
34
+ return {
35
+ id: v.id,
36
+ name: v.name,
37
+ source: typeof v.source === "string" ? v.source : undefined,
38
+ baselineStartedAt:
39
+ typeof v.baselineStartedAt === "number" && Number.isFinite(v.baselineStartedAt) ? v.baselineStartedAt : null,
40
+ };
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ function notify(sessionId: string): void {
47
+ const set = subscribers.get(sessionId);
48
+ if (set) for (const cb of set) cb();
49
+ }
50
+
51
+ function write(sessionId: string, value: FlowAttachment | null): void {
52
+ cache.set(sessionId, value);
53
+ try {
54
+ if (value) localStorage.setItem(flowAttachKey(sessionId), JSON.stringify(value));
55
+ else localStorage.removeItem(flowAttachKey(sessionId));
56
+ } catch {
57
+ /* noop — degrade to in-memory */
58
+ }
59
+ notify(sessionId);
60
+ }
61
+
62
+ /** Current attachment for a session (stable reference until written). */
63
+ export function getAttachment(sessionId: string): FlowAttachment | null {
64
+ if (!cache.has(sessionId)) {
65
+ let raw: string | null = null;
66
+ try {
67
+ raw = localStorage.getItem(flowAttachKey(sessionId));
68
+ } catch {
69
+ /* noop */
70
+ }
71
+ cache.set(sessionId, parse(raw));
72
+ }
73
+ return cache.get(sessionId) ?? null;
74
+ }
75
+
76
+ /** Attach a flow (replaces any existing attachment for the session). */
77
+ export function setAttachment(sessionId: string, attachment: FlowAttachment): void {
78
+ write(sessionId, attachment);
79
+ }
80
+
81
+ /** Set a still-null baseline, only when the stored entry has `id`. */
82
+ export function resolveBaseline(sessionId: string, id: string, baselineStartedAt: number): void {
83
+ const cur = getAttachment(sessionId);
84
+ if (!cur || cur.id !== id || cur.baselineStartedAt !== null) return;
85
+ write(sessionId, { ...cur, baselineStartedAt });
86
+ }
87
+
88
+ /** Remove the attachment; with `id`, only when the stored entry still has it. */
89
+ export function clearAttachment(sessionId: string, id?: string): void {
90
+ const cur = getAttachment(sessionId);
91
+ if (!cur) return;
92
+ if (id !== undefined && cur.id !== id) return;
93
+ write(sessionId, null);
94
+ }
95
+
96
+ /** Random per-attach token. */
97
+ export function newAttachmentId(): string {
98
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
99
+ }
100
+
101
+ function subscribe(sessionId: string, cb: () => void): () => void {
102
+ let set = subscribers.get(sessionId);
103
+ if (!set) {
104
+ set = new Set();
105
+ subscribers.set(sessionId, set);
106
+ }
107
+ set.add(cb);
108
+ return () => {
109
+ set.delete(cb);
110
+ if (set.size === 0) subscribers.delete(sessionId);
111
+ };
112
+ }
113
+
114
+ /** React hook — the session's attachment, re-rendering on any change. */
115
+ export function useFlowAttachment(sessionId: string): FlowAttachment | null {
116
+ const sub = useCallback((cb: () => void) => subscribe(sessionId, cb), [sessionId]);
117
+ const get = useCallback(() => getAttachment(sessionId), [sessionId]);
118
+ return useSyncExternalStore(sub, get, get);
119
+ }
120
+
121
+ // Cross-tab sync: another tab of this browser wrote/removed an attachment.
122
+ if (typeof window !== "undefined") {
123
+ window.addEventListener("storage", (e: StorageEvent) => {
124
+ if (e.key === null) {
125
+ const ids = Array.from(cache.keys());
126
+ cache.clear();
127
+ for (const id of ids) notify(id);
128
+ return;
129
+ }
130
+ if (!e.key.startsWith(KEY_PREFIX)) return;
131
+ const sessionId = e.key.slice(KEY_PREFIX.length);
132
+ cache.set(sessionId, parse(e.newValue));
133
+ notify(sessionId);
134
+ });
135
+ }
136
+
137
+ /** Test-only: drop the in-memory cache (subscribers kept). */
138
+ export function __resetFlowAttachStoreForTests(): void {
139
+ cache.clear();
140
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Shared geometry for the flow agent-card grid.
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.
6
+ * The classes are written as literals (not interpolated from the constants) so
7
+ * Tailwind's source scanner can see them; the constants stay the numeric truth
8
+ * the specs pin against. See change: consolidate-flow-agent-cards (D1, D5).
9
+ */
10
+
11
+ /** Row-track minimum for a full card (px). */
12
+ export const FLOW_CARD_ROW_MIN = 124;
13
+ /** Row-track minimum for a compact tile below the pane threshold (px). */
14
+ export const FLOW_CARD_ROW_MIN_COMPACT = 76;
15
+ /** Grid column minimum (px) — `repeat(auto-fill, minmax(190px, 1fr))`. */
16
+ export const FLOW_CARD_COLUMN_MIN = 190;
17
+ /** Grid gap (px) — `gap-2`. */
18
+ export const FLOW_CARD_GAP = 8;
19
+ /** Pane width at or below which the grid collapses to compact tiles (px). */
20
+ export const FLOW_CARD_COMPACT_MAX_PX = 480;
21
+
22
+ /**
23
+ * Outer wrapper: the query container. An element cannot query itself, so the
24
+ * grid below carries the variants against THIS element's inline size — the
25
+ * PANE width, not the viewport. `min-w-0` lets it shrink inside the flex pane.
26
+ */
27
+ export const FLOW_CARD_GRID_CONTAINER_CLASS = "@container min-w-0";
28
+
29
+ /**
30
+ * Inner grid: auto-fill columns, one row track shared by the row's cards, and
31
+ * the compact single-column treatment below {@link FLOW_CARD_COMPACT_MAX_PX}.
32
+ * Cards fill the cell (`h-full` on the `data-step` wrapper + `[&>*]:h-full`).
33
+ */
34
+ export const FLOW_CARD_GRID_CLASS =
35
+ "grid gap-2 grid-cols-[repeat(auto-fill,minmax(190px,1fr))] auto-rows-[minmax(124px,auto)]" +
36
+ " @max-[480px]:grid-cols-1 @max-[480px]:auto-rows-[minmax(76px,auto)]";
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Client access to a session's flow files (flow YAML, agent `.md`, code-node
3
+ * handlers) via the flows-plugin server (`/api/plugins/flows/file|files`, fed
4
+ * by this plugin's bridge) — so files in runtime-registered flow dirs open —
5
+ * falling back to the host `/api/pi-resource-file` (project `.pi/**`,
6
+ * `~/.pi/agent/**`, `node_modules/**`). Never touches host core.
7
+ * See change: attach-flow-before-run.
8
+ */
9
+ import type { FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
10
+ import { useCallback, useEffect, useState } from "react";
11
+ import { useLocation } from "wouter";
12
+
13
+ const RETRY_MS = 1_200;
14
+
15
+ const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
16
+
17
+ async function readJson(r: Response): Promise<Record<string, unknown> | null> {
18
+ try {
19
+ return (await r.json()) as Record<string, unknown>;
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ function contentOf(json: Record<string, unknown> | null): string | null {
26
+ const data = json?.data as { content?: unknown } | undefined;
27
+ return json?.success && typeof data?.content === "string" ? data.content : null;
28
+ }
29
+
30
+ /** Read a flow-related file's content; throws `Error(message)` on failure. */
31
+ export async function fetchFlowFile(sessionId: string | undefined, filePath: string): Promise<string> {
32
+ if (sessionId) {
33
+ const url = `/api/plugins/flows/file?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(filePath)}`;
34
+ for (let attempt = 0; attempt < 2; attempt++) {
35
+ try {
36
+ const r = await fetch(url);
37
+ const json = await readJson(r);
38
+ const content = contentOf(json);
39
+ if (content !== null) return content;
40
+ if (r.status !== 409 || !json?.retry) break;
41
+ await wait(RETRY_MS);
42
+ } catch {
43
+ break; // network / plugin unavailable → host fallback
44
+ }
45
+ }
46
+ }
47
+ const r = await fetch(`/api/pi-resource-file?path=${encodeURIComponent(filePath)}`);
48
+ const json = await readJson(r);
49
+ const content = contentOf(json);
50
+ if (content !== null) return content;
51
+ throw new Error(typeof json?.error === "string" ? json.error : `HTTP ${r.status}`);
52
+ }
53
+
54
+ export interface FlowNodeFiles {
55
+ /** agent name → absolute agent file. */
56
+ agents: Record<string, string>;
57
+ /** flow name → step id → absolute code handler file. */
58
+ handlers: Record<string, Record<string, string>>;
59
+ }
60
+
61
+ /** The session's reported agent + handler file paths (null until known). */
62
+ export function useFlowNodeFiles(sessionId: string | undefined, enabled = true): FlowNodeFiles | null {
63
+ const [files, setFiles] = useState<FlowNodeFiles | null>(null);
64
+ useEffect(() => {
65
+ setFiles(null);
66
+ if (!sessionId || !enabled) return;
67
+ let cancelled = false;
68
+ void (async () => {
69
+ for (let attempt = 0; attempt < 4 && !cancelled; attempt++) {
70
+ try {
71
+ const r = await fetch(`/api/plugins/flows/files?sessionId=${encodeURIComponent(sessionId)}`);
72
+ const json = await readJson(r);
73
+ const data = json?.data as ({ reported?: unknown } & Partial<FlowNodeFiles>) | undefined;
74
+ if (!json?.success || !data) return;
75
+ if (data.reported === true) {
76
+ if (!cancelled) setFiles({ agents: data.agents ?? {}, handlers: data.handlers ?? {} });
77
+ return;
78
+ }
79
+ } catch {
80
+ return;
81
+ }
82
+ await wait(RETRY_MS);
83
+ }
84
+ })();
85
+ return () => {
86
+ cancelled = true;
87
+ };
88
+ }, [sessionId, enabled]);
89
+ return files;
90
+ }
91
+
92
+ /**
93
+ * Fill `sourcePath` (agent file) and `codeTarget` (handler file) on cards that
94
+ * do not carry them yet — idle cards never do, live cards only after
95
+ * `flow_agent_started`. Existing values are never overridden. Returns the SAME
96
+ * state when nothing changes.
97
+ */
98
+ export function withNodeFiles(state: FlowState, files: FlowNodeFiles | null): FlowState {
99
+ if (!files) return state;
100
+ const handlers = files.handlers[state.flowName] ?? {};
101
+ const steps = new Map((state.dagSteps ?? []).map((d) => [d.id, d]));
102
+ let agents: FlowState["agents"] | undefined;
103
+ for (const [key, a] of state.agents) {
104
+ const stepId = a.stepId || key;
105
+ const agentName = steps.get(stepId)?.agent ?? (a.nodeKind === "code" || a.nodeKind === "code-decision" ? undefined : a.agentName);
106
+ const sourcePath = a.sourcePath ?? (agentName ? files.agents[agentName] : undefined);
107
+ const codeTarget = a.codeTarget ?? handlers[stepId];
108
+ if (sourcePath === a.sourcePath && codeTarget === a.codeTarget) continue;
109
+ agents ??= new Map(state.agents);
110
+ agents.set(key, { ...a, sourcePath, codeTarget });
111
+ }
112
+ return agents ? { ...state, agents } : state;
113
+ }
114
+
115
+ /**
116
+ * Open a file in the host's built-in editor (Monaco, Split view) via its
117
+ * `/session/:id/editor?file=<path>` deep link — the same in-app route the
118
+ * host's own file links use. `null` without a session (no editor to target).
119
+ *
120
+ * Every call stamps a fresh `openNonce` into the history entry's state. The URL
121
+ * is byte-identical for the same file, so after the user closes the editor
122
+ * (pane close control, or just the file's tab) a second click would otherwise
123
+ * be indistinguishable from the re-render that follows the close — the host's
124
+ * apply-once key would not change and the split would never come back. The host
125
+ * folds the nonce into that key, so a deliberate open re-applies while a
126
+ * re-render at the same nonce stays a no-op. The nonce stays out of the URL, so
127
+ * a copied deep link is unchanged. See change: consolidate-flow-agent-cards (D8).
128
+ *
129
+ * The nonce must be unique across page loads: `history.state` survives a
130
+ * reload, but this module's counter restarts, so a bare counter would re-mint a
131
+ * value that already sits in the surviving entry (open file → nonce 1 → reload
132
+ * → close → click = nonce 1 again) and the swallowed open would recur. Hence a
133
+ * timestamp prefix plus the counter, as a string (the host accepts
134
+ * number|string).
135
+ */
136
+ let openNonceSeq = 0;
137
+
138
+ const nextOpenNonce = (): string => `${Date.now().toString(36)}-${(++openNonceSeq).toString(36)}`;
139
+
140
+ export function useOpenFileInEditor(sessionId: string | undefined): ((filePath: string) => void) | null {
141
+ const [, navigate] = useLocation();
142
+ const open = useCallback(
143
+ (filePath: string) => {
144
+ if (sessionId)
145
+ navigate(`/session/${encodeURIComponent(sessionId)}/editor?file=${encodeURIComponent(filePath)}`, {
146
+ state: { openNonce: nextOpenNonce() },
147
+ });
148
+ },
149
+ [navigate, sessionId],
150
+ );
151
+ return sessionId ? open : null;
152
+ }