@nanobpm/nano-workforce 0.136.0 → 0.138.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,106 @@
1
+ // Tests for the POST /app/api/actions/delivery-graph/stage operation `stageDeliveryGraph` (ADR 0005
2
+ // Decision 7, issues #460 + #516) — the STAGE half of the preview/stage split. It parses the
3
+ // operator's pasted JSON STRING, runs the SAME compiler the preview/agent doors use, and — on success
4
+ // — persists the compiled graph as a `staged` proposal (200, `staged:true`). Unlike the pure preview
5
+ // door it PERSISTS; unlike dispatch it never launches (no run key / instance key comes back).
6
+ import { mkdtempSync, rmSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join, resolve } from "node:path";
9
+ import { test } from "node:test";
10
+ import { assert, assertEquals } from "#test-assert";
11
+ import type { AppApi, DataLayer } from "@nanobpm/urban";
12
+ import { bootTestApp } from "@nanobpm/urban-testkit";
13
+ import { deliveryGraphProposals } from "../app/deliveryGraphProposals.ts";
14
+ import { noopLog } from "../test/log.ts";
15
+ import handler from "./stageDeliveryGraph.ts";
16
+
17
+ const APP_ROOT = resolve(import.meta.dirname, "..");
18
+
19
+ async function withApp(fn: (app: AppApi, data: DataLayer) => Promise<void>): Promise<void> {
20
+ const dir = mkdtempSync(join(tmpdir(), "nwf-dgstage-"));
21
+ const app = await bootTestApp(APP_ROOT, { env: { NANO_APP_DB_URL: `file:${join(dir, "app.db")}` } });
22
+ try {
23
+ const edge = { data: app.db, log: noopLog() } as unknown as AppApi;
24
+ await fn(edge, app.db);
25
+ } finally {
26
+ await app.stop?.();
27
+ rmSync(dir, { recursive: true, force: true });
28
+ }
29
+ }
30
+
31
+ async function call(app: AppApi, body: unknown) {
32
+ return (await handler({ req: {} as any, params: {}, query: {}, body } as any, app)) as any;
33
+ }
34
+
35
+ const GOOD = JSON.stringify({
36
+ name: "runbook",
37
+ nodes: [
38
+ { id: "a", kind: "agent", agent: { jobType: "senior:feature" } },
39
+ { id: "b", kind: "human", human: { prompt: "do X" } },
40
+ ],
41
+ edges: [{ from: "a", to: "b" }],
42
+ });
43
+
44
+ test("stage-delivery-graph: a pasted well-formed graph → 200, staged, with digest + counts", async () => {
45
+ await withApp(async (app, data) => {
46
+ const res = await call(app, { graphJson: GOOD });
47
+ assertEquals(res.status, 200);
48
+ assertEquals(res.body.ok, true);
49
+ assertEquals(res.body.staged, true);
50
+ assert(typeof res.body.digest === "string" && res.body.digest.length > 0);
51
+ assert(typeof res.body.reviewUrl === "string" && res.body.reviewUrl.length > 0);
52
+ assertEquals(res.body.nodeCount, 2);
53
+ assertEquals(res.body.humanNodeCount, 1);
54
+ assertEquals(res.body.sideEffectCount, 1);
55
+ assertEquals(res.body.sideEffecting, true);
56
+ assertEquals(res.body.title, "runbook");
57
+ // Full preview detail is still returned so the page renders the same summary as preview.
58
+ assert(Array.isArray(res.body.humanNodes) && res.body.humanNodes.length === 1);
59
+ assert(Array.isArray(res.body.sideEffects) && res.body.sideEffects.length === 1);
60
+ // The stage door persists a `staged` proposal — and returns NO dispatch handle (#460).
61
+ assertEquals((await deliveryGraphProposals(data).get(res.body.digest))?.status, "staged");
62
+ assertEquals(res.body.runKey, undefined);
63
+ assertEquals(res.body.processInstanceKey, undefined);
64
+ // The stage summary omits the heavy BPMN (the staged grid recompiles by digest for its DI preview).
65
+ assertEquals(res.body.bpmn, undefined);
66
+ });
67
+ });
68
+
69
+ test("stage-delivery-graph: repeated stages of the same graph → one live row (idempotent on digest)", async () => {
70
+ await withApp(async (app, data) => {
71
+ const a = await call(app, { graphJson: GOOD });
72
+ const b = await call(app, { graphJson: GOOD });
73
+ assertEquals(a.body.digest, b.body.digest);
74
+ assertEquals((await deliveryGraphProposals(data).find({ digest: a.body.digest })).length, 1);
75
+ });
76
+ });
77
+
78
+ test("stage-delivery-graph: text that is not valid JSON → 400, nothing staged", async () => {
79
+ await withApp(async (app, data) => {
80
+ const res = await call(app, { graphJson: "{ not json" });
81
+ assertEquals(res.status, 400);
82
+ assertEquals(res.body.ok, false);
83
+ assert(typeof res.body.error === "string" && res.body.error.includes("not valid JSON"));
84
+ assertEquals((await deliveryGraphProposals(data).all()).length, 0);
85
+ });
86
+ });
87
+
88
+ test("stage-delivery-graph: a valid-JSON but malformed graph → 400 with path-qualified errors, nothing staged", async () => {
89
+ await withApp(async (app, data) => {
90
+ const res = await call(app, {
91
+ graphJson: JSON.stringify({ nodes: [{ id: "a", kind: "agent", agent: { jobType: "j" } }], edges: [{ from: "a", to: "ghost" }] }),
92
+ });
93
+ assertEquals(res.status, 400);
94
+ assertEquals(res.body.ok, false);
95
+ assert(Array.isArray(res.body.errors) && res.body.errors.length > 0);
96
+ assertEquals((await deliveryGraphProposals(data).all()).length, 0);
97
+ });
98
+ });
99
+
100
+ test("stage-delivery-graph: a blank paste → 400, never a 500", async () => {
101
+ await withApp(async (app) => {
102
+ const res = await call(app, { graphJson: " " });
103
+ assertEquals(res.status, 400);
104
+ assertEquals(res.body.ok, false);
105
+ });
106
+ });
@@ -0,0 +1,53 @@
1
+ // POST /app/api/actions/delivery-graph/stage → operationId `stageDeliveryGraph` (ADR 0005 Decision 7,
2
+ // issues #460 + #516). The human-facing UI JSON-paste STAGE ingress: the Delivery Graphs page's
3
+ // "Stage" action posts the operator's pasted delivery-graph as a raw JSON STRING; this door parses it,
4
+ // runs the SAME `compileDeliveryGraph` compiler the preview/agent doors use, and — on success —
5
+ // persists the compiled graph as a `staged` proposal (content-addressed by its `digest`) for an
6
+ // operator to dispatch from the Staged proposals grid.
7
+ //
8
+ // It is the STAGE half of the preview/stage split (#516): preview (`previewDeliveryGraph`) compiles
9
+ // WITHOUT persisting; this door is the deliberate commit step. It never deploys or dispatches —
10
+ // dispatch is a separate OPERATOR action on the staged proposal (the Dispatch button on the
11
+ // staged-proposals grid, #460). A blank/invalid JSON string, or a graph that fails validation, is a
12
+ // 400 carrying a human `error` (and path-qualified `errors` for a compile failure); nothing is staged.
13
+
14
+ import {
15
+ buildProposalPreview,
16
+ buildProposalRow,
17
+ proposalLogicalKey,
18
+ stageProposal,
19
+ } from "../app/deliveryGraphProposals.ts";
20
+ import { buildTextPreviewBody, parseAndCompileText } from "../app/deliveryGraphTextIngress.ts";
21
+ import { defineOperation } from "../nano-generated/operations.ts";
22
+
23
+ export default defineOperation("stageDeliveryGraph", async ({ body }, app) => {
24
+ const ingress = await parseAndCompileText(body);
25
+ if (!ingress.ok) {
26
+ app.log.warn("stage-delivery-graph rejected", { message: ingress.body.error });
27
+ return { status: ingress.status, body: ingress.body };
28
+ }
29
+
30
+ const { compiled, digest, name, graph } = ingress;
31
+ await stageProposal(
32
+ app.data,
33
+ buildProposalRow({
34
+ digest,
35
+ logicalKey: proposalLogicalKey(name, digest),
36
+ title: name,
37
+ graphJson: JSON.stringify(graph),
38
+ preview: buildProposalPreview(compiled),
39
+ nodeCount: compiled.resolved.nodes.length,
40
+ humanNodeCount: compiled.humanNodes.length,
41
+ sideEffectCount: compiled.sideEffects.length,
42
+ sideEffecting: compiled.sideEffects.length > 0,
43
+ }),
44
+ );
45
+
46
+ app.log.info("stage-delivery-graph staged", {
47
+ nodes: compiled.resolved.nodes.length,
48
+ humanNodes: compiled.humanNodes.length,
49
+ sideEffects: compiled.sideEffects.length,
50
+ digest,
51
+ });
52
+ return { status: 200, body: buildTextPreviewBody(ingress, { staged: true }) };
53
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nanobpm/nano-workforce",
3
- "version": "0.136.0",
3
+ "version": "0.138.0",
4
4
  "description": "Nano Workforce — an Agent Graph Orchestration application for Agentic SDLC: durable BPMN processes that coordinate a graph of AI agents across the software delivery lifecycle.",
5
5
  "type": "module",
6
6
  "main": "main.ts",
@@ -66,12 +66,12 @@
66
66
  "@biomejs/biome": "^2.4.11",
67
67
  "@nanobpm/urban-testkit": "^0.13.1",
68
68
  "@nanobpm/workflow": "^0.14.0",
69
- "@semantic-release/changelog": "^6.0.3",
70
- "@semantic-release/git": "^10.0.1",
69
+ "@semantic-release/changelog": "^7.0.0",
70
+ "@semantic-release/git": "^11.0.0",
71
71
  "@semantic-release/npm": "^13.1.5",
72
- "@types/node": "^22",
72
+ "@types/node": "^24.0.0",
73
73
  "conventional-changelog-conventionalcommits": "^8.0.0",
74
- "semantic-release": "^24.2.9",
74
+ "semantic-release": "^25.0.0",
75
75
  "typescript": "^5.6.0"
76
76
  },
77
77
  "overrides": {
@@ -33,6 +33,53 @@
33
33
  border-color: rgba(63, 185, 80, 0.5);
34
34
  }
35
35
 
36
+ /* The compose panel is a native <details> so it can collapse (#516). Its <summary> is the disclosure
37
+ header; the caret rotates on open, and the body hides when collapsed (the textarea keeps its value). */
38
+ .dg .compose > summary {
39
+ cursor: pointer;
40
+ list-style: none;
41
+ display: flex;
42
+ align-items: baseline;
43
+ gap: 10px;
44
+ font-size: 15px;
45
+ font-weight: 600;
46
+ user-select: none;
47
+ }
48
+
49
+ .dg .compose > summary::-webkit-details-marker {
50
+ display: none;
51
+ }
52
+
53
+ .dg .compose > summary::before {
54
+ content: "\25B6";
55
+ font-size: 10px;
56
+ color: #8aa0b8;
57
+ transition: transform 0.15s ease;
58
+ }
59
+
60
+ .dg .compose[open] > summary::before {
61
+ transform: rotate(90deg);
62
+ }
63
+
64
+ .dg .compose > summary:focus-visible {
65
+ outline: 2px solid #388bfd;
66
+ outline-offset: 3px;
67
+ border-radius: 4px;
68
+ }
69
+
70
+ .dg .compose > summary .hint {
71
+ font-size: 12px;
72
+ font-weight: 400;
73
+ }
74
+
75
+ .dg .compose[open] > summary .hint {
76
+ display: none;
77
+ }
78
+
79
+ .dg .compose-body {
80
+ margin-top: 12px;
81
+ }
82
+
36
83
  .dg h2 {
37
84
  margin: 0 0 8px;
38
85
  font-size: 15px;
@@ -24,7 +24,7 @@
24
24
  const cfg = window.__NANO_APP_VIEW__ ?? {};
25
25
  mountDeliveryGraphs(cfg.host ?? document.getElementById("delivery-graphs-root"), {
26
26
  previewUrl: cfg.previewUrl,
27
- dispatchUrl: cfg.dispatchUrl,
27
+ stageUrl: cfg.stageUrl,
28
28
  hookSecret: cfg.hookSecret,
29
29
  });
30
30
  </script>
@@ -1,42 +1,35 @@
1
- // pages/delivery-graphs/mount.js — the Delivery Graphs composepreview STAGE view (ADR 0005,
2
- // issues #441 + #460). The human front door for a delivery graph: author/paste a `DeliveryGraph` JSON
3
- // and PREVIEW it a compile that renders the plan (mermaid `diagram`, the `humanNodes[]` stop-points,
4
- // the `sideEffects[]` a dispatch will perform) AND stages it as a proposal for dispatch.
1
+ // pages/delivery-graphs/mount.js — the Delivery Graphs COMPOSEPREVIEW / STAGE view (ADR 0005,
2
+ // issues #441 + #460 + #516). The human front door for a delivery graph: author/paste a `DeliveryGraph`
3
+ // JSON, PREVIEW it (a pure compile that renders the plan mermaid `diagram`, the `humanNodes[]`
4
+ // stop-points, the `sideEffects[]` a dispatch will perform and the laid-out BPMN in the host
5
+ // explorer), and, as a SEPARATE deliberate action, STAGE it as a proposal for dispatch.
5
6
  //
6
- // Dispatch is deliberately NOT here (issue #460): it is an OPERATOR action on the **Staged proposals**
7
- // grid on the same page (the Dispatch row-action, which posts the proposal's `digest`). Removing the
8
- // dispatch affordance from every agent-reachable seam closes the self-approval hole the old replayable
9
- // approval token (a content digest handed back to the same caller) left open — this view only ever
10
- // stages, never launches.
7
+ // Preview and Stage are separate (issue #516): Preview compiles WITHOUT persisting, so an operator can
8
+ // inspect and iterate on a graph before committing it to the Staged-proposals list. Dispatch is NOT
9
+ // here (issue #460): it is an OPERATOR action on the **Staged proposals** grid on the same page.
10
+ // Removing the dispatch affordance from every agent-reachable seam closes the self-approval hole the
11
+ // old replayable approval token left open — this view only ever previews/stages, never launches.
11
12
  //
12
13
  // A self-contained, dependency-free renderer in the SAME shape as the demand×supply board
13
14
  // (pages/board/mount.js) and the agent cockpit: the SAME module mounts embedded in the console (App
14
15
  // View) and standalone on a phone — only the host element and injected endpoint config differ. The app
15
- // has no browser build step, so this consumes the preview door straight off the wire.
16
- //
17
- // It is a THIN UI over the EXISTING door — there is no parallel compile/stage path:
18
- // • PREVIEW & STAGE → POST previewUrl (previewDeliveryGraph) — renders the mermaid `diagram`, the
19
- // `humanNodes[]` stop-points, the `sideEffects[]` a dispatch will perform, and path-qualified
20
- // validation `errors[]` inline for a 400 (the fix-and-recompile loop); on success the compiled
21
- // graph is STAGED as a proposal (an operator dispatches it from the Staged proposals grid below).
16
+ // has no browser build step, so this consumes the preview/stage doors straight off the wire.
22
17
 
23
18
  const DEFAULT_PREVIEW_URL = "app/api/actions/delivery-graph/preview";
24
- // The read-only DI preview door: recompiles a staged proposal's BPMN (with diagram interchange) so its
25
- // generated diagram can be rendered in the host explorer BEFORE dispatch. No deploy, no dispatch.
26
- const DEFAULT_PROPOSAL_BPMN_URL = "app/api/actions/delivery-graph/proposal-bpmn";
19
+ const DEFAULT_STAGE_URL = "app/api/actions/delivery-graph/stage";
27
20
 
28
- // A bounded timeout for every door request. Without it a hung preview endpoint leaves the fetch
29
- // promise pending forever, so the busy() lock never clears and the UI is stranded (buttons disabled,
30
- // status stuck) with no way to retry. On timeout the AbortController rejects the fetch, which surfaces
31
- // as an error banner and re-enables the controls via the callers' finally blocks.
21
+ // A bounded timeout for every door request. Without it a hung endpoint leaves the fetch promise pending
22
+ // forever, so the busy() lock never clears and the UI is stranded (buttons disabled, status stuck) with
23
+ // no way to retry. On timeout the AbortController rejects the fetch, which surfaces as an error banner
24
+ // and re-enables the controls via the callers' finally blocks.
32
25
  const REQUEST_TIMEOUT_MS = 30000;
33
26
 
34
- const EXAMPLE_GRAPH = JSON.stringify(
27
+ export const EXAMPLE_GRAPH = JSON.stringify(
35
28
  {
36
29
  name: "example-runbook",
37
30
  nodes: [
38
31
  { id: "build", kind: "agent", agent: { jobType: "senior:feature" }, emits: [{ name: "pr", type: "url" }] },
39
- { id: "soak", kind: "wait", wait: { target: "checks-green" } },
32
+ { id: "soak", kind: "wait", wait: { kind: "pr", target: "owner/repo#123", match: { prState: "checks-green" } } },
40
33
  { id: "signoff", kind: "human", human: { prompt: "Review the PR and approve the release." } },
41
34
  { id: "publish", kind: "connector", connector: { target: "publish-package", dedupeKey: "example-runbook-publish" } },
42
35
  ],
@@ -128,15 +121,19 @@ function renderErrors(message, errors) {
128
121
  </section>`;
129
122
  }
130
123
 
131
- /** Render the successful preview: the staged banner, summary chips, the human/side-effect tables, and
132
- * the mermaid source. Dispatch is NOT offered here the operator dispatches the staged proposal from
133
- * the Staged proposals grid below (issue #460). */
134
- function renderPreview(result) {
124
+ /** Render the successful result: the preview/staged banner, summary chips, the human/side-effect
125
+ * tables, and the mermaid source. When `staged` is false (a pure Preview, #516) the banner offers
126
+ * "Preview generated DI" (the door returns the laid-out BPMN, so it renders WITHOUT staging) and a
127
+ * reminder that nothing is staged yet. When `staged` is true the banner points the operator at the
128
+ * Staged proposals grid below, where the per-row Dispatch (and DI preview) live (#460 + #513). */
129
+ function renderPreview(result, staged) {
135
130
  const title = result.title ? `<code>${esc(result.title)}</code>` : '<span class="muted">(unnamed)</span>';
136
131
  const gate = result.sideEffecting
137
132
  ? '<span class="pill pill-connector">side-effecting</span>'
138
133
  : '<span class="pill pill-wait">no side effects</span>';
139
- const summary = `<section class="card card-ok">
134
+ const canPreviewDi = typeof result.bpmn === "string" && result.bpmn.trim() !== "";
135
+ const summary = staged
136
+ ? `<section class="card card-ok">
140
137
  <h2>Staged ${gate}</h2>
141
138
  <p class="ok">Compiled and staged as a proposal. Dispatch is an operator action — review it in the <b>Staged proposals</b> grid below and click <b>Dispatch</b> on the one you approve.</p>
142
139
  <div class="chips">
@@ -146,23 +143,38 @@ function renderPreview(result) {
146
143
  <span class="chip">Side effects <b>${esc(result.sideEffectCount)}</b></span>
147
144
  <span class="chip">Digest <code>${esc(result.digest)}</code></span>
148
145
  </div>
149
- <div class="actions">
150
- <button class="btn btn-ghost" type="button" data-preview-di="${esc(result.digest)}">Preview generated DI</button>
151
- <span class="muted">the real laid-out BPMN, exactly as a dispatch would run it</span>
146
+ </section>`
147
+ : `<section class="card card-ok">
148
+ <h2>Previewed ${gate}</h2>
149
+ <p class="ok">Compiled — <b>not staged yet</b>. Review the plan below, then click <b>Stage</b> to add it to the Staged proposals for dispatch.</p>
150
+ <div class="chips">
151
+ <span class="chip">Graph ${title}</span>
152
+ <span class="chip">Nodes <b>${esc(result.nodeCount)}</b></span>
153
+ <span class="chip">Human <b>${esc(result.humanNodeCount)}</b></span>
154
+ <span class="chip">Side effects <b>${esc(result.sideEffectCount)}</b></span>
155
+ <span class="chip">Digest <code>${esc(result.digest)}</code></span>
152
156
  </div>
157
+ ${
158
+ canPreviewDi
159
+ ? `<div class="actions">
160
+ <button class="btn btn-ghost" type="button" data-preview-di>Preview generated DI</button>
161
+ <span class="muted">the real laid-out BPMN, exactly as a dispatch would run it</span>
162
+ </div>`
163
+ : ""
164
+ }
153
165
  </section>`;
154
166
  const diagram = `<section class="card">
155
167
  <h2>Diagram <span class="muted">(mermaid flowchart source)</span></h2>
156
- <p class="muted">The resolved graph as a mermaid <code>flowchart</code>. Paste it into any mermaid renderer, or click <b>Preview generated DI</b> above to render the laid-out BPMN in the process explorer.</p>
168
+ <p class="muted">The resolved graph as a mermaid <code>flowchart</code>. Paste it into any mermaid renderer${staged ? "" : ", or click <b>Preview generated DI</b> above to render the laid-out BPMN in the process explorer"}.</p>
157
169
  <pre class="diagram">${esc(result.diagram)}</pre>
158
170
  </section>`;
159
171
  return summary + renderSideEffects(result.sideEffects) + renderHumanNodes(result.humanNodes) + diagram;
160
172
  }
161
173
 
162
174
  /**
163
- * Mount the compose → preview stage view into `host`.
175
+ * Mount the compose → preview / stage view into `host`.
164
176
  * @param {Element|null} host — the element to render into (or null → look up #delivery-graphs-root).
165
- * @param {{previewUrl?:string, proposalBpmnUrl?:string, hookSecret?:string}} [config]
177
+ * @param {{previewUrl?:string, stageUrl?:string, hookSecret?:string}} [config]
166
178
  */
167
179
  export function mountDeliveryGraphs(host, config = {}) {
168
180
  const isElement = host != null && host.nodeType === 1 && typeof host.innerHTML === "string";
@@ -170,25 +182,30 @@ export function mountDeliveryGraphs(host, config = {}) {
170
182
  if (!root) return () => {};
171
183
 
172
184
  const previewUrl = config.previewUrl ?? DEFAULT_PREVIEW_URL;
173
- const proposalBpmnUrl = config.proposalBpmnUrl ?? DEFAULT_PROPOSAL_BPMN_URL;
185
+ const stageUrl = config.stageUrl ?? DEFAULT_STAGE_URL;
174
186
  const headers = () => ({
175
187
  "content-type": "application/json",
176
188
  ...(config.hookSecret ? { "x-hook-secret": config.hookSecret } : {}),
177
189
  });
178
190
 
179
- // The static compose shell. The <textarea> is a real element (its value must survive re-renders of
180
- // the output panes), so it is created once and never clobbered.
191
+ // The static compose shell. The compose card is a native <details> so an operator can COLLAPSE the
192
+ // large paste panel (#516) and focus on the Staged / in-flight grids, expanding it only to author.
193
+ // The <textarea> is a real element (its value must survive re-renders of the output panes, and it is
194
+ // only HIDDEN — never destroyed — when the panel collapses), so it is created once and never clobbered.
181
195
  root.innerHTML = `<div class="dg">
182
- <section class="card">
183
- <h2>1 · Compose</h2>
184
- <p class="muted">Paste or author a <code>DeliveryGraph</code> JSON (nodes/edges over the closed <code>agent</code>/<code>wait</code>/<code>human</code>/<code>connector</code> vocabulary).</p>
185
- <textarea id="dg-json" class="json" spellcheck="false" placeholder='{ "name": "…", "nodes": [ … ], "edges": [ ] }'></textarea>
186
- <div class="actions">
187
- <button id="dg-preview" class="btn btn-primary" type="button">Preview &amp; stage</button>
188
- <button id="dg-example" class="btn btn-ghost" type="button">Load example</button>
189
- <span id="dg-status" class="status"></span>
196
+ <details id="dg-compose" class="compose card" open>
197
+ <summary><span class="step">1 · Compose</span><span class="hint muted">paste a DeliveryGraph, then Preview or Stage</span></summary>
198
+ <div class="compose-body">
199
+ <p class="muted">Paste or author a <code>DeliveryGraph</code> JSON (nodes/edges over the closed <code>agent</code>/<code>wait</code>/<code>human</code>/<code>connector</code> vocabulary).</p>
200
+ <textarea id="dg-json" class="json" spellcheck="false" placeholder='{ "name": "…", "nodes": [ … ], "edges": [ … ] }'></textarea>
201
+ <div class="actions">
202
+ <button id="dg-preview" class="btn btn-primary" type="button">Preview</button>
203
+ <button id="dg-stage" class="btn" type="button">Stage</button>
204
+ <button id="dg-example" class="btn btn-ghost" type="button">Load example</button>
205
+ <span id="dg-status" class="status"></span>
206
+ </div>
190
207
  </div>
191
- </section>
208
+ </details>
192
209
  <div id="dg-output"></div>
193
210
  </div>`;
194
211
 
@@ -196,8 +213,14 @@ export function mountDeliveryGraphs(host, config = {}) {
196
213
  const statusEl = root.querySelector("#dg-status");
197
214
  const outputEl = root.querySelector("#dg-output");
198
215
  const previewBtn = root.querySelector("#dg-preview");
216
+ const stageBtn = root.querySelector("#dg-stage");
199
217
  const exampleBtn = root.querySelector("#dg-example");
200
218
 
219
+ // The most recent successful PREVIEW's laid-out BPMN — bridged to the host explorer on demand (the
220
+ // preview door returns it, so DI preview needs no staging, #516). Cleared whenever the composed graph
221
+ // changes so a stale diagram can never be shown against edited JSON.
222
+ let lastBpmn = "";
223
+
201
224
  function setStatus(text, tone) {
202
225
  statusEl.textContent = text || "";
203
226
  statusEl.className = "status" + (tone ? " status-" + tone : "");
@@ -205,6 +228,7 @@ export function mountDeliveryGraphs(host, config = {}) {
205
228
 
206
229
  function busy(on) {
207
230
  previewBtn.disabled = on;
231
+ stageBtn.disabled = on;
208
232
  exampleBtn.disabled = on;
209
233
  }
210
234
 
@@ -236,78 +260,77 @@ export function mountDeliveryGraphs(host, config = {}) {
236
260
  return jsonEl.value;
237
261
  }
238
262
 
239
- async function doPreview() {
263
+ /** Shared compile driver for both Preview (stage=false) and Stage (stage=true). Both POST the pasted
264
+ * JSON to their door and render the SAME summary; only the banner and whether a proposal was
265
+ * persisted differ. */
266
+ async function submit(url, staged) {
240
267
  if (graphJson().trim() === "") {
241
- setStatus("Paste a delivery-graph JSON to preview.", "err");
268
+ setStatus(`Paste a delivery-graph JSON to ${staged ? "stage" : "preview"}.`, "err");
242
269
  return;
243
270
  }
244
271
  busy(true);
245
- setStatus("Compiling & staging…");
272
+ setStatus(staged ? "Compiling & staging…" : "Compiling…");
246
273
  try {
247
- const { status, body } = await post(previewUrl, { graphJson: graphJson() });
274
+ const { status, body } = await post(url, { graphJson: graphJson() });
248
275
  if (status === 200 && body.ok) {
249
- outputEl.innerHTML = renderPreview(body);
250
- setStatus("\u2713 Staged — dispatch it from the Staged proposals grid below.", "ok");
276
+ lastBpmn = !staged && typeof body.bpmn === "string" ? body.bpmn : lastBpmn;
277
+ outputEl.innerHTML = renderPreview(body, staged);
278
+ setStatus(
279
+ staged ? "\u2713 Staged — dispatch it from the Staged proposals grid below." : "\u2713 Previewed — Stage it when you're ready.",
280
+ "ok",
281
+ );
251
282
  } else {
252
283
  outputEl.innerHTML = renderErrors(body.error, body.errors);
253
- setStatus("Preview failed — fix the errors and re-preview.", "err");
284
+ setStatus(`${staged ? "Stage" : "Preview"} failed — fix the errors and retry.`, "err");
254
285
  }
255
286
  } catch (err) {
256
287
  outputEl.innerHTML = renderErrors(err && err.message ? err.message : String(err), []);
257
- setStatus("Preview request failed.", "err");
288
+ setStatus(`${staged ? "Stage" : "Preview"} request failed.`, "err");
258
289
  } finally {
259
290
  busy(false);
260
291
  }
261
292
  }
262
293
 
263
- previewBtn.addEventListener("click", doPreview);
294
+ previewBtn.addEventListener("click", () => submit(previewUrl, false));
295
+ stageBtn.addEventListener("click", () => submit(stageUrl, true));
264
296
  exampleBtn.addEventListener("click", () => {
265
297
  jsonEl.value = EXAMPLE_GRAPH;
298
+ lastBpmn = "";
266
299
  outputEl.innerHTML = "";
267
- setStatus("Example loaded — Preview & stage it.", "");
300
+ setStatus("Example loaded — Preview or Stage it.", "");
301
+ });
302
+ // Any edit invalidates the previewed BPMN so "Preview generated DI" can't show a stale diagram.
303
+ jsonEl.addEventListener("input", () => {
304
+ lastBpmn = "";
268
305
  });
269
306
 
270
- // "Preview generated DI": recompile the staged proposal's BPMN (with diagram interchange) and hand it
271
- // to the host console's process explorer, which renders it read-only in a definition-preview view.
272
- // We run inside the console App-View iframe, so we fetch from our OWN nwf door (same origin as this
273
- // app) and pass the XML UP to the console over the nano-navigate bridge — the XML is far larger than a
274
- // URL budget, so it travels in the message, not the path. Standalone (not embedded) there is no host
275
- // explorer to drive, so we say so instead of failing silently.
307
+ // "Preview generated DI": hand the previewed proposal's laid-out BPMN (returned by the preview door,
308
+ // #516) to the host console's process explorer, which renders it read-only in a definition-preview
309
+ // view. We run inside the console App-View iframe, so we pass the XML UP to the console over the
310
+ // nano-navigate bridge — the XML is far larger than a URL budget, so it travels in the message, not
311
+ // the path. Standalone (not embedded) there is no host explorer to drive, so we say so instead of
312
+ // failing silently.
276
313
  const isEmbedded = typeof window !== "undefined" && window.parent && window.parent !== window;
277
- async function doPreviewDi(digest) {
278
- const staged = typeof digest === "string" ? digest.trim() : "";
279
- if (staged === "") {
280
- setStatus("No staged proposal to preview yet — Preview & stage a graph first.", "err");
314
+ function doPreviewDi() {
315
+ if (lastBpmn.trim() === "") {
316
+ setStatus("Preview a graph first — the laid-out BPMN comes from the preview.", "err");
281
317
  return;
282
318
  }
283
319
  if (!isEmbedded) {
284
320
  setStatus("Open this page inside the console cockpit to preview the generated DI.", "err");
285
321
  return;
286
322
  }
287
- busy(true);
288
- setStatus("Compiling DI…");
289
- try {
290
- const { status, body } = await post(proposalBpmnUrl, { digest: staged });
291
- if (status === 200 && body.ok && typeof body.bpmn === "string" && body.bpmn.trim() !== "") {
292
- window.parent.postMessage(
293
- { type: "nano-navigate", target: "definitionPreview", params: { xml: body.bpmn } },
294
- window.location.origin,
295
- );
296
- setStatus("\u2713 Opening the generated DI in the process explorer…", "ok");
297
- } else {
298
- setStatus(body && body.error ? body.error : "Could not compile the DI for this proposal.", "err");
299
- }
300
- } catch (err) {
301
- setStatus(err && err.message ? err.message : "DI preview request failed.", "err");
302
- } finally {
303
- busy(false);
304
- }
323
+ window.parent.postMessage(
324
+ { type: "nano-navigate", target: "definitionPreview", params: { xml: lastBpmn } },
325
+ window.location.origin,
326
+ );
327
+ setStatus("\u2713 Opening the generated DI in the process explorer…", "ok");
305
328
  }
306
329
  outputEl.addEventListener("click", (ev) => {
307
330
  const btn = ev.target && ev.target.closest ? ev.target.closest("[data-preview-di]") : null;
308
331
  if (!btn) return;
309
332
  ev.preventDefault();
310
- doPreviewDi(btn.getAttribute("data-preview-di"));
333
+ doPreviewDi();
311
334
  });
312
335
 
313
336
  return () => {
@@ -30,7 +30,7 @@
30
30
  }
31
31
  mountDeliveryGraphs(document.getElementById("delivery-graphs-root"), {
32
32
  previewUrl: params.get("preview") ?? undefined,
33
- dispatchUrl: params.get("dispatch") ?? undefined,
33
+ stageUrl: params.get("stage") ?? undefined,
34
34
  hookSecret,
35
35
  });
36
36
  </script>