@floless/app 0.154.0 → 0.155.1

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 (47) hide show
  1. package/dist/floless-server.cjs +49502 -37986
  2. package/dist/schemas/steel.model.v2.schema.json +19 -5
  3. package/dist/skills/floless-app-onboarding/SKILL.md +22 -13
  4. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +12 -8
  5. package/dist/skills/floless-app-steel-model/SKILL.md +23 -2
  6. package/dist/skills/floless-app-steel-takeoff/SKILL.md +158 -65
  7. package/dist/skills/floless-app-workflows/SKILL.md +23 -5
  8. package/dist/skills/floless-app-workflows/references/blender-exec.md +183 -0
  9. package/dist/skills/floless-app-workflows/references/dev-server-and-run-trace.md +27 -12
  10. package/dist/templates/blender-construction-sequence.flo +96 -0
  11. package/dist/web/agents.js +33 -13
  12. package/dist/web/app.css +275 -33
  13. package/dist/web/aware.js +745 -82
  14. package/dist/web/chat-question-card.js +477 -0
  15. package/dist/web/chat.css +177 -12
  16. package/dist/web/chat.js +1537 -717
  17. package/dist/web/commands-shell.js +424 -7
  18. package/dist/web/commands-steel.js +105 -4
  19. package/dist/web/guide.js +4 -3
  20. package/dist/web/index.html +96 -7
  21. package/dist/web/instructor.js +10 -9
  22. package/dist/web/left-pane.js +40 -3
  23. package/dist/web/media-player.js +234 -0
  24. package/dist/web/model-editor-contract.js +2 -0
  25. package/dist/web/model-editor-revit-adapter.js +1 -0
  26. package/dist/web/model-editor-steel-adapter.js +89 -1
  27. package/dist/web/model-panel-bridge.js +16 -2
  28. package/dist/web/model-view-query.js +590 -0
  29. package/dist/web/model-viewport-revit-adapter.js +15 -1
  30. package/dist/web/model-viewport-toolbar.js +5 -2
  31. package/dist/web/pages.js +592 -0
  32. package/dist/web/panels.js +2 -1
  33. package/dist/web/revit-editor.js +181 -16
  34. package/dist/web/run-progress.js +193 -0
  35. package/dist/web/run-strip.js +173 -0
  36. package/dist/web/steel-3d-core.js +70 -0
  37. package/dist/web/steel-editor.html +2751 -219
  38. package/dist/web/steel-frames-core.js +958 -0
  39. package/dist/web/steel-last-seen.js +315 -0
  40. package/dist/web/steel-marks-core.js +530 -0
  41. package/dist/web/steel-model-slim.js +95 -0
  42. package/dist/web/steel-model-v2-client-validation.js +14 -2
  43. package/dist/web/steel-model-v2-commands.js +258 -27
  44. package/dist/web/steel-model-v2-projection.js +78 -18
  45. package/dist/web/steel-read-confidence.js +11 -2
  46. package/dist/web/workspaces.js +416 -26
  47. package/package.json +3 -2
package/dist/web/aware.js CHANGED
@@ -109,6 +109,9 @@
109
109
  // explicitly via "Save inputs" (Ctrl+S) and rehydrated when the app opens.
110
110
  const LS_LAST_APP = 'floless:lastApp';
111
111
  const lsInputsKey = (id) => 'floless:inputs:' + id;
