@floless/app 0.156.0 → 0.158.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 (59) hide show
  1. package/cli-actions.mjs +28 -5
  2. package/dist/floless-server.cjs +110947 -67461
  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 +82 -17
  6. package/dist/skills/floless-app-knowledge/SKILL.md +34 -2
  7. package/dist/skills/floless-app-knowledge/references/schema.md +4 -1
  8. package/dist/skills/floless-app-new-workflow/SKILL.md +23 -7
  9. package/dist/skills/floless-app-onboarding/SKILL.md +31 -1
  10. package/dist/skills/floless-app-report-issue/SKILL.md +3 -3
  11. package/dist/skills/floless-app-rfi/SKILL.md +40 -6
  12. package/dist/skills/floless-app-routines/SKILL.md +9 -2
  13. package/dist/skills/floless-app-steel-model/SKILL.md +35 -1
  14. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +4 -2
  15. package/dist/skills/floless-app-steel-takeoff/SKILL.md +51 -1
  16. package/dist/skills/floless-app-tweak-contract/SKILL.md +25 -5
  17. package/dist/skills/floless-app-workflows/SKILL.md +46 -10
  18. package/dist/skills/floless-app-workflows/references/agent-steps.md +119 -0
  19. package/dist/web/agent-steps.js +864 -47
  20. package/dist/web/agents.js +28 -8
  21. package/dist/web/app.css +620 -17
  22. package/dist/web/app.js +110 -11
  23. package/dist/web/aware-update-client.js +1 -0
  24. package/dist/web/aware.js +921 -220
  25. package/dist/web/chat-landing-scene.js +372 -0
  26. package/dist/web/chat.css +263 -1
  27. package/dist/web/chat.js +2660 -86
  28. package/dist/web/commands-drawing-check.js +17 -0
  29. package/dist/web/commands-shell.js +1059 -8
  30. package/dist/web/commands-steel.js +6 -0
  31. package/dist/web/connections.js +1 -0
  32. package/dist/web/drawing-check-editor.html +33 -5
  33. package/dist/web/drawing-check-editor.js +538 -22
  34. package/dist/web/drawing-check-overlay.js +13 -0
  35. package/dist/web/flo-avatar.js +28 -3
  36. package/dist/web/guide.js +7 -2
  37. package/dist/web/index.html +143 -8
  38. package/dist/web/instructor.js +4 -4
  39. package/dist/web/kb-categories.js +351 -0
  40. package/dist/web/kb-graph-worker.js +73 -0
  41. package/dist/web/model-view-query.js +12 -2
  42. package/dist/web/pages.js +978 -39
  43. package/dist/web/panels.js +5 -2
  44. package/dist/web/parser-setup-recovery.js +12 -4
  45. package/dist/web/project-access.js +549 -0
  46. package/dist/web/run-page-view.js +353 -0
  47. package/dist/web/startup-admission.js +132 -0
  48. package/dist/web/steel-3d-core.js +9 -0
  49. package/dist/web/steel-editor.html +681 -22
  50. package/dist/web/steel-model-v2-commands.js +63 -5
  51. package/dist/web/step-rename.js +287 -0
  52. package/dist/web/tab-signal.js +323 -0
  53. package/dist/web/terminal-requests.js +103 -13
  54. package/dist/web/tool-updates.js +1 -0
  55. package/dist/web/workspace-root-management.js +39 -0
  56. package/dist/web/workspaces.js +2883 -146
  57. package/launch-starting-page.mjs +181 -0
  58. package/launch.mjs +97 -12
  59. package/package.json +5 -1
package/dist/web/aware.js CHANGED
@@ -22,6 +22,8 @@
22
22
  const $kbDriftChip = document.getElementById('kb-drift-chip');
23
23
  const $reportModal = document.getElementById('report-modal');
24
24
  const $reportFrame = document.getElementById('report-frame');
25
+ const $reportFramePage = document.getElementById('report-frame-page'); // #2476: the saved Page version of a report with files
26
+ const $reportFilesNote = document.getElementById('report-files-note');
25
27
  const $reportFrame3d = document.getElementById('report-frame-3d');
26
28
  const $reportOverlay = document.getElementById('report-overlay');
27
29
  const $reportTitle = document.getElementById('report-title');
@@ -63,6 +65,7 @@
63
65
  // One persistent array the inspect Execution tab reads; we mutate in place so
64
66
  // every AGENTS[node].execution reference stays valid across re-renders.
65
67
  const liveTrace = [];
68
+ let traceRunId = null; // #2374: the run the trace being shown belongs to (from its run-start)
66
69
  // Latest normalized app payload, keyed by id, so handlers can read mode/gate.
67
70
  const apps = new Map();
68
71
  // Who owns each listed workflow, from the Workflows library (/api/workflows/library). A PARALLEL map like
@@ -302,10 +305,21 @@
302
305
  });
303
306
  window.addEventListener('pageshow', () => { awarePageUnloading = false; });
304
307
 
