@blackbelt-technology/pi-dashboard-flows-plugin 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/package.json +18 -7
  2. package/src/bridge/flow-files-reporter.ts +113 -0
  3. package/src/bridge/index.ts +5 -1
  4. package/src/client/FlowAgentCard.tsx +82 -213
  5. package/src/client/FlowAgentDetail.tsx +1 -1
  6. package/src/client/FlowDashboard.tsx +428 -66
  7. package/src/client/FlowInputWiring.tsx +2 -2
  8. package/src/client/FlowSummary.tsx +22 -16
  9. package/src/client/FlowYamlPopoverButton.tsx +27 -92
  10. package/src/client/FlowsCommandRoutes.tsx +13 -5
  11. package/src/client/FlowsSessionStateContext.tsx +40 -4
  12. package/src/client/FlowsSettings.tsx +4 -4
  13. package/src/client/SessionFlowActions.tsx +80 -6
  14. package/src/client/flow-attach-store.ts +140 -0
  15. package/src/client/flow-card-grid.ts +36 -0
  16. package/src/client/flow-files.ts +152 -0
  17. package/src/client/flow-idle-state.ts +230 -0
  18. package/src/client/format-cost.ts +21 -0
  19. package/src/client/send-safe.ts +19 -0
  20. package/src/flow-files-contract.ts +21 -0
  21. package/src/flow-reducer.ts +4 -0
  22. package/src/i18n.ts +28 -0
  23. package/src/server/automation-actions.ts +3 -0
  24. package/src/server/flow-files.ts +264 -0
  25. package/src/server/index.ts +15 -0
  26. package/src/AGENTS.md +0 -8
  27. package/src/__tests__/FlowGraph.test.ts +0 -305
  28. package/src/__tests__/FlowInputWiring.test.tsx +0 -97
  29. package/src/__tests__/FlowSummary.test.tsx +0 -331
  30. package/src/__tests__/FlowYamlPreview.test.tsx +0 -75
  31. package/src/__tests__/FlowsSessionStateContext.test.tsx +0 -223
  32. package/src/__tests__/FlowsUiStateContext.test.tsx +0 -140
  33. package/src/__tests__/authoring-renderers.test.tsx +0 -190
  34. package/src/__tests__/automation-actions.test.ts +0 -117
  35. package/src/__tests__/flow-agent-card-code-source.test.tsx +0 -190
  36. package/src/__tests__/flow-agent-cost.test.tsx +0 -160
  37. package/src/__tests__/flow-agent-error.test.ts +0 -60
  38. package/src/__tests__/flow-collapse-storage.test.ts +0 -90
  39. package/src/__tests__/flow-edges.test.ts +0 -195
  40. package/src/__tests__/flow-inputs.test.ts +0 -69
  41. package/src/__tests__/flow-reducer-bridge-contract.test.ts +0 -108
  42. package/src/__tests__/flow-reducer-seed-on-start.test.ts +0 -61
  43. package/src/__tests__/flow-yaml-parse.test.ts +0 -124
  44. package/src/__tests__/flows-for-cwd.test.ts +0 -51
  45. package/src/__tests__/flowsAvailability.test.ts +0 -79
  46. package/src/__tests__/manifest-discoverability.test.ts +0 -97
  47. package/src/__tests__/node-kind-reducer.test.ts +0 -135
  48. package/src/__tests__/plugin-action-handler.test.ts +0 -54
  49. package/src/__tests__/reducer-parity.test.ts +0 -106
  50. package/src/__tests__/render-actions.test.ts +0 -63
  51. package/src/__tests__/session-flow-actions-edit.test.tsx +0 -98
  52. package/src/bridge/AGENTS.md +0 -8
  53. package/src/client/AGENTS.md +0 -32
  54. package/src/server/AGENTS.md +0 -10