112
+ // #2228: the long run this tab is showing progress for (see the live-progress controller near runningFlo).
113
+ // Declared up here because syncRunControls reads it, and that runs during start-up.
114
+ let liveRun = null; // { appId, token, runId, owner, surface, view, shown, showTimer, lingerTimer, ended, startedAt }
112
115
  function loadSavedInputs(id) {
113
116
  try {
114
117
  const v = JSON.parse(localStorage.getItem(lsInputsKey(id)) || 'null');
@@ -518,6 +521,9 @@
518
521
  for (const raw of String(code).split(/\r?\n/)) {
519
522
  const line = raw.trim();
520
523
  if (line.startsWith('//')) { out.push(line.replace(/^\/\/+\s?/, '')); continue; }
524
+ // A Python (blender/exec) or Ruby (sketchup) script opens with `# …`. Only `#` followed by a space or
525
+ // nothing counts, so a C# directive (`#nullable`, `#region`) or a shebang (`#!`) never becomes prose.
526
+ if (/^#(\s|$)/.test(line)) { out.push(line.replace(/^#+\s?/, '')); continue; }
521
527
  if (line === '') { if (out.length) break; else continue; }
522
528
  break; // first real (non-comment, non-blank) line ends the header block
523
529
  }
@@ -538,7 +544,11 @@
538
544
  const inputs = n.inputs && Object.keys(n.inputs).length ? n.inputs : n.config;
539
545
  // The exec node's Roslyn C# (the actual script the host runs). null for
540
546
  // pure-agent nodes that carry no inline code.
541
- const execSource = n.config && typeof n.config.code === 'string' ? n.config.code : null;
547
+ // A builtin agent (blender/exec) takes its script as an input rather than in `config:` — the same
548
+ // authored code either way, so it gets the same Description and Code tab.
549
+ const execSource = n.config && typeof n.config.code === 'string' ? n.config.code
550
+ : n.inputs && typeof n.inputs.code === 'string' ? n.inputs.code : null;
551
+ const pythonSource = n.agent === 'blender';
542
552
  // Description tab: a plain-English explanation + a small input table that
543
553
  // EXCLUDES the code (code belongs to the Code tab, never dumped here).
544
554
  const plainDesc = execSource ? leadingComment(execSource) : '';
@@ -567,7 +577,9 @@
567
577
  // live host) that's `config.code` straight from the .flo — the same text
568
578
  // the host compiles, so "Debug in VS" attaches to exactly this. For
569
579
  // non-exec nodes there is no script; we show the resolved lockfile YAML.
570
- code: execSource
580
+ code: execSource && pythonSource
581
+ ? escapeHtml(`# ${n.agent}${n.command ? '.' + n.command : ''} · node "${n.id}" · live source from ~/.aware/apps/${app.id}/\n${execSource}`)
582
+ : execSource
571
583
  ? highlightCSharp(`// ${n.agent || n.kind}${n.command ? '.' + n.command : ''} · node "${n.id}" · live source from ~/.aware/apps/${app.id}/\n${execSource}`)
572
584
  : app.lock.present
573
585
  ? `<span class="cm"># ${escapeHtml(app.id)}.lock · node "${escapeHtml(n.id)}"</span>\n${escapeHtml(nodeYaml(n))}`
@@ -1104,6 +1116,80 @@
1104
1116
 
1105
1117
  let reportRunning = false;
1106
1118
  let cancelRequested = false;
1119
+ let activeManualRun = null;
1120
+ let stopPending = false;
1121
+
1122
+ function missingRunInputs(app, values) {
1123
+ return (app.inputs || []).filter((input) => {
1124
+ // A baked drawing was consumed during authoring; the approved run uses its baked data.
1125
+ if (input.readStrategy === 'bake') return false;
1126
+ // #2230: output-dir left empty is a choice, not a gap: FloLess gives the run its own folder, so what it renders
1127
+ // plays inside FloLess (server/run-media.ts).
1128
+ if (input.name === 'output-dir') return false;
1129
+ const value = values[input.name];
1130
+ const blank = value === undefined || value === null || String(value).trim() === '';
1131
+ const hasDefault = input.hasDefault === undefined ? input.default !== null && input.default !== undefined : input.hasDefault;
1132
+ return blank && (input.widget === 'workspace-model-revision' || !hasDefault);
1133
+ });
1134
+ }
1135
+
1136
+ async function askForMissingRunInputs(app) {
1137
+ const missing = missingRunInputs(app, currentInputs());
1138
+ if (!missing.length) return false;
1139
+ const names = missing.map((input) => input.label || input.name.replace(/_/g, ' ').toLowerCase()).join(', ');
1140
+ showToast(`Choose ${names} in Set inputs, then choose Run workflow. Nothing has started.`, 'info');
1141
+ await openInputsDialog({ focusInputName: missing[0].name });
1142
+ return true;
1143
+ }
1144
+
1145
+ function syncReportStopControls() {
1146
+ if (!$reportStop) return;
1147
+ $reportStop.hidden = !(foregroundTrigger || reportRunning && activeManualRun);
1148
+ $reportStop.disabled = cancelRequested || stopPending || foregroundStopping;
1149
+ $reportStop.textContent = cancelRequested ? 'Cancelling…' : stopPending || foregroundStopping ? 'Stopping…' : '■ Stop run';
1150
+ $reportStop.dataset.tip = foregroundTrigger ? 'Stop the live session — the report stops updating on each change' : 'Stop this workflow run';
1151
+ }
1152
+
1153
+ function beginManualRun(appId) {
1154
+ const request = { id: crypto.randomUUID(), appId, stopPromise: null, settled: false };
1155
+ activeManualRun = request;
1156
+ stopPending = false;
1157
+ return request;
1158
+ }
1159
+
1160
+ // Run's own outcome is authoritative, even if a Stop acknowledgement was lost or arrived later.
1161
+ async function dispatchManualRun(request, payload) {
1162
+ let result, error;
1163
+ try {
1164
+ result = await api('/api/run', { method: 'POST', body: JSON.stringify({ ...payload, runRequestId: request.id }) });
1165
+ } catch (caught) { error = caught; }
1166
+ // A Stop reply can disappear even after the server has settled this run. Its acknowledgement
1167
+ // cannot hold the authoritative result hostage or change it after completion.
1168
+ request.settled = true;
1169
+ if (activeManualRun === request) cancelRequested = !!(error && error.body && error.body.cancelled);
1170
+ if (error) throw error;
1171
+ return result;
1172
+ }
1173
+
1174
+ function finishManualRun(request) {
1175
+ request.settled = true;
1176
+ if (activeManualRun !== request) return;
1177
+ activeManualRun = null;
1178
+ stopPending = false;
1179
+ }
1180
+
1181
+ function stoppedRunCopy(body, report = false) {
1182
+ if (report) return 'Report cancelled. No report was saved.';
1183
+ if (body && body.error === 'Run stopped before execution started.') return 'Run stopped before execution started.';
1184
+ if (body && body.error === 'Simulated run stopped.') return 'Simulated run stopped.';
1185
+ return 'Run stopped. Work already sent to the host may remain.';
1186
+ }
1187
+
1188
+ function acceptsManualRunEvent(message) {
1189
+ if (message.runOrigin === 'panel' && !activeManualRun && !state.running && !reportRunning) return true;
1190
+ if (!message.runRequestId) return !activeManualRun;
1191
+ return !!activeManualRun && !cancelRequested && activeManualRun.id === message.runRequestId;
1192
+ }
1107
1193
  let runningSimulation = false;
1108
1194
  let foregroundTrigger = null;
1109
1195
  let foregroundStarting = false;
@@ -1185,7 +1271,7 @@
1185
1271
  // same state (it's the reachable Stop while the Viewer covers the header one).
1186
1272
  $runBtn.disabled = !app.runnable || reportRunning || state.running || foregroundStarting || foregroundStopping || !!foregroundTrigger;
1187
1273
  if ($stopRunBtn) $stopRunBtn.hidden = !(reportRunning || state.running || foregroundStopping || foregroundTrigger);
1188
- if ($reportStop) $reportStop.hidden = !foregroundTrigger;
1274
+ syncReportStopControls();
1189
1275
  const agentChanged = gateStateFor(app) === 'agent-changed';
1190
1276
  $runBtn.dataset.tip = agentChanged
1191
1277
  ? (app.approvalCheck
@@ -1728,10 +1814,9 @@
1728
1814
  return true;
1729
1815
  } catch (error) {
1730
1816
  const copied = await copyToClipboard(markedInstruction(request));
1731
- const chosen = runtime ? runtimeLabel(runtime) : 'your terminal AI';
1732
- showToast(copied
1733
- ? `Couldn’t start ${chosen}. Request queued and copied — paste it in your terminal.`
1734
- : `Couldn’t start ${chosen}. Request queued — open Requests to copy it.`, 'err');
1817
+ const workspaceProblem = ['instructor-workspace-root-changed', 'instructor-workspace-earlier-generation', 'instructor-workspace-unavailable'].includes(error?.code);
1818
+ showToast(workspaceProblem ? error.message
1819
+ : `AI Chat couldn’t start this answer. Your question is saved in Requests; open it there to try again.${copied ? ' The question is also copied.' : ''}`, 'err');
1735
1820
  try { await loadRequests(); } catch (refreshError) { console.error(refreshError); }
1736
1821
  activeInstructorRuns.delete(fingerprint);
1737
1822
  return false;
@@ -2096,6 +2181,7 @@
2096
2181
  setComboSelected(id);
2097
2182
  renderChat();
2098
2183
  renderTopology(); // selects first node + renderInspect
2184
+ syncRunStrip(); // #2228: a live run's strip shows only over the workflow it belongs to
2099
2185
  paintModes();
2100
2186
  markStars();
2101
2187
  seedAppInputs(app);
@@ -3005,7 +3091,8 @@
3005
3091
  // The input node is the first node templating {{ inputs.* }} ANYWHERE in its
3006
3092
  // config. An exec node carries it under `config.args`, but a REST/agent node
3007
3093
  // (e.g. floless-workspace/read-approved) carries it in a plain config field,
3008
- // so scan the whole config recursively — not just args.
3094
+ // so scan the whole config recursively — not just args. A node may also template them under `inputs:` rather
3095
+ // than `config:` (#2229: the Blender exec demo does), which the server hands over as `node.inputs`.
3009
3096
  const usesInput = (v) => {
3010
3097
  if (typeof v === 'string') return /\{\{\s*inputs\.[A-Za-z0-9._-]+\s*\}\}/.test(v);
3011
3098
  if (Array.isArray(v)) return v.some(usesInput);
@@ -3013,7 +3100,7 @@
3013
3100
  return false;
3014
3101
  };
3015
3102
  for (const n of app.nodes) {
3016
- if (n.config && usesInput(n.config)) return n.id;
3103
+ if ((n.config && usesInput(n.config)) || (n.inputs && usesInput(n.inputs))) return n.id;
3017
3104
  }
3018
3105
  return null;
3019
3106
  }
@@ -3755,20 +3842,20 @@
3755
3842
 
3756
3843
  // Double-click the input node → styled dialog to set the declared inputs. Writes
3757
3844
  // to appInputValues; the header "▶ Run workflow" uses them. No native window.prompt.
3758
- function openInputsDialog() {
3845
+ function openInputsDialog({ focusInputName = null } = {}) {
3759
3846
  const appId = currentId;
3760
3847
  const generation = workflowSelectionGeneration;
3761
3848
  if (!appId) return Promise.resolve();
3762
3849
  const active = inputDialogFlights.get(appId);
3763
3850
  if (active && active.generation === generation) return active.promise;
3764
- const promise = openInputsDialogFor(appId, generation).finally(() => {
3851
+ const promise = openInputsDialogFor(appId, generation, focusInputName).finally(() => {
3765
3852
  if (inputDialogFlights.get(appId)?.promise === promise) inputDialogFlights.delete(appId);
3766
3853
  });
3767
3854
  inputDialogFlights.set(appId, { generation, promise });
3768
3855
  return promise;
3769
3856
  }
3770
3857
 
3771
- async function openInputsDialogFor(appId, generation) {
3858
+ async function openInputsDialogFor(appId, generation, focusInputName = null) {
3772
3859
  const app = apps.get(appId);
3773
3860
  if (!app || !Array.isArray(app.inputs) || !app.inputs.length) return;
3774
3861
  const isCurrent = () => currentId === appId && workflowSelectionGeneration === generation;
@@ -3875,7 +3962,7 @@
3875
3962
  group: project.name, groupMeta: `${selectedModelName} model`, label: `Approved v${version.approvalVersion}`,
3876
3963
  triggerLabel: `${project.name} · approved v${version.approvalVersion} · ${short}${accepted ? ` · ${accepted}` : ''}`,
3877
3964
  meta: `${date} · ${short}${accepted ? ` · ${accepted}` : ''}`,
3878
- ariaLabel: `${project.name}, ${selectedModelName} model, approved version ${version.approvalVersion}, ${date}, revision ${version.approvedRevisionId}${accepted ? `, approved with ${accepted.replace(/ accepted$/, '')} accepted as stated assumptions` : ''}`,
3965
+ ariaLabel: `${project.name}, ${selectedModelName} model, approved version ${version.approvalVersion}, ${date}, revision ${short}${accepted ? `, approved with ${accepted.replace(/ accepted$/, '')} accepted as stated assumptions` : ''}`,
3879
3966
  search: `${project.name} ${selectedModelName} approved version ${version.approvalVersion} ${date} ${version.approvedRevisionId}`,
3880
3967
  };
3881
3968
  });
@@ -3917,7 +4004,7 @@
3917
4004
  value: cur[inp.name] != null ? cur[inp.name] : inp.default != null ? inp.default : '',
3918
4005
  };
3919
4006
  });
3920
- const res = await formModal({ title: `Inputs · ${app.displayName}`, sub: 'Set the values this run uses, then ▶ Run workflow.', fields, okLabel: 'Set inputs' });
4007
+ const res = await formModal({ title: `Inputs · ${app.displayName}`, sub: 'Set the values this run uses, then ▶ Run workflow.', fields, okLabel: 'Set inputs', focusInputName });
3921
4008
  if (!res || !isCurrent()) return;
3922
4009
  const store = {};
3923
4010
  for (const inp of app.inputs) {
@@ -3951,14 +4038,18 @@
3951
4038
  paintRunState(app); // The Instructor's set/total count follows Set inputs, not the next Run.
3952
4039
  markSpecialNodes();
3953
4040
  refreshDirtyIndicator(); // values changed → reflect unsaved state in the header/menu
3954
- const badge = Object.entries(store).map(([k, v]) => `${k}=${visualNames.has(k) ? String(v).split(/[\\/]/).pop() : v}`).join(' · ');
4041
+ const badge = Object.entries(store).map(([k, v]) => `${k}=${visualNames.has(k) ? String(v).split(/[\\/]/).pop() : workflowInputDisplayValue(fields.find((field) => field.name === k), v)}`).join(' · ');
3955
4042
  appendNarration(`Inputs set — <strong>${escapeHtml(badge)}</strong>. Run with <strong>▶ Run workflow</strong>.`);
3956
4043
  showToast('Inputs set: ' + badge, 'ok');
3957
4044
  }
3958
4045
 
3959
- // Set when the user hits Stop. api() throws a bare Error on the cancelled
3960
- // response (the {cancelled:true} flag is lost), so we read this flag in the
3961
- // run catch blocks to show "cancelled" rather than a misleading "run failed".
4046
+ // Selection JSON is an AWARE input carrier; people see the same name they picked.
4047
+ function workflowInputDisplayValue(field, value) {
4048
+ if (field?.commandId !== 'workflow.select-model-revision') return value;
4049
+ const option = field.options.find((item) => String(item.value) === String(value));
4050
+ return option ? option.triggerLabel || option.label : 'Previously selected model version unavailable';
4051
+ }
4052
+
3962
4053
  // The most recent rendered report per app id: { nodeId, label, html }. Lets a
3963
4054
  // double-click LOAD the last result instantly instead of re-running.
3964
4055
  const lastReportByApp = new Map();
@@ -3980,15 +4071,21 @@
3980
4071
  // the user, on the modal's × tooltip, that closing leaves the run going (Stop is in the
3981
4072
  // header) — the canvas keeps showing progress (markCanvasRunning), by design.
3982
4073
  function syncRunControls() {
3983
- const running = reportRunning || state.running || foregroundStarting || foregroundStopping || !!foregroundTrigger;
4074
+ // #2228: a run this tab resumed after a reload, or follows from another window, is live too: Run stays off for
4075
+ // that workflow until it ends (its own Stop is in the run strip).
4076
+ const followedRun = !!(liveRun && !liveRun.ended && liveRun.appId === currentId && !state.running && !reportRunning);
4077
+ const running = reportRunning || state.running || foregroundStarting || foregroundStopping || !!foregroundTrigger || followedRun;
3984
4078
  const stoppable = reportRunning || state.running || foregroundStopping || !!foregroundTrigger;
3985
- // The in-modal Stop is reachable only for a live foreground session (the header
3986
- // Stop is occluded by the report-modal backdrop). Show it while one is live.
3987
- if ($reportStop) $reportStop.hidden = !foregroundTrigger;
4079
+ // The persistent viewer Stop covers finite manual and live foreground work while
4080
+ // the modal backdrop occludes the header Stop.
4081
+ syncReportStopControls();
3988
4082
  if ($stopRunBtn) {
3989
4083
  $stopRunBtn.hidden = !stoppable;
3990
4084
  // Reset to a fresh, clickable Stop each run; stopRun() flips it to "Cancelling…".
3991
- if (stoppable && !cancelRequested && !foregroundStopping) { $stopRunBtn.disabled = false; $stopRunBtn.textContent = '■ Stop run'; }
4085
+ if (stoppable && !cancelRequested && !foregroundStopping) {
4086
+ $stopRunBtn.disabled = stopPending;
4087
+ $stopRunBtn.textContent = stopPending ? 'Stopping…' : '■ Stop run';
4088
+ }
3992
4089
  }
3993
4090
  if (running) {
3994
4091
  $runBtn.disabled = true;
@@ -4007,10 +4104,9 @@
4007
4104
  }
4008
4105
  }
4009
4106
 
4010
- // Stop the in-flight run (the escape hatch for a hung/unattached host). Marks
4011
- // cancelRequested so the catch shows "cancelled", clears the canvas running
4012
- // pulse, and asks the server to kill the `aware app run` child. The in-flight
4013
- // /api/run then rejects via api() and the catch renders the cancelled state.
4107
+ // Ask to stop this manual run by its request identity. The original run's
4108
+ // answer determines whether it stopped or finished; the Stop acknowledgement
4109
+ // alone must not relabel a completed report or clear another producer's work.
4014
4110
  async function stopRun() {
4015
4111
  if (!reportRunning && !state.running && !foregroundTrigger) return;
4016
4112
  // A live foreground session ends via its own stop route (it runs outside the
@@ -4021,8 +4117,6 @@
4021
4117
  foregroundStopping = true;
4022
4118
  foregroundTrigger = null;
4023
4119
  if ($stopRunBtn) { $stopRunBtn.disabled = true; $stopRunBtn.textContent = 'Stopping…'; }
4024
- const ovStop = document.querySelector('.overlay-stop');
4025
- if (ovStop) { ovStop.disabled = true; ovStop.textContent = 'Stopping…'; }
4026
4120
  syncRunControls();
4027
4121
  try { await api(`/api/trigger-run/${encodeURIComponent(ft.appId)}/stop`, { method: 'POST' }); } catch { /* best effort — the session may already be gone */ }
4028
4122
  finally {
@@ -4036,14 +4130,40 @@
4036
4130
  }
4037
4131
  return;
4038
4132
  }
4039
- cancelRequested = true;
4040
- clearNodeStatus();
4041
- // Reflect "cancelling" on BOTH Stop surfaces — the in-modal overlay and the header.
4042
- const stopBtn = document.querySelector('.overlay-stop');
4043
- if (stopBtn) { stopBtn.disabled = true; stopBtn.textContent = 'Cancelling…'; }
4044
- if ($stopRunBtn) { $stopRunBtn.disabled = true; $stopRunBtn.textContent = 'Cancelling…'; }
4133
+ const request = activeManualRun;
4134
+ if (!request || request.settled || stopPending || cancelRequested) return;
4135
+ stopPending = true;
4045
4136
  syncRunControls();
4046
- try { await api('/api/run/stop', { method: 'POST' }); } catch { /* the run's own catch surfaces it */ }
4137
+ request.stopPromise = (async () => {
4138
+ try {
4139
+ let answer;
4140
+ try {
4141
+ answer = await api('/api/run/stop', { method: 'POST', body: JSON.stringify({ runRequestId: request.id }) });
4142
+ } catch {
4143
+ if (activeManualRun !== request || request.settled) return;
4144
+ showToast('FloLess could not confirm Stop. Try Stop again; the run will confirm whether it stopped.', 'warn');
4145
+ return;
4146
+ }
4147
+ if (activeManualRun !== request || request.settled) return;
4148
+ cancelRequested = answer.accepted === true;
4149
+ if (cancelRequested) {
4150
+ clearNodeStatus();
4151
+ if (reportRunning) $reportSub.textContent = 'Cancelling this report run…';
4152
+ } else if (answer.reason === 'finishing') {
4153
+ if (reportRunning) $reportSub.textContent = 'Execution ended. Waiting for the outcome.';
4154
+ else showToast('Execution ended. Waiting for the outcome.', 'info');
4155
+ } else if (answer.pending) {
4156
+ if (reportRunning) $reportSub.textContent = 'Stop requested. Waiting for this run to confirm its outcome.';
4157
+ }
4158
+ } finally {
4159
+ if (activeManualRun === request && !request.settled) {
4160
+ stopPending = false;
4161
+ if ($stopRunBtn && cancelRequested) { $stopRunBtn.disabled = true; $stopRunBtn.textContent = 'Cancelling…'; }
4162
+ syncRunControls();
4163
+ }
4164
+ }
4165
+ })();
4166
+ await request.stopPromise;
4047
4167
  }
4048
4168
 
4049
4169
  // Share is visible exactly when the frame holds a report (the empty state HIDES it —
@@ -4081,21 +4201,36 @@
4081
4201
  $reportObjectError.textContent = '';
4082
4202
  $reportFrame.removeAttribute('src');
4083
4203
  }