305
- async function api(path, opts) {
308
+ // The health poll and startup admission share one generation-fenced observation.
309
+ async function readHealth() {
310
+ if (globalThis.flolessStartupAdmission) return globalThis.flolessStartupAdmission.health();
311
+ const response = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(45_000) });
312
+ if (!response.ok) throw new Error('FloLess could not be reached. Make sure it is still running, then try again.');
313
+ return response.json();
314
+ }
315
+
316
+ async function api(path, opts = {}) {
317
+ await globalThis.flolessStartupAdmission?.admit(path, { method: opts?.method, signal: opts?.signal });
318
+ const { timeoutMs, ...requestOptions } = opts;
319
+ if (!requestOptions.signal && Number.isFinite(timeoutMs)) requestOptions.signal = AbortSignal.timeout(timeoutMs);
306
320
  const res = await fetch(path, {
307
321
  headers: { 'content-type': 'application/json' },
308
- ...opts,
322
+ ...requestOptions,
309
323
  });
310
324
  const body = await res.json().catch(() => ({
311
325
  ok: false,
@@ -558,9 +572,12 @@
558
572
  // #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,
559
573
  // 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.
560
574
  const aiStep = window.flolessAgentSteps?.entryParts(app, n, window.flolessAgentSteps.checkFor(app.id, n.id)) || null;
575
+ // #2374: a node FloLess found using (or decided by) an Agent step's answer carries a quieter chip and one Inspect line.
576
+ const aiUse = !aiStep && window.flolessAgentSteps?.useParts ? window.flolessAgentSteps.useParts(app, n) : null;
561
577
  return {
562
578
  _mode: n.mode,
563
579
  _aiStep: aiStep ? { badge: aiStep.badge, attention: aiStep.attention } : null,
580
+ _aiUse: aiUse ? aiUse.chip : null,
564
581
  _runtimeModel: !!n.runtimeModel, // B2: lock stamped runtime-model → card badge
565
582
  _frozen: !!n.frozen, // source node carries a `frozen:` block → card badge + Unfreeze menu
566
583
  icon: iconFor(n.agent),
@@ -570,7 +587,7 @@
570
587
  title: escapeHtml(n.id),
571
588
  subtitle: `${agentLabel}${cmd ? '/' + cmd : ''} · ${mode}`,
572
589
  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`,
573
- description: aiStep ? `${aiStep.descriptionHtml}${notesHtml}` : `${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}`,
590
+ 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}`,
574
591
  // Rich agent/command detail when the manifest is installed (n.skill); else
575
592
  // the lock-pointer fallback below (exec/agent-less nodes, uninstalled agents).
576
593
  skill: skillBody(
@@ -1451,7 +1468,10 @@
1451
1468
  paintKbInformed(null, false); // clear the previous workflow's row before the await, not after
1452
1469
  if (!id) return;
1453
1470
  try {
1454
- const r = await fetch(`/api/kb-pin/${encodeURIComponent(id)}`, { cache: 'no-store' });
1471
+ const path = `/api/kb-pin/${encodeURIComponent(id)}`;
1472
+ await globalThis.flolessStartupAdmission?.admit(path);
1473
+ if (read !== kbPinRead || currentId !== id) return;
1474
+ const r = await fetch(path, { cache: 'no-store' });
1455
1475
  const d = await r.json();
1456
1476
  if (read !== kbPinRead || currentId !== id) return; // superseded — a newer workflow owns the strip
1457
1477
  if (r.ok && d.ok) paintKbInformed(d.pin, !!d.drift);
@@ -2181,6 +2201,8 @@
2181
2201
  openAgents: () => { void window.flolessWorkspaces?.setMode?.('agents'); },
2182
2202
  toast: (text, kind) => showToast(text, kind),
2183
2203
  repaint: repaintAgentSteps,
2204
+ // #2374: the trace labels outputs from the run's own record, which arrives after the run ends.
2205
+ runRecordChanged: (appId) => { if (appId === currentId && state.currentTab === 'execution') renderInspect(); },
2184
2206
  });
2185
2207
 
2186
2208
  async function loadApp(id) {
@@ -2269,6 +2291,20 @@
2269
2291
  return waitForPublicationAvailabilityIdle();
2270
2292
  }
2271
2293
 
2294
+ // An SSE-driven availability re-read is for the workflow still selected underneath whatever is on
2295
+ // screen. While Workspaces or Agents is showing, a failure there is nothing the person did, and
2296
+ // returning to Workflows re-reads it (refreshCurrentWorkflow) and reports a failure itself — so it
2297
+ // is logged, not toasted. 2026-10-16: an expired module lease turned every chat approval's
2298
+ // projects-changed into a generic "We couldn't finish that" toast over a Tekla Parser project.
2299
+ // On Workflows the card is the person's to see, so a failure there is still reported.
2300
+ function reportBackgroundAvailabilityErr(e) {
2301
+ if (document.body.classList.contains('mode-workspaces') || document.body.classList.contains('mode-agents')) {
2302
+ console.warn('[floless] the selected workflow’s availability could not be refreshed in the background', e);
2303
+ return;
2304
+ }
2305
+ reportErr(e);
2306
+ }
2307
+
2272
2308
  // Workspaces keeps the existing workflow selected underneath its project surface. Returning to
2273
2309
  // Workflows is therefore a re-open of that workflow: refresh both its publication state and the
2274
2310
  // additive provenance strip, so a KB organize that happened while the project was open cannot
@@ -2501,7 +2537,12 @@
2501
2537
  let wsTitleLanding = false; // explicit because a project may itself be named "Workspaces"
2502
2538
  let wsTitleProjectId = null; // identity: two projects may legitimately share a display name
2503
2539
  // #1890: on the Workflows landing the tab is named after it, not after the workflow still loaded underneath.
2504
- const syncTabTitle = () => { document.title = tabTitle(wsTitleName || (wfLanding ? 'Workflows' : null), wfTitleText); };
2540
+ // The tab signal (web/tab-signal.js) leads the title with how a run is going; aware.js stays its one writer.
2541
+ const syncTabTitle = () => {
2542
+ const lead = window.flolessTabSignal ? window.flolessTabSignal.prefix() : '';
2543
+ document.title = lead + tabTitle(wsTitleName || (wfLanding ? 'Workflows' : null), wfTitleText);
2544
+ };
2545
+ if (window.flolessTabSignal) window.flolessTabSignal.onChange(syncTabTitle);
2505
2546
  function setComboTriggerLabel(text) {
2506
2547
  if ($wfTriggerLabel) $wfTriggerLabel.textContent = text || 'select workflow';
2507
2548
  wfTitleText = text || '';
@@ -4115,10 +4156,43 @@
4115
4156
  // 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
4116
4157
  // newer one. `workflowPageLatest` is the newest version this window knows per workflow, for the empty viewer after
4117
4158
  // a reload; for one Page it only ever grows.
4118
- const workflowPageByRun = new Map(); // runId → { app, home, pageId, version }
4159
+ // Keyed by CAPTURE: a completed run's runId, or `runId#fireKey` for one fire of a live trigger session (slice 3b),
4160
+ // so an older fire's news never joins a newer fire's report.
4161
+ const workflowPageByRun = new Map(); // captureKey → { app, home, pageId, version }
4162
+ function captureKeyOf(runId, fireKey) {
4163
+ if (typeof runId !== 'string' || !runId) return null;
4164
+ return typeof fireKey === 'string' && fireKey ? `${runId}#${fireKey}` : runId;
4165
+ }
4119
4166
  const workflowPageLatest = new Map(); // app id → { home, pageId, version, at }
4120
4167
  const WORKFLOW_PAGE_RUNS_KEPT = 64;
4121
4168
 
4169
+ // #2476: the run viewer's view of a report that carries files — the inert copy and a plain note while its Page version is
4170
+ // being saved, then that version's own isolated frame once it says it is ready. Its state comes from the server's answer
4171
+ // about this exact run (web/run-page-view.js); this file only feeds it the report on screen, the news, and the end of a view.
4172
+ const runPageView = window.FlolessRunPageView.create({
4173
+ api, inert: $reportFrame, page: $reportFramePage, note: $reportFilesNote, win: window,
4174
+ currentApp: () => currentId,
4175
+ // A lookup that found the version: the header's "Version N · Open in Pages" learns it even if the news was missed.
4176
+ onSaved: ({ app, runId, fire, home, pageId, version }) => {
4177
+ const key = captureKeyOf(runId, fire);
4178
+ if (!key) return;
4179
+ const known = workflowPageByRun.get(key);
4180
+ if (known && known.version >= version) return;
4181
+ workflowPageByRun.set(key, { app, home, pageId, version });
4182
+ if (workflowPageByRun.size > WORKFLOW_PAGE_RUNS_KEPT) workflowPageByRun.delete(workflowPageByRun.keys().next().value);
4183
+ noteWorkflowPageLatest(app, { home, pageId, version });
4184
+ if (currentId === app) paintReportPageLinks();
4185
+ },
4186
+ });
4187
+ // A workspace switch: what this window knows about saved versions belongs to the old workspace.
4188
+ let runPageRoot = null;
4189
+ window.addEventListener('floless:workspace-root-state', (event) => {
4190
+ const root = event.detail && event.detail.root;
4191
+ const id = root ? `${root.rootId}#${root.generation}` : null;
4192
+ if (runPageRoot !== null && id !== runPageRoot) { runPageView.reset(); workflowPageByRun.clear(); paintReportPageLinks(); }
4193
+ runPageRoot = id;
4194
+ });
4195
+
4122
4196
  function noteWorkflowPageLatest(app, page) {
4123
4197
  const prev = workflowPageLatest.get(app);
4124
4198
  if (prev && prev.home === page.home && prev.pageId === page.pageId && prev.version >= page.version) return;
@@ -4127,23 +4201,36 @@
4127
4201
 
4128
4202
  /** The Page version this cached report became, once its capture has landed. */
4129
4203
  function reportPageOf(entry) {
4130
- return entry && typeof entry.runId === 'string' ? workflowPageByRun.get(entry.runId) || null : null;
4204
+ const key = entry ? (typeof entry.captureKey === 'string' ? entry.captureKey : captureKeyOf(entry.runId)) : null;
4205
+ return key ? workflowPageByRun.get(key) || null : null;
4131
4206
  }
4132
4207
 
4133
4208
  function applyWorkflowPageCaptured(m) {
4134
4209
  if (!m || typeof m.app !== 'string' || typeof m.runId !== 'string') return;
4210
+ runPageView.onNews(m); // #2476: a report with files on screen follows its own capture
4135
4211
  if (typeof m.warning === 'string') {
4136
4212
  // The run itself succeeded and its report is shown; the window on this workflow is told, the others log it.
4137
4213
  if (currentId === m.app) showToast(m.warning, 'warn');
4138
4214
  else console.warn(`Workflow ${m.app}: ${m.warning}`);
4139
4215
  return;
4140
4216
  }
4217
+ // #2262 slice 3c: saved, but part of what the run made could not go with it (a report folder's files).
4218
+ if (typeof m.notice === 'string') {
4219
+ if (currentId === m.app) showToast(m.notice, 'warn');
4220
+ else console.warn(`Workflow ${m.app}: ${m.notice}`);
4221
+ }
4222
+ if (m.relabelled === 'live-failed' && typeof m.home === 'string' && typeof m.pageId === 'string') {
4223
+ // A failed live session's versions changed label: an open copy of that Page must not keep the old one.
4224
+ window.flolessPages?.reloadIfOpen?.(m.home, m.pageId);
4225
+ window.flolessPages?.refresh?.();
4226
+ return;
4227
+ }
4141
4228
  if (typeof m.home !== 'string' || typeof m.pageId !== 'string' || !Number.isInteger(m.version) || m.version < 1) {
4142
4229
  console.warn('A workflow Page update could not be read, so it was ignored.', m);
4143
4230
  return;
4144
4231
  }
4145
4232
  const page = { app: m.app, home: m.home, pageId: m.pageId, version: m.version };
4146
- workflowPageByRun.set(m.runId, page);
4233
+ workflowPageByRun.set(captureKeyOf(m.runId, m.fireKey) || m.runId, page);
4147
4234
  if (workflowPageByRun.size > WORKFLOW_PAGE_RUNS_KEPT) workflowPageByRun.delete(workflowPageByRun.keys().next().value);
4148
4235
  noteWorkflowPageLatest(m.app, page);
4149
4236
  window.flolessPages?.refresh?.();
@@ -4185,7 +4272,11 @@
4185
4272
  function paintReportPageLinks() {
4186
4273
  const app = currentId;
4187
4274
  const cached = app ? lastReportByApp.get(app) : null;
4188
- const page = cached && !reportRunning && $reportOverlay.hidden ? reportPageOf(cached) : null;
4275
+ // #2539: only for the report actually on screen — a complete report shown is that run's own (matched by handle), never
4276
+ // one opened from a Page version or another run.
4277
+ const shown = cached && !reportRunning && $reportOverlay.hidden
4278
+ && (cached.handle ? currentCompleteReport?.handle === cached.handle : !currentCompleteReport);
4279
+ const page = shown ? reportPageOf(cached) : null;
4189
4280
  if ($reportPage) {
4190
4281
  $reportPage.hidden = !page;
4191
4282
  if (page) {
@@ -4283,7 +4374,7 @@
4283
4374
  if (foregroundTrigger) {
4284
4375
  const ft = foregroundTrigger;
4285
4376
  foregroundStopping = true;
4286
- foregroundTrigger = null;
4377
+ foregroundTrigger = null; liveViewerMayHaveChanged();
4287
4378
  if ($stopRunBtn) { $stopRunBtn.disabled = true; $stopRunBtn.textContent = 'Stopping…'; }
4288
4379
  syncRunControls();
4289
4380
  try { await api(`/api/trigger-run/${encodeURIComponent(ft.appId)}/stop`, { method: 'POST' }); } catch { /* best effort — the session may already be gone */ }
@@ -4342,6 +4433,7 @@
4342
4433
  let currentCompleteReport = null;
4343
4434
  let currentReportSection = 0;
4344
4435
  let reportSectionRequest = 0;
4436
+ let reportObjectLookup = 0; // #2539: the newest Go to object; an older one never touches its message
4345
4437
  function updateReportSectionNavigation(ordinal, index) {
4346
4438
  const first = ordinal === 0;
4347
4439
  const last = ordinal + 1 >= index.chunkCount;
@@ -4359,6 +4451,31 @@
4359
4451
  }
4360
4452
  if (controls.some(([control]) => control === focused)) window.Instructor?.refreshCarrier(focused);
4361
4453
  }
4454
+ // #2262 slice 3c: "Open the full report" beside a complete report's Page version. The server answers the report's
4455
+ // handle for that version's run, after the report viewer's own checks; the Page viewer closes and this one opens.
4456
+ window.FlolessReports = {
4457
+ async openPageVersionReport({ home, id, n, title, beforeShow }) {
4458
+ let answer;
4459
+ try {
4460
+ await ensureReportDiscoverySession();
4461
+ answer = await api(`/api/pages/${encodeURIComponent(home)}/${encodeURIComponent(id)}/versions/${encodeURIComponent(n)}/full-report`);
4462
+ } catch (error) {
4463
+ showToast(error?.message && !/^HTTP \d+$/.test(error.message) ? error.message : 'FloLess couldn’t open the full report. Try again in a moment.', 'warn');
4464
+ return false;
4465
+ }
4466
+ if (typeof answer?.handle !== 'string' || !answer.handle) {
4467
+ showToast('FloLess couldn’t open the full report. Try again in a moment.', 'warn');
4468
+ return false;
4469
+ }
4470
+ beforeShow?.();
4471
+ $reportTitle.textContent = `HTML Viewer · ${title || 'Complete model report'}`;
4472
+ showModal($reportModal);
4473
+ $reportClose.focus();
4474
+ await paintCompleteReport({ handle: answer.handle });
4475
+ return true;
4476
+ },
4477
+ };
4478
+
4362
4479
  function clearCompleteReportView() {
4363
4480
  reportSectionRequest += 1;
4364
4481
  currentCompleteReport = null;
@@ -4369,95 +4486,132 @@
4369
4486
  $reportObjectError.textContent = '';
4370
4487
  $reportFrame.removeAttribute('src');
4371
4488
  }
4372
- async function paintCompleteReport(report, ordinal = null) {
4489
+ /** Show one section of a saved complete report. Resolves true once it is on screen, false when it is not. */
4490
+ async function paintCompleteReport(report, asked = null, busyUntil = null) {
4491
+ runPageView.invalidate(); // #2476: another view replaces a report-with-files view
4492
+ $reportFrame.hidden = false;
4493
+ // #2539: a report another read holds is waited for, not failed — right after a run that is the workflow's Page
4494
+ // saving its copy, which reads the whole report. Past this wait the viewer offers Try again instead.
4495
+ const REPORT_BUSY_WAIT_MS = 5 * 60_000;
4496
+ // The server answers a busy report with 202 and this code (never a failure status), whichever route was asked.
4497
+ const reportIsBusy = (error) => error?.body?.code === 'report-busy';
4373
4498
  const request = ++reportSectionRequest;
4374
4499
  const handle = encodeURIComponent(report.handle);
4375
4500
  $reportOverlay.hidden = false;
4376
4501
  $reportOverlay.replaceChildren(mkEl('div', 'spinner'), mkEl('div', null, 'Loading report section…'));
4377
- try {
4378
- let index = await api(`/api/model-reports/${handle}/index?at=${ordinal ?? 0}`);
4379
- if (request !== reportSectionRequest) return;
4380
- // Start with the first object's data, while First still opens Model information.
4381
- // Ask the verified index where that object begins instead of assuming section 2.
4382
- if (ordinal == null) {
4383
- ordinal = 0;
4384
- if (Number(index.objectCount) > 0 && index.current?.firstObject == null) {
4385
- const firstObject = await api(`/api/model-reports/${handle}/object/0`);
4386
- if (request !== reportSectionRequest) return;
4387
- ordinal = firstObject.chunkOrdinal;
4388
- index = await api(`/api/model-reports/${handle}/index?at=${ordinal}`);
4502
+ // A wait resumed for the same section (the frame found it busy) keeps its first deadline, never a fresh one.
4503
+ const waitUntil = busyUntil ?? Date.now() + REPORT_BUSY_WAIT_MS;
4504
+ for (;;) {
4505
+ let ordinal = asked;
4506
+ try {
4507
+ let index = await api(`/api/model-reports/${handle}/index?at=${ordinal ?? 0}`);
4508
+ if (request !== reportSectionRequest) return false;
4509
+ // Start with the first object's data, while First still opens Model information.
4510
+ // Ask the verified index where that object begins instead of assuming section 2.
4511
+ if (ordinal == null) {
4512
+ ordinal = 0;
4513
+ if (Number(index.objectCount) > 0 && index.current?.firstObject == null) {
4514
+ const firstObject = await api(`/api/model-reports/${handle}/object/0`);
4515
+ if (request !== reportSectionRequest) return false;
4516
+ ordinal = firstObject.chunkOrdinal;
4517
+ index = await api(`/api/model-reports/${handle}/index?at=${ordinal}`);
4518
+ }
4519
+ }
4520
+ if (request !== reportSectionRequest) return false;
4521
+ const response = await fetch(`/api/model-reports/${handle}/chunk/${ordinal}`, { credentials: 'same-origin', cache: 'no-store' });
4522
+ if (!response.ok || response.status === 202) {
4523
+ const body = await response.json().catch(() => null);
4524
+ throw Object.assign(new Error('Report section request failed'), { status: response.status, body });
4525
+ }
4526
+ const length = Number(response.headers.get('content-length'));
4527
+ if (Number.isFinite(length) && length > 1200 * 1024) {
4528
+ await response.body?.cancel();
4529
+ throw Object.assign(new Error('Report section exceeds viewer limit'), { status: 413 });
4389
4530
  }
4390
- }
4391
- if (request !== reportSectionRequest) return;
4392
- const response = await fetch(`/api/model-reports/${handle}/chunk/${ordinal}`, { credentials: 'same-origin', cache: 'no-store' });
4393
- if (!response.ok) {
4394
- const body = await response.json().catch(() => null);
4395
- throw Object.assign(new Error('Report section request failed'), { status: response.status, body });
4396
- }
4397
- const length = Number(response.headers.get('content-length'));
4398
- if (Number.isFinite(length) && length > 1200 * 1024) {
4399
4531
  await response.body?.cancel();
4400
- throw Object.assign(new Error('Report section exceeds viewer limit'), { status: 413 });
4401
- }
4402
- await response.body?.cancel();
4403
- if (request !== reportSectionRequest) return;
4404
- $reportFrame.removeAttribute('srcdoc');
4405
- // Navigate to the real session-gated route. Its restrictive CSP must belong to the
4406
- // rendered document itself; a blob: copy would silently lose that response header.
4407
- $reportFrame.src = `/api/model-reports/${handle}/chunk/${ordinal}`;
4408
- $reportFrame.hidden = false;
4409
- $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4410
- currentCompleteReport = report;
4411
- currentReportSection = ordinal;
4412
- const count = Number(index.objectCount) || 0;
4413
- const properties = Number(index.propertyCount) || 0;
4414
- const current = index.current || {};
4415
- const objectRange = count === 0 ? 'No objects' : current.firstObject == null
4416
- ? `Model information · Report contains ${count} objects` : `Objects ${Number(current.firstObject) + 1}–${Number(current.lastObject) + 1} of ${count}`;
4417
- const propertyRange = properties === 0 ? '0 properties'
4418
- : current.firstProperty == null ? `Report contains ${properties} properties`
4419
- : `Properties ${Number(current.firstProperty) + 1}–${Number(current.lastProperty) + 1} of ${properties}`;
4420
- $reportSectionStatus.textContent = `${objectRange} · ${propertyRange} · section ${ordinal + 1} of ${index.chunkCount}`;
4421
- updateReportSectionNavigation(ordinal, index);
4422
- $reportNav.hidden = false;
4423
- $reportDownload.hidden = false;
4424
- $reportOpen.hidden = true;
4425
- $reportShare.hidden = true;
4426
- showSavedPathActions('');
4427
- $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
4428
- // #1840: the caption says when the report's approved version accepted open import findings (the
4429
- // server's sentence). The report body comes from AWARE's report protocol, which appears to have no
4430
- // field for it (inferred from its parser's messages, not reproduced). When the server could not
4431
- // read that approval's record, the caption says so instead of reading as a plain approval.
4432
- $reportSub.textContent = report.scheduledCaption
4433
- || `Complete read-only report · ${count} objects · ${properties} properties · approved revision ${String(index.revisionId).slice(0, 12)} · source unchanged.`;
4434
- if (typeof index.acceptedImportFindingsNote === 'string') $reportSub.textContent += ` ${index.acceptedImportFindingsNote}`;
4435
- else if (index.approvalDetailsUnavailable === true) $reportSub.textContent += ' Approval details unavailable.';
4436
- // What the report rests on comes first (a scheduled "Latest approved" run that read an older
4437
- // approved version says which), never after the counts where it would read as a footnote.
4438
- const warnings = Array.isArray(index.warnings) ? index.warnings.filter((warning) => typeof warning === 'string' && warning) : [];
4439
- if (warnings.length) $reportSub.textContent = `${warnings.join(' ')} ${$reportSub.textContent}`;
4440
- } catch (error) {
4441
- if (request !== reportSectionRequest) return;
4442
- clearCompleteReportView();
4443
- $reportFrame.srcdoc = '';
4444
- $reportSub.textContent = 'This report section could not be displayed.';
4445
- const status = Number(error?.status);
4446
- let remedy = 'Close the viewer and choose View report to retry loading this saved report.';
4447
- if (status === 401) remedy = 'Sign in again, then close the viewer and choose View report to load this saved report.';
4448
- else if (status === 403) remedy = 'Report access could not be confirmed. Check your account access and connection, then choose View report again.';
4449
- else if (status === 404 || status === 410) remedy = 'This report is no longer available. Choose Run workflow to create a fresh report.';
4450
- 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.';
4451
- 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.';
4452
- else if (status === 413) {
4453
- remedy = 'This section is too large for the viewer. Download complete report to read the saved report.';
4532
+ if (request !== reportSectionRequest) return false;
4533
+ $reportFrame.removeAttribute('srcdoc');
4534
+ // Navigate to the real session-gated route. Its restrictive CSP must belong to the
4535
+ // rendered document itself; a blob: copy would silently lose that response header.
4536
+ // #2539: which paint this frame load belongs to, and its wait deadline, should the frame find the report busy.
4537
+ Object.assign($reportFrame.dataset, { request: String(request), busyUntil: String(waitUntil) });
4538
+ $reportFrame.src = `/api/model-reports/${handle}/chunk/${ordinal}`;
4539
+ $reportFrame.hidden = false;
4540
+ $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4454
4541
  currentCompleteReport = report;
4542
+ currentReportSection = ordinal;
4543
+ const count = Number(index.objectCount) || 0;
4544
+ const properties = Number(index.propertyCount) || 0;
4545
+ const current = index.current || {};
4546
+ const objectRange = count === 0 ? 'No objects' : current.firstObject == null
4547
+ ? `Model information · Report contains ${count} objects` : `Objects ${Number(current.firstObject) + 1}–${Number(current.lastObject) + 1} of ${count}`;
4548
+ const propertyRange = properties === 0 ? '0 properties'
4549
+ : current.firstProperty == null ? `Report contains ${properties} properties`
4550
+ : `Properties ${Number(current.firstProperty) + 1}–${Number(current.lastProperty) + 1} of ${properties}`;
4551
+ $reportSectionStatus.textContent = `${objectRange} · ${propertyRange} · section ${ordinal + 1} of ${index.chunkCount}`;
4552
+ updateReportSectionNavigation(ordinal, index);
4553
+ $reportNav.hidden = false;
4455
4554
  $reportDownload.hidden = false;
4456
- } else if (status === 503) remedy = 'Saved reports are being prepared. Wait a moment, then close the viewer and choose View report again.';
4457
- // Keep diagnostics bounded: transport messages can contain private paths or server details.
4458
- console.warn('Report section display failed', { status: Number.isFinite(status) ? status : null });
4459
- $reportOverlay.hidden = false;
4460
- $reportOverlay.replaceChildren(mkEl('div', null, remedy));
4555
+ $reportOpen.hidden = true;
4556
+ $reportShare.hidden = true;
4557
+ showSavedPathActions('');
4558
+ $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
4559
+ // #1840: the caption says when the report's approved version accepted open import findings (the
4560
+ // server's sentence). The report body comes from AWARE's report protocol, which appears to have no
4561
+ // field for it (inferred from its parser's messages, not reproduced). When the server could not
4562
+ // read that approval's record, the caption says so instead of reading as a plain approval.
4563
+ $reportSub.textContent = report.scheduledCaption
4564
+ || `Complete read-only report · ${count} objects · ${properties} properties · approved revision ${String(index.revisionId).slice(0, 12)} · source unchanged.`;
4565
+ if (typeof index.acceptedImportFindingsNote === 'string') $reportSub.textContent += ` ${index.acceptedImportFindingsNote}`;
4566
+ else if (index.approvalDetailsUnavailable === true) $reportSub.textContent += ' Approval details unavailable.';
4567
+ // What the report rests on comes first (a scheduled "Latest approved" run that read an older
4568
+ // approved version says which), never after the counts where it would read as a footnote.
4569
+ const warnings = Array.isArray(index.warnings) ? index.warnings.filter((warning) => typeof warning === 'string' && warning) : [];
4570
+ if (warnings.length) $reportSub.textContent = `${warnings.join(' ')} ${$reportSub.textContent}`;
4571
+ paintReportPageLinks(); // #2539: the Page version this report became, now that it is on screen
4572
+ return true;
4573
+ } catch (error) {
4574
+ if (request !== reportSectionRequest) return false;
4575
+ // #2539: busy is not a failure. Say what it waits for (the server's sentence) and open the report by itself.
4576
+ if (reportIsBusy(error) && Date.now() < waitUntil) {
4577
+ const waiting = mkEl('div', null, String(error.body.error || 'This report is busy. It opens as soon as that finishes.'));
4578
+ waiting.setAttribute('role', 'status');
4579
+ $reportOverlay.replaceChildren(mkEl('div', 'spinner'), waiting);
4580
+ const pause = Math.min(10_000, Math.max(500, Number(error.body.retryAfterMs) || 2_000));
4581
+ await new Promise((resolve) => setTimeout(resolve, pause));
4582
+ if (request !== reportSectionRequest) return false;
4583
+ continue;
4584
+ }
4585
+ clearCompleteReportView();
4586
+ $reportFrame.srcdoc = '';
4587
+ $reportSub.textContent = 'This report section could not be displayed.';
4588
+ const status = Number(error?.status);
4589
+ let remedy = 'Close the viewer and choose View report to retry loading this saved report.';
4590
+ if (status === 401) remedy = 'Sign in again, then close the viewer and choose View report to load this saved report.';
4591
+ else if (status === 403) remedy = 'Report access could not be confirmed. Check your account access and connection, then choose View report again.';
4592
+ else if (status === 404 || status === 410) remedy = 'This report is no longer available. Choose Run workflow to create a fresh report.';
4593
+ 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.';
4594
+ 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.';
4595
+ 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.';
4596
+ else if (status === 413) {
4597
+ remedy = 'This section is too large for the viewer. Download complete report to read the saved report.';
4598
+ currentCompleteReport = report;
4599
+ $reportDownload.hidden = false;
4600
+ } else if (status === 503) remedy = 'Saved reports are being prepared. Wait a moment, then close the viewer and choose View report again.';
4601
+ // Keep diagnostics bounded: transport messages can contain private paths or server details.
4602
+ console.warn('Report section display failed', { status: Number.isFinite(status) ? status : null });
4603
+ $reportOverlay.hidden = false;
4604
+ $reportOverlay.replaceChildren(mkEl('div', null, remedy));
4605
+ if (reportIsBusy(error)) {
4606
+ const again = mkEl('button', 'ghost report-retry', 'Try again');
4607
+ again.type = 'button';
4608
+ again.setAttribute('data-command-id', 'shell.report-busy-retry');
4609
+ again.addEventListener('click', () => { void paintCompleteReport(report, asked); });
4610
+ $reportOverlay.append(again);
4611
+ again.focus?.();
4612
+ }
4613
+ return false;
4614
+ }
4461
4615
  }
4462
4616
  }
4463
4617
  // The share route's user-facing cap (server/index.ts sets a 6 MB body limit; the JSON envelope
@@ -4480,13 +4634,15 @@
4480
4634
  // INTERACTIVE 3D doc (viewer-3d) uses the script-enabled frame via a data: URL (opaque
4481
4635
  // origin, cannot touch the app page) and keeps a "Loading 3D view…" overlay until the doc
4482
4636
  // posts `viewer-ready`. Exactly one frame is shown at a time.
4483
- function paintReport(html, interactive) {
4637
+ function paintReport(html, interactive, entry = null) {
4638
+ runPageView.invalidate(); // #2476: a new paint ends the previous report's Page frame, its lookups and its timers
4484
4639
  clearCompleteReportView();
4485
4640
  $reportOpen.hidden = false;
4486
4641
  lastPaintedHtml = html || '';
4487
4642
  lastPaintedInteractive = !!interactive; // drives the share copy: a 3D model is not a "frozen report"
4488
4643
  showSavedPathActions(''); // default off; the caller re-shows if this report saved a file
4489
4644
  if ($reportPage) $reportPage.hidden = true; // likewise its Page link (paintReportPageLinks, once it is cached)
4645
+ if (!interactive && entry && entry.withFiles) { paintReportWithFiles(html, entry); return; }
4490
4646
  if (interactive) {
4491
4647
  $reportFrame.hidden = true; $reportFrame.srcdoc = '';
4492
4648
  $reportFrame3d.hidden = false;
@@ -4506,10 +4662,26 @@
4506
4662
  }
4507
4663
  }
4508
4664
 
4665
+ // #2262 slice 3c / #2476: a report that carries files (`report_folder`) refers to them as `assets/…`, which resolve only in
4666
+ // its Page version. `html` is the inert copy the SERVER made (nothing asks FloLess for a missing file); the controller
4667
+ // (web/run-page-view.js) says what is happening to the version and shows it in its own isolated frame once it is ready.
4668
+ // Open and Share stay hidden in every state of this view: they would hand out the copy without its files — the Page has
4669
+ // its own Share, and "Version N · Open in Pages" is the way out.
4670
+ function paintReportWithFiles(html, entry) {
4671
+ $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4672
+ $reportFrame.hidden = false;
4673
+ $reportFrame.srcdoc = html;
4674
+ $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
4675
+ $reportOpen.hidden = true;
4676
+ $reportShare.hidden = true;
4677
+ runPageView.paint(entry);
4678
+ }
4679
+
4509
4680
  // Reset the viewer to "no report shown": clear BOTH frames + the Open buffer, so a stale
4510
4681
  // interactive 3D doc can't linger (its WebGL loop running) behind an overlay, and ↗ Open
4511
4682
  // can't reopen a previous app's report. Used by every empty / transition state.
4512
4683
  function clearReportFrames() {
4684
+ runPageView.invalidate(); // #2476
4513
4685
  clearCompleteReportView();
4514
4686
  $reportOpen.hidden = false;
4515
4687
  $reportFrame.srcdoc = ''; $reportFrame.hidden = false;
@@ -4541,7 +4713,7 @@
4541
4713
  } else {
4542
4714
  $reportSub.textContent = `Last report${sfx} — rendered from the run's output, never composed by the UI.`;
4543
4715
  }
4544
- paintReport(cached.html, cached.interactive);
4716
+ paintReport(cached.html, cached.interactive, cached);
4545
4717
  showSavedPathActions(cached.savedPath); // re-show Open file / Reveal if this run saved one
4546
4718
  } else {
4547
4719
  clearReportFrames();
@@ -5286,33 +5458,34 @@
5286
5458
  if (res.credentialIssue) { $reportSub.textContent = 'Execution ended. Reconnect the integration to run again.'; surfaceCredentialIssue(res.credentialIssue); return; }
5287
5459
  if (res.report && res.report.kind === 'complete-model-properties' && typeof res.report.handle === 'string') {
5288
5460
  $reportTitle.textContent = `HTML Viewer · ${app.displayName}`;
5289
- lastReportByApp.set(app.id, { nodeId, label: inputBadge, ...res.report });
5290
- await paintCompleteReport(res.report);
5291
- if (!currentCompleteReport || !$reportOverlay.hidden) return;
5292
- markFirstRunDone(app.id);
5293
- $reportModal.dataset.html = '1';
5294
- appendNarration(`Rendered the complete read-only property report from <strong>${escapeHtml(nodeId)}</strong>.`);
5461
+ lastReportByApp.set(app.id, { nodeId, label: inputBadge, ...res.report, runId: typeof res.runId === 'string' ? res.runId : null });
5462
+ // #2539: the run is over once the server answered. Showing its report may still wait for the workflow's Page to
5463
+ // save its copy, so the run controls are released now (not awaited) and the viewer opens the report by itself.
5464
+ const runApp = app.id;
5465
+ void paintCompleteReport(res.report).then((painted) => {
5466
+ if (!painted || !currentCompleteReport || !$reportOverlay.hidden) return;
5467
+ markFirstRunDone(runApp);
5468
+ $reportModal.dataset.html = '1';
5469
+ appendNarration(`Rendered the complete read-only property report from <strong>${escapeHtml(nodeId)}</strong>.`);
5470
+ });
5295
5471
  return;
5296
5472
  }
5297
5473
  const html = res.report && res.report.html;
5298
5474
  const interactive = !!(res.report && res.report.interactive);
5299
- if (!html) {
5300
- $reportSub.textContent = 'Execution ended without an HTML report.';
5301
- $reportOverlay.innerHTML = `<div>Run completed but <code>${escapeHtml(nodeId)}</code> returned no <code>html</code>. Check the Execution tab.</div>`;
5302
- return;
5303
- }
5475
+ if (!html) { showNoReport(res, nodeId, app.id); return; }
5304
5476
  if (interactive) {
5305
5477
  $reportTitle.textContent = `3D Viewer · ${app.displayName}`;
5306
5478
  $reportSub.innerHTML = `Live 3D view from <code>${escapeHtml(nodeId)}</code>${inputBadge ? ' · ' + escapeHtml(inputBadge) : ''} — drag to orbit, scroll to zoom, click an element to inspect.`;
5307
5479
  }
5308
- paintReport(html, interactive);
5480
+ const withFiles = !!(res.report && res.report.withFiles);
5481
+ paintReport(html, interactive, { withFiles, runId: typeof res.runId === 'string' ? res.runId : null });
5309
5482
  if (!interactive) $reportSub.textContent = 'Report created from the latest workflow run.';
5310
5483
  // If a node wrote an output file, the run reports its path — surface the
5311
5484
  // ⧉ Open file / ▤ Reveal buttons and cache it so a later double-click restores them (#209).
5312
5485
  const savedPath = res && typeof res.savedPath === 'string' ? res.savedPath : '';
5313
5486
  showSavedPathActions(savedPath);
5314
5487
  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)
5315
- lastReportByApp.set(currentId, { nodeId, label: inputBadge, html, interactive, savedPath, runId: typeof res.runId === 'string' ? res.runId : null });
5488
+ lastReportByApp.set(currentId, { nodeId, label: inputBadge, html, interactive, savedPath, withFiles, runId: typeof res.runId === 'string' ? res.runId : null });
5316
5489
  paintReportPageLinks();
5317
5490
  $reportModal.dataset.html = '1';
5318
5491
  appendNarration(`Rendered the ${interactive ? '3D view' : 'report'} from <strong>${escapeHtml(nodeId)}</strong>${inputBadge ? ' (' + escapeHtml(inputBadge) + ')' : ''} — live run against the model.`);
@@ -5347,6 +5520,7 @@
5347
5520
  if (clientRunToken) { if (liveOutcome === 'no-answer') settleLiveRunWithoutAnswer(); else finishLiveRun(liveOutcome); }
5348
5521
  reportRunning = false;
5349
5522
  syncRunControls(); // run ended — hide the header Stop, restore Run from the gate
5523
+ paintReportPageLinks(); // #2539: hidden while the run was in flight; its Page version may already be known
5350
5524
  }
5351
5525
  }
5352
5526
 
@@ -5428,6 +5602,50 @@
5428
5602
  if (first) first.focus(); else { card.tabIndex = -1; card.focus(); } // #2123: a not-run card may have no button
5429
5603
  }
5430
5604
 
5605
+ // A run that finished without report HTML. #2415: when an AI step in it did not answer (its -ok check stops the run on
5606
+ // purpose), say which step and offer its questions instead of the generic words.
5607
+ function showNoReport(res, nodeId, appId) {
5608
+ const aiStop = globalThis.flolessAgentSteps?.stoppedReportView(res, nodeId);
5609
+ if (aiStop) { showAiStepStopped(aiStop, appId); return; }
5610
+ $reportSub.textContent = 'Execution ended without an HTML report.';
5611
+ $reportOverlay.innerHTML = `<div>Run completed but <code>${escapeHtml(nodeId)}</code> returned no <code>html</code>. Check the Execution tab.</div>`;
5612
+ }
5613
+
5614
+ // #2415: the run stopped before the report because an AI step did not answer. Not a fault, so no Report this problem:
5615
+ // the way on is the step's questions, in the canvas's Last run panel. textContent only — step names come from the run.
5616
+ function showAiStepStopped(view, appId) {
5617
+ clearReportFrames();
5618
+ $reportShare.hidden = true;
5619
+ $reportOverlay.hidden = false;
5620
+ $reportOverlay.replaceChildren();
5621
+ $reportSub.textContent = view.sub;
5622
+ const card = mkEl('div', 'cred-fail-card run-fail-card ai-stop-card');
5623
+ card.setAttribute('role', 'status');
5624
+ const status = mkEl('div', 'cred-fail-status');
5625
+ const icon = mkEl('span', 'cred-fail-icon', typeof floAvatar === 'function' ? '' : '△');
5626
+ icon.setAttribute('aria-hidden', 'true');
5627
+ if (typeof floAvatar === 'function') { icon.classList.add('run-fail-flo'); floAvatar(icon, { size: 28, mood: 'warning' }); }
5628
+ status.append(icon, document.createTextNode(view.status));
5629
+ const actions = mkEl('div', 'cred-fail-actions');
5630
+ const open = mkEl('button', 'cred-open-integrations ai-stop-open', view.button);
5631
+ open.type = 'button';
5632
+ open.dataset.commandId = view.commandId;
5633
+ open.onclick = async () => {
5634
+ // The viewer closes only once Last run shows THIS run; otherwise it stays open, with focus on the button, and says why.
5635
+ let shown = false;
5636
+ try { shown = await globalThis.flolessAgentSteps?.openQuestions(appId, view.runId, () => hideModal($reportModal)) === true; } catch { shown = false; }
5637
+ if (shown) return;
5638
+ showToast(view.listed
5639
+ ? 'FloLess couldn’t show this run’s questions yet. Close the viewer, then open Last run above the canvas.'
5640
+ : 'FloLess couldn’t show this run in Last run yet. Close the viewer, then open Last run above the canvas.', 'warn');
5641
+ open.focus();
5642
+ };
5643
+ actions.append(open);
5644
+ card.append(status, mkEl('div', 'cred-fail-headline', view.headline), mkEl('div', 'cred-fail-body', view.body), actions);
5645
+ $reportOverlay.append(card);
5646
+ open.focus();
5647
+ }
5648
+
5431
5649
  const CRED_BODY_IDLE = 'Sign in again and then run the workflow — it takes about 30 seconds.';
5432
5650
 
5433
5651
  function showCredentialReconnect(cred) {
@@ -6409,6 +6627,8 @@
6409
6627
 
6410
6628
  async function closeReportViewer() {
6411
6629
  hideModal($reportModal);
6630
+ runPageView.invalidate(); // #2476: nothing about a report with files keeps running behind a closed viewer
6631
+ reportSectionRequest += 1; // #2539: a section still waiting for a busy report stops asking once the viewer closes
6412
6632
  const routineId = viewingScheduledReportRoutine;
6413
6633
  viewingScheduledReportRoutine = null;
6414
6634
  if (!routineId) return;
@@ -6442,7 +6662,11 @@
6442
6662
  window.addEventListener('message', (e) => {
6443
6663
  if ($reportFrame3d.hidden || e.source !== $reportFrame3d.contentWindow) return;
6444
6664
  const t = e.data && e.data.type;
6445
- if (t === 'viewer-ready') { $reportOverlay.hidden = true; $reportOverlay.replaceChildren(); }
6665
+ if (t === 'viewer-ready') {
6666
+ $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
6667
+ // #2262 slice 3c: a 3D view is a Page version too; its "Open in Pages" link waits for the view to be ready.
6668
+ paintReportPageLinks();
6669
+ }
6446
6670
  else if (t === 'viewer-error') {
6447
6671
  $reportOverlay.hidden = false; $reportOverlay.replaceChildren();
6448
6672
  $reportOverlay.append(mkEl('div', null, '3D view failed to load — check your connection, then click ▶ Run workflow to try again.'));
@@ -6472,6 +6696,7 @@
6472
6696
  $reportLast.onclick = () => { if (currentCompleteReport) void paintCompleteReport(currentCompleteReport, currentCompleteReport.chunkCount - 1); };
6473
6697
  $reportGoObject.onclick = async () => {
6474
6698
  if (!currentCompleteReport) return;
6699
+ const lookup = ++reportObjectLookup;
6475
6700
  const raw = $reportObjectNumber.value.trim();
6476
6701
  const number = Number(raw);
6477
6702
  if (!/^[1-9][0-9]*$/.test(raw) || !Number.isSafeInteger(number) || number > currentCompleteReport.objectCount) {
@@ -6481,11 +6706,36 @@
6481
6706
  return;
6482
6707
  }
6483
6708
  $reportObjectError.hidden = true;
6709
+ const report = currentCompleteReport;
6710
+ const request = reportSectionRequest;
6711
+ const waitUntil = Date.now() + 5 * 60_000;
6712
+ // Stale once the viewer closed or moved on, or a newer Go took over. The message belongs to the newest lookup, so a
6713
+ // stale one clears only its own text, and only when no newer lookup has written there.
6714
+ const stale = () => lookup !== reportObjectLookup || request !== reportSectionRequest || currentCompleteReport !== report;
6715
+ const leave = () => { if (lookup === reportObjectLookup) $reportObjectError.hidden = true; };
6484
6716
  try {
6485
- const located = await api(`/api/model-reports/${encodeURIComponent(currentCompleteReport.handle)}/object/${number - 1}`);
6486
- await paintCompleteReport(currentCompleteReport, located.chunkOrdinal);
6717
+ let located;
6718
+ for (;;) {
6719
+ try { located = await api(`/api/model-reports/${encodeURIComponent(report.handle)}/object/${number - 1}`); break; }
6720
+ catch (error) {
6721
+ // #2539: a busy report is waited for here too, saying why, and the object opens by itself.
6722
+ if (error?.body?.code !== 'report-busy' || Date.now() >= waitUntil) throw error;
6723
+ if (stale()) { leave(); return; } // a busy answer for a lookup already replaced writes nothing
6724
+ $reportObjectError.textContent = String(error.body.error || 'This report is busy. It opens as soon as that finishes.');
6725
+ $reportObjectError.hidden = false;
6726
+ await new Promise((resolve) => setTimeout(resolve, Math.min(10_000, Math.max(500, Number(error.body.retryAfterMs) || 2_000))));
6727
+ if (stale()) { leave(); return; }
6728
+ }
6729
+ }
6730
+ // The viewer may have closed or moved on while the lookup was answered: then it opens nothing, and drops the wait's text.
6731
+ if (stale()) { leave(); return; }
6732
+ $reportObjectError.hidden = true;
6733
+ await paintCompleteReport(report, located.chunkOrdinal);
6487
6734
  } catch (error) {
6488
- $reportObjectError.textContent = error?.message || 'Could not find that object. Try again.';
6735
+ if (stale()) { leave(); return; }
6736
+ $reportObjectError.textContent = error?.body?.code === 'report-busy'
6737
+ ? 'This report is still busy. Choose Go again to open that object.'
6738
+ : error?.message || 'Could not find that object. Try again.';
6489
6739
  $reportObjectError.hidden = false;
6490
6740
  }
6491
6741
  };
@@ -6495,7 +6745,16 @@
6495
6745
  $reportFrame.addEventListener('load', () => {
6496
6746
  if (!currentCompleteReport || !$reportFrame.getAttribute('src')?.startsWith('/api/model-reports/')) return;
6497
6747
  try {
6498
- if ($reportFrame.contentDocument?.contentType === 'text/html') return;
6748
+ const shown = $reportFrame.contentDocument;
6749
+ if (shown?.contentType === 'text/html') return;
6750
+ // #2539: the report became busy between the section check and the frame's own request. Wait for it like any
6751
+ // busy read instead of calling it changed access.
6752
+ if (shown?.contentType === 'application/json' && JSON.parse(shown.body?.textContent || 'null')?.code === 'report-busy') {
6753
+ // Only for the paint still current (closing the viewer or moving on ends it), and within its first deadline.
6754
+ if ($reportFrame.dataset.request !== String(reportSectionRequest)) return;
6755
+ void paintCompleteReport(currentCompleteReport, currentReportSection, Number($reportFrame.dataset.busyUntil) || null);
6756
+ return;
6757
+ }
6499
6758
  } catch { /* an inaccessible document is not an authenticated report */ }
6500
6759
  clearCompleteReportView();
6501
6760
  $reportFrame.removeAttribute('src');
@@ -6512,7 +6771,10 @@
6512
6771
  link.download = 'complete-model-properties.html';
6513
6772
  document.body.append(link); link.click(); link.remove();
6514
6773
  } catch (error) {
6515
- showToast(error?.message || 'Report access could not be confirmed. Try again.', 'warn');
6774
+ // #2539: busy is not a failure of access; the report is there, it is just being read.
6775
+ showToast(error?.body?.code === 'report-busy'
6776
+ ? 'This report is busy, so it can’t be downloaded yet. Choose Download complete report again in a moment.'
6777
+ : error?.message || 'Report access could not be confirmed. Try again.', 'warn');
6516
6778
  }
6517
6779
  };
6518
6780
 
@@ -6607,12 +6869,93 @@
6607
6869
  };
6608
6870
  $promptSel.onchange = () => { showWorkflowsLanding(false); loadApp($promptSel.value).catch(reportErr); };
6609
6871
 
6610
- $compileBtn.onclick = async () => {
6872
+ /**
6873
+ * #2314: two steps share one name, so AWARE cannot compile the workflow. Ask which to rename; after a rename, compile again (the
6874
+ * workflow changed, so it is approved again, and an AI step's confirmation is asked of the person again). Cancel keeps it as is.
6875
+ */
6876
+ async function renameStepThenCompile(id, ask) {
6877
+ const outcome = globalThis.flolessStepRename ? await globalThis.flolessStepRename.open(ask) : { renamed: false };
6878
+ if (!outcome.renamed) {
6879
+ // Keep the reason in view: the person cancelled the rename, so the workflow still cannot compile, and here is why.
6880
+ showToast(`${ask && ask.sentence ? `${ask.sentence} ` : ''}Nothing was renamed, so the workflow is not compiled yet.`, 'warn');
6881
+ return;
6882
+ }
6883
+ const r = outcome.result || {};
6884
+ if (r.warning) {
6885
+ // The rename did not land exactly as previewed (or could not be checked): the person looks before anything compiles.
6886
+ showToast(r.warning, 'warn');
6887
+ appendNarration(`Renamed the step <strong>${escapeHtml(r.renamed?.from || '')}</strong> to <strong>${escapeHtml(r.renamed?.to || '')}</strong>. ${escapeHtml(r.warning)}`);
6888
+ if (currentId === id) { try { await loadApp(id); } catch (e) { reportErr(e); } }
6889
+ return;
6890
+ }
6891
+ 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.`);
6892
+ if (currentId !== id) return;
6893
+ try { await loadApp(id); } catch (e) { reportErr(e); return; }
6894
+ if (currentId === id) await compileCurrentWorkflow();
6895
+ }
6896
+
6897
+ /**
6898
+ * #2474: a workflow you own runs from an immutable published copy, so its Compile publishes a new version from the
6899
+ * workflow's own file, exactly as the draft view does (`/api/compile` on the copy is refused). Consent works as it does
6900
+ * there: building is allowed, and the new version's AI step is confirmed by the person before it runs (Run asks). The
6901
+ * confirmation dialog is not shown first, because it could only show the old copy, not the bytes being published.
6902
+ */
6903
+ async function publishOwnedFromHeader(id, workflowId) {
6904
+ const name = workflowLabelOf(id);
6905
+ $compileBtn.disabled = true;
6906
+ const prev = $compileBtn.textContent;
6907
+ $compileBtn.textContent = '⎙ Compiling…';
6908
+ const restore = () => { $compileBtn.textContent = prev; $compileBtn.disabled = false; };
6909
+ let newId;
6910
+ try {
6911
+ const res = await api(`/api/workflows/owned/${encodeURIComponent(workflowId)}/publish`, { method: 'POST' });
6912
+ newId = res?.workflow?.activePublication?.runtimeAppId || null;
6913
+ } catch (e) {
6914
+ restore();
6915
+ const ask = globalThis.flolessStepRename ? globalThis.flolessStepRename.askOf(e) : null;
6916
+ if (ask) { await renameStepThenCompile(id, ask); return; }
6917
+ // The publish route's own refusal is a sentence for the person; anything else is reported as usual.
6918
+ if (e?.body?.code === 'workflow-compile-failed' && typeof e.body.error === 'string') { showToast(e.body.error, 'warn'); return; }
6919
+ reportErr(e);
6920
+ return;
6921
+ }
6922
+ const notOpened = `${name} is compiled. FloLess couldn’t open the new version — open it from the Workflows page.`;
6923
+ // Only the publish answer names the new version: never fall back to the old copy, which would show the old steps as current.
6924
+ if (!newId) { restore(); showToast(notOpened, 'warn'); return; }
6925
+ // Refresh the lists without letting the refresh pick a workflow to open; the new version is opened next, on purpose.
6926
+ const owner = ownedWorkflowOf(id);
6927
+ try { await loadApps({ preserveSelection: true }); } catch (e) { console.warn('[compile] the workflow list could not be refreshed', e); }
6928
+ // The new version belongs to the same workflow. Even when the refresh failed, it is known as owned, so its next Compile
6929
+ // publishes again instead of reaching the refused copy.
6930
+ if (owner && !ownedWorkflowOf(newId)) workflowOwners.set(newId, owner);
6931
+ // The person opened something else meanwhile: its own load repainted the button, so it is left as that workflow shows it.
6932
+ if (currentId !== id) { showToast(`${name} is compiled.`, 'ok'); return; }
6933
+ try { await loadApp(newId); } catch (e) { console.warn('[compile] the new version could not be opened', e); restore(); showToast(notOpened, 'warn'); return; }
6934
+ if (currentId !== newId) { showToast(`${name} is compiled.`, 'ok'); return; } // a newer choice won while it was opening
6935
+ const app = apps.get(newId);
6936
+ const consent = globalThis.flolessAgentSteps?.consentStatus ? await globalThis.flolessAgentSteps.consentStatus(newId) : null;
6937
+ const unconfirmed = consent && (consent.state === 'needed' || consent.state === 'changed');
6938
+ if (unconfirmed) {
6939
+ 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.');
6940
+ showToast('Workflow compiled. Confirm its AI step before it runs.', 'ok');
6941
+ } else {
6942
+ appendNarration(app?.runnable
6943
+ ? 'Workflow compiled. Review any notices above the canvas before running.'
6944
+ : `Compiled, but ${app?.notes?.length ?? 0} notice(s) remain — review them above the canvas.`);
6945
+ showToast('Workflow compiled', 'ok');
6946
+ }
6947
+ maybeAskPolicyAfterApproval();
6948
+ }
6949
+
6950
+ async function compileCurrentWorkflow() {
6611
6951
  if (!currentId || $compileBtn.disabled || $compileBtn.hidden) return; // hidden = suppressed for a maintained drift
6612
6952
  const id = currentId;
6953
+ const ownedId = ownedWorkflowOf(id)?.ownedWorkflow?.workflowId || null;
6954
+ if (ownedId) { await publishOwnedFromHeader(id, ownedId); return; }
6613
6955
  // #2241 S4: a workflow with an AI step nobody has confirmed (or that changed) is approved from the confirmation dialog, which
6614
6956
  // records the tick and approves the exact bytes it showed. 'proceed' = nothing to ask, the normal compile goes on.
6615
6957
  const consent = globalThis.flolessAgentSteps ? await globalThis.flolessAgentSteps.confirmBeforeApprove(apps.get(id) || { id }) : 'proceed';
6958
+ if (consent === 'rename-step') { await renameStepThenCompile(id, globalThis.flolessAgentSteps.takeRenameAsk()); return; }
6616
6959
  if (consent === 'cancel' || currentId !== id) return;
6617
6960
  $compileBtn.disabled = true;
6618
6961
  const prev = $compileBtn.textContent;
@@ -6630,9 +6973,12 @@
6630
6973
  } catch (e) {
6631
6974
  $compileBtn.textContent = prev;
6632
6975
  $compileBtn.disabled = false;
6976
+ const ask = globalThis.flolessStepRename ? globalThis.flolessStepRename.askOf(e) : null;
6977
+ if (ask) { await renameStepThenCompile(id, ask); return; }
6633
6978
  reportErr(e);
6634
6979
  }
6635
- };
6980
+ }
6981
+ $compileBtn.onclick = () => compileCurrentWorkflow();
6636
6982
 
6637
6983
  // ── Bake into agent ──────────────────────────────────────────────────────────
6638
6984
  // Open a preview/confirm modal (agent name + the inputs it will expose, mirrored
@@ -7213,14 +7559,8 @@
7213
7559
 
7214
7560
  function graftTeklaReadErrorMessage(error) {
7215
7561
  const body = error?.body;
7216
- if (error?.status === 402 || body?.error === 'subscription required') {
7217
- if (body?.state === 'expired') return 'Your FloLess subscription has expired. Renew your FloLess subscription, then try again.';
7218
- 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.';
7219
- if (body?.reason === 'session-expired') return 'Your FloLess sign-in has expired. Sign in again, then try again.';
7220
- if (body?.reason === 'signed-out') return 'You are signed out of FloLess. Sign in again, then try again.';
7221
- if (body?.reason === 'seat-taken') return 'Your FloLess session has ended. Sign in again, then try again.';
7222
- return 'Sign in to FloLess to check your account access, then try again.';
7223
- }
7562
+ const access = accountAccessText(error);
7563
+ if (access) return access;
7224
7564
  if (body?.bootstrap === 'failed') {
7225
7565
  return 'FloLess could not prepare its runtime. Choose Try again on the setup card, then verify the model read again.';
7226
7566
  }
@@ -7813,7 +8153,10 @@
7813
8153
  }
7814
8154
  showToast(body && body.code === 'exists'
7815
8155
  ? 'A workflow with that name already exists. Choose a different name, then try again.'
7816
- : 'We couldn’t import that workflow because FloLess could not read it. Check the file, then try again.', 'err');
8156
+ // #2470: the server's sentence names the General project id and a name to use instead.
8157
+ : body && body.code === 'reserved-id' && typeof body.error === 'string' && body.error
8158
+ ? `${body.error} Change the app: line in the file, then import it again.`
8159
+ : 'We couldn’t import that workflow because FloLess could not read it. Check the file, then try again.', 'err');
7817
8160
  }
7818
8161
  } finally {
7819
8162
  _importing = false; // every path, including an unreadable file and the dialog's early return
@@ -8074,6 +8417,7 @@
8074
8417
  const $body = $notesPopover.querySelector('.relnotes-body');
8075
8418
  let notes = null;
8076
8419
  try {
8420
+ await globalThis.flolessStartupAdmission?.admit('/api/release-notes');
8077
8421
  const r = await fetch('/api/release-notes?component=' + encodeURIComponent(component) + '&version=' + encodeURIComponent(version));
8078
8422
  notes = await r.json();
8079
8423
  } catch { notes = null; }
@@ -8179,6 +8523,7 @@
8179
8523
  resetNotesAffordance(el);
8180
8524
  let notes = null;
8181
8525
  try {
8526
+ await globalThis.flolessStartupAdmission?.admit('/api/release-notes');
8182
8527
  const r = await fetch('/api/release-notes?component=' + encodeURIComponent(component) + '&version=' + encodeURIComponent(version));
8183
8528
  notes = await r.json();
8184
8529
  } catch { notes = null; }
@@ -8286,6 +8631,7 @@
8286
8631
  async function refreshUpdate() {
8287
8632
  if (!$appUpdate) return;
8288
8633
  try {
8634
+ await globalThis.flolessStartupAdmission?.admit('/api/update');
8289
8635
  const r = await fetch('/api/update');
8290
8636
  const d = await r.json();
8291
8637
  if (r.ok && d.supported && d.updateAvailable && d.targetVersion) {
@@ -8350,6 +8696,7 @@
8350
8696
  }
8351
8697
  async function refreshWorkflowUpdates() {
8352
8698
  try {
8699
+ await globalThis.flolessStartupAdmission?.admit('/api/workflows/updates');
8353
8700
  const r = await fetch('/api/workflows/updates');
8354
8701
  const d = await r.json();
8355
8702
  _wfUpdates = (r.ok && d.ok && Array.isArray(d.updates)) ? d.updates : [];
@@ -8576,6 +8923,7 @@
8576
8923
  if (!$awareUpdate) return;
8577
8924
  if (awareJobOwnsPill()) return;
8578
8925
  try {
8926
+ await globalThis.flolessStartupAdmission?.admit('/api/aware/update');
8579
8927
  const r = await fetch('/api/aware/update');
8580
8928
  const d = await r.json();
8581
8929
  if (awareJobOwnsPill()) return; // the job resolved while this request was in flight
@@ -9282,6 +9630,7 @@
9282
9630
  (async () => {
9283
9631
  let notes = null;
9284
9632
  try {
9633
+ await globalThis.flolessStartupAdmission?.admit('/api/release-notes');
9285
9634
  const r = await fetch('/api/release-notes?component=app&version=' + encodeURIComponent(pending));
9286
9635
  notes = await r.json();
9287
9636
  } catch { notes = null; }
@@ -9473,6 +9822,8 @@
9473
9822
  // #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
9474
9823
  // ends, never cleared here: the trace is replayed after a run, and a clear would discard the refresh already in flight.)
9475
9824
  globalThis.flolessAgentSteps?.noteTrace(ev);
9825
+ if (ev.kind === 'run-start') traceRunId = typeof ev.run_id === 'string' ? ev.run_id : null;
9826
+ let usePill = null;
9476
9827
  switch (ev.kind) {
9477
9828
  case 'run-start': msg = `run start · ${escapeHtml(ev.app || '')} (${escapeHtml(ev.instance || 'default')})${runStartApprovalNote(ev)}`; break;
9478
9829
  case 'node-start': lvl = 'event'; msg = `node ${node} · ${agent}${cmd}`; break;
@@ -9480,12 +9831,24 @@
9480
9831
  case 'node-output': case 'output': case 'write': lvl = 'ok'; msg = `${escapeHtml(ev.kind)} ${node}`.trim();
9481
9832
  // #2241 S5: AWARE marks an Agent step's output; the trace says so wherever it shows the output.
9482
9833
  if (ev.nondeterministic === true && globalThis.flolessAgentSteps) msg += ` ${globalThis.flolessAgentSteps.aiPillHtml()}`;
9834
+ // #2374: an output FloLess found built on (or decided by) an Agent step's answer is labelled too, in quieter words.
9835
+ else if (ev.node) usePill = { node: ev.node, runId: typeof ev.run_id === 'string' ? ev.run_id : traceRunId };
9483
9836
  break;
9484
9837
  case 'run-end': lvl = ev.status === 'ok' ? 'ok' : 'err'; msg = `run ${escapeHtml(ev.status || 'ended')}`; break;
9485
9838
  default: msg = `${escapeHtml(ev.kind)} ${node}`.trim();
9486
9839
  }
9487
9840
  // `node` (the raw node id) feeds the Execution tab's node-filter chips.
9488
- liveTrace.push({ kind: ev.kind, ts: fmtTs(ev.ts), lvl, msg, node: ev.node || '' });
9841
+ const row = { kind: ev.kind, ts: fmtTs(ev.ts), lvl, msg, node: ev.node || '' };
9842
+ // #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).
9843
+ if (usePill) {
9844
+ let text = msg;
9845
+ Object.defineProperty(row, 'msg', {
9846
+ enumerable: true,
9847
+ get() { const pill = globalThis.flolessAgentSteps?.usePillHtml?.(usePill.node, usePill.runId) || ''; return pill ? `${text} ${pill}` : text; },
9848
+ set(value) { text = value; },
9849
+ });
9850
+ }
9851
+ liveTrace.push(row);
9489
9852
 
9490
9853
  // Paint the node's status on the canvas as the trace streams in. Once the
9491
9854
  // user hits Stop, leave the canvas alone — late SSE events (the fs-watcher
@@ -9613,6 +9976,9 @@
9613
9976
  // idea whether Node.js is missing. Telling someone to install what they already
9614
9977
  // have is the exact bug this reason exists to prevent.
9615
9978
  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.";
9979
+ case 'aware-version-unreadable':
9980
+ // The version check did not answer (usually a busy machine); AWARE is not necessarily old.
9981
+ 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.";
9616
9982
  case 'aware-version-required':
9617
9983
  return 'This FloLess release needs AWARE 0.157.0 or newer. Update AWARE, then try again.';
9618
9984
  case 'offline':
@@ -10244,10 +10610,9 @@
10244
10610
  const healthTick = async () => {
10245
10611
  let ok = false;
10246
10612
  try {
10247
- const r = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(45_000) });
10248
- ok = r.ok;
10613
+ const h = await readHealth();
10614
+ ok = true;
10249
10615
  if (ok) {
10250
- const h = await r.json();
10251
10616
  // Stamp the build + AWARE runtime versions into the footer once (so a
10252
10617
  // stale install or AWARE mismatch is self-diagnosable). appVersion is
10253
10618
  // the real sq.version on an install (package.json only from source);
@@ -10370,12 +10735,44 @@
10370
10735
  const es = new EventSource('/api/events');
10371
10736
  let reloadTimer = null;
10372
10737
  let everOpened = false;
10738
+ let rootDisconnected = false;
10739
+ let connectionGeneration = 0;
10740
+ let pendingCatchup = null;
10741
+ function drainPendingCatchup() {
10742
+ const generation = pendingCatchup;
10743
+ const roots = window.flolessWorkspaceRoot;
10744
+ if (generation === null || generation !== connectionGeneration || !roots?.isCurrent(roots.current())) return;
10745
+ // Clear before dispatch: root publication and its GET continuation may both arrive here.
10746
+ pendingCatchup = null;
10747
+ window.dispatchEvent(new CustomEvent('floless:apps-changed', { detail: {} }));
10748
+ window.dispatchEvent(new CustomEvent('floless:projects-changed', { detail: {} }));
10749
+ window.dispatchEvent(new CustomEvent('floless:action-proposal', { detail: { resync: true } }));
10750
+ loadRequests();
10751
+ const workflowId = currentId;
10752
+ if (workflowId) refreshCurrentWorkflowAvailability().catch(error => {
10753
+ if (generation === connectionGeneration) reportBackgroundAvailabilityErr(error);
10754
+ });
10755
+ void refreshSelectedCompleteReportDiscovery(workflowId);
10756
+ void resyncLiveRun();
10757
+ if (workflowId) void refreshWorkflowPage(workflowId);
10758
+ }
10759
+ // One unfinished reconnect may resume after an existing dialog refresh or root selection.
10760
+ window.addEventListener('floless:workspace-root-state', drainPendingCatchup);
10373
10761
  es.onopen = () => {
10762
+ const reconnect = everOpened || rootDisconnected;
10763
+ everOpened = true;
10764
+ rootDisconnected = false;
10765
+ const generation = ++connectionGeneration;
10766
+ pendingCatchup = reconnect ? generation : null;
10767
+ if (reconnect) {
10768
+ window.flolessWorkspaceRoot.invalidateConnection();
10769
+ globalThis.flolessStartupAdmission?.invalidate();
10770
+ }
10374
10771
  setServerStatus(true);
10375
10772
  // Core provisioning may have finished after the page read /api/apps but before this
10376
10773
  // at-most-once stream connected. Re-read the catalogue on every open, including the
10377
10774
  // first one; Workspaces defers its repaint while a dialog is active.
10378
- window.dispatchEvent(new CustomEvent('floless:apps-changed', { detail: {} }));
10775
+ if (!reconnect) window.dispatchEvent(new CustomEvent('floless:apps-changed', { detail: {} }));
10379
10776
  // A RECONNECT MEANS WE MISSED WHATEVER HAPPENED WHILE WE WERE GONE — and this catches up the
10380
10777
  // PROJECT half of that, not every arm below (workflow imports, contract writes and the rest
10381
10778
  // still heal on their next event or a reload). These events are
@@ -10386,25 +10783,21 @@
10386
10783
  // reconnect only (never the first connect, which has nothing to catch up on) and carry NO
10387
10784
  // payload: workspaces.js answers an empty event by re-reading the live set, which is exactly
10388
10785
  // the catch-up question. (Found by review.)
10389
- if (everOpened) {
10390
- window.dispatchEvent(new CustomEvent('floless:projects-changed', { detail: {} }));
10391
- // #2248: requests from the terminal made or answered during the gap are read again too.
10392
- window.dispatchEvent(new CustomEvent('floless:action-proposal', { detail: { resync: true } }));
10393
- loadRequests();
10394
- // The SAME catch-up for the other half a live `projects-changed` drives (see that arm): the
10395
- // open workflow's publication availability turns on project state, so a gap leaves the card
10396
- // asserting a state that may no longer hold. Re-asking for Workspaces but not for Workflows
10397
- // would fix one stale surface and leave its sibling. (Found by review round 2.)
10398
- if (currentId) refreshCurrentWorkflowAvailability().catch(reportErr);
10786
+ if (reconnect) {
10787
+ // The catalogue event also reads projects. None of this catch-up can use a cached root
10788
+ // from the previous server. A later accepted dialog observation may finish this work too.
10789
+ window.flolessWorkspaceRoot.refresh({ throwOnError: true,
10790
+ isCurrent: () => generation === connectionGeneration,
10791
+ }).then(drainPendingCatchup).catch(() => {
10792
+ if (generation === connectionGeneration && pendingCatchup === generation) showToast('FloLess could not check the current Workspace directory. Open Workspace directory to try again.', 'err');
10793
+ });
10794
+ return;
10399
10795
  }
10400
10796
  // Scheduled reports may finish with every browser closed; refresh their authorized
10401
10797
  // pointers on both first connection and reconnect, never from SSE payload data.
10402
10798
  void refreshSelectedCompleteReportDiscovery(currentId);
10403
10799
  // #2228: progress events are at-most-once too — a reload or a reconnect asks where this tab's run is.
10404
10800
  void resyncLiveRun();
10405
- // #2262 slice 3a: a capture that landed while we were gone is read again, for the workflow on screen.
10406
- if (everOpened && currentId) void refreshWorkflowPage(currentId);
10407
- everOpened = true;
10408
10801
  };
10409
10802
  es.onmessage = (e) => {
10410
10803
  let m;
@@ -10430,8 +10823,9 @@
10430
10823
  // workflow this tab shows that someone else started is followed read-only (no Stop).
10431
10824
  // #2241: a run that FAILED after an Agent answered ends with run-finished, not run-ended: its AI record is read then too.
10432
10825
  if (m.type === 'run-finished' && m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id);
10826
+ signalRunEvent(m); // the browser tab hears its run's ending even when the strip already settled
10433
10827
  if (liveRunOwns(m)) {
10434
- if (m.type === 'run-live') { if (m.runId) liveRun.runId = m.runId; }
10828
+ if (m.type === 'run-live') { if (m.runId) { liveRun.runId = m.runId; signalRunNote(liveRun); } }
10435
10829
  else if (m.type === 'node-progress') onLiveProgress(m);
10436
10830
  else finishLiveRun(typeof m.outcome === 'string' ? m.outcome : 'failed');
10437
10831
  } else if (m.id === currentId && !(liveRun && liveRun.owner && !liveRun.ended)) {
@@ -10467,7 +10861,11 @@
10467
10861
  // `clearExportReceiptsForApp` repaints via markSpecialNodes(), so the stale map was actively
10468
10862
  // RE-APPLIED rather than merely left behind. Nothing self-healed until the user switched
10469
10863
  // workflows. Re-read the payload rather than guess at the new state.
10470
- if (m.appId === currentId) refreshCurrentWorkflowAvailability().catch(reportErr);
10864
+ if (m.appId === currentId) refreshCurrentWorkflowAvailability().catch(reportBackgroundAvailabilityErr);
10865
+ } else if (m.type === 'contract-changed' && typeof m.appId === 'string' && typeof m.project === 'string') {
10866
+ // #2482: a PROJECT's contract changed (a checklist draft, a reference added from AI Chat). workspaces.js relays
10867
+ // it to that project's open editor frame, which has no event stream of its own.
10868
+ window.dispatchEvent(new CustomEvent('floless:contract-changed', { detail: m }));
10471
10869
  } else if (m.type === 'projects-changed') {
10472
10870
  // Relayed as a DOM event for the same reason apps-changed is (see that arm below):
10473
10871
  // workspaces.js owns the project view and is the only listener. It reconciles the project it
@@ -10479,7 +10877,7 @@
10479
10877
  // this tab happens to be showing.
10480
10878
  window.dispatchEvent(new CustomEvent('floless:projects-changed', { detail: m }));
10481
10879
  if (m.kind !== 'metadata' && (typeof m.appId !== 'string' || m.appId === currentId)) {
10482
- refreshCurrentWorkflowAvailability().catch(reportErr);
10880
+ refreshCurrentWorkflowAvailability().catch(reportBackgroundAvailabilityErr);
10483
10881
  }
10484
10882
  } else if (m.type === 'workspace-root-changed') {
10485
10883
  // Root identity/path belongs to the server's protected registry. Re-read it so every open tab
@@ -10621,6 +11019,9 @@
10621
11019
  // The terminal AI (or undo/reset) rewrote ~/.floless/ui/extensions.json —
10622
11020
  // re-render the Dashboard / inspect-tab panels live. panels.js owns it.
10623
11021
  if (window.flolessPanels) window.flolessPanels.refresh({ fromChange: true });
11022
+ } else if (m.type === 'knowledge-changed') {
11023
+ // #2399 slice 0b: a chat, a terminal or another window changed a project's references or design set.
11024
+ window.flolessWorkspaces?.knowledgeChanged?.(m.projectId);
10624
11025
  } else if (m.type === 'revision-note-changed') {
10625
11026
  window.dispatchEvent(new CustomEvent('floless:revision-note-changed', { detail: m }));
10626
11027
  } else if (m.type === 'run-ended') {
@@ -10629,9 +11030,15 @@
10629
11030
  if (m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id); // #2241 S5
10630
11031
  } else if (m.type === 'routine-changed') {
10631
11032
  loadRoutinesData();
11033
+ window.flolessProjectAccess?.refresh?.(); // Project access lists schedules: its chip count and open sheet follow
11034
+ } else if (m.type === 'agent-step-fires-changed') {
11035
+ // S8: a watcher's AI step recorded an event: its Inspect history and its routine card count are read again.
11036
+ globalThis.flolessAgentSteps?.watcherChanged?.(m.id);
11037
+ if (m.routineId) loadRoutinesData();
10632
11038
  } else if (m.type === 'agent-changed') {
10633
11039
  // #2062: an agent was paused, resumed, archived or restored; an open page of it shows the new state.
10634
11040
  window.flolessAgents?.refreshAgent?.(m.agentId);
11041
+ window.flolessProjectAccess?.refresh?.();
10635
11042
  } else if (m.type === 'routine-run-started') {
10636
11043
  runningRoutines.add(m.id);
10637
11044
  if ($routinesModal.classList.contains('show')) renderRoutinesList();
@@ -10705,7 +11112,13 @@
10705
11112
  recheckLicenseAndGate();
10706
11113
  }
10707
11114
  };
10708
- es.onerror = () => setServerStatus(false); // server unreachable → red; EventSource auto-reconnects (onopen → green)
11115
+ es.onerror = () => {
11116
+ connectionGeneration++;
11117
+ pendingCatchup = null;
11118
+ rootDisconnected = true;
11119
+ window.flolessWorkspaceRoot.invalidateConnection();
11120
+ setServerStatus(false); // EventSource auto-reconnects; an earlier continuation must not catch up.
11121
+ };
10709
11122
  }
10710
11123
 
10711
11124
  // A Request start the chat routes refused with one of the codes below has its own sentence in AI
@@ -10727,9 +11140,45 @@
10727
11140
  showToast(text, 'warn');
10728
11141
  }
10729
11142
 
11143
+ // The sentence for a 402 from the subscription gate (server/subscription-gate.ts), or '' for any other failure.
11144
+ // The one copy every surface uses: when the FloLess sign-in lapsed, chat said "could not complete this chat action"
11145
+ // and a workflow refresh said "could not reach it", so nobody knew that signing in again was the fix (2026-10-16).
11146
+ // Reads the response body when the caller kept it, else the structured fields copied onto the error.
11147
+ function accountAccessText(error) {
11148
+ const access = error?.body || error;
11149
+ if (error?.status !== 402 && access?.error !== 'subscription required') return '';
11150
+ if (access?.state === 'expired') return 'Your FloLess subscription has expired. Renew your FloLess subscription, then try again.';
11151
+ 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.';
11152
+ if (access?.reason === 'session-expired') return 'Your FloLess sign-in has expired. Sign in again, then try again.';
11153
+ if (access?.reason === 'signed-out') return 'You are signed out of FloLess. Sign in again, then try again.';
11154
+ if (access?.reason === 'seat-taken') return 'Your FloLess session has ended. Sign in again, then try again.';
11155
+ return 'Sign in to FloLess to check your account access, then try again.';
11156
+ }
11157
+
11158
+ // A refusal the server wrote for the person — a commercial module (Revit, Tekla, Drawing Checker)
11159
+ // that is not confirmed for this computer says what is wrong and what to do (module-registry
11160
+ // REFUSAL_COPY), and sends that sentence as `userMessage`. The generic "try again, reopen FloLess"
11161
+ // line used to replace it, although neither fixes the refusal. Only `userMessage` is shown: `error`
11162
+ // on the same code can be internal wording.
11163
+ function moduleRefusalText(e) {
11164
+ const text = e?.status === 403 && typeof e.body?.userMessage === 'string' ? e.body.userMessage.trim() : '';
11165
+ return text;
11166
+ }
11167
+
10730
11168
  function reportErr(e) {
10731
11169
  if (awarePageUnloading && e instanceof TypeError && e.message === 'Failed to fetch') return;
10732
11170
  console.error(e);
11171
+ const refusal = moduleRefusalText(e);
11172
+ if (refusal) {
11173
+ showToast(refusal, 'warn');
11174
+ return;
11175
+ }
11176
+ // #2474: a change asked of a workflow's published copy says how to change the workflow instead.
11177
+ const owned = e?.status === 409 && e.body?.code === 'owned-workflow-publication' && typeof e.body.userMessage === 'string' ? e.body.userMessage.trim() : '';
11178
+ if (owned) {
11179
+ showToast(owned, 'warn');
11180
+ return;
11181
+ }
10733
11182
  showToast('We couldn’t finish that. Your work is still here. Try again. If it keeps happening, reopen FloLess.', 'err');
10734
11183
  }
10735
11184
 
@@ -10959,7 +11408,7 @@
10959
11408
  try {
10960
11409
  // A dead local server must not leave a Copy button waiting forever. Keep the
10961
11410
  // authoritative revalidation, but fail closed after a short, user-action-sized wait.
10962
- const latest = await api('/api/requests', { signal: AbortSignal.timeout(5000) });
11411
+ const latest = await api('/api/requests', { timeoutMs: 5000 });
10963
11412
  current = Array.isArray(latest?.requests)
10964
11413
  ? latest.requests.find((candidate) => candidate && candidate.id === req.id)
10965
11414
  : null;
@@ -12223,7 +12672,7 @@
12223
12672
  let doneRequestsUnreadable = 0;
12224
12673
  async function loadDoneRequests() {
12225
12674
  try {
12226
- const body = await api('/api/requests/done', { signal: AbortSignal.timeout(30_000) });
12675
+ const body = await api('/api/requests/done', { timeoutMs: 30_000 });
12227
12676
  doneRequests = Array.isArray(body?.requests) ? body.requests : [];
12228
12677
  doneRequestsUnreadable = Number(body?.unreadable) || 0;
12229
12678
  doneRequestsError = null;
@@ -12454,7 +12903,7 @@
12454
12903
  try {
12455
12904
  // Bounded: every later read waits behind this one, so a response that never arrives must not
12456
12905
  // freeze the list for good. The route's own lock waits give up after 60 s.
12457
- const { requests, chatPublications = [], needsYou, backlog = null } = await api('/api/requests', { signal: AbortSignal.timeout(90_000) });
12906
+ const { requests, chatPublications = [], needsYou, backlog = null } = await api('/api/requests', { timeoutMs: 90_000 });
12458
12907
  reconcileActiveInstructorRuns(requests, chatPublications);
12459
12908
  pendingRequests = requests;
12460
12909
  requestsBacklog = backlog && typeof backlog === 'object' ? backlog : null;
@@ -15532,9 +15981,7 @@
15532
15981
 
15533
15982
  async function ensureReportDiscoverySession(force = false) {
15534
15983
  if (!reportDiscoveryBootstrapMode) {
15535
- reportDiscoveryBootstrapMode = fetch('/api/health', { cache: 'no-store' }).then(async (response) => {
15536
- if (!response.ok) throw new Error('report discovery health check unavailable');
15537
- const health = await response.json();
15984
+ reportDiscoveryBootstrapMode = readHealth().then((health) => {
15538
15985
  if (typeof health?.capabilities?.editorSessionHttpBootstrap !== 'boolean') {
15539
15986
  throw new Error('report discovery session mode unavailable');
15540
15987
  }
@@ -15630,9 +16077,7 @@
15630
16077
  async function savedReportsStillStarting() {
15631
16078
  if (!reportsMaybeStarting) return null;
15632
16079
  try {
15633
- const response = await fetch('/api/health', { cache: 'no-store' });
15634
- if (!response.ok) return null;
15635
- const state = (await response.json())?.startup?.reports;
16080
+ const state = (await readHealth())?.startup?.reports;
15636
16081
  // An older server has no startup field: it only ever answers once reports are ready.
15637
16082
  if (state === undefined || state === 'ready') { reportsMaybeStarting = false; return null; }
15638
16083
  return state === 'paused' ? 'paused' : 'checking';
@@ -15746,7 +16191,9 @@
15746
16191
  }
15747
16192
  // #2241 S5: the last scheduled run used an AI step - say so in the row, and how many questions it left for the person.
15748
16193
  function routineAiHtml(r) {
15749
- const ai = !r.agent && r.lastRun ? globalThis.flolessAgentSteps?.routineAiParts(r.lastRun) : null;
16194
+ // S8: a watcher has no run per event; its card speaks from the events that reached its AI step.
16195
+ const ai = r.kind === 'trigger' ? globalThis.flolessAgentSteps?.watcherCardParts?.(r.aiEvents) ?? null
16196
+ : !r.agent && r.lastRun ? globalThis.flolessAgentSteps?.routineAiParts(r.lastRun) : null;
15750
16197
  if (!ai) return '';
15751
16198
  return `<span class="rtn-dot">·</span><span class="rtn-ai" data-tip="${escapeAttr(ai.aiTip)}">${escapeHtml(ai.ai)}</span>`
15752
16199
  + (ai.questions ? `<span class="rtn-dot">·</span><span class="rtn-ai-q" data-tip="${escapeAttr(ai.questionsTip)}">${escapeHtml(ai.questions)}</span>` : '');
@@ -15956,10 +16403,14 @@
15956
16403
  // depends on the report-frame `allow-same-origin` fix to repaint in Chrome.)
15957
16404
  function applyTriggerReport(m) {
15958
16405
  if (!m || !m.workflow || typeof m.html !== 'string') return;
15959
- lastReportByApp.set(m.workflow, { nodeId: m.nodeId || null, label: 'live · on selection change', html: m.html });
16406
+ const runId = typeof m.runId === 'string' ? m.runId : null;
16407
+ const entry = { nodeId: m.nodeId || null, label: 'live · on selection change', html: m.html,
16408
+ runId, captureKey: captureKeyOf(runId, m.fireKey), fireKey: typeof m.fireKey === 'string' ? m.fireKey : null, withFiles: m.withFiles === true };
16409
+ lastReportByApp.set(m.workflow, entry);
15960
16410
  const open = $reportModal && $reportModal.classList.contains('show');
15961
16411
  if (!open || currentId !== m.workflow || reportRunning) return;
15962
- paintReport(m.html); // unhides Share + clears the overlay
16412
+ paintReport(m.html, false, entry); // unhides Share + clears the overlay
16413
+ paintReportPageLinks();
15963
16414
  const t = new Date().toLocaleTimeString();
15964
16415
  $reportSub.innerHTML =
15965
16416
  `<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.`;
@@ -15982,11 +16433,12 @@
15982
16433
  const interactive = m.interactive === true;
15983
16434
  const savedPath = typeof m.savedPath === 'string' ? m.savedPath : '';
15984
16435
  const fromChat = m.from !== 'terminal';
15985
- lastReportByApp.set(m.workflow, { nodeId: m.nodeId || null, label: fromChat ? 'from AI Chat' : 'from a terminal', html: m.html, interactive, savedPath,
15986
- runId: typeof m.runId === 'string' ? m.runId : null });
16436
+ const entry = { nodeId: m.nodeId || null, label: fromChat ? 'from AI Chat' : 'from a terminal', html: m.html, interactive, savedPath,
16437
+ withFiles: m.withFiles === true, runId: typeof m.runId === 'string' ? m.runId : null };
16438
+ lastReportByApp.set(m.workflow, entry);
15987
16439
  const open = $reportModal && $reportModal.classList.contains('show');
15988
16440
  if (!open || currentId !== m.workflow || reportRunning) return;
15989
- paintReport(m.html, interactive);
16441
+ paintReport(m.html, interactive, entry);
15990
16442
  paintReportPageLinks();
15991
16443
  $reportSub.textContent = fromChat ? 'Report from the run you confirmed in AI Chat — rendered from the run\'s output, never composed by the UI.'
15992
16444
  : 'Report from a run started in a terminal — rendered from the run\'s output, never composed by the UI.';
@@ -15997,10 +16449,11 @@
15997
16449
  if (!m || !m.workflow || typeof m.html !== 'string') return;
15998
16450
  const prev = lastReportByApp.get(m.workflow);
15999
16451
  const changed = !prev || prev.html !== m.html;
16000
- lastReportByApp.set(m.workflow, { nodeId: m.nodeId || null, label: 'scheduled', html: m.html, runId: typeof m.runId === 'string' ? m.runId : null });
16452
+ const entry = { nodeId: m.nodeId || null, label: 'scheduled', html: m.html, withFiles: m.withFiles === true, runId: typeof m.runId === 'string' ? m.runId : null };
16453
+ lastReportByApp.set(m.workflow, entry);
16001
16454
  const open = $reportModal && $reportModal.classList.contains('show');
16002
16455
  if (open && currentId === m.workflow && !reportRunning && !foregroundTrigger) {
16003
- paintReport(m.html); // unhides Share + clears the overlay
16456
+ paintReport(m.html, false, entry); // unhides Share + clears the overlay
16004
16457
  paintReportPageLinks();
16005
16458
  const t = new Date().toLocaleTimeString();
16006
16459
  $reportSub.innerHTML =
@@ -16132,8 +16585,10 @@
16132
16585
  syncRunStrip();
16133
16586
  }
16134
16587
 
16135
- function disposeLiveRun() {
16588
+ function disposeLiveRun({ keepSignal = false } = {}) {
16136
16589
  if (!liveRun) return;
16590
+ // A run let go before its ending takes the tab signal along; a video offer keeps it for the ending to come.
16591
+ if (!liveRun.ended && !keepSignal && signalRunIs(liveRun)) signalRunDrop();
16137
16592
  if (liveRun.showTimer) clearTimeout(liveRun.showTimer);
16138
16593
  if (liveRun.lingerTimer) clearTimeout(liveRun.lingerTimer);
16139
16594
  if (liveRun.view) liveRun.view.destroy();
@@ -16150,6 +16605,7 @@
16150
16605
  const token = newRunToken();
16151
16606
  rememberRunToken(appId, token);
16152
16607
  liveRun = { appId, token, runId: null, owner: true, surface, view: null, shown: false, showTimer: null, lingerTimer: null, ended: false, startedAt: Date.now() };
16608
+ signalRunBegin(liveRun);
16153
16609
  if (surface === 'overlay' && overlayHost && window.flolessRunProgressView) {
16154
16610
  liveRun.view = window.flolessRunProgressView.create({ size: 40, hat: true, fallbackHeadline, stop: null });
16155
16611
  overlayHost.append(liveRun.view.root);
@@ -16160,6 +16616,55 @@
16160
16616
  return token;
16161
16617
  }
16162
16618
 
16619
+ // ── tab signal (begin) — lifted by server/tab-signal-ui.test.ts; keep it self-contained.
16620
+ // The browser tab follows the run too (web/tab-signal.js), so a person working in Tekla sees it end. It follows
16621
+ // the RUN, by its token and run id, not the liveRun view: a video offer can replace that view before the run's
16622
+ // own ending arrives, and the tab must still hear that ending.
16623
+ let signalRun = null; // { run, token, runId }
16624
+ function signalRunBegin(run) {
16625
+ if (!window.flolessTabSignal) return;
16626
+ signalRun = { run, token: run.token || null, runId: run.runId || null };
16627
+ const app = apps.get(run.appId);
16628
+ window.flolessTabSignal.begin((app && app.displayName) || run.appId, run.startedAt);
16629
+ }
16630
+ function signalRunIs(r) {
16631
+ if (!signalRun || !r) return false;
16632
+ return r === signalRun.run || !!(r.token && r.token === signalRun.token) || !!(r.runId && r.runId === signalRun.runId);
16633
+ }
16634
+ /** The run learned its id (run-live, node-progress): the tab can now match its ending by it. */
16635
+ function signalRunNote(run) {
16636
+ if (signalRun && run && run.runId && signalRunIs(run)) signalRun.runId = run.runId;
16637
+ }
16638
+ function signalRunEnd(outcome) {
16639
+ if (!signalRun) return;
16640
+ const { runId } = signalRun;
16641
+ signalRun = null;
16642
+ if (window.flolessTabSignal) window.flolessTabSignal.finish(outcome, runId);
16643
+ }
16644
+ function signalRunDrop() {
16645
+ if (!signalRun) return;
16646
+ signalRun = null;
16647
+ if (window.flolessTabSignal) window.flolessTabSignal.cancel();
16648
+ }
16649
+ function signalRunOwns(m) {
16650
+ return !!(signalRun && m && ((m.clientRunToken && m.clientRunToken === signalRun.token) || (m.runId && m.runId === signalRun.runId)));
16651
+ }
16652
+ /** Every run event the server sends, before the liveRun view decides whether it is still its own. */
16653
+ function signalRunEvent(m) {
16654
+ if (!signalRunOwns(m)) return;
16655
+ if (m.runId) signalRun.runId = m.runId;
16656
+ if (m.type !== 'run-finished') return;
16657
+ // The ending can beat this tab's own Run answer after a video offer settled the strip: the saved token goes
16658
+ // now either way, so a reload never rediscovers a finished run.
16659
+ if (signalRun.token) forgetRunToken(signalRun.token);
16660
+ signalRunEnd(typeof m.outcome === 'string' ? m.outcome : 'failed');
16661
+ }
16662
+ /** A progress record reaches the tab only when it is the followed run's own (another workflow's is not). */
16663
+ function signalRunProgress(m) {
16664
+ if (signalRunOwns(m) && window.flolessTabSignal) window.flolessTabSignal.progress(m);
16665
+ }
16666
+ // ── tab signal (end)
16667
+
16163
16668
  function liveRunOwns(m) {
16164
16669
  if (!liveRun || liveRun.ended) return false;
16165
16670
  if (m.clientRunToken && m.clientRunToken === liveRun.token) return true;
@@ -16168,9 +16673,10 @@
16168
16673
 
16169
16674
  function onLiveProgress(m) {
16170
16675
  if (!liveRun) return;
16171
- if (m.runId && !liveRun.runId) liveRun.runId = m.runId;
16676
+ if (m.runId && !liveRun.runId) { liveRun.runId = m.runId; signalRunNote(liveRun); }
16172
16677
  if (liveRun.surface === 'strip' && !liveRun.shown) showRunStrip();
16173
16678
  if (liveRun.view) liveRun.view.apply(m);
16679
+ signalRunProgress(m);
16174
16680
  if (liveRun.appId === currentId) setNodeProgress(m.node, m);
16175
16681
  }
16176
16682
 
@@ -16194,8 +16700,11 @@
16194
16700
  const appName = (apps.get(appId) && apps.get(appId).displayName) || appId;
16195
16701
  let run = liveRun && liveRun.appId === appId && liveRun.surface === 'strip' ? liveRun : null;
16196
16702
  if (!run || !run.view) {
16197
- disposeLiveRun();
16198
- liveRun = { appId, token: null, runId: null, owner: true, surface: 'strip', view: null, shown: false, showTimer: null, lingerTimer: null, ended: false, startedAt: Date.now() };
16703
+ // The videos can arrive before the run's own ending: the offer keeps the run's identity, so the tab signal
16704
+ // still hears that ending (signalRunEvent, or this tab's own Run answer through finishLiveRun).
16705
+ const prior = liveRun && !liveRun.ended ? liveRun : null;
16706
+ disposeLiveRun({ keepSignal: !!prior });
16707
+ liveRun = { appId, token: prior ? prior.token : null, runId: prior ? prior.runId : null, owner: true, surface: 'strip', view: null, shown: false, showTimer: null, lingerTimer: null, ended: false, startedAt: Date.now() };
16199
16708
  showRunStrip();
16200
16709
  run = liveRun;
16201
16710
  run.view.finish('ok');
@@ -16228,9 +16737,16 @@
16228
16737
 
16229
16738
  function finishLiveRun(outcome) {
16230
16739
  if (pageLeaving) return; // the page is going away mid-run: keep the token so the next page resumes it
16740
+ if (liveRun && liveRun.ended && signalRunIs(liveRun)) {
16741
+ // Its videos came first and settled the strip; this is the ending the tab was still waiting for.
16742
+ forgetRunToken(liveRun.token);
16743
+ signalRunEnd(outcome);
16744
+ return;
16745
+ }
16231
16746
  if (!liveRun || liveRun.ended) return;
16232
16747
  const run = liveRun;
16233
16748
  run.ended = true;
16749
+ if (signalRunIs(run)) signalRunEnd(outcome);
16234
16750
  forgetRunToken(run.token);
16235
16751
  syncRunControls();
16236
16752
  if (run.showTimer) { clearTimeout(run.showTimer); run.showTimer = null; }
@@ -16286,6 +16802,7 @@
16286
16802
  if (liveRun && !liveRun.ended) return;
16287
16803
  disposeLiveRun();
16288
16804
  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() };
16805
+ signalRunBegin(liveRun);
16289
16806
  liveRun.showTimer = setTimeout(showRunStrip, RUN_STRIP_DELAY_MS);
16290
16807
  }
16291
16808
 
@@ -16381,6 +16898,7 @@
16381
16898
  }
16382
16899
  disposeLiveRun();
16383
16900
  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 };
16901
+ signalRunBegin(liveRun); // a reload mid-run: the tab says it is still going
16384
16902
  showRunStrip();
16385
16903
  for (const rec of snap.nodes || []) onLiveProgress({ ...rec, runId: snap.runId });
16386
16904
  }
@@ -16414,7 +16932,7 @@
16414
16932
  // revert to the last cached report if there is one, else an idle prompt.
16415
16933
  function clearTriggerCollecting() {
16416
16934
  const cached = currentId && lastReportByApp.get(currentId);
16417
- if (cached && cached.html) { paintReport(cached.html); return; }
16935
+ if (cached && cached.html) { paintReport(cached.html, cached.interactive, cached); return; }
16418
16936
  $reportOverlay.replaceChildren();
16419
16937
  $reportOverlay.hidden = false;
16420
16938
  $reportOverlay.append(mkEl('div', null, 'Listening for the next selection…'));
@@ -16427,6 +16945,31 @@
16427
16945
  // server hosts the long-lived `aware app run`; here we open the Viewer, surface
16428
16946
  // Stop, and reflect the live state. We never compose HTML — the Viewer relays
16429
16947
  // exactly what the node returns (applyTriggerReport paints each fresh report).
16948
+ // 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
16949
+ // 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.
16950
+ let viewerBeatApp = null;
16951
+ function beatLiveViewer() {
16952
+ const viewing = !!foregroundTrigger && currentId === foregroundTrigger.appId && $reportModal.classList.contains('show')
16953
+ && document.visibilityState === 'visible';
16954
+ const appId = viewing ? foregroundTrigger.appId : null;
16955
+ const send = (id, on) => fetch(`/api/trigger-run/${encodeURIComponent(id)}/viewing`, {
16956
+ method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ viewing: on }),
16957
+ }).catch(() => { /* presence only: a missed beat just means the next change is held */ });
16958
+ if (viewerBeatApp && viewerBeatApp !== appId) send(viewerBeatApp, false);
16959
+ if (appId) send(appId, true);
16960
+ viewerBeatApp = appId;
16961
+ }
16962
+ setInterval(beatLiveViewer, 15_000);
16963
+ document.addEventListener('visibilitychange', beatLiveViewer);
16964
+ /** 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
16965
+ * approvable for up to 15 s after the person stopped looking. Only a change of who is viewing sends anything. */
16966
+ function liveViewerMayHaveChanged() {
16967
+ const viewing = !!foregroundTrigger && currentId === foregroundTrigger.appId && $reportModal.classList.contains('show')
16968
+ && document.visibilityState === 'visible';
16969
+ if ((viewing ? foregroundTrigger.appId : null) !== viewerBeatApp) beatLiveViewer();
16970
+ }
16971
+ new MutationObserver(liveViewerMayHaveChanged).observe($reportModal, { attributes: true, attributeFilter: ['class'] });
16972
+
16430
16973
  async function startForegroundTrigger(app) {
16431
16974
  if (foregroundTrigger || foregroundStarting || foregroundStopping) return;
16432
16975
  const id = currentId;
@@ -16438,7 +16981,7 @@
16438
16981
  $reportTitle.textContent = `HTML Viewer · ${app.displayName}`;
16439
16982
  $reportModal.dataset.nodeId = reportNodeId() || '';
16440
16983
  const cached = lastReportByApp.get(id);
16441
- if (cached && cached.html) paintReport(cached.html);
16984
+ if (cached && cached.html) paintReport(cached.html, cached.interactive, cached);
16442
16985
  else { clearReportFrames(); $reportShare.hidden = true; }
16443
16986
  $reportOverlay.hidden = false;
16444
16987
  $reportOverlay.replaceChildren();
@@ -16450,6 +16993,7 @@
16450
16993
  foregroundTrigger = { appId: id, sessionId: res.sessionId, firedCount: 0 };
16451
16994
  markFirstRunDone(id); // a real live session started → a streaming workflow's "first run" is no longer new
16452
16995
  paintForegroundListening();
16996
+ beatLiveViewer();
16453
16997
  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.`);
16454
16998
  } catch (e) {
16455
16999
  // A refusal (a watcher already holds this host) names the concrete path back —
@@ -16495,7 +17039,7 @@
16495
17039
  const fired = foregroundTrigger.firedCount > prevFired;
16496
17040
  const viewerOpen = currentId === foregroundTrigger.appId && $reportModal.classList.contains('show');
16497
17041
  if (snapshot.state === 'error') {
16498
- foregroundTrigger = null;
17042
+ foregroundTrigger = null; liveViewerMayHaveChanged();
16499
17043
  if (viewerOpen) {
16500
17044
  $reportShare.hidden = true; // the error overlay is the primary content now
16501
17045
  $reportOverlay.hidden = false;
@@ -16510,7 +17054,7 @@
16510
17054
  if (snapshot.state === 'stopped') {
16511
17055
  // The stream ended on its own — a one-shot (`once`) snapshot fired then exited,
16512
17056
  // or the host closed cleanly. A clean self-exit reads as "Run complete".
16513
- foregroundTrigger = null;
17057
+ foregroundTrigger = null; liveViewerMayHaveChanged();
16514
17058
  if (viewerOpen) paintForegroundStopped('complete');
16515
17059
  syncRunControls();
16516
17060
  return;
@@ -16530,7 +17074,7 @@
16530
17074
  if (cached && cached.html) {
16531
17075
  $reportOverlay.hidden = true;
16532
17076
  $reportOverlay.replaceChildren();
16533
- $reportShare.hidden = false; // the cached report is the primary content
17077
+ $reportShare.hidden = !!cached.withFiles && !cached.interactive; // the cached report is the primary content (a report with files is not shared from here)
16534
17078
  $reportSub.innerHTML = `<span class="live-pip" aria-hidden="true"></span>Live · waiting for the next change — change your selection in Tekla to refresh the report.`;
16535
17079
  } else {
16536
17080
  clearReportFrames();
@@ -16555,7 +17099,7 @@
16555
17099
  if (cached && cached.html) {
16556
17100
  $reportOverlay.hidden = true;
16557
17101
  $reportOverlay.replaceChildren();
16558
- $reportShare.hidden = false;
17102
+ $reportShare.hidden = !!cached.withFiles && !cached.interactive;
16559
17103
  $reportSub.innerHTML = complete
16560
17104
  ? `Run complete · last report above — click <strong>▶ Run workflow</strong> to run again.`
16561
17105
  : `Live session stopped · last report above — click <strong>▶ Run workflow</strong> to start again.`;
@@ -17140,6 +17684,13 @@
17140
17684
  };
17141
17685
  // #2035: an agent's page opens a new routine with that agent chosen.
17142
17686
  window.flolessRoutines = {
17687
+ /** Project access: open Routines with one routine's editor, so the person sees exactly the schedule they picked. */
17688
+ async open(routineId) {
17689
+ openRoutines();
17690
+ await loadRoutinesData();
17691
+ if (routinesData.some((r) => r.id === routineId)) await openRoutineEdit(routineId);
17692
+ else showToast('That schedule no longer exists. Routines lists the ones you have.', 'warn');
17693
+ },
17143
17694
  /** #2046: a Guide suggestion — a new routine for this workflow, opened for the person to finish. */
17144
17695
  async editForWorkflow(workflowId, returnFocus) {
17145
17696
  await loadRoutinesData();
@@ -18089,8 +18640,7 @@
18089
18640
  // Show the installed build (so a stale install is self-diagnosable from the
18090
18641
  // gate — the highest-value spot since that's where a confused user lands).
18091
18642
  // /api/health is un-gated, so this works even while unlicensed.
18092
- fetch('/api/health', { cache: 'no-store' })
18093
- .then((r) => r.json())
18643
+ readHealth()
18094
18644
  .then((h) => { if (h && h.appVersion) document.getElementById('lg-version').textContent = 'FloLess ' + h.appVersion; })
18095
18645
  .catch(() => { /* version is a nicety; never block the gate on it */ });
18096
18646
  document.getElementById('lg-signin').onclick = async () => {
@@ -18163,6 +18713,10 @@
18163
18713
  if (selectionTicket === selectionAtStart) selectionTicket += 1;
18164
18714
  const committed = { ...row, ...workflow, restoreRefreshState: 'pending' };
18165
18715
  wfOwned = wfOwned.filter((item) => item.workflowId !== workflowId).concat(committed);
18716
+ // It lands in Your workflows: open that section now, so the restored card and its "Refreshing…" line show at once
18717
+ // rather than only after the list refresh, however long that takes.
18718
+ const yours = $wfLanding?.querySelector('.wf-section[data-wf-section="yours"]');
18719
+ if (yours) yours.open = true;
18166
18720
  if (wfLanding) renderWorkflowsLanding();
18167
18721
  let refreshFailed = false;
18168
18722
  try { await loadApps({ preserveSelection: true }); }
@@ -18187,6 +18741,9 @@
18187
18741
  ? $wfLanding.querySelector(`[data-wf-restored="${CSS.escape(workflowId)}"]`)
18188
18742
  || $wfLanding.querySelector(publication ? `[data-wf-id="${CSS.escape(publication.id)}"]` : `[data-wf-draft="${CSS.escape(workflowId)}"]`)
18189
18743
  : $wfLanding.querySelector(`[data-wf-restore="${CSS.escape(workflowId)}"]`);
18744
+ // A card in a section the person closed cannot take focus: open its section first.
18745
+ const section = target?.closest('.wf-section');
18746
+ if (section && !section.open) section.open = true;
18190
18747
  (target && !target.hidden ? target : document.getElementById('wf-landing-title'))?.focus();
18191
18748
  }
18192
18749
  }
@@ -18197,6 +18754,10 @@
18197
18754
  const $wfLanding = document.getElementById('wf-landing');
18198
18755
  // The landing search's query, kept outside the input because the landing re-renders with innerHTML.
18199
18756
  let wfLandingQuery = '';
18757
+ // #2568: the landing's two tabs. The choice is remembered by this browser window; anything unknown, or a store that
18758
+ // throws (private window, blocked site data), reads as Workflows.
18759
+ const WF_TAB_KEY = 'floless.workflowsLandingTab';
18760
+ let wfLandingTab = (() => { try { return localStorage.getItem(WF_TAB_KEY) === 'pages' ? 'pages' : 'workflows'; } catch { return 'workflows'; } })();
18200
18761
  function showWorkflowsLanding(on) {
18201
18762
  const next = Boolean(on);
18202
18763
  if (next === wfLanding && (!next || $wfLanding?.childElementCount)) { if (next) renderWorkflowsLanding(); return; }
@@ -18246,19 +18807,75 @@
18246
18807
  + `Your other workflows are not affected. Ask AI Chat to repair or reinstall ${one ? 'it' : 'them'}.</div>`;
18247
18808
  }
18248
18809
 
18810
+ /** The Workflows landing's heading, sub line, tabs and (when there is something to search) search box, shared by both tabs. */
18811
+ function workflowsLandingHeadHtml(esc, showSearch) {
18812
+ const pages = wfLandingTab === 'pages';
18813
+ const tab = (id, label) => `<button type="button" role="tab" id="wf-tab-${id}" data-wf-tab="${id}" class="${wfLandingTab === id ? 'active' : ''}"`
18814
+ + ` aria-selected="${wfLandingTab === id}"${id === 'pages' ? ' aria-controls="wf-pages-panel"' : ''} tabindex="${wfLandingTab === id ? 0 : -1}"`
18815
+ + ` data-command-id="shell.workflows-landing-tab#${esc(id)}">${label}</button>`;
18816
+ return `<div class="ws-head"><div class="ws-head-text"><h2 tabindex="-1" id="wf-landing-title">Workflows</h2>`
18817
+ + `<p class="ws-sub">Build, run and manage the workflows behind your projects. Ask AI Chat on the left to build one with you.</p>`
18818
+ + `<div class="tabs ws-step-tabs wf-landing-tabs" role="tablist" aria-label="Workflows page">${tab('workflows', 'Workflows')}${tab('pages', 'Pages')}</div></div>`
18819
+ + (showSearch ? `<div class="ws-head-actions"><input type="search" id="wf-landing-search" class="ws-landing-search" data-command-id="shell.workflows-landing-search" placeholder="${pages ? 'Search pages' : 'Search workflows'}" aria-label="${pages ? 'Search Pages by workflow, Page title or project' : 'Search workflows by name, project or tool'}" autocomplete="off" spellcheck="false" value="${esc(wfLandingQuery)}"></div>` : '')
18820
+ + `</div>`;
18821
+ }
18822
+
18823
+ /** Switch the landing's tab: remember it, repaint, and (for a keyboard or button move) put focus on the chosen tab. */
18824
+ function setWorkflowsLandingTab(tab, focusTab) {
18825
+ const next = tab === 'pages' ? 'pages' : 'workflows';
18826
+ if (next !== wfLandingTab) {
18827
+ wfLandingTab = next;
18828
+ try { localStorage.setItem(WF_TAB_KEY, next); } catch { /* not remembered; the tab still switches */ }
18829
+ }
18830
+ renderWorkflowsLanding();
18831
+ if (focusTab) $wfLanding.querySelector(`[data-wf-tab="${next}"]`)?.focus();
18832
+ }
18833
+
18834
+ /** The Pages tab: the heading and tabs, the search, and a panel pages.js fills with every workflow's Page. */
18835
+ function renderWorkflowsPagesTab() {
18836
+ const focusedTab = document.activeElement?.closest?.('#wf-landing [data-wf-tab]')?.dataset.wfTab || null;
18837
+ const search = document.activeElement?.id === 'wf-landing-search' ? document.activeElement : null;
18838
+ const keepCaret = search ? [search.selectionStart, search.selectionEnd] : null;
18839
+ const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
18840
+ $wfLanding.innerHTML = workflowsLandingHeadHtml(esc, true)
18841
+ + '<div id="wf-pages-panel" class="wf-pages-panel" role="tabpanel" aria-labelledby="wf-tab-pages"></div>';
18842
+ const panel = $wfLanding.querySelector('#wf-pages-panel');
18843
+ if (window.flolessPages?.renderWorkflowsList) {
18844
+ void window.flolessPages.renderWorkflowsList(panel, {
18845
+ getQuery: () => wfLandingQuery,
18846
+ onAction: (act) => {
18847
+ if (act === 'show-workflows') setWorkflowsLandingTab('workflows', true);
18848
+ else if (act === 'clear-search') { setWorkflowsLandingQuery(''); $wfLanding.querySelector('#wf-landing-search')?.focus(); }
18849
+ },
18850
+ });
18851
+ } else {
18852
+ panel.innerHTML = '<div class="pg-empty" role="alert"><p>FloLess couldn’t load the workflows’ Pages. Check that FloLess is running, then try again.</p></div>';
18853
+ }
18854
+ if (focusedTab) $wfLanding.querySelector(`[data-wf-tab="${focusedTab}"]`)?.focus();
18855
+ if (keepCaret) { const box = $wfLanding.querySelector('#wf-landing-search'); box?.focus(); box?.setSelectionRange?.(keepCaret[0], keepCaret[1]); }
18856
+ }
18857
+
18249
18858
  function renderWorkflowsLanding() {
18250
18859
  if (!$wfLanding) return;
18860
+ if (wfLandingTab === 'pages') { renderWorkflowsPagesTab(); return; }
18861
+ const focusedTab = document.activeElement?.closest?.('#wf-landing [data-wf-tab]')?.dataset.wfTab || null;
18251
18862
  const focusedId = document.activeElement?.closest?.('#wf-landing [data-wf-id]')?.dataset.wfId || null;
18252
18863
  const search = document.activeElement?.id === 'wf-landing-search' ? document.activeElement : null;
18253
18864
  const keepCaret = search ? [search.selectionStart, search.selectionEnd] : null;
18254
18865
  const clearFocused = document.activeElement?.id === 'wf-search-clear';
18255
18866
  const focusedDraft = document.activeElement?.closest?.('#wf-landing [data-wf-draft]')?.dataset.wfDraft || null;
18256
18867
  const focusedRestore = document.activeElement?.closest?.('[data-wf-restore]')?.dataset.wfRestore || null;
18257
- // The Archived disclosure keeps its open state across repaints (apps-changed, search, restore); focus inside it implies open.
18258
- // Focus on the summary alone must NOT force it open (the person just closed it); focus on a card inside must.
18259
- const keepArchivedOpen = !!$wfLanding.querySelector('.wf-archived')?.open || !!document.activeElement?.closest?.('.wf-archived > .ws-grid');
18260
- const keepSearchOpened = !!$wfLanding.querySelector('.wf-archived')?.dataset.searchOpened;
18261
- const archivedSummaryFocused = !!document.activeElement?.closest?.('.wf-archived > summary');
18868
+ // Every section (Your workflows, Installed, Archived) is the same disclosure, and each keeps its open state across
18869
+ // repaints (apps-changed, search, restore, coming back to the tab); focus on a card inside implies open. Focus on
18870
+ // the summary alone must NOT force it open (the person just closed it).
18871
+ const keptSections = {};
18872
+ for (const box of $wfLanding.querySelectorAll('.wf-section')) {
18873
+ keptSections[box.dataset.wfSection] = {
18874
+ open: !!box.open || document.activeElement?.closest?.('.wf-section > .ws-grid')?.parentElement === box,
18875
+ searchOpened: !!box.dataset.searchOpened,
18876
+ summaryFocused: document.activeElement?.closest?.('.wf-section > summary')?.parentElement === box,
18877
+ };
18878
+ }
18262
18879
  const focusedRestored = document.activeElement?.closest?.('[data-wf-restored]')?.dataset.wfRestored || null;
18263
18880
  const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
18264
18881
  const restoredRows = wfOwned.filter((row) => row.status !== 'archived' && row.restoreRefreshState);
@@ -18306,28 +18923,34 @@
18306
18923
  + `<div class="ws-name">${esc(name)}</div><div class="ws-meta">${esc(where)}</div>`
18307
18924
  + `<div class="ws-meta wf-card-nodes">${esc(workflowCardMeta(row))}</div></div></div></div>`;
18308
18925
  };
18309
- const group = (title, rows, show) => (rows.length
18310
- ? `${show ? `<div class="wf-group-label">${esc(title)} (${rows.length})</div>` : ''}<div class="ws-grid">${rows.map(card).join('')}</div>` : '');
18311
- const yours = unlisted.length + owned.length + restoredRows.length;
18312
- const both = yours > 0 && installed.length > 0;
18313
- const yoursGroup = yours
18314
- ? `${both ? `<div class="wf-group-label">Your workflows (${yours})</div>` : ''}<div class="ws-grid">${unlisted.map(draftCard).join('')}${owned.map(card).join('')}${restoredRows.map(restoredCard).join('')}</div>`
18315
- : '';
18316
- $wfLanding.innerHTML = `<div class="ws-head"><div class="ws-head-text"><h2 tabindex="-1" id="wf-landing-title">Workflows</h2>`
18317
- + `<p class="ws-sub">Build, run and manage the workflows behind your projects. Ask AI Chat on the left to build one with you.</p></div>`
18318
- + (wfLibrary.length || unlisted.length || archived.length || restoredRows.length ? `<div class="ws-head-actions"><input type="search" id="wf-landing-search" class="ws-landing-search" data-command-id="shell.workflows-landing-search" placeholder="Search workflows" aria-label="Search workflows by name, project or tool" autocomplete="off" spellcheck="false" value="${esc(wfLandingQuery)}"></div>` : '')
18319
- + `</div>`
18926
+ // One section: a disclosure whose summary names it and counts its cards. Your workflows and Installed start open,
18927
+ // Archived starts closed; a section the person opened or closed stays that way (keptSections). The summary's
18928
+ // Instructor carrier is passed whole by each caller: a command id is never assembled from parts.
18929
+ const section = (key, carrier, title, count, cards, openByDefault) => {
18930
+ if (!count) return '';
18931
+ const open = keptSections[key] ? keptSections[key].open : openByDefault;
18932
+ return `<details class="ws-archived wf-section wf-${key}" data-wf-section="${key}"${open ? ' open' : ''}>`
18933
+ + `<summary class="ws-archived-summary" ${carrier}><span class="ws-archived-caret hd-caret" aria-hidden="true">▸</span>${title} <span class="ws-archived-count">${count}</span></summary>`
18934
+ + `<div class="ws-grid">${cards}</div></details>`;
18935
+ };
18936
+ const yoursSection = section('yours', 'data-command-id="shell.workflows-landing-yours"', 'Your workflows', unlisted.length + owned.length + restoredRows.length,
18937
+ `${unlisted.map(draftCard).join('')}${owned.map(card).join('')}${restoredRows.map(restoredCard).join('')}`, true);
18938
+ $wfLanding.innerHTML = workflowsLandingHeadHtml(esc, Boolean(wfLibrary.length || unlisted.length || archived.length || restoredRows.length))
18320
18939
  + `<div class="ws-create-grid"><div class="ws-card ws-create ws-card-create wf-create" role="button" tabindex="0" data-wf-new="1" data-command-id="shell.workflows-landing-new">`
18321
18940
  + `<div class="ws-thumb">+</div><div class="ws-body"><div><div class="ws-name">New workflow</div>`
18322
18941
  + `<div class="ws-meta">Name it and choose where it belongs. AI builds it with you.</div></div></div></div></div>`
18323
18942
  + unreadableNote
18324
18943
  + (wfLibrary.length || unlisted.length || archived.length || restoredRows.length
18325
- ? yoursGroup + group('Installed', installed, both)
18944
+ ? yoursSection + section('installed', 'data-command-id="shell.workflows-landing-installed"', 'Installed', installed.length, installed.map(card).join(''), true)
18945
+ + section('archived', 'data-command-id="shell.workflows-landing-archived"', 'Archived', archived.length, archived.map(archivedCard).join(''), false)
18326
18946
  + '<div class="ws-empty-note ws-search-empty" id="wf-search-empty" role="status" aria-live="polite"></div>'
18327
- : '<div class="ws-empty-note">No active workflows yet. Start with New workflow, or ask AI Chat on the left.</div>')
18328
- + (archived.length ? `<details class="ws-archived wf-archived"><summary class="ws-archived-summary" data-command-id="shell.workflows-landing-archived"><span class="ws-archived-caret hd-caret" aria-hidden="true">▸</span>Archived <span class="ws-archived-count">${archived.length}</span></summary><div class="ws-grid">${archived.map(archivedCard).join('')}</div></details>` : '');
18329
- if (keepArchivedOpen) { const d = $wfLanding.querySelector('.wf-archived'); if (d) { d.open = true; if (keepSearchOpened) d.dataset.searchOpened = '1'; } }
18330
- if (archivedSummaryFocused) $wfLanding.querySelector('.wf-archived > summary')?.focus();
18947
+ : '<div class="ws-empty-note">No active workflows yet. Start with New workflow, or ask AI Chat on the left.</div>');
18948
+ for (const box of $wfLanding.querySelectorAll('.wf-section')) {
18949
+ const kept = keptSections[box.dataset.wfSection];
18950
+ if (kept?.open && kept.searchOpened) box.dataset.searchOpened = '1';
18951
+ if (kept?.summaryFocused) box.querySelector(':scope > summary')?.focus();
18952
+ }
18953
+ if (focusedTab) $wfLanding.querySelector(`[data-wf-tab="${focusedTab}"]`)?.focus();
18331
18954
  if (focusedId) $wfLanding.querySelector(`[data-wf-id="${CSS.escape(focusedId)}"]`)?.focus();
18332
18955
  if (focusedDraft) $wfLanding.querySelector(`[data-wf-draft="${CSS.escape(focusedDraft)}"]`)?.focus();
18333
18956
  if (focusedRestore) $wfLanding.querySelector(`[data-wf-restore="${CSS.escape(focusedRestore)}"]:not(:disabled)`)?.focus();
@@ -18340,10 +18963,12 @@
18340
18963
  /** Hide the workflow cards that don't match the landing search: every typed word must appear somewhere in the
18341
18964
  * card's name or the line under it (its project, or the tool an installed workflow runs on), never in its
18342
18965
  * "N nodes · tool" line, which every card has. New workflow is an action,
18343
- * not a result, so it stays. A group with nothing left hides its label; a shown label counts "1 of 3". */
18966
+ * not a result, so it stays. A section with nothing left hides whole; a shown one counts "1 of 3" in its summary. */
18344
18967
  function applyWorkflowsLandingSearch(caret) {
18345
18968
  const input = $wfLanding.querySelector('#wf-landing-search');
18346
18969
  if (!input) return;
18970
+ // The Pages tab filters its own rows (pages.js), from the same query.
18971
+ if (wfLandingTab === 'pages') { window.flolessPages?.repaintWorkflowsList?.($wfLanding.querySelector('#wf-pages-panel')); return; }
18347
18972
  const terms = wfLandingQuery.trim().toLowerCase().split(/\s+/).filter(Boolean);
18348
18973
  let shownAll = 0;
18349
18974
  for (const grid of $wfLanding.querySelectorAll('.ws-grid')) {
@@ -18354,23 +18979,15 @@
18354
18979
  card.hidden = !terms.every((t) => hay.includes(t));
18355
18980
  if (!card.hidden) shown++;
18356
18981
  }
18357
- const archivedBox = grid.closest('.wf-archived');
18358
- if (archivedBox) {
18359
- // The Archived disclosure counts in its summary; a search that matches opens it, an empty match hides all of it,
18360
- // and clearing the search closes it again only if the search was what opened it.
18361
- archivedBox.hidden = !shown;
18362
- const count = archivedBox.querySelector('.ws-archived-count');
18982
+ // Each section counts in its summary; a search that matches opens a closed one, an empty match hides all of it,
18983
+ // and clearing the search closes it again only if the search was what opened it.
18984
+ const box = grid.closest('.wf-section');
18985
+ if (box) {
18986
+ box.hidden = !shown;
18987
+ const count = box.querySelector('.ws-archived-count');
18363
18988
  if (count) count.textContent = terms.length ? `${shown} of ${cards.length}` : String(cards.length);
18364
- if (terms.length && shown && !archivedBox.open) { archivedBox.open = true; archivedBox.dataset.searchOpened = '1'; }
18365
- else if (!terms.length && archivedBox.dataset.searchOpened) { archivedBox.open = false; delete archivedBox.dataset.searchOpened; }
18366
- shownAll += shown;
18367
- continue;
18368
- }
18369
- grid.hidden = !shown;
18370
- const label = grid.previousElementSibling?.classList.contains('wf-group-label') ? grid.previousElementSibling : null;
18371
- if (label) {
18372
- label.hidden = !shown;
18373
- label.textContent = label.textContent.replace(/\(\d+(?: of \d+)?\)$/, terms.length ? `(${shown} of ${cards.length})` : `(${cards.length})`);
18989
+ if (terms.length && shown && !box.open) { box.open = true; box.dataset.searchOpened = '1'; }
18990
+ else if (!terms.length && box.dataset.searchOpened) { box.open = false; delete box.dataset.searchOpened; }
18374
18991
  }
18375
18992
  shownAll += shown;
18376
18993
  }
@@ -18418,9 +19035,15 @@
18418
19035
  || String(b.updatedAt || '').localeCompare(String(a.updatedAt || '')));
18419
19036
  }
18420
19037
 
19038
+ /** The owned workflow (not archived) a chat names by its owned id, or null. */
19039
+ function ownedForOpen(workflowId) {
19040
+ return wfOwned.find((row) => row.workflowId === workflowId && row.status !== 'archived') || null;
19041
+ }
19042
+
19043
+ /** Open an owned workflow's draft view; false when there is no such draft (or no view to show it in). */
18421
19044
  function openDraftWorkflow(workflowId) {
18422
19045
  const row = wfOwned.find((item) => item.workflowId === workflowId && item.status !== 'archived');
18423
- if (!row || !$wfDraft) return;
19046
+ if (!row || !$wfDraft) return false;
18424
19047
  selectionTicket += 1;
18425
19048
  if (draftWorkflow) closeDraftView();
18426
19049
  draftWorkflow = { workflowId: row.workflowId, displayName: row.displayName, ownerLabel: row.ownerLabel || 'Standalone',
@@ -18443,6 +19066,7 @@
18443
19066
  notifyChatScope();
18444
19067
  void watchDraft(draftWorkflow);
18445
19068
  document.getElementById('wf-draft-title')?.focus();
19069
+ return true;
18446
19070
  }
18447
19071
 
18448
19072
  // The AI writes a draft's workflow file from its chat, which raises no workflow event, so an open draft re-reads
@@ -18552,11 +19176,32 @@
18552
19176
  document.getElementById('wf-draft-compile')?.focus();
18553
19177
  try {
18554
19178
  await api(`/api/workflows/owned/${encodeURIComponent(d.workflowId)}/publish`, { method: 'POST' });
18555
- } catch {
19179
+ } catch (error) {
18556
19180
  // The route's own wording is internal; the person gets the plain sentence and two ways on.
18557
19181
  d.busy = false;
18558
19182
  if (draftWorkflow !== d) return;
18559
19183
  d.compiling = false;
19184
+ // #2314: two steps share one name. Ask which to rename; after a rename, compile again. Cancel keeps today's failure.
19185
+ const ask = globalThis.flolessStepRename ? globalThis.flolessStepRename.askOf(error) : null;
19186
+ if (ask) {
19187
+ renderDraftView();
19188
+ const outcome = await globalThis.flolessStepRename.open(ask);
19189
+ if (draftWorkflow !== d) return;
19190
+ if (outcome.renamed) {
19191
+ const warning = outcome.result && outcome.result.warning;
19192
+ if (warning) {
19193
+ // Not exactly as previewed (or not checkable): no automatic Compile — the person looks, then presses Compile.
19194
+ showToast(warning, 'warn');
19195
+ d.note = warning;
19196
+ renderDraftView();
19197
+ return;
19198
+ }
19199
+ await compileDraftWorkflow();
19200
+ return;
19201
+ }
19202
+ // Cancelled: the draft's failure view stays, and the reason stays in view with it.
19203
+ showToast(`${ask.sentence ? `${ask.sentence} ` : ''}Nothing was renamed.`, 'warn');
19204
+ }
18560
19205
  d.failed = true;
18561
19206
  renderDraftView();
18562
19207
  document.getElementById('wf-draft-failure')?.focus();
@@ -18617,8 +19262,8 @@
18617
19262
 
18618
19263
  if ($wfLanding) {
18619
19264
  $wfLanding.addEventListener('click', (event) => {
18620
- // A hand toggle of Archived means the person owns its state now: clearing the search must not undo it.
18621
- if (event.target.closest('.wf-archived > summary')) delete event.target.closest('.wf-archived').dataset.searchOpened;
19265
+ // A hand toggle of a section means the person owns its state now: clearing the search must not undo it.
19266
+ if (event.target.closest('.wf-section > summary')) delete event.target.closest('.wf-section').dataset.searchOpened;
18622
19267
  const restore = event.target.closest('[data-wf-restore]');
18623
19268
  if (restore) {
18624
19269
  if (!restore.disabled) {
@@ -18629,6 +19274,8 @@
18629
19274
  }
18630
19275
  return;
18631
19276
  }
19277
+ const tabEl = event.target.closest('[data-wf-tab]');
19278
+ if (tabEl) { setWorkflowsLandingTab(tabEl.dataset.wfTab, true); return; }
18632
19279
  if (event.target.closest('[data-wf-new]')) { requestNewWorkflow(); return; }
18633
19280
  // Clearing empties the message the button sits in, so focus goes back to the search box.
18634
19281
  if (event.target.closest('#wf-search-clear')) { setWorkflowsLandingQuery(''); $wfLanding.querySelector('#wf-landing-search')?.focus(); return; }
@@ -18647,6 +19294,17 @@
18647
19294
  if (event.key === 'Escape' && event.target.id === 'wf-landing-search' && event.target.value) {
18648
19295
  event.preventDefault(); event.stopPropagation(); setWorkflowsLandingQuery(''); return;
18649
19296
  }
19297
+ // The tabs move by arrow keys (the focused tab is the one tab stop) and activate as they take focus.
19298
+ const onTab = event.target.closest?.('[data-wf-tab]');
19299
+ if (onTab && ['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {
19300
+ event.preventDefault();
19301
+ const order = ['workflows', 'pages'];
19302
+ const at = order.indexOf(onTab.dataset.wfTab);
19303
+ const to = event.key === 'Home' ? 0 : event.key === 'End' ? order.length - 1
19304
+ : (at + (event.key === 'ArrowRight' ? 1 : order.length - 1)) % order.length;
19305
+ setWorkflowsLandingTab(order[to], true);
19306
+ return;
19307
+ }
18650
19308
  if (event.key !== 'Enter' && event.key !== ' ') return;
18651
19309
  const target = event.target.closest('[data-wf-id], [data-wf-new], [data-wf-draft]');
18652
19310
  if (!target || target !== event.target) return;
@@ -18689,12 +19347,18 @@
18689
19347
  // #1997: open an installed workflow by its AWARE app id (the "Open workflow" next step of Approve updated
18690
19348
  // workflows, e.g. "open it and press Compile").
18691
19349
  // Only a workflow the Workflows page lists can be opened; one installed outside FloLess (from a terminal) is not.
18692
- canOpenApp: (appId) => wfLibrary.some((row) => row.id === appId),
19350
+ // A chat working on a FloLess-owned workflow knows it by its owned id, not its AWARE app id (#2241 S6: the
19351
+ // "confirm its AI step" card from the workflow's own chat), so an owned id opens its published app, or its draft.
19352
+ canOpenApp: (appId) => wfLibrary.some((row) => row.id === appId) || Boolean(ownedForOpen(appId)),
18693
19353
  async openApp(appId) {
18694
19354
  await window.flolessWorkspaces?.setMode?.('workflows');
18695
19355
  await loadApps();
18696
19356
  if (!wfLibrary.some((row) => row.id === appId)) {
18697
- throw new Error('That workflow is not on your Workflows page, so FloLess cannot open it. Compile it from the terminal that installed it.');
19357
+ const owned = ownedForOpen(appId);
19358
+ const runtimeId = owned?.activePublication?.runtimeAppId;
19359
+ if (runtimeId && wfLibrary.some((row) => row.id === runtimeId)) appId = runtimeId;
19360
+ else if (owned) return openDraftWorkflow(owned.workflowId);
19361
+ 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.');
18698
19362
  }
18699
19363
  await loadApp(appId);
18700
19364
  showWorkflowsLanding(false);
@@ -18707,7 +19371,21 @@
18707
19371
  // opened after the run) holds a different one or none. Say so instead of showing the wrong report.
18708
19372
  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.';
18709
19373
  const cached = lastReportByApp.get(appId);
18710
- if (!runId || cached?.runId !== runId) throw new Error(gone);
19374
+ if (!runId) throw new Error(gone);
19375
+ // #2266: a window opened (or reloaded) after the run reads the copy FloLess kept of THAT run's report, in the
19376
+ // workflow's Page. Never another run's: a report no longer kept says so.
19377
+ if (cached?.runId !== runId) {
19378
+ let kept = null;
19379
+ try { kept = await api(`/api/pages/workflow?app=${encodeURIComponent(appId)}&run=${encodeURIComponent(runId)}`); }
19380
+ 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.'); }
19381
+ if (kept?.home && kept.page?.id && kept.shown?.kept === true) {
19382
+ 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.');
19383
+ return await window.flolessPages.open(kept.home, kept.page.id, kept.shown.version);
19384
+ }
19385
+ throw new Error(kept?.shown?.note
19386
+ ? `${kept.shown.note} Open the workflow to see its latest results.`
19387
+ : 'FloLess did not keep a copy of that run’s report. Open the workflow to see its latest results.');
19388
+ }
18711
19389
  await this.openApp(appId);
18712
19390
  // Opening the workflow waits; a newer report may have arrived meanwhile. Show this run's report or nothing.
18713
19391
  if (lastReportByApp.get(appId) !== cached) throw new Error(gone);
@@ -18718,6 +19396,25 @@
18718
19396
  },
18719
19397
  // #1890 PR 3b: open a FloLess-owned workflow by its id — its published app when it has one, otherwise its draft
18720
19398
  // view — so a conversation that moved into it can be followed there. Throws a plain sentence when it is gone.
19399
+ // Project access: an archived workflow has no canvas to open, so show it where it can be restored — its card in the
19400
+ // Workflows list's Archived section, opened, scrolled to and focused on Restore. Throws a plain sentence when it is gone.
19401
+ async openArchivedWorkflow(workflowId) {
19402
+ await window.flolessWorkspaces?.setMode?.('workflows');
19403
+ // The switch can stay on the current tab (another workflow's read failed): never focus a card nobody can see.
19404
+ if (document.body.classList.contains('mode-workspaces') || document.body.classList.contains('mode-agents')) {
19405
+ throw new Error('FloLess could not switch to the Workflows tab just now. Open it and find the workflow under Archived.');
19406
+ }
19407
+ // The list is what is needed here, not any one workflow: a reload that fails keeps the list already on screen.
19408
+ try { await loadApps(); } catch (error) { console.warn('[project-access] the workflow list could not be read again', error); }
19409
+ showWorkflowsLanding(true);
19410
+ const card = [...($wfLanding?.querySelectorAll('[data-wf-archived]') || [])].find((el) => el.getAttribute('data-wf-archived') === workflowId);
19411
+ 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.');
19412
+ const box = card.closest('.wf-archived');
19413
+ if (box) box.open = true;
19414
+ card.scrollIntoView?.({ block: 'center' });
19415
+ card.querySelector('[data-wf-restore]')?.focus();
19416
+ return true;
19417
+ },
18721
19418
  async openOwnedWorkflow(workflowId) {
18722
19419
  await window.flolessWorkspaces?.setMode?.('workflows');
18723
19420
  await loadApps();
@@ -18792,6 +19489,10 @@
18792
19489
  refreshCurrentWorkflow() {
18793
19490
  return refreshCurrentWorkflow();
18794
19491
  },
19492
+ // The person-facing sentence of a module refusal (see reportErr), or '' for any other failure.
19493
+ moduleRefusalText,
19494
+ // The person-facing sentence of a lapsed sign-in or subscription (HTTP 402), or '' for any other failure.
19495
+ accountAccessText,
18795
19496
  reloadCompiledWorkflows,
18796
19497
  // Workspaces is a replacement surface. Invalidate a pending workflow-pin read as soon as it
18797
19498
  // opens, rather than allowing a late answer to survive behind the project UI until the return.
@@ -18991,7 +19692,7 @@
18991
19692
  // Setup-first: if AWARE isn't ready, show the overlay and DEFER routing until it
18992
19693
  // is (the health poll + finishBootstrapReady → onBootstrapReady do the routing).
18993
19694
  let h = null;
18994
- try { h = await (await fetch('/api/health', { cache: 'no-store' })).json(); }
19695
+ try { h = await readHealth(); }
18995
19696
  catch { /* health unreachable → route now; the offline overlay handles a down server */ }
18996
19697
  if (h && h.bootstrap && h.bootstrap !== 'ready') {
18997
19698
  updateBootstrap({ status: h.bootstrap, reason: h.bootstrapReason ?? null, remediation: h.bootstrapRemediation ?? null });