@@ -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
+ }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Idle (not-started) flow state for the attach-before-run panel.
3
+ *
4
+ * `buildIdleFlowState` maps a flow.yaml to the step payload pi-flows 0.5.0
5
+ * `onFlowStarted` would emit (per-kind field subset + parser coercions), wraps it
6
+ * in a fake `flow_started` event and replays it through the REAL reducer, so the
7
+ * idle graph + cards equal what a real start shows. Mirrors every 0.5.0 parser
8
+ * throw so a bad definition yields an error instead of a wrong panel.
9
+ *
10
+ * `resolveFlowSlot` decides what the flow slot renders (running → attached →
11
+ * completed → nothing); `isAttachmentConsumed` is the replay catch-up rule.
12
+ *
13
+ * `flow-yaml-parse.ts` (the shallow `flow_write` snapshot parser) is untouched.
14
+ * See change: attach-flow-before-run (D1, D3, D4).
15
+ */
16
+ import type { DashboardEvent, FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
17
+ import { parse as parseYaml } from "yaml";
18
+ import { reduceFlowEvent } from "../reducer.js";
19
+
20
+ /** One step of the pi-flows 0.5.0 `flow:flow-started` payload. */
21
+ interface StartedStep {
22
+ id: string;
23
+ stepType: string;
24
+ agent?: string;
25
+ blockedBy: string[];
26
+ branches?: Record<string, string>;
27
+ onError?: string;
28
+ }
29
+
30
+ type Raw = Record<string, unknown>;
31
+
32
+ function requireField(obj: Raw, key: string, where: string): string {
33
+ const v = obj[key];
34
+ if (v === undefined || v === null) throw new Error(`flow.yaml: ${where} missing required field "${key}"`);
35
+ return String(v);
36
+ }
37
+
38
+ function blockedByOf(raw: Raw): string[] {
39
+ if (!raw.blockedBy) return [];
40
+ return Array.isArray(raw.blockedBy) ? raw.blockedBy.map(String) : [String(raw.blockedBy)];
41
+ }
42
+
43
+ function branchesOf(raw: Raw): Record<string, string> {
44
+ const out: Record<string, string> = {};
45
+ if (raw.branches && typeof raw.branches === "object") {
46
+ for (const [k, v] of Object.entries(raw.branches as Raw)) out[k] = String(v);
47
+ }
48
+ return out;
49
+ }
50
+
51
+ /** 0.5.0 `toInt`: an optional integer field must parse. */
52
+ function checkInt(obj: Raw, key: string, where: string): void {
53
+ if (obj[key] === undefined) return;
54
+ if (Number.isNaN(Number.parseInt(String(obj[key]), 10))) {
55
+ throw new Error(`flow.yaml: ${where} "${key}" must be an integer`);
56
+ }
57
+ }
58
+
59
+ const INPUT_TYPES = new Set(["string", "number", "boolean", "object", "array"]);
60
+
61
+ /** 0.5.0 `parseFlowInputs`: optional mapping of name → { type }. */
62
+ function checkInputs(raw: unknown): void {
63
+ if (raw === undefined) return;
64
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error('flow.yaml: "inputs" must be a mapping');
65
+ for (const [k, v] of Object.entries(raw as Raw)) {
66
+ const type = (v as Raw | null)?.type;
67
+ if (typeof type !== "string" || !INPUT_TYPES.has(type)) {
68
+ throw new Error(`flow.yaml: input "${k}" needs a valid "type"`);
69
+ }
70
+ }
71
+ }
72
+
73
+ function onErrorOf(raw: Raw): string | undefined {
74
+ return raw.on_error ? String(raw.on_error) : undefined;
75
+ }
76
+
77
+ /**
78
+ * Map one YAML step to its started-payload shape using the pi-flows 0.5.0
79
+ * per-kind field table (agent: blockedBy+on_error; code: blockedBy+on_error;
80
+ * code-decision: blockedBy+branches; fork: branches (+optional agent);
81
+ * agent-decision: agent+branches). Throws where the 0.5.0 parser throws.
82
+ */
83
+ function toStartedStep(raw: unknown, index: number): StartedStep {
84
+ if (!raw || typeof raw !== "object") throw new Error(`flow.yaml: step ${index} is not an object`);
85
+ const r = raw as Raw;
86
+ const id = r.id;
87
+ if (!id || typeof id !== "string") throw new Error(`flow.yaml: step ${index} missing "id" field`);
88
+ const type = r.type;
89
+ if (!type || typeof type !== "string") throw new Error(`flow.yaml: step "${id}" missing required "type" field`);
90
+ const where = `step "${id}"`;
91
+ checkInt(r, "timeout", where);
92
+ checkInt(r, "max_iterations", where);
93
+ switch (type) {
94
+ case "agent":
95
+ return { id, stepType: type, agent: requireField(r, "agent", where), blockedBy: blockedByOf(r), onError: onErrorOf(r) };
96
+ case "code":
97
+ return { id, stepType: type, blockedBy: blockedByOf(r), onError: onErrorOf(r) };
98
+ case "code-decision":
99
+ return { id, stepType: type, blockedBy: blockedByOf(r), branches: branchesOf(r) };
100
+ case "fork":
101
+ requireField(r, "question", where);
102
+ requireField(r, "options", where);
103
+ return { id, stepType: type, agent: r.agent ? String(r.agent) : undefined, blockedBy: [], branches: branchesOf(r) };
104
+ case "agent-decision": {
105
+ const agent = requireField(r, "agent", where);
106
+ requireField(r, "task", where);
107
+ return { id, stepType: type, agent, blockedBy: [], branches: branchesOf(r) };
108
+ }
109
+ default:
110
+ throw new Error(`flow.yaml: unknown step type "${type}" for step "${id}"`);
111
+ }
112
+ }
113
+
114
+ /** Parse a flow.yaml into the 0.5.0 started-step payload. Throws on any error. */
115
+ function flowYamlToStartedSteps(content: string): StartedStep[] {
116
+ const doc = parseYaml(content) as unknown;
117
+ if (!doc || typeof doc !== "object") throw new Error("flow.yaml: empty or not a mapping");
118
+ requireField(doc as Raw, "name", "flow");
119
+ requireField(doc as Raw, "description", "flow");
120
+ checkInt(doc as Raw, "max_concurrent", "flow");
121
+ checkInputs((doc as Raw).inputs);
122
+ const steps = (doc as Raw).steps;
123
+ if (!Array.isArray(steps)) throw new Error('flow.yaml: "steps" must be an array');
124
+ return steps.map(toStartedStep);
125
+ }
126
+
127
+ export type IdleBuildResult =
128
+ | { kind: "ready"; flowState: FlowState }
129
+ | { kind: "error"; message: string };
130
+
131
+ /** Build the idle FlowState by replaying a fake 0.5.0 `flow_started`. */
132
+ export function buildIdleFlowState(
133
+ content: string,
134
+ flow: { name: string; source?: string },
135
+ ): IdleBuildResult {
136
+ let steps: StartedStep[];
137
+ try {
138
+ steps = flowYamlToStartedSteps(content);
139
+ } catch (err) {
140
+ return { kind: "error", message: err instanceof Error ? err.message : String(err) };
141
+ }
142
+ const event = {
143
+ seq: 0,
144
+ timestamp: 0,
145
+ eventType: "flow_started",
146
+ data: { flowName: flow.name, task: "", source: flow.source, autonomousMode: true, steps },
147
+ } as unknown as DashboardEvent;
148
+ // flow_started always seeds a state from null.
149
+ return { kind: "ready", flowState: reduceFlowEvent(null, event) as FlowState };
150
+ }
151
+
152
+ /** Coerce an event timestamp (number or ISO string) to epoch ms; non-finite → 0. */
153
+ export function toEventTime(ts: unknown): number {
154
+ const n = typeof ts === "string" ? Date.parse(ts) : Number(ts);
155
+ return Number.isFinite(n) ? n : 0;
156
+ }
157
+
158
+ /** Replay catch-up: a `flow_started` strictly newer than the attach baseline. */
159
+ export function isAttachmentConsumed(baselineStartedAt: number | null, lastFlowStartedAt: unknown): boolean {
160
+ if (baselineStartedAt === null) return false;
161
+ if (lastFlowStartedAt === undefined || lastFlowStartedAt === null) return false;
162
+ return toEventTime(lastFlowStartedAt) > baselineStartedAt;
163
+ }
164
+
165
+ /** Stored per-session attachment (see flow-attach-store.ts). */
166
+ export interface FlowAttachment {
167
+ /** Random per-attach token (conditional delete). */
168
+ id: string;
169
+ name: string;
170
+ source?: string;
171
+ baselineStartedAt: number | null;
172
+ }
173
+
174
+ export type IdleLoad =
175
+ | { kind: "loading" }
176
+ | { kind: "error"; message: string }
177
+ | { kind: "ready"; flowState: FlowState };
178
+
179
+ type FlowSlotError = { kind: "unavailable" } | { kind: "load"; message: string };
180
+
181
+ export interface FlowSlot {
182
+ mode: "live" | "idle" | "loading" | "error" | "none";
183
+ flowState?: FlowState;
184
+ error?: FlowSlotError;
185
+ /** True when an attachment exists and has been consumed (caller deletes it). */
186
+ attachmentConsumed: boolean;
187
+ }
188
+
189
+ function findRunning(
190
+ live: FlowState | null,
191
+ liveStates: ReadonlyMap<string, FlowState>,
192
+ ): FlowState | undefined {
193
+ if (live?.status === "running") return live;
194
+ let running: FlowState | undefined;
195
+ for (const s of liveStates.values()) if (s.status === "running") running = s;
196
+ return running;
197
+ }
198
+
199
+ /**
200
+ * Slot priority: running flow → attached (unconsumed) flow → completed flow →
201
+ * nothing. The idle state is only ever returned in `idle` mode; it never enters
202
+ * the live path.
203
+ */
204
+ export function resolveFlowSlot(input: {
205
+ live: FlowState | null;
206
+ liveStates: ReadonlyMap<string, FlowState>;
207
+ attachment: FlowAttachment | null;
208
+ idle: IdleLoad;
209
+ lastFlowStartedAt?: unknown;
210
+ flowsList: ReadonlyArray<{ name: string }>;
211
+ }): FlowSlot {
212
+ const { live, liveStates, attachment, idle, lastFlowStartedAt, flowsList } = input;
213
+ const running = findRunning(live, liveStates);
214
+ if (running) return { mode: "live", flowState: running, attachmentConsumed: !!attachment };
215
+
216
+ if (attachment && !isAttachmentConsumed(attachment.baselineStartedAt, lastFlowStartedAt)) {
217
+ if (flowsList.length > 0 && !flowsList.some((f) => f.name === attachment.name)) {
218
+ return { mode: "error", error: { kind: "unavailable" }, attachmentConsumed: false };
219
+ }
220
+ if (idle.kind === "loading") return { mode: "loading", attachmentConsumed: false };
221
+ if (idle.kind === "error") {
222
+ return { mode: "error", error: { kind: "load", message: idle.message }, attachmentConsumed: false };
223
+ }
224
+ return { mode: "idle", flowState: idle.flowState, attachmentConsumed: false };
225
+ }
226
+
227
+ const consumed = !!attachment;
228
+ if (live) return { mode: "live", flowState: live, attachmentConsumed: consumed };
229
+ return { mode: "none", attachmentConsumed: consumed };
230
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Accumulated-USD cost formatting — a leaf module with no dependencies.
3
+ *
4
+ * Extracted from `FlowAgentCard.tsx` to break the import cycle
5
+ * `FlowAgentCard -> FlowAgentDetail -> FlowAgentCard`: the card renders the
6
+ * detail view, and the detail view only needed the card for this formatter.
7
+ * A currency formatter living in a card component was incidental placement.
8
+ *
9
+ * See change: cleanup-import-cycles (D2).
10
+ */
11
+
12
+ /**
13
+ * Format an accumulated USD cost, matching the pi-flows TUI precision
14
+ * (`agent-card.ts`): two decimals at or above $1, four decimals sub-dollar.
15
+ *
16
+ * The sub-dollar branch is load-bearing — flow agent costs are routinely well
17
+ * below $1, where 2 decimals would collapse distinct values to `$0.00`.
18
+ */
19
+ export function formatCost(n: number): string {
20
+ return `$${n >= 1 ? n.toFixed(2) : n.toFixed(4)}`;
21
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Discard-with-a-stated-handler wrapper around the plugin send primitive.
3
+ *
4
+ * A plugin message dispatched from an event handler or effect has no caller to
5
+ * own its promise. Wrapping it here keeps the discard explicit and routes the
6
+ * rejection to the package's logging path, so a dropped message is observable
7
+ * instead of leaving the UI showing a change the server never applied.
8
+ *
9
+ * See change: cleanup-client-plugin-promises (design D1).
10
+ */
11
+ export type PluginSend = (message: unknown) => void | Promise<void>;
12
+
13
+ export function makeSafeSend(send: PluginSend): (message: unknown) => void {
14
+ return (message: unknown): void => {
15
+ void Promise.resolve(send(message)).catch((err: unknown) => {
16
+ console.error("[flows-plugin] plugin send failed:", err);
17
+ });
18
+ };
19
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Contract between the flows-plugin bridge and server for reporting a session's
3
+ * flow files (see `bridge/flow-files-reporter.ts`, `server/flow-files.ts`).
4
+ * Import-free leaf so the bridge never pulls server code.
5
+ * See change: attach-flow-before-run.
6
+ */
7
+
8
+ export interface ReportedFile {
9
+ name: string;
10
+ source: string;
11
+ }
12
+
13
+ export interface FlowFilesReport {
14
+ flows?: ReportedFile[];
15
+ agents?: ReportedFile[];
16
+ }
17
+
18
+ /** Private bridge → server lane message carrying a {@link FlowFilesReport}. */
19
+ export const FLOW_FILES_REPORT = "flow-files/report";
20
+ /** pi event the server emits into a session to ask its bridge to (re)report. */
21
+ export const FLOW_FILES_REQUEST_EVENT = "dashboard-flows:report-files";
@@ -356,6 +356,10 @@ export function reduceFlowEvent(
356
356
 
357
357
  case "flow_complete": {
358
358
  if (!flowState) return null;
359
+ // A rejected start (pi-flows refused to run; no flow_started was emitted)
360
+ // never refers to the run held here — leave it untouched.
361
+ // See change: attach-flow-before-run (D10).
362
+ if (data.status === "rejected") return flowState;
359
363
  const status = ((data.status as string) || "success") as FlowState["status"];
360
364
  // When the flow ends non-successfully (error / aborted / interrupted),
361
365
  // downgrade any step left running/pending so its card does not spin
package/src/i18n.ts CHANGED
@@ -39,6 +39,20 @@ export const catalog = {
39
39
  newFlowOption: "+ 新建流程",
40
40
  newFlowOptionDesc: "使用 edit-flow 技能创建新流程",
41
41
  runFlowButton: "运行流程…",
42
+ openFlowButton: "打开流程…",
43
+ openFlowDialogTitle: "打开流程",
44
+ openFlowDisabledRunning: "有流程正在运行",
45
+ flowNotStarted: "未开始",
46
+ runFlow: "运行",
47
+ closeAttachedFlow: "关闭",
48
+ flowDefinitionLoadError: "流程定义文件不可用",
49
+ flowNoLongerAvailable: "已不可用",
50
+ flowLoading: "加载中…",
51
+ flowRunRejected: "启动被拒绝",
52
+ flowRunSendFailed: "无法启动流程",
53
+ openHandlerInEditor: "在编辑器中打开处理程序",
54
+ openSourceInEditor: "在编辑器中打开 {name} 源文件",
55
+ openFlowYamlInEditor: "在编辑器中打开 {name} YAML",
42
56
  newEditButton: "新建 / 编辑…",
43
57
  runFlowDialogTitle: "运行流程",
44
58
  searchFlows: "搜索流程…",
@@ -76,6 +90,20 @@ export const catalog = {
76
90
  newFlowOption: "+ Új folyamat",
77
91
  newFlowOptionDesc: "Új folyamat készítése az edit-flow készséggel",
78
92
  runFlowButton: "Folyamat futtatása…",
93
+ openFlowButton: "Folyamat megnyitása…",
94
+ openFlowDialogTitle: "Folyamat megnyitása",
95
+ openFlowDisabledRunning: "Egy folyamat fut",
96
+ flowNotStarted: "nincs elindítva",
97
+ runFlow: "Futtatás",
98
+ closeAttachedFlow: "Bezárás",
99
+ flowDefinitionLoadError: "A folyamatdefiníciós fájl nem érhető el",
100
+ flowNoLongerAvailable: "már nem érhető el",
101
+ flowLoading: "betöltés…",
102
+ flowRunRejected: "Az indítás elutasítva",
103
+ flowRunSendFailed: "A folyamat nem indítható el",
104
+ openHandlerInEditor: "Kezelő megnyitása a szerkesztőben",
105
+ openSourceInEditor: "{name} forrásának megnyitása a szerkesztőben",
106
+ openFlowYamlInEditor: "{name} YAML megnyitása a szerkesztőben",
79
107
  newEditButton: "Új / Szerkesztés…",
80
108
  runFlowDialogTitle: "Folyamat futtatása",
81
109
  searchFlows: "Folyamatok keresése…",