4084
- async function paintCompleteReport(report, ordinal = 0) {
4204
+ async function paintCompleteReport(report, ordinal = null) {
4085
4205
  const request = ++reportSectionRequest;
4086
4206
  const handle = encodeURIComponent(report.handle);
4087
4207
  $reportOverlay.hidden = false;
4088
4208
  $reportOverlay.replaceChildren(mkEl('div', 'spinner'), mkEl('div', null, 'Loading report section…'));
4089
4209
  try {
4090
- const index = await api(`/api/model-reports/${handle}/index?at=${ordinal}`);
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}`);
4221
+ }
4222
+ }
4091
4223
  if (request !== reportSectionRequest) return;
4092
4224
  const response = await fetch(`/api/model-reports/${handle}/chunk/${ordinal}`, { credentials: 'same-origin', cache: 'no-store' });
4093
4225
  if (!response.ok) {
4094
4226
  const body = await response.json().catch(() => null);
4095
- throw new Error(body?.error || 'This report is no longer available. Run it again.');
4227
+ throw Object.assign(new Error('Report section request failed'), { status: response.status, body });
4096
4228
  }
4097
4229
  const length = Number(response.headers.get('content-length'));
4098
- if (Number.isFinite(length) && length > 1200 * 1024) throw new Error('This report section is too large to display safely.');
4230
+ if (Number.isFinite(length) && length > 1200 * 1024) {
4231
+ await response.body?.cancel();
4232
+ throw Object.assign(new Error('Report section exceeds viewer limit'), { status: 413 });
4233
+ }
4099
4234
  await response.body?.cancel();
4100
4235
  if (request !== reportSectionRequest) return;
4101
4236
  $reportFrame.removeAttribute('srcdoc');
@@ -4110,9 +4245,9 @@
4110
4245
  const properties = Number(index.propertyCount) || 0;
4111
4246
  const current = index.current || {};
4112
4247
  const objectRange = count === 0 ? 'No objects' : current.firstObject == null
4113
- ? `Model information · 0 of ${count} objects` : `Objects ${Number(current.firstObject) + 1}–${Number(current.lastObject) + 1} of ${count}`;
4248
+ ? `Model information · Report contains ${count} objects` : `Objects ${Number(current.firstObject) + 1}–${Number(current.lastObject) + 1} of ${count}`;
4114
4249
  const propertyRange = properties === 0 ? '0 properties'
4115
- : current.firstProperty == null ? `0 of ${properties} properties in this section`
4250
+ : current.firstProperty == null ? `Report contains ${properties} properties`
4116
4251
  : `Properties ${Number(current.firstProperty) + 1}–${Number(current.lastProperty) + 1} of ${properties}`;
4117
4252
  $reportSectionStatus.textContent = `${objectRange} · ${propertyRange} · section ${ordinal + 1} of ${index.chunkCount}`;
4118
4253
  updateReportSectionNavigation(ordinal, index);
@@ -4138,8 +4273,23 @@
4138
4273
  if (request !== reportSectionRequest) return;
4139
4274
  clearCompleteReportView();
4140
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.';
4286
+ currentCompleteReport = report;
4287
+ $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 });
4141
4291
  $reportOverlay.hidden = false;
4142
- $reportOverlay.replaceChildren(mkEl('div', null, error?.message || 'This report could not be displayed. Run it again.'));
4292
+ $reportOverlay.replaceChildren(mkEl('div', null, remedy));
4143
4293
  }
4144
4294
  }
4145
4295
  // The share route's user-facing cap (server/index.ts sets a 6 MB body limit; the JSON envelope
@@ -4212,7 +4362,7 @@
4212
4362
  const cached = lastReportByApp.get(currentId);
4213
4363
  if (cached && cached.handle) {
4214
4364
  $reportTitle.textContent = `HTML Viewer · ${app.displayName}`;
4215
- void paintCompleteReport(cached, 0);
4365
+ void paintCompleteReport(cached);
4216
4366
  } else if (cached && cached.html) {
4217
4367
  const sfx = cached.label ? ' · ' + cached.label : '';
4218
4368
  if (cached.interactive) {
@@ -4905,23 +5055,39 @@
4905
5055
  if (!app) return;
4906
5056
  if (!app.runnable) { showToast('Compile the workflow first — Run is gated on a fresh lock.', 'warn'); return; }
4907
5057
  if (reportRunning) return;
5058
+ if (await askForMissingRunInputs(app)) return;
5059
+ if (currentId !== app.id || reportRunning || state.running || foregroundStarting || foregroundStopping || foregroundTrigger) return;
5060
+ const request = opts.debug ? null : beginManualRun(app.id);
4908
5061
  reportRunning = true;
4909
5062
  cancelRequested = false;
4910
5063
  markCanvasRunning(); // paints behind the modal; visible once it's closed
4911
5064
  syncRunControls(); // header ■ Stop run + Run disabled — reachable even if the modal is closed (#39)
4912
5065
 
4913
5066
  const inputs = currentInputs();
4914
- const inputBadge = Object.entries(inputs).map(([k, v]) => `${k}=${v}`).join(' · ');
5067
+ const inputBadge = Object.entries(inputs).map(([k, v]) => `${k}=${app.inputs?.some((input) => input.name === k && input.widget === 'workspace-model-revision') ? 'Selected approved model version' : v}`).join(' · ');
4915
5068
  const approvedModelReport = app.templateId === 'floless-workspace-model-report' || app.templateId === 'tekla-model-report';
4916
5069
  $reportTitle.textContent = `HTML Viewer · ${app.displayName}`;
4917
5070
  $reportSub.textContent = 'Running the workflow to create your report.';
4918
5071
  clearReportFrames(); // clear any previous report (static or 3D) before this run paints a fresh one
4919
5072
  $reportShare.hidden = true; // the frame is blank — only a painted report is shareable
4920
5073
  $reportOverlay.hidden = false;
4921
- $reportOverlay.innerHTML = opts.debug
4922
- ? `<div>Launching the .NET debugger for <code>${escapeHtml(nodeId)}</code> — a Windows picker will pop; choose your <strong>Visual Studio</strong> to attach to <code>aware-tekla.exe</code>, then step through. The report renders when you let it finish.</div>`
4923
- : `<div>${approvedModelReport ? 'Reading the selected approved model to make a complete, read-only report…' : `Running <code>${escapeHtml(currentId)}</code> against the live model…`}</div><button type="button" class="overlay-stop">■ Stop run</button>`;
4924
- $reportOverlay.prepend(runningFlo());
5074
+ let clientRunToken = null;
5075
+ if (opts.debug) {
5076
+ $reportOverlay.innerHTML = `<div>Launching the .NET debugger for <code>${escapeHtml(nodeId)}</code> — a Windows picker will pop; choose your <strong>Visual Studio</strong> to attach to <code>aware-tekla.exe</code>, then step through. The report renders when you let it finish.</div>`;
5077
+ $reportOverlay.prepend(runningFlo());
5078
+ } else {
5079
+ // #2228: the working Flo, what the run is doing, elapsed time and a real bar when the run reports one —
5080
+ // the same view the canvas strip uses, so a long render reads the same in both places.
5081
+ $reportOverlay.replaceChildren();
5082
+ const host = mkEl('div', 'rp-host');
5083
+ $reportOverlay.append(host); // Stop lives in the report header (#reportStop), beside the run it stops
5084
+ clientRunToken = beginLiveRun(currentId, 'overlay', host,
5085
+ approvedModelReport ? 'Reading the selected approved model to make a complete, read-only report…' : 'Running the workflow against the live model…');
5086
+ if (!host.firstChild) $reportOverlay.prepend(runningFlo()); // the view could not mount: keep the working Flo
5087
+ }
5088
+ let liveOutcome = 'failed';
5089
+ const $reportWatch = document.getElementById('report-watch');
5090
+ if ($reportWatch) $reportWatch.hidden = true;
4925
5091
  showModal($reportModal);
4926
5092
  $reportModal.dataset.nodeId = nodeId;
4927
5093
 
@@ -4930,18 +5096,25 @@
4930
5096
  // so VS attaches to aware-tekla.exe; a normal run goes through aware app run.
4931
5097
  const res = opts.debug
4932
5098
  ? await api('/api/debug-node', { method: 'POST', body: JSON.stringify({ id: currentId, nodeId, inputs }) })
4933
- : await api('/api/run', { method: 'POST', body: JSON.stringify({ id: currentId, simulate: false, inputs }) });
5099
+ : await dispatchManualRun(request, { id: app.id, simulate: false, inputs, ...(clientRunToken ? { clientRunToken } : {}) });
5100
+ liveOutcome = 'ok';
5101
+ const reportVideos = runVideos(res);
5102
+ if (res && typeof res.mediaWarning === 'string') showToast(res.mediaWarning, 'warn');
5103
+ if ($reportWatch && reportVideos.length) {
5104
+ $reportWatch.hidden = false;
5105
+ $reportWatch.onclick = () => watchRunVideos(reportVideos, `Rendered by ${app.displayName}`);
5106
+ }
4934
5107
  // Reflect the run in the Execution tab too.
4935
5108
  if (Array.isArray(res.events)) { liveTrace.length = 0; res.events.forEach(pushTrace); state.hasRun = true; if (state.currentTab === 'execution') renderInspect(); }
4936
5109
  // A run can "succeed" yet carry a rejected token (the report would be an error
4937
5110
  // body, not real data) — prompt reconnect instead of rendering the noise.
4938
- if (res.credentialIssue) { surfaceCredentialIssue(res.credentialIssue); return; }
5111
+ if (res.credentialIssue) { $reportSub.textContent = 'Execution ended. Reconnect the integration to run again.'; surfaceCredentialIssue(res.credentialIssue); return; }
4939
5112
  if (res.report && res.report.kind === 'complete-model-properties' && typeof res.report.handle === 'string') {
4940
5113
  $reportTitle.textContent = `HTML Viewer · ${app.displayName}`;
4941
- await paintCompleteReport(res.report, 0);
4942
- if (!currentCompleteReport) return;
4943
- markFirstRunDone(app.id);
4944
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);
4945
5118
  $reportModal.dataset.html = '1';
4946
5119
  appendNarration(`Rendered the complete read-only property report from <strong>${escapeHtml(nodeId)}</strong>.`);
4947
5120
  return;
@@ -4949,6 +5122,7 @@
4949
5122
  const html = res.report && res.report.html;
4950
5123
  const interactive = !!(res.report && res.report.interactive);
4951
5124
  if (!html) {
5125
+ $reportSub.textContent = 'Execution ended without an HTML report.';
4952
5126
  $reportOverlay.innerHTML = `<div>Run completed but <code>${escapeHtml(nodeId)}</code> returned no <code>html</code>. Check the Execution tab.</div>`;
4953
5127
  return;
4954
5128
  }
@@ -4968,26 +5142,33 @@
4968
5142
  appendNarration(`Rendered the ${interactive ? '3D view' : 'report'} from <strong>${escapeHtml(nodeId)}</strong>${inputBadge ? ' (' + escapeHtml(inputBadge) + ')' : ''} — live run against the model.`);
4969
5143
  } catch (e) {
4970
5144
  const msg = e && e.message ? e.message : String(e);
4971
- if (cancelRequested) {
5145
+ liveOutcome = (e && e.body && e.body.cancelled) ? 'stopped' : !(e && e.status) ? 'no-answer'
5146
+ : (e && e.body && (e.body.notRun || e.body.refusal)) ? 'not-run' : 'failed';
5147
+ if (e.body && e.body.cancelled) {
4972
5148
  // User hit Stop — an expected outcome, not a failure. A node already
4973
5149
  // executing on the host may still finish; the run result is discarded.
4974
5150
  clearNodeStatus(); // wipe any status painted before the flag was set
4975
- $reportOverlay.innerHTML = `<div>Run cancelled. A node already running on the host may still finish there; click <strong>▶ Run workflow</strong> to run again.</div>`;
5151
+ $reportSub.textContent = 'Execution stopped.';
5152
+ $reportOverlay.innerHTML = `<div>${stoppedRunCopy(e.body, approvedModelReport)} Click <strong>▶ Run workflow</strong> to run again.</div>`;
4976
5153
  showToast('Run cancelled', 'info');
4977
5154
  } else {
4978
5155
  // Expected, recoverable failure. If it was a rejected token, prompt the
4979
5156
  // user to reconnect that integration (not the misleading host hint).
4980
5157
  const cred = e.body && e.body.credentialIssue;
4981
5158
  if (cred) {
5159
+ $reportSub.textContent = 'Execution ended. Reconnect the integration to run again.';
4982
5160
  surfaceCredentialIssue(cred);
4983
5161
  } else {
4984
5162
  // Other recoverable failures (host not attached, stale lock, …): show it
4985
5163
  // in the viewer overlay + a toast. No console.error — the server returns the
4986
5164
  // failure in-band, so a failed run isn't a console-worthy fault.
5165
+ $reportSub.textContent = 'Execution ended without a report.';
4987
5166
  showRunFailure(e.body || {}, runFailureMessage(msg), app);
4988
5167
  }
4989
5168
  }
4990
5169
  } finally {
5170
+ if (request) finishManualRun(request);
5171
+ if (clientRunToken) { if (liveOutcome === 'no-answer') settleLiveRunWithoutAnswer(); else finishLiveRun(liveOutcome); }
4991
5172
  reportRunning = false;
4992
5173
  syncRunControls(); // run ended — hide the header Stop, restore Run from the gate
4993
5174
  }
@@ -5299,7 +5480,7 @@
5299
5480
  // `onChange(values) -> string` makes the dialog able to answer a question no static label can:
5300
5481
  // one whose answer DEPENDS on the choices (five viewpoints cost five times one). Its return value
5301
5482
  // becomes the footnote line under the fields. Optional — dialogs that don't pass it are unchanged.
5302
- function formModal({ title, sub = '', fields, okLabel = 'Save', okCommandId = null, okCommandInstanceLabel = null, cancelCommandInstanceLabel = null, danger = false, safeDefault = false, hideCancel = false, hideOk = false, returnFocusTo = null, returnFocusFallback = null, footnote = '', onChange = null, modalState = null, modalMode = null }) {
5483
+ function formModal({ title, sub = '', fields, okLabel = 'Save', okCommandId = null, okCommandInstanceLabel = null, cancelCommandInstanceLabel = null, danger = false, safeDefault = false, hideCancel = false, hideOk = false, returnFocusTo = null, returnFocusFallback = null, focusInputName = null, footnote = '', onChange = null, modalState = null, modalMode = null }) {
5303
5484
  return new Promise((resolve) => {
5304
5485
  if (_formModalOpen) { console.warn('formModal: a modal is already open — refusing re-entry'); resolve(null); return; }
5305
5486
  const returnFocus = returnFocusTo instanceof HTMLElement
@@ -5458,7 +5639,7 @@
5458
5639
  } else {
5459
5640
  const fieldCommand = f.commandId === 'shell.new-workflow-name'
5460
5641
  ? ' data-command-id="shell.new-workflow-name"'
5461
- : '';
5642
+ : f.commandId === 'shell.revision-note-text' ? ' data-command-id="shell.revision-note-text"' : '';
5462
5643
  ctl = f.multiline
5463
5644
  ? `<textarea id="${id}" rows="4" data-fm="${escapeHtml(f.name)}" placeholder="${ph}"${fieldCommand}>${escapeHtml(val)}</textarea>`
5464
5645
  : `<input id="${id}" type="${f.type || 'text'}"${f.type === 'number' ? ' step="1"' : ''} data-fm="${escapeHtml(f.name)}" value="${escapeHtml(val)}" placeholder="${ph}"${fieldCommand}>`;
@@ -5472,7 +5653,7 @@
5472
5653
  `<div class="fm-footnote" data-fm-footnote role="status" aria-live="polite"${footnote ? '' : ' hidden'}>${escapeHtml(footnote)}</div>`);
5473
5654
  }
5474
5655
  $ok.textContent = okLabel;
5475
- const allowedOkCommand = okCommandId === 'shell.host-send-continue' || okCommandId === 'shell.dialog-close';
5656
+ const allowedOkCommand = okCommandId === 'shell.host-send-continue' || okCommandId === 'shell.dialog-close' || okCommandId === 'shell.revision-note-save';
5476
5657
  $ok.setAttribute('data-command-id', allowedOkCommand
5477
5658
  ? `${okCommandId}#${okCommandInstanceLabel || 'the dialog'}`
5478
5659
  : 'shell.form-submit');
@@ -5915,7 +6096,11 @@
5915
6096
  // no-op. Gate first, then put focus on an enabled action. In an empty required picker, gating disables
5916
6097
  // OK; focusing it before this point made Chromium drop focus outside the modal and bypass the
5917
6098
  // Escape/Tab trap. The themed Reload action is the useful first stop when one is available.
5918
- const first = $body.querySelector('input:not(.fm-file-input):not([type="hidden"]):not(.wf-search),textarea')
6099
+ const focusCarrier = focusInputName ? Array.from($body.querySelectorAll('[data-fm],[data-fm-file-box],[data-fm-files],[data-fm-images]'))
6100
+ .find((el) => [el.dataset.fm, el.dataset.fmFileBox, el.dataset.fmFiles, el.dataset.fmImages].includes(focusInputName)) : null;
6101
+ const requestedFocus = focusCarrier?.matches(':disabled,[type="hidden"],.fm-file-input,.fm-file,.fm-files,.fm-images')
6102
+ ? focusCarrier.closest('.modal-field')?.querySelector('.fm-select-trigger:not([disabled]),.fm-drop,[data-fm-empty-action]:not([disabled])') : focusCarrier;
6103
+ const first = requestedFocus || $body.querySelector('input:not(.fm-file-input):not([type="hidden"]):not(.wf-search),textarea')
5919
6104
  || $body.querySelector('.fm-select-trigger:not([disabled])')
5920
6105
  || $body.querySelector('.fm-files .fm-drop, .fm-file .fm-drop, .fm-images .fm-drop')
5921
6106
  || $body.querySelector('[data-fm-empty-action]:not([disabled])');
@@ -6075,9 +6260,6 @@
6075
6260
  void closeReportViewer();
6076
6261
  }
6077
6262
  });
6078
- // The Stop button is rebuilt into the overlay each run — delegate so one
6079
- // listener survives every innerHTML swap.
6080
- $reportOverlay.addEventListener('click', (e) => { if (e.target.closest('.overlay-stop')) stopRun(); });
6081
6263
  // The interactive 3D doc (viewer-3d) posts a load handshake from its opaque-origin frame:
6082
6264
  // `viewer-ready` clears the loading overlay; `viewer-error` (CDN/script/timeout) shows a
6083
6265
  // retry. Guard: only when the 3D frame is the active surface and the message is from it.
@@ -8945,6 +9127,8 @@
8945
9127
  if (!app) return;
8946
9128
  if (!app.runnable) { showToast($runBtn.dataset.tip, 'warn'); return; }
8947
9129
  if (state.running || reportRunning || foregroundStarting || foregroundStopping || foregroundTrigger) return;
9130
+ if (!simulate && await askForMissingRunInputs(app)) return;
9131
+ if (currentId !== app.id || state.running || reportRunning || foregroundStarting || foregroundStopping || foregroundTrigger) return;
8948
9132
 
8949
9133
  // Streaming/watch app → a LIVE FOREGROUND session, not a finite run (which would
8950
9134
  // never complete and time out at 60s). It re-renders the report in the Viewer on
@@ -8959,6 +9143,7 @@
8959
9143
  if (!simulate && rid) { runReport(rid); return; }
8960
9144
 
8961
9145
  runningSimulation = simulate;
9146
+ const request = beginManualRun(app.id);
8962
9147
  state.running = true;
8963
9148
  cancelRequested = false;
8964
9149
  $runBtn.disabled = true;
@@ -8967,8 +9152,17 @@
8967
9152
  syncRunControls(); // surface the header ■ Stop run for the inline (no-modal) run too (#39)
8968
9153
  liveTrace.length = 0;
8969
9154
  state.hasRun = true;
9155
+ // #2228: a simulated run stubs every node, so it reports no progress; a real one is watched live.
9156
+ const clientRunToken = simulate ? null : beginLiveRun(currentId, 'strip');
9157
+ let liveOutcome = 'failed';
8970
9158
  try {
8971
- const res = await api('/api/run', { method: 'POST', body: JSON.stringify({ id: currentId, simulate, inputs: currentInputs() }) });
9159
+ const runAppId = currentId;
9160
+ const res = await dispatchManualRun(request, { id: app.id, simulate, inputs: currentInputs(), ...(clientRunToken ? { clientRunToken } : {}) });
9161
+ liveOutcome = 'ok';
9162
+ const videos = runVideos(res);
9163
+ if (videos.length) { finishLiveRun('ok'); offerRunVideos(runAppId, videos); }
9164
+ // #2230: the run worked, but what it rendered could not be readied for playing here — say so, and where it is.
9165
+ if (res && typeof res.mediaWarning === 'string') showToast(res.mediaWarning, 'warn');
8972
9166
  // SSE usually fills liveTrace first; backfill from the response if it didn't.
8973
9167
  if (liveTrace.length === 0 && Array.isArray(res.events)) res.events.forEach(pushTrace);
8974
9168
  // A "succeeded" run carrying a rejected token → prompt reconnect, not a result.
@@ -8980,10 +9174,17 @@
8980
9174
  : `Run complete · ${steps} node${steps === 1 ? '' : 's'} against the live model · see the <strong>Execution</strong> tab.`);
8981
9175
  if (!simulate) markFirstRunDone(app.id); // a real run completed → calm the beacon (app captured pre-await)
