@floless/app 0.155.2 → 0.157.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 (64) hide show
  1. package/cli-actions.mjs +392 -0
  2. package/dist/floless-server.cjs +182734 -141519
  3. package/dist/schemas/drawing-check.profile.v1.schema.json +15 -2
  4. package/dist/schemas/steel.model.v2.schema.json +25 -1
  5. package/dist/skills/floless-app-actions/SKILL.md +199 -0
  6. package/dist/skills/floless-app-approval/SKILL.md +8 -5
  7. package/dist/skills/floless-app-bridge/SKILL.md +12 -9
  8. package/dist/skills/floless-app-knowledge/SKILL.md +50 -14
  9. package/dist/skills/floless-app-new-workflow/SKILL.md +26 -10
  10. package/dist/skills/floless-app-onboarding/SKILL.md +31 -1
  11. package/dist/skills/floless-app-onboarding/references/aware-runtime.md +4 -4
  12. package/dist/skills/floless-app-queue/SKILL.md +10 -6
  13. package/dist/skills/floless-app-report-issue/SKILL.md +15 -12
  14. package/dist/skills/floless-app-rfi/SKILL.md +98 -73
  15. package/dist/skills/floless-app-routines/SKILL.md +27 -15
  16. package/dist/skills/floless-app-routines/references/routines-api.md +8 -2
  17. package/dist/skills/floless-app-steel-model/SKILL.md +1 -1
  18. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +4 -2
  19. package/dist/skills/floless-app-tweak-contract/SKILL.md +25 -5
  20. package/dist/skills/floless-app-workflows/SKILL.md +50 -13
  21. package/dist/skills/floless-app-workflows/references/agent-steps.md +119 -0
  22. package/dist/web/agent-steps.js +1750 -0
  23. package/dist/web/agents.js +33 -8
  24. package/dist/web/app.css +681 -4
  25. package/dist/web/app.js +111 -11
  26. package/dist/web/aware-update-client.js +1 -0
  27. package/dist/web/aware.js +1257 -202
  28. package/dist/web/chat-landing-scene.js +372 -0
  29. package/dist/web/chat.css +254 -1
  30. package/dist/web/chat.js +2657 -87
  31. package/dist/web/commands-drawing-check.js +17 -0
  32. package/dist/web/commands-shell.js +1108 -4
  33. package/dist/web/commands-steel.js +6 -0
  34. package/dist/web/connections.js +1 -0
  35. package/dist/web/drawing-check-editor.html +33 -5
  36. package/dist/web/drawing-check-editor.js +538 -22
  37. package/dist/web/drawing-check-overlay.js +13 -0
  38. package/dist/web/flo-avatar.js +28 -3
  39. package/dist/web/guide.js +7 -2
  40. package/dist/web/index.html +171 -7
  41. package/dist/web/instructor.js +6 -4
  42. package/dist/web/leave-guard.js +4 -2
  43. package/dist/web/left-pane.js +8 -3
  44. package/dist/web/model-revit-module.js +15 -0
  45. package/dist/web/model-view-query.js +12 -2
  46. package/dist/web/model-viewport-revit-adapter.js +3 -1
  47. package/dist/web/pages.js +891 -36
  48. package/dist/web/panels.js +8 -5
  49. package/dist/web/parser-setup-recovery.js +12 -4
  50. package/dist/web/project-access.js +549 -0
  51. package/dist/web/project-reconciliation.js +357 -0
  52. package/dist/web/report-files.js +50 -0
  53. package/dist/web/revit-editor.js +116 -27
  54. package/dist/web/startup-admission.js +132 -0
  55. package/dist/web/steel-3d-core.js +9 -0
  56. package/dist/web/steel-editor.html +642 -22
  57. package/dist/web/steel-model-v2-commands.js +63 -5
  58. package/dist/web/step-rename.js +287 -0
  59. package/dist/web/terminal-requests.js +590 -0
  60. package/dist/web/tool-updates.js +148 -13
  61. package/dist/web/workspace-root-management.js +39 -0
  62. package/dist/web/workspaces.js +1879 -74
  63. package/launch.mjs +82 -2
  64. package/package.json +3 -1
package/dist/web/aware.js CHANGED
@@ -28,6 +28,7 @@
28
28
  const $reportSub = document.getElementById('report-sub');
29
29
  const $reportOpen = document.getElementById('report-open');
30
30
  const $reportShare = document.getElementById('report-share');
31
+ const $reportPage = document.getElementById('report-page');
31
32
  const $reportOpenFile = document.getElementById('report-open-file');
32
33
  const $reportRevealFile = document.getElementById('report-reveal-file');
33
34
  const $reportClose = document.getElementById('report-close');
@@ -46,6 +47,7 @@
46
47
  const $restoreBtn = document.getElementById('restore-btn');
47
48
  const $customizeBtn = document.getElementById('customize-btn');
48
49
  const $wfForked = document.getElementById('wf-forked');
50
+ const $wfAgentStep = document.getElementById('wf-agent-step');
49
51
 
50
52
  // Contract editor — a dedicated full-window surface for an editable typed
51
53
  // contract (steel takeoff, …). Unlike the opaque report viewer, this is a
@@ -61,6 +63,7 @@
61
63
  // One persistent array the inspect Execution tab reads; we mutate in place so
62
64
  // every AGENTS[node].execution reference stays valid across re-renders.
63
65
  const liveTrace = [];
66
+ let traceRunId = null; // #2374: the run the trace being shown belongs to (from its run-start)
64
67
  // Latest normalized app payload, keyed by id, so handlers can read mode/gate.
65
68
  const apps = new Map();
66
69
  // Who owns each listed workflow, from the Workflows library (/api/workflows/library). A PARALLEL map like
@@ -300,10 +303,21 @@
300
303
  });
301
304
  window.addEventListener('pageshow', () => { awarePageUnloading = false; });
302
305
 
