@blackbelt-technology/pi-dashboard-flows-plugin 0.8.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.
@@ -8,6 +8,8 @@ import { FlowAgentCard } from "./FlowAgentCard.js";
8
8
  import { FlowGraph, flowStateToGraphSteps } from "./FlowGraph.js";
9
9
  import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
10
10
  import { FlowYamlPopoverButton } from "./FlowYamlPopoverButton.js";
11
+ import { FLOW_CARD_GRID_CLASS, FLOW_CARD_GRID_CONTAINER_CLASS } from "./flow-card-grid.js";
12
+ import { useFlowNodeFiles, withNodeFiles } from "./flow-files.js";
11
13
  import { useFlowCollapsePersisted } from "./flow-collapse-storage.js";
12
14
 
13
15
 
@@ -52,7 +54,10 @@ export function FlowSummary({
52
54
  // improve-flow-graph-dialog-and-card-interaction.
53
55
  const [selectedStepId, setSelectedStepId] = useState<string | null>(null);
54
56
  const rootRef = useRef<HTMLDivElement>(null);
55
- const agents = Array.from(flowState.agents.values());
57
+ // Agent / handler file paths for the frozen cards' file buttons.
58
+ // See change: attach-flow-before-run.
59
+ const nodeFiles = useFlowNodeFiles(sessionId ?? session?.id);
60
+ const agents = Array.from(withNodeFiles(flowState, nodeFiles).agents.values());
56
61
  // Only summary-bearing agents are listed in the Summaries subsection (others
57
62
  // stay in the frozen cards + graph). See change: fix-flow-ui-graph-zoom-summary.
58
63
  const summarised = agents.filter(a => a.summary);
@@ -137,6 +142,7 @@ export function FlowSummary({
137
142
  <FlowYamlPopoverButton
138
143
  flowSource={flowState.flowSource}
139
144
  flowName={flowState.flowName}
145
+ sessionId={sessionId ?? session?.id}
140
146
  />
141
147
  </div>
142
148
  )}
@@ -145,22 +151,22 @@ export function FlowSummary({
145
151
  the whole panel always fits the viewport (no page scroll). The summaries
146
152
  section and each agent row stay independently collapsible inside it. */}
147
153
  <div className="mt-2 overflow-y-auto" style={{ maxHeight: "48vh" }} data-testid="flow-summary-scrollbox">
148
- {/* Frozen agent cards — read-only. */}
154
+ {/* Frozen agent cards — read-only. Same grid geometry as the live panel
155
+ (shared helper); the wrapper is the query container (design D1/D5). */}
149
156
  {agents.length > 0 && (
150
- <div
151
- className="grid gap-2"
152
- style={{ gridTemplateColumns: `repeat(auto-fill, minmax(200px, 1fr))` }}
153
- >
154
- {agents.map(agent => (
155
- <FlowAgentCard
156
- key={agent.stepId || agent.agentName}
157
- agent={agent}
158
- session={session}
159
- sessionId={sessionId ?? session?.id}
160
- selected={selectedStepId === (agent.stepId || agent.agentName)}
161
- onSelect={handleSelectStep}
162
- />
163
- ))}
157
+ <div className={FLOW_CARD_GRID_CONTAINER_CLASS}>
158
+ <div className={FLOW_CARD_GRID_CLASS}>
159
+ {agents.map(agent => (
160
+ <FlowAgentCard
161
+ key={agent.stepId || agent.agentName}
162
+ agent={agent}
163
+ session={session}
164
+ sessionId={sessionId ?? session?.id}
165
+ selected={selectedStepId === (agent.stepId || agent.agentName)}
166
+ onSelect={handleSelectStep}
167
+ />
168
+ ))}
169
+ </div>
164
170
  </div>
165
171
  )}
166
172
 
@@ -1,110 +1,45 @@
1
1
  /**
2
- * FlowYamlPopoverButton — paper-icon button that opens a popover anchored
3
- * to itself, fetches the flow's YAML at `/api/pi-resource-file?path=...`,
4
- * and renders it inside the popover via the `ui:markdown-content` primitive
5
- * (wrapped in a `yaml` code fence for syntax highlighting).
2
+ * FlowYamlPopoverButton — paper-icon button that opens the flow's YAML in the
3
+ * host's built-in editor (Split view) via `useOpenFileInEditor`. Hidden without
4
+ * a session (no editor to target).
6
5
  *
7
- * Used by `FlowDashboard` (live flow) and `FlowSummary` (completed flow).
6
+ * Used by `FlowDashboard` (live / idle flow) and `FlowSummary` (completed flow).
8
7
  *
9
8
  * The flow's YAML path is emitted by pi-flows in the `flow:flow-started`
10
- * event (see `packages/pi-flows/extensions/flow-engine/flow-tui.ts:487` —
11
- * `source: flow.source`) and stored on `FlowState.flowSource` by the flow
12
- * reducer.
9
+ * event (`source: flow.source`) and stored on `FlowState.flowSource` by the
10
+ * flow reducer; an attached idle flow carries it from `flowsList`.
13
11
  *
14
- * See change: add-ui-popover-primitive.
12
+ * See change: add-ui-popover-primitive, attach-flow-before-run.
15
13
  */
16
- import React, { useEffect, useState } from "react";
17
- import { Icon } from "@mdi/react";
14
+ import { useT } from "@blackbelt-technology/dashboard-plugin-runtime";
18
15
  import { mdiFileDocumentOutline } from "@mdi/js";
19
- import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
20
- import { useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
21
-
22
- type YamlFetchState =
23
- | { kind: "idle" }
24
- | { kind: "loading" }
25
- | { kind: "loaded"; content: string }
26
- | { kind: "error"; error: string };
16
+ import { Icon } from "@mdi/react";
17
+ import { useOpenFileInEditor } from "./flow-files.js";
27
18
 
28
19
  export function FlowYamlPopoverButton({
29
20
  flowSource,
30
21
  flowName,
22
+ sessionId,
31
23
  }: {
32
24
  flowSource: string;
33
25
  flowName: string;
26
+ /** Owning session — the editor to open the YAML in. */
27
+ sessionId?: string;
34
28
  }) {
35
- const Dialog = useUiPrimitive(UI_PRIMITIVE_KEYS.dialog);
36
- const MarkdownContent = useUiPrimitive(UI_PRIMITIVE_KEYS.markdownContent);
37
- const [open, setOpen] = useState(false);
38
- const [state, setState] = useState<YamlFetchState>({ kind: "idle" });
39
-
40
- // Deps include only `open` + `flowSource`. Including state.kind would
41
- // cause cleanup to fire on the idle→loading transition, self-cancelling
42
- // the fetch. Same pattern as `usePiResourceFileFetch` in the client.
43
- useEffect(() => {
44
- if (!open) return;
45
- let cancelled = false;
46
- setState({ kind: "loading" });
47
- fetch(`/api/pi-resource-file?path=${encodeURIComponent(flowSource)}`)
48
- .then(async (r) => {
49
- const json = await r.json();
50
- if (cancelled) return;
51
- if (json?.success && typeof json?.data?.content === "string") {
52
- setState({ kind: "loaded", content: json.data.content });
53
- } else {
54
- setState({
55
- kind: "error",
56
- error: typeof json?.error === "string" ? json.error : "Failed to read flow YAML",
57
- });
58
- }
59
- })
60
- .catch((err) => {
61
- if (!cancelled) setState({ kind: "error", error: String(err) });
62
- });
63
- return () => {
64
- cancelled = true;
65
- };
66
- }, [open, flowSource]);
67
-
29
+ const t = useT();
30
+ const openInEditor = useOpenFileInEditor(sessionId);
31
+ if (!openInEditor) return null;
68
32
  return (
69
- <>
70
- <button
71
- onClick={(e) => {
72
- e.stopPropagation();
73
- setOpen((prev) => !prev);
74
- }}
75
- className={`transition-colors p-0.5 rounded inline-flex items-center ${
76
- open
77
- ? "text-blue-400 bg-blue-400/10"
78
- : "text-[var(--text-tertiary)] hover:text-blue-400 hover:bg-[var(--bg-surface)]"
79
- }`}
80
- title={open ? "Close flow YAML" : `View ${flowName} YAML`}
81
- >
82
- <Icon path={mdiFileDocumentOutline} size={0.5} />
83
- </button>
84
- <Dialog
85
- open={open}
86
- onClose={() => setOpen(false)}
87
- title={`${flowName} · YAML`}
88
- size="lg"
89
- >
90
- {/* Pinned path header; YAML scrolls inside a fixed-height region so the
91
- dialog stays a fixed size. See change:
92
- improve-flow-graph-dialog-and-card-interaction. */}
93
- <div className="text-[11px] text-[var(--text-tertiary)] font-mono break-all" title={flowSource}>
94
- {flowSource}
95
- </div>
96
- <div className="h-[60vh] overflow-y-auto">
97
- {state.kind === "loading" && (
98
- <div className="text-xs text-[var(--text-muted)]">Loading…</div>
99
- )}
100
- {state.kind === "error" && (
101
- <div className="text-xs text-red-400">⚠ {state.error}</div>
102
- )}
103
- {state.kind === "loaded" && (
104
- <MarkdownContent content={"```yaml\n" + state.content + "\n```"} />
105
- )}
106
- </div>
107
- </Dialog>
108
- </>
33
+ <button
34
+ type="button"
35
+ onClick={(e) => {
36
+ e.stopPropagation();
37
+ openInEditor(flowSource);
38
+ }}
39
+ className="transition-colors p-0.5 rounded inline-flex items-center text-[var(--text-tertiary)] hover:text-blue-400 hover:bg-[var(--bg-surface)]"
40
+ title={t("openFlowYamlInEditor", { name: flowName }, `Open ${flowName} YAML in editor`)}
41
+ >
42
+ <Icon path={mdiFileDocumentOutline} size={0.5} />
43
+ </button>
109
44
  );
110
45
  }
@@ -24,13 +24,15 @@
24
24
  *
25
25
  * See change: pluginize-flows-via-registry.
26
26
  */
27
- import { useMemo } from "react";
27
+
28
+ import { useSessionEvents } from "@blackbelt-technology/dashboard-plugin-runtime";
28
29
  import type {
29
- FlowState,
30
30
  DashboardEvent,
31
+ FlowState,
31
32
  } from "@blackbelt-technology/pi-dashboard-shared/types.js";
32
- import { useSessionEvents } from "@blackbelt-technology/dashboard-plugin-runtime";
33
+ import { useMemo } from "react";
33
34
  import { isFlowEvent, reduceFlowEvent } from "../reducer.js";
35
+ import { toEventTime } from "./flow-idle-state.js";
34
36
 
35
37
  /** Shape exposed to flows-plugin components for a single session. */
36
38
  export interface FlowsSessionState {
@@ -42,6 +44,14 @@ export interface FlowsSessionState {
42
44
  * (FlowDashboard's multi-flow tab bar).
43
45
  */
44
46
  flowStates: ReadonlyMap<string, FlowState>;
47
+ /** Epoch ms of the newest `flow_started` in the stream (attach baseline /
48
+ * consumption clock). See change: attach-flow-before-run (D4). */
49
+ lastFlowStartedAt?: number;
50
+ /** Latest autonomous mode seen (`flow_started.autonomousMode` or
51
+ * `flow_autonomous_changed.enabled`), captured even with no flowState (D8). */
52
+ lastAutonomousMode?: boolean;
53
+ /** Latest start pi-flows refused (`flow_complete` status `rejected`) (D7). */
54
+ lastRejection?: { flowName: string; reason?: string; timestamp: number };
45
55
  }
46
56
 
47
57
  const EMPTY_STATE: FlowsSessionState = Object.freeze({
@@ -70,6 +80,9 @@ export function reduceFlowsSessionState(
70
80
  let flowState: FlowState | null = null;
71
81
  let flowStates: Map<string, FlowState> = new Map();
72
82
  let flowStatesMutated = false;
83
+ let lastFlowStartedAt: number | undefined;
84
+ let lastAutonomousMode: boolean | undefined;
85
+ let lastRejection: FlowsSessionState["lastRejection"];
73
86
 
74
87
  // Diagnostic counter for C1 — see fix-flows-plugin-polish. Gated to dev.
75
88
  let flowEventCount = 0;
@@ -77,6 +90,20 @@ export function reduceFlowsSessionState(
77
90
  for (const event of events) {
78
91
  if (isFlowEvent(event.eventType)) {
79
92
  flowEventCount++;
93
+ const data = event.data ?? {};
94
+ if (event.eventType === "flow_started") {
95
+ const ts = toEventTime(event.timestamp);
96
+ if (lastFlowStartedAt === undefined || ts > lastFlowStartedAt) lastFlowStartedAt = ts;
97
+ if (typeof data.autonomousMode === "boolean") lastAutonomousMode = data.autonomousMode;
98
+ } else if (event.eventType === "flow_autonomous_changed") {
99
+ if (typeof data.enabled === "boolean") lastAutonomousMode = data.enabled;
100
+ } else if (event.eventType === "flow_complete" && data.status === "rejected") {
101
+ lastRejection = {
102
+ flowName: String(data.flowName ?? ""),
103
+ reason: typeof data.reason === "string" ? data.reason : undefined,
104
+ timestamp: toEventTime(event.timestamp),
105
+ };
106
+ }
80
107
  flowState = reduceFlowEvent(flowState, event);
81
108
  if (flowState) {
82
109
  if (!flowStatesMutated) {
@@ -109,13 +136,22 @@ export function reduceFlowsSessionState(
109
136
  }
110
137
  }
111
138
 
112
- if (flowState === null && flowStates.size === 0) {
139
+ if (
140
+ flowState === null &&
141
+ flowStates.size === 0 &&
142
+ lastFlowStartedAt === undefined &&
143
+ lastAutonomousMode === undefined &&
144
+ lastRejection === undefined
145
+ ) {
113
146
  return EMPTY_STATE;
114
147
  }
115
148
 
116
149
  return {
117
150
  flowState,
118
151
  flowStates,
152
+ lastFlowStartedAt,
153
+ lastAutonomousMode,
154
+ lastRejection,
119
155
  };
120
156
  }
121
157
 
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  usePluginSend,
3
3
  useSessionData,
4
+ useSessionEvents,
4
5
  useT,
5
6
  useUiPrimitive,
6
7
  } from "@blackbelt-technology/dashboard-plugin-runtime";
@@ -13,7 +14,7 @@ import type {
13
14
  FlowInfo,
14
15
  FlowState,
15
16
  } from "@blackbelt-technology/pi-dashboard-shared/types.js";
16
- import { mdiPencil, mdiPlay } from "@mdi/js";
17
+ import { mdiEyeOutline, mdiPencil, mdiPlay } from "@mdi/js";
17
18
  import { Icon } from "@mdi/react";
18
19
  import React, { useEffect, useMemo, useRef, useState } from "react";
19
20
  import { FlowActivityBadge } from "./FlowActivityBadge.js";
@@ -21,8 +22,34 @@ import { FlowAuthorPromptDialog } from "./FlowAuthorPromptDialog.js";
21
22
  import { FlowLaunchDialog } from "./FlowLaunchDialog.js";
22
23
  import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
23
24
  import type { FlowsPluginConfig } from "./FlowsSettings.js";
25
+ import { newAttachmentId, setAttachment } from "./flow-attach-store.js";
24
26
  import { makeSafeSend } from "./send-safe.js";
25
27
 
28
+ /** Open flow… — disabled (with tooltip) while any flow runs. See change:
29
+ * attach-flow-before-run (D7). */
30
+ function OpenFlowButton({ disabled, onClick }: { disabled: boolean; onClick: () => void }) {
31
+ const t = useT();
32
+ return (
33
+ <button
34
+ onClick={(e) => { e.stopPropagation(); onClick(); }}
35
+ disabled={disabled}
36
+ title={disabled ? t("openFlowDisabledRunning", undefined, "A flow is running") : undefined}
37
+ className="text-[10px] px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-secondary)] hover:bg-[var(--bg-hover)] disabled:opacity-50 disabled:cursor-not-allowed"
38
+ data-testid="flows-open-button"
39
+ >
40
+ <Icon path={mdiEyeOutline} size={0.4} className="inline mr-0.5" />{t("openFlowButton", undefined, "Open flow…")}
41
+ </button>
42
+ );
43
+ }
44
+
45
+ function isAnyFlowRunning(
46
+ flowState: FlowState | null | undefined,
47
+ flowStates: ReadonlyMap<string, FlowState> | undefined,
48
+ ): boolean {
49
+ if (flowState?.status === "running") return true;
50
+ return flowStates ? Array.from(flowStates.values()).some((s) => s.status === "running") : false;
51
+ }
52
+
26
53
  export function SessionFlowActions({
27
54
  flows,
28
55
  editMode,
@@ -30,7 +57,9 @@ export function SessionFlowActions({
30
57
  onFlowAction,
31
58
  onEditFlow,
32
59
  flowState,
60
+ flowStates,
33
61
  onAbortFlow,
62
+ onOpenFlow,
34
63
  }: {
35
64
  flows: FlowInfo[];
36
65
  /** Edit-mode on → show the New / Edit launcher (authoring via the skill). */
@@ -47,11 +76,17 @@ export function SessionFlowActions({
47
76
  flowState?: FlowState | null;
48
77
  /** Dispatch flow_control abort. Called by the running-flow pill's Abort button. */
49
78
  onAbortFlow?: () => void;
79
+ /** All flow states this session — Open is disabled while any is running. */
80
+ flowStates?: ReadonlyMap<string, FlowState>;
81
+ /** Attach a flow to the session flow slot before it runs. See change:
82
+ * attach-flow-before-run (D7). */
83
+ onOpenFlow?: (flow: FlowInfo) => void;
50
84
  }) {
51
85
  const t = useT();
52
86
  const ConfirmDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.confirmDialog);
53
87
  const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
54
88
  const [pickerOpen, setPickerOpen] = useState(false);
89
+ const [openPickerOpen, setOpenPickerOpen] = useState(false);
55
90
  const [editPickerOpen, setEditPickerOpen] = useState(false);
56
91
  // After picking from the edit launcher, capture intent before launching the skill.
57
92
  const [authorTarget, setAuthorTarget] = useState<{ mode: "new" | "edit"; flowName?: string } | null>(null);
@@ -79,6 +114,8 @@ export function SessionFlowActions({
79
114
 
80
115
  if (flows.length === 0 && !editMode && !badgeProps) return null;
81
116
 
117
+ const anyRunning = isAnyFlowRunning(flowState, flowStates);
118
+
82
119
  const flowOptions: SelectOption[] = flows.map((f) => ({
83
120
  value: f.name,
84
121
  label: f.name,
@@ -108,6 +145,9 @@ export function SessionFlowActions({
108
145
  <Icon path={mdiPlay} size={0.4} className="inline mr-0.5" />{t("runFlowButton", undefined, "Run Flow...")}
109
146
  </button>
110
147
  )}
148
+ {onOpenFlow && flows.length > 0 && (
149
+ <OpenFlowButton disabled={anyRunning} onClick={() => setOpenPickerOpen(true)} />
150
+ )}
111
151
  {editMode && (
112
152
  <button
113
153
  onClick={(e) => { e.stopPropagation(); setEditPickerOpen(true); }}
@@ -156,6 +196,22 @@ export function SessionFlowActions({
156
196
  />
157
197
  )}
158
198
 
199
+ {/* Open: pick flow → attach it to the flow slot (not started). */}
200
+ {openPickerOpen && onOpenFlow && (
201
+ <SearchableSelectDialog
202
+ title={t("openFlowDialogTitle", undefined, "Open flow")}
203
+ options={flowOptions}
204
+ placeholder={t("searchFlows", undefined, "Search flows...")}
205
+ emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
206
+ onSelect={(value) => {
207
+ const flow = flows.find((f) => f.name === value);
208
+ if (flow) onOpenFlow(flow);
209
+ setOpenPickerOpen(false);
210
+ }}
211
+ onCancel={() => setOpenPickerOpen(false)}
212
+ />
213
+ )}
214
+
159
215
  {/* New / Edit: pick an existing flow or "new" → launch the edit-flow skill */}
160
216
  {editPickerOpen && (
161
217
  <SearchableSelectDialog
@@ -230,7 +286,8 @@ export function SessionFlowActions({
230
286
  export function SessionFlowActionsClaim({ session }: { session: DashboardSession }) {
231
287
  const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
232
288
  const commands = useSessionData<CommandInfo[]>(session.id, "commandsList") ?? [];
233
- const { flowState } = useFlowsSessionState(session.id);
289
+ const { flowState, flowStates, lastFlowStartedAt } = useFlowsSessionState(session.id);
290
+ const events = useSessionEvents(session.id);
234
291
  const send = usePluginSend();
235
292
  // The edit-mode reconcile effect and the author-prompt handler cannot own the
236
293
  // send promise — discard it explicitly.
@@ -262,6 +319,18 @@ export function SessionFlowActionsClaim({ session }: { session: DashboardSession
262
319
  editMode={editMode}
263
320
  hasFlowsDelete={hasFlowsDelete}
264
321
  flowState={flowState}
322
+ flowStates={flowStates}
323
+ onOpenFlow={(flow) =>
324
+ // Baseline = newest flow_started seen now; null on an empty (not yet
325
+ // replayed) stream — the flow slot resolves it from the first batch.
326
+ // See change: attach-flow-before-run (D4).
327
+ setAttachment(session.id, {
328
+ id: newAttachmentId(),
329
+ name: flow.name,
330
+ source: flow.source,
331
+ baselineStartedAt: events.length > 0 ? (lastFlowStartedAt ?? 0) : null,
332
+ })
333
+ }
265
334
  onAbortFlow={() => send({ type: "flow_control", sessionId: session.id, action: "abort" })}
266
335
  onEditFlow={(flowName, instruction) => {
267
336
  const intent = instruction.trim();
@@ -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)]";