8982
9176
  } catch (e) {
8983
- if (cancelRequested) {
9177
+ liveOutcome = (e && e.body && e.body.cancelled) ? 'stopped'
9178
+ : !(e && e.status) ? 'no-answer' // the request itself was lost (reload, dropped connection), not the run
9179
+ : (e && e.body && (e.body.notRun || e.body.refusal)) ? 'not-run' : 'failed';
9180
+ if (e.body && e.body.cancelled) {
8984
9181
  clearNodeStatus();
8985
9182
  showToast('Run cancelled', 'info');
8986
- appendNarration('Run cancelled. Click <strong>▶ Run workflow</strong> to run again.');
9183
+ appendNarration(stoppedRunCopy(e.body, !simulate && (app.templateId === 'floless-workspace-model-report' || app.templateId === 'tekla-model-report')) + ' Click <strong>▶ Run workflow</strong> to run again.');
9184
+ } else if (liveOutcome === 'no-answer' && clientRunToken) {
9185
+ // #2228: the request was lost, not the run — which may still be working. The strip says how it ends
9186
+ // once FloLess answers again; reporting a failure here would contradict it.
9187
+ appendNarration('Lost touch with FloLess while the run was working. The strip above the canvas shows how it ends once FloLess is back.');
8987
9188
  } else {
8988
9189
  const cred = e.body && e.body.credentialIssue;
8989
9190
  if (cred) {
@@ -9010,6 +9211,8 @@
9010
9211
  }
9011
9212
  }
9012
9213
  } finally {
9214
+ finishManualRun(request);
9215
+ if (clientRunToken) { if (liveOutcome === 'no-answer') settleLiveRunWithoutAnswer(); else finishLiveRun(liveOutcome); }
9013
9216
  state.running = false;
9014
9217
  runningSimulation = false;
9015
9218
  $runBtn.disabled = false;
@@ -9055,7 +9258,8 @@
9055
9258
  }
9056
9259
  function clearNodeStatus() {
9057
9260
  document.querySelectorAll('.agent-card').forEach((card) => {
9058
- card.classList.remove('node-running', 'node-done', 'node-error');
9261
+ card.classList.remove('node-running', 'node-done', 'node-error', 'has-progress');
9262
+ card.style.removeProperty('--node-progress');
9059
9263
  const pip = card.querySelector('.node-stat');
9060
9264
  if (pip) pip.remove();
9061
9265
  });
@@ -9068,6 +9272,18 @@
9068
9272
  }
9069
9273
 
9070
9274
  function pushTrace(ev) {
9275
+ // #2228: a long render reports every frame. The Execution tab keeps ONE row per node and pass, updated in
9276
+ // place ("render 143 of 240 · pass 1 of 1"), so a 1,000-frame animation cannot bury the steps that matter.
9277
+ if (ev.kind === 'node-progress') {
9278
+ const d = ev.data && typeof ev.data === 'object' ? ev.data : {};
9279
+ const key = `${ev.node || ''}|${d.phase || ''}|${d.message || ''}`;
9280
+ const count = typeof d.done === 'number' ? ` ${d.done}${typeof d.total === 'number' ? ' of ' + d.total : ''}` : '';
9281
+ const msg = `progress ${escapeHtml(ev.node || '')} · ${escapeHtml(d.phase || '')}${count}${d.message ? ' · ' + escapeHtml(d.message) : ''}`;
9282
+ const row = liveTrace.length && liveTrace[liveTrace.length - 1];
9283
+ if (row && row.kind === 'node-progress' && row.progressKey === key) { row.msg = msg; row.ts = fmtTs(ev.ts); return; }
9284
+ liveTrace.push({ kind: ev.kind, ts: fmtTs(ev.ts), lvl: 'info', msg, node: ev.node || '', progressKey: key });
9285
+ return;
9286
+ }
9071
9287
  const node = escapeHtml(ev.node || '');
9072
9288
  const agent = escapeHtml(ev.agent || '');
9073
9289
  const cmd = ev.command ? '/' + escapeHtml(ev.command) : '';
@@ -9672,6 +9888,8 @@
9672
9888
  // Scheduled reports may finish with every browser closed; refresh their authorized
9673
9889
  // pointers on both first connection and reconnect, never from SSE payload data.
9674
9890
  void refreshSelectedCompleteReportDiscovery(currentId);
9891
+ // #2228: progress events are at-most-once too — a reload or a reconnect asks where this tab's run is.
9892
+ void resyncLiveRun();
9675
9893
  everOpened = true;
9676
9894
  };
9677
9895
  es.onmessage = (e) => {
@@ -9690,6 +9908,27 @@
9690
9908
  // it immediately; the init-time adopt() only covers tabs opened after it began. adopt() is
9691
9909
  // single-flight and idempotent, so the two racing is fine.
9692
9910
  if (window.awareUpdateController) window.awareUpdateController.adopt().catch(() => {});
9911
+ } else if (m.type === 'run-live' || m.type === 'node-progress' || m.type === 'run-finished') {
9912
+ // #2228: live progress of a long run. This tab's own run is matched by its token; a run of the
9913
+ // workflow this tab shows that someone else started is followed read-only (no Stop).
9914
+ if (liveRunOwns(m)) {
9915
+ if (m.type === 'run-live') { if (m.runId) liveRun.runId = m.runId; }
9916
+ else if (m.type === 'node-progress') onLiveProgress(m);
9917
+ else finishLiveRun(typeof m.outcome === 'string' ? m.outcome : 'failed');
9918
+ } else if (m.id === currentId && !(liveRun && liveRun.owner && !liveRun.ended)) {
9919
+ if (m.type === 'run-finished') {
9920
+ if (liveRun && !liveRun.owner && (!m.runId || m.runId === liveRun.runId)) finishLiveRun(typeof m.outcome === 'string' ? m.outcome : 'failed');
9921
+ } else {
9922
+ if (!liveRun || liveRun.ended || (m.runId && liveRun.runId && m.runId !== liveRun.runId)) observeLiveRun(m);
9923
+ if (m.type === 'node-progress') onLiveProgress(m);
9924
+ }
9925
+ }
9926
+ } else if (m.type === 'run-media' && Array.isArray(m.media)) {
9927
+ // #2230: the videos a run rendered, for a tab that lost the Run answer (a reload mid-run). The tab that
9928
+ // still holds the answer offers them from it; offerRunVideos is idempotent either way.
9929
+ const videos = m.media.filter((x) => x && x.kind === 'video' && typeof x.url === 'string');
9930
+ const mine = liveRun && ((m.clientRunToken && liveRun.token === m.clientRunToken) || (m.runId && liveRun.runId === m.runId));
9931
+ if (videos.length && (mine || m.id === currentId)) offerRunVideos(m.id, videos);
9693
9932
  } else if (m.type === 'render-progress') {
9694
9933
  // Relayed as a DOM event rather than widening the bridge: workspaces.js owns the Exports
9695
9934
  // card and is the only listener, and a render can outlive several repaints of it.
@@ -9745,17 +9984,17 @@
9745
9984
  // The event is only an invalidation. Re-read the workflow-scoped pin so the server remains
9746
9985
  // the source of truth; refresh clears first and its epoch rejects any older response.
9747
9986
  refreshKbInformed(currentId);
9748
- } else if (m.type === 'trace' && m.id === currentId) {
9987
+ } else if (m.type === 'trace' && m.id === currentId && acceptsManualRunEvent(m)) {
9749
9988
  pushTrace(m.event);
9750
9989
  if (state.currentTab === 'execution') renderInspect();
9751
- } else if (m.type === 'trace-file' && m.id === currentId && !state.running) {
9990
+ } else if (m.type === 'trace-file' && m.id === currentId && !state.running && !reportRunning && !activeManualRun) {
9752
9991
  // A terminal-driven run wrote a trace for the open app (our own UI runs
9753
9992
  // are handled by the type:'trace' path above and skipped via state.running).
9754
9993
  liveTrace.length = 0;
9755
9994
  (m.events || []).forEach(pushTrace);
9756
9995
  state.hasRun = true;
9757
9996
  if (state.currentTab === 'execution') renderInspect();
9758
- } else if (m.type === 'run-started' && m.id === currentId) {
9997
+ } else if (m.type === 'run-started' && m.id === currentId && acceptsManualRunEvent(m)) {
9759
9998
  liveTrace.length = 0;
9760
9999
  state.hasRun = true;
9761
10000
  } else if (m.type === 'templates-changed') {
@@ -9859,6 +10098,8 @@
9859
10098
  // The terminal AI (or undo/reset) rewrote ~/.floless/ui/extensions.json —
9860
10099
  // re-render the Dashboard / inspect-tab panels live. panels.js owns it.
9861
10100
  if (window.flolessPanels) window.flolessPanels.refresh({ fromChange: true });
10101
+ } else if (m.type === 'revision-note-changed') {
10102
+ window.dispatchEvent(new CustomEvent('floless:revision-note-changed', { detail: m }));
9862
10103
  } else if (m.type === 'run-ended') {
9863
10104
  // Panel data bindings (last-run-output/-status) go stale after any run.
9864
10105
  if (window.flolessPanels) window.flolessPanels.refreshData();
@@ -9885,6 +10126,8 @@
9885
10126
  applyTriggerReport(m);
9886
10127
  } else if (m.type === 'routine-report') {
9887
10128
  applyRoutineReport(m);
10129
+ } else if (m.type === 'action-run-report') {
10130
+ applyActionRunReport(m);
9888
10131
  } else if (m.type === 'routine-report-changed') {
9889
10132
  if (typeof m.id === 'string') void refreshRoutineReportDiscovery(m.id);
9890
10133
  } else if (m.type === 'connect-result') {
@@ -11496,7 +11739,7 @@
11496
11739
  const unreadable = link?.chatState === 'unreadable';
11497
11740
  const linked = Boolean(link?.chatId) && !unreadable;
11498
11741
  const provider = preferredChatProvider();
11499
- const inScope = Boolean(r.project || r.workflowId) && requestMatchesChatScope(r);
11742
+ const inScope = requestHasChatOwner(r) && requestMatchesChatScope(r);
11500
11743
  const chatLabel = `${label}${owner ? ` for ${owner}` : ''}`;
11501
11744
  // #2185: a request that was set aside (not deleted) says why, and can be brought back exactly as it was.
11502
11745
  const soft = r.lifecycle && typeof r.lifecycle === 'object' ? r.lifecycle : null;
@@ -11507,8 +11750,8 @@
11507
11750
  let action = '';
11508
11751
  if (provider && inScope) {
11509
11752
  action = `<button class="req-chat-action" data-done-chat="${linked ? 'open' : 'discuss'}" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-done-discuss#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="${linked ? 'Open the chat for' : 'Discuss'} ${escapeAttr(chatLabel)} in AI Chat" data-tip="${linked ? 'Open this request’s conversation in AI Chat' : 'Start a conversation about this request in AI Chat. Nothing runs.'}">${linked ? 'Open chat' : 'Discuss in AI Chat'}</button>`;
11510
- } else if (provider && (r.project || r.workflowId)) {
11511
- action = `<span class="req-chat-elsewhere" data-tip="Open ${escapeAttr(owner)} to open this request’s conversation">Open ${escapeHtml(owner)} for AI Chat</span>`;
11753
+ } else if (provider && requestHasChatOwner(r)) {
11754
+ action = `<span class="req-chat-elsewhere" data-tip="${escapeAttr(requestChatScopeReason(r))}">${escapeHtml(requestChatScopeReason(r))}</span>`;
11512
11755
  } else if (!provider) {
11513
11756
  action = '<span class="req-chat-elsewhere" data-tip="AI Chat needs Claude or Codex on this computer">AI Chat isn’t available</span>';
11514
11757
  }
@@ -11839,9 +12082,26 @@
11839
12082
  if (request.type === 'new-workflow' && request.buildId && request.workflowId) {
11840
12083
  return scope.owner.kind === 'workflow' && request.workflowId === scope.owner.workflowId;
11841
12084
  }
11842
- return scope.owner.kind === 'project'
11843
- ? request.project === scope.owner.projectId
11844
- : request.workflowId === scope.owner.workflowId;
12085
+ if (request.project) return scope.owner.kind === 'project' && request.project === scope.owner.projectId;
12086
+ if (request.workflowId) return scope.owner.kind === 'workflow' && request.workflowId === scope.owner.workflowId;
12087
+ return workspaceInstructorRequest(request) && scope.owner.kind === 'workspace'
12088
+ && (request.instructorWorkspaceState === 'current'
12089
+ || (!request.instructorWorkspaceRootId && !request.instructorWorkspaceState));
12090
+ }
12091
+
12092
+ function workspaceInstructorRequest(request) {
12093
+ return !!request && request.type === 'guide' && !!request.instructorContext && !request.project && !request.workflowId;
12094
+ }
12095
+
12096
+ function requestHasChatOwner(request) {
12097
+ return !!request && !!(request.project || request.workflowId || workspaceInstructorRequest(request));
12098
+ }
12099
+
12100
+ function requestChatScopeReason(request) {
12101
+ if (workspaceInstructorRequest(request)) {
12102
+ return request.instructorWorkspaceWhy || 'Open the Workspaces list to use this question’s AI Chat.';
12103
+ }
12104
+ return `Open ${requestOwnerName(request)} for AI Chat`;
11845
12105
  }
11846
12106
 
11847
12107
  // Everything a search should match: the project/workflow the request belongs to, its badge
@@ -13026,7 +13286,7 @@
13026
13286
  : `<button class="req-run" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-run#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Start this request in the background" data-tip="Start this request in the background with your terminal AI">▶</button>`
13027
13287
  : '';
13028
13288
  const chatProvider = preferredChatProvider();
13029
- const hasChatOwner = Boolean(r.project || r.workflowId);
13289
+ const hasChatOwner = requestHasChatOwner(r);
13030
13290
  const inChatScope = hasChatOwner && requestMatchesChatScope(r);
13031
13291
  const chatLabel = `${label}${owner ? ` for ${owner}` : ''}`;
13032
13292
  const hasLinkedChat = Boolean(r.chatConversation?.chatId);
@@ -13048,7 +13308,7 @@
13048
13308
  const chatMeta = discardQuestion ? '' : chatProvider && inChatScope
13049
13309
  ? `<span class="req-chat-meta">AI Chat · ${escapeHtml(runtimeLabel(chatProvider))} · ${r.type === 'guide' || (r.type === 'tweak-contract' && r.mode === 'query') ? 'Read only' : 'Auto'}</span>`
13050
13310
  : chatProvider && hasChatOwner
13051
- ? `<span class="req-chat-elsewhere" data-tip="Open ${escapeAttr(owner)} to discuss or start this request in AI Chat">Open ${escapeHtml(owner)} for AI Chat</span>`
13311
+ ? `<span class="req-chat-elsewhere" data-tip="${escapeAttr(requestChatScopeReason(r))}">${escapeHtml(requestChatScopeReason(r))}</span>`
13052
13312
  : '';
13053
13313
  return `
13054
13314
  <div class="req-item" data-id="${escapeAttr(r.id)}">
@@ -14801,7 +15061,7 @@
14801
15061
  completeReportDiscovery.set(id, { ...result, checking: false });
14802
15062
  if (viewingScheduledReportRoutine === id && $reportModal.classList.contains('show')
14803
15063
  && currentId === r.workflow && result.report && !reportRunning) {
14804
- await paintCompleteReport(completeReportViewerShape(result.report, scheduledReportCaption(result)), 0);
15064
+ await paintCompleteReport(completeReportViewerShape(result.report, scheduledReportCaption(result)));
14805
15065
  }
14806
15066
  if ($routinesModal.classList.contains('show')) renderRoutinesList();
14807
15067
  return result;
@@ -14894,7 +15154,7 @@
14894
15154
  $reportTitle.textContent = `HTML Viewer · ${apps.get(r.workflow)?.displayName || r.workflow}`;
14895
15155
  showModal($reportModal);
14896
15156
  $reportClose.focus();
14897
- await paintCompleteReport(completeReportViewerShape(state.report, scheduledReportCaption(state)), 0);
15157
+ await paintCompleteReport(completeReportViewerShape(state.report, scheduledReportCaption(state)));
14898
15158
  }
14899
15159
  // Why a second start is refused, in the user's words. Said identically by the greyed ▶ (tip + `?`)
14900
15160
  // and by the toast when a click races ahead of the repaint. "or waiting its turn" is not padding:
@@ -15072,7 +15332,11 @@
15072
15332
  if (!run) return '';
15073
15333
  const lives = run.targets.map((t) => t.live);
15074
15334
  const declined = run.targets.reduce((sum, t) => sum + (t.declines ? t.declines.list.filter((d) => d.state === 'declined').length + t.declines.moreDeclined : 0), 0);
15075
- const tail = declined ? ` · ${declined} step${declined === 1 ? '' : 's'} declined — see Questions for you on the Agents page` : '';
15335
+ // #2223: an AI question nobody was there to answer is not a declined step; the AI went on with an assumption.
15336
+ const assumed = run.targets.reduce((sum, t) => sum + (t.declines ? t.declines.list.filter((d) => d.state === 'assumed').length + (t.declines.moreAssumed || 0) : 0), 0);
15337
+ const notes = [declined ? `${declined} step${declined === 1 ? '' : 's'} declined` : '',
15338
+ assumed ? `${assumed} question${assumed === 1 ? '' : 's'} went on without your answer` : ''].filter(Boolean);
15339
+ const tail = notes.length ? ` · ${notes.join(' · ')} — see Questions for you on the Agents page` : '';
15076
15340
  // #2122: every live state has a deliberate summary; only a run whose every part finished (or was skipped up front)
15077
15341
  // says Done, and a state this list does not know yet reads as needing a look — never as Done.
15078
15342
  // Most urgent first: the person is being asked something, then work still going, then work that stopped short.
@@ -15172,6 +15436,25 @@
15172
15436
  // report HTML actually changed (e.g. an exception-monitor flips from "all clear" to
15173
15437
  // "exception detected"). Never auto-opens the viewer, never hijacks another app's open
15174
15438
  // viewer, never stomps an in-flight manual run or a live foreground session.
15439
+ // #2247: a run started by a FloLess action (a chat's confirmed card, or a terminal) made a report. No browser
15440
+ // request was waiting on that run, so the server hands the report here. Cache it as this workflow's last report —
15441
+ // "View report" and the card's button then show it — and repaint only when this workflow's viewer is already open
15442
+ // and idle. Never auto-opens the viewer and never stomps a run started here.
15443
+ function applyActionRunReport(m) {
15444
+ if (!m || typeof m.workflow !== 'string' || typeof m.html !== 'string') return;
15445
+ const interactive = m.interactive === true;
15446
+ const savedPath = typeof m.savedPath === 'string' ? m.savedPath : '';
15447
+ 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 });
15450
+ const open = $reportModal && $reportModal.classList.contains('show');
15451
+ if (!open || currentId !== m.workflow || reportRunning) return;
15452
+ paintReport(m.html, interactive);
15453
+ $reportSub.textContent = fromChat ? 'Report from the run you confirmed in AI Chat — rendered from the run\'s output, never composed by the UI.'
15454
+ : 'Report from a run started in a terminal — rendered from the run\'s output, never composed by the UI.';
15455
+ showSavedPathActions(savedPath);
15456
+ }
15457
+
15175
15458
  function applyRoutineReport(m) {
15176
15459
  if (!m || !m.workflow || typeof m.html !== 'string') return;
15177
15460
  const prev = lastReportByApp.get(m.workflow);
@@ -15222,6 +15505,371 @@
15222
15505
  return host;
15223
15506
  }
15224
15507
 
15508
+ // ── #2228: live progress of a long run ─────────────────────────────────────────────────────────
15509
+ // A long node (a Blender animation, a big model read) runs for minutes inside one run. The server
15510
+ // relays AWARE's node-progress records (`run-live` → `node-progress`… → `run-finished`), keyed by the
15511
+ // token this tab minted for its Run click, and the view in web/run-strip.js says what is happening.
15512
+ // An ordinary Run shows it in the strip over the canvas; a report Run shows it in the report overlay
15513
+ // under the working Flo. The token is kept in sessionStorage so a reload finds its run again.
15514
+ const $runStrip = document.getElementById('run-strip');
15515
+ const RUN_TOKEN_KEY = 'floless.run.token';
15516
+ const RUN_STRIP_DELAY_MS = 2000;
15517
+ const RUN_STRIP_LINGER_MS = 6000;
15518
+ // A reload or a closed tab aborts the in-flight Run request, and its catch/finally would settle the strip and
15519
+ // forget the token — which is exactly what a reload needs to find its run again. The run goes on on the server.
15520
+ let pageLeaving = false;
15521
+ window.addEventListener('pagehide', () => { pageLeaving = true; });
15522
+ window.addEventListener('pageshow', () => { pageLeaving = false; });
15523
+
15524
+ function newRunToken() {
15525
+ try { if (window.crypto && typeof crypto.randomUUID === 'function') return crypto.randomUUID(); } catch { /* fall through */ }
15526
+ return `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
15527
+ }
15528
+ function rememberRunToken(appId, token) {
15529
+ try { sessionStorage.setItem(RUN_TOKEN_KEY, JSON.stringify({ appId, token })); } catch { /* private mode */ }
15530
+ }
15531
+ function forgetRunToken(token) {
15532
+ try {
15533
+ const saved = JSON.parse(sessionStorage.getItem(RUN_TOKEN_KEY) || 'null');
15534
+ if (!token || (saved && saved.token === token)) sessionStorage.removeItem(RUN_TOKEN_KEY);
15535
+ } catch { /* private mode */ }
15536
+ }
15537
+
15538
+ function clearNodeProgress() {
15539
+ document.querySelectorAll('.agent-card.has-progress').forEach((card) => {
15540
+ card.classList.remove('has-progress');
15541
+ card.style.removeProperty('--node-progress');
15542
+ });
15543
+ }
15544
+ function setNodeProgress(nodeId, rec) {
15545
+ if (!nodeId || typeof rec.total !== 'number' || rec.total <= 0 || typeof rec.done !== 'number') return;
15546
+ const card = document.querySelector(`.agent-card[data-agent-id="${(window.CSS && CSS.escape) ? CSS.escape(nodeId) : nodeId}"]`);
15547
+ if (!card || !card.classList.contains('node-running')) return;
15548
+ card.classList.add('has-progress');
15549
+ card.style.setProperty('--node-progress', String(Math.max(0, Math.min(1, rec.done / rec.total))));
15550
+ }
15551
+
15552
+ // Stop from the strip: the same Stop as the header when this tab started the run; after a reload the
15553
+ // tab no longer holds the request, so it asks the server to stop that request by its identity (which the
15554
+ // progress snapshot handed back) — the run's own route ends it.
15555
+ function stopLiveRun() {
15556
+ if (state.running || reportRunning) { stopRun(); return; }
15557
+ const runRequestId = liveRun && liveRun.runRequestId;
15558
+ // On success the run-finished event settles the strip; a stop that never reached the server must say so.
15559
+ api('/api/run/stop', { method: 'POST', body: JSON.stringify(runRequestId ? { runRequestId } : {}) }).catch(() => {
15560
+ // Stop disabled itself on click; a stop that did not land must be pressable again.
15561
+ const btn = liveRun && liveRun.view && liveRun.view.root.querySelector('[data-command-id="workflow.run-strip-stop"]');
15562
+ if (btn) { btn.disabled = false; btn.textContent = '■ Stop run'; }
15563
+ showToast('FloLess didn’t confirm the stop. If the strip keeps counting, the run is still going — press Stop again.', 'warn');
15564
+ });
15565
+ }
15566
+
15567
+ function syncRunStrip() {
15568
+ if (!$runStrip) return;
15569
+ const show = !!(liveRun && liveRun.surface === 'strip' && liveRun.view && liveRun.shown && liveRun.appId === currentId);
15570
+ $runStrip.hidden = !show;
15571
+ syncRunControls();
15572
+ }
15573
+
15574
+ function mountStripView(startedAt) {
15575
+ if (!liveRun || liveRun.view || !$runStrip || !window.flolessRunProgressView) return;
15576
+ $runStrip.classList.remove('rp-leaving');
15577
+ $runStrip.replaceChildren();
15578
+ liveRun.view = window.flolessRunProgressView.create({
15579
+ size: 28,
15580
+ hat: false,
15581
+ startedAt,
15582
+ fallbackHeadline: 'Working on your workflow…',
15583
+ stop: liveRun.owner ? { onClick: stopLiveRun, commandId: 'workflow.run-strip-stop' } : null,
15584
+ });
15585
+ $runStrip.append(liveRun.view.root);
15586
+ }
15587
+
15588
+ function showRunStrip() {
15589
+ if (!liveRun || liveRun.surface !== 'strip' || liveRun.ended) return;
15590
+ if (liveRun.showTimer) { clearTimeout(liveRun.showTimer); liveRun.showTimer = null; }
15591
+ mountStripView(liveRun.startedAt);
15592
+ liveRun.shown = true;
15593
+ syncRunStrip();
15594
+ }
15595
+
15596
+ function disposeLiveRun() {
15597
+ if (!liveRun) return;
15598
+ if (liveRun.showTimer) clearTimeout(liveRun.showTimer);
15599
+ if (liveRun.lingerTimer) clearTimeout(liveRun.lingerTimer);
15600
+ if (liveRun.view) liveRun.view.destroy();
15601
+ if (liveRun.surface === 'strip' && $runStrip) { $runStrip.replaceChildren(); $runStrip.hidden = true; $runStrip.classList.remove('rp-leaving'); }
15602
+ liveRun = null;
15603
+ }
15604
+
15605
+ /**
15606
+ * Begin watching a run this tab is about to start. surface: 'strip' (ordinary Run) or 'overlay' (a
15607
+ * report Run, whose overlay hosts the view). Returns the token to send with the POST.
15608
+ */
15609
+ function beginLiveRun(appId, surface, overlayHost, fallbackHeadline) {
15610
+ disposeLiveRun();
15611
+ const token = newRunToken();
15612
+ rememberRunToken(appId, token);
15613
+ liveRun = { appId, token, runId: null, owner: true, surface, view: null, shown: false, showTimer: null, lingerTimer: null, ended: false, startedAt: Date.now() };
15614
+ if (surface === 'overlay' && overlayHost && window.flolessRunProgressView) {
15615
+ liveRun.view = window.flolessRunProgressView.create({ size: 40, hat: true, fallbackHeadline, stop: null });
15616
+ overlayHost.append(liveRun.view.root);
15617
+ } else if (surface === 'strip') {
15618
+ // Only a run that lasts: a quick one finishes before the strip would appear, so it never flashes.
15619
+ liveRun.showTimer = setTimeout(showRunStrip, RUN_STRIP_DELAY_MS);
15620
+ }
15621
+ return token;
15622
+ }
15623
+
15624
+ function liveRunOwns(m) {
15625
+ if (!liveRun || liveRun.ended) return false;
15626
+ if (m.clientRunToken && m.clientRunToken === liveRun.token) return true;
15627
+ return !!(m.runId && liveRun.runId && m.runId === liveRun.runId);
15628
+ }
15629
+
15630
+ function onLiveProgress(m) {
15631
+ if (!liveRun) return;
15632
+ if (m.runId && !liveRun.runId) liveRun.runId = m.runId;
15633
+ if (liveRun.surface === 'strip' && !liveRun.shown) showRunStrip();
15634
+ if (liveRun.view) liveRun.view.apply(m);
15635
+ if (liveRun.appId === currentId) setNodeProgress(m.node, m);
15636
+ }
15637
+
15638
+ /** outcome: 'ok' | 'failed' | 'stopped' | 'not-run'. Idempotent — the SSE event and the POST both call it. */
15639
+ // #2230: the videos a run rendered, as the server named them (opaque ids, never a path to fetch).
15640
+ function runVideos(res) {
15641
+ return res && Array.isArray(res.media) ? res.media.filter((m) => m && m.kind === 'video' && typeof m.url === 'string') : [];
15642
+ }
15643
+ function watchRunVideos(videos, sub) {
15644
+ if (!videos.length || !window.flolessMediaPlayer) return;
15645
+ window.flolessMediaPlayer.open({ items: videos, sub });
15646
+ }
15647
+
15648
+ /**
15649
+ * A finished run rendered a video: the strip stays (no fade) with Watch as its one primary action, until
15650
+ * the person watches it, dismisses it, or starts another run. A run quick enough never to have shown the
15651
+ * strip shows it now, already finished.
15652
+ */
15653
+ function offerRunVideos(appId, videos) {
15654
+ if (!videos.length || !$runStrip || !window.flolessRunProgressView) return;
15655
+ const appName = (apps.get(appId) && apps.get(appId).displayName) || appId;
15656
+ let run = liveRun && liveRun.appId === appId && liveRun.surface === 'strip' ? liveRun : null;
15657
+ if (!run || !run.view) {
15658
+ disposeLiveRun();
15659
+ liveRun = { appId, token: null, runId: null, owner: true, surface: 'strip', view: null, shown: false, showTimer: null, lingerTimer: null, ended: false, startedAt: Date.now() };
15660
+ showRunStrip();
15661
+ run = liveRun;
15662
+ run.view.finish('ok');
15663
+ run.ended = true;
15664
+ // It never showed while running, so there is no honest duration to state here.
15665
+ const head = run.view.root.querySelector('.rp-headline');
15666
+ if (head) head.textContent = 'Finished';
15667
+ }
15668
+ if (run.lingerTimer) { clearTimeout(run.lingerTimer); run.lingerTimer = null; }
15669
+ if ($runStrip) $runStrip.classList.remove('rp-leaving');
15670
+ const detail = run.view.root.querySelector('.rp-detail');
15671
+ if (detail) { detail.textContent = videos.length === 1 ? 'Video ready' : `${videos.length} videos ready`; detail.hidden = false; }
15672
+ const actions = run.view.root.querySelector('.rp-actions');
15673
+ if (!actions || actions.querySelector('.rp-watch')) return;
15674
+ const watch = mkEl('button', 'rp-watch', videos.length === 1 ? '▶ Watch video' : `▶ Watch videos (${videos.length})`);
15675
+ watch.type = 'button';
15676
+ watch.dataset.commandId = 'workflow.run-strip-watch';
15677
+ watch.onclick = () => {
15678
+ watchRunVideos(videos, `Rendered by ${appName}`);
15679
+ watch.textContent = '▶ Watch again';
15680
+ };
15681
+ const dismiss = mkEl('button', 'rp-dismiss', 'Dismiss');
15682
+ dismiss.type = 'button';
15683
+ dismiss.dataset.commandId = 'workflow.run-strip-dismiss';
15684
+ dismiss.onclick = () => { if (liveRun === run) disposeLiveRun(); };
15685
+ actions.append(watch, dismiss);
15686
+ run.shown = true;
15687
+ syncRunStrip();
15688
+ }
15689
+
15690
+ function finishLiveRun(outcome) {
15691
+ if (pageLeaving) return; // the page is going away mid-run: keep the token so the next page resumes it
15692
+ if (!liveRun || liveRun.ended) return;
15693
+ const run = liveRun;
15694
+ run.ended = true;
15695
+ forgetRunToken(run.token);
15696
+ syncRunControls();
15697
+ if (run.showTimer) { clearTimeout(run.showTimer); run.showTimer = null; }
15698
+ clearNodeProgress();
15699
+ if (run.surface === 'overlay') {
15700
+ // The overlay's own result (the report, or the failure card) replaces it.
15701
+ if (run.view) run.view.destroy();
15702
+ liveRun = null;
15703
+ return;
15704
+ }
15705
+ if (!run.shown) { disposeLiveRun(); return; } // a quick run never showed a strip — nothing to settle
15706
+ run.view.finish(outcome);
15707
+ if (outcome === 'ok') {
15708
+ run.lingerTimer = setTimeout(() => {
15709
+ if (liveRun !== run) return;
15710
+ if ($runStrip) $runStrip.classList.add('rp-leaving');
15711
+ setTimeout(() => { if (liveRun === run) disposeLiveRun(); }, 160);
15712
+ }, RUN_STRIP_LINGER_MS);
15713
+ return;
15714
+ }
15715
+ // Failed or stopped: it stays until dismissed or the next run. The failure's own details live in the
15716
+ // Execution tab; the strip carries one line and the way there.
15717
+ const actions = run.view.root.querySelector('.rp-actions');
15718
+ if (actions) {
15719
+ if (outcome === 'failed') {
15720
+ const see = mkEl('button', 'rp-link', 'See what happened');
15721
+ see.type = 'button';
15722
+ see.dataset.commandId = 'workflow.run-strip-details';
15723
+ see.onclick = () => switchToExecution();
15724
+ actions.append(see);
15725
+ }
15726
+ const dismiss = mkEl('button', 'rp-dismiss', 'Dismiss');
15727
+ dismiss.type = 'button';
15728
+ dismiss.dataset.commandId = 'workflow.run-strip-dismiss';
15729
+ dismiss.onclick = () => { if (liveRun === run) disposeLiveRun(); };
15730
+ actions.append(dismiss);
15731
+ }
15732
+ }
15733
+
15734
+ /**
15735
+ * The Run request failed with NO answer — the page is reloading, or the connection dropped. That says nothing
15736
+ * about the run, which goes on on the server: keep the token, and ask the server where the run is instead of
15737
+ * declaring it failed.
15738
+ */
15739
+ function settleLiveRunWithoutAnswer() {
15740
+ if (!liveRun || liveRun.ended) return;
15741
+ liveRun.owner = false; // this tab no longer holds the request; Stop goes through the server (stopLiveRun)
15742
+ setTimeout(() => { void resyncLiveRun(); }, 1500);
15743
+ }
15744
+
15745
+ /** Another tab (or the terminal) started a run of the workflow this tab shows: follow it, without Stop. */
15746
+ function observeLiveRun(m) {
15747
+ if (liveRun && !liveRun.ended) return;
15748
+ disposeLiveRun();
15749
+ liveRun = { appId: m.id, token: m.clientRunToken || null, runId: m.runId || null, owner: false, surface: 'strip', view: null, shown: false, showTimer: null, lingerTimer: null, ended: false, startedAt: typeof m.startedAt === 'number' ? m.startedAt : Date.now() };
15750
+ liveRun.showTimer = setTimeout(showRunStrip, RUN_STRIP_DELAY_MS);
15751
+ }
15752
+
15753
+ // ── live-run resync (begin) — lifted whole by server/run-strip-ui.test.ts; keep it self-contained.
15754
+ // After a reload or an SSE reconnect: is the run this tab started still going? Resume its strip — or, when it
15755
+ // ended while this tab could not hear it, settle the strip with how it ended (the server remembers that for a
15756
+ // while), so it never ticks on with Run held off. One question at a time: a reconnect and a lost Run answer
15757
+ // can both ask, and they share the one in flight and the one retry timer.
15758
+ let resyncBusy = false;
15759
+ let resyncAgain = false; // asked for while one was in flight: ask once more, fresh, when it settles
15760
+ // The backoff belongs to one run (its token): a reconnect for the same run never restarts it or asks early.
15761
+ let resyncRetry = { token: null, attempt: 0, timer: null };
15762
+
15763
+ function savedRunToken() {
15764
+ try {
15765
+ const saved = JSON.parse(sessionStorage.getItem(RUN_TOKEN_KEY) || 'null');
15766
+ return saved && typeof saved.token === 'string' ? saved : null;
15767
+ } catch { return null; /* private mode */ }
15768
+ }
15769
+
15770
+ /** What a tab that reloaded is told when its run ended while it was away and rendered nothing to watch. */
15771
+ function endedWhileAwayText(outcome) {
15772
+ if (outcome === 'ok') return 'Your workflow finished while the page was reloading.';
15773
+ if (outcome === 'unknown') return 'The run you started has ended, but FloLess can no longer tell how it went (it may have restarted). Run it again if its result is missing.';
15774
+ if (outcome === 'stopped') return 'Your workflow was stopped while the page was reloading.';
15775
+ if (outcome === 'not-run') return 'Your workflow didn’t run. Run it again to see why.';
15776
+ return 'Your workflow stopped with a problem while the page was reloading. Run it again to see what happened.';
15777
+ }
15778
+
15779
+ // A run followed from another tab carries no token of this tab's: ask the server about that workflow instead.
15780
+ // Still going → catch up on what was missed; gone → let it go quietly (it is not this tab's run to report).
15781
+ async function reconcileFollowedRun(saved) {
15782
+ const followed = liveRun;
15783
+ if (!followed || followed.ended || followed.owner || (saved && followed.token === saved.token)) return;
15784
+ let snap;
15785
+ try { snap = await api(`/api/run/progress?app=${encodeURIComponent(followed.appId)}`); } catch { return; }
15786
+ if (liveRun !== followed || followed.ended) return; // it settled, or another run began, while we asked
15787
+ if (snap && snap.active && (!followed.runId || !snap.runId || snap.runId === followed.runId)) {
15788
+ for (const rec of snap.nodes || []) onLiveProgress({ ...rec, runId: snap.runId });
15789
+ return;
15790
+ }
15791
+ disposeLiveRun();
15792
+ syncRunControls();
15793
+ }
15794
+
15795
+ async function resyncOnce() {
15796
+ const saved = savedRunToken();
15797
+ await reconcileFollowedRun(saved);
15798
+ if (!saved) return;
15799
+ const asked = liveRun;
15800
+ let snap;
15801
+ try { snap = await api(`/api/run/progress?token=${encodeURIComponent(saved.token)}`); }
15802
+ catch {
15803
+ // FloLess is not answering yet (a restart, a dropped connection): ask again, a little later each time. The
15804
+ // SSE reconnect asks once more when the server is back.
15805
+ if (resyncRetry.token === saved.token && resyncRetry.attempt < 4) {
15806
+ resyncRetry.attempt += 1;
15807
+ resyncRetry.timer = setTimeout(() => { resyncRetry.timer = null; void resyncLiveRun(); }, 1500 * 2 ** resyncRetry.attempt);
15808
+ }
15809
+ return;
15810
+ }
15811
+ if (resyncRetry.token === saved.token) resyncRetry.attempt = 0; // FloLess answered: a later failure starts afresh
15812
+ // The answer may be stale: the run's own end event settled it, or another Run started, while it was on its way.
15813
+ const still = savedRunToken();
15814
+ if (!still || still.token !== saved.token || liveRun !== asked) return;
15815
+ if (!snap || !snap.active) {
15816
+ forgetRunToken(saved.token);
15817
+ const outcome = snap && typeof snap.outcome === 'string' ? snap.outcome : 'unknown';
15818
+ const videos = runVideos(snap);
15819
+ if (liveRun && liveRun.token === saved.token && !liveRun.ended) {
15820
+ const appId = liveRun.appId;
15821
+ finishLiveRun(outcome);
15822
+ if (videos.length) offerRunVideos(appId, videos);
15823
+ } else if (snap && snap.ended) {
15824
+ // This tab reloaded, and the run ended meanwhile: say how, and offer what it rendered.
15825
+ if (videos.length) offerRunVideos(snap.id, videos);
15826
+ else showToast(endedWhileAwayText(outcome), outcome === 'ok' ? 'ok' : 'warn');
15827
+ } else {
15828
+ // This tab reloaded and FloLess no longer knows the run at all (it restarted, or the run ended long ago).
15829
+ // Never silent — the person started something and is owed a word on where it went.
15830
+ showToast(endedWhileAwayText('unknown'), 'warn');
15831
+ }
15832
+ return;
15833
+ }
15834
+ if (liveRun && liveRun.token === saved.token && !liveRun.ended) {
15835
+ // This tab lost the Run answer: it now stops the run by its request, which the snapshot carries.
15836
+ if (typeof snap.runRequestId === 'string') liveRun.runRequestId = snap.runRequestId;
15837
+ if (liveRun.surface === 'strip') {
15838
+ for (const rec of snap.nodes || []) onLiveProgress({ ...rec, runId: snap.runId });
15839
+ return;
15840
+ }
15841
+ // A report run's overlay belonged to a viewer that has already shown its failure: follow the run on the strip.
15842
+ }
15843
+ disposeLiveRun();
15844
+ liveRun = { appId: snap.id, token: saved.token, runId: snap.runId, runRequestId: typeof snap.runRequestId === 'string' ? snap.runRequestId : null, owner: true, surface: 'strip', view: null, shown: false, showTimer: null, lingerTimer: null, ended: false, startedAt: snap.startedAt };
15845
+ showRunStrip();
15846
+ for (const rec of snap.nodes || []) onLiveProgress({ ...rec, runId: snap.runId });
15847
+ }
15848
+
15849
+ async function resyncLiveRun() {
15850
+ // The question in flight may be about another run (a followed one, or an answer that turns out stale): one
15851
+ // asked for meanwhile is never dropped — it is asked once more, fresh, when that one settles.
15852
+ if (resyncBusy) { resyncAgain = true; return; }
15853
+ resyncBusy = true;
15854
+ try {
15855
+ // A loop, not a call to itself: however many askers queue up meanwhile, they drain one question at a time.
15856
+ do {
15857
+ resyncAgain = false;
15858
+ const saved = savedRunToken();
15859
+ const token = saved ? saved.token : null;
15860
+ if (resyncRetry.token !== token) {
15861
+ if (resyncRetry.timer) clearTimeout(resyncRetry.timer);
15862
+ resyncRetry = { token, attempt: 0, timer: null };
15863
+ }
15864
+ if (resyncRetry.timer) continue; // a retry for this run is already waiting its turn: it asks, not us
15865
+ await resyncOnce();
15866
+ } while (resyncAgain);
15867
+ } finally {
15868
+ resyncBusy = false;
15869
+ }
15870
+ }
15871
+ // ── live-run resync (end)
15872
+
15225
15873
  // The trigger session errored/stopped while a "collecting…" spinner was up (a