303
- async function api(path, opts) {
306
+ // The health poll and startup admission share one generation-fenced observation.
307
+ async function readHealth() {
308
+ if (globalThis.flolessStartupAdmission) return globalThis.flolessStartupAdmission.health();
309
+ const response = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(45_000) });
310
+ if (!response.ok) throw new Error('FloLess could not be reached. Make sure it is still running, then try again.');
311
+ return response.json();
312
+ }
313
+
314
+ async function api(path, opts = {}) {
315
+ await globalThis.flolessStartupAdmission?.admit(path, { method: opts?.method, signal: opts?.signal });
316
+ const { timeoutMs, ...requestOptions } = opts;
317
+ if (!requestOptions.signal && Number.isFinite(timeoutMs)) requestOptions.signal = AbortSignal.timeout(timeoutMs);
304
318
  const res = await fetch(path, {
305
319
  headers: { 'content-type': 'application/json' },
306
- ...opts,
320
+ ...requestOptions,
307
321
  });
308
322
  const body = await res.json().catch(() => ({
309
323
  ok: false,
@@ -553,8 +567,15 @@
553
567
  // EXCLUDES the code (code belongs to the Code tab, never dumped here).
554
568
  const plainDesc = execSource ? leadingComment(execSource) : '';
555
569
  const blurbText = plainDesc && (s => s.length > 80 ? s.slice(0, 79) + '…' : s)(plainDesc.replace(/\.\s+.*/, '.').trim());
570
+ // #2241: an Agent step (its ANSWER is written by an AI at run time). Null for every other node. A label is a fact about the workflow,
571
+ // so it shows whether or not the feature is on; web/agent-steps.js builds the parts from the lock marker / source node, never invented here.
572
+ const aiStep = window.flolessAgentSteps?.entryParts(app, n, window.flolessAgentSteps.checkFor(app.id, n.id)) || null;
573
+ // #2374: a node FloLess found using (or decided by) an Agent step's answer carries a quieter chip and one Inspect line.
574
+ const aiUse = !aiStep && window.flolessAgentSteps?.useParts ? window.flolessAgentSteps.useParts(app, n) : null;
556
575
  return {
557
576
  _mode: n.mode,
577
+ _aiStep: aiStep ? { badge: aiStep.badge, attention: aiStep.attention } : null,
578
+ _aiUse: aiUse ? aiUse.chip : null,
558
579
  _runtimeModel: !!n.runtimeModel, // B2: lock stamped runtime-model → card badge
559
580
  _frozen: !!n.frozen, // source node carries a `frozen:` block → card badge + Unfreeze menu
560
581
  icon: iconFor(n.agent),
@@ -563,8 +584,8 @@
563
584
  version: pin ? `v${escapeHtml(String(pin))}` : '—',
564
585
  title: escapeHtml(n.id),
565
586
  subtitle: `${agentLabel}${cmd ? '/' + cmd : ''} · ${mode}`,
566
- blurb: blurbText ? escapeHtml(blurbText) : n.notes[0] ? escapeHtml(humanizeNote(n.notes[0].text)) : `${mode}-mode ${cmd ? '<code>' + cmd + '</code>' : escapeHtml(n.kind)} node`,
567
- description: `${plainDesc ? `<p>${escapeHtml(plainDesc)}</p>` : ''}<p>Resolves to ${modeBadge} via <code>${escapeHtml(n.agent || n.kind)}${n.command ? '.' + escapeHtml(n.command) : ''}</code>.</p>${descInputs(inputs)}${execSource ? `<p class="dim-note">Full source in the <strong>Code</strong> tab.</p>` : ''}${notesHtml}`,
587
+ blurb: aiStep ? aiStep.blurb : blurbText ? escapeHtml(blurbText) : n.notes[0] ? escapeHtml(humanizeNote(n.notes[0].text)) : `${mode}-mode ${cmd ? '<code>' + cmd + '</code>' : escapeHtml(n.kind)} node`,
588
+ description: aiStep ? `${aiStep.descriptionHtml}${notesHtml}` : `${aiUse ? aiUse.descriptionHtml : ''}${plainDesc ? `<p>${escapeHtml(plainDesc)}</p>` : ''}<p>Resolves to ${modeBadge} via <code>${escapeHtml(n.agent || n.kind)}${n.command ? '.' + escapeHtml(n.command) : ''}</code>.</p>${descInputs(inputs)}${execSource ? `<p class="dim-note">Full source in the <strong>Code</strong> tab.</p>` : ''}${notesHtml}`,
568
589
  // Rich agent/command detail when the manifest is installed (n.skill); else
569
590
  // the lock-pointer fallback below (exec/agent-less nodes, uninstalled agents).
570
591
  skill: skillBody(
@@ -1302,6 +1323,16 @@
1302
1323
  const maintained = app.publisher === 'floless' && !app.forked;
1303
1324
  const drifted = app.runState === 'drift';
1304
1325
  if ($wfForked) $wfForked.hidden = !app.forked;
1326
+ // #2241: text only, and only while Agents as workflow steps is on. It says what varies (one step's answer), never that the whole
1327
+ // workflow is non-deterministic.
1328
+ if ($wfAgentStep) {
1329
+ const aiSteps = window.flolessAgentSteps?.stepCount(app) || 0;
1330
+ $wfAgentStep.hidden = !aiSteps;
1331
+ if (aiSteps) {
1332
+ $wfAgentStep.textContent = window.flolessAgentSteps.headerText(aiSteps);
1333
+ $wfAgentStep.dataset.tip = window.flolessAgentSteps.markTip(aiSteps);
1334
+ }
1335
+ }
1305
1336
  if ($customizeBtn) $customizeBtn.hidden = !maintained;
1306
1337
  if ($restoreBtn) $restoreBtn.hidden = !(maintained && drifted);
1307
1338
  // Suppress Compile for a maintained, drifted app: approving an out-of-band logic edit via
@@ -1435,7 +1466,10 @@
1435
1466
  paintKbInformed(null, false); // clear the previous workflow's row before the await, not after
1436
1467
  if (!id) return;
1437
1468
  try {
1438
- const r = await fetch(`/api/kb-pin/${encodeURIComponent(id)}`, { cache: 'no-store' });
1469
+ const path = `/api/kb-pin/${encodeURIComponent(id)}`;
1470
+ await globalThis.flolessStartupAdmission?.admit(path);
1471
+ if (read !== kbPinRead || currentId !== id) return;
1472
+ const r = await fetch(path, { cache: 'no-store' });
1439
1473
  const d = await r.json();
1440
1474
  if (read !== kbPinRead || currentId !== id) return; // superseded — a newer workflow owns the strip
1441
1475
  if (r.ok && d.ok) paintKbInformed(d.pin, !!d.drift);
@@ -2146,7 +2180,33 @@
2146
2180
  return false;
2147
2181
  }
2148
2182
 
2183
+ // #2241: the Agent-step labels (web/agent-steps.js) learn the open workflow from here and ask for repaints when a check lands.
2184
+ function repaintAgentSteps(appId) {
2185
+ if (appId !== currentId) return;
2186
+ const app = apps.get(appId);
2187
+ if (!app) return;
2188
+ for (const n of app.nodes) {
2189
+ if (!window.flolessAgentSteps.isStepNode(n)) continue;
2190
+ AGENTS[n.id] = buildAgentEntry(app, n);
2191
+ const blurb = [...document.querySelectorAll('.agent-card')].find((card) => card.dataset.agentId === n.id)?.querySelector('.blurb');
2192
+ if (blurb) blurb.innerHTML = AGENTS[n.id].blurb;
2193
+ }
2194
+ if (state.selectedAgentId && AGENTS[state.selectedAgentId]?._aiStep) renderInspect();
2195
+ }
2196
+ window.flolessAgentSteps?.configure({
2197
+ currentApp: () => (currentId ? apps.get(currentId) || null : null),
2198
+ openAgent: (agentId) => { void window.flolessAgents?.open?.(agentId); },
2199
+ openAgents: () => { void window.flolessWorkspaces?.setMode?.('agents'); },
2200
+ toast: (text, kind) => showToast(text, kind),
2201
+ repaint: repaintAgentSteps,
2202
+ // #2374: the trace labels outputs from the run's own record, which arrives after the run ends.
2203
+ runRecordChanged: (appId) => { if (appId === currentId && state.currentTab === 'execution') renderInspect(); },
2204
+ });
2205
+
2149
2206
  async function loadApp(id) {
2207
+ // (globalThis, not window: this function is also lifted into a test harness that has no window; in the page they are the same object.
2208
+ // It never awaits the Agent-step status probe: opening a workflow must not wait on anything new, or the boot race below it gets likelier.)
2209
+ selectionTargetId = id;
2150
2210
  hideSpotlight(); // a spotlight pointing at the previous app's beacon must clear on switch
2151
2211
  const ticket = ++selectionTicket;
2152
2212
  const payload = api(`/api/app/${encodeURIComponent(id)}`);
@@ -2171,6 +2231,7 @@
2171
2231
  // loaded before this app did, so repaint it once the ownership boundary is known.
2172
2232
  renderFavBar();
2173
2233
  try { localStorage.setItem(LS_LAST_APP, id); } catch { /* private mode / quota */ }
2234
+ globalThis.flolessAgentSteps?.forgetChecks(id); // #2241: a check from an earlier open of this workflow is stale until the new one lands
2174
2235
  transform(app);
2175
2236
  liveTrace.length = 0;
2176
2237
  state.promptKey = id;
@@ -2193,6 +2254,9 @@
2193
2254
  refreshDirtyIndicator(); // clean app → dot off; switched back to a dirty one → dot on
2194
2255
  renderWfUpdatePill(); // show the "↑ Update to vX" pill when THIS app has a newer published version
2195
2256
  maybeSpotlight(app); // one-time first-open spotlight pointing at the beacon (slice 2)
2257
+ globalThis.flolessAgentSteps?.paintCanvasControl();
2258
+ void globalThis.flolessAgentSteps?.refreshChecks(app); // #2241: newer-instructions banner; a failed check says nothing
2259
+ void globalThis.flolessAgentSteps?.refreshRunRecord(app.id); // #2241 S5: how the last run's AI steps went, and what it left for you
2196
2260
  }
2197
2261
 
2198
2262
  async function waitForPublicationAvailabilityIdle() {
@@ -2225,18 +2289,42 @@
2225
2289
  return waitForPublicationAvailabilityIdle();
2226
2290
  }
2227
2291
 
2292
+ // An SSE-driven availability re-read is for the workflow still selected underneath whatever is on
2293
+ // screen. While Workspaces or Agents is showing, a failure there is nothing the person did, and
2294
+ // returning to Workflows re-reads it (refreshCurrentWorkflow) and reports a failure itself — so it
2295
+ // is logged, not toasted. 2026-10-16: an expired module lease turned every chat approval's
2296
+ // projects-changed into a generic "We couldn't finish that" toast over a Tekla Parser project.
2297
+ // On Workflows the card is the person's to see, so a failure there is still reported.
2298
+ function reportBackgroundAvailabilityErr(e) {
2299
+ if (document.body.classList.contains('mode-workspaces') || document.body.classList.contains('mode-agents')) {
2300
+ console.warn('[floless] the selected workflow’s availability could not be refreshed in the background', e);
2301
+ return;
2302
+ }
2303
+ reportErr(e);
2304
+ }
2305
+
2228
2306
  // Workspaces keeps the existing workflow selected underneath its project surface. Returning to
2229
2307
  // Workflows is therefore a re-open of that workflow: refresh both its publication state and the
2230
2308
  // additive provenance strip, so a KB organize that happened while the project was open cannot
2231
2309
  // leave a stale "Informed by" answer on the canvas.
2232
2310
  function refreshCurrentWorkflow() {
2233
2311
  const id = currentId;
2312
+ // #2241: an Agent may have been edited, archived or restored while another surface was open; ask again how the steps stand.
2313
+ if (id && apps.get(id)) void window.flolessAgentSteps?.refreshChecks(apps.get(id));
2234
2314
  return Promise.all([
2235
2315
  refreshCurrentWorkflowAvailability(),
2236
2316
  refreshKbInformed(id),
2237
2317
  ]).then(() => {});
2238
2318
  }
2239
2319
 
2320
+ // Bulk Compile changes the lock itself, including pins and notices. Availability alone cannot
2321
+ // refresh that canvas. A pending selection of another workflow always keeps the person's choice.
2322
+ async function reloadCompiledWorkflows(appIds) {
2323
+ const id = currentId;
2324
+ if (!id || selectionTargetId !== id || !appIds.includes(id)) return;
2325
+ await loadApp(id); // loadApp's selection ticket also rejects a later workflow switch
2326
+ }
2327
+
2240
2328
  async function loadApps({ preserveSelection = false } = {}) {
2241
2329
  // …and mean it: the trigger said "loading…" but stayed CLICKABLE, so a click during the fetch
2242
2330
  // opened the popover onto an empty #wf-list — the exact "picker opens and stays empty, it never
@@ -2439,6 +2527,7 @@
2439
2527
  // Opening anything (a workflow or a draft) takes a new ticket; a workflow load that finishes after a newer open
2440
2528
  // is dropped, so a slow load can never land on top of a draft opened meanwhile (#1890 PR 3b-0 review).
2441
2529
  let selectionTicket = 0;
2530
+ let selectionTargetId = null;
2442
2531
  // Each loadApps() takes a number; only the newest may change the lists or what is open.
2443
2532
  let appsLoadGeneration = 0;
2444
2533
  let wsTitleKind = null; // #2007: 'agents' while the Agents tab is on screen (it reuses this title/Instructor seam)
@@ -2504,6 +2593,7 @@
2504
2593
  + `<button type="button" class="wf-act act-del" data-wf-act="delete" data-command-id="workflow.delete#${escapeAttr(aid)}" data-id="${aid}" tabindex="-1" data-tip="Delete" aria-label="Delete ${escapeAttr(workflowName)}">×</button>`;
2505
2594
  html += `<div class="wf-option" role="option" id="wf-opt-${aid}" data-id="${aid}" data-workflow-id="${escapeAttr(ownedId)}" data-workflow-name="${escapeAttr(workflowName)}" data-command-id="workflow.select#${escapeAttr(aid)}" data-baked="${a.baked ? '1' : ''}" data-search="${escapeAttr((workflowName + ' ' + a.id + ' ' + (a.ownerLabel || '') + ' ' + p).toLowerCase())}" tabindex="-1" aria-selected="false">`
2506
2595
  + `<span class="wf-option-name">${escapeHtml(workflowName)}</span><span class="wf-option-meta">${meta}</span>`
2596
+ + (a.agentStep ? `<span class="wf-fork-badge wf-ai-badge" data-tip="A step in this workflow is answered by an AI Agent, so that answer can differ each run.">AI step</span>` : '')
2507
2597
  + (a.forked ? `<span class="wf-fork-badge" data-tip="You forked this workflow — it no longer receives FloLess updates. You own its output.">yours</span>` : '')
2508
2598
  + `<span class="wf-option-actions">`
2509
2599
  + actions
@@ -4054,6 +4144,140 @@
4054
4144
  // double-click LOAD the last result instantly instead of re-running.
4055
4145
  const lastReportByApp = new Map();
4056
4146
 
4147
+ // #2262 slice 3a: a successful real run's report is also kept as a version of its workflow's Page. The server saves
4148
+ // it after answering the run and says when it landed (`workflow-page-captured`), so that news can arrive before or
4149
+ // after the report is cached here. It is kept by run id and joined to the report of the SAME run only, never to a
4150
+ // newer one. `workflowPageLatest` is the newest version this window knows per workflow, for the empty viewer after
4151
+ // a reload; for one Page it only ever grows.
4152
+ // Keyed by CAPTURE: a completed run's runId, or `runId#fireKey` for one fire of a live trigger session (slice 3b),
4153
+ // so an older fire's news never joins a newer fire's report.
4154
+ const workflowPageByRun = new Map(); // captureKey → { app, home, pageId, version }
4155
+ function captureKeyOf(runId, fireKey) {
4156
+ if (typeof runId !== 'string' || !runId) return null;
4157
+ return typeof fireKey === 'string' && fireKey ? `${runId}#${fireKey}` : runId;
4158
+ }
4159
+ const workflowPageLatest = new Map(); // app id → { home, pageId, version, at }
4160
+ const WORKFLOW_PAGE_RUNS_KEPT = 64;
4161
+
4162
+ function noteWorkflowPageLatest(app, page) {
4163
+ const prev = workflowPageLatest.get(app);
4164
+ if (prev && prev.home === page.home && prev.pageId === page.pageId && prev.version >= page.version) return;
4165
+ workflowPageLatest.set(app, { home: page.home, pageId: page.pageId, version: page.version, at: Date.now() });
4166
+ }
4167
+
4168
+ /** The Page version this cached report became, once its capture has landed. */
4169
+ function reportPageOf(entry) {
4170
+ const key = entry ? (typeof entry.captureKey === 'string' ? entry.captureKey : captureKeyOf(entry.runId)) : null;
4171
+ return key ? workflowPageByRun.get(key) || null : null;
4172
+ }
4173
+
4174
+ function applyWorkflowPageCaptured(m) {
4175
+ if (!m || typeof m.app !== 'string' || typeof m.runId !== 'string') return;
4176
+ if (typeof m.warning === 'string') {
4177
+ // The run itself succeeded and its report is shown; the window on this workflow is told, the others log it.
4178
+ if (currentId === m.app) showToast(m.warning, 'warn');
4179
+ else console.warn(`Workflow ${m.app}: ${m.warning}`);
4180
+ return;
4181
+ }
4182
+ // #2262 slice 3c: saved, but part of what the run made could not go with it (a report folder's files).
4183
+ if (typeof m.notice === 'string') {
4184
+ if (currentId === m.app) showToast(m.notice, 'warn');
4185
+ else console.warn(`Workflow ${m.app}: ${m.notice}`);
4186
+ }
4187
+ if (m.relabelled === 'live-failed' && typeof m.home === 'string' && typeof m.pageId === 'string') {
4188
+ // A failed live session's versions changed label: an open copy of that Page must not keep the old one.
4189
+ window.flolessPages?.reloadIfOpen?.(m.home, m.pageId);
4190
+ window.flolessPages?.refresh?.();
4191
+ return;
4192
+ }
4193
+ if (typeof m.home !== 'string' || typeof m.pageId !== 'string' || !Number.isInteger(m.version) || m.version < 1) {
4194
+ console.warn('A workflow Page update could not be read, so it was ignored.', m);
4195
+ return;
4196
+ }
4197
+ const page = { app: m.app, home: m.home, pageId: m.pageId, version: m.version };
4198
+ workflowPageByRun.set(captureKeyOf(m.runId, m.fireKey) || m.runId, page);
4199
+ if (workflowPageByRun.size > WORKFLOW_PAGE_RUNS_KEPT) workflowPageByRun.delete(workflowPageByRun.keys().next().value);
4200
+ noteWorkflowPageLatest(m.app, page);
4201
+ window.flolessPages?.refresh?.();
4202
+ if (currentId === m.app) paintReportPageLinks();
4203
+ }
4204
+
4205
+ /** A Page deleted in this window: its versions are gone, so no report may still offer to open them. */
4206
+ function forgetDeletedPage(home, pageId) {
4207
+ for (const [runId, page] of workflowPageByRun) if (page.home === home && page.pageId === pageId) workflowPageByRun.delete(runId);
4208
+ for (const [app, page] of workflowPageLatest) if (page.home === home && page.pageId === pageId) workflowPageLatest.delete(app);
4209
+ paintReportPageLinks();
4210
+ }
4211
+ window.addEventListener('floless:page-deleted', (event) => {
4212
+ const d = event.detail || {};
4213
+ if (typeof d.home === 'string' && typeof d.id === 'string') forgetDeletedPage(d.home, d.id);
4214
+ });
4215
+
4216
+ /** Ask the server for a workflow's Page: the report area after a reload, a reconnect, or an empty viewer. */
4217
+ async function refreshWorkflowPage(app) {
4218
+ if (!app) return;
4219
+ const asked = Date.now();
4220
+ let body;
4221
+ try { body = await api(`/api/pages/workflow?app=${encodeURIComponent(app)}`); }
4222
+ catch (e) { console.warn(`FloLess couldn’t read the Page of workflow ${app}.`, e); return; }
4223
+ const page = body && body.page;
4224
+ if (page && typeof body.home === 'string' && typeof page.id === 'string' && Number.isInteger(page.latestVersion)) {
4225
+ noteWorkflowPageLatest(app, { home: body.home, pageId: page.id, version: page.latestVersion });
4226
+ } else if (body && typeof body.note === 'string') {
4227
+ // Unreadable or unplaceable is not "deleted": keep what this window knows, and say why in the console.
4228
+ console.warn(`Workflow ${app}: ${body.note}`);
4229
+ } else if (body && body.ok && !page && (workflowPageLatest.get(app)?.at ?? 0) < asked) {
4230
+ workflowPageLatest.delete(app); // the Page was deleted (a capture that landed meanwhile is kept)
4231
+ }
4232
+ if (currentId === app) paintReportPageLinks();
4233
+ }
4234
+
4235
+ /** The viewer's links to the workflow's Page: in the header, the version the SHOWN report became; in the empty
4236
+ * viewer, the latest version. Each is hidden when it is not known — never a guess at a version. */
4237
+ function paintReportPageLinks() {
4238
+ const app = currentId;
4239
+ const cached = app ? lastReportByApp.get(app) : null;
4240
+ // #2539: only for the report actually on screen — a complete report shown is that run's own (matched by handle), never
4241
+ // one opened from a Page version or another run.
4242
+ const shown = cached && !reportRunning && $reportOverlay.hidden
4243
+ && (cached.handle ? currentCompleteReport?.handle === cached.handle : !currentCompleteReport);
4244
+ const page = shown ? reportPageOf(cached) : null;
4245
+ if ($reportPage) {
4246
+ $reportPage.hidden = !page;
4247
+ if (page) {
4248
+ $reportPage.textContent = `Version ${page.version} · Open in Pages`;
4249
+ $reportPage.setAttribute('data-command-id', `shell.report-page-open#${app}`);
4250
+ Object.assign($reportPage.dataset, { home: page.home, page: page.pageId, version: String(page.version) });
4251
+ }
4252
+ }
4253
+ const latestButton = document.getElementById('report-latest-page');
4254
+ if (latestButton) {
4255
+ const latest = !cached && app ? workflowPageLatest.get(app) : null;
4256
+ latestButton.hidden = !latest;
4257
+ // "No report yet" would contradict the saved one offered right below it.
4258
+ const line = document.getElementById('report-empty-line');
4259
+ if (line && latest) line.innerHTML = 'No report open in this window.<div class="report-empty-hint">Saved reports are kept in the workflow’s Page. Or click <strong>▶ Run workflow</strong> for a fresh one.</div>';
4260
+ if (latest) {
4261
+ latestButton.textContent = `Open latest report (version ${latest.version})`;
4262
+ Object.assign(latestButton.dataset, { home: latest.home, page: latest.pageId, version: String(latest.version) });
4263
+ }
4264
+ }
4265
+ }
4266
+
4267
+ // Open the Page itself. The report viewer sits above the Page viewer, so it closes first.
4268
+ $reportModal?.addEventListener('click', (event) => {
4269
+ const link = event.target.closest?.('#report-page, #report-latest-page');
4270
+ if (!link || !link.dataset.home || !link.dataset.page) return;
4271
+ const version = Number(link.dataset.version);
4272
+ void (async () => {
4273
+ try {
4274
+ if (typeof window.flolessPages?.open !== 'function') throw new Error('The Pages viewer is not loaded. Reload FloLess and try again.');
4275
+ await closeReportViewer();
4276
+ await window.flolessPages.open(link.dataset.home, link.dataset.page, Number.isInteger(version) && version > 0 ? version : undefined);
4277
+ } catch (e) { showToast(`FloLess couldn’t open the workflow’s Page. ${e && e.message ? e.message : ''}`.trim(), 'warn'); }
4278
+ })();
4279
+ });
4280
+
4057
4281
  // A live FOREGROUND trigger session — ▶ Run on a streaming/watch app (one whose
4058
4282
  // source is a lifecycle:start watch). The finite run can't complete for a stream,
4059
4283
  // so Run hosts a live session that re-renders the report in the Viewer on every
@@ -4115,7 +4339,7 @@
4115
4339
  if (foregroundTrigger) {
4116
4340
  const ft = foregroundTrigger;
4117
4341
  foregroundStopping = true;
4118
- foregroundTrigger = null;
4342
+ foregroundTrigger = null; liveViewerMayHaveChanged();
4119
4343
  if ($stopRunBtn) { $stopRunBtn.disabled = true; $stopRunBtn.textContent = 'Stopping…'; }
4120
4344
  syncRunControls();
4121
4345
  try { await api(`/api/trigger-run/${encodeURIComponent(ft.appId)}/stop`, { method: 'POST' }); } catch { /* best effort — the session may already be gone */ }
@@ -4174,6 +4398,7 @@
4174
4398
  let currentCompleteReport = null;
4175
4399
  let currentReportSection = 0;
4176
4400
  let reportSectionRequest = 0;
4401
+ let reportObjectLookup = 0; // #2539: the newest Go to object; an older one never touches its message
4177
4402
  function updateReportSectionNavigation(ordinal, index) {
4178
4403
  const first = ordinal === 0;
4179
4404
  const last = ordinal + 1 >= index.chunkCount;
@@ -4191,6 +4416,31 @@
4191
4416
  }
4192
4417
  if (controls.some(([control]) => control === focused)) window.Instructor?.refreshCarrier(focused);
4193
4418
  }
4419
+ // #2262 slice 3c: "Open the full report" beside a complete report's Page version. The server answers the report's
4420
+ // handle for that version's run, after the report viewer's own checks; the Page viewer closes and this one opens.
4421
+ window.FlolessReports = {
4422
+ async openPageVersionReport({ home, id, n, title, beforeShow }) {
4423
+ let answer;
4424
+ try {
4425
+ await ensureReportDiscoverySession();
4426
+ answer = await api(`/api/pages/${encodeURIComponent(home)}/${encodeURIComponent(id)}/versions/${encodeURIComponent(n)}/full-report`);
4427
+ } catch (error) {
4428
+ showToast(error?.message && !/^HTTP \d+$/.test(error.message) ? error.message : 'FloLess couldn’t open the full report. Try again in a moment.', 'warn');
4429
+ return false;
4430
+ }
4431
+ if (typeof answer?.handle !== 'string' || !answer.handle) {
4432
+ showToast('FloLess couldn’t open the full report. Try again in a moment.', 'warn');
4433
+ return false;
4434
+ }
4435
+ beforeShow?.();
4436
+ $reportTitle.textContent = `HTML Viewer · ${title || 'Complete model report'}`;
4437
+ showModal($reportModal);
4438
+ $reportClose.focus();
4439
+ await paintCompleteReport({ handle: answer.handle });
4440
+ return true;
4441
+ },
4442
+ };
4443
+
4194
4444
  function clearCompleteReportView() {
4195
4445
  reportSectionRequest += 1;
4196
4446
  currentCompleteReport = null;
@@ -4201,95 +4451,130 @@
4201
4451
  $reportObjectError.textContent = '';
4202
4452
  $reportFrame.removeAttribute('src');
4203
4453
  }
4204
- async function paintCompleteReport(report, ordinal = null) {
4454
+ /** Show one section of a saved complete report. Resolves true once it is on screen, false when it is not. */
4455
+ async function paintCompleteReport(report, asked = null, busyUntil = null) {
4456
+ // #2539: a report another read holds is waited for, not failed — right after a run that is the workflow's Page
4457
+ // saving its copy, which reads the whole report. Past this wait the viewer offers Try again instead.
4458
+ const REPORT_BUSY_WAIT_MS = 5 * 60_000;
4459
+ // The server answers a busy report with 202 and this code (never a failure status), whichever route was asked.
4460
+ const reportIsBusy = (error) => error?.body?.code === 'report-busy';
4205
4461
  const request = ++reportSectionRequest;
4206
4462
  const handle = encodeURIComponent(report.handle);
4207
4463
  $reportOverlay.hidden = false;
4208
4464
  $reportOverlay.replaceChildren(mkEl('div', 'spinner'), mkEl('div', null, 'Loading report section…'));
4209
- try {
4210
- let index = await api(`/api/model-reports/${handle}/index?at=${ordinal ?? 0}`);
4211
- if (request !== reportSectionRequest) return;
4212
- // Start with the first object's data, while First still opens Model information.
4213
- // Ask the verified index where that object begins instead of assuming section 2.
4214
- if (ordinal == null) {
4215
- ordinal = 0;
4216
- if (Number(index.objectCount) > 0 && index.current?.firstObject == null) {
4217
- const firstObject = await api(`/api/model-reports/${handle}/object/0`);
4218
- if (request !== reportSectionRequest) return;
4219
- ordinal = firstObject.chunkOrdinal;
4220
- index = await api(`/api/model-reports/${handle}/index?at=${ordinal}`);
4465
+ // A wait resumed for the same section (the frame found it busy) keeps its first deadline, never a fresh one.
4466
+ const waitUntil = busyUntil ?? Date.now() + REPORT_BUSY_WAIT_MS;
4467
+ for (;;) {
4468
+ let ordinal = asked;
4469
+ try {
4470
+ let index = await api(`/api/model-reports/${handle}/index?at=${ordinal ?? 0}`);
4471
+ if (request !== reportSectionRequest) return false;
4472
+ // Start with the first object's data, while First still opens Model information.
4473
+ // Ask the verified index where that object begins instead of assuming section 2.
4474
+ if (ordinal == null) {
4475
+ ordinal = 0;
4476
+ if (Number(index.objectCount) > 0 && index.current?.firstObject == null) {
4477
+ const firstObject = await api(`/api/model-reports/${handle}/object/0`);
4478
+ if (request !== reportSectionRequest) return false;
4479
+ ordinal = firstObject.chunkOrdinal;
4480
+ index = await api(`/api/model-reports/${handle}/index?at=${ordinal}`);
4481
+ }
4482
+ }
4483
+ if (request !== reportSectionRequest) return false;
4484
+ const response = await fetch(`/api/model-reports/${handle}/chunk/${ordinal}`, { credentials: 'same-origin', cache: 'no-store' });
4485
+ if (!response.ok || response.status === 202) {
4486
+ const body = await response.json().catch(() => null);
4487
+ throw Object.assign(new Error('Report section request failed'), { status: response.status, body });
4488
+ }
4489
+ const length = Number(response.headers.get('content-length'));
4490
+ if (Number.isFinite(length) && length > 1200 * 1024) {
4491
+ await response.body?.cancel();
4492
+ throw Object.assign(new Error('Report section exceeds viewer limit'), { status: 413 });
4221
4493
  }
4222
- }
4223
- if (request !== reportSectionRequest) return;
4224
- const response = await fetch(`/api/model-reports/${handle}/chunk/${ordinal}`, { credentials: 'same-origin', cache: 'no-store' });
4225
- if (!response.ok) {
4226
- const body = await response.json().catch(() => null);
4227
- throw Object.assign(new Error('Report section request failed'), { status: response.status, body });
4228
- }
4229
- const length = Number(response.headers.get('content-length'));
4230
- if (Number.isFinite(length) && length > 1200 * 1024) {
4231
4494
  await response.body?.cancel();
4232
- throw Object.assign(new Error('Report section exceeds viewer limit'), { status: 413 });
4233
- }
4234
- await response.body?.cancel();
4235
- if (request !== reportSectionRequest) return;
4236
- $reportFrame.removeAttribute('srcdoc');
4237
- // Navigate to the real session-gated route. Its restrictive CSP must belong to the
4238
- // rendered document itself; a blob: copy would silently lose that response header.
4239
- $reportFrame.src = `/api/model-reports/${handle}/chunk/${ordinal}`;
4240
- $reportFrame.hidden = false;
4241
- $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4242
- currentCompleteReport = report;
4243
- currentReportSection = ordinal;
4244
- const count = Number(index.objectCount) || 0;
4245
- const properties = Number(index.propertyCount) || 0;
4246
- const current = index.current || {};
4247
- const objectRange = count === 0 ? 'No objects' : current.firstObject == null
4248
- ? `Model information · Report contains ${count} objects` : `Objects ${Number(current.firstObject) + 1}–${Number(current.lastObject) + 1} of ${count}`;
4249
- const propertyRange = properties === 0 ? '0 properties'
4250
- : current.firstProperty == null ? `Report contains ${properties} properties`
4251
- : `Properties ${Number(current.firstProperty) + 1}–${Number(current.lastProperty) + 1} of ${properties}`;
4252
- $reportSectionStatus.textContent = `${objectRange} · ${propertyRange} · section ${ordinal + 1} of ${index.chunkCount}`;
4253
- updateReportSectionNavigation(ordinal, index);
4254
- $reportNav.hidden = false;
4255
- $reportDownload.hidden = false;
4256
- $reportOpen.hidden = true;
4257
- $reportShare.hidden = true;
4258
- showSavedPathActions('');
4259
- $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
4260
- // #1840: the caption says when the report's approved version accepted open import findings (the
4261
- // server's sentence). The report body comes from AWARE's report protocol, which appears to have no
4262
- // field for it (inferred from its parser's messages, not reproduced). When the server could not
4263
- // read that approval's record, the caption says so instead of reading as a plain approval.
4264
- $reportSub.textContent = report.scheduledCaption
4265
- || `Complete read-only report · ${count} objects · ${properties} properties · approved revision ${String(index.revisionId).slice(0, 12)} · source unchanged.`;
4266
- if (typeof index.acceptedImportFindingsNote === 'string') $reportSub.textContent += ` ${index.acceptedImportFindingsNote}`;
4267
- else if (index.approvalDetailsUnavailable === true) $reportSub.textContent += ' Approval details unavailable.';
4268
- // What the report rests on comes first (a scheduled "Latest approved" run that read an older
4269
- // approved version says which), never after the counts where it would read as a footnote.
4270
- const warnings = Array.isArray(index.warnings) ? index.warnings.filter((warning) => typeof warning === 'string' && warning) : [];
4271
- if (warnings.length) $reportSub.textContent = `${warnings.join(' ')} ${$reportSub.textContent}`;
4272
- } catch (error) {
4273
- if (request !== reportSectionRequest) return;
4274
- clearCompleteReportView();
4275
- $reportFrame.srcdoc = '';
4276
- $reportSub.textContent = 'This report section could not be displayed.';
4277
- const status = Number(error?.status);
4278
- let remedy = 'Close the viewer and choose View report to retry loading this saved report.';
4279
- if (status === 401) remedy = 'Sign in again, then close the viewer and choose View report to load this saved report.';
4280
- else if (status === 403) remedy = 'Report access could not be confirmed. Check your account access and connection, then choose View report again.';
4281
- else if (status === 404 || status === 410) remedy = 'This report is no longer available. Choose Run workflow to create a fresh report.';
4282
- else if (status === 409) remedy = 'This saved report cannot be opened right now. If another read is running, wait for it to finish and choose View report again. Otherwise choose an approved model in Inputs and Run workflow to create a fresh report.';
4283
- else if (status === 429) remedy = 'This report is busy. Wait for the current read to finish, then close the viewer and choose View report again.';
4284
- else if (status === 413) {
4285
- remedy = 'This section is too large for the viewer. Download complete report to read the saved report.';
4495
+ if (request !== reportSectionRequest) return false;
4496
+ $reportFrame.removeAttribute('srcdoc');
4497
+ // Navigate to the real session-gated route. Its restrictive CSP must belong to the
4498
+ // rendered document itself; a blob: copy would silently lose that response header.
4499
+ // #2539: which paint this frame load belongs to, and its wait deadline, should the frame find the report busy.
4500
+ Object.assign($reportFrame.dataset, { request: String(request), busyUntil: String(waitUntil) });
4501
+ $reportFrame.src = `/api/model-reports/${handle}/chunk/${ordinal}`;
4502
+ $reportFrame.hidden = false;
4503
+ $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4286
4504
  currentCompleteReport = report;
4505
+ currentReportSection = ordinal;
4506
+ const count = Number(index.objectCount) || 0;
4507
+ const properties = Number(index.propertyCount) || 0;
4508
+ const current = index.current || {};
4509
+ const objectRange = count === 0 ? 'No objects' : current.firstObject == null
4510
+ ? `Model information · Report contains ${count} objects` : `Objects ${Number(current.firstObject) + 1}–${Number(current.lastObject) + 1} of ${count}`;
4511
+ const propertyRange = properties === 0 ? '0 properties'
4512
+ : current.firstProperty == null ? `Report contains ${properties} properties`
4513
+ : `Properties ${Number(current.firstProperty) + 1}–${Number(current.lastProperty) + 1} of ${properties}`;
4514
+ $reportSectionStatus.textContent = `${objectRange} · ${propertyRange} · section ${ordinal + 1} of ${index.chunkCount}`;
4515
+ updateReportSectionNavigation(ordinal, index);
4516
+ $reportNav.hidden = false;
4287
4517
  $reportDownload.hidden = false;
4288
- } else if (status === 503) remedy = 'Saved reports are being prepared. Wait a moment, then close the viewer and choose View report again.';
4289
- // Keep diagnostics bounded: transport messages can contain private paths or server details.
4290
- console.warn('Report section display failed', { status: Number.isFinite(status) ? status : null });
4291
- $reportOverlay.hidden = false;
4292
- $reportOverlay.replaceChildren(mkEl('div', null, remedy));
4518
+ $reportOpen.hidden = true;
4519
+ $reportShare.hidden = true;
4520
+ showSavedPathActions('');
4521
+ $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
4522
+ // #1840: the caption says when the report's approved version accepted open import findings (the
4523
+ // server's sentence). The report body comes from AWARE's report protocol, which appears to have no
4524
+ // field for it (inferred from its parser's messages, not reproduced). When the server could not
4525
+ // read that approval's record, the caption says so instead of reading as a plain approval.
4526
+ $reportSub.textContent = report.scheduledCaption
4527
+ || `Complete read-only report · ${count} objects · ${properties} properties · approved revision ${String(index.revisionId).slice(0, 12)} · source unchanged.`;
4528
+ if (typeof index.acceptedImportFindingsNote === 'string') $reportSub.textContent += ` ${index.acceptedImportFindingsNote}`;
4529
+ else if (index.approvalDetailsUnavailable === true) $reportSub.textContent += ' Approval details unavailable.';
4530
+ // What the report rests on comes first (a scheduled "Latest approved" run that read an older
4531
+ // approved version says which), never after the counts where it would read as a footnote.
4532
+ const warnings = Array.isArray(index.warnings) ? index.warnings.filter((warning) => typeof warning === 'string' && warning) : [];
4533
+ if (warnings.length) $reportSub.textContent = `${warnings.join(' ')} ${$reportSub.textContent}`;
4534
+ paintReportPageLinks(); // #2539: the Page version this report became, now that it is on screen
4535
+ return true;
4536
+ } catch (error) {
4537
+ if (request !== reportSectionRequest) return false;
4538
+ // #2539: busy is not a failure. Say what it waits for (the server's sentence) and open the report by itself.
4539
+ if (reportIsBusy(error) && Date.now() < waitUntil) {
4540
+ const waiting = mkEl('div', null, String(error.body.error || 'This report is busy. It opens as soon as that finishes.'));
4541
+ waiting.setAttribute('role', 'status');
4542
+ $reportOverlay.replaceChildren(mkEl('div', 'spinner'), waiting);
4543
+ const pause = Math.min(10_000, Math.max(500, Number(error.body.retryAfterMs) || 2_000));
4544
+ await new Promise((resolve) => setTimeout(resolve, pause));
4545
+ if (request !== reportSectionRequest) return false;
4546
+ continue;
4547
+ }
4548
+ clearCompleteReportView();
4549
+ $reportFrame.srcdoc = '';
4550
+ $reportSub.textContent = 'This report section could not be displayed.';
4551
+ const status = Number(error?.status);
4552
+ let remedy = 'Close the viewer and choose View report to retry loading this saved report.';
4553
+ if (status === 401) remedy = 'Sign in again, then close the viewer and choose View report to load this saved report.';
4554
+ else if (status === 403) remedy = 'Report access could not be confirmed. Check your account access and connection, then choose View report again.';
4555
+ else if (status === 404 || status === 410) remedy = 'This report is no longer available. Choose Run workflow to create a fresh report.';
4556
+ else if (reportIsBusy(error)) remedy = 'This report is still busy. Choose Try again to open it, or close the viewer and choose View report later.';
4557
+ else if (status === 409) remedy = 'This saved report cannot be opened right now. If another read is running, wait for it to finish and choose View report again. Otherwise choose an approved model in Inputs and Run workflow to create a fresh report.';
4558
+ else if (status === 429) remedy = 'This report is busy. Wait for the current read to finish, then close the viewer and choose View report again.';
4559
+ else if (status === 413) {
4560
+ remedy = 'This section is too large for the viewer. Download complete report to read the saved report.';
4561
+ currentCompleteReport = report;
4562
+ $reportDownload.hidden = false;
4563
+ } else if (status === 503) remedy = 'Saved reports are being prepared. Wait a moment, then close the viewer and choose View report again.';
4564
+ // Keep diagnostics bounded: transport messages can contain private paths or server details.
4565
+ console.warn('Report section display failed', { status: Number.isFinite(status) ? status : null });
4566
+ $reportOverlay.hidden = false;
4567
+ $reportOverlay.replaceChildren(mkEl('div', null, remedy));
4568
+ if (reportIsBusy(error)) {
4569
+ const again = mkEl('button', 'ghost report-retry', 'Try again');
4570
+ again.type = 'button';
4571
+ again.setAttribute('data-command-id', 'shell.report-busy-retry');
4572
+ again.addEventListener('click', () => { void paintCompleteReport(report, asked); });
4573
+ $reportOverlay.append(again);
4574
+ again.focus?.();
4575
+ }
4576
+ return false;
4577
+ }
4293
4578
  }
4294
4579
  }
4295
4580
  // The share route's user-facing cap (server/index.ts sets a 6 MB body limit; the JSON envelope
@@ -4312,12 +4597,14 @@
4312
4597
  // INTERACTIVE 3D doc (viewer-3d) uses the script-enabled frame via a data: URL (opaque
4313
4598
  // origin, cannot touch the app page) and keeps a "Loading 3D view…" overlay until the doc
4314
4599
  // posts `viewer-ready`. Exactly one frame is shown at a time.
4315
- function paintReport(html, interactive) {
4600
+ function paintReport(html, interactive, entry = null) {
4316
4601
  clearCompleteReportView();
4317
4602
  $reportOpen.hidden = false;
4318
4603
  lastPaintedHtml = html || '';
4319
4604
  lastPaintedInteractive = !!interactive; // drives the share copy: a 3D model is not a "frozen report"
4320
4605
  showSavedPathActions(''); // default off; the caller re-shows if this report saved a file
4606
+ if ($reportPage) $reportPage.hidden = true; // likewise its Page link (paintReportPageLinks, once it is cached)
4607
+ if (!interactive && entry && entry.withFiles) { paintReportWithFiles(html); return; }
4321
4608
  if (interactive) {
4322
4609
  $reportFrame.hidden = true; $reportFrame.srcdoc = '';
4323
4610
  $reportFrame3d.hidden = false;
@@ -4337,6 +4624,21 @@
4337
4624
  }
4338
4625
  }
4339
4626
 
4627
+ // #2262 slice 3c: a report that carries files (`report_folder`) refers to them as `assets/…`, which resolve only in its
4628
+ // Page version. The run viewer shows a copy with those references made inert (web/report-files.js: no broken picture,
4629
+ // no failed request) and a note pointing to the Page version, where the files are ("Open in Pages" appears once it is
4630
+ // saved). Open and Share are hidden here: they would hand out this copy without its files — the Page has its own Share.
4631
+ // (A viewer that switches to the saved version itself was split out on the night shift — Fable, review stop signal.)
4632
+ const FILES_NOTE = 'This report has pictures and files that only show in its Page version. Use “Open in Pages” at the top to see it with them.';
4633
+ function paintReportWithFiles(html) {
4634
+ $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4635
+ $reportFrame.hidden = false;
4636
+ $reportFrame.srcdoc = window.FlolessReportFiles.neutralize(html, null, FILES_NOTE);
4637
+ $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
4638
+ $reportOpen.hidden = true;
4639
+ $reportShare.hidden = true;
4640
+ }
4641
+
4340
4642
  // Reset the viewer to "no report shown": clear BOTH frames + the Open buffer, so a stale
4341
4643
  // interactive 3D doc can't linger (its WebGL loop running) behind an overlay, and ↗ Open
4342
4644
  // can't reopen a previous app's report. Used by every empty / transition state.
@@ -4347,6 +4649,7 @@
4347
4649
  $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4348
4650
  lastPaintedHtml = '';
4349
4651
  showSavedPathActions(''); // no report shown → no saved-file actions
4652
+ if ($reportPage) $reportPage.hidden = true;
4350
4653
  }
4351
4654
 
4352
4655
  // Double-click the HTML Viewer node → LOAD the last report (no run; running is
@@ -4371,15 +4674,19 @@
4371
4674
  } else {
4372
4675
  $reportSub.textContent = `Last report${sfx} — rendered from the run's output, never composed by the UI.`;
4373
4676
  }
4374
- paintReport(cached.html, cached.interactive);
4677
+ paintReport(cached.html, cached.interactive, cached);
4375
4678
  showSavedPathActions(cached.savedPath); // re-show Open file / Reveal if this run saved one
4376
4679
  } else {
4377
4680
  clearReportFrames();
4378
4681
  $reportShare.hidden = true; // nothing to share — hide, don't disable
4379
4682
  $reportOverlay.hidden = false;
4380
- $reportOverlay.innerHTML = `<div>No report yet. Click <strong>▶ Run workflow</strong> (top right) to run it against the live model, then double-click to view it any time.</div>`;
4683
+ $reportOverlay.innerHTML = `<div id="report-empty-line">No report yet. Click <strong>▶ Run workflow</strong> (top right) to run it against the live model, then double-click to view it any time.</div>`
4684
+ // #2262 slice 3a: after a reload this window holds no report, but the workflow's Page may: offer its latest.
4685
+ + `<button type="button" class="ghost report-latest-page" id="report-latest-page" data-command-id="shell.report-latest-page-open#${escapeHtml(app.id)}" hidden></button>`;
4381
4686
  $reportSub.textContent = 'Double-click loads the last report; ▶ Run workflow generates a fresh one.';
4382
4687
  }
4688
+ paintReportPageLinks();
4689
+ void refreshWorkflowPage(app.id);
4383
4690
  }
4384
4691
 
4385
4692
  // ── Contract editor (tier-1 typed, editable contract) ───────────────────────
@@ -5056,6 +5363,7 @@
5056
5363
  if (!app.runnable) { showToast('Compile the workflow first — Run is gated on a fresh lock.', 'warn'); return; }
5057
5364
  if (reportRunning) return;
5058
5365
  if (await askForMissingRunInputs(app)) return;
5366
+ if (!opts.debug && globalThis.flolessAgentSteps && await globalThis.flolessAgentSteps.confirmBeforeRun(app) === 'cancel') return; // #2241 S4
5059
5367
  if (currentId !== app.id || reportRunning || state.running || foregroundStarting || foregroundStopping || foregroundTrigger) return;
5060
5368
  const request = opts.debug ? null : beginManualRun(app.id);
5061
5369
  reportRunning = true;
@@ -5111,33 +5419,35 @@
5111
5419
  if (res.credentialIssue) { $reportSub.textContent = 'Execution ended. Reconnect the integration to run again.'; surfaceCredentialIssue(res.credentialIssue); return; }
5112
5420
  if (res.report && res.report.kind === 'complete-model-properties' && typeof res.report.handle === 'string') {
5113
5421
  $reportTitle.textContent = `HTML Viewer · ${app.displayName}`;
5114
- lastReportByApp.set(app.id, { nodeId, label: inputBadge, ...res.report });
5115
- await paintCompleteReport(res.report);
5116
- if (!currentCompleteReport || !$reportOverlay.hidden) return;
5117
- markFirstRunDone(app.id);
5118
- $reportModal.dataset.html = '1';
5119
- appendNarration(`Rendered the complete read-only property report from <strong>${escapeHtml(nodeId)}</strong>.`);
5422
+ lastReportByApp.set(app.id, { nodeId, label: inputBadge, ...res.report, runId: typeof res.runId === 'string' ? res.runId : null });
5423
+ // #2539: the run is over once the server answered. Showing its report may still wait for the workflow's Page to
5424
+ // save its copy, so the run controls are released now (not awaited) and the viewer opens the report by itself.
5425
+ const runApp = app.id;
5426
+ void paintCompleteReport(res.report).then((painted) => {
5427
+ if (!painted || !currentCompleteReport || !$reportOverlay.hidden) return;
5428
+ markFirstRunDone(runApp);
5429
+ $reportModal.dataset.html = '1';
5430
+ appendNarration(`Rendered the complete read-only property report from <strong>${escapeHtml(nodeId)}</strong>.`);
5431
+ });
5120
5432
  return;
5121
5433
  }
5122
5434
  const html = res.report && res.report.html;
5123
5435
  const interactive = !!(res.report && res.report.interactive);
5124
- if (!html) {
5125
- $reportSub.textContent = 'Execution ended without an HTML report.';
5126
- $reportOverlay.innerHTML = `<div>Run completed but <code>${escapeHtml(nodeId)}</code> returned no <code>html</code>. Check the Execution tab.</div>`;
5127
- return;
5128
- }
5436
+ if (!html) { showNoReport(res, nodeId, app.id); return; }
5129
5437
  if (interactive) {
5130
5438
  $reportTitle.textContent = `3D Viewer · ${app.displayName}`;
5131
5439
  $reportSub.innerHTML = `Live 3D view from <code>${escapeHtml(nodeId)}</code>${inputBadge ? ' · ' + escapeHtml(inputBadge) : ''} — drag to orbit, scroll to zoom, click an element to inspect.`;
5132
5440
  }
5133
- paintReport(html, interactive);
5441
+ const withFiles = !!(res.report && res.report.withFiles);
5442
+ paintReport(html, interactive, { withFiles, runId: typeof res.runId === 'string' ? res.runId : null });
5134
5443
  if (!interactive) $reportSub.textContent = 'Report created from the latest workflow run.';
5135
5444
  // If a node wrote an output file, the run reports its path — surface the
5136
5445
  // ⧉ Open file / ▤ Reveal buttons and cache it so a later double-click restores them (#209).
5137
5446
  const savedPath = res && typeof res.savedPath === 'string' ? res.savedPath : '';
5138
5447
  showSavedPathActions(savedPath);
5139
5448
  markFirstRunDone(app.id); // a real run rendered → this workflow is no longer "new" (app captured pre-await; a mid-run switch must not mark the wrong workflow)
5140
- lastReportByApp.set(currentId, { nodeId, label: inputBadge, html, interactive, savedPath });
5449
+ lastReportByApp.set(currentId, { nodeId, label: inputBadge, html, interactive, savedPath, withFiles, runId: typeof res.runId === 'string' ? res.runId : null });
5450
+ paintReportPageLinks();
5141
5451
  $reportModal.dataset.html = '1';
5142
5452
  appendNarration(`Rendered the ${interactive ? '3D view' : 'report'} from <strong>${escapeHtml(nodeId)}</strong>${inputBadge ? ' (' + escapeHtml(inputBadge) + ')' : ''} — live run against the model.`);
5143
5453
  } catch (e) {
@@ -5171,6 +5481,7 @@
5171
5481
  if (clientRunToken) { if (liveOutcome === 'no-answer') settleLiveRunWithoutAnswer(); else finishLiveRun(liveOutcome); }
5172
5482
  reportRunning = false;
5173
5483
  syncRunControls(); // run ended — hide the header Stop, restore Run from the gate
5484
+ paintReportPageLinks(); // #2539: hidden while the run was in flight; its Page version may already be known
5174
5485
  }
5175
5486
  }
5176
5487
 
@@ -5252,6 +5563,50 @@
5252
5563
  if (first) first.focus(); else { card.tabIndex = -1; card.focus(); } // #2123: a not-run card may have no button
5253
5564
  }
5254
5565
 
5566
+ // A run that finished without report HTML. #2415: when an AI step in it did not answer (its -ok check stops the run on
5567
+ // purpose), say which step and offer its questions instead of the generic words.
5568
+ function showNoReport(res, nodeId, appId) {
5569
+ const aiStop = globalThis.flolessAgentSteps?.stoppedReportView(res, nodeId);
5570
+ if (aiStop) { showAiStepStopped(aiStop, appId); return; }
5571
+ $reportSub.textContent = 'Execution ended without an HTML report.';
5572
+ $reportOverlay.innerHTML = `<div>Run completed but <code>${escapeHtml(nodeId)}</code> returned no <code>html</code>. Check the Execution tab.</div>`;
5573
+ }
5574
+
5575
+ // #2415: the run stopped before the report because an AI step did not answer. Not a fault, so no Report this problem:
5576
+ // the way on is the step's questions, in the canvas's Last run panel. textContent only — step names come from the run.
5577
+ function showAiStepStopped(view, appId) {
5578
+ clearReportFrames();
5579
+ $reportShare.hidden = true;
5580
+ $reportOverlay.hidden = false;
5581
+ $reportOverlay.replaceChildren();
5582
+ $reportSub.textContent = view.sub;
5583
+ const card = mkEl('div', 'cred-fail-card run-fail-card ai-stop-card');
5584
+ card.setAttribute('role', 'status');
5585
+ const status = mkEl('div', 'cred-fail-status');
5586
+ const icon = mkEl('span', 'cred-fail-icon', typeof floAvatar === 'function' ? '' : '△');
5587
+ icon.setAttribute('aria-hidden', 'true');
5588
+ if (typeof floAvatar === 'function') { icon.classList.add('run-fail-flo'); floAvatar(icon, { size: 28, mood: 'warning' }); }
5589
+ status.append(icon, document.createTextNode(view.status));
5590
+ const actions = mkEl('div', 'cred-fail-actions');
5591
+ const open = mkEl('button', 'cred-open-integrations ai-stop-open', view.button);
5592
+ open.type = 'button';
5593
+ open.dataset.commandId = view.commandId;
5594
+ open.onclick = async () => {
5595
+ // The viewer closes only once Last run shows THIS run; otherwise it stays open, with focus on the button, and says why.
5596
+ let shown = false;
5597
+ try { shown = await globalThis.flolessAgentSteps?.openQuestions(appId, view.runId, () => hideModal($reportModal)) === true; } catch { shown = false; }
5598
+ if (shown) return;
5599
+ showToast(view.listed
5600
+ ? 'FloLess couldn’t show this run’s questions yet. Close the viewer, then open Last run above the canvas.'
5601
+ : 'FloLess couldn’t show this run in Last run yet. Close the viewer, then open Last run above the canvas.', 'warn');
5602
+ open.focus();
5603
+ };
5604
+ actions.append(open);
5605
+ card.append(status, mkEl('div', 'cred-fail-headline', view.headline), mkEl('div', 'cred-fail-body', view.body), actions);
5606
+ $reportOverlay.append(card);
5607
+ open.focus();
5608
+ }
5609
+
5255
5610
  const CRED_BODY_IDLE = 'Sign in again and then run the workflow — it takes about 30 seconds.';
5256
5611
 
5257
5612
  function showCredentialReconnect(cred) {
@@ -6233,6 +6588,7 @@
6233
6588
 
6234
6589
  async function closeReportViewer() {
6235
6590
  hideModal($reportModal);
6591
+ reportSectionRequest += 1; // #2539: a section still waiting for a busy report stops asking once the viewer closes
6236
6592
  const routineId = viewingScheduledReportRoutine;
6237
6593
  viewingScheduledReportRoutine = null;
6238
6594
  if (!routineId) return;
@@ -6266,7 +6622,11 @@
6266
6622
  window.addEventListener('message', (e) => {
6267
6623
  if ($reportFrame3d.hidden || e.source !== $reportFrame3d.contentWindow) return;
6268
6624
  const t = e.data && e.data.type;
6269
- if (t === 'viewer-ready') { $reportOverlay.hidden = true; $reportOverlay.replaceChildren(); }
6625
+ if (t === 'viewer-ready') {
6626
+ $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
6627
+ // #2262 slice 3c: a 3D view is a Page version too; its "Open in Pages" link waits for the view to be ready.
6628
+ paintReportPageLinks();
6629
+ }
6270
6630
  else if (t === 'viewer-error') {
6271
6631
  $reportOverlay.hidden = false; $reportOverlay.replaceChildren();
6272
6632
  $reportOverlay.append(mkEl('div', null, '3D view failed to load — check your connection, then click ▶ Run workflow to try again.'));
@@ -6296,6 +6656,7 @@
6296
6656
  $reportLast.onclick = () => { if (currentCompleteReport) void paintCompleteReport(currentCompleteReport, currentCompleteReport.chunkCount - 1); };
6297
6657
  $reportGoObject.onclick = async () => {
6298
6658
  if (!currentCompleteReport) return;
6659
+ const lookup = ++reportObjectLookup;
6299
6660
  const raw = $reportObjectNumber.value.trim();
6300
6661
  const number = Number(raw);
6301
6662
  if (!/^[1-9][0-9]*$/.test(raw) || !Number.isSafeInteger(number) || number > currentCompleteReport.objectCount) {
@@ -6305,11 +6666,36 @@
6305
6666
  return;
6306
6667
  }
6307
6668
  $reportObjectError.hidden = true;
6669
+ const report = currentCompleteReport;
6670
+ const request = reportSectionRequest;
6671
+ const waitUntil = Date.now() + 5 * 60_000;
6672
+ // Stale once the viewer closed or moved on, or a newer Go took over. The message belongs to the newest lookup, so a
6673
+ // stale one clears only its own text, and only when no newer lookup has written there.
6674
+ const stale = () => lookup !== reportObjectLookup || request !== reportSectionRequest || currentCompleteReport !== report;
6675
+ const leave = () => { if (lookup === reportObjectLookup) $reportObjectError.hidden = true; };
6308
6676
  try {
6309
- const located = await api(`/api/model-reports/${encodeURIComponent(currentCompleteReport.handle)}/object/${number - 1}`);
6310
- await paintCompleteReport(currentCompleteReport, located.chunkOrdinal);
6677
+ let located;
6678
+ for (;;) {
6679
+ try { located = await api(`/api/model-reports/${encodeURIComponent(report.handle)}/object/${number - 1}`); break; }
6680
+ catch (error) {
6681
+ // #2539: a busy report is waited for here too, saying why, and the object opens by itself.
6682
+ if (error?.body?.code !== 'report-busy' || Date.now() >= waitUntil) throw error;
6683
+ if (stale()) { leave(); return; } // a busy answer for a lookup already replaced writes nothing
6684
+ $reportObjectError.textContent = String(error.body.error || 'This report is busy. It opens as soon as that finishes.');
6685
+ $reportObjectError.hidden = false;
6686
+ await new Promise((resolve) => setTimeout(resolve, Math.min(10_000, Math.max(500, Number(error.body.retryAfterMs) || 2_000))));
6687
+ if (stale()) { leave(); return; }
6688
+ }
6689
+ }
6690
+ // The viewer may have closed or moved on while the lookup was answered: then it opens nothing, and drops the wait's text.
6691
+ if (stale()) { leave(); return; }
6692
+ $reportObjectError.hidden = true;
6693
+ await paintCompleteReport(report, located.chunkOrdinal);
6311
6694
  } catch (error) {
6312
- $reportObjectError.textContent = error?.message || 'Could not find that object. Try again.';
6695
+ if (stale()) { leave(); return; }
6696
+ $reportObjectError.textContent = error?.body?.code === 'report-busy'
6697
+ ? 'This report is still busy. Choose Go again to open that object.'
6698
+ : error?.message || 'Could not find that object. Try again.';
6313
6699
  $reportObjectError.hidden = false;
6314
6700
  }
6315
6701
  };
@@ -6319,7 +6705,16 @@
6319
6705
  $reportFrame.addEventListener('load', () => {
6320
6706
  if (!currentCompleteReport || !$reportFrame.getAttribute('src')?.startsWith('/api/model-reports/')) return;
6321
6707
  try {
6322
- if ($reportFrame.contentDocument?.contentType === 'text/html') return;
6708
+ const shown = $reportFrame.contentDocument;
6709
+ if (shown?.contentType === 'text/html') return;
6710
+ // #2539: the report became busy between the section check and the frame's own request. Wait for it like any
6711
+ // busy read instead of calling it changed access.
6712
+ if (shown?.contentType === 'application/json' && JSON.parse(shown.body?.textContent || 'null')?.code === 'report-busy') {
6713
+ // Only for the paint still current (closing the viewer or moving on ends it), and within its first deadline.
6714
+ if ($reportFrame.dataset.request !== String(reportSectionRequest)) return;
6715
+ void paintCompleteReport(currentCompleteReport, currentReportSection, Number($reportFrame.dataset.busyUntil) || null);
6716
+ return;
6717
+ }
6323
6718
  } catch { /* an inaccessible document is not an authenticated report */ }
6324
6719
  clearCompleteReportView();
6325
6720
  $reportFrame.removeAttribute('src');
@@ -6336,7 +6731,10 @@
6336
6731
  link.download = 'complete-model-properties.html';
6337
6732
  document.body.append(link); link.click(); link.remove();
6338
6733
  } catch (error) {
6339
- showToast(error?.message || 'Report access could not be confirmed. Try again.', 'warn');
6734
+ // #2539: busy is not a failure of access; the report is there, it is just being read.
6735
+ showToast(error?.body?.code === 'report-busy'
6736
+ ? 'This report is busy, so it can’t be downloaded yet. Choose Download complete report again in a moment.'
6737
+ : error?.message || 'Report access could not be confirmed. Try again.', 'warn');
6340
6738
  }
6341
6739
  };
6342
6740
 
@@ -6431,14 +6829,99 @@
6431
6829
  };
6432
6830
  $promptSel.onchange = () => { showWorkflowsLanding(false); loadApp($promptSel.value).catch(reportErr); };
6433
6831
 
6434
- $compileBtn.onclick = async () => {
6832
+ /**
6833
+ * #2314: two steps share one name, so AWARE cannot compile the workflow. Ask which to rename; after a rename, compile again (the
6834
+ * workflow changed, so it is approved again, and an AI step's confirmation is asked of the person again). Cancel keeps it as is.
6835
+ */
6836
+ async function renameStepThenCompile(id, ask) {
6837
+ const outcome = globalThis.flolessStepRename ? await globalThis.flolessStepRename.open(ask) : { renamed: false };
6838
+ if (!outcome.renamed) {
6839
+ // Keep the reason in view: the person cancelled the rename, so the workflow still cannot compile, and here is why.
6840
+ showToast(`${ask && ask.sentence ? `${ask.sentence} ` : ''}Nothing was renamed, so the workflow is not compiled yet.`, 'warn');
6841
+ return;
6842
+ }
6843
+ const r = outcome.result || {};
6844
+ if (r.warning) {
6845
+ // The rename did not land exactly as previewed (or could not be checked): the person looks before anything compiles.
6846
+ showToast(r.warning, 'warn');
6847
+ appendNarration(`Renamed the step <strong>${escapeHtml(r.renamed?.from || '')}</strong> to <strong>${escapeHtml(r.renamed?.to || '')}</strong>. ${escapeHtml(r.warning)}`);
6848
+ if (currentId === id) { try { await loadApp(id); } catch (e) { reportErr(e); } }
6849
+ return;
6850
+ }
6851
+ appendNarration(`Renamed the step <strong>${escapeHtml(r.renamed?.from || '')}</strong> to <strong>${escapeHtml(r.renamed?.to || '')}</strong>. The workflow changed, so it is compiled and approved again.`);
6852
+ if (currentId !== id) return;
6853
+ try { await loadApp(id); } catch (e) { reportErr(e); return; }
6854
+ if (currentId === id) await compileCurrentWorkflow();
6855
+ }
6856
+
6857
+ /**
6858
+ * #2474: a workflow you own runs from an immutable published copy, so its Compile publishes a new version from the
6859
+ * workflow's own file, exactly as the draft view does (`/api/compile` on the copy is refused). Consent works as it does
6860
+ * there: building is allowed, and the new version's AI step is confirmed by the person before it runs (Run asks). The
6861
+ * confirmation dialog is not shown first, because it could only show the old copy, not the bytes being published.
6862
+ */
6863
+ async function publishOwnedFromHeader(id, workflowId) {
6864
+ const name = workflowLabelOf(id);
6865
+ $compileBtn.disabled = true;
6866
+ const prev = $compileBtn.textContent;
6867
+ $compileBtn.textContent = '⎙ Compiling…';
6868
+ const restore = () => { $compileBtn.textContent = prev; $compileBtn.disabled = false; };
6869
+ let newId;
6870
+ try {
6871
+ const res = await api(`/api/workflows/owned/${encodeURIComponent(workflowId)}/publish`, { method: 'POST' });
6872
+ newId = res?.workflow?.activePublication?.runtimeAppId || null;
6873
+ } catch (e) {
6874
+ restore();
6875
+ const ask = globalThis.flolessStepRename ? globalThis.flolessStepRename.askOf(e) : null;
6876
+ if (ask) { await renameStepThenCompile(id, ask); return; }
6877
+ // The publish route's own refusal is a sentence for the person; anything else is reported as usual.
6878
+ if (e?.body?.code === 'workflow-compile-failed' && typeof e.body.error === 'string') { showToast(e.body.error, 'warn'); return; }
6879
+ reportErr(e);
6880
+ return;
6881
+ }
6882
+ const notOpened = `${name} is compiled. FloLess couldn’t open the new version — open it from the Workflows page.`;
6883
+ // Only the publish answer names the new version: never fall back to the old copy, which would show the old steps as current.
6884
+ if (!newId) { restore(); showToast(notOpened, 'warn'); return; }
6885
+ // Refresh the lists without letting the refresh pick a workflow to open; the new version is opened next, on purpose.
6886
+ const owner = ownedWorkflowOf(id);
6887
+ try { await loadApps({ preserveSelection: true }); } catch (e) { console.warn('[compile] the workflow list could not be refreshed', e); }
6888
+ // The new version belongs to the same workflow. Even when the refresh failed, it is known as owned, so its next Compile
6889
+ // publishes again instead of reaching the refused copy.
6890
+ if (owner && !ownedWorkflowOf(newId)) workflowOwners.set(newId, owner);
6891
+ // The person opened something else meanwhile: its own load repainted the button, so it is left as that workflow shows it.
6892
+ if (currentId !== id) { showToast(`${name} is compiled.`, 'ok'); return; }
6893
+ try { await loadApp(newId); } catch (e) { console.warn('[compile] the new version could not be opened', e); restore(); showToast(notOpened, 'warn'); return; }
6894
+ if (currentId !== newId) { showToast(`${name} is compiled.`, 'ok'); return; } // a newer choice won while it was opening
6895
+ const app = apps.get(newId);
6896
+ const consent = globalThis.flolessAgentSteps?.consentStatus ? await globalThis.flolessAgentSteps.consentStatus(newId) : null;
6897
+ const unconfirmed = consent && (consent.state === 'needed' || consent.state === 'changed');
6898
+ if (unconfirmed) {
6899
+ appendNarration('Workflow compiled. It has an AI step whose answer may differ each run, and this version is not confirmed yet: FloLess asks you to confirm it before it runs.');
6900
+ showToast('Workflow compiled. Confirm its AI step before it runs.', 'ok');
6901
+ } else {
6902
+ appendNarration(app?.runnable
6903
+ ? 'Workflow compiled. Review any notices above the canvas before running.'
6904
+ : `Compiled, but ${app?.notes?.length ?? 0} notice(s) remain — review them above the canvas.`);
6905
+ showToast('Workflow compiled', 'ok');
6906
+ }
6907
+ maybeAskPolicyAfterApproval();
6908
+ }
6909
+
6910
+ async function compileCurrentWorkflow() {
6435
6911
  if (!currentId || $compileBtn.disabled || $compileBtn.hidden) return; // hidden = suppressed for a maintained drift
6436
6912
  const id = currentId;
6913
+ const ownedId = ownedWorkflowOf(id)?.ownedWorkflow?.workflowId || null;
6914
+ if (ownedId) { await publishOwnedFromHeader(id, ownedId); return; }
6915
+ // #2241 S4: a workflow with an AI step nobody has confirmed (or that changed) is approved from the confirmation dialog, which
6916
+ // records the tick and approves the exact bytes it showed. 'proceed' = nothing to ask, the normal compile goes on.
6917
+ const consent = globalThis.flolessAgentSteps ? await globalThis.flolessAgentSteps.confirmBeforeApprove(apps.get(id) || { id }) : 'proceed';
6918
+ if (consent === 'rename-step') { await renameStepThenCompile(id, globalThis.flolessAgentSteps.takeRenameAsk()); return; }
6919
+ if (consent === 'cancel' || currentId !== id) return;
6437
6920
  $compileBtn.disabled = true;
6438
6921
  const prev = $compileBtn.textContent;
6439
6922
  $compileBtn.textContent = '⎙ Compiling…';
6440
6923
  try {
6441
- await api('/api/compile', { method: 'POST', body: JSON.stringify({ id }) });
6924
+ if (consent !== 'approved') await api('/api/compile', { method: 'POST', body: JSON.stringify({ id }) });
6442
6925
  await loadApp(id);
6443
6926
  const app = apps.get(id);
6444
6927
  appendNarration(app.runnable
@@ -6450,9 +6933,12 @@
6450
6933
  } catch (e) {
6451
6934
  $compileBtn.textContent = prev;
6452
6935
  $compileBtn.disabled = false;
6936
+ const ask = globalThis.flolessStepRename ? globalThis.flolessStepRename.askOf(e) : null;
6937
+ if (ask) { await renameStepThenCompile(id, ask); return; }
6453
6938
  reportErr(e);
6454
6939
  }
6455
- };
6940
+ }
6941
+ $compileBtn.onclick = () => compileCurrentWorkflow();
6456
6942
 
6457
6943
  // ── Bake into agent ──────────────────────────────────────────────────────────
6458
6944
  // Open a preview/confirm modal (agent name + the inputs it will expose, mirrored
@@ -7033,14 +7519,8 @@
7033
7519
 
7034
7520
  function graftTeklaReadErrorMessage(error) {
7035
7521
  const body = error?.body;
7036
- if (error?.status === 402 || body?.error === 'subscription required') {
7037
- if (body?.state === 'expired') return 'Your FloLess subscription has expired. Renew your FloLess subscription, then try again.';
7038
- if (body?.reason === 'no-subscription') return 'This account does not have a FloLess subscription. Sign in with a subscribed account or subscribe, then try again.';
7039
- if (body?.reason === 'session-expired') return 'Your FloLess sign-in has expired. Sign in again, then try again.';
7040
- if (body?.reason === 'signed-out') return 'You are signed out of FloLess. Sign in again, then try again.';
7041
- if (body?.reason === 'seat-taken') return 'Your FloLess session has ended. Sign in again, then try again.';
7042
- return 'Sign in to FloLess to check your account access, then try again.';
7043
- }
7522
+ const access = accountAccessText(error);
7523
+ if (access) return access;
7044
7524
  if (body?.bootstrap === 'failed') {
7045
7525
  return 'FloLess could not prepare its runtime. Choose Try again on the setup card, then verify the model read again.';
7046
7526
  }
@@ -7633,7 +8113,10 @@
7633
8113
  }
7634
8114
  showToast(body && body.code === 'exists'
7635
8115
  ? 'A workflow with that name already exists. Choose a different name, then try again.'
7636
- : 'We couldn’t import that workflow because FloLess could not read it. Check the file, then try again.', 'err');
8116
+ // #2470: the server's sentence names the General project id and a name to use instead.
8117
+ : body && body.code === 'reserved-id' && typeof body.error === 'string' && body.error
8118
+ ? `${body.error} Change the app: line in the file, then import it again.`
8119
+ : 'We couldn’t import that workflow because FloLess could not read it. Check the file, then try again.', 'err');
7637
8120
  }
7638
8121
  } finally {
7639
8122
  _importing = false; // every path, including an unreadable file and the dialog's early return
@@ -7894,6 +8377,7 @@
7894
8377
  const $body = $notesPopover.querySelector('.relnotes-body');
7895
8378
  let notes = null;
7896
8379
  try {
8380
+ await globalThis.flolessStartupAdmission?.admit('/api/release-notes');
7897
8381
  const r = await fetch('/api/release-notes?component=' + encodeURIComponent(component) + '&version=' + encodeURIComponent(version));
7898
8382
  notes = await r.json();
7899
8383
  } catch { notes = null; }
@@ -7999,6 +8483,7 @@
7999
8483
  resetNotesAffordance(el);
8000
8484
  let notes = null;
8001
8485
  try {
8486
+ await globalThis.flolessStartupAdmission?.admit('/api/release-notes');
8002
8487
  const r = await fetch('/api/release-notes?component=' + encodeURIComponent(component) + '&version=' + encodeURIComponent(version));
8003
8488
  notes = await r.json();
8004
8489
  } catch { notes = null; }
@@ -8106,6 +8591,7 @@
8106
8591
  async function refreshUpdate() {
8107
8592
  if (!$appUpdate) return;
8108
8593
  try {
8594
+ await globalThis.flolessStartupAdmission?.admit('/api/update');
8109
8595
  const r = await fetch('/api/update');
8110
8596
  const d = await r.json();
8111
8597
  if (r.ok && d.supported && d.updateAvailable && d.targetVersion) {
@@ -8170,6 +8656,7 @@
8170
8656
  }
8171
8657
  async function refreshWorkflowUpdates() {
8172
8658
  try {
8659
+ await globalThis.flolessStartupAdmission?.admit('/api/workflows/updates');
8173
8660
  const r = await fetch('/api/workflows/updates');
8174
8661
  const d = await r.json();
8175
8662
  _wfUpdates = (r.ok && d.ok && Array.isArray(d.updates)) ? d.updates : [];
@@ -8396,6 +8883,7 @@
8396
8883
  if (!$awareUpdate) return;
8397
8884
  if (awareJobOwnsPill()) return;
8398
8885
  try {
8886
+ await globalThis.flolessStartupAdmission?.admit('/api/aware/update');
8399
8887
  const r = await fetch('/api/aware/update');
8400
8888
  const d = await r.json();
8401
8889
  if (awareJobOwnsPill()) return; // the job resolved while this request was in flight
@@ -9102,6 +9590,7 @@
9102
9590
  (async () => {
9103
9591
  let notes = null;
9104
9592
  try {
9593
+ await globalThis.flolessStartupAdmission?.admit('/api/release-notes');
9105
9594
  const r = await fetch('/api/release-notes?component=app&version=' + encodeURIComponent(pending));
9106
9595
  notes = await r.json();
9107
9596
  } catch { notes = null; }
@@ -9128,6 +9617,7 @@
9128
9617
  if (!app.runnable) { showToast($runBtn.dataset.tip, 'warn'); return; }
9129
9618
  if (state.running || reportRunning || foregroundStarting || foregroundStopping || foregroundTrigger) return;
9130
9619
  if (!simulate && await askForMissingRunInputs(app)) return;
9620
+ if (!simulate && !reportNodeId() && globalThis.flolessAgentSteps && await globalThis.flolessAgentSteps.confirmBeforeRun(app) === 'cancel') return; // #2241 S4 (a report run asks inside runReport; a live trigger session asks here, before it starts)
9131
9621
  if (currentId !== app.id || state.running || reportRunning || foregroundStarting || foregroundStopping || foregroundTrigger) return;
9132
9622
 
9133
9623
  // Streaming/watch app → a LIVE FOREGROUND session, not a finite run (which would
@@ -9289,16 +9779,36 @@
9289
9779
  const cmd = ev.command ? '/' + escapeHtml(ev.command) : '';
9290
9780
  let lvl = 'info';
9291
9781
  let msg;
9782
+ // #2241 S5: a confirmation step starting means a change may soon be waiting for the person. (The last-run panel is refreshed when a run
9783
+ // ends, never cleared here: the trace is replayed after a run, and a clear would discard the refresh already in flight.)
9784
+ globalThis.flolessAgentSteps?.noteTrace(ev);
9785
+ if (ev.kind === 'run-start') traceRunId = typeof ev.run_id === 'string' ? ev.run_id : null;
9786
+ let usePill = null;
9292
9787
  switch (ev.kind) {
9293
9788
  case 'run-start': msg = `run start · ${escapeHtml(ev.app || '')} (${escapeHtml(ev.instance || 'default')})${runStartApprovalNote(ev)}`; break;
9294
9789
  case 'node-start': lvl = 'event'; msg = `node ${node} · ${agent}${cmd}`; break;
9295
9790
  case 'would-write': lvl = 'warn'; msg = `would-write ${node} · ${escapeHtml(JSON.stringify(ev.proposed_inputs || {}))}`; break;
9296
- case 'node-output': case 'output': case 'write': lvl = 'ok'; msg = `${escapeHtml(ev.kind)} ${node}`.trim(); break;
9791
+ case 'node-output': case 'output': case 'write': lvl = 'ok'; msg = `${escapeHtml(ev.kind)} ${node}`.trim();
9792
+ // #2241 S5: AWARE marks an Agent step's output; the trace says so wherever it shows the output.
9793
+ if (ev.nondeterministic === true && globalThis.flolessAgentSteps) msg += ` ${globalThis.flolessAgentSteps.aiPillHtml()}`;
9794
+ // #2374: an output FloLess found built on (or decided by) an Agent step's answer is labelled too, in quieter words.
9795
+ else if (ev.node) usePill = { node: ev.node, runId: typeof ev.run_id === 'string' ? ev.run_id : traceRunId };
9796
+ break;
9297
9797
  case 'run-end': lvl = ev.status === 'ok' ? 'ok' : 'err'; msg = `run ${escapeHtml(ev.status || 'ended')}`; break;
9298
9798
  default: msg = `${escapeHtml(ev.kind)} ${node}`.trim();
9299
9799
  }
9300
9800
  // `node` (the raw node id) feeds the Execution tab's node-filter chips.
9301
- liveTrace.push({ kind: ev.kind, ts: fmtTs(ev.ts), lvl, msg, node: ev.node || '' });
9801
+ const row = { kind: ev.kind, ts: fmtTs(ev.ts), lvl, msg, node: ev.node || '' };
9802
+ // #2374: the label is looked up when the row is drawn, so it appears once that run's record has arrived (and only from it).
9803
+ if (usePill) {
9804
+ let text = msg;
9805
+ Object.defineProperty(row, 'msg', {
9806
+ enumerable: true,
9807
+ get() { const pill = globalThis.flolessAgentSteps?.usePillHtml?.(usePill.node, usePill.runId) || ''; return pill ? `${text} ${pill}` : text; },
9808
+ set(value) { text = value; },
9809
+ });
9810
+ }
9811
+ liveTrace.push(row);
9302
9812
 
9303
9813
  // Paint the node's status on the canvas as the trace streams in. Once the
9304
9814
  // user hits Stop, leave the canvas alone — late SSE events (the fs-watcher
@@ -9415,7 +9925,10 @@
9415
9925
  switch (reason) {
9416
9926
  case 'no-node':
9417
9927
  case 'no-npm':
9418
- return 'AWARE requires Node.js, which was not found on this machine. Install Node.js (nodejs.org), then try again.';
9928
+ // The fallback copy, before the install plan has loaded. The Node.js card (nodeInstallView)
9929
+ // replaces it on Windows. No "try again" here: where the server cannot re-read PATH, only a
9930
+ // relaunch finds a Node.js installed after FloLess started (#2381).
9931
+ return "AWARE runs on Node.js, which isn't installed on this computer. Install it from nodejs.org, then close FloLess and open it again.";
9419
9932
  case 'eacces':
9420
9933
  return "Couldn't install because this location requires administrator permissions. Run FloLess as administrator, or install Node.js globally yourself and try again.";
9421
9934
  case 'toolchain-unverified':
@@ -9423,6 +9936,9 @@
9423
9936
  // idea whether Node.js is missing. Telling someone to install what they already
9424
9937
  // have is the exact bug this reason exists to prevent.
9425
9938
  return "Couldn't check whether Node.js is installed — the check didn't finish, which usually means the machine was busy. Nothing is necessarily missing; try again.";
9939
+ case 'aware-version-unreadable':
9940
+ // The version check did not answer (usually a busy machine); AWARE is not necessarily old.
9941
+ return "Couldn't check the installed AWARE just now — it didn't answer, which usually means the machine was busy. Nothing is necessarily wrong; try again.";
9426
9942
  case 'aware-version-required':
9427
9943
  return 'This FloLess release needs AWARE 0.157.0 or newer. Update AWARE, then try again.';
9428
9944
  case 'offline':
@@ -9451,22 +9967,265 @@
9451
9967
  wrap.id = 'aware-bootstrap-overlay';
9452
9968
  // role=status announces the card text on insertion; spinner + log are
9453
9969
  // decorative/noisy (aria-hidden); bs-status is the polite live channel.
9970
+ // A dialog rather than role=status: the failed and Node.js views carry buttons, a link and a
9971
+ // command to read before agreeing, and a dialog announces its title and body on focus.
9454
9972
  wrap.innerHTML =
9455
- `<div class="bs-card" role="status" tabindex="-1">
9973
+ `<div class="bs-card" role="dialog" aria-modal="true" aria-labelledby="bs-title" aria-describedby="bs-body" tabindex="-1">
9456
9974
  <div class="bs-spinner" aria-hidden="true"></div>
9457
- <h1></h1>
9458
- <p class="bs-body"></p>
9975
+ <h1 id="bs-title"></h1>
9976
+ <p class="bs-body" id="bs-body"></p>
9977
+ <div class="bs-cmd-wrap" hidden>
9978
+ <pre class="bs-cmd"></pre>
9979
+ <button type="button" class="bs-copy" data-command-id="shell.setup-node-install-copy" data-tip="Copy command" aria-label="Copy command">Copy</button>
9980
+ </div>
9981
+ <p class="bs-note"></p>
9459
9982
  <p class="bs-status" id="bs-status" aria-live="polite"></p>
9460
9983
  <p class="bs-log" aria-hidden="true"></p>
9461
9984
  <p class="bs-remediation"></p>
9462
- <button type="button" class="secondary" hidden>Try again</button>
9985
+ <button type="button" class="bs-primary bs-offer" data-command-id="shell.setup-node-install" hidden></button>
9986
+ <div class="bs-actions">
9987
+ <button type="button" class="secondary bs-cancel" data-command-id="shell.setup-node-install-cancel" hidden>Cancel</button>
9988
+ <button type="button" class="bs-primary bs-confirm" data-command-id="shell.setup-node-install-confirm" hidden>Install</button>
9989
+ <a class="bs-link" data-command-id="shell.setup-node-download" target="_blank" rel="noopener noreferrer" hidden>Download from nodejs.org ↗</a>
9990
+ <button type="button" class="secondary bs-retry" data-command-id="shell.setup-retry" hidden>Try again</button>
9991
+ </div>
9992
+ <p class="bs-hint"></p>
9463
9993
  </div>`;
9464
9994
  document.body.appendChild(wrap);
9465
9995
  bootstrapOverlayEl = wrap;
9466
- wrap.querySelector('.secondary').addEventListener('click', onBootstrapRetry);
9996
+ wrap.querySelector('.bs-retry').addEventListener('click', onBootstrapRetry);
9997
+ wrap.querySelector('.bs-offer').addEventListener('click', onNodeInstallOffer);
9998
+ wrap.querySelector('.bs-confirm').addEventListener('click', onNodeInstallConfirm);
9999
+ wrap.querySelector('.bs-cancel').addEventListener('click', onNodeInstallCancel);
10000
+ wrap.querySelector('.bs-copy').addEventListener('click', onNodeInstallCopy);
10001
+ // Esc on the consent step is Cancel; it does nothing anywhere else on this card.
10002
+ wrap.addEventListener('keydown', (e) => {
10003
+ if (e.key === 'Escape' && nodeInstall.step === 'confirm') { e.preventDefault(); onNodeInstallCancel(); }
10004
+ });
9467
10005
  wrap.querySelector('.bs-card').focus();
9468
10006
  }
9469
10007
 
10008
+ // ── "Install Node.js for me" (#2381) ──────────────────────────────────────
10009
+ // For no-node/no-npm the card offers to install Node.js. The SERVER owns the install (winget, or the
10010
+ // nodejs.org MSI checked against its published checksum), streams it as `node-install` SSE events, and
10011
+ // when it ends re-checks and carries on into the AWARE install by itself; this only shows the plan, asks
10012
+ // for consent with the exact command on screen, and follows the job.
10013
+ const NODE_REASONS = new Set(['no-node', 'no-npm']);
10014
+ // How long to show "Checking for Node.js…" after a successful install before concluding the server's
10015
+ // re-check is not coming (its continuation failed), and telling the person to relaunch instead.
10016
+ const NODE_RECHECK_GRACE_MS = 60_000;
10017
+ const nodeInstall = {
10018
+ plan: null, // {supported, method, command, downloadPage} from GET /api/bootstrap/node-install
10019
+ job: null, // {id, rev, status, method, error, recheckError, lastLine, finishedAt}
10020
+ step: 'offer', // 'offer' | 'confirm' — the card's own step; the job is the server's
10021
+ planLoading: false,
10022
+ planFailedAt: 0, // when the plan last failed to load — retried from the next 5 s health tick, not at once
10023
+ startInFlight: false,
10024
+ recheckSeen: false, // the bootstrap left `failed` after the install succeeded
10025
+ };
10026
+
10027
+ // Take a job snapshot only if it is not older than the one we have. SSE events, the POST reply and the
10028
+ // 5 s re-read can arrive in any order; a late "running" must never undo a "failed" or "succeeded".
10029
+ function adoptNodeJob(next) {
10030
+ if (!next || typeof next !== 'object') return false;
10031
+ const cur = nodeInstall.job;
10032
+ // Ids restart with the server; a different epoch is a new server, whose snapshot always wins.
10033
+ if (cur && cur.epoch === next.epoch && typeof cur.id === 'number' && typeof next.id === 'number') {
10034
+ if (next.id < cur.id || (next.id === cur.id && (next.rev ?? 0) < (cur.rev ?? 0))) return false;
10035
+ }
10036
+ nodeInstall.job = { ...(cur && cur.epoch === next.epoch && cur.id === next.id ? cur : {}), ...next };
10037
+ return true;
10038
+ }
10039
+
10040
+ function loadNodeInstallPlan() {
10041
+ if (nodeInstall.plan || nodeInstall.planLoading || Date.now() - nodeInstall.planFailedAt < 4000) return;
10042
+ nodeInstall.planLoading = true;
10043
+ api('/api/bootstrap/node-install')
10044
+ .then((r) => {
10045
+ nodeInstall.plan = r.plan || null;
10046
+ adoptNodeJob(r.job);
10047
+ if (!nodeInstall.plan) nodeInstall.planFailedAt = Date.now();
10048
+ })
10049
+ .catch((err) => { nodeInstall.planFailedAt = Date.now(); console.warn('node install plan unavailable', err); })
10050
+ .finally(() => { nodeInstall.planLoading = false; rerenderBootstrap(); });
10051
+ }
10052
+
10053
+ let nodeJobRefreshedAt = 0;
10054
+ function refreshNodeInstallJob() {
10055
+ if (Date.now() - nodeJobRefreshedAt < 4000) return;
10056
+ nodeJobRefreshedAt = Date.now();
10057
+ api('/api/bootstrap/node-install')
10058
+ .then((r) => {
10059
+ const before = nodeInstall.job && `${nodeInstall.job.id}/${nodeInstall.job.rev}/${nodeInstall.job.status}`;
10060
+ if (adoptNodeJob(r.job) && `${nodeInstall.job.id}/${nodeInstall.job.rev}/${nodeInstall.job.status}` !== before) rerenderBootstrap();
10061
+ })
10062
+ .catch((err) => { console.warn('node install status unavailable', err); });
10063
+ }
10064
+
10065
+ function rerenderBootstrap() {
10066
+ if (bootstrapState && bootstrapState.status !== 'ready') updateBootstrap({ ...bootstrapState });
10067
+ }
10068
+
10069
+ // Which Node.js view the failed card shows. Null = not a Node.js failure.
10070
+ function nodeInstallView(reason) {
10071
+ if (!NODE_REASONS.has(reason)) return null;
10072
+ const job = nodeInstall.job;
10073
+ if (job && job.status === 'running') return 'node-running';
10074
+ if (job && job.status === 'succeeded') {
10075
+ if (job.recheckError) return 'node-recheck-failed';
10076
+ const since = Date.parse(job.finishedAt || '') || 0;
10077
+ return !nodeInstall.recheckSeen && Date.now() - since < NODE_RECHECK_GRACE_MS ? 'node-checking' : 'node-relaunch';
10078
+ }
10079
+ if (!nodeInstall.plan) return 'node-unknown';
10080
+ if (!nodeInstall.plan.supported) return 'node-manual';
10081
+ if (nodeInstall.step === 'confirm') return 'node-confirm';
10082
+ return job && job.status === 'failed' ? 'node-failed' : 'node-offer';
10083
+ }
10084
+
10085
+ // Paint one Node.js view onto the card's elements. Everything not named here stays hidden. Every view
10086
+ // keeps a way forward — the nodejs.org link at the least — because nothing here refuses, it asks.
10087
+ function paintNodeInstallView(view, els) {
10088
+ const { h1, body, cmdWrap, cmd, note, hint, remediation, offer, confirm, cancel, link, retry } = els;
10089
+ const plan = nodeInstall.plan;
10090
+ const job = nodeInstall.job;
10091
+ link.href = (plan && plan.downloadPage) || 'https://nodejs.org/en/download';
10092
+ if (view === 'node-running' || view === 'node-checking') {
10093
+ h1.textContent = view === 'node-running' ? 'Installing Node.js…' : 'Checking for Node.js…';
10094
+ body.textContent = view === 'node-running'
10095
+ ? "This takes a minute or two. If Windows asks for permission and you don't see it, look for a flashing icon in the taskbar."
10096
+ : 'Node.js is installed. FloLess is checking for it, then it will set up AWARE.';
10097
+ // Stalled or not, the manual route stays on screen; there is no Cancel, because a running
10098
+ // installer cannot be stopped cleanly.
10099
+ hint.textContent = view === 'node-running' ? 'Prefer to install it yourself?' : '';
10100
+ link.hidden = view !== 'node-running';
10101
+ return { spinner: true };
10102
+ }
10103
+ if (view === 'node-confirm') {
10104
+ h1.textContent = 'Install Node.js?';
10105
+ body.textContent = 'FloLess will run this command:';
10106
+ // One unbreakable span per argument: Chrome would otherwise break after the hyphen of a flag
10107
+ // ("--" / "source"), and a command split mid-flag reads as a different command.
10108
+ cmd.replaceChildren(...String(plan.command).split(' ').flatMap((tok, i) => {
10109
+ const span = document.createElement('span');
10110
+ span.className = 'bs-tok';
10111
+ span.textContent = tok;
10112
+ return i ? [' ', span] : [span];
10113
+ }));
10114
+ cmdWrap.hidden = false;
10115
+ note.textContent = plan.method === 'winget'
10116
+ ? 'Windows will ask for permission to make changes. Running it accepts the winget source and Node.js package licence terms.'
10117
+ : "winget isn't available, so FloLess downloads the official Node.js LTS installer from nodejs.org, checks it against nodejs.org's published checksum, then runs it. Windows will ask for permission to make changes.";
10118
+ cancel.hidden = false;
10119
+ confirm.hidden = false;
10120
+ confirm.disabled = nodeInstall.startInFlight;
10121
+ confirm.textContent = nodeInstall.startInFlight ? 'Starting…' : 'Install';
10122
+ return { spinner: false };
10123
+ }
10124
+ if (view === 'node-recheck-failed') {
10125
+ h1.textContent = 'Node.js is installed';
10126
+ body.textContent = "FloLess couldn't carry on setting up AWARE by itself. Choose Try again to continue.";
10127
+ if (job.recheckError) remediation.textContent = job.recheckError;
10128
+ retry.hidden = false;
10129
+ return { spinner: false };
10130
+ }
10131
+ if (view === 'node-relaunch') {
10132
+ h1.textContent = 'Almost there';
10133
+ body.textContent = "Node.js is installed, but FloLess can't see it yet. Close FloLess and open it again to finish setup.";
10134
+ retry.hidden = false;
10135
+ return { spinner: false };
10136
+ }
10137
+ if (view === 'node-manual' || view === 'node-unknown') {
10138
+ h1.textContent = 'Node.js is needed';
10139
+ // Off Windows (node-manual) a running process cannot see a new PATH, so only a relaunch helps and the
10140
+ // copy must not promise Try again. While the plan has not loaded (node-unknown) we cannot tell which
10141
+ // applies, so the copy covers both.
10142
+ body.textContent = view === 'node-manual'
10143
+ ? "AWARE runs on Node.js, which isn't installed on this computer. Install it from nodejs.org, then close FloLess and open it again."
10144
+ : "AWARE runs on Node.js, which isn't installed on this computer. Install it from nodejs.org, then choose Try again. If FloLess still can't find it, close FloLess and open it again.";
10145
+ link.hidden = false;
10146
+ retry.hidden = false;
10147
+ return { spinner: false };
10148
+ }
10149
+ // node-offer / node-failed
10150
+ if (view === 'node-failed') {
10151
+ h1.textContent = "Node.js didn't install";
10152
+ body.textContent = (job && job.error) || 'The install stopped before Node.js was installed.';
10153
+ offer.textContent = 'Try the install again';
10154
+ if (job && job.lastLine && job.lastLine !== job.error) remediation.textContent = job.lastLine;
10155
+ } else {
10156
+ h1.textContent = 'Node.js is needed';
10157
+ body.textContent = "AWARE runs on Node.js, which isn't installed on this computer. FloLess can install it for you, or you can install it yourself.";
10158
+ offer.textContent = 'Install Node.js for me';
10159
+ hint.textContent = 'Installed it yourself? Choose Try again.';
10160
+ }
10161
+ offer.hidden = false;
10162
+ link.hidden = false;
10163
+ retry.hidden = false;
10164
+ return { spinner: false };
10165
+ }
10166
+
10167
+ function onNodeInstallOffer() {
10168
+ nodeInstall.step = 'confirm';
10169
+ rerenderBootstrap();
10170
+ }
10171
+
10172
+ function onNodeInstallCancel() {
10173
+ nodeInstall.step = 'offer';
10174
+ rerenderBootstrap();
10175
+ bootstrapOverlayEl?.querySelector('.bs-offer')?.focus();
10176
+ }
10177
+
10178
+ async function onNodeInstallCopy() {
10179
+ const statusEl = bootstrapOverlayEl?.querySelector('.bs-status');
10180
+ const copied = await copyToClipboard(nodeInstall.plan?.command || '');
10181
+ if (statusEl) statusEl.textContent = copied ? 'Copied.' : "Couldn't copy — select the command and copy it instead.";
10182
+ setTimeout(() => { if (statusEl && /^Cop|^Couldn't copy/.test(statusEl.textContent)) statusEl.textContent = ''; }, 2000);
10183
+ }
10184
+
10185
+ async function onNodeInstallConfirm() {
10186
+ if (nodeInstall.startInFlight) return; // guard double-clicks even before disabled paints
10187
+ nodeInstall.startInFlight = true;
10188
+ rerenderBootstrap();
10189
+ let statusText = '';
10190
+ try {
10191
+ // The method the person just read. If the server would now run a different one, it starts nothing
10192
+ // and sends the new plan back, and the card asks again with the new command on screen.
10193
+ const r = await api('/api/bootstrap/node-install', { method: 'POST', body: JSON.stringify({ method: nodeInstall.plan?.method ?? null }) });
10194
+ // Keep the plan the card showed unless the reply carries a complete one to replace it.
10195
+ if (r.plan && r.plan.command) nodeInstall.plan = r.plan;
10196
+ if (r.planChanged) {
10197
+ statusText = 'FloLess would now install Node.js a different way. Check the command and choose Install again.';
10198
+ } else {
10199
+ adoptNodeJob(r.job);
10200
+ nodeInstall.recheckSeen = false;
10201
+ nodeInstall.step = 'offer';
10202
+ }
10203
+ } catch (err) {
10204
+ console.warn('node install did not start', err);
10205
+ // The server answered (err.status) with its own reason, or it did not answer at all.
10206
+ statusText = err && err.status
10207
+ ? `Couldn't start the install: ${err.message}`
10208
+ : "Couldn't start the install — FloLess's server didn't answer. Try again in a moment.";
10209
+ } finally {
10210
+ nodeInstall.startInFlight = false;
10211
+ rerenderBootstrap();
10212
+ const statusEl = bootstrapOverlayEl?.querySelector('.bs-status');
10213
+ if (statusEl && statusText) statusEl.textContent = statusText;
10214
+ }
10215
+ }
10216
+
10217
+ // A `node-install` SSE event: follow the server's job. A progress line carries the job's id and rev,
10218
+ // so an older one cannot drag a finished job back to "running".
10219
+ function onNodeInstallEvent(m) {
10220
+ const { type: _t, line, ...rest } = m;
10221
+ const isLine = line != null;
10222
+ const next = isLine ? { epoch: rest.epoch, id: rest.id, rev: rest.rev, status: rest.status, method: rest.method, lastLine: line } : rest;
10223
+ if (!adoptNodeJob(next)) return;
10224
+ if (rest.status === 'succeeded') nodeInstall.recheckSeen = false;
10225
+ if (isLine) setBootstrapLogLine(line);
10226
+ rerenderBootstrap();
10227
+ }
10228
+
9470
10229
  // The live npm ticker: REPLACE (never append) the single line; aria-hidden so
9471
10230
  // the rapid output is not announced. Only meaningful while installing.
9472
10231
  function setBootstrapLogLine(line) {
@@ -9484,56 +10243,101 @@
9484
10243
  showBootstrapOverlay();
9485
10244
  if (!bootstrapOverlayEl) return;
9486
10245
  const prev = bootstrapState;
9487
- bootstrapState = { status, reason: s.reason ?? null, remediation: s.remediation ?? null };
10246
+ // The re-check after a Node.js install has begun once setup leaves `failed`.
10247
+ if (status !== 'failed' && nodeInstall.job && nodeInstall.job.status === 'succeeded') nodeInstall.recheckSeen = true;
10248
+ const nodeView = status === 'failed' ? nodeInstallView(s.reason) : null;
10249
+ const view = nodeView || status;
10250
+ bootstrapState = { status, reason: s.reason ?? null, remediation: s.remediation ?? null, view };
9488
10251
  const card = bootstrapOverlayEl.querySelector('.bs-card');
9489
- const spinner = bootstrapOverlayEl.querySelector('.bs-spinner');
9490
10252
  const h1 = bootstrapOverlayEl.querySelector('h1');
9491
- const body = bootstrapOverlayEl.querySelector('.bs-body');
9492
- const statusEl = bootstrapOverlayEl.querySelector('.bs-status');
10253
+ const els = {
10254
+ h1,
10255
+ body: bootstrapOverlayEl.querySelector('.bs-body'),
10256
+ cmdWrap: bootstrapOverlayEl.querySelector('.bs-cmd-wrap'),
10257
+ cmd: bootstrapOverlayEl.querySelector('.bs-cmd'),
10258
+ note: bootstrapOverlayEl.querySelector('.bs-note'),
10259
+ hint: bootstrapOverlayEl.querySelector('.bs-hint'),
10260
+ statusEl: bootstrapOverlayEl.querySelector('.bs-status'),
10261
+ remediation: bootstrapOverlayEl.querySelector('.bs-remediation'),
10262
+ offer: bootstrapOverlayEl.querySelector('.bs-offer'),
10263
+ confirm: bootstrapOverlayEl.querySelector('.bs-confirm'),
10264
+ cancel: bootstrapOverlayEl.querySelector('.bs-cancel'),
10265
+ link: bootstrapOverlayEl.querySelector('.bs-link'),
10266
+ retry: bootstrapOverlayEl.querySelector('.bs-retry'),
10267
+ };
9493
10268
  const log = bootstrapOverlayEl.querySelector('.bs-log');
9494
- const remediation = bootstrapOverlayEl.querySelector('.bs-remediation');
9495
- const retry = bootstrapOverlayEl.querySelector('.secondary');
9496
- if (status === 'failed') {
10269
+ const { body, statusEl, remediation, retry } = els;
10270
+ // Every view starts from a blank card and shows only what it names.
10271
+ hideBootstrapControls();
10272
+ els.note.textContent = '';
10273
+ els.hint.textContent = '';
10274
+ remediation.textContent = '';
10275
+ // A view change clears the status line; a re-render of the same view keeps it (e.g. "Copied.").
10276
+ if (!prev || prev.view !== view) statusEl.textContent = '';
10277
+ let spin;
10278
+ if (nodeView) {
10279
+ // Load the plan the first time a Node.js failure shows; until it arrives the card shows the manual
10280
+ // route, which is never wrong.
10281
+ loadNodeInstallPlan();
10282
+ // SSE is at-most-once: while an install is in flight, the 5 s health re-render also re-reads the
10283
+ // job, so a missed "finished" event cannot leave the card spinning forever.
10284
+ if (nodeView === 'node-running' || nodeView === 'node-checking' || nodeView === 'node-unknown') refreshNodeInstallJob();
10285
+ spin = paintNodeInstallView(nodeView, els).spinner;
10286
+ if (nodeView !== 'node-running' && log) log.textContent = '';
10287
+ if (nodeView === 'node-running' && nodeInstall.job && nodeInstall.job.lastLine && log && !log.textContent) log.textContent = nodeInstall.job.lastLine;
10288
+ } else if (status === 'failed') {
9497
10289
  // No spinner on failure — absence of motion is the signal (no error icon).
9498
- if (spinner) spinner.remove();
10290
+ spin = false;
9499
10291
  h1.textContent = 'Setup failed';
9500
10292
  body.textContent = bootstrapBody(s.reason);
9501
- statusEl.textContent = '';
9502
10293
  if (log) log.textContent = ''; // ticker is only meaningful while installing
9503
10294
  // Server remediation is SUPPLEMENTARY dim context — omit if empty or if it
9504
10295
  // duplicates the fixed body (the fixed copy is the user-facing message).
9505
10296
  const rem = (s.remediation || '').trim();
9506
10297
  remediation.textContent = rem && rem !== body.textContent ? rem : '';
9507
10298
  retry.hidden = false;
9508
- // Respect an in-flight retry: an SSE/poll re-render of `failed` mid-retry
9509
- // would otherwise re-enable the button and allow duplicate clicks. The
9510
- // server is idempotent today (terminal-state guard on /api/bootstrap/retry),
9511
- // but the UI shouldn't depend on that.
9512
- retry.disabled = bootstrapRetryInFlight;
9513
- retry.textContent = bootstrapRetryInFlight ? 'Trying…' : 'Try again';
9514
10299
  } else {
9515
10300
  // probing / installing — spinner spins, no button.
9516
- if (!bootstrapOverlayEl.querySelector('.bs-spinner')) {
9517
- const sp = document.createElement('div');
9518
- sp.className = 'bs-spinner';
9519
- sp.setAttribute('aria-hidden', 'true');
9520
- card.insertBefore(sp, h1);
9521
- }
10301
+ spin = true;
10302
+ nodeInstall.step = 'offer';
9522
10303
  h1.textContent = 'Setting up AWARE…';
9523
10304
  body.textContent = 'Installing the AWARE runtime. This happens once.';
9524
10305
  // probing may say "Checking…"; installing clears it (the ticker carries the signal).
9525
10306
  statusEl.textContent = status === 'probing' ? 'Checking for AWARE…' : '';
9526
10307
  if (status !== 'installing' && log) log.textContent = ''; // clear ticker when not installing
9527
- remediation.textContent = '';
9528
- retry.hidden = true;
9529
10308
  }
9530
- // Re-focus the card when the STATE changes (not on every event) so the new
9531
- // h1/body is re-announced via role=status without spamming on each ticker line.
9532
- if (!prev || prev.status !== status) {
10309
+ // Respect an in-flight retry: an SSE/poll re-render of `failed` mid-retry
10310
+ // would otherwise re-enable the button and allow duplicate clicks. The
10311
+ // server is idempotent today (terminal-state guard on /api/bootstrap/retry),
10312
+ // but the UI shouldn't depend on that.
10313
+ retry.disabled = bootstrapRetryInFlight;
10314
+ retry.textContent = bootstrapRetryInFlight ? 'Trying…' : 'Try again';
10315
+ const spinner = bootstrapOverlayEl.querySelector('.bs-spinner');
10316
+ if (spin && !spinner) {
10317
+ const sp = document.createElement('div');
10318
+ sp.className = 'bs-spinner';
10319
+ sp.setAttribute('aria-hidden', 'true');
10320
+ card.insertBefore(sp, h1);
10321
+ } else if (!spin && spinner) spinner.remove();
10322
+ // Re-focus the card when the VIEW changes (not on every event) so the new
10323
+ // h1/body is re-announced without spamming on each ticker line. Keyed on the
10324
+ // view, not the status: offer → consent → installing are all `failed` to the
10325
+ // server. On consent the card takes focus, never Install, which starts an
10326
+ // elevation prompt.
10327
+ if (!prev || prev.view !== view) {
9533
10328
  if (document.activeElement !== card) card.focus();
9534
10329
  }
9535
10330
  }
9536
10331
 
10332
+ // Hide every control on the card; each view un-hides only its own.
10333
+ function hideBootstrapControls() {
10334
+ if (!bootstrapOverlayEl) return;
10335
+ for (const sel of ['.bs-cmd-wrap', '.bs-offer', '.bs-confirm', '.bs-cancel', '.bs-link', '.bs-retry']) {
10336
+ const el = bootstrapOverlayEl.querySelector(sel);
10337
+ if (el) el.hidden = true;
10338
+ }
10339
+ }
10340
+
9537
10341
  // Transition installing→ready: a brief "Ready" beat, then remove (not instant)
9538
10342
  // so success registers before the workspace paints. A dwell, not an animation.
9539
10343
  function finishBootstrapReady() {
@@ -9559,7 +10363,9 @@
9559
10363
  card.querySelector('.bs-status').textContent = '';
9560
10364
  card.querySelector('.bs-log').textContent = '';
9561
10365
  card.querySelector('.bs-remediation').textContent = '';
9562
- card.querySelector('.secondary').hidden = true;
10366
+ card.querySelector('.bs-note').textContent = '';
10367
+ card.querySelector('.bs-hint').textContent = '';
10368
+ hideBootstrapControls();
9563
10369
  }
9564
10370
  bootstrapReadyTimer = setTimeout(() => {
9565
10371
  hideBootstrapOverlay();
@@ -9675,7 +10481,37 @@
9675
10481
  padding:7px 16px;border-radius:7px;}
9676
10482
  #aware-bootstrap-overlay .secondary:hover{border-color:var(--accent,#3b82f6);color:var(--text,#f8fafc);}
9677
10483
  #aware-bootstrap-overlay .secondary:disabled{cursor:default;opacity:.55;border-color:var(--border,#1e293b);color:var(--text-dim,#94a3b8);}
9678
- #aware-bootstrap-overlay .bs-log:empty,#aware-bootstrap-overlay .bs-remediation:empty{display:none;}`;
10484
+ #aware-bootstrap-overlay .bs-log:empty,#aware-bootstrap-overlay .bs-remediation:empty{display:none;}
10485
+ /* "Install Node.js for me" (#2381): the primary action, the consent step's command, and the
10486
+ alternatives row. Primary mirrors .modal-actions button.primary; no new tokens. */
10487
+ #aware-bootstrap-overlay .bs-primary{appearance:none;cursor:pointer;font-size:13px;font-weight:600;margin-top:16px;
10488
+ background:var(--accent,#3b82f6);border:1px solid var(--accent,#3b82f6);color:#fff;padding:8px 18px;border-radius:7px;}
10489
+ #aware-bootstrap-overlay .bs-primary:hover{background:var(--accent-bright,#60a5fa);box-shadow:0 0 14px var(--accent-glow,rgba(59,130,246,.4));}
10490
+ #aware-bootstrap-overlay .bs-primary:disabled{cursor:default;opacity:.6;box-shadow:none;background:var(--accent,#3b82f6);}
10491
+ #aware-bootstrap-overlay .bs-primary:focus-visible,#aware-bootstrap-overlay .secondary:focus-visible,
10492
+ #aware-bootstrap-overlay .bs-link:focus-visible,#aware-bootstrap-overlay .bs-copy:focus-visible{outline:2px solid var(--accent-bright,#60a5fa);outline-offset:2px;}
10493
+ #aware-bootstrap-overlay .bs-actions{display:flex;gap:12px;justify-content:center;align-items:center;flex-wrap:wrap;}
10494
+ #aware-bootstrap-overlay .bs-actions .bs-primary{margin-top:16px;}
10495
+ #aware-bootstrap-overlay .bs-link{font-size:12.5px;margin-top:16px;color:var(--text-dim,#94a3b8);text-decoration:none;}
10496
+ #aware-bootstrap-overlay .bs-link:hover{color:var(--accent-bright,#60a5fa);text-decoration:underline;}
10497
+ #aware-bootstrap-overlay .bs-cmd-wrap{position:relative;margin:10px 0 6px;text-align:left;}
10498
+ #aware-bootstrap-overlay .bs-cmd{margin:0;font:11.5px/1.5 var(--mono,monospace);color:var(--text,#f8fafc);
10499
+ background:color-mix(in srgb,var(--text-dim,#94a3b8) 8%,transparent);border:1px solid var(--border,#1e293b);border-radius:7px;
10500
+ padding:10px 52px 10px 12px;white-space:pre-wrap;overflow-wrap:break-word;max-height:140px;overflow:auto;
10501
+ scrollbar-width:thin;scrollbar-color:color-mix(in srgb,var(--text-dim,#94a3b8) 40%,transparent) transparent;}
10502
+ #aware-bootstrap-overlay .bs-cmd .bs-tok{white-space:nowrap;}
10503
+ #aware-bootstrap-overlay .bs-cmd::-webkit-scrollbar{width:8px;height:8px;}
10504
+ #aware-bootstrap-overlay .bs-cmd::-webkit-scrollbar-track{background:transparent;}
10505
+ #aware-bootstrap-overlay .bs-cmd::-webkit-scrollbar-thumb{background:color-mix(in srgb,var(--text-dim,#94a3b8) 40%,transparent);border-radius:4px;}
10506
+ #aware-bootstrap-overlay .bs-copy{position:absolute;top:6px;right:6px;appearance:none;cursor:pointer;font-size:11px;
10507
+ background:var(--surface,#0b1424);border:1px solid var(--border,#1e293b);color:var(--text-dim,#94a3b8);padding:2px 8px;border-radius:5px;}
10508
+ #aware-bootstrap-overlay .bs-copy:hover{border-color:var(--accent,#3b82f6);color:var(--text,#f8fafc);}
10509
+ #aware-bootstrap-overlay .bs-note{font-size:12.5px;}
10510
+ #aware-bootstrap-overlay .bs-hint{font-size:12px;margin:12px 0 0;}
10511
+ #aware-bootstrap-overlay .bs-note:empty,#aware-bootstrap-overlay .bs-hint:empty{display:none;}
10512
+ /* display set above would beat the UA [hidden] rule — restore hiding for every control. */
10513
+ #aware-bootstrap-overlay .bs-primary[hidden],#aware-bootstrap-overlay .secondary[hidden],
10514
+ #aware-bootstrap-overlay .bs-link[hidden],#aware-bootstrap-overlay .bs-cmd-wrap[hidden]{display:none;}`;
9679
10515
  document.head.appendChild(style);
9680
10516
  const stat = document.querySelector('footer .status .stat'); // first stat = runtime
9681
10517
  if (!stat) return;
@@ -9734,10 +10570,9 @@
9734
10570
  const healthTick = async () => {
9735
10571
  let ok = false;
9736
10572
  try {
9737
- const r = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(45_000) });
9738
- ok = r.ok;
10573
+ const h = await readHealth();
10574
+ ok = true;
9739
10575
  if (ok) {
9740
- const h = await r.json();
9741
10576
  // Stamp the build + AWARE runtime versions into the footer once (so a
9742
10577
  // stale install or AWARE mismatch is self-diagnosable). appVersion is
9743
10578
  // the real sq.version on an install (package.json only from source);
@@ -9860,12 +10695,44 @@
9860
10695
  const es = new EventSource('/api/events');
9861
10696
  let reloadTimer = null;
9862
10697
  let everOpened = false;
10698
+ let rootDisconnected = false;
10699
+ let connectionGeneration = 0;
10700
+ let pendingCatchup = null;
10701
+ function drainPendingCatchup() {
10702
+ const generation = pendingCatchup;
10703
+ const roots = window.flolessWorkspaceRoot;
10704
+ if (generation === null || generation !== connectionGeneration || !roots?.isCurrent(roots.current())) return;
10705
+ // Clear before dispatch: root publication and its GET continuation may both arrive here.
10706
+ pendingCatchup = null;
10707
+ window.dispatchEvent(new CustomEvent('floless:apps-changed', { detail: {} }));
10708
+ window.dispatchEvent(new CustomEvent('floless:projects-changed', { detail: {} }));
10709
+ window.dispatchEvent(new CustomEvent('floless:action-proposal', { detail: { resync: true } }));
10710
+ loadRequests();
10711
+ const workflowId = currentId;
10712
+ if (workflowId) refreshCurrentWorkflowAvailability().catch(error => {
10713
+ if (generation === connectionGeneration) reportBackgroundAvailabilityErr(error);
10714
+ });
10715
+ void refreshSelectedCompleteReportDiscovery(workflowId);
10716
+ void resyncLiveRun();
10717
+ if (workflowId) void refreshWorkflowPage(workflowId);
10718
+ }
10719
+ // One unfinished reconnect may resume after an existing dialog refresh or root selection.
10720
+ window.addEventListener('floless:workspace-root-state', drainPendingCatchup);
9863
10721
  es.onopen = () => {
10722
+ const reconnect = everOpened || rootDisconnected;
10723
+ everOpened = true;
10724
+ rootDisconnected = false;
10725
+ const generation = ++connectionGeneration;
10726
+ pendingCatchup = reconnect ? generation : null;
10727
+ if (reconnect) {
10728
+ window.flolessWorkspaceRoot.invalidateConnection();
10729
+ globalThis.flolessStartupAdmission?.invalidate();
10730
+ }
9864
10731
  setServerStatus(true);
9865
10732
  // Core provisioning may have finished after the page read /api/apps but before this
9866
10733
  // at-most-once stream connected. Re-read the catalogue on every open, including the
9867
10734
  // first one; Workspaces defers its repaint while a dialog is active.
9868
- window.dispatchEvent(new CustomEvent('floless:apps-changed', { detail: {} }));
10735
+ if (!reconnect) window.dispatchEvent(new CustomEvent('floless:apps-changed', { detail: {} }));
9869
10736
  // A RECONNECT MEANS WE MISSED WHATEVER HAPPENED WHILE WE WERE GONE — and this catches up the
9870
10737
  // PROJECT half of that, not every arm below (workflow imports, contract writes and the rest
9871
10738
  // still heal on their next event or a reload). These events are
@@ -9876,21 +10743,21 @@
9876
10743
  // reconnect only (never the first connect, which has nothing to catch up on) and carry NO
9877
10744
  // payload: workspaces.js answers an empty event by re-reading the live set, which is exactly
9878
10745
  // the catch-up question. (Found by review.)
9879
- if (everOpened) {
9880
- window.dispatchEvent(new CustomEvent('floless:projects-changed', { detail: {} }));
9881
- loadRequests();
9882
- // The SAME catch-up for the other half a live `projects-changed` drives (see that arm): the
9883
- // open workflow's publication availability turns on project state, so a gap leaves the card
9884
- // asserting a state that may no longer hold. Re-asking for Workspaces but not for Workflows
9885
- // would fix one stale surface and leave its sibling. (Found by review round 2.)
9886
- if (currentId) refreshCurrentWorkflowAvailability().catch(reportErr);
10746
+ if (reconnect) {
10747
+ // The catalogue event also reads projects. None of this catch-up can use a cached root
10748
+ // from the previous server. A later accepted dialog observation may finish this work too.
10749
+ window.flolessWorkspaceRoot.refresh({ throwOnError: true,
10750
+ isCurrent: () => generation === connectionGeneration,
10751
+ }).then(drainPendingCatchup).catch(() => {
10752
+ if (generation === connectionGeneration && pendingCatchup === generation) showToast('FloLess could not check the current Workspace directory. Open Workspace directory to try again.', 'err');
10753
+ });
10754
+ return;
9887
10755
  }
9888
10756
  // Scheduled reports may finish with every browser closed; refresh their authorized
9889
10757
  // pointers on both first connection and reconnect, never from SSE payload data.
9890
10758
  void refreshSelectedCompleteReportDiscovery(currentId);
9891
10759
  // #2228: progress events are at-most-once too — a reload or a reconnect asks where this tab's run is.
9892
10760
  void resyncLiveRun();
9893
- everOpened = true;
9894
10761
  };
9895
10762
  es.onmessage = (e) => {
9896
10763
  let m;
@@ -9903,6 +10770,9 @@
9903
10770
  // (installing only) → dim ticker; `status`/`reason` drive the card state.
9904
10771
  if (m.line != null) setBootstrapLogLine(m.line);
9905
10772
  if (m.status) updateBootstrap({ status: m.status, reason: m.reason ?? null, remediation: m.remediation ?? null });
10773
+ } else if (m.type === 'node-install') {
10774
+ // "Install Node.js for me" (#2381): the server's install job, its progress lines and its end.
10775
+ onNodeInstallEvent(m);
9906
10776
  } else if (m.type === 'aware-update') {
9907
10777
  // The server started an automatic bridge repair. Adopt it now so an ALREADY-OPEN tab shows
9908
10778
  // it immediately; the init-time adopt() only covers tabs opened after it began. adopt() is
@@ -9911,6 +10781,8 @@
9911
10781
  } else if (m.type === 'run-live' || m.type === 'node-progress' || m.type === 'run-finished') {
9912
10782
  // #2228: live progress of a long run. This tab's own run is matched by its token; a run of the
9913
10783
  // workflow this tab shows that someone else started is followed read-only (no Stop).
10784
+ // #2241: a run that FAILED after an Agent answered ends with run-finished, not run-ended: its AI record is read then too.
10785
+ if (m.type === 'run-finished' && m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id);
9914
10786
  if (liveRunOwns(m)) {
9915
10787
  if (m.type === 'run-live') { if (m.runId) liveRun.runId = m.runId; }
9916
10788
  else if (m.type === 'node-progress') onLiveProgress(m);
@@ -9929,6 +10801,10 @@
9929
10801
  const videos = m.media.filter((x) => x && x.kind === 'video' && typeof x.url === 'string');
9930
10802
  const mine = liveRun && ((m.clientRunToken && liveRun.token === m.clientRunToken) || (m.runId && liveRun.runId === m.runId));
9931
10803
  if (videos.length && (mine || m.id === currentId)) offerRunVideos(m.id, videos);
10804
+ } else if (m.type === 'action-proposal' && typeof m.proposalId === 'string') {
10805
+ // #2248: a request from the terminal was made or changed. terminal-requests.js reads it back by id and shows it.
10806
+ try { window.dispatchEvent(new CustomEvent('floless:action-proposal', { detail: { proposalId: m.proposalId } })); }
10807
+ catch { /* a listener throwing must not break the SSE loop */ }
9932
10808
  } else if (m.type === 'render-progress') {
9933
10809
  // Relayed as a DOM event rather than widening the bridge: workspaces.js owns the Exports
9934
10810
  // card and is the only listener, and a render can outlive several repaints of it.
@@ -9944,7 +10820,11 @@
9944
10820
  // `clearExportReceiptsForApp` repaints via markSpecialNodes(), so the stale map was actively
9945
10821
  // RE-APPLIED rather than merely left behind. Nothing self-healed until the user switched
9946
10822
  // workflows. Re-read the payload rather than guess at the new state.
9947
- if (m.appId === currentId) refreshCurrentWorkflowAvailability().catch(reportErr);
10823
+ if (m.appId === currentId) refreshCurrentWorkflowAvailability().catch(reportBackgroundAvailabilityErr);
10824
+ } else if (m.type === 'contract-changed' && typeof m.appId === 'string' && typeof m.project === 'string') {
10825
+ // #2482: a PROJECT's contract changed (a checklist draft, a reference added from AI Chat). workspaces.js relays
10826
+ // it to that project's open editor frame, which has no event stream of its own.
10827
+ window.dispatchEvent(new CustomEvent('floless:contract-changed', { detail: m }));
9948
10828
  } else if (m.type === 'projects-changed') {
9949
10829
  // Relayed as a DOM event for the same reason apps-changed is (see that arm below):
9950
10830
  // workspaces.js owns the project view and is the only listener. It reconciles the project it
@@ -9955,8 +10835,8 @@
9955
10835
  // workflow, and the open PROJECT is a different question — its app need not be the workflow
9956
10836
  // this tab happens to be showing.
9957
10837
  window.dispatchEvent(new CustomEvent('floless:projects-changed', { detail: m }));
9958
- if (typeof m.appId !== 'string' || m.appId === currentId) {
9959
- refreshCurrentWorkflowAvailability().catch(reportErr);
10838
+ if (m.kind !== 'metadata' && (typeof m.appId !== 'string' || m.appId === currentId)) {
10839
+ refreshCurrentWorkflowAvailability().catch(reportBackgroundAvailabilityErr);
9960
10840
  }
9961
10841
  } else if (m.type === 'workspace-root-changed') {
9962
10842
  // Root identity/path belongs to the server's protected registry. Re-read it so every open tab
@@ -10098,16 +10978,26 @@
10098
10978
  // The terminal AI (or undo/reset) rewrote ~/.floless/ui/extensions.json —
10099
10979
  // re-render the Dashboard / inspect-tab panels live. panels.js owns it.
10100
10980
  if (window.flolessPanels) window.flolessPanels.refresh({ fromChange: true });
10981
+ } else if (m.type === 'knowledge-changed') {
10982
+ // #2399 slice 0b: a chat, a terminal or another window changed a project's references or design set.
10983
+ window.flolessWorkspaces?.knowledgeChanged?.(m.projectId);
10101
10984
  } else if (m.type === 'revision-note-changed') {
10102
10985
  window.dispatchEvent(new CustomEvent('floless:revision-note-changed', { detail: m }));
10103
10986
  } else if (m.type === 'run-ended') {
10104
10987
  // Panel data bindings (last-run-output/-status) go stale after any run.
10105
10988
  if (window.flolessPanels) window.flolessPanels.refreshData();
10989
+ if (m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id); // #2241 S5
10106
10990
  } else if (m.type === 'routine-changed') {
10107
10991
  loadRoutinesData();
10992
+ window.flolessProjectAccess?.refresh?.(); // Project access lists schedules: its chip count and open sheet follow
10993
+ } else if (m.type === 'agent-step-fires-changed') {
10994
+ // S8: a watcher's AI step recorded an event: its Inspect history and its routine card count are read again.
10995
+ globalThis.flolessAgentSteps?.watcherChanged?.(m.id);
10996
+ if (m.routineId) loadRoutinesData();
10108
10997
  } else if (m.type === 'agent-changed') {
10109
10998
  // #2062: an agent was paused, resumed, archived or restored; an open page of it shows the new state.
10110
10999
  window.flolessAgents?.refreshAgent?.(m.agentId);
11000
+ window.flolessProjectAccess?.refresh?.();
10111
11001
  } else if (m.type === 'routine-run-started') {
10112
11002
  runningRoutines.add(m.id);
10113
11003
  if ($routinesModal.classList.contains('show')) renderRoutinesList();
@@ -10116,6 +11006,7 @@
10116
11006
  loadRoutinesData();
10117
11007
  if (window.flolessPanels) window.flolessPanels.refreshData(); // routine runs also refresh bindings
10118
11008
  window.flolessAgents?.refreshRuns?.(); // #2035: an open agent page shows the run its routine just started
11009
+ if (currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(currentId); // #2241 S5: a scheduled run may have left questions
10119
11010
  } else if (m.type === 'trigger-session-changed') {
10120
11011
  // A foreground live-run session (▶ Run on a streaming app) shares this SSE
10121
11012
  // event with background routines; its server-namespaced id routes it to the
@@ -10126,6 +11017,8 @@
10126
11017
  applyTriggerReport(m);
10127
11018
  } else if (m.type === 'routine-report') {
10128
11019
  applyRoutineReport(m);
11020
+ } else if (m.type === 'workflow-page-captured') {
11021
+ applyWorkflowPageCaptured(m);
10129
11022
  } else if (m.type === 'action-run-report') {
10130
11023
  applyActionRunReport(m);
10131
11024
  } else if (m.type === 'routine-report-changed') {
@@ -10178,7 +11071,13 @@
10178
11071
  recheckLicenseAndGate();
10179
11072
  }
10180
11073
  };
10181
- es.onerror = () => setServerStatus(false); // server unreachable → red; EventSource auto-reconnects (onopen → green)
11074
+ es.onerror = () => {
11075
+ connectionGeneration++;
11076
+ pendingCatchup = null;
11077
+ rootDisconnected = true;
11078
+ window.flolessWorkspaceRoot.invalidateConnection();
11079
+ setServerStatus(false); // EventSource auto-reconnects; an earlier continuation must not catch up.
11080
+ };
10182
11081
  }
10183
11082
 
10184
11083
  // A Request start the chat routes refused with one of the codes below has its own sentence in AI
@@ -10200,9 +11099,45 @@
10200
11099
  showToast(text, 'warn');
10201
11100
  }
10202
11101
 
11102
+ // The sentence for a 402 from the subscription gate (server/subscription-gate.ts), or '' for any other failure.
11103
+ // The one copy every surface uses: when the FloLess sign-in lapsed, chat said "could not complete this chat action"
11104
+ // and a workflow refresh said "could not reach it", so nobody knew that signing in again was the fix (2026-10-16).
11105
+ // Reads the response body when the caller kept it, else the structured fields copied onto the error.
11106
+ function accountAccessText(error) {
11107
+ const access = error?.body || error;
11108
+ if (error?.status !== 402 && access?.error !== 'subscription required') return '';
11109
+ if (access?.state === 'expired') return 'Your FloLess subscription has expired. Renew your FloLess subscription, then try again.';
11110
+ if (access?.reason === 'no-subscription') return 'This account does not have a FloLess subscription. Sign in with a subscribed account or subscribe, then try again.';
11111
+ if (access?.reason === 'session-expired') return 'Your FloLess sign-in has expired. Sign in again, then try again.';
11112
+ if (access?.reason === 'signed-out') return 'You are signed out of FloLess. Sign in again, then try again.';
11113
+ if (access?.reason === 'seat-taken') return 'Your FloLess session has ended. Sign in again, then try again.';
11114
+ return 'Sign in to FloLess to check your account access, then try again.';
11115
+ }
11116
+
11117
+ // A refusal the server wrote for the person — a commercial module (Revit, Tekla, Drawing Checker)
11118
+ // that is not confirmed for this computer says what is wrong and what to do (module-registry
11119
+ // REFUSAL_COPY), and sends that sentence as `userMessage`. The generic "try again, reopen FloLess"
11120
+ // line used to replace it, although neither fixes the refusal. Only `userMessage` is shown: `error`
11121
+ // on the same code can be internal wording.
11122
+ function moduleRefusalText(e) {
11123
+ const text = e?.status === 403 && typeof e.body?.userMessage === 'string' ? e.body.userMessage.trim() : '';
11124
+ return text;
11125
+ }
11126
+
10203
11127
  function reportErr(e) {
10204
11128
  if (awarePageUnloading && e instanceof TypeError && e.message === 'Failed to fetch') return;
10205
11129
  console.error(e);
11130
+ const refusal = moduleRefusalText(e);
11131
+ if (refusal) {
11132
+ showToast(refusal, 'warn');
11133
+ return;
11134
+ }
11135
+ // #2474: a change asked of a workflow's published copy says how to change the workflow instead.
11136
+ const owned = e?.status === 409 && e.body?.code === 'owned-workflow-publication' && typeof e.body.userMessage === 'string' ? e.body.userMessage.trim() : '';
11137
+ if (owned) {
11138
+ showToast(owned, 'warn');
11139
+ return;
11140
+ }
10206
11141
  showToast('We couldn’t finish that. Your work is still here. Try again. If it keeps happening, reopen FloLess.', 'err');
10207
11142
  }
10208
11143
 
@@ -10432,7 +11367,7 @@
10432
11367
  try {
10433
11368
  // A dead local server must not leave a Copy button waiting forever. Keep the
10434
11369
  // authoritative revalidation, but fail closed after a short, user-action-sized wait.
10435
- const latest = await api('/api/requests', { signal: AbortSignal.timeout(5000) });
11370
+ const latest = await api('/api/requests', { timeoutMs: 5000 });
10436
11371
  current = Array.isArray(latest?.requests)
10437
11372
  ? latest.requests.find((candidate) => candidate && candidate.id === req.id)
10438
11373
  : null;
@@ -11696,7 +12631,7 @@
11696
12631
  let doneRequestsUnreadable = 0;
11697
12632
  async function loadDoneRequests() {
11698
12633
  try {
11699
- const body = await api('/api/requests/done', { signal: AbortSignal.timeout(30_000) });
12634
+ const body = await api('/api/requests/done', { timeoutMs: 30_000 });
11700
12635
  doneRequests = Array.isArray(body?.requests) ? body.requests : [];
11701
12636
  doneRequestsUnreadable = Number(body?.unreadable) || 0;
11702
12637
  doneRequestsError = null;
@@ -11927,7 +12862,7 @@
11927
12862
  try {
11928
12863
  // Bounded: every later read waits behind this one, so a response that never arrives must not
11929
12864
  // freeze the list for good. The route's own lock waits give up after 60 s.
11930
- const { requests, chatPublications = [], needsYou, backlog = null } = await api('/api/requests', { signal: AbortSignal.timeout(90_000) });
12865
+ const { requests, chatPublications = [], needsYou, backlog = null } = await api('/api/requests', { timeoutMs: 90_000 });
11931
12866
  reconcileActiveInstructorRuns(requests, chatPublications);
11932
12867
  pendingRequests = requests;
11933
12868
  requestsBacklog = backlog && typeof backlog === 'object' ? backlog : null;
@@ -15005,9 +15940,7 @@
15005
15940
 
15006
15941
  async function ensureReportDiscoverySession(force = false) {
15007
15942
  if (!reportDiscoveryBootstrapMode) {
15008
- reportDiscoveryBootstrapMode = fetch('/api/health', { cache: 'no-store' }).then(async (response) => {
15009
- if (!response.ok) throw new Error('report discovery health check unavailable');
15010
- const health = await response.json();
15943
+ reportDiscoveryBootstrapMode = readHealth().then((health) => {
15011
15944
  if (typeof health?.capabilities?.editorSessionHttpBootstrap !== 'boolean') {
15012
15945
  throw new Error('report discovery session mode unavailable');
15013
15946
  }
@@ -15103,9 +16036,7 @@
15103
16036
  async function savedReportsStillStarting() {
15104
16037
  if (!reportsMaybeStarting) return null;
15105
16038
  try {
15106
- const response = await fetch('/api/health', { cache: 'no-store' });
15107
- if (!response.ok) return null;
15108
- const state = (await response.json())?.startup?.reports;
16039
+ const state = (await readHealth())?.startup?.reports;
15109
16040
  // An older server has no startup field: it only ever answers once reports are ready.
15110
16041
  if (state === undefined || state === 'ready') { reportsMaybeStarting = false; return null; }
15111
16042
  return state === 'paused' ? 'paused' : 'checking';
@@ -15217,6 +16148,15 @@
15217
16148
  const d = new Date(iso);
15218
16149
  return isNaN(d.getTime()) ? '' : d.toLocaleString();
15219
16150
  }
16151
+ // #2241 S5: the last scheduled run used an AI step - say so in the row, and how many questions it left for the person.
16152
+ function routineAiHtml(r) {
16153
+ // S8: a watcher has no run per event; its card speaks from the events that reached its AI step.
16154
+ const ai = r.kind === 'trigger' ? globalThis.flolessAgentSteps?.watcherCardParts?.(r.aiEvents) ?? null
16155
+ : !r.agent && r.lastRun ? globalThis.flolessAgentSteps?.routineAiParts(r.lastRun) : null;
16156
+ if (!ai) return '';
16157
+ return `<span class="rtn-dot">·</span><span class="rtn-ai" data-tip="${escapeAttr(ai.aiTip)}">${escapeHtml(ai.ai)}</span>`
16158
+ + (ai.questions ? `<span class="rtn-dot">·</span><span class="rtn-ai-q" data-tip="${escapeAttr(ai.questionsTip)}">${escapeHtml(ai.questions)}</span>` : '');
16159
+ }
15220
16160
  function lastRunTip(r) {
15221
16161
  if (!r.lastRun) return 'Never run yet';
15222
16162
  const lr = r.lastRun;
@@ -15232,6 +16172,9 @@
15232
16172
  return `Didn’t start${lr.reason ? ' — ' + lr.reason : ''} · ${when}`;
15233
16173
  }
15234
16174
  const dur = lr.durationMs != null ? ` · ${(lr.durationMs / 1000).toFixed(1)} s` : '';
16175
+ // #2241 S5: a run with an AI step says so, and says how many questions it left for you.
16176
+ const ai = globalThis.flolessAgentSteps?.routineAiParts(lr);
16177
+ const aiWords = ai ? ` — ${ai.ai}${ai.questions ? ' · ' + ai.questions : ''}` : '';
15235
16178
  // A run that finished on a stated assumption says so with its outcome, never only in the report.
15236
16179
  const warnings = Array.isArray(lr.warnings) ? lr.warnings.filter((warning) => typeof warning === 'string' && warning) : [];
15237
16180
  // #1998: a run made under an approval carried forward to newer tool versions says so, in AWARE's words.
@@ -15243,7 +16186,7 @@
15243
16186
  && typeof w.detail === 'string' && w.detail.trim() && (w.via === null || typeof w.via === 'string')
15244
16187
  && Array.isArray(w.choices) && w.choices.every((choice) => typeof choice === 'string')) : [];
15245
16188
  const bridge = bridgeWarnings.map((w) => `\n${w.status === 'declaration-invalid' ? 'Ran with an invalid bridge declaration' : 'Ran with a bridge mismatch'}: ${w.via ? w.via + ' → ' : ''}${w.name}. ${w.detail}`).join('');
15246
- return `Last run ${lr.status}${lr.reason ? ' — ' + lr.reason : ''}${warnings.length ? ' — ' + warnings.join(' ') : ''} · ${absTime(lr.at)}${dur}${carried}${bridge}`;
16189
+ return `Last run ${lr.status}${aiWords}${lr.reason ? ' — ' + lr.reason : ''}${warnings.length ? ' — ' + warnings.join(' ') : ''} · ${absTime(lr.at)}${dur}${carried}${bridge}`;
15247
16190
  }
15248
16191
 
15249
16192
  // ── Trigger-routine row helpers ─────────────────────────────────────────────
@@ -15419,10 +16362,14 @@
15419
16362
  // depends on the report-frame `allow-same-origin` fix to repaint in Chrome.)
15420
16363
  function applyTriggerReport(m) {
15421
16364
  if (!m || !m.workflow || typeof m.html !== 'string') return;
15422
- lastReportByApp.set(m.workflow, { nodeId: m.nodeId || null, label: 'live · on selection change', html: m.html });
16365
+ const runId = typeof m.runId === 'string' ? m.runId : null;
16366
+ const entry = { nodeId: m.nodeId || null, label: 'live · on selection change', html: m.html,
16367
+ runId, captureKey: captureKeyOf(runId, m.fireKey), withFiles: m.withFiles === true };
16368
+ lastReportByApp.set(m.workflow, entry);
15423
16369
  const open = $reportModal && $reportModal.classList.contains('show');
15424
16370
  if (!open || currentId !== m.workflow || reportRunning) return;
15425
- paintReport(m.html); // unhides Share + clears the overlay
16371
+ paintReport(m.html, false, entry); // unhides Share + clears the overlay
16372
+ paintReportPageLinks();
15426
16373
  const t = new Date().toLocaleTimeString();
15427
16374
  $reportSub.innerHTML =
15428
16375
  `<span class="live-pip" aria-hidden="true"></span>Live &middot; updated ${escapeHtml(t)} &middot; on selection change — rendered from the node's output, never composed by the UI.`;
@@ -15445,11 +16392,13 @@
15445
16392
  const interactive = m.interactive === true;
15446
16393
  const savedPath = typeof m.savedPath === 'string' ? m.savedPath : '';
15447
16394
  const fromChat = m.from !== 'terminal';
15448
- lastReportByApp.set(m.workflow, { nodeId: m.nodeId || null, label: fromChat ? 'from AI Chat' : 'from a terminal', html: m.html, interactive, savedPath,
15449
- runId: typeof m.runId === 'string' ? m.runId : null });
16395
+ const entry = { nodeId: m.nodeId || null, label: fromChat ? 'from AI Chat' : 'from a terminal', html: m.html, interactive, savedPath,
16396
+ withFiles: m.withFiles === true, runId: typeof m.runId === 'string' ? m.runId : null };
16397
+ lastReportByApp.set(m.workflow, entry);
15450
16398
  const open = $reportModal && $reportModal.classList.contains('show');
15451
16399
  if (!open || currentId !== m.workflow || reportRunning) return;
15452
- paintReport(m.html, interactive);
16400
+ paintReport(m.html, interactive, entry);
16401
+ paintReportPageLinks();
15453
16402
  $reportSub.textContent = fromChat ? 'Report from the run you confirmed in AI Chat — rendered from the run\'s output, never composed by the UI.'
15454
16403
  : 'Report from a run started in a terminal — rendered from the run\'s output, never composed by the UI.';
15455
16404
  showSavedPathActions(savedPath);
@@ -15459,10 +16408,12 @@
15459
16408
  if (!m || !m.workflow || typeof m.html !== 'string') return;
15460
16409
  const prev = lastReportByApp.get(m.workflow);
15461
16410
  const changed = !prev || prev.html !== m.html;
15462
- lastReportByApp.set(m.workflow, { nodeId: m.nodeId || null, label: 'scheduled', html: m.html });
16411
+ const entry = { nodeId: m.nodeId || null, label: 'scheduled', html: m.html, withFiles: m.withFiles === true, runId: typeof m.runId === 'string' ? m.runId : null };
16412
+ lastReportByApp.set(m.workflow, entry);
15463
16413
  const open = $reportModal && $reportModal.classList.contains('show');
15464
16414
  if (open && currentId === m.workflow && !reportRunning && !foregroundTrigger) {
15465
- paintReport(m.html); // unhides Share + clears the overlay
16415
+ paintReport(m.html, false, entry); // unhides Share + clears the overlay
16416
+ paintReportPageLinks();
15466
16417
  const t = new Date().toLocaleTimeString();
15467
16418
  $reportSub.innerHTML =
15468
16419
  `<span class="live-pip" aria-hidden="true"></span>Scheduled &middot; updated ${escapeHtml(t)} — rendered from the node's output, never composed by the UI.`;
@@ -15888,6 +16839,31 @@
15888
16839
  // server hosts the long-lived `aware app run`; here we open the Viewer, surface
15889
16840
  // Stop, and reflect the live state. We never compose HTML — the Viewer relays
15890
16841
  // exactly what the node returns (applyTriggerReport paints each fresh report).
16842
+ // S8 (#2495): while a person has the live run's Viewer on screen, the page says so every 15 s. An AI step's change card in a live
16843
+ // run is shown only while such a beat is recent; once the Viewer closes, the tab is hidden or the run ends, it says it stopped.
16844
+ let viewerBeatApp = null;
16845
+ function beatLiveViewer() {
16846
+ const viewing = !!foregroundTrigger && currentId === foregroundTrigger.appId && $reportModal.classList.contains('show')
16847
+ && document.visibilityState === 'visible';
16848
+ const appId = viewing ? foregroundTrigger.appId : null;
16849
+ const send = (id, on) => fetch(`/api/trigger-run/${encodeURIComponent(id)}/viewing`, {
16850
+ method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ viewing: on }),
16851
+ }).catch(() => { /* presence only: a missed beat just means the next change is held */ });
16852
+ if (viewerBeatApp && viewerBeatApp !== appId) send(viewerBeatApp, false);
16853
+ if (appId) send(appId, true);
16854
+ viewerBeatApp = appId;
16855
+ }
16856
+ setInterval(beatLiveViewer, 15_000);
16857
+ document.addEventListener('visibilitychange', beatLiveViewer);
16858
+ /** The moment the Viewer closes or the live run ends, say so at once — not at the next beat — so a change card is never
16859
+ * approvable for up to 15 s after the person stopped looking. Only a change of who is viewing sends anything. */
16860
+ function liveViewerMayHaveChanged() {
16861
+ const viewing = !!foregroundTrigger && currentId === foregroundTrigger.appId && $reportModal.classList.contains('show')
16862
+ && document.visibilityState === 'visible';
16863
+ if ((viewing ? foregroundTrigger.appId : null) !== viewerBeatApp) beatLiveViewer();
16864
+ }
16865
+ new MutationObserver(liveViewerMayHaveChanged).observe($reportModal, { attributes: true, attributeFilter: ['class'] });
16866
+
15891
16867
  async function startForegroundTrigger(app) {
15892
16868
  if (foregroundTrigger || foregroundStarting || foregroundStopping) return;
15893
16869
  const id = currentId;
@@ -15911,6 +16887,7 @@
15911
16887
  foregroundTrigger = { appId: id, sessionId: res.sessionId, firedCount: 0 };
15912
16888
  markFirstRunDone(id); // a real live session started → a streaming workflow's "first run" is no longer new
15913
16889
  paintForegroundListening();
16890
+ beatLiveViewer();
15914
16891
  appendNarration(`Live session started for <strong>${escapeHtml(id)}</strong> — the report updates on every event. Click <strong>■ Stop run</strong> (top right) to end it.`);
15915
16892
  } catch (e) {
15916
16893
  // A refusal (a watcher already holds this host) names the concrete path back —
@@ -15956,7 +16933,7 @@
15956
16933
  const fired = foregroundTrigger.firedCount > prevFired;
15957
16934
  const viewerOpen = currentId === foregroundTrigger.appId && $reportModal.classList.contains('show');
15958
16935
  if (snapshot.state === 'error') {
15959
- foregroundTrigger = null;
16936
+ foregroundTrigger = null; liveViewerMayHaveChanged();
15960
16937
  if (viewerOpen) {
15961
16938
  $reportShare.hidden = true; // the error overlay is the primary content now
15962
16939
  $reportOverlay.hidden = false;
@@ -15971,7 +16948,7 @@
15971
16948
  if (snapshot.state === 'stopped') {
15972
16949
  // The stream ended on its own — a one-shot (`once`) snapshot fired then exited,
15973
16950
  // or the host closed cleanly. A clean self-exit reads as "Run complete".
15974
- foregroundTrigger = null;
16951
+ foregroundTrigger = null; liveViewerMayHaveChanged();
15975
16952
  if (viewerOpen) paintForegroundStopped('complete');
15976
16953
  syncRunControls();
15977
16954
  return;
@@ -16118,7 +17095,7 @@
16118
17095
  <div class="rtn-item ${isTrigger ? 'trigger ' : ''}${r.enabled ? '' : 'disabled'} ${running ? 'running' : ''}" data-id="${escapeAttr(r.id)}">
16119
17096
  <div class="rtn-main">
16120
17097
  <div class="rtn-name">${escapeHtml(r.name)}</div>
16121
- <div class="rtn-sub"><span class="rtn-wf">${escapeHtml(whatText)}</span><span class="rtn-dot">·</span><span>${escapeHtml(whenText)}</span>${broken}</div>
17098
+ <div class="rtn-sub"><span class="rtn-wf">${escapeHtml(whatText)}</span><span class="rtn-dot">·</span><span>${escapeHtml(whenText)}</span>${broken}${routineAiHtml(r)}</div>
16122
17099
  ${reportLine}
16123
17100
  </div>
16124
17101
  <div class="rtn-meta"${isTrigger ? ' aria-live="polite" aria-atomic="true"' : ''}>
@@ -16601,6 +17578,13 @@
16601
17578
  };
16602
17579
  // #2035: an agent's page opens a new routine with that agent chosen.
16603
17580
  window.flolessRoutines = {
17581
+ /** Project access: open Routines with one routine's editor, so the person sees exactly the schedule they picked. */
17582
+ async open(routineId) {
17583
+ openRoutines();
17584
+ await loadRoutinesData();
17585
+ if (routinesData.some((r) => r.id === routineId)) await openRoutineEdit(routineId);
17586
+ else showToast('That schedule no longer exists. Routines lists the ones you have.', 'warn');
17587
+ },
16604
17588
  /** #2046: a Guide suggestion — a new routine for this workflow, opened for the person to finish. */
16605
17589
  async editForWorkflow(workflowId, returnFocus) {
16606
17590
  await loadRoutinesData();
@@ -17550,8 +18534,7 @@
17550
18534
  // Show the installed build (so a stale install is self-diagnosable from the
17551
18535
  // gate — the highest-value spot since that's where a confused user lands).
17552
18536
  // /api/health is un-gated, so this works even while unlicensed.
17553
- fetch('/api/health', { cache: 'no-store' })
17554
- .then((r) => r.json())
18537
+ readHealth()
17555
18538
  .then((h) => { if (h && h.appVersion) document.getElementById('lg-version').textContent = 'FloLess ' + h.appVersion; })
17556
18539
  .catch(() => { /* version is a nicety; never block the gate on it */ });
17557
18540
  document.getElementById('lg-signin').onclick = async () => {
@@ -17879,9 +18862,15 @@
17879
18862
  || String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));
17880
18863
  }
17881
18864
 
18865
+ /** The owned workflow (not archived) a chat names by its owned id, or null. */
18866
+ function ownedForOpen(workflowId) {
18867
+ return wfOwned.find((row) => row.workflowId === workflowId && row.status !== 'archived') || null;
18868
+ }
18869
+
18870
+ /** Open an owned workflow's draft view; false when there is no such draft (or no view to show it in). */
17882
18871
  function openDraftWorkflow(workflowId) {
17883
18872
  const row = wfOwned.find((item) => item.workflowId === workflowId && item.status !== 'archived');
17884
- if (!row || !$wfDraft) return;
18873
+ if (!row || !$wfDraft) return false;
17885
18874
  selectionTicket += 1;
17886
18875
  if (draftWorkflow) closeDraftView();
17887
18876
  draftWorkflow = { workflowId: row.workflowId, displayName: row.displayName, ownerLabel: row.ownerLabel || 'Standalone',
@@ -17904,6 +18893,7 @@
17904
18893
  notifyChatScope();
17905
18894
  void watchDraft(draftWorkflow);
17906
18895
  document.getElementById('wf-draft-title')?.focus();
18896
+ return true;
17907
18897
  }
17908
18898
 
17909
18899
  // The AI writes a draft's workflow file from its chat, which raises no workflow event, so an open draft re-reads
@@ -18013,11 +19003,32 @@
18013
19003
  document.getElementById('wf-draft-compile')?.focus();
18014
19004
  try {
18015
19005
  await api(`/api/workflows/owned/${encodeURIComponent(d.workflowId)}/publish`, { method: 'POST' });
18016
- } catch {
19006
+ } catch (error) {
18017
19007
  // The route's own wording is internal; the person gets the plain sentence and two ways on.
18018
19008
  d.busy = false;
18019
19009
  if (draftWorkflow !== d) return;
18020
19010
  d.compiling = false;
19011
+ // #2314: two steps share one name. Ask which to rename; after a rename, compile again. Cancel keeps today's failure.
19012
+ const ask = globalThis.flolessStepRename ? globalThis.flolessStepRename.askOf(error) : null;
19013
+ if (ask) {
19014
+ renderDraftView();
19015
+ const outcome = await globalThis.flolessStepRename.open(ask);
19016
+ if (draftWorkflow !== d) return;
19017
+ if (outcome.renamed) {
19018
+ const warning = outcome.result && outcome.result.warning;
19019
+ if (warning) {
19020
+ // Not exactly as previewed (or not checkable): no automatic Compile — the person looks, then presses Compile.
19021
+ showToast(warning, 'warn');
19022
+ d.note = warning;
19023
+ renderDraftView();
19024
+ return;
19025
+ }
19026
+ await compileDraftWorkflow();
19027
+ return;
19028
+ }
19029
+ // Cancelled: the draft's failure view stays, and the reason stays in view with it.
19030
+ showToast(`${ask.sentence ? `${ask.sentence} ` : ''}Nothing was renamed.`, 'warn');
19031
+ }
18021
19032
  d.failed = true;
18022
19033
  renderDraftView();
18023
19034
  document.getElementById('wf-draft-failure')?.focus();
@@ -18150,12 +19161,18 @@
18150
19161
  // #1997: open an installed workflow by its AWARE app id (the "Open workflow" next step of Approve updated
18151
19162
  // workflows, e.g. "open it and press Compile").
18152
19163
  // Only a workflow the Workflows page lists can be opened; one installed outside FloLess (from a terminal) is not.
18153
- canOpenApp: (appId) => wfLibrary.some((row) => row.id === appId),
19164
+ // A chat working on a FloLess-owned workflow knows it by its owned id, not its AWARE app id (#2241 S6: the
19165
+ // "confirm its AI step" card from the workflow's own chat), so an owned id opens its published app, or its draft.
19166
+ canOpenApp: (appId) => wfLibrary.some((row) => row.id === appId) || Boolean(ownedForOpen(appId)),
18154
19167
  async openApp(appId) {
18155
19168
  await window.flolessWorkspaces?.setMode?.('workflows');
18156
19169
  await loadApps();
18157
19170
  if (!wfLibrary.some((row) => row.id === appId)) {
18158
- throw new Error('That workflow is not on your Workflows page, so FloLess cannot open it. Compile it from the terminal that installed it.');
19171
+ const owned = ownedForOpen(appId);
19172
+ const runtimeId = owned?.activePublication?.runtimeAppId;
19173
+ if (runtimeId && wfLibrary.some((row) => row.id === runtimeId)) appId = runtimeId;
19174
+ else if (owned) return openDraftWorkflow(owned.workflowId);
19175
+ else throw new Error('That workflow is not on your Workflows page, so FloLess cannot open it. Compile it from the terminal that installed it.');
18159
19176
  }
18160
19177
  await loadApp(appId);
18161
19178
  showWorkflowsLanding(false);
@@ -18168,7 +19185,21 @@
18168
19185
  // opened after the run) holds a different one or none. Say so instead of showing the wrong report.
18169
19186
  const gone = 'This window no longer holds that run\'s report: a newer run replaced it, or the window opened after it ran. Open the workflow to see its latest results.';
18170
19187
  const cached = lastReportByApp.get(appId);
18171
- if (!runId || cached?.runId !== runId) throw new Error(gone);
19188
+ if (!runId) throw new Error(gone);
19189
+ // #2266: a window opened (or reloaded) after the run reads the copy FloLess kept of THAT run's report, in the
19190
+ // workflow's Page. Never another run's: a report no longer kept says so.
19191
+ if (cached?.runId !== runId) {
19192
+ let kept = null;
19193
+ try { kept = await api(`/api/pages/workflow?app=${encodeURIComponent(appId)}&run=${encodeURIComponent(runId)}`); }
19194
+ catch { throw new Error('FloLess couldn’t read that run’s report just now. Try again, or open the workflow to see its latest results.'); }
19195
+ if (kept?.home && kept.page?.id && kept.shown?.kept === true) {
19196
+ if (typeof window.flolessPages?.open !== 'function') throw new Error('FloLess kept that run’s report, but this window cannot open Pages. Open it from the Pages list.');
19197
+ return await window.flolessPages.open(kept.home, kept.page.id, kept.shown.version);
19198
+ }
19199
+ throw new Error(kept?.shown?.note
19200
+ ? `${kept.shown.note} Open the workflow to see its latest results.`
19201
+ : 'FloLess did not keep a copy of that run’s report. Open the workflow to see its latest results.');
19202
+ }
18172
19203
  await this.openApp(appId);
18173
19204
  // Opening the workflow waits; a newer report may have arrived meanwhile. Show this run's report or nothing.
18174
19205
  if (lastReportByApp.get(appId) !== cached) throw new Error(gone);
@@ -18179,6 +19210,25 @@
18179
19210
  },
18180
19211
  // #1890 PR 3b: open a FloLess-owned workflow by its id — its published app when it has one, otherwise its draft
18181
19212
  // view — so a conversation that moved into it can be followed there. Throws a plain sentence when it is gone.
19213
+ // Project access: an archived workflow has no canvas to open, so show it where it can be restored — its card in the
19214
+ // Workflows list's Archived section, opened, scrolled to and focused on Restore. Throws a plain sentence when it is gone.
19215
+ async openArchivedWorkflow(workflowId) {
19216
+ await window.flolessWorkspaces?.setMode?.('workflows');
19217
+ // The switch can stay on the current tab (another workflow's read failed): never focus a card nobody can see.
19218
+ if (document.body.classList.contains('mode-workspaces') || document.body.classList.contains('mode-agents')) {
19219
+ throw new Error('FloLess could not switch to the Workflows tab just now. Open it and find the workflow under Archived.');
19220
+ }
19221
+ // The list is what is needed here, not any one workflow: a reload that fails keeps the list already on screen.
19222
+ try { await loadApps(); } catch (error) { console.warn('[project-access] the workflow list could not be read again', error); }
19223
+ showWorkflowsLanding(true);
19224
+ const card = [...($wfLanding?.querySelectorAll('[data-wf-archived]') || [])].find((el) => el.getAttribute('data-wf-archived') === workflowId);
19225
+ if (!card) throw new Error('That workflow is no longer in the Archived list, so FloLess cannot show it. It may have been restored or removed.');
19226
+ const box = card.closest('.wf-archived');
19227
+ if (box) box.open = true;
19228
+ card.scrollIntoView?.({ block: 'center' });
19229
+ card.querySelector('[data-wf-restore]')?.focus();
19230
+ return true;
19231
+ },
18182
19232
  async openOwnedWorkflow(workflowId) {
18183
19233
  await window.flolessWorkspaces?.setMode?.('workflows');
18184
19234
  await loadApps();
@@ -18253,6 +19303,11 @@
18253
19303
  refreshCurrentWorkflow() {
18254
19304
  return refreshCurrentWorkflow();
18255
19305
  },
19306
+ // The person-facing sentence of a module refusal (see reportErr), or '' for any other failure.
19307
+ moduleRefusalText,
19308
+ // The person-facing sentence of a lapsed sign-in or subscription (HTTP 402), or '' for any other failure.
19309
+ accountAccessText,
19310
+ reloadCompiledWorkflows,
18256
19311
  // Workspaces is a replacement surface. Invalidate a pending workflow-pin read as soon as it
18257
19312
  // opens, rather than allowing a late answer to survive behind the project UI until the return.
18258
19313
  clearKbInformed() {
@@ -18451,7 +19506,7 @@
18451
19506
  // Setup-first: if AWARE isn't ready, show the overlay and DEFER routing until it
18452
19507
  // is (the health poll + finishBootstrapReady → onBootstrapReady do the routing).
18453
19508
  let h = null;
18454
- try { h = await (await fetch('/api/health', { cache: 'no-store' })).json(); }
19509
+ try { h = await readHealth(); }
18455
19510
  catch { /* health unreachable → route now; the offline overlay handles a down server */ }
18456
19511
  if (h && h.bootstrap && h.bootstrap !== 'ready') {
18457
19512
  updateBootstrap({ status: h.bootstrap, reason: h.bootstrapReason ?? null, remediation: h.bootstrapRemediation ?? null });