15226
15874
  // fire whose report never arrived) — clear it instead of spinning forever:
15227
15875
  // revert to the last cached report if there is one, else an idle prompt.
@@ -15352,7 +16000,6 @@
15352
16000
  $reportOverlay.replaceChildren();
15353
16001
  $reportOverlay.append(
15354
16002
  mkEl('div', null, 'Listening for events — change your selection in Tekla to generate the first report.'),
15355
- Object.assign(mkEl('button', 'overlay-stop', '■ Stop run'), { type: 'button' }),
15356
16003
  );
15357
16004
  $reportSub.innerHTML = `<span class="live-pip" aria-hidden="true"></span>Live · listening…`;
15358
16005
  }
@@ -17514,6 +18161,22 @@
17514
18161
  showWorkflowsLanding(false);
17515
18162
  return true;
17516
18163
  },
18164
+ // #2247: open a workflow and its report viewer on the last report (a chat card's "View report"). Shows only what
18165
+ // the run already made; it never starts a run.
18166
+ async openAppReport(appId, runId) {
18167
+ // Only the report of THAT run: this window keeps the latest report per workflow, and a newer run (or a window
18168
+ // opened after the run) holds a different one or none. Say so instead of showing the wrong report.
18169
+ 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
+ const cached = lastReportByApp.get(appId);
18171
+ if (!runId || cached?.runId !== runId) throw new Error(gone);
18172
+ await this.openApp(appId);
18173
+ // Opening the workflow waits; a newer report may have arrived meanwhile. Show this run's report or nothing.
18174
+ if (lastReportByApp.get(appId) !== cached) throw new Error(gone);
18175
+ const nodeId = reportNodeId();
18176
+ if (!nodeId) throw new Error('This workflow has no report view, so there is nothing to open. Its results are in the workflow.');
18177
+ showReport(nodeId);
18178
+ return true;
18179
+ },
17517
18180
  // #1890 PR 3b: open a FloLess-owned workflow by its id — its published app when it has one, otherwise its draft
17518
18181
  // view — so a conversation that moved into it can be followed there. Throws a plain sentence when it is gone.
17519
18182
  async openOwnedWorkflow(workflowId) {