@floless/app 0.168.0 → 0.170.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 (80) hide show
  1. package/cli-actions.mjs +8 -1
  2. package/dist/floless-server.cjs +125533 -99597
  3. package/dist/schemas/drawing-check.profile.v1.schema.json +12 -2
  4. package/dist/schemas/steel.model.v2.schema.json +2 -1
  5. package/dist/skills/floless-app-knowledge/SKILL.md +43 -13
  6. package/dist/skills/floless-app-new-workflow/SKILL.md +8 -1
  7. package/dist/skills/floless-app-rfi/SKILL.md +4 -2
  8. package/dist/skills/floless-app-routines/SKILL.md +2 -2
  9. package/dist/skills/floless-app-routines/references/routines-api.md +20 -8
  10. package/dist/skills/floless-app-steel-model/SKILL.md +8 -5
  11. package/dist/skills/floless-app-steel-takeoff/SKILL.md +31 -1
  12. package/dist/skills/floless-app-workflows/SKILL.md +22 -3
  13. package/dist/skills/floless-app-workflows/references/agent-steps.md +40 -6
  14. package/dist/skills/floless-app-workflows/references/exec-contract.md +27 -0
  15. package/dist/skills/floless-app-workflows/references/script-runner.md +105 -0
  16. package/dist/templates/college-phase-exporter.flo +7 -2
  17. package/dist/templates/trimble-list-projects.flo +10 -2
  18. package/dist/web/agent-steps.js +90 -19
  19. package/dist/web/agents.js +77 -31
  20. package/dist/web/app.css +267 -4
  21. package/dist/web/app.js +71 -7
  22. package/dist/web/aware-update-client.js +4 -4
  23. package/dist/web/aware.js +1277 -219
  24. package/dist/web/chat.css +10 -0
  25. package/dist/web/chat.js +407 -117
  26. package/dist/web/checkpoint-standard.js +5 -3
  27. package/dist/web/commands-drawing-check.js +4 -0
  28. package/dist/web/commands-shell.js +551 -15
  29. package/dist/web/commands-steel.js +68 -2
  30. package/dist/web/commands-vector.js +69 -0
  31. package/dist/web/drawing-check-editor.html +10 -0
  32. package/dist/web/drawing-check-editor.js +821 -237
  33. package/dist/web/failure-copy.js +50 -2
  34. package/dist/web/filter-ai-proposal.js +11 -8
  35. package/dist/web/flo-3d.js +310 -0
  36. package/dist/web/flo-card.js +72 -0
  37. package/dist/web/guide.js +33 -24
  38. package/dist/web/index.html +95 -5
  39. package/dist/web/instructor.js +102 -15
  40. package/dist/web/left-pane.js +4 -1
  41. package/dist/web/local-discovery.js +8 -7
  42. package/dist/web/missed-routines.js +239 -0
  43. package/dist/web/model-editor-steel-adapter.js +41 -1
  44. package/dist/web/model-measure.js +6 -0
  45. package/dist/web/model-spatial-panel.js +19 -4
  46. package/dist/web/model-spatial-tools.js +3 -3
  47. package/dist/web/model-viewport-revit-adapter.js +3 -3
  48. package/dist/web/model-viewport-toolbar.js +11 -0
  49. package/dist/web/origin-rule.js +155 -0
  50. package/dist/web/pages.js +17 -14
  51. package/dist/web/panels.js +1 -1
  52. package/dist/web/project-access.js +1 -1
  53. package/dist/web/project-history.js +2 -2
  54. package/dist/web/project-modules.js +5 -5
  55. package/dist/web/project-reconciliation.js +1 -1
  56. package/dist/web/project-rfis.js +8 -3
  57. package/dist/web/project-workflows.js +8 -6
  58. package/dist/web/renderers.js +6 -0
  59. package/dist/web/report-csp.js +68 -0
  60. package/dist/web/revit-editor.js +22 -8
  61. package/dist/web/run-history.js +14 -4
  62. package/dist/web/steel-3d-core.js +39 -9
  63. package/dist/web/steel-3d-flo.js +331 -0
  64. package/dist/web/steel-3d-view.js +164 -0
  65. package/dist/web/steel-ai-marks.js +3 -1
  66. package/dist/web/steel-editor.html +583 -129
  67. package/dist/web/steel-environments.js +297 -0
  68. package/dist/web/steel-filter.html +3 -2
  69. package/dist/web/steel-model-v2-client-validation.js +8 -1
  70. package/dist/web/steel-model-v2-commands.js +23 -9
  71. package/dist/web/steel-model-v2-projection.js +1 -1
  72. package/dist/web/step-rename.js +3 -2
  73. package/dist/web/terminal-requests.js +79 -1
  74. package/dist/web/tool-updates.js +9 -7
  75. package/dist/web/vector-3d.html +1 -1
  76. package/dist/web/vector-editor.html +50 -8
  77. package/dist/web/workspace-root-management.js +1 -1
  78. package/dist/web/workspaces.js +2334 -253
  79. package/launch.mjs +5 -0
  80. package/package.json +11 -8
package/dist/web/aware.js CHANGED
@@ -173,7 +173,7 @@
173
173
  }
174
174
 
175
175
  function agentDisplayName(id) {
176
- return ({ 'html-report': 'HTML Report', 'html-report-stream': 'HTML Report', 'viewer-3d': '3D Viewer', file: 'File' })[id] || id;
176
+ return ({ 'html-report': 'HTML Report', 'html-report-stream': 'HTML Report', 'viewer-3d': '3D Viewer', file: 'File', script: 'Script' })[id] || id;
177
177
  }
178
178
 
179
179
  function runFailureMessage(message) {
@@ -253,6 +253,23 @@
253
253
  }).join('');
254
254
  }
255
255
 
256
+ // #3234: the listing row's answer (app-reader appListFacts → needsAware), or null.
257
+ function awareTooOldFor(id) {
258
+ const row = wfLibrary.find((item) => item.id === id);
259
+ const t = row && row.needsAware;
260
+ return t && typeof t.minimum === 'string' && Array.isArray(t.agents) && t.agents.length ? t : null;
261
+ }
262
+ // The one explanation every surface uses (the notice above the canvas, the status pill's tip).
263
+ function awareTooOldSentence(t) {
264
+ const steps = t.agents.length === 1 ? `${agentDisplayName(t.agents[0])} steps` : 'Some of its steps';
265
+ return `This workflow's ${steps} run inside AWARE itself and need no other program. This computer has AWARE ${t.installed || 'an older version'}, which cannot run them, and installing a tool will not help. `
266
+ + 'To fix it, choose Upgrade AWARE beside the AWARE version at the bottom of the window, then press Compile. If Upgrade AWARE does not show, the newer AWARE is not available to this computer yet.';
267
+ }
268
+ function awareTooOldRow(t) {
269
+ return `<li class="missing-agent-row"><div><strong>AWARE ${escapeHtml(t.minimum)} or newer</strong>` +
270
+ `<div class="missing-agent-detail">${escapeHtml(awareTooOldSentence(t))}</div></div></li>`;
271
+ }
272
+
256
273
  function missingAgentsBulkButton(pending, canInstall) {
257
274
  if (pending.length <= 1) return '';
258
275
  return `<button class="btn small" type="button" data-note-install-all data-command-id="shell.workflow-agents-install-all" aria-label="Install all missing tools" aria-busy="${!canInstall.length}" ${canInstall.length ? '' : 'disabled data-blocked-reason="Tool installations are in progress. Please wait."'}>${canInstall.length ? `Install all (${canInstall.length})` : 'Installing…'}</button>`;
@@ -268,17 +285,20 @@
268
285
  'microsoft-365': '<rect x="2" y="2" width="8" height="8" rx="1"/><rect x="14" y="2" width="8" height="8" rx="1"/><rect x="2" y="14" width="8" height="8" rx="1"/><rect x="14" y="14" width="8" height="8" rx="1"/>',
269
286
  email: '<rect x="2" y="4" width="20" height="16" rx="2"/><path d="M2 7l10 7 10-7"/>',
270
287
  http: '<polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/>',
288
+ // #3234: AWARE's built-in script runner — braces, since its step is code that needs no program.
289
+ script: '<path d="M8 3H7a2 2 0 00-2 2v5a2 2 0 01-2 2 2 2 0 012 2v5a2 2 0 002 2h1"/><path d="M16 3h1a2 2 0 012 2v5a2 2 0 002 2 2 2 0 00-2 2v5a2 2 0 01-2 2h-1"/>',
271
290
  };
272
291
  const AGENT_NAMES = {
273
292
  tekla: 'Tekla', file: 'File', excel: 'Excel', revit: 'Revit', slack: 'Slack',
274
293
  'trimble-connect': 'Trimble Connect', 'microsoft-365': 'Microsoft 365', email: 'Email', http: 'HTTP',
294
+ script: 'Script step (runs inside AWARE, no other program needed)',
275
295
  };
276
296
  const _svgWrap = (inner) => `<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${inner}</svg>`;
277
297
  const iconFor = (agent) => _svgWrap(AGENT_ICONS[agent] || '<path d="M12 2l8 10-8 10L4 12z"/>');
278
298
  const iconTipFor = (agent) => AGENT_NAMES[agent] || (agent ? agent.replace(/-/g, ' ') : '');
279
299
  const AGENT_ICONS_TEXT = {
280
300
  tekla: '⊞', file: '🗀', excel: '◵', revit: '◰', slack: '✦',
281
- 'trimble-connect': '☁', 'microsoft-365': '✉', email: '✉', http: '⇄',
301
+ 'trimble-connect': '☁', 'microsoft-365': '✉', email: '✉', http: '⇄', script: '{}',
282
302
  };
283
303
  const iconTextFor = (agent) => AGENT_ICONS_TEXT[agent] || '◈';
284
304
 
@@ -354,12 +374,11 @@
354
374
  awareMaintenanceRefused = true;
355
375
  }
356
376
  // The server's own words when it gave some; otherwise the shared failure sentence (#3097), never "HTTP 500".
357
- const serverText = (body.code === 'maintenance-busy' && body.message) || body.error;
377
+ const serverText = (body.code === 'maintenance-busy' && body.message) || personText(body);
358
378
  const err = new Error(serverText || apiFailureText({ status: res.status, body }, readOnly));
359
379
  err.body = body; // preserve the in-band payload (e.g. credentialIssue) for callers
360
380
  err.status = res.status; // callers need to distinguish a terminal refusal from a transient outage
361
- // False: the message is one of FloLess's own generic sentences, not the server's reason for this request.
362
- err.serverText = Boolean(serverText) && body.code !== 'response-unreadable';
381
+ // #3097 3b: no marker for "the server said this"; a reader works the sentence out again from `body` (errorText).
363
382
  throw err;
364
383
  }
365
384
  return body;
@@ -498,7 +517,13 @@
498
517
  'bool', 'string', 'char', 'object', 'dynamic', 'this', 'base', 'typeof', 'nameof',
499
518
  'default', 'get', 'set', 'async', 'await', 'yield', 'lock', 'params', 'when', 'where',
500
519
  ]);
501
- function highlightCSharp(src) {
520
+ // #3234: the same C-family scanner colours a script step's JavaScript, with its own keywords and `template` strings.
521
+ const JS_KEYWORDS = new Set([
522
+ 'const', 'let', 'var', 'function', 'return', 'if', 'else', 'for', 'of', 'in', 'while', 'do', 'switch', 'case', 'break',
523
+ 'continue', 'try', 'catch', 'finally', 'throw', 'new', 'typeof', 'instanceof', 'null', 'undefined', 'true', 'false',
524
+ 'this', 'class', 'extends', 'delete', 'void', 'yield', 'default',
525
+ ]);
526
+ function highlightCSharp(src, keywords = CSHARP_KEYWORDS) {
502
527
  const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
503
528
  const span = (cls, text) => `<span class="${cls}">${esc(text)}</span>`;
504
529
  const n = src.length;
@@ -519,13 +544,13 @@
519
544
  while (j < n) { if (src[j] === '"') { if (src[j + 1] === '"') { j += 2; continue; } j++; break; } j++; }
520
545
  out += span('st', src.slice(i, j)); i = j; continue;
521
546
  }
522
- if (c === '"' || c === "'" || (c === '$' && src[i + 1] === '"')) { // string / char
547
+ if (c === '"' || c === "'" || c === '`' || (c === '$' && src[i + 1] === '"')) { // string / char / JS template
523
548
  const quote = c === '$' ? '"' : c;
524
549
  let j = c === '$' ? i + 2 : i + 1;
525
550
  while (j < n) {
526
551
  if (src[j] === '\\') { j += 2; continue; }
527
552
  if (src[j] === quote) { j++; break; }
528
- if (src[j] === '\n') break;
553
+ if (src[j] === '\n' && quote !== '`') break;
529
554
  j++;
530
555
  }
531
556
  out += span('st', src.slice(i, j)); i = j; continue;
@@ -537,7 +562,7 @@
537
562
  if (/[A-Za-z_]/.test(c)) { // identifier / keyword / type
538
563
  let j = i; while (j < n && /[A-Za-z0-9_]/.test(src[j])) j++;
539
564
  const word = src.slice(i, j);
540
- if (CSHARP_KEYWORDS.has(word)) out += span('kw', word);
565
+ if (keywords.has(word)) out += span('kw', word);
541
566
  else if (/^[A-Z]/.test(word)) out += span('ty', word);
542
567
  else out += esc(word);
543
568
  i = j; continue;
@@ -564,6 +589,16 @@
564
589
  return out.join(' ').replace(/\s+/g, ' ').trim();
565
590
  }
566
591
 
592
+ // A node's plain-English Description, as paragraphs: the code's leading comment when it has one, else the
593
+ // step's own `description:` from the .flo (#2952: a step that calls a tool has no code to carry a comment).
594
+ // A blank line in the authored text starts a new paragraph; any other line break is just wrapping.
595
+ function plainDescriptionParas(n, execSource) {
596
+ const fromCode = execSource ? leadingComment(execSource) : '';
597
+ if (fromCode) return [fromCode];
598
+ const own = typeof n.description === 'string' ? n.description : '';
599
+ return own.split(/\r?\n[ \t]*\r?\n/).map((p) => p.replace(/\s+/g, ' ').trim()).filter(Boolean);
600
+ }
601
+
567
602
  function buildAgentEntry(app, n) {
568
603
  const pin = app.lock.agentPins && n.agent ? app.lock.agentPins[n.agent] : null;
569
604
  // All file-derived strings are escaped here: cardEl/renderInspect inject these
@@ -583,9 +618,12 @@
583
618
  const execSource = n.config && typeof n.config.code === 'string' ? n.config.code
584
619
  : n.inputs && typeof n.inputs.code === 'string' ? n.inputs.code : null;
585
620
  const pythonSource = n.agent === 'blender';
621
+ const jsSource = n.agent === 'script'; // #3234: AWARE's built-in script runner takes JavaScript
586
622
  // Description tab: a plain-English explanation + a small input table that
587
623
  // EXCLUDES the code (code belongs to the Code tab, never dumped here).
588
- const plainDesc = execSource ? leadingComment(execSource) : '';
624
+ const plainParas = plainDescriptionParas(n, execSource);
625
+ // The card blurb is the first sentence of the FIRST paragraph only, so a paragraph without a full stop never runs into the next.
626
+ const plainDesc = plainParas[0] || '';
589
627
  const blurbText = plainDesc && (s => s.length > 80 ? s.slice(0, 79) + '…' : s)(plainDesc.replace(/\.\s+.*/, '.').trim());
590
628
  // #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,
591
629
  // 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.
@@ -605,7 +643,7 @@
605
643
  title: escapeHtml(n.id),
606
644
  subtitle: `${agentLabel}${cmd ? '/' + cmd : ''} · ${mode}`,
607
645
  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`,
608
- 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}`,
646
+ description: aiStep ? `${aiStep.descriptionHtml}${notesHtml}` : `${aiUse ? aiUse.descriptionHtml : ''}${plainParas.map((p) => `<p class="node-desc">${escapeHtml(p)}</p>`).join('')}<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}`,
609
647
  // Rich agent/command detail when the manifest is installed (n.skill); else
610
648
  // the lock-pointer fallback below (exec/agent-less nodes, uninstalled agents).
611
649
  skill: skillBody(
@@ -620,6 +658,8 @@
620
658
  // non-exec nodes there is no script; we show the resolved lockfile YAML.
621
659
  code: execSource && pythonSource
622
660
  ? escapeHtml(`# ${n.agent}${n.command ? '.' + n.command : ''} · node "${n.id}" · live source from ~/.aware/apps/${app.id}/\n${execSource}`)
661
+ : execSource && jsSource
662
+ ? highlightCSharp(`// ${n.agent}${n.command ? '.' + n.command : ''} · node "${n.id}" · live source from ~/.aware/apps/${app.id}/\n${execSource}`, JS_KEYWORDS)
623
663
  : execSource
624
664
  ? highlightCSharp(`// ${n.agent || n.kind}${n.command ? '.' + n.command : ''} · node "${n.id}" · live source from ~/.aware/apps/${app.id}/\n${execSource}`)
625
665
  : app.lock.present
@@ -701,6 +741,9 @@
701
741
  // #1998: the exact tool version this workflow was approved with cannot run; the person chooses (reinstall
702
742
  // it, or Compile again). Presentation only: the gate is 'agent-changed'.
703
743
  'needs-you': { label: 'Needs you', className: 'drift' },
744
+ // #3234: steps that run inside AWARE need a newer AWARE than this computer has. It comes before every other
745
+ // state: Compile, a reinstall or a run all fail until AWARE is upgraded. Presentation only.
746
+ 'needs-aware': { label: 'Needs newer AWARE', className: 'drift' },
704
747
  drift: { label: 'Needs refresh', className: 'drift' },
705
748
  uncompiled: { label: 'Not set up', className: 'uncompiled' },
706
749
  };
@@ -761,6 +804,7 @@
761
804
  // #1996: what the pill shows for a gate state. The gate itself (and the Instructor's runState) is unchanged;
762
805
  // only the label can say more.
763
806
  function presentedGateState(app, gateState) {
807
+ if (gateState !== 'draft' && awareTooOldFor(app.id)) return 'needs-aware';
764
808
  if (gateState === 'agent-changed' && app.approvalCheck && app.approvalCheck.remedy === 'publish') return 'needs-publish';
765
809
  if (gateState === 'agent-changed' && app.approvalCheck && app.approvalCheck.remedy === 'needs-you') return 'needs-you';
766
810
  if (gateState === 'ready' && app.approvalCheck && app.approvalCheck.bridgeWarnings && app.approvalCheck.bridgeWarnings.length) return 'needs-you';
@@ -807,11 +851,20 @@
807
851
  // verbatim in the details, because that record is the label — never "unchanged behaviour".
808
852
  const $approvalStrip = document.getElementById('approval-strip');
809
853
  let approvalStripReinstalling = null; // `${appId}\u0000${agent}` while a reinstall is in flight
854
+ // #3097: what a failed reinstall says when the server explained no further (errorText, web/failure-copy.js).
855
+ const REINSTALL_FAILURE = { action: 'put the approved tool back', unsure: 'Reopen the workflow to see whether the tool is back before trying again.' };
810
856
 
811
857
  function approvalStripState(app) {
812
858
  const check = app && app.approvalCheck;
813
859
  if (!check) return null;
814
- if (gateStateFor(app) === 'agent-changed' && check.remedy === 'needs-you') return 'needs-you';
860
+ if (gateStateFor(app) === 'agent-changed' && check.remedy === 'needs-you') {
861
+ // #3234: a version this AWARE is too old to run cannot be reinstalled either; the notice above the canvas says
862
+ // to upgrade AWARE, so the strip offers no reinstall for it. A bridge warning or a carried-over approval still
863
+ // shows: the check falls through to them.
864
+ const tooOld = awareTooOldFor(app.id);
865
+ const unavailable = Array.isArray(check.unavailable) ? check.unavailable : [];
866
+ if (!(tooOld && unavailable.length && unavailable.every((u) => tooOld.agents.includes(u.agent)))) return 'needs-you';
867
+ }
815
868
  if (check.current && check.origin === 'successor' && Array.isArray(check.successors) && check.successors.length) return 'carried';
816
869
  if (Array.isArray(check.bridgeWarnings) && check.bridgeWarnings.length) return 'bridge-warning';
817
870
  return null;
@@ -869,7 +922,9 @@
869
922
  return;
870
923
  }
871
924
  if (state === 'needs-you') {
872
- const rows = (check.unavailable || []).filter((u) => u.reinstall);
925
+ // #3234: a runner this AWARE is too old for gets no reinstall (AWARE would refuse it); the notice says to upgrade.
926
+ const tooOld = awareTooOldFor(app.id);
927
+ const rows = (check.unavailable || []).filter((u) => u.reinstall && !(tooOld && tooOld.agents.includes(u.agent)));
873
928
  $approvalStrip.className = 'approval-strip approval-needs-you';
874
929
  $approvalStrip.setAttribute('role', 'group');
875
930
  $approvalStrip.setAttribute('aria-label', 'A tool version needs your decision');
@@ -959,10 +1014,11 @@
959
1014
  $compileBtn.disabled = true; // never approve whichever copy happens to be installed mid-swap
960
1015
  const app = apps.get(id);
961
1016
  if (app) paintApprovalStrip(app);
962
- let res = null;
1017
+ // `outcome`, not `res`: its `message` is the route's own sentence for a person (afterReinstallMessage).
1018
+ let outcome = null;
963
1019
  let error = null;
964
1020
  try {
965
- res = await api(`/api/app/${encodeURIComponent(id)}/reinstall-approved-tool`, { method: 'POST', body: JSON.stringify({ agent, version }) });
1021
+ outcome = await api(`/api/app/${encodeURIComponent(id)}/reinstall-approved-tool`, { method: 'POST', body: JSON.stringify({ agent, version }) });
966
1022
  } catch (err) {
967
1023
  error = err;
968
1024
  } finally {
@@ -973,14 +1029,15 @@
973
1029
  // The state moved on; repaint from it (only if the person is still on this workflow).
974
1030
  if (stillHere()) await loadApp(id).catch(reportErr);
975
1031
  else repaintShown();
976
- showToast(error.message, 'info');
1032
+ showToast(errorText(error, REINSTALL_FAILURE), 'info');
977
1033
  return;
978
1034
  }
979
1035
  if (error) {
980
1036
  repaintShown();
981
1037
  const row = stillHere() && $approvalStrip.querySelector(`.approval-row[data-agent="${CSS.escape(agent)}"] .approval-row-error`);
982
- if (row) row.textContent = (error.body && error.body.code === 'reinstall-failed') ? `${error.message} You can try again, or Compile again.` : error.message;
983
- else showToast(error.message, 'warn'); // the person moved on: the failure still reaches them
1038
+ const said = errorText(error, REINSTALL_FAILURE);
1039
+ if (row) row.textContent = (error.body && error.body.code === 'reinstall-failed') ? `${said} You can try again, or Compile again.` : said;
1040
+ else showToast(said, 'warn'); // the person moved on: the failure still reaches them
984
1041
  return;
985
1042
  }
986
1043
  if (stillHere()) await loadApp(id).catch(reportErr);
@@ -988,7 +1045,7 @@
988
1045
  if (typeof loadAgentCatalog === 'function') {
989
1046
  loadAgentCatalog().catch((err) => console.warn('[floless] the Agents list could not be refreshed after a reinstall', err));
990
1047
  }
991
- showToast(res.message, res.reinstalled === true ? 'ok' : 'warn');
1048
+ showToast(outcome.message, outcome.reinstalled === true ? 'ok' : 'warn');
992
1049
  });
993
1050
  }
994
1051
 
@@ -1127,7 +1184,8 @@
1127
1184
  if (err.body && err.body.statement && policyView) { policyView.statement = err.body.statement; policyView.statementSha256 = err.body.statementSha256; renderPolicyModal(); }
1128
1185
  t.disabled = false; t.removeAttribute('aria-busy'); t.textContent = prev;
1129
1186
  const $e = $policyModal.querySelector('.policy-error') || $err;
1130
- if ($e) $e.textContent = err.message;
1187
+ if ($e) $e.textContent = errorText(err, { action: off ? 'turn automatic tool updates off' : 'turn automatic tool updates on',
1188
+ unsure: 'Reopen this setting to see whether it changed before trying again.' });
1131
1189
  }
1132
1190
  }
1133
1191
  });
@@ -1199,11 +1257,79 @@
1199
1257
  }
1200
1258
 
1201
1259
  // Run's own outcome is authoritative, even if a Stop acknowledgement was lost or arrived later.
1202
- async function dispatchManualRun(request, payload) {
1260
+ /**
1261
+ * #3253: the workflow's FloLess steps are set to reach another FloLess on this computer (it was approved while that one
1262
+ * was in charge). Ask before anything starts: compile and approve it here (the default), run it anyway, or cancel. On an
1263
+ * AWARE that can point at only one FloLess, compiling here would not help yet, so that choice is replaced by what does.
1264
+ */
1265
+ async function askRunElsewhere(elsewhere, { routine = false } = {}) {
1266
+ const port = Number.isInteger(elsewhere.port) ? ` The other FloLess is on port ${elsewhere.port}.` : '';
1267
+ const what = 'Its FloLess steps (the ones that use your FloLess projects, and its AI steps) are set to reach another FloLess '
1268
+ + 'running on this computer. If it runs as it is, they would read that FloLess’s projects instead of yours, and its AI steps would not start.';
1269
+ const sub = elsewhere.overlay
1270
+ ? `${what} That happened because it was approved while the other FloLess was in charge. `
1271
+ + `${routine ? 'Open the workflow, then compile and approve it there' : 'Compile and approve it here'} to point it at this FloLess.${port}`
1272
+ : `${what} Compiling it here would not change that yet: your version of AWARE (the engine FloLess runs on) can point at only one `
1273
+ + 'FloLess at a time, and the other FloLess holds it. Update AWARE and then compile and approve it here, or close the other '
1274
+ + `FloLess and restart this one so it takes over, or run it anyway.${port}`;
1275
+ const commandIds = { confirm: routine ? 'shell.run-elsewhere-open' : 'shell.run-elsewhere-approve',
1276
+ discard: 'shell.run-elsewhere-anyway', cancel: 'shell.dialog-cancel#the another-FloLess prompt' };
1277
+ const choice = await confirmUnsavedSwitch('', sub, 'This workflow is set up for another FloLess',
1278
+ elsewhere.overlay ? { confirm: routine ? 'Open the workflow' : 'Compile and approve here', discard: 'Run anyway', cancel: 'Cancel', commandIds }
1279
+ : { hideSave: true, discard: 'Run anyway', cancel: 'Cancel', initialFocus: 'cancel', commandIds });
1280
+ return choice === 'save' ? 'approve' : choice === 'discard' ? 'anyway' : 'cancel';
1281
+ }
1282
+
1283
+ /**
1284
+ * #3253: POST a run (a routine's Run now, a live run) and, while the server answers that its FloLess steps reach another
1285
+ * FloLess, ask; "Run anyway" posts again naming the endpoints shown, and other endpoints ask again. Not running throws a
1286
+ * not-run answer the caller already shows; "Compile and approve here" (or "Open the workflow") calls `onApprove` first.
1287
+ */
1288
+ async function postAskingElsewhere(url, body, { routine = false, onApprove } = {}) {
1289
+ let send = body;
1290
+ for (;;) {
1291
+ try {
1292
+ return await api(url, { method: 'POST', body: JSON.stringify(send) });
1293
+ } catch (error) {
1294
+ if (!(error && error.status === 409 && error.body && error.body.code === 'floless-steps-elsewhere' && error.body.elsewhere)) throw error;
1295
+ const choice = await askRunElsewhere(error.body.elsewhere, { routine });
1296
+ if (choice !== 'anyway') {
1297
+ if (choice === 'approve' && onApprove) await onApprove();
1298
+ throw Object.assign(new Error('Run stopped before execution started.'), { body: { notRun: true, elsewhereStopped: true, error: 'Run stopped before execution started.' } });
1299
+ }
1300
+ send = { ...body, runElsewhere: error.body.elsewhere.signature };
1301
+ }
1302
+ }
1303
+ }
1304
+
1305
+ /**
1306
+ * `retrack` (a tracked run only) starts a fresh tracked attempt for a Run anyway resend and returns its token: the
1307
+ * refused attempt ended under its own token, before, during or after the ask, and its ending must never settle,
1308
+ * or drop the saved token of, the run that actually goes ahead.
1309
+ */
1310
+ async function dispatchManualRun(request, payload, retrack) {
1203
1311
  let result, error;
1204
1312
  try {
1205
1313
  result = await api('/api/run', { method: 'POST', body: JSON.stringify({ ...payload, runRequestId: request.id }) });
1206
1314
  } catch (caught) { error = caught; }
1315
+ // #3253: asked again for as long as the server answers with other endpoints than the ones the person accepted.
1316
+ while (error && error.status === 409 && error.body && error.body.code === 'floless-steps-elsewhere' && error.body.elsewhere) {
1317
+ const { signature } = error.body.elsewhere;
1318
+ const choice = await askRunElsewhere(error.body.elsewhere);
1319
+ if (choice !== 'anyway') {
1320
+ if (choice === 'approve' && $compileBtn && !$compileBtn.disabled) $compileBtn.click();
1321
+ error = Object.assign(new Error('Run stopped before execution started.'), { body: { cancelled: true, error: 'Run stopped before execution started.' } });
1322
+ break;
1323
+ }
1324
+ // A new request id: the refused one is finished on the server. "Run anyway" covers exactly the endpoints shown;
1325
+ // if they changed meanwhile, the server answers with the new ones and the loop asks again.
1326
+ request.id = crypto.randomUUID();
1327
+ if (payload.clientRunToken && retrack) payload = { ...payload, clientRunToken: retrack() };
1328
+ error = undefined;
1329
+ try {
1330
+ result = await api('/api/run', { method: 'POST', body: JSON.stringify({ ...payload, runRequestId: request.id, runElsewhere: signature }) });
1331
+ } catch (caught) { error = caught; }
1332
+ }
1207
1333
  // A Stop reply can disappear even after the server has settled this run. Its acknowledgement
1208
1334
  // cannot hold the authoritative result hostage or change it after completion.
1209
1335
  request.settled = true;
@@ -1274,6 +1400,8 @@
1274
1400
  if (gateState === 'ready' && app.approvalCheck && app.approvalCheck.bridgeWarnings && app.approvalCheck.bridgeWarnings.length) {
1275
1401
  gateTips.ready += '\nBridge needs attention. Review the warning and choices above the canvas. Run workflow is still available; the run record will note the warning.';
1276
1402
  }
1403
+ const tooOld = gateState !== 'draft' ? awareTooOldFor(app.id) : null;
1404
+ if (tooOld) gateTips[gateState] = `Needs a newer AWARE.\n${awareTooOldSentence(tooOld)}`;
1277
1405
  $runState.dataset.tip = activeTips[status.label] || gateTips[gateState] || '';
1278
1406
 
1279
1407
  // Push a snapshot to the Instructor band. One-way: the band renders what it
@@ -1287,6 +1415,8 @@
1287
1415
  statusLabel: status.label,
1288
1416
  // #1996: what the Instructor says for a not-confirmed carried-forward approval or an incomplete record.
1289
1417
  remedy: (app.approvalCheck && app.approvalCheck.remedy) || null,
1418
+ // #3234: comes before every other state: nothing else can be done until AWARE is upgraded.
1419
+ awareTooOld: tooOld ? { minimum: tooOld.minimum } : null,
1290
1420
  recordIncomplete: recordNeedsCheck(app, gateState),
1291
1421
  bridgeWarning: !!(app.approvalCheck && app.approvalCheck.bridgeWarnings && app.approvalCheck.bridgeWarnings.length),
1292
1422
  totalInputs: inputs.length,
@@ -1314,7 +1444,10 @@
1314
1444
  if ($stopRunBtn) $stopRunBtn.hidden = !(reportRunning || state.running || foregroundStopping || foregroundTrigger);
1315
1445
  syncReportStopControls();
1316
1446
  const agentChanged = gateStateFor(app) === 'agent-changed';
1317
- $runBtn.dataset.tip = agentChanged
1447
+ const awareTooOld = awareTooOldFor(app.id);
1448
+ $runBtn.dataset.tip = awareTooOld
1449
+ ? `This workflow needs AWARE ${awareTooOld.minimum} or newer — upgrade AWARE first`
1450
+ : agentChanged
1318
1451
  ? (app.approvalCheck
1319
1452
  ? (app.approvalCheck.remedy === 'publish'
1320
1453
  ? 'This workflow changed outside FloLess since it was published — ask AI Chat to publish it again first'
@@ -1377,20 +1510,26 @@
1377
1510
  : 'Compile first — there is no approved lock yet, so Bake is blocked.';
1378
1511
  }
1379
1512
 
1380
- if (app.notes.length) {
1513
+ // #3234: a built-in runner (AWARE's `script`) that the AWARE here does not have yet. It is part of AWARE itself, so
1514
+ // installing a tool cannot help: say so, and leave it out of the install rows. The server works it out from the CLI
1515
+ // version, so this holds whether or not the tool's manifest is installed.
1516
+ const tooOld = awareTooOldFor(app.id);
1517
+ if (app.notes.length || tooOld) {
1381
1518
  const n = app.notes.length;
1382
1519
  const missing = missingAgentGroups(app.notes);
1520
+ if (tooOld) for (const id of tooOld.agents) missing.delete(id);
1383
1521
  const installed = installedIdSet();
1384
1522
  const pending = [...missing.keys()].filter((id) => installingIds.has(id) || missingAgentFailures.has(workflowAgentKey(id)) || (!installed.has(id) && !completedAgentInstalls.has(workflowAgentKey(id))));
1385
1523
  const canInstall = pending.filter((id) => !installingIds.has(id));
1386
1524
  const unchecked = [...missing.keys()].some((id) => installed.has(id) && !completedAgentInstalls.has(workflowAgentKey(id)));
1387
1525
  const nextAction = pending.some((id) => missingAgentFailures.has(workflowAgentKey(id))) ? 'attention' : 'installing';
1388
1526
  const ordinaryNotes = app.notes.filter((nt) => !missingAgentId(nt.text));
1527
+ const awareRow = tooOld ? awareTooOldRow(tooOld) : '';
1389
1528
  const sig = notesSig(app.notes);
1390
1529
  // Strip severity = worst note kind (info < warn < error). Drives colour +
1391
1530
  // icon; AWARE 0.48 tags each note with `kind` (#170) so we render by it
1392
1531
  // rather than guessing from the text.
1393
- const worst = app.notes.some((x) => x.kind === 'error') ? 'error'
1532
+ const worst = tooOld || app.notes.some((x) => x.kind === 'error') ? 'error'
1394
1533
  : app.notes.some((x) => x.kind === 'warn') ? 'warn' : 'info';
1395
1534
  const icon = worst === 'error' ? '✕' : worst === 'warn' ? '⚠' : 'ℹ';
1396
1535
  $notesStrip.hidden = false;
@@ -1399,10 +1538,10 @@
1399
1538
  $notesStrip.classList.remove('sev-info', 'sev-warn', 'sev-error');
1400
1539
  $notesStrip.classList.add('sev-' + worst);
1401
1540
  $notesStrip.innerHTML =
1402
- `<div class="notes-head"><span class="notes-title">${icon} ${missing.size ? (pending.length ? `${pending.length} tool${pending.length === 1 ? ' needs' : 's need'} ${nextAction}` : unchecked ? 'Check tool installations before compiling' : 'Tools installed — compile to refresh checks') : `${n} workflow notice${n === 1 ? '' : 's'}`}</span>` +
1541
+ `<div class="notes-head"><span class="notes-title">${icon} ${tooOld && !missing.size ? 'Needs a newer AWARE' : missing.size ? (pending.length ? `${pending.length} tool${pending.length === 1 ? ' needs' : 's need'} ${nextAction}` : unchecked ? 'Check tool installations before compiling' : 'Tools installed — compile to refresh checks') : `${n} workflow notice${n === 1 ? '' : 's'}`}</span>` +
1403
1542
  missingAgentsBulkButton(pending, canInstall) +
1404
1543
  `<button class="notes-dismiss" type="button" aria-label="Collapse compiler notes" data-tip="Collapse">×</button></div>` +
1405
- (missing.size ? `<ul class="missing-agent-list" aria-live="polite">${missingAgentRows(missing)}</ul>` : '') +
1544
+ (awareRow || missing.size ? `<ul class="missing-agent-list" aria-live="polite">${awareRow}${missingAgentRows(missing)}</ul>` : '') +
1406
1545
  (ordinaryNotes.length ? `<ul>${ordinaryNotes.map((nt) => `<li><span class="note-kind ${nt.kind}">${nt.kind}</span><code>${escapeHtml(nt.nodeId)}</code> — ${escapeHtml(humanizeNote(nt.text))}</li>`).join('')}</ul>` : '');
1407
1546
  // Collapse decision: a remembered choice for this exact note set wins;
1408
1547
  // otherwise default to collapsed for benign info-only sets (keep the canvas
@@ -1626,7 +1765,7 @@
1626
1765
  } catch (error) {
1627
1766
  const copied = await copyToClipboard(markedInstruction(request));
1628
1767
  const workspaceProblem = ['instructor-workspace-root-changed', 'instructor-workspace-earlier-generation', 'instructor-workspace-unavailable'].includes(error?.code);
1629
- showToast(workspaceProblem ? error.message
1768
+ showToast(workspaceProblem ? errorText(error, { action: 'start this answer in AI Chat', unsure: 'Your question is saved in Requests; open it there to try again.' })
1630
1769
  : `AI Chat couldn’t start this answer. Your question is saved in Requests; open it there to try again.${copied ? ' The question is also copied.' : ''}`, 'err');
1631
1770
  try { await loadRequests(); } catch (refreshError) { console.error(refreshError); }
1632
1771
  activeInstructorRuns.delete(fingerprint);
@@ -1805,9 +1944,11 @@
1805
1944
  } catch (e) {
1806
1945
  if (guide) throw e;
1807
1946
  if (!building) { reportErr(e); return null; }
1808
- // Every message on this path is written for people (ours, the AI setup's, the build route's); the toast's own
1809
- // filter still catches anything technical.
1810
- showToast(`${e?.message || 'FloLess couldn’t start building it.'} To try again, use ≡ → New workflow with the same name and place; FloLess picks up the same draft.`, 'warn', { persistent: true });
1947
+ // Ours and the AI setup's are marked forPerson; the build route's reply is read again from its body (errorText).
1948
+ // The retry step is the unknown-outcome advice too, so an unexplained failure does not say "try again" twice.
1949
+ const again = 'To try again, use ≡ → New workflow with the same name and place; FloLess picks up the same draft.';
1950
+ const said = errorText(e, { action: 'start building it', unsure: again });
1951
+ showToast(said.includes(again) ? said : `${said} ${again}`, 'warn', { persistent: true });
1811
1952
  return null;
1812
1953
  }
1813
1954
  }
@@ -1817,12 +1958,12 @@
1817
1958
  * Guide build uses the AI its Guide conversation uses; ≡ New workflow uses the AI Chat's own choice.
1818
1959
  */
1819
1960
  async function buildWorkflowInChat({ buildId, payload, reopen = false }) {
1820
- if (typeof window.flolessChat?.startWorkflowBuild !== 'function') throw new Error('AI Chat is still starting. Try again in a moment.');
1961
+ if (typeof window.flolessChat?.startWorkflowBuild !== 'function') throw Object.assign(new Error('AI Chat is still starting. Try again in a moment.'), { forPerson: true });
1821
1962
  const provider = payload.source === 'guide' ? (window.flolessChat.currentProvider?.() || preferredChatProvider()) : preferredChatProvider();
1822
- if (!provider) throw new Error('Sign in to Claude or Codex in AI Chat, then build the workflow again.');
1963
+ if (!provider) throw Object.assign(new Error('Sign in to Claude or Codex in AI Chat, then build the workflow again.'), { forPerson: true });
1823
1964
  // Reopening a started build needs no AI set up first: the conversation opens either way, and says if it can't send.
1824
1965
  const ready = reopen ? { ok: true } : await ensureChatRuntimeReady(provider);
1825
- if (!ready.ok) throw Object.assign(new Error(ready.reason || 'Claude or Codex could not be set up for AI Chat. Try again in a moment.'), { code: 'chat-runtime-not-ready' });
1966
+ if (!ready.ok) throw Object.assign(new Error(ready.reason || 'Claude or Codex could not be set up for AI Chat. Try again in a moment.'), { code: 'chat-runtime-not-ready', forPerson: true });
1826
1967
  const result = await window.flolessChat.startWorkflowBuild(buildId, payload.source === 'menu' ? { ...payload, provider } : payload);
1827
1968
  try { ({ workflows: wfOwned } = await api('/api/workflows/owned')); } catch { /* the next refresh lists it */ }
1828
1969
  return result;
@@ -2975,12 +3116,13 @@
2975
3116
  // status-bar app like hello-world runs exec yet emits no HTML, so it has no
2976
3117
  // report-viewer node (and Run must fill the trace, not open an empty viewer).
2977
3118
  // The code test matches `html` in anonymous-object-property position only —
2978
- // `html =` OR shorthand `html` (preceded by `{`/`,`, followed by `=`/`,`/`}`)
2979
- // — so a local `html` variable in a non-report node doesn't false-qualify it.
3119
+ // `html =` OR shorthand `html` (preceded by `{`/`,`, followed by `=`/`,`/`}`), or a JavaScript
3120
+ // `html:` (#3234: a script step returns a plain object) — so a local `html` variable in a
3121
+ // non-report node doesn't false-qualify it.
2980
3122
  const producesHtml = app.nodes.some((n) => {
2981
3123
  const cfg = n.config;
2982
3124
  if (!cfg) return false;
2983
- if (typeof cfg.code === 'string' && /[,{]\s*html\s*[=,}]/.test(cfg.code)) return true;
3125
+ if (typeof cfg.code === 'string' && /[,{]\s*html\s*[=:,}]/.test(cfg.code)) return true;
2984
3126
  if (cfg.args && typeof cfg.args === 'object') {
2985
3127
  for (const v of Object.values(cfg.args)) {
2986
3128
  if (typeof v === 'string' && /\{\{\s*[\w.-]+\.result\.html\s*\}\}/.test(v)) return true;
@@ -4156,10 +4298,10 @@
4156
4298
  const version = Number(link.dataset.version);
4157
4299
  void (async () => {
4158
4300
  try {
4159
- if (typeof window.flolessPages?.open !== 'function') throw new Error('The Pages viewer is not loaded. Reload FloLess and try again.');
4301
+ if (typeof window.flolessPages?.open !== 'function') throw Object.assign(new Error('FloLess couldn’t open the workflow’s Page, because the Pages viewer is not loaded. Reload FloLess and try again.'), { forPerson: true });
4160
4302
  await closeReportViewer();
4161
4303
  await window.flolessPages.open(link.dataset.home, link.dataset.page, Number.isInteger(version) && version > 0 ? version : undefined);
4162
- } catch (e) { showToast(`FloLess couldn’t open the workflow’s Page. ${e && e.message ? e.message : ''}`.trim(), 'warn'); }
4304
+ } catch (e) { showToast(errorText(e, { action: 'open the workflow’s Page', retrySafe: true }), 'warn'); }
4163
4305
  })();
4164
4306
  });
4165
4307
 
@@ -4311,9 +4453,9 @@
4311
4453
  answer = await api(`/api/pages/${encodeURIComponent(home)}/${encodeURIComponent(id)}/versions/${encodeURIComponent(n)}/full-report`);
4312
4454
  } catch (error) {
4313
4455
  console.warn('full report did not open', error);
4314
- // The server's reason when it gave one (#3097: api() marks it); a lost connection or an unexplained failure gets
4315
- // the shared sentence for this read, never the browser's "Failed to fetch".
4316
- showToast(error?.serverText ? error.message : failureCopy(error, { action: 'open the full report', retrySafe: true }).text, 'warn');
4456
+ // The server's reason when it gave one, read again from its reply (#3097 errorText); a lost connection or an
4457
+ // unexplained failure gets the shared sentence for this read, never the browser's "Failed to fetch".
4458
+ showToast(errorText(error, { action: 'open the full report', retrySafe: true }), 'warn');
4317
4459
  return false;
4318
4460
  }
4319
4461
  if (typeof answer?.handle !== 'string' || !answer.handle) {
@@ -4390,6 +4532,7 @@
4390
4532
  await response.body?.cancel();
4391
4533
  if (request !== reportSectionRequest) return false;
4392
4534
  $reportFrame.removeAttribute('srcdoc');
4535
+ $reportFrame.dataset.surface = 'light'; // #3233
4393
4536
  // Navigate to the real session-gated route. Its restrictive CSP must belong to the
4394
4537
  // rendered document itself; a blob: copy would silently lose that response header.
4395
4538
  // #2539: which paint this frame load belongs to, and its wait deadline, should the frame find the report busy.
@@ -4442,7 +4585,7 @@
4442
4585
  continue;
4443
4586
  }
4444
4587
  clearCompleteReportView();
4445
- $reportFrame.srcdoc = '';
4588
+ $reportFrame.srcdoc = ''; delete $reportFrame.dataset.surface;
4446
4589
  $reportSub.textContent = 'This report section could not be displayed.';
4447
4590
  const status = Number(error?.status);
4448
4591
  let remedy = 'Close the viewer and choose View report to retry loading this saved report.';
@@ -4496,6 +4639,7 @@
4496
4639
  function paintReport(html, interactive, entry = null) {
4497
4640
  runPageView.invalidate(); // #2476: a new paint ends the previous report's Page frame, its lookups and its timers
4498
4641
  clearCompleteReportView();
4642
+ paintAiStopBanner(entry && entry.aiStop ? entry.aiStop : null); // #3229: every report says whether its run stopped, or nothing
4499
4643
  $reportOpen.hidden = false;
4500
4644
  lastPaintedHtml = html || '';
4501
4645
  lastPaintedInteractive = !!interactive; // drives the share copy: a 3D model is not a "frozen report"
@@ -4503,7 +4647,7 @@
4503
4647
  if ($reportPage) $reportPage.hidden = true; // likewise its Page link (paintReportPageLinks, once it is cached)
4504
4648
  if (!interactive && entry && entry.withFiles) { paintReportWithFiles(html, entry); return; }
4505
4649
  if (interactive) {
4506
- $reportFrame.hidden = true; $reportFrame.srcdoc = '';
4650
+ $reportFrame.hidden = true; $reportFrame.srcdoc = ''; delete $reportFrame.dataset.surface;
4507
4651
  $reportFrame3d.hidden = false;
4508
4652
  $reportFrame3d.src = 'data:text/html;charset=utf-8,' + encodeURIComponent(html);
4509
4653
  // A 3D doc IS shareable: AWARE's viewer-3d renders one self-contained HTML file, and the public
@@ -4515,7 +4659,9 @@
4515
4659
  $reportOverlay.append(mkEl('div', 'spinner'), mkEl('div', null, 'Loading 3D view…'));
4516
4660
  } else {
4517
4661
  $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4518
- $reportFrame.hidden = false; $reportFrame.srcdoc = html;
4662
+ // #3130: the report's own content rules ride at its top; lastPaintedHtml keeps exactly what the run produced.
4663
+ $reportFrame.dataset.surface = 'light'; // #3233: until the report has loaded and its own text colour can say otherwise
4664
+ $reportFrame.hidden = false; $reportFrame.srcdoc = window.FlolessReportCsp.withReportCsp(html);
4519
4665
  $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
4520
4666
  $reportShare.hidden = false;
4521
4667
  }
@@ -4529,21 +4675,67 @@
4529
4675
  function paintReportWithFiles(html, entry) {
4530
4676
  $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4531
4677
  $reportFrame.hidden = false;
4532
- $reportFrame.srcdoc = html;
4678
+ $reportFrame.dataset.surface = 'light'; // #3233
4679
+ $reportFrame.srcdoc = window.FlolessReportCsp.withReportCsp(html); // #3130
4533
4680
  $reportOverlay.hidden = true; $reportOverlay.replaceChildren();
4534
4681
  $reportOpen.hidden = true;
4535
4682
  $reportShare.hidden = true;
4536
4683
  runPageView.paint(entry);
4537
4684
  }
4538
4685
 
4686
+ // #3233: the page a report is painted on. A report that paints no background of its own used to show FloLess's dark --bg
4687
+ // through, so a report written for the browser's default light page read as dark grey on near-black. Every report now starts
4688
+ // on a light page, the one a browser gives it; once it has loaded its own text colour decides, so light text written for a
4689
+ // dark page it never painted gets a dark one. A report that declares `color-scheme: dark` gets the browser's own dark page
4690
+ // whatever this says, and a report that paints its own background covers it.
4691
+ let reportColorCanvas = null;
4692
+ /** A CSS colour as sRGB [r, g, b] (0–255), or null. A computed colour keeps the form it was written in (`oklch()`,
4693
+ * `color(srgb …)`), so anything that is not plain rgb() is painted on a 1×1 canvas and read back. */
4694
+ function rgbOfCssColor(color) {
4695
+ const m = /^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/.exec(color);
4696
+ if (m) return [Number(m[1]), Number(m[2]), Number(m[3])];
4697
+ if (!color) return null;
4698
+ reportColorCanvas ??= document.createElement('canvas');
4699
+ reportColorCanvas.width = reportColorCanvas.height = 1;
4700
+ const ctx = reportColorCanvas.getContext('2d', { willReadFrequently: true });
4701
+ if (!ctx) return null;
4702
+ ctx.clearRect(0, 0, 1, 1);
4703
+ ctx.fillStyle = 'rgba(0, 0, 0, 0)'; // a colour the canvas rejects leaves this, not the last colour read
4704
+ ctx.fillStyle = color;
4705
+ ctx.fillRect(0, 0, 1, 1);
4706
+ const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;
4707
+ return a ? [r, g, b] : null; // nothing painted: a colour the canvas could not read
4708
+ }
4709
+ function reportSurfaceOf(doc) {
4710
+ try {
4711
+ const color = doc?.body && doc.defaultView ? doc.defaultView.getComputedStyle(doc.body).color : '';
4712
+ const rgb = rgbOfCssColor(color);
4713
+ if (!rgb) return 'light';
4714
+ const linear = (c) => { const v = c / 255; return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; };
4715
+ const luminance = 0.2126 * linear(rgb[0]) + 0.7152 * linear(rgb[1]) + 0.0722 * linear(rgb[2]);
4716
+ // 0.179 is where a colour contrasts equally with white and with black.
4717
+ return luminance > 0.179 ? 'dark' : 'light';
4718
+ } catch { return 'light'; } // an unreadable document keeps the light page
4719
+ }
4720
+ function paintReportSurface() {
4721
+ if (!$reportFrame.dataset.surface) return; // the empty viewer follows the theme
4722
+ let doc = null;
4723
+ try { doc = $reportFrame.contentDocument; } catch { /* not readable: stays light */ }
4724
+ $reportFrame.dataset.surface = reportSurfaceOf(doc);
4725
+ }
4726
+ $reportFrame.addEventListener('load', paintReportSurface);
4727
+ // A report's own dark rules follow the computer's theme, so its text colour can change while it is on screen.
4728
+ try { window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', paintReportSurface); } catch { /* no matchMedia */ }
4729
+
4539
4730
  // Reset the viewer to "no report shown": clear BOTH frames + the Open buffer, so a stale
4540
4731
  // interactive 3D doc can't linger (its WebGL loop running) behind an overlay, and ↗ Open
4541
4732
  // can't reopen a previous app's report. Used by every empty / transition state.
4542
4733
  function clearReportFrames() {
4543
4734
  runPageView.invalidate(); // #2476
4544
4735
  clearCompleteReportView();
4736
+ paintAiStopBanner(null);
4545
4737
  $reportOpen.hidden = false;
4546
- $reportFrame.srcdoc = ''; $reportFrame.hidden = false;
4738
+ $reportFrame.srcdoc = ''; $reportFrame.hidden = false; delete $reportFrame.dataset.surface;
4547
4739
  $reportFrame3d.hidden = true; $reportFrame3d.removeAttribute('src');
4548
4740
  lastPaintedHtml = '';
4549
4741
  showSavedPathActions(''); // no report shown → no saved-file actions
@@ -4603,6 +4795,9 @@
4603
4795
  // and the section speaks to that editor while it is open — the same tabs, by the same code, as the
4604
4796
  // workspace's Model step (web/model-panel-bridge.js).
4605
4797
  let contractEditorApp = null; // the workflow the editor was opened for: Approve bakes that one
4798
+ // What the overlay is showing, for Close's unsaved-work question (#3143): the name that question uses, and whether
4799
+ // the page is one whose unsaved edits Close must ask about through its save state (renderer `asksBeforeClose`).
4800
+ let overlaySurface = { name: 'the editor', asksBeforeClose: false };
4606
4801
  // The regions of #app the overlay covers. Covering them is not enough: Tab from the Close button or the left panel
4607
4802
  // would still reach the header, canvas and footer under it, and Enter there runs or compiles the workflow. Cards
4608
4803
  // drawn above the overlay (#fullscreen-nudge, #ix-ask-menu) are not covered, so they are not listed and stay usable.
@@ -4640,6 +4835,7 @@
4640
4835
  const r = window.CONTRACT_RENDERERS && window.CONTRACT_RENDERERS[type];
4641
4836
  if (!r) return false;
4642
4837
  contractEditorApp = appId;
4838
+ overlaySurface = { name: r.name || 'the editor', asksBeforeClose: !!r.asksBeforeClose };
4643
4839
  overlayModelPanel(!!r.modelPanel);
4644
4840
  coverShell(r.modelPanel ? OVERLAY_COVERS : FULL_WINDOW_COVERS);
4645
4841
  // The editor bakes the .lock on Approve — that control belongs to an editable contract editor, not
@@ -4665,6 +4861,7 @@
4665
4861
  function openLocalViewer(appId, type) {
4666
4862
  const r = window.CONTRACT_RENDERERS && window.CONTRACT_RENDERERS[type];
4667
4863
  if (!r || !r.viewerUrl) return false;
4864
+ overlaySurface = { name: 'the 3D view', asksBeforeClose: false };
4668
4865
  overlayModelPanel(false);
4669
4866
  coverShell(FULL_WINDOW_COVERS);
4670
4867
  const ap = document.getElementById('contract-editor-approve'); if (ap) ap.hidden = true;
@@ -4681,6 +4878,7 @@
4681
4878
  // steel-filter.html (layer/thickness/colour facets + eyedropper). Same seam as the editor: the
4682
4879
  // iframe talks to /api/contract directly and Save writes contract.filter.
4683
4880
  function openFilterView(appId) {
4881
+ overlaySurface = { name: 'the Drawing Filter', asksBeforeClose: false }; // it asks through its own __floGuard
4684
4882
  overlayModelPanel(false);
4685
4883
  coverShell(FULL_WINDOW_COVERS);
4686
4884
  // The filter view has its own Save; the overlay's "Approve & bake lock" (editor-only) would
@@ -4695,19 +4893,78 @@
4695
4893
  $contractEditor.hidden = false;
4696
4894
  return true;
4697
4895
  }
4896
+ // #3143: an editor that autosaves and keeps no copy of its own (the vector editor) exposes contractSaveState() and
4897
+ // flushContract() rather than a __floGuard. An unfinished write is finished first, quietly; whatever is still not
4898
+ // saved after that — a refused write (conflict), a failed one, one still running, or a state that cannot be read —
4899
+ // is asked about, because closing tears the page down and those edits with it. True = close, false = keep it open.
4900
+ const CLOSE_FLUSH_MS = 20000;
4901
+ async function savedOrLetGo(name) {
4902
+ let win = null;
4903
+ try { win = $contractEditorFrame.contentWindow; } catch (_) { win = null; }
4904
+ const read = () => {
4905
+ try { return win && typeof win.contractSaveState === 'function' ? win.contractSaveState() : 'clean'; }
4906
+ catch (_) { return 'unknown'; }
4907
+ };
4908
+ // The wait is capped, the save is not: a save still running at the cap keeps running, and waiting again waits
4909
+ // for THAT save rather than starting another one behind it.
4910
+ let pending = null;
4911
+ const flush = async () => {
4912
+ if (!win || typeof win.flushContract !== 'function') return;
4913
+ if (!pending) {
4914
+ pending = Promise.resolve().then(() => win.flushContract())
4915
+ .catch(() => { /* read() says what is left */ })
4916
+ .finally(() => { pending = null; });
4917
+ }
4918
+ let timer = null;
4919
+ try { await Promise.race([pending, new Promise((resolve) => { timer = setTimeout(resolve, CLOSE_FLUSH_MS); })]); }
4920
+ finally { clearTimeout(timer); }
4921
+ };
4922
+ let state = read();
4923
+ if (state === 'dirty' || state === 'saving') { await flush(); state = read(); }
4924
+ while (state !== 'clean') {
4925
+ const ask = state === 'conflict'
4926
+ ? [`Someone else saved this drawing while you had ${name} open, so your latest changes were not saved. If you close now, they are lost. To keep them, choose Keep editing, then click Save conflict at the top of the editor to pick which version to keep.`,
4927
+ { discard: 'Close without saving', cancel: 'Keep editing', hideSave: true, initialFocus: 'cancel' }]
4928
+ : state === 'unknown'
4929
+ ? [`FloLess couldn’t check whether your changes in ${name} are saved. If you close now, any that are not saved are lost.`,
4930
+ { discard: 'Close anyway', cancel: 'Keep editing', hideSave: true, initialFocus: 'cancel' }]
4931
+ : state === 'saving'
4932
+ ? [`FloLess is still saving your latest changes in ${name}. It is taking longer than usual. If you close now, the save may still finish, or your latest changes may be lost. Wait for the save, or keep editing.`,
4933
+ { confirm: 'Wait for the save', discard: 'Close anyway', cancel: 'Keep editing', initialFocus: 'cancel' }]
4934
+ : [`FloLess couldn’t save your latest changes in ${name}, so they are not saved yet. If you close now, they are lost. Try saving again, or keep editing.`,
4935
+ { confirm: 'Try saving again', discard: 'Close without saving', cancel: 'Keep editing', initialFocus: 'cancel' }];
4936
+ const choice = await confirmUnsavedSwitch('', ask[0], 'Your latest changes aren’t saved', ask[1]);
4937
+ if (choice === 'discard') return true;
4938
+ if (choice !== 'save') return false;
4939
+ state = read(); // the save may have landed while the question was up
4940
+ if (state !== 'clean') { await flush(); state = read(); }
4941
+ }
4942
+ return true;
4943
+ }
4944
+ // One close at a time, from Close and Esc alike (#3143): a second click while the first is still saving or asking
4945
+ // would otherwise run its own close and tear the editor down after the person chose Keep editing.
4946
+ let overlayClosing = false;
4698
4947
  async function closeContractEditor() {
4948
+ if (overlayClosing) return;
4949
+ overlayClosing = true;
4950
+ try { await closeContractEditorOnce(); } finally { overlayClosing = false; }
4951
+ }
4952
+ async function closeContractEditorOnce() {
4699
4953
  // A surface inside the iframe (the steel filter) can expose a same-origin dirty-guard so we show
4700
4954
  // OUR styled confirm modal instead of its native beforeunload "Leave site?" (#170). Cross-origin
4701
4955
  // (about:blank) access throws — treat that as "no guard".
4956
+ const surface = overlaySurface; // each opener sets a new one, so a different editor opened meanwhile is not closed
4957
+ const name = surface.name;
4702
4958
  let guard = null;
4703
4959
  try { guard = $contractEditorFrame.contentWindow && $contractEditorFrame.contentWindow.__floGuard; }
4704
4960
  catch (_) { guard = null; }
4705
4961
  if (guard && typeof guard.isDirty === 'function' && guard.isDirty()) {
4706
- const choice = await confirmUnsavedSwitch('', 'You have unsaved changes to the Drawing Filter. What would you like to do?', 'Unsaved Drawing Filter changes');
4962
+ const choice = await confirmUnsavedSwitch('', `You have unsaved changes in ${name}. What would you like to do?`, `Unsaved changes in ${name}`);
4707
4963
  if (choice === 'cancel') return; // keep the view open
4708
4964
  if (choice === 'save') { const ok = await guard.save(); if (!ok) return; } // save failed → stay open
4709
4965
  else if (choice === 'discard') { try { guard.discard(); } catch (_) {} } // silence the backstop
4710
- }
4966
+ } else if (surface.asksBeforeClose && !(await savedOrLetGo(name))) return; // keep the editor open
4967
+ if (overlaySurface !== surface) return; // the overlay shows something else now; that one closes on its own terms
4711
4968
  $contractEditor.hidden = true;
4712
4969
  overlayModelPanel(false); // the left Model section goes back to the workspace
4713
4970
  // Unhook the focus-on-load first: about:blank loading would otherwise pull focus into the now-hidden frame,
@@ -5269,17 +5526,19 @@
5269
5526
  if (!currentId) return;
5270
5527
  const verb = currentlyFrozen ? 'unfreeze' : 'freeze';
5271
5528
  try {
5272
- await api(`/api/app/${encodeURIComponent(currentId)}/${verb}`, { method: 'POST', body: JSON.stringify({ nodeId }) });
5529
+ const res = await api(`/api/app/${encodeURIComponent(currentId)}/${verb}`, { method: 'POST', body: JSON.stringify({ nodeId }) });
5273
5530
  await loadApp(currentId); // re-read → frozen badge/state repaints
5531
+ // #3132: the workflow had changes nobody approved, so the step changed but the approval did not — say that, not "done".
5532
+ if (res && res.approvalPending && typeof res.notice === 'string') { showToast(res.notice, 'warn'); return; }
5274
5533
  showToast(currentlyFrozen
5275
5534
  ? 'Node unfrozen — it will run normally.'
5276
5535
  : 'Output frozen — this node will replay its last result on the next run.',
5277
5536
  currentlyFrozen ? 'info' : 'ok');
5278
5537
  } catch (e) {
5279
- // Surface the real aware reason the route attached as body.reason — otherwise the friendly
5280
- // lead hides the actual cause. First non-empty line, capped, keeps the warn toast sane.
5538
+ // A reason the route marked diagnostic (AWARE's own output) is for the log and the AI, never
5539
+ // the toast (#3097); any other reason is shown, first non-empty line, capped.
5281
5540
  const lead = (e && e.message) || `Could not ${verb} this node.`;
5282
- const raw = e && e.body && typeof e.body.reason === 'string' ? e.body.reason.trim() : '';
5541
+ const raw = e && e.body && !e.body.diagnostic && typeof e.body.reason === 'string' ? e.body.reason.trim() : '';
5283
5542
  const reason = raw ? (raw.split('\n').find((l) => l.trim()) || '').trim().slice(0, 200) : '';
5284
5543
  showToast(reason ? `${lead} — ${reason}` : lead, 'warn');
5285
5544
  }
@@ -5346,18 +5605,24 @@
5346
5605
  $reportShare.hidden = true; // the frame is blank — only a painted report is shareable
5347
5606
  $reportOverlay.hidden = false;
5348
5607
  let clientRunToken = null;
5349
- if (opts.debug) {
5350
- $reportOverlay.innerHTML = `<div>Launching the .NET debugger for <code>${escapeHtml(nodeId)}</code> — a Windows picker will pop; choose your <strong>Visual Studio</strong> to attach to <code>aware-tekla.exe</code>, then step through. The report renders when you let it finish.</div>`;
5351
- $reportOverlay.prepend(runningFlo());
5352
- } else {
5353
- // #2228: the working Flo, what the run is doing, elapsed time and a real bar when the run reports one —
5354
- // the same view the canvas strip uses, so a long render reads the same in both places.
5608
+ const runAppId = currentId;
5609
+ // #2228: the working Flo, what the run is doing, elapsed time and a real bar when the run reports one —
5610
+ // the same view the canvas strip uses, so a long render reads the same in both places. #3253: a Run anyway resend
5611
+ // is watched as a new attempt with a view of its own; this run then holds that one.
5612
+ const trackOverlay = () => {
5355
5613
  $reportOverlay.replaceChildren();
5356
5614
  const host = mkEl('div', 'rp-host');
5357
5615
  $reportOverlay.append(host); // Stop lives in the report header (#reportStop), beside the run it stops
5358
- clientRunToken = beginLiveRun(currentId, 'overlay', host,
5616
+ clientRunToken = beginLiveRun(runAppId, 'overlay', host,
5359
5617
  approvedModelReport ? 'Reading the selected approved model to make a complete, read-only report…' : 'Running the workflow against the live model…');
5360
5618
  if (!host.firstChild) $reportOverlay.prepend(runningFlo()); // the view could not mount: keep the working Flo
5619
+ return clientRunToken;
5620
+ };
5621
+ if (opts.debug) {
5622
+ $reportOverlay.innerHTML = `<div>Launching the .NET debugger for <code>${escapeHtml(nodeId)}</code> — a Windows picker will pop; choose your <strong>Visual Studio</strong> to attach to <code>aware-tekla.exe</code>, then step through. The report renders when you let it finish.</div>`;
5623
+ $reportOverlay.prepend(runningFlo());
5624
+ } else {
5625
+ trackOverlay();
5361
5626
  }
5362
5627
  let liveOutcome = 'failed';
5363
5628
  const $reportWatch = document.getElementById('report-watch');
@@ -5370,10 +5635,12 @@
5370
5635
  // so VS attaches to aware-tekla.exe; a normal run goes through aware app run.
5371
5636
  const res = opts.debug
5372
5637
  ? await api('/api/debug-node', { method: 'POST', body: JSON.stringify({ id: currentId, nodeId, inputs }) })
5373
- : await dispatchManualRun(request, { id: app.id, simulate: false, inputs, ...(clientRunToken ? { clientRunToken } : {}) });
5638
+ : await dispatchManualRun(request, { id: app.id, simulate: false, inputs, ...(clientRunToken ? { clientRunToken } : {}) }, trackOverlay);
5374
5639
  liveOutcome = 'ok';
5375
5640
  const reportVideos = runVideos(res);
5376
5641
  if (res && typeof res.mediaWarning === 'string') showToast(res.mediaWarning, 'warn');
5642
+ // #3228: a step that works with FloLess was turned away (another FloLess replaced the connection): say so in plain words.
5643
+ if (res && typeof res.connectionWarning === 'string') showToast(res.connectionWarning, 'warn');
5377
5644
  if ($reportWatch && reportVideos.length) {
5378
5645
  $reportWatch.hidden = false;
5379
5646
  $reportWatch.onclick = () => watchRunVideos(reportVideos, `Rendered by ${app.displayName}`);
@@ -5403,13 +5670,15 @@
5403
5670
  $reportSub.innerHTML = `Live 3D view from <code>${escapeHtml(nodeId)}</code>${inputBadge ? ' · ' + escapeHtml(inputBadge) : ''} — drag to orbit, scroll to zoom, click an element to inspect.`;
5404
5671
  }
5405
5672
  const withFiles = !!(res.report && res.report.withFiles);
5406
- paintReport(html, interactive, { withFiles, runId: typeof res.runId === 'string' ? res.runId : null });
5407
- if (!interactive) $reportSub.textContent = 'Report created from the latest workflow run.';
5673
+ // #3229: the run stopped at an AI step's check after this report was made; the viewer says so above it.
5674
+ const aiStop = globalThis.flolessAgentSteps?.stoppedRunView?.(res) ?? null;
5675
+ paintReport(html, interactive, { withFiles, runId: typeof res.runId === 'string' ? res.runId : null, aiStop });
5676
+ if (!interactive) $reportSub.textContent = aiStop ? 'Report created before the run stopped.' : 'Report created from the latest workflow run.';
5408
5677
  // If a node wrote an output file, the run reports its path — surface the
5409
5678
  // ⧉ Open file / ▤ Reveal buttons and cache it so a later double-click restores them (#209).
5410
5679
  const savedPath = res && typeof res.savedPath === 'string' ? res.savedPath : '';
5411
5680
  showSavedPathActions(savedPath);
5412
- lastReportByApp.set(currentId, { nodeId, label: inputBadge, html, interactive, savedPath, withFiles, runId: typeof res.runId === 'string' ? res.runId : null });
5681
+ lastReportByApp.set(currentId, { nodeId, label: inputBadge, html, interactive, savedPath, withFiles, runId: typeof res.runId === 'string' ? res.runId : null, aiStop });
5413
5682
  paintReportPageLinks();
5414
5683
  $reportModal.dataset.html = '1';
5415
5684
  reportReadyNote(app, nodeId);
@@ -5436,6 +5705,8 @@
5436
5705
  // in the viewer overlay + a toast. No console.error — the server returns the
5437
5706
  // failure in-band, so a failed run isn't a console-worthy fault.
5438
5707
  $reportSub.textContent = 'Execution ended without a report.';
5708
+ // #3228: one of its steps could not connect to FloLess; this says why, beside the failure.
5709
+ if (e.body && typeof e.body.connectionWarning === 'string') showToast(e.body.connectionWarning, 'warn');
5439
5710
  // #2796: Try again only once the server has answered that this run ended. With no answer the run may still be
5440
5711
  // going on the host, and a second one could do its work twice.
5441
5712
  showRunFailure(e.body || {}, runFailureMessage(msg), app, opts.debug || liveOutcome === 'no-answer' ? null : () => runReport(nodeId));
@@ -5443,7 +5714,7 @@
5443
5714
  }
5444
5715
  } finally {
5445
5716
  if (request) finishManualRun(request);
5446
- if (clientRunToken) { if (liveOutcome === 'no-answer') settleLiveRunWithoutAnswer(); else finishLiveRun(liveOutcome); }
5717
+ finishOwnLiveRun(clientRunToken, liveOutcome);
5447
5718
  reportRunning = false;
5448
5719
  syncRunControls(); // run ended — hide the header Stop, restore Run from the gate
5449
5720
  paintReportPageLinks(); // #2539: hidden while the run was in flight; its Page version may already be known
@@ -5553,6 +5824,29 @@
5553
5824
  $reportOverlay.innerHTML = `<div>Run completed but <code>${escapeHtml(nodeId)}</code> returned no <code>html</code>. Check the Execution tab.</div>`;
5554
5825
  }
5555
5826
 
5827
+ // #3229: the report shown was made before the run stopped at an AI step's check (`view` from flolessAgentSteps.stoppedRunView),
5828
+ // or null to hide the banner. Above the frame, never over it, and not dismissible: it goes with the next run or report.
5829
+ // textContent only — the step id comes from the run.
5830
+ function paintAiStopBanner(view) {
5831
+ const banner = document.getElementById('report-ai-stop');
5832
+ if (!banner) return;
5833
+ banner.replaceChildren();
5834
+ banner.hidden = !view;
5835
+ if (!view) return;
5836
+ const appId = currentId;
5837
+ const open = mkEl('button', 'ghost report-ai-stop-open', view.button);
5838
+ open.type = 'button';
5839
+ open.dataset.commandId = view.commandId;
5840
+ open.onclick = async () => {
5841
+ let shown = false;
5842
+ try { shown = await globalThis.flolessAgentSteps?.openQuestions(appId, view.runId, () => hideModal($reportModal)) === true; } catch { shown = false; }
5843
+ if (shown) return;
5844
+ showToast('FloLess couldn’t show this run in Last run yet. Close the viewer, then open Last run above the canvas.', 'warn');
5845
+ open.focus();
5846
+ };
5847
+ banner.append(mkEl('span', 'report-ai-stop-status', 'Needs you'), mkEl('span', 'report-ai-stop-text', view.banner), open);
5848
+ }
5849
+
5556
5850
  // #2415: the run stopped before the report because an AI step did not answer. Not a fault, so no Report this problem:
5557
5851
  // the way on is the step's questions, in the canvas's Last run panel. textContent only — step names come from the run.
5558
5852
  function showAiStepStopped(view, appId) {
@@ -5699,6 +5993,15 @@
5699
5993
  $dont.textContent = (actionLabels && actionLabels.discard) || 'Don’t save';
5700
5994
  $cancel.textContent = (actionLabels && actionLabels.cancel) || 'Cancel';
5701
5995
  $dont.hidden = !!(actionLabels && actionLabels.hideDiscard);
5996
+ $save.hidden = !!(actionLabels && actionLabels.hideSave); // when there is nothing safe to save (a refused write)
5997
+ // A caller that gives the buttons another meaning names it, so Instructor explains what they do here.
5998
+ const ownIds = [$save, $dont, $cancel].map((b) => b.getAttribute('data-command-id'));
5999
+ const ids = actionLabels && actionLabels.commandIds;
6000
+ if (ids) {
6001
+ if (ids.confirm) $save.setAttribute('data-command-id', ids.confirm);
6002
+ if (ids.discard) $dont.setAttribute('data-command-id', ids.discard);
6003
+ if (ids.cancel) $cancel.setAttribute('data-command-id', ids.cancel);
6004
+ }
5702
6005
  $title.textContent = titleMsg || 'Unsaved input changes'; // reset each call (default = the inputs-switch copy)
5703
6006
  $sub.textContent = subMsg || `You changed the inputs for “${appName}” but haven’t saved them yet. What would you like to do?`;
5704
6007
  showModal($confirmModal);
@@ -5716,6 +6019,8 @@
5716
6019
  else modal.setAttribute('aria-hidden', ariaHidden);
5717
6020
  });
5718
6021
  $dont.hidden = false;
6022
+ $save.hidden = false;
6023
+ [$save, $dont, $cancel].forEach((b, i) => { if (ownIds[i] !== null) b.setAttribute('data-command-id', ownIds[i]); });
5719
6024
  document.removeEventListener('keydown', onKey, true);
5720
6025
  $save.onclick = $dont.onclick = $cancel.onclick = $confirmModal.onclick = null;
5721
6026
  if (returnFocus && returnFocus.isConnected && !returnFocus.matches(':disabled,[aria-disabled="true"]')) returnFocus.focus();
@@ -6637,7 +6942,7 @@
6637
6942
  try {
6638
6943
  await api(endpoint, { method: 'POST', body: JSON.stringify({ path: currentSavedPath }) });
6639
6944
  } catch (e) {
6640
- const detail = e && e.body && e.body.error;
6945
+ const detail = personText(e && e.body);
6641
6946
  showToast(detail ? `${failMsg} — ${detail}` : failMsg, 'warn');
6642
6947
  }
6643
6948
  }
@@ -6675,7 +6980,7 @@
6675
6980
  // #2539: a busy report is waited for here too, saying why, and the object opens by itself.
6676
6981
  if (error?.body?.code !== 'report-busy' || Date.now() >= waitUntil) throw error;
6677
6982
  if (stale()) { leave(); return; } // a busy answer for a lookup already replaced writes nothing
6678
- $reportObjectError.textContent = String(error.body.error || 'This report is busy. It opens as soon as that finishes.');
6983
+ $reportObjectError.textContent = personText(error.body) || 'This report is busy. It opens as soon as that finishes.';
6679
6984
  $reportObjectError.hidden = false;
6680
6985
  await new Promise((resolve) => setTimeout(resolve, Math.min(10_000, Math.max(500, Number(error.body.retryAfterMs) || 2_000))));
6681
6986
  if (stale()) { leave(); return; }
@@ -6689,7 +6994,7 @@
6689
6994
  if (stale()) { leave(); return; }
6690
6995
  $reportObjectError.textContent = error?.body?.code === 'report-busy'
6691
6996
  ? 'This report is still busy. Choose Go again to open that object.'
6692
- : error?.message || 'Could not find that object. Try again.';
6997
+ : errorText(error, { action: 'find that object', retrySafe: true });
6693
6998
  $reportObjectError.hidden = false;
6694
6999
  }
6695
7000
  };
@@ -6728,17 +7033,18 @@
6728
7033
  // #2539: busy is not a failure of access; the report is there, it is just being read.
6729
7034
  showToast(error?.body?.code === 'report-busy'
6730
7035
  ? 'This report is busy, so it can’t be downloaded yet. Choose Download complete report again in a moment.'
6731
- : error?.message || 'Report access could not be confirmed. Try again.', 'warn');
7036
+ : errorText(error, { action: 'download the complete report', retrySafe: true }), 'warn');
6732
7037
  }
6733
7038
  };
6734
7039
 
6735
7040
  $reportOpen.onclick = () => {
6736
7041
  const html = lastPaintedHtml || $reportFrame.srcdoc;
6737
7042
  if (!html) return;
6738
- // Open via a blob: URL — an opaque origin, so the report can't script the
6739
- // app origin (mirrors the iframe's sandbox intent).
6740
- const url = URL.createObjectURL(new Blob([html], { type: 'text/html' }));
6741
- window.open(url, '_blank');
7043
+ // #3130: a blob: URL has THIS page's origin, so the report is never the blob itself — it would run as FloLess. The blob
7044
+ // is a script-free page holding the report in a sandboxed, opaque-origin frame (web/report-csp.js).
7045
+ const doc = window.FlolessReportCsp.openDocument(html, lastPaintedInteractive, apps.get(currentId)?.displayName);
7046
+ const url = URL.createObjectURL(new Blob([doc], { type: 'text/html' }));
7047
+ window.open(url, '_blank', 'noopener');
6742
7048
  setTimeout(() => URL.revokeObjectURL(url), 30000);
6743
7049
  };
6744
7050
 
@@ -6757,7 +7063,7 @@
6757
7063
  try {
6758
7064
  // The report stays open until the Page is known to open (beforeShow); a Page that cannot be opened says why and leaves it.
6759
7065
  await window.flolessPages.open(page.home, page.pageId, page.version, { share: true, beforeShow: () => closeReportViewer() });
6760
- } catch (e) { showToast(`FloLess couldn’t open the workflow’s Page to share it. ${e && e.message ? e.message : ''}`.trim(), 'warn'); }
7066
+ } catch (e) { showToast(errorText(e, { action: 'open the workflow’s Page to share it', retrySafe: true }), 'warn'); }
6761
7067
  return;
6762
7068
  }
6763
7069
  // Share exactly what's on screen — the HTML we painted — so the link can never carry a different
@@ -6906,9 +7212,18 @@
6906
7212
  if (currentId !== newId) { showToast(`${name} is compiled.`, 'ok'); return; } // a newer choice won while it was opening
6907
7213
  const app = apps.get(newId);
6908
7214
  const consent = globalThis.flolessAgentSteps?.consentStatus ? await globalThis.flolessAgentSteps.consentStatus(newId) : null;
7215
+ // #3284: the answer is about this version's confirmation, so it is never said over another workflow opened while it was read.
7216
+ if (currentId !== newId) { showToast(`${name} is compiled.`, 'ok'); return; }
6909
7217
  const unconfirmed = consent && (consent.state === 'needed' || consent.state === 'changed');
6910
7218
  if (unconfirmed) {
6911
7219
  showToast('Workflow compiled. Confirm its AI step before it runs.', 'ok');
7220
+ } else if (app?.runnable && consent?.state === 'current' && consent.latest?.onOtherVersion) {
7221
+ // #3284: not asked, because the step is what the person ticked; the new version's write warning is still theirs to see.
7222
+ const kept = (consent.steps?.length ?? 1) > 1
7223
+ ? 'Workflow compiled. The AI steps are unchanged, so the earlier confirmation that their answers may differ each run still stands.'
7224
+ : 'Workflow compiled. The AI step is unchanged, so the earlier confirmation that its answer may differ each run still stands.';
7225
+ if (consent.carriedWarning) standingToast('compile', `${kept} ${consent.carriedWarning}`, 'warn');
7226
+ else { standingToast('compile'); showToast(kept, 'ok'); }
6912
7227
  } else {
6913
7228
  compiledToast(app);
6914
7229
  }
@@ -7036,6 +7351,7 @@
7036
7351
  document.getElementById('bake-cancel').onclick = () => hideModal($bakeModal);
7037
7352
  document.getElementById('bake-confirm').onclick = () => runBake();
7038
7353
  onBackdropDismiss($bakeModal, () => hideModal($bakeModal), () => !document.getElementById('bake-confirm').disabled);
7354
+ onEscapeDismiss($bakeModal, () => hideModal($bakeModal), () => !document.getElementById('bake-cancel').disabled);
7039
7355
 
7040
7356
  // ── Graft into agent ────────────────────────────────────────────────────────
7041
7357
  // Build an agent from a foreign tool (DLL / C# source / NuGet / OpenAPI / …).
@@ -7655,9 +7971,8 @@
7655
7971
  await window.flolessChat.openVerifiedTeklaDraft(receipt);
7656
7972
  } catch (e) {
7657
7973
  console.warn('Continue in AI Chat failed', e);
7658
- showToast(e?.plainEnglish && e.message
7659
- ? e.message
7660
- : 'FloLess could not open AI Chat. Open a project or workflow, then verify the model read again.', 'warn');
7974
+ // AI Chat's own refusals are marked forPerson (chat.js); anything else gets the shared sentence (#3097 errorText).
7975
+ showToast(errorText(e, { action: 'open AI Chat', unsure: 'Open a project or workflow, then verify the model read again.' }), 'warn');
7661
7976
  return;
7662
7977
  }
7663
7978
  closeGraftModal();
@@ -8155,8 +8470,9 @@
8155
8470
  }
8156
8471
  // A file FloLess could not read is a 400. The Workspace refusing to keep it (no Workspace folder, a folder it
8157
8472
  // cannot write) is labelled by the server, whose sentence names why. Anything else is unconfirmed: it may have been kept.
8158
- showToast(body && body.stage === 'workspace' && typeof body.error === 'string' && body.error
8159
- ? `We couldn’t save that workflow to your Workspace: ${body.error.replace(/[.\s]+$/, '')}. Try again.`
8473
+ const workspaceSaid = body && body.stage === 'workspace' ? personText(body) : '';
8474
+ showToast(workspaceSaid
8475
+ ? `We couldn’t save that workflow to your Workspace: ${workspaceSaid.replace(/[.\s]+$/, '')}. Try again.`
8160
8476
  // Only a 400 is a verdict on the file; a lost response (no status) may follow a kept draft.
8161
8477
  : e && e.status === 400
8162
8478
  ? 'We couldn’t import that workflow because FloLess could not read it. Check the file, then try again.'
@@ -8628,12 +8944,16 @@
8628
8944
  }
8629
8945
  if (!r.ok || !d.ok) throw new Error(d.error || 'update failed');
8630
8946
  // Success: the server is exiting + Update.exe relaunches the new build. The health
8631
- // poll flips to offline (R1 overlay), then the new version reconnects on its own.
8947
+ // poll flips to offline, and the card says FloLess is updating (not that it stopped
8948
+ // responding); then the new version reconnects on its own.
8949
+ markAppUpdateRelaunch(v);
8632
8950
  // Recovery guard: if the relaunch never happens and this page stays alive (e.g. a UAC
8633
8951
  // prompt was declined after the server already responded), re-enable the pill after 90 s
8634
8952
  // so the user can retry — the page won't go offline in that case.
8635
8953
  _appUpdateRecoveryTimer = setTimeout(() => {
8636
8954
  _appUpdateRecoveryTimer = null;
8955
+ // FloLess never went away for the update: a later outage is not this update.
8956
+ if (serverState !== 'updating') clearAppUpdateRelaunch();
8637
8957
  if ($appUpdate && $appUpdate.disabled) {
8638
8958
  $appUpdate.disabled = false;
8639
8959
  _updateApplying = null; // relaunch never happened — release the lock so retry works
@@ -8643,6 +8963,7 @@
8643
8963
  }
8644
8964
  }, 90_000);
8645
8965
  } catch (e) {
8966
+ clearAppUpdateRelaunch();
8646
8967
  $appUpdate.disabled = false;
8647
8968
  _updateApplying = null;
8648
8969
  try { localStorage.removeItem('floless.whatsNew.pending'); } catch { /* private mode */ }
@@ -8838,7 +9159,7 @@
8838
9159
  async function runWfUpdate(u, opts = {}) {
8839
9160
  const prior = _wfRowState.get(u.id);
8840
9161
  if (prior && (prior.state === 'busy' || prior.state === 'undoing')) return false;
8841
- _wfRowState.set(u.id, { state: 'busy', offer: u });
9162
+ _wfRowState.set(u.id, { state: 'busy', offer: u, since: Date.now() });
8842
9163
  wfRowsChanged();
8843
9164
  try {
8844
9165
  const r = await fetch(`/api/workflows/${encodeURIComponent(u.id)}/update`, { method: 'POST', headers: { 'content-type': 'application/json' },
@@ -8911,7 +9232,7 @@
8911
9232
  : opts.recovery ? wfRecoveryOf(id) : s;
8912
9233
  if (!handle || !handle.backupPath || s.state === 'undoing' || s.state === 'busy') return;
8913
9234
  const putBack = (patch = {}) => { _wfRowState.set(id, { ...s, ...patch }); if (s.state === 'idle' && !Object.keys(patch).length) _wfRowState.delete(id); };
8914
- _wfRowState.set(id, { ...s, state: 'undoing' });
9235
+ _wfRowState.set(id, { ...s, state: 'undoing', since: Date.now() });
8915
9236
  wfRowsChanged();
8916
9237
  try {
8917
9238
  const r = await fetch(`/api/workflows/${encodeURIComponent(id)}/undo-update`, { method: 'POST', headers: { 'content-type': 'application/json' },
@@ -8923,6 +9244,8 @@
8923
9244
  const later = d.replacedLater && d.backupPath ? { backupPath: d.backupPath, sourceHash: d.sourceHash } : null;
8924
9245
  if (later) wfRecoverySet(id, later.backupPath, later);
8925
9246
  _wfRowState.set(id, { state: 'undone', offer: s.offer, version: d.version });
9247
+ // Paint it now: the refresh below may fail, and the dialog must not keep Not now waiting on a finished Undo (#3147).
9248
+ wfRowsChanged();
8926
9249
  const text = `Put “${wfUpdateLabel(id)}” back to ${d.version}.`
8927
9250
  + (d.replacedLater ? ' The changes made after the update are in a backup.' : '')
8928
9251
  + (d.knowledgePinNotRestored ? ' Its pinned knowledge was not brought back: pin it again in Knowledge if it needs it.' : '');
@@ -9023,8 +9346,11 @@
9023
9346
  const line = document.createElement('span');
9024
9347
  line.className = 'tool-updates-needs-sentence';
9025
9348
  const changed = wfRowChanged(s, u);
9026
- if (s.state === 'busy') line.textContent = 'Updating… a backup is saved first.';
9027
- else if (s.state === 'undoing') line.textContent = 'Putting your previous version back…';
9349
+ // In the header dialog the row also says why Not now waits, or that it no longer has to (#3147).
9350
+ const waits = !opts.textOnly ? '' : wfWaitedLong(s) ? ' This is taking longer than usual. You can close this; it still finishes.'
9351
+ : ' You can close this when it finishes.';
9352
+ if (s.state === 'busy') line.textContent = 'Updating… a backup is saved first.' + waits;
9353
+ else if (s.state === 'undoing') line.textContent = 'Putting your previous version back…' + waits;
9028
9354
  else if (s.state === 'done') line.textContent = s.laterChanges ? WF_LATER_CHANGES : 'Updated and ready to run. Your previous version is saved.';
9029
9355
  else if (recovery?.laterChanges) line.textContent = WF_LATER_CHANGES;
9030
9356
  else if (s.state === 'undone') line.textContent = recovery ? 'Your previous version is back. The changes made after the update are in a backup.' : 'Your previous version is back.';
@@ -9116,8 +9442,30 @@
9116
9442
  if (cancel) {
9117
9443
  cancel.textContent = s.state === 'done' ? 'Close' : 'Not now';
9118
9444
  cancel.hidden = s.state === 'undone'; // Done is the only thing left to do
9445
+ // #3147: closing mid-update would hide work still running, then a toast and a reload would land from nowhere.
9446
+ cancel.disabled = wfModalWorking();
9447
+ if (cancel.disabled) cancel.setAttribute('data-blocked-reason', s.state === 'busy' ? 'Still updating. You can close this when it finishes.'
9448
+ : 'Still putting your previous version back. You can close this when it finishes.');
9449
+ else cancel.removeAttribute('data-blocked-reason');
9450
+ // A run that never answers must not hold the dialog open: repaint when the wait is up, and Not now comes back.
9451
+ clearTimeout(_wfModalWaitTimer);
9452
+ if (cancel.disabled) {
9453
+ _wfModalWaitTimer = setTimeout(paintWfUpdateModal, WF_MODAL_WAIT_MS - (Date.now() - s.since) + 50);
9454
+ _wfModalWaitTimer?.unref?.();
9455
+ }
9119
9456
  }
9120
9457
  }
9458
+ const WF_MODAL_WAIT_MS = 30000;
9459
+ let _wfModalWaitTimer = null;
9460
+ /** An update or Undo still running after the wait: the dialog may close, and says the work goes on (#3147). */
9461
+ function wfWaitedLong(s) {
9462
+ return (s.state === 'busy' || s.state === 'undoing') && Date.now() - (s.since || 0) >= WF_MODAL_WAIT_MS;
9463
+ }
9464
+ /** The dialog's update or Undo is running: Not now, Escape and the backdrop wait for it, up to the wait (#3147). */
9465
+ function wfModalWorking() {
9466
+ const s = _wfModalOffer && _wfRowState.get(_wfModalOffer.id);
9467
+ return !!s && (s.state === 'busy' || s.state === 'undoing') && !wfWaitedLong(s);
9468
+ }
9121
9469
  function openWfUpdateModal(u) {
9122
9470
  if (!$wfUpdateModal) return;
9123
9471
  // Confirm exactly the offer displayed here, even if background polling replaces the live list.
@@ -9148,7 +9496,10 @@
9148
9496
  const $cancel = document.getElementById('wf-update-cancel'); if ($cancel) $cancel.onclick = dismissWfUpdateModal;
9149
9497
  const $ok = document.getElementById('wf-update-ok'); if ($ok) $ok.onclick = onWfUpdateOk;
9150
9498
  const $ai = document.getElementById('wf-update-ai'); if ($ai) $ai.onclick = () => { if (_wfModalOffer) openKeepMyChanges(_wfModalOffer); };
9151
- if ($wfUpdateModal) onBackdropDismiss($wfUpdateModal, dismissWfUpdateModal);
9499
+ if ($wfUpdateModal) {
9500
+ onBackdropDismiss($wfUpdateModal, dismissWfUpdateModal, () => !wfModalWorking());
9501
+ onEscapeDismiss($wfUpdateModal, dismissWfUpdateModal, () => !wfModalWorking());
9502
+ }
9152
9503
  }
9153
9504
 
9154
9505
  // The poll deliberately does NOT start here. Module init runs before the boot sequence, so the
@@ -10098,11 +10449,13 @@
10098
10449
  liveTrace.length = 0;
10099
10450
  state.hasRun = true;
10100
10451
  // #2228: a simulated run stubs every node, so it reports no progress; a real one is watched live.
10101
- const clientRunToken = simulate ? null : beginLiveRun(currentId, 'strip');
10452
+ let clientRunToken = simulate ? null : beginLiveRun(currentId, 'strip');
10102
10453
  let liveOutcome = 'failed';
10103
10454
  try {
10104
10455
  const runAppId = currentId;
10105
- const res = await dispatchManualRun(request, { id: app.id, simulate, inputs: currentInputs(), ...(clientRunToken ? { clientRunToken } : {}) });
10456
+ // #3253: a Run anyway resend is watched as a new attempt; this run then holds that one.
10457
+ const retrack = () => (clientRunToken = beginLiveRun(runAppId, 'strip'));
10458
+ const res = await dispatchManualRun(request, { id: app.id, simulate, inputs: currentInputs(), ...(clientRunToken ? { clientRunToken } : {}) }, retrack);
10106
10459
  liveOutcome = 'ok';
10107
10460
  const videos = runVideos(res);
10108
10461
  if (videos.length) { finishLiveRun('ok'); offerRunVideos(runAppId, videos); }
@@ -10110,11 +10463,20 @@
10110
10463
  if (res && typeof res.mediaWarning === 'string') showToast(res.mediaWarning, 'warn');
10111
10464
  // SSE usually fills liveTrace first; backfill from the response if it didn't.
10112
10465
  if (liveTrace.length === 0 && Array.isArray(res.events)) res.events.forEach(pushTrace);
10113
- // A "succeeded" run carrying a rejected token → prompt reconnect, not a result.
10114
- if (res.credentialIssue) { surfaceCredentialIssue(res.credentialIssue); return; }
10466
+ // A "succeeded" run carrying a rejected token → prompt reconnect, not a result. #3228: a step that could not connect
10467
+ // to FloLess is still said, so the step that did not run is never left unmentioned behind the reconnect prompt.
10468
+ if (res.credentialIssue) {
10469
+ if (typeof res.connectionWarning === 'string') showToast(res.connectionWarning, 'warn');
10470
+ surfaceCredentialIssue(res.credentialIssue); return;
10471
+ }
10115
10472
  switchToExecution();
10116
10473
  const steps = liveTrace.filter((r) => r.kind === 'node-start').length;
10117
- standingToast('run', simulate ? `Simulated run complete · ${steps} node${steps === 1 ? '' : 's'} stubbed. See the Execution tab.`
10474
+ // #3228: a run can end with a step that works with FloLess turned away; "Run complete" would hide that it did not run.
10475
+ // #3229: a run its AI step's check stopped ended "ok"; the toast says where it stopped, never "Run complete".
10476
+ const aiStop = !simulate ? globalThis.flolessAgentSteps?.stoppedRunView?.(res) ?? null : null;
10477
+ if (res && typeof res.connectionWarning === 'string') standingToast('run', res.connectionWarning, 'warn', false);
10478
+ else if (aiStop) standingToast('run', aiStop.toast, 'warn'); // stays up: it may be the only sign the run did not finish
10479
+ else standingToast('run', simulate ? `Simulated run complete · ${steps} node${steps === 1 ? '' : 's'} stubbed. See the Execution tab.`
10118
10480
  : `Run complete · ${steps} node${steps === 1 ? '' : 's'}. See the Execution tab.`, 'ok', false);
10119
10481
  } catch (e) {
10120
10482
  liveOutcome = (e && e.body && e.body.cancelled) ? 'stopped'
@@ -10130,7 +10492,8 @@
10130
10492
  } else {
10131
10493
  const cred = e.body && e.body.credentialIssue;
10132
10494
  if (cred) {
10133
- // A rejected token — prompt reconnect for that integration, not the host hint.
10495
+ // A rejected token — prompt reconnect for that integration, not the host hint (#3228: and say the FloLess step too).
10496
+ if (e.body && typeof e.body.connectionWarning === 'string') showToast(e.body.connectionWarning, 'warn');
10134
10497
  surfaceCredentialIssue(cred);
10135
10498
  } else {
10136
10499
  // A failed run is an expected, recoverable outcome (the server returns it
@@ -10144,14 +10507,16 @@
10144
10507
  if (e && e.body && (e.body.refusal || notRun)) clearNodeStatus();
10145
10508
  // A not-run answer is already a whole sentence ("…, so it didn’t run. …"); "Run failed:" would misstate it.
10146
10509
  // Nothing failed — it was declined with a reason — so the toast is informational, not a warning.
10147
- standingToast('run', notRun ? runFailureMessage(msg)
10510
+ // #3228: the failure was a step that could not connect to FloLess: that sentence says what happened and what to do.
10511
+ const connection = e && e.body && typeof e.body.connectionWarning === 'string' ? e.body.connectionWarning : null;
10512
+ standingToast('run', connection ?? (notRun ? runFailureMessage(msg)
10148
10513
  : simulate ? `Simulate failed: ${runFailureMessage(msg).replace(/([^.!?])$/, '$1.')} Simulate can’t check code steps, so ▶ Run workflow is the real test.`
10149
- : 'Run failed: ' + runFailureMessage(msg), notRun ? 'info' : 'warn');
10514
+ : 'Run failed: ' + runFailureMessage(msg)), notRun && !connection ? 'info' : 'warn');
10150
10515
  }
10151
10516
  }
10152
10517
  } finally {
10153
10518
  finishManualRun(request);
10154
- if (clientRunToken) { if (liveOutcome === 'no-answer') settleLiveRunWithoutAnswer(); else finishLiveRun(liveOutcome); }
10519
+ finishOwnLiveRun(clientRunToken, liveOutcome);
10155
10520
  state.running = false;
10156
10521
  runningSimulation = false;
10157
10522
  $runBtn.disabled = false;
@@ -10295,6 +10660,20 @@
10295
10660
  let serverOnline = null;
10296
10661
  // SSE is newer evidence than a health probe already in flight. Fence all effects of that probe.
10297
10662
  let serverObservationEpoch = 0;
10663
+ // What the card says while FloLess is not answering (2026-11-06). A health check that goes unanswered while the
10664
+ // /api/events stream is still open means the FloLess process is alive but busy: a process that exits closes that
10665
+ // connection, and the stream's error moves the card to 'reconnecting' at once. That is weak evidence (a stuck process
10666
+ // keeps its connection open too), so the busy copy only says FloLess may be busy, and offers a refresh after
10667
+ // BUSY_ESCALATE_MS.
10668
+ // 'updating' is an update the person started, which closes FloLess and opens the new version.
10669
+ let serverState = null; // 'online' | 'busy' | 'reconnecting' | 'updating'
10670
+ let eventStreamOpen = false;
10671
+ let appUpdateRelaunch = null; // { version, until } while an update the person started relaunches FloLess
10672
+ let appUpdateRelaunchTimer = null;
10673
+ const BUSY_ESCALATE_MS = 120000; // offer a refresh (it stops nothing)
10674
+ const BUSY_STUCK_MS = 600000; // only then suggest closing FloLess, which stops what it was doing
10675
+ const APP_UPDATE_RELAUNCH_MS = 90000; // how long the card says 'updating' before offering Refresh/Start; matches applyAppUpdate's 90 s recovery guard (a separate literal: keep in step)
10676
+ const APP_UPDATE_RELAUNCH_MAX_MS = 600000; // past this an outage is an ordinary one, whatever was started before
10298
10677
 
10299
10678
  // The overlay leads with AUTO-RECOVERY. The login watchdog (FlolessApp --supervise)
10300
10679
  // respawns a dead server within seconds, so a crash heals itself with NO user action
@@ -10307,6 +10686,8 @@
10307
10686
  // reliable fallback when the watchdog itself is down is "reopen FloLess", which the
10308
10687
  // escalation line offers. The link is a real <a href> the USER clicks — a synthetic
10309
10688
  // anchor.click() is silently dropped by Chromium for external protocols.
10689
+ // Since 2026-11-06 the card also says 'Waiting for FloLess…' (busy: Start is never offered, FloLess is running) and
10690
+ // 'Updating FloLess…' (Start after APP_UPDATE_RELAUNCH_MS); SERVER_STATE_ESCALATIONS holds each state's timing.
10310
10691
  const ESCALATE_MS = 15000; // 3 missed 5s health polls ⇒ the watchdog isn't recovering
10311
10692
  let escalateTimer = null;
10312
10693
  let lastFocusBeforeOverlay = null;
@@ -10333,18 +10714,86 @@
10333
10714
  const next = at < 0 ? (event.shiftKey ? actions.length - 1 : 0) : (at + (event.shiftKey ? actions.length - 1 : 1)) % actions.length;
10334
10715
  actions[next].focus();
10335
10716
  }
10336
- function showOfflineOverlay() {
10337
- if (offlineOverlayEl) return;
10717
+ /** The card's words for one state; `footer` is the status bar label. Never claims more than the window can see. */
10718
+ function serverStateCopy(state) {
10719
+ const desktop = document.documentElement.classList.contains('desktop');
10720
+ const view = desktop ? 'This window' : 'This tab';
10721
+ if (state === 'busy') {
10722
+ return { title: 'Waiting for FloLess…', footer: 'waiting for FloLess',
10723
+ body: `FloLess is still running but hasn’t answered for a while. It may be busy with something large, for example approving a big model. ${view} carries on by itself as soon as FloLess answers.` };
10724
+ }
10725
+ if (state === 'updating') {
10726
+ const what = appUpdateRelaunch?.version ? `version ${appUpdateRelaunch.version}` : 'an update';
10727
+ return { title: 'Updating FloLess…', footer: 'updating FloLess',
10728
+ body: `FloLess is installing ${what} and will open again by itself. Please keep ${view.toLowerCase()} open. It reconnects when FloLess is back.` };
10729
+ }
10730
+ return { title: 'Reconnecting to FloLess…', footer: 'server offline',
10731
+ body: `FloLess isn’t responding. ${desktop ? 'FloLess' : 'This tab'} will keep trying to reconnect.` };
10732
+ }
10733
+ /** What the card says once a state has lasted a while, and which choices it then offers. */
10734
+ const SERVER_STATE_ESCALATIONS = {
10735
+ reconnecting: [{ after: ESCALATE_MS, refresh: true, start: true,
10736
+ text: 'This is taking longer than usual. You can refresh this page, or start FloLess if it is closed.' }],
10737
+ // FloLess is running, so never "Start". Refreshing is offered first because it stops nothing; quitting is advised only
10738
+ // much later, because it does stop what FloLess is doing (a large approval can take several minutes).
10739
+ busy: [
10740
+ { after: BUSY_ESCALATE_MS, refresh: true, start: false,
10741
+ text: 'Still waiting. Large jobs can take several minutes. Refreshing this page does not stop FloLess.' },
10742
+ { after: BUSY_STUCK_MS, refresh: true, start: false,
10743
+ text: `FloLess has not answered for ${BUSY_STUCK_MS / 60000} minutes. If nothing changes, close FloLess and open it again. Anything it was working on will stop.` },
10744
+ ],
10745
+ // The old FloLess has closed by now, so starting it is a real choice if the new one does not open by itself.
10746
+ updating: [{ after: APP_UPDATE_RELAUNCH_MS, refresh: true, start: true,
10747
+ text: 'This is taking longer than usual. Updates can take a few minutes. If FloLess does not open by itself, start it from the Start menu or desktop shortcut.' }],
10748
+ };
10749
+ /** Say `state` on the card: its words, which choices show, and when it escalates. Restarts the escalation on every
10750
+ * call; setServerStatus calls it only when the state changes, so repeats of one state never restart it. */
10751
+ function applyOverlayState(state) {
10752
+ if (!offlineOverlayEl) return;
10753
+ const copy = serverStateCopy(state);
10754
+ offlineOverlayEl.querySelector('h1').textContent = copy.title;
10755
+ offlineOverlayEl.querySelector('.so-body').textContent = copy.body;
10756
+ const card = offlineOverlayEl.querySelector('.so-card');
10757
+ const focusedChoice = offlineOverlayEl.contains(document.activeElement) && document.activeElement !== card;
10758
+ const show = (step) => {
10759
+ const status = document.getElementById('so-status');
10760
+ if (status) status.textContent = step ? step.text : '';
10761
+ const refresh = document.getElementById('so-refresh');
10762
+ if (refresh) refresh.hidden = !step?.refresh;
10763
+ const start = document.getElementById('so-start');
10764
+ if (start) start.hidden = !step?.start;
10765
+ };
10766
+ show(null);
10767
+ // A choice that just disappeared must not keep focus: back to the card.
10768
+ if (focusedChoice && document.activeElement?.hidden) card.focus();
10769
+ if (escalateTimer) { clearTimeout(escalateTimer); escalateTimer = null; }
10770
+ let at = 0;
10771
+ const next = (steps) => {
10772
+ const step = steps[0];
10773
+ if (!step) return;
10774
+ escalateTimer = setTimeout(() => {
10775
+ escalateTimer = null;
10776
+ if (serverState !== state) return; // healed, or now saying something else
10777
+ show(step);
10778
+ next(steps.slice(1));
10779
+ }, step.after - at);
10780
+ at = step.after;
10781
+ };
10782
+ next(SERVER_STATE_ESCALATIONS[state] || []);
10783
+ }
10784
+ function showOfflineOverlay(state = 'reconnecting') {
10785
+ if (offlineOverlayEl) { applyOverlayState(state); return; }
10338
10786
  lastFocusBeforeOverlay = document.activeElement; // restored on heal (WCAG 2.4.3)
10339
10787
  const wrap = document.createElement('div');
10340
10788
  wrap.id = 'server-offline-overlay';
10341
- // role=status on the card → screen readers announce its text on insertion. The
10342
- // spinner is decorative (aria-hidden). The manual link is hidden until escalation.
10789
+ // role=status on the card → screen readers announce its text on insertion, and its changes
10790
+ // when the state moves (busy → reconnecting). The spinner is decorative (aria-hidden). The
10791
+ // manual choices are hidden until escalation.
10343
10792
  wrap.innerHTML =
10344
- `<div class="so-card" role="status" tabindex="-1">
10793
+ `<div class="so-card" role="status" aria-atomic="true" tabindex="-1">
10345
10794
  <div class="so-spinner" aria-hidden="true"></div>
10346
- <h1>Reconnecting to FloLess…</h1>
10347
- <p>FloLess isn’t responding. ${document.documentElement.classList.contains('desktop') ? 'FloLess' : 'This tab'} will keep trying to reconnect.</p>
10795
+ <h1></h1>
10796
+ <p class="so-body"></p>
10348
10797
  <p class="so-status" id="so-status"></p>
10349
10798
  <div class="so-actions">
10350
10799
  <button type="button" id="so-refresh" data-command-id="app.reconnect-refresh" class="secondary" hidden>Refresh page</button>
@@ -10368,20 +10817,27 @@
10368
10817
  }
10369
10818
  });
10370
10819
  window.addEventListener('keydown', trapOfflineOverlayKeys, true);
10820
+ applyOverlayState(state);
10371
10821
  // No action is required, so move focus to the CARD (tabindex=-1), NOT the link —
10372
10822
  // keeps keyboard focus inside the overlay without implying the link is the action.
10373
10823
  if (!document.getElementById('leave-guard-modal')?.classList.contains('show')) wrap.querySelector('.so-card').focus();
10374
- // Reveal the manual fallback only if recovery is clearly stuck (watchdog down).
10375
- if (escalateTimer) clearTimeout(escalateTimer);
10376
- escalateTimer = setTimeout(() => {
10377
- if (serverOnline === true) return; // healed
10378
- const s = document.getElementById('so-status');
10379
- const a = document.getElementById('so-start');
10380
- if (s) s.textContent = 'This is taking longer than usual. You can refresh this page, or start FloLess if it is closed.';
10381
- const refresh = document.getElementById('so-refresh');
10382
- if (refresh) refresh.hidden = false;
10383
- if (a) a.hidden = false;
10384
- }, ESCALATE_MS);
10824
+ }
10825
+ /** An update the person started is closing FloLess and opening the new version: say so while it does. */
10826
+ function markAppUpdateRelaunch(version) {
10827
+ if (appUpdateRelaunchTimer) clearTimeout(appUpdateRelaunchTimer);
10828
+ appUpdateRelaunch = { version: version || null, until: Date.now() + APP_UPDATE_RELAUNCH_MAX_MS };
10829
+ appUpdateRelaunchTimer = setTimeout(clearAppUpdateRelaunch, APP_UPDATE_RELAUNCH_MAX_MS);
10830
+ if (serverOnline === false) setServerStatus(false);
10831
+ }
10832
+ /**
10833
+ * The update is over: FloLess answered again after it (a new build reloads this page instead), the request failed,
10834
+ * or its last window passed. From then on an outage is an ordinary one, and the card says so at once.
10835
+ */
10836
+ function clearAppUpdateRelaunch() {
10837
+ if (appUpdateRelaunchTimer) { clearTimeout(appUpdateRelaunchTimer); appUpdateRelaunchTimer = null; }
10838
+ if (!appUpdateRelaunch) return;
10839
+ appUpdateRelaunch = null;
10840
+ if (serverOnline === false) setServerStatus(false);
10385
10841
  }
10386
10842
  function hideOfflineOverlay() {
10387
10843
  if (escalateTimer) { clearTimeout(escalateTimer); escalateTimer = null; }
@@ -10688,11 +11144,12 @@
10688
11144
  }
10689
11145
  } catch (err) {
10690
11146
  console.warn('node install did not start', err);
10691
- // #3097: the server's own reason when it gave one (api() marks it); otherwise the shared sentence. A start is a
10692
- // change, so an unexplained failure asks the person to check before starting it again.
10693
- statusText = err && err.serverText
10694
- ? `Couldn’t start the install. ${err.message}`
10695
- : failureCopy(err, { action: 'start the install', unsure: 'If Windows asks for permission in a moment, allow it; if nothing happens, choose Install again.' }).text;
11147
+ // #3097: the server's own reason when it gave one, read from its reply; otherwise the shared sentence. A start is
11148
+ // a change, so an unexplained failure asks the person to check before starting it again.
11149
+ const said = personText(err && err.body);
11150
+ statusText = said
11151
+ ? `Couldn’t start the install. ${said}`
11152
+ : errorText(err, { action: 'start the install', unsure: 'If Windows asks for permission in a moment, allow it; if nothing happens, choose Install again.' });
10696
11153
  } finally {
10697
11154
  nodeInstall.startInFlight = false;
10698
11155
  rerenderBootstrap();
@@ -10914,6 +11371,7 @@
10914
11371
  const style = document.createElement('style');
10915
11372
  style.textContent = `
10916
11373
  footer .status .stat-server .dot.offline{background:var(--err,#f87171);box-shadow:0 0 6px var(--err,#f87171);}
11374
+ footer .status .stat-server .dot.waiting{background:var(--warn,#fbbf24);box-shadow:0 0 6px var(--warn,#fbbf24);}
10917
11375
  #server-status-restart{appearance:none;border:1px solid var(--err,#f87171);background:transparent;color:var(--err,#f87171);
10918
11376
  font-family:var(--mono,monospace);font-size:11px;cursor:pointer;padding:1px 7px;border-radius:4px;margin-left:2px;text-decoration:none;display:inline-block;}
10919
11377
  /* display:inline-block on the ID above would beat the UA [hidden]{display:none}
@@ -11023,6 +11481,7 @@
11023
11481
  stat.classList.add('stat-server');
11024
11482
  const btn = document.createElement('a'); // real anchor — the href performs the launch
11025
11483
  btn.id = 'server-status-restart';
11484
+ btn.dataset.commandId = 'app.footer-restart';
11026
11485
  btn.href = 'floless://start';
11027
11486
  btn.textContent = '↻ Restart FloLess';
11028
11487
  btn.dataset.tip = 'Restart the local server';
@@ -11034,25 +11493,36 @@
11034
11493
  });
11035
11494
  stat.appendChild(btn);
11036
11495
  }
11496
+ /**
11497
+ * One observation of the server (`online`: it answered), turned into ONE state for the footer and the card. Called
11498
+ * again with the same reachability whenever what is known changes (the event stream dropped, an update started or
11499
+ * ended), so the card moves from 'busy' to 'reconnecting' while the server stays unreachable.
11500
+ */
11037
11501
  function setServerStatus(online) {
11038
11502
  if (window.__flolessStopped) return; // stopped on purpose — the "FloLess has stopped" screen owns the page
11039
- if (online === serverOnline) return;
11040
11503
  const wasOnline = serverOnline;
11041
11504
  serverOnline = online;
11505
+ if (appUpdateRelaunch && Date.now() >= appUpdateRelaunch.until) appUpdateRelaunch = null;
11506
+ const state = online ? 'online' : appUpdateRelaunch ? 'updating' : eventStreamOpen ? 'busy' : 'reconnecting';
11507
+ if (state === serverState) return;
11508
+ const was = serverState;
11509
+ serverState = state;
11042
11510
  const stat = document.querySelector('footer .status .stat-server') || document.querySelector('footer .status .stat');
11043
11511
  const dot = stat && stat.querySelector('.dot');
11044
11512
  const label = stat && stat.querySelector('.stat-val');
11045
11513
  const btn = document.getElementById('server-status-restart');
11046
- if (dot) dot.classList.toggle('offline', !online);
11047
- if (label) label.textContent = online ? 'runtime online' : 'server offline';
11048
- if (btn) btn.hidden = online;
11514
+ if (dot) { dot.classList.toggle('offline', state === 'reconnecting'); dot.classList.toggle('waiting', state === 'busy' || state === 'updating'); }
11515
+ if (label) label.textContent = online ? 'runtime online' : serverStateCopy(state).footer;
11516
+ if (btn) btn.hidden = state !== 'reconnecting'; // FloLess running (busy) or relaunching itself: nothing to start
11049
11517
  if (online) {
11518
+ // Answering again after an update the person started: the update is over (a new build reloads this page first).
11519
+ if (was === 'updating') clearAppUpdateRelaunch();
11050
11520
  hideOfflineOverlay(); // also clears the escalation timer + restores focus
11051
11521
  // Recovered from a boot-time / never-loaded outage: now that the server is
11052
11522
  // back, pull the workspace so the canvas fills in instead of staying empty.
11053
11523
  if (wasOnline === false && !currentId) loadWorkspaceData();
11054
11524
  } else {
11055
- showOfflineOverlay();
11525
+ showOfflineOverlay(state);
11056
11526
  }
11057
11527
  }
11058
11528
  let shownVersion = false;
@@ -11168,7 +11638,9 @@
11168
11638
  document.getElementById('app')?.removeAttribute('inert');
11169
11639
  }
11170
11640
  if (!licensed) {
11171
- renderGate(status || { state: 'unlicensed' });
11641
+ // #3134: Core opens on the chosen account's signed subscription, so a sign-in with several accounts chooses first.
11642
+ if (status?.reason === 'account-selection-required') renderAccountGate(status.accounts);
11643
+ else renderGate(status || { state: 'unlicensed' });
11172
11644
  return false;
11173
11645
  }
11174
11646
  return true;
@@ -11191,6 +11663,7 @@
11191
11663
  function connectionsChangeOf(m) {
11192
11664
  if (!m || typeof m !== 'object') return null;
11193
11665
  if (m.type === 'connect-result' && m.status === 'connected') return { reason: 'connected', id: typeof m.id === 'string' ? m.id : null };
11666
+ if (m.type === 'disconnect-result') return { reason: m.status === 'disconnected' ? 'disconnected' : 'disconnect-unconfirmed', id: typeof m.id === 'string' ? m.id : null };
11194
11667
  if (m.type === 'fs-change' && m.kind === 'credential') return { reason: 'credential', id: null };
11195
11668
  if (m.type === 'agent-install-result' && m.ok) return { reason: 'installed', id: typeof m.id === 'string' ? m.id : null };
11196
11669
  if (m.type === 'connections-changed') return { reason: 'tool-ready', id: typeof m.id === 'string' ? m.id : null };
@@ -11228,6 +11701,7 @@
11228
11701
  window.addEventListener('floless:workspace-root-state', drainPendingCatchup);
11229
11702
  es.onopen = () => {
11230
11703
  serverObservationEpoch++;
11704
+ eventStreamOpen = true; // the FloLess process is there: an unanswered health check now means busy, not gone
11231
11705
  const reconnect = everOpened || rootDisconnected;
11232
11706
  everOpened = true;
11233
11707
  rootDisconnected = false;
@@ -11288,25 +11762,7 @@
11288
11762
  // single-flight and idempotent, so the two racing is fine.
11289
11763
  if (window.awareUpdateController) window.awareUpdateController.adopt().catch(() => {});
11290
11764
  } else if (m.type === 'run-live' || m.type === 'node-progress' || m.type === 'run-finished') {
11291
- // #2228: live progress of a long run. This tab's own run is matched by its token; a run of the
11292
- // workflow this tab shows that someone else started is followed read-only (no Stop).
11293
- // #2241: a run that FAILED after an Agent answered ends with run-finished, not run-ended: its AI record is read then too.
11294
- if (m.type === 'run-finished' && m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id);
11295
- // Workflows → History: a run starting shows as Running, and a failed run ends with run-finished alone.
11296
- if (m.type !== 'node-progress') window.flolessRunHistory?.refresh?.();
11297
- signalRunEvent(m); // the browser tab hears its run's ending even when the strip already settled
11298
- if (liveRunOwns(m)) {
11299
- if (m.type === 'run-live') { if (m.runId) { liveRun.runId = m.runId; signalRunNote(liveRun); } }
11300
- else if (m.type === 'node-progress') onLiveProgress(m);
11301
- else finishLiveRun(typeof m.outcome === 'string' ? m.outcome : 'failed');
11302
- } else if (m.id === currentId && !(liveRun && liveRun.owner && !liveRun.ended)) {
11303
- if (m.type === 'run-finished') {
11304
- if (liveRun && !liveRun.owner && (!m.runId || m.runId === liveRun.runId)) finishLiveRun(typeof m.outcome === 'string' ? m.outcome : 'failed');
11305
- } else {
11306
- if (!liveRun || liveRun.ended || (m.runId && liveRun.runId && m.runId !== liveRun.runId)) observeLiveRun(m);
11307
- if (m.type === 'node-progress') onLiveProgress(m);
11308
- }
11309
- }
11765
+ onRunEvent(m);
11310
11766
  } else if (m.type === 'run-media' && Array.isArray(m.media)) {
11311
11767
  // #2230: the videos a run rendered, for a tab that lost the Run answer (a reload mid-run). The tab that
11312
11768
  // still holds the answer offers them from it; offerRunVideos is idempotent either way.
@@ -11563,6 +12019,9 @@
11563
12019
  } else if (slot) {
11564
12020
  slot.innerHTML = connectResultSlotHtml(m);
11565
12021
  }
12022
+ } else if (m.type === 'disconnect-result') {
12023
+ // #3301: a service was disconnected (here, in another window or from AI Chat): every open Integrations flips.
12024
+ refreshIntegrations();
11566
12025
  } else if (m.type === 'fs-change' && m.kind === 'credential') {
11567
12026
  // `aware connect`/`disconnect` wrote/removed a token in the local vault —
11568
12027
  // refresh the Integrations window so its status reflects reality live.
@@ -11595,6 +12054,7 @@
11595
12054
  };
11596
12055
  es.onerror = () => {
11597
12056
  serverObservationEpoch++;
12057
+ eventStreamOpen = false; // the connection to FloLess closed: an outage, not a busy server
11598
12058
  // A later health poll must not borrow a pre-disconnect shared startup probe.
11599
12059
  globalThis.flolessStartupAdmission?.invalidate();
11600
12060
  connectionGeneration++;
@@ -11636,6 +12096,10 @@
11636
12096
  if (access?.reason === 'session-expired') return 'Your FloLess sign-in has expired. Sign in again, then try again.';
11637
12097
  if (access?.reason === 'signed-out') return 'You are signed out of FloLess. Sign in again, then try again.';
11638
12098
  if (access?.reason === 'seat-taken') return 'Your FloLess session has ended. Sign in again, then try again.';
12099
+ // #3134: three reasons that signing in does not fix.
12100
+ if (access?.reason === 'account-selection-required') return 'Your sign-in belongs to more than one FloLess account. Reload FloLess and choose the account to use, then try again.';
12101
+ if (access?.reason === 'core-unavailable') return 'FloLess couldn’t reach floless.io to confirm your subscription. Check your internet connection, then try again.';
12102
+ if (access?.reason === 'update-required') return 'floless.io no longer accepts this version of FloLess. Install the latest FloLess, then try again.';
11639
12103
  return 'Sign in to FloLess to check your account access, then try again.';
11640
12104
  }
11641
12105
 
@@ -12372,20 +12836,21 @@
12372
12836
  // Refused for another reason once the project was free: say why, exactly as the other start surfaces do.
12373
12837
  const notReady = error?.code === 'chat-runtime-not-ready';
12374
12838
  const explained = notReady ? '' : chatStartErrorText(error);
12375
- if (notReady) showToast(error.message, 'warn');
12839
+ if (notReady) showToast(errorText(error), 'warn');
12376
12840
  else reportChatStartErr(error);
12377
- say(notReady ? error.message : explained || `Couldn’t start ${requestLabel(request)} in AI Chat. Try again.`);
12841
+ say(notReady ? errorText(error) : explained || `Couldn’t start ${requestLabel(request)} in AI Chat. Try again.`);
12378
12842
  }
12379
12843
  };
12380
12844
  requestStartWaits.set(request.id, setTimeout(tick, REQUEST_START_WAIT_MS));
12381
12845
  }
12382
12846
 
12383
12847
  async function startRequestChatWithSetup(requestId, provider, mode, { onSetup, isCancelled = () => false, ownChat = false, restoreFirst = false } = {}) {
12384
- if (typeof window.flolessChat?.startRequest !== 'function') throw new Error('AI Chat is still starting. Try again in a moment.');
12848
+ if (typeof window.flolessChat?.startRequest !== 'function') throw Object.assign(new Error('AI Chat is still starting. Try again in a moment.'), { forPerson: true });
12385
12849
  if (mode === 'start') {
12386
12850
  const ready = await ensureChatRuntimeReady(provider, { onProgress: (status) => onSetup?.(status), isCancelled });
12387
12851
  if (ready.cancelled || isCancelled()) throw Object.assign(new Error('The start was cancelled.'), { code: 'chat-start-cancelled' });
12388
- if (!ready.ok) throw Object.assign(new Error(ready.reason), { code: 'chat-runtime-not-ready' });
12852
+ // ready.reason is this file's own sentence (ensureChatRuntimeReady), so it is said as written.
12853
+ if (!ready.ok) throw Object.assign(new Error(ready.reason), { code: 'chat-runtime-not-ready', forPerson: true });
12389
12854
  }
12390
12855
  return window.flolessChat.startRequest(requestId, provider, mode, { ownChat, restoreFirst });
12391
12856
  }
@@ -12665,7 +13130,7 @@
12665
13130
  if (holder.kind === 'knowledge') {
12666
13131
  // #2106: the project's Knowledge step, where its organizing shows.
12667
13132
  try { await openKnowledgeStepOf(holder.projectId); }
12668
- catch (error) { showToast(error?.message || 'FloLess couldn’t open that project’s Knowledge step. Open it from Workspaces.', 'warn'); }
13133
+ catch (error) { showToast(errorText(error, { action: 'open that project’s Knowledge step', unsure: 'Open it from Workspaces.' }), 'warn'); }
12669
13134
  return;
12670
13135
  }
12671
13136
  if (holder.kind === 'chat' && holder.chatId && holder.owner && typeof window.flolessChat?.openConversationIn === 'function') {
@@ -13386,10 +13851,10 @@
13386
13851
  // The same refusal handling as the queued rows' start surface (request-chat-start-eligibility.test.ts).
13387
13852
  const notReady = error?.code === 'chat-runtime-not-ready';
13388
13853
  const explained = notReady ? '' : chatStartErrorText(error);
13389
- if (notReady) showToast(error.message, 'warn');
13854
+ if (notReady) showToast(errorText(error), 'warn');
13390
13855
  else reportChatStartErr(error);
13391
13856
  if (actionStatus) actionStatus.textContent = notReady
13392
- ? error.message
13857
+ ? errorText(error)
13393
13858
  : explained || `Couldn’t open ${requestLabel(request)} in AI Chat. Try again.`;
13394
13859
  if (!button.isConnected) return;
13395
13860
  button.disabled = false;
@@ -14048,7 +14513,7 @@
14048
14513
  : 'Its discard record could be read again, so there was nothing to decide.';
14049
14514
  discardRecordUi.delete(id);
14050
14515
  } catch (error) {
14051
- discardRecordUi.set(id, { status: error?.message || 'That didn’t work. Try again.' });
14516
+ discardRecordUi.set(id, { status: errorText(error, { action: 'record your choice', unsure: 'Check the request below before choosing again.' }) });
14052
14517
  await loadRequests().catch(() => {});
14053
14518
  renderRequests();
14054
14519
  focusDiscardRecordControl(id, choice === 'keep' ? 'keep' : 'ask');
@@ -14452,7 +14917,9 @@
14452
14917
  try {
14453
14918
  await api(`/api/requests/${encodeURIComponent(id)}/restore`, { method: 'POST', body: '{}' });
14454
14919
  } catch (error) {
14455
- showToast(error?.body?.error || 'FloLess couldn’t restore that request. It is still in Done; try again.', 'warn');
14920
+ showToast(personText(error?.body) || (error?.body?.diagnostic
14921
+ ? 'FloLess couldn’t tell whether that request was restored. Check Requests before trying again.'
14922
+ : 'FloLess couldn’t restore that request. It is still in Done; try again.'), 'warn');
14456
14923
  return false;
14457
14924
  }
14458
14925
  await loadRequests().catch(() => {});
@@ -14475,7 +14942,9 @@
14475
14942
  const body = error?.body;
14476
14943
  if (body?.code === 'request-held' && body.hold) return askDismissHeld(r, body.hold);
14477
14944
  if (body?.code === 'request-already-set-aside' || error?.status === 404) { await loadRequests().catch(() => {}); renderRequests(); return 'gone'; }
14478
- showToast(body?.error || 'FloLess couldn’t set that request aside. It is still in Requests; try again.', 'warn');
14945
+ showToast(personText(body) || (body?.diagnostic
14946
+ ? 'FloLess couldn’t tell whether that request was set aside. Check Requests before trying again.'
14947
+ : 'FloLess couldn’t set that request aside. It is still in Requests; try again.'), 'warn');
14479
14948
  return 'error';
14480
14949
  }
14481
14950
  return afterDismissed(r);
@@ -14572,11 +15041,11 @@
14572
15041
  // Refused after Restore: say why in the list as well, exactly as the other start surfaces do.
14573
15042
  const notReady = error?.code === 'chat-runtime-not-ready';
14574
15043
  const explained = notReady ? '' : chatStartErrorText(error);
14575
- if (notReady) showToast(error.message, 'warn');
15044
+ if (notReady) showToast(errorText(error), 'warn');
14576
15045
  else reportChatStartErr(error);
14577
15046
  await loadRequests().catch(() => {}); renderRequests();
14578
15047
  const actionStatus = document.getElementById('requests-action-status');
14579
- if (actionStatus) actionStatus.textContent = notReady ? error.message : explained || `Couldn’t start ${requestLabel(request)} in AI Chat. Try again.`;
15048
+ if (actionStatus) actionStatus.textContent = notReady ? errorText(error) : explained || `Couldn’t start ${requestLabel(request)} in AI Chat. Try again.`;
14580
15049
  }
14581
15050
  }
14582
15051
 
@@ -14606,7 +15075,11 @@
14606
15075
  if (result.failed > 0) {
14607
15076
  showToast(`${result.restored ? `${put} ` : ''}${result.failed} couldn’t be put back, so ${result.failed === 1 ? 'it is' : 'they are'} still in Done. Press Undo again to retry.`, 'warn');
14608
15077
  } else showToast(put, 'ok');
14609
- } catch (error) { showToast(error?.body?.error || 'FloLess couldn’t undo that. The requests are still in Done.', 'warn'); }
15078
+ } catch (error) {
15079
+ showToast(personText(error?.body) || (error?.body?.diagnostic
15080
+ ? 'FloLess couldn’t tell whether the requests were put back. Check Requests before pressing Undo again.'
15081
+ : 'FloLess couldn’t undo that. The requests are still in Done.'), 'warn');
15082
+ }
14610
15083
  await loadRequests().catch(() => {}); renderRequests();
14611
15084
  };
14612
15085
  const close = document.createElement('button');
@@ -14938,10 +15411,10 @@
14938
15411
  }
14939
15412
  const notReady = error?.code === 'chat-runtime-not-ready';
14940
15413
  const explained = notReady ? '' : chatStartErrorText(error);
14941
- if (notReady) showToast(error.message, 'warn');
15414
+ if (notReady) showToast(errorText(error), 'warn');
14942
15415
  else reportChatStartErr(error);
14943
15416
  if (actionStatus) actionStatus.textContent = notReady
14944
- ? error.message
15417
+ ? errorText(error)
14945
15418
  : explained || `Couldn’t ${starting ? 'start' : 'open'} ${requestLabel(request)} in AI Chat. Try again.`;
14946
15419
  if (notReady || !button.isConnected) {
14947
15420
  endStart();
@@ -15493,10 +15966,10 @@
15493
15966
  btn.onclick = () => saveAgentCommandTemplate(btn.dataset.agent, btn.dataset.cmd);
15494
15967
  });
15495
15968
  } catch (e) {
15496
- // #3097: the server's reason when it gave one (api() marks it), else the shared sentence for this read; never
15969
+ // #3097: the server's reason when it gave one, read from its reply, else the shared sentence for this read; never
15497
15970
  // "error: " plus the browser's exception text. The error itself goes to the console.
15498
15971
  console.warn('agent commands unavailable', id, e);
15499
- const said = e && e.serverText ? e.message : failureCopy(e, { action: 'load this agent’s commands', retrySafe: true }).text;
15972
+ const said = errorText(e, { action: 'load this agent’s commands', retrySafe: true });
15500
15973
  box.innerHTML = `<div class="cmd-desc">${escapeHtml(said)}</div>`;
15501
15974
  }
15502
15975
  }
@@ -15560,6 +16033,8 @@
15560
16033
  // "Available" means available-to-install, so already-installed agents live only
15561
16034
  // in the Installed tab. agentCatalog holds the installed set (id per item).
15562
16035
  function installedIdSet() { return new Set(agentCatalog.map((a) => a.id)); }
16036
+ // A `planned` tool has no runnable program yet (aware-aeco/aware#767): installing it could never make it usable.
16037
+ function offeredForInstall(a, installed) { return !installed.has(a.id) && a.status !== 'planned'; }
15563
16038
 
15564
16039
  function availCardHtml(a) {
15565
16040
  const name = escapeHtml(a.display_name || a.id);
@@ -15622,7 +16097,7 @@
15622
16097
  }
15623
16098
 
15624
16099
  const installed = installedIdSet();
15625
- const notInstalled = availableCatalog.filter((a) => !installed.has(a.id));
16100
+ const notInstalled = availableCatalog.filter((a) => offeredForInstall(a, installed));
15626
16101
  const q = ($libAvailSearch.value || '').toLowerCase().trim();
15627
16102
  const match = (a) => !q
15628
16103
  || a.id.toLowerCase().includes(q)
@@ -15684,7 +16159,7 @@
15684
16159
  showToast(`Installing “${nice}” — this can take a minute or two`, 'info');
15685
16160
  api('/api/agents/install', { method: 'POST', body: JSON.stringify({ id, ...(appId ? { appId, sourceHash } : {}) }) })
15686
16161
  .catch((e) => { // the START failed (bad id / server) — completion errors arrive via SSE
15687
- recordAgentInstallResult({ id, appId, sourceHash, ok: false, error: e.message || 'Please try again.' });
16162
+ recordAgentInstallResult({ id, appId, sourceHash, ok: false, error: errorText(e, { action: `start installing “${nice}”` }) });
15688
16163
  refreshAgentNotes();
15689
16164
  if ($libModal && $libModal.classList.contains('show')) renderAvailable();
15690
16165
  reportErr(e, 'install this tool');
@@ -16151,6 +16626,32 @@
16151
16626
  return granted.drive ? 'Allowed: Gmail sending and Drive file list.' : 'Allowed: Gmail sending. Not allowed: Drive file list (optional).';
16152
16627
  }
16153
16628
 
16629
+ /**
16630
+ * #3295: Microsoft adds every permission approved for FloLess Desktop earlier, so a sign-in can allow more than FloLess
16631
+ * asks for. Information plus a way out, never a gate: the account stays usable and its state is unchanged. The server
16632
+ * lists the extra permissions in words, the ones that write first.
16633
+ */
16634
+ function microsoftGrantNotice(slot, noticeId) {
16635
+ const grant = slot.microsoftGrant;
16636
+ if (!grant || grant.state !== 'wider' || !Array.isArray(grant.extra) || !grant.extra.length) return '';
16637
+ const shown = grant.extra.slice(0, 4).map((permission) => escapeHtml(permission.meaning));
16638
+ const more = grant.extra.length - shown.length;
16639
+ if (more > 0) shown.push(`and ${more} more`);
16640
+ const what = shown.length <= 2
16641
+ ? `: it ${shown.join(' and ')}.`
16642
+ : `. It:<ul class="int-grant-list">${shown.map((line) => `<li>${line}</li>`).join('')}</ul>`;
16643
+ const reconnect = slot.alias ? 'click Reconnect this account' : 'click Reconnect on this card';
16644
+ return `<div class="int-notice is-warn int-grant-notice" role="note" id="${escapeAttr(noticeId)}">`
16645
+ + '<strong class="int-grant-title">This sign-in allows more than FloLess asked for</strong>'
16646
+ // AWARE does not record which app issued a sign-in, so the approval is "the app this sign-in uses"; revoking FloLess
16647
+ // Desktop and reconnecting (which signs in with it) is the way out either way.
16648
+ + `<span class="int-grant-body">Microsoft kept permissions from an earlier approval of the app this sign-in uses${what} `
16649
+ + 'FloLess didn’t ask for them, but while they’re allowed, Microsoft 365 commands run from FloLess can use them. To remove them, sign in at '
16650
+ + '<a href="https://myapps.microsoft.com" target="_blank" rel="noopener noreferrer">myapps.microsoft.com<span class="sr-only"> (opens in a new tab)</span></a>, '
16651
+ + `open FloLess Desktop and remove its access, then ${reconnect}. If your organisation approved it, ask your IT admin to remove it. `
16652
+ + 'You can keep using this account meanwhile.</span></div>';
16653
+ }
16654
+
16154
16655
  function renderIntegrationAccounts(integration) {
16155
16656
  const slots = Array.isArray(integration.accountSlots) ? integration.accountSlots : [];
16156
16657
  if (!slots.length) return integration.chatSupported
@@ -16201,11 +16702,15 @@
16201
16702
  ? `<span class="int-account-access${slot.granted.gmail ? '' : ' is-warn'}">${escapeHtml(googleAccessLine(slot.granted, slot.alias))}</span>` : '';
16202
16703
  // #2649: a named account reconnects on its own whenever it needs a new sign-in or new consent; the card's main
16203
16704
  // button is the default account's. Its Drive choice is the card's checkbox, the person's current selection.
16705
+ const grantNoticeId = `int-grant-${integration.id}-${slot.alias || 'default'}`.replace(/[^A-Za-z0-9_-]/g, '-');
16706
+ const grantNotice = integration.id === 'microsoft-365' ? microsoftGrantNotice(slot, grantNoticeId) : '';
16204
16707
  const needsSignIn = slot.status !== 'valid' || (slot.granted && !slot.granted.gmail)
16205
16708
  || ['scope-missing', 'identity-unverified', 'credential-expired', 'generation-unavailable'].includes(slot.unavailableCode);
16206
- const reconnect = slot.alias && needsSignIn
16709
+ // A wider Microsoft grant also offers a named account its own Reconnect: the way out after removing the approval.
16710
+ const reconnect = slot.alias && (needsSignIn || grantNotice)
16207
16711
  ? `<button class="int-action int-account-reconnect" type="button" data-int="${escapeAttr(integration.id)}" data-int-action="connect"`
16208
16712
  + ` data-int-alias="${escapeAttr(slot.alias)}"`
16713
+ + (grantNotice ? ` aria-describedby="${escapeAttr(grantNoticeId)}"` : '')
16209
16714
  + ` data-command-id="shell.integrations-account-reconnect#${escapeAttr(`${integration.id}:${slot.alias}`)}"`
16210
16715
  + ` data-command-instance-label="${escapeAttr(`${integration.name} account ${slot.alias}`)}"`
16211
16716
  + ` aria-label="Reconnect ${escapeAttr(integration.name)} account ${escapeAttr(slot.alias)}">Reconnect this account</button>`
@@ -16217,6 +16722,7 @@
16217
16722
  </div>
16218
16723
  <span class="int-chat-state">${state}</span>
16219
16724
  ${access}
16725
+ ${grantNotice}
16220
16726
  <span class="int-account-reason">${escapeHtml(why)}</span>
16221
16727
  ${reconnect}
16222
16728
  </div>`;
@@ -16314,6 +16820,186 @@
16314
16820
  + ` data-command-id="shell.integrations-connect#${escapeAttr(i.id)}" data-command-instance-label="${escapeAttr(i.name)}">Reconnect</button>`;
16315
16821
  }
16316
16822
 
16823
+ /**
16824
+ * #3301: the account a card's Disconnect removes — the one its Connected badge stands for (the first signed-in
16825
+ * account, as the server picks it), and how the confirm names it: the verified account, else its FloLess name.
16826
+ */
16827
+ function disconnectTarget(i) {
16828
+ const slots = Array.isArray(i.accountSlots) ? i.accountSlots : [];
16829
+ const slot = slots.find((s) => s.status === 'valid') || slots[0] || null;
16830
+ const alias = slot && typeof slot.alias === 'string' && slot.alias ? slot.alias : null;
16831
+ const label = slot?.verifiedPrincipal?.presentationLabel || alias || null;
16832
+ return { alias, label };
16833
+ }
16834
+
16835
+ /** The Disconnect button's carriers: the account it removes and its Instructor registration. */
16836
+ function disconnectButtonAttrs(i) {
16837
+ const { alias } = disconnectTarget(i);
16838
+ return ` data-command-id="shell.integrations-disconnect#${escapeAttr(i.id)}" data-command-instance-label="${escapeAttr(i.name)}"`
16839
+ + (alias ? ` data-int-alias="${escapeAttr(alias)}"` : '');
16840
+ }
16841
+
16842
+ /**
16843
+ * #3301: the Disconnect confirm's words. Names the service and the account, says what stops working and that
16844
+ * connecting again undoes it. An AWARE older than 0.175.0 keeps Google's sign-in for the whole computer
16845
+ * (aware-aeco/aware#782): the server says when that is so (`signOutWholeComputer`, #3334), and only then does it warn.
16846
+ */
16847
+ function disconnectConfirmCopy(i) {
16848
+ const { alias, label } = disconnectTarget(i);
16849
+ const title = `Disconnect ${i.name}${alias ? ` (${alias})` : ''}?`;
16850
+ const who = label || 'the default account';
16851
+ const sub = `This removes the saved sign-in for ${who} from this computer. Knowledge sources from ${i.name} stop syncing, `
16852
+ + 'and workflows and AI Chat checks that use it will ask you to sign in again. To undo it, reconnect: click Connect on this card and sign in.';
16853
+ // Other signed-in accounts of the same service keep working; say which, so "disconnect" is not read as the whole service.
16854
+ const slots = Array.isArray(i.accountSlots) ? i.accountSlots : [];
16855
+ const others = slots.filter((s) => s.status === 'valid' && (s.alias || null) !== alias)
16856
+ .map((s) => s.verifiedPrincipal?.presentationLabel || s.alias || 'the default account');
16857
+ const stays = others.length ? ` ${others.join(', ')} stay${others.length === 1 ? 's' : ''} connected.` : '';
16858
+ return { title, sub: sub + stays, alias, google: i.signOutWholeComputer === true };
16859
+ }
16860
+
16861
+ /**
16862
+ * #3301: what a finished Disconnect says, from the route's answer and the card as AWARE now reports it. Nothing was
16863
+ * stored, or the follow-up check could not run: the server's own sentence. Another account still signed in: the card
16864
+ * stays Connected, so it says so and keeps focus on its Disconnect. Otherwise the service is disconnected and Connect
16865
+ * is next.
16866
+ */
16867
+ function disconnectOutcome(i, result, refreshed) {
16868
+ if (result && typeof result.note === 'string' && result.note) {
16869
+ return { text: result.note, tone: 'info', focus: refreshed?.status === 'connected' ? 'disconnect' : 'connect' };
16870
+ }
16871
+ if (refreshed?.status === 'connected') {
16872
+ const { alias, label } = disconnectTarget(i);
16873
+ const who = label || alias || 'the default account';
16874
+ return { text: `Disconnected ${who} from ${i.name}. Another ${i.name} account is still connected.`, tone: 'ok', focus: 'disconnect' };
16875
+ }
16876
+ return { text: `${i.name} disconnected. Click Connect to sign in again.`, tone: 'ok', focus: 'connect' };
16877
+ }
16878
+
16879
+ /**
16880
+ * #3301: ask, then disconnect in the app. Opens above Integrations (which is inerted while it is up); Cancel holds
16881
+ * focus and Esc or the backdrop cancel, except while the request is out, so its outcome is never lost. A failure stays
16882
+ * here in words, with Try again and the terminal command as a last resort. On success the card is redrawn from AWARE,
16883
+ * the change is announced, and focus moves to the redrawn card's Connect.
16884
+ */
16885
+ let intDisconnectOpen = false;
16886
+ function confirmIntegrationDisconnect(i) {
16887
+ if (intDisconnectOpen) return;
16888
+ const $modal = document.getElementById('int-disconnect-modal');
16889
+ const $box = $modal.querySelector('.modal');
16890
+ const $title = document.getElementById('int-disconnect-title');
16891
+ const $sub = document.getElementById('int-disconnect-sub');
16892
+ const $google = document.getElementById('int-disconnect-google');
16893
+ const $error = document.getElementById('int-disconnect-error');
16894
+ const $ok = document.getElementById('int-disconnect-ok');
16895
+ const $cancel = document.getElementById('int-disconnect-cancel');
16896
+ const $copy = document.getElementById('int-disconnect-copy');
16897
+ const copy = disconnectConfirmCopy(i);
16898
+ $title.textContent = copy.title;
16899
+ $sub.textContent = copy.sub;
16900
+ $google.hidden = !copy.google;
16901
+ // A hidden notice still reaches a screen reader through aria-describedby, so it is named only when it is shown (#3334).
16902
+ $modal.setAttribute('aria-describedby', copy.google ? 'int-disconnect-sub int-disconnect-google' : 'int-disconnect-sub');
16903
+ $error.textContent = '';
16904
+ $copy.hidden = true;
16905
+ $copy.textContent = 'Copy command';
16906
+ $ok.textContent = 'Disconnect';
16907
+ $ok.disabled = $cancel.disabled = false;
16908
+ $box.removeAttribute('aria-busy');
16909
+ $ok.setAttribute('data-command-instance-label', i.name);
16910
+ $cancel.setAttribute('data-command-instance-label', `disconnecting ${i.name}`);
16911
+ const returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
16912
+ const covered = Array.from(document.querySelectorAll('.modal-backdrop.show')).filter((m) => m !== $modal)
16913
+ .map((modal) => ({ modal, inert: !!modal.inert, ariaHidden: modal.getAttribute('aria-hidden') }));
16914
+ covered.forEach(({ modal }) => { modal.inert = true; modal.setAttribute('aria-hidden', 'true'); });
16915
+ intDisconnectOpen = true;
16916
+ showModal($modal);
16917
+ setTimeout(() => $cancel.focus(), 0);
16918
+ let working = false;
16919
+ let closed = false;
16920
+ let command = '';
16921
+ // Once per opening: a late continuation of this dialog must never close or unhook a newer one.
16922
+ const close = (focusTarget) => {
16923
+ if (closed) return;
16924
+ closed = true;
16925
+ intDisconnectOpen = false;
16926
+ hideModal($modal);
16927
+ covered.forEach(({ modal, inert, ariaHidden }) => {
16928
+ modal.inert = inert;
16929
+ if (ariaHidden === null) modal.removeAttribute('aria-hidden');
16930
+ else modal.setAttribute('aria-hidden', ariaHidden);
16931
+ });
16932
+ document.removeEventListener('keydown', onKey, true);
16933
+ $ok.onclick = $cancel.onclick = $copy.onclick = null;
16934
+ $modal.onclick = $modal.onmousedown = null;
16935
+ // A closed dialog keeps no busy state behind (the accessibility tree still reads hidden controls' names).
16936
+ $ok.textContent = 'Disconnect';
16937
+ $ok.disabled = $cancel.disabled = false;
16938
+ $box.removeAttribute('aria-busy');
16939
+ const target = typeof focusTarget === 'function' ? focusTarget() : focusTarget;
16940
+ if (target && target.isConnected) target.focus();
16941
+ else if (returnFocus && returnFocus.isConnected) returnFocus.focus();
16942
+ else document.getElementById('integrations-close')?.focus();
16943
+ };
16944
+ const onKey = (e) => {
16945
+ if (document.getElementById('server-offline-overlay')) return;
16946
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); if (!working) close(); }
16947
+ else if (e.key === 'Tab') {
16948
+ // Above Integrations: own Tab so the lower dialog's trap cannot pull focus behind this one.
16949
+ e.stopPropagation();
16950
+ const focusable = Array.from($modal.querySelectorAll('button:not([disabled]):not([hidden])')).filter((el) => el.getClientRects().length);
16951
+ if (!focusable.length) { e.preventDefault(); return; }
16952
+ const first = focusable[0]; const last = focusable[focusable.length - 1];
16953
+ if (e.shiftKey && (document.activeElement === first || !$modal.contains(document.activeElement))) { e.preventDefault(); last.focus(); }
16954
+ else if (!e.shiftKey && (document.activeElement === last || !$modal.contains(document.activeElement))) { e.preventDefault(); first.focus(); }
16955
+ }
16956
+ };
16957
+ $cancel.onclick = () => { if (!working) close(); };
16958
+ $copy.onclick = async () => {
16959
+ const copied = await copyToClipboard(command);
16960
+ $copy.textContent = copied ? 'Copied' : 'Copy command';
16961
+ if (!copied) showToast(`Run in your terminal: ${command}`, 'info');
16962
+ setTimeout(() => { $copy.textContent = 'Copy command'; }, 1600);
16963
+ };
16964
+ $ok.onclick = async () => {
16965
+ working = true;
16966
+ $error.textContent = '';
16967
+ $box.setAttribute('aria-busy', 'true');
16968
+ $box.focus();
16969
+ $ok.textContent = 'Disconnecting…';
16970
+ $ok.disabled = $cancel.disabled = true;
16971
+ let result;
16972
+ try {
16973
+ result = await api(`/api/integrations/${encodeURIComponent(i.id)}/disconnect`, {
16974
+ method: 'POST', body: JSON.stringify(copy.alias ? { alias: copy.alias } : {}),
16975
+ });
16976
+ } catch (error) {
16977
+ working = false;
16978
+ $box.removeAttribute('aria-busy');
16979
+ command = typeof error?.body?.command === 'string' ? error.body.command : '';
16980
+ $error.textContent = errorText(error, { action: `disconnect ${i.name}` });
16981
+ $copy.hidden = !command;
16982
+ $ok.textContent = 'Try again';
16983
+ $ok.disabled = $cancel.disabled = false;
16984
+ $ok.focus();
16985
+ // The card underneath shows what AWARE holds now (a failure can land after the sign-in was removed).
16986
+ void refreshIntegrations();
16987
+ return;
16988
+ }
16989
+ const id = (window.CSS && CSS.escape) ? CSS.escape(i.id) : i.id;
16990
+ // Still working while the card is redrawn, so Esc or the backdrop cannot close the dialog mid-way.
16991
+ await refreshIntegrations();
16992
+ working = false;
16993
+ // Worded from the server's answer and the redrawn card, never assumed: another account may still be connected.
16994
+ const outcome = disconnectOutcome(i, result, integrations.find((row) => row.id === i.id));
16995
+ document.getElementById('integrations-status').textContent = outcome.text;
16996
+ close(() => $integrationsList.querySelector(`[data-integration-id="${id}"] .int-action[data-int-action="${outcome.focus}"]`));
16997
+ showToast(outcome.text, outcome.tone);
16998
+ };
16999
+ onBackdropDismiss($modal, () => close(), () => !working);
17000
+ document.addEventListener('keydown', onKey, true);
17001
+ }
17002
+
16317
17003
  /** One OAuth integration's card (#2649: a named function, so its rendered carriers and controls are tested). */
16318
17004
  function integrationCardHtml(i) {
16319
17005
  const action = i.status === 'connected' ? 'Disconnect' : i.status === 'expired' ? 'Reconnect' : 'Connect';
@@ -16326,10 +17012,18 @@
16326
17012
  const reconnect = google ? google.reconnect
16327
17013
  : i.id === MICROSOFT_INTEGRATION_ID && i.status === 'connected' ? reconnectButtonHtml(i) : '';
16328
17014
  // #2466: what a Microsoft sign-in asks for, said before the person clicks (FLOLESS_M365_SCOPES, server/oauth-presets.ts).
17015
+ // #3295: while a sign-in allows more than that, or FloLess cannot tell what it allows, the card never says it only reads.
17016
+ const grants = i.id === MICROSOFT_INTEGRATION_ID && Array.isArray(i.accountSlots) ? i.accountSlots.map((slot) => slot.microsoftGrant?.state) : [];
17017
+ const wider = grants.filter((state) => state === 'wider').length;
16329
17018
  const microsoftHelp = i.id === MICROSOFT_INTEGRATION_ID
16330
17019
  ? '<div class="int-drive-help is-flush" id="int-microsoft-access-help">When you sign in, FloLess asks Microsoft to let AI Chat read your OneDrive and SharePoint files, '
16331
- + 'Excel workbooks, Outlook mail, Planner and Teams chats. It only reads. Excel’s permission also allows changes '
16332
- + '(Microsoft has no read-only one), but FloLess never edits a file.</div>'
17020
+ + 'Excel workbooks, Outlook mail, Planner and Teams chats. '
17021
+ + (wider
17022
+ ? `FloLess itself only reads, but Microsoft gave ${wider > 1 ? 'some of your sign-ins' : 'one of your sign-ins'} more. See the note below. `
17023
+ : grants.includes('unknown')
17024
+ ? 'FloLess itself only reads, but Microsoft didn’t say what your sign-in allows, so FloLess can’t check it. '
17025
+ : 'It only reads. ')
17026
+ + 'Excel’s permission also allows changes (Microsoft has no read-only one), but FloLess never edits a file.</div>'
16333
17027
  : '';
16334
17028
  return `
16335
17029
  <div class="int-item int-${i.status}" data-integration-id="${escapeAttr(i.id)}" tabindex="-1">
@@ -16347,7 +17041,7 @@
16347
17041
  <span class="int-badge int-badge-${i.status}">${badge}</span>
16348
17042
  <span class="int-recovery-actions">
16349
17043
  ${reconnect}
16350
- <button class="int-action" data-int="${escapeAttr(i.id)}" data-int-action="${action.toLowerCase()}"${action === 'Disconnect' ? '' : ` data-command-id="shell.integrations-connect#${escapeAttr(i.id)}" data-command-instance-label="${escapeAttr(i.name)}"`}>${action}</button>
17044
+ <button class="int-action" data-int="${escapeAttr(i.id)}" data-int-action="${action.toLowerCase()}"${action === 'Disconnect' ? disconnectButtonAttrs(i) : ` data-command-id="shell.integrations-connect#${escapeAttr(i.id)}" data-command-instance-label="${escapeAttr(i.name)}"`}>${action}</button>
16351
17045
  </span>
16352
17046
  </div>
16353
17047
  ${i.status === 'connected' || (google && !google.deviceCodeAvailable) ? '' : `
@@ -16459,13 +17153,12 @@
16459
17153
  });
16460
17154
  $integrationsList.querySelectorAll('.int-action[data-int]').forEach((btn) => {
16461
17155
  btn.onclick = async () => {
16462
- // Connect/Reconnect drive the device-code sign-in IN the app (AWARE owns
16463
- // the OAuth + token storage; we only show the code + reflect the result —
16464
- // the token never crosses floless.app). Disconnect stays a copied command.
17156
+ // Connect/Reconnect drive the sign-in IN the app (AWARE owns the OAuth + token storage; we only show the code
17157
+ // and reflect the result — the token never crosses floless.app). #3301: Disconnect runs in the app too, after a
17158
+ // confirm: AWARE deletes the stored sign-in itself, so no secret crosses here either.
16465
17159
  if (btn.dataset.intAction === 'disconnect') {
16466
- const cmd = 'aware disconnect ' + btn.dataset.int;
16467
- const copied = await copyToClipboard(cmd);
16468
- showToast(`${copied ? 'Copied — run' : 'Run'} in your terminal: ${cmd}`, 'info');
17160
+ const integration = integrations.find((row) => row.id === btn.dataset.int);
17161
+ if (integration) confirmIntegrationDisconnect(integration);
16469
17162
  return;
16470
17163
  }
16471
17164
  // #2649: a named account's own Reconnect carries its account; the Drive choice is the card's checkbox.
@@ -16563,22 +17256,23 @@
16563
17256
  });
16564
17257
  if (slot) slot.innerHTML = 'Starting sign-in…';
16565
17258
  try {
16566
- const res = await api(`/api/connect/${encodeURIComponent(id)}`, { method: 'POST', body });
17259
+ // `connect`, not `res`: a start it declines carries the route’s own sentence in `message` (a constant per service).
17260
+ const connect = await api(`/api/connect/${encodeURIComponent(id)}`, { method: 'POST', body });
16567
17261
  // A managed-preset pre-flight (e.g. port 80 already in use) refuses to start
16568
17262
  // and broadcasts the reason over SSE (connect-result). Clear the guard so the
16569
17263
  // user can retry after fixing it, and don't claim the browser opened. #2649: the
16570
17264
  // reason also comes back here, so a card waiting on a reconnecting SSE still says why.
16571
- if (res && res.started === false) {
17265
+ if (connect && connect.started === false) {
16572
17266
  connecting.delete(id);
16573
- if (slot && typeof res.message === 'string') slot.innerHTML = connectResultSlotHtml({ status: 'failed', message: res.message });
17267
+ if (slot && typeof connect.message === 'string') slot.innerHTML = connectResultSlotHtml({ status: 'failed', message: connect.message });
16574
17268
  return;
16575
17269
  }
16576
17270
  if (slot) {
16577
- if (res.flow === 'device-code' && res.prompt) {
17271
+ if (connect.flow === 'device-code' && connect.prompt) {
16578
17272
  // Fallback flow: show the device code to enter at the verification URL.
16579
17273
  slot.innerHTML =
16580
- `Go to <a href="${escapeAttr(res.prompt.verification_uri)}" target="_blank" rel="noopener">${escapeHtml(res.prompt.verification_uri)}</a>` +
16581
- ` and enter code <strong class="dc-code">${escapeHtml(res.prompt.user_code)}</strong> — waiting for sign-in…`;
17274
+ `Go to <a href="${escapeAttr(connect.prompt.verification_uri)}" target="_blank" rel="noopener">${escapeHtml(connect.prompt.verification_uri)}</a>` +
17275
+ ` and enter code <strong class="dc-code">${escapeHtml(connect.prompt.user_code)}</strong> — waiting for sign-in…`;
16582
17276
  } else {
16583
17277
  // OAuth: aware opened the provider sign-in in the browser.
16584
17278
  slot.innerHTML = 'Opening your browser to sign in… complete it there and this will update automatically.';
@@ -16590,7 +17284,7 @@
16590
17284
  // (a 409 busy lock, whose sentence names it) are shown where the person clicked; anything else goes to the usual
16591
17285
  // error report.
16592
17286
  const own = e && (e.status === 400 || (e.status === 409 && e.body?.code === 'lifecycle-busy'));
16593
- const said = own && e.body && typeof e.body.error === 'string' ? e.body.error : '';
17287
+ const said = own ? personText(e.body) : '';
16594
17288
  if (slot) slot.innerHTML = said ? escapeHtml(said) : '';
16595
17289
  if (!said) reportErr(e);
16596
17290
  }
@@ -16615,7 +17309,8 @@
16615
17309
  const db = document.getElementById('debug-btn');
16616
17310
  if (db) {
16617
17311
  const node = id && currentId && apps.get(currentId)?.nodes.find((n) => n.id === id);
16618
- db.hidden = !(node && node.config && typeof node.config.code === 'string');
17312
+ // #3234: the debugger attaches to the Tekla bridge, so only a Tekla exec step offers it (the server refuses any other).
17313
+ db.hidden = !(node && node.agent === 'tekla' && node.command === 'exec' && node.config && typeof node.config.code === 'string');
16619
17314
  }
16620
17315
  };
16621
17316
 
@@ -16892,7 +17587,7 @@
16892
17587
  const ai = r.kind === 'trigger' ? globalThis.flolessAgentSteps?.watcherCardParts?.(r.aiEvents) ?? null
16893
17588
  : !r.agent && r.lastRun ? globalThis.flolessAgentSteps?.routineAiParts(r.lastRun) : null;
16894
17589
  if (!ai) return '';
16895
- return `<span class="rtn-dot">·</span><span class="rtn-ai" data-tip="${escapeAttr(ai.aiTip)}">${escapeHtml(ai.ai)}</span>`
17590
+ return `<span class="rtn-dot">·</span><span class="rtn-ai${ai.stoppedAt ? ' is-stopped' : ''}" data-tip="${escapeAttr(ai.aiTip)}">${escapeHtml(ai.ai)}</span>`
16896
17591
  + (ai.questions ? `<span class="rtn-dot">·</span><span class="rtn-ai-q" data-tip="${escapeAttr(ai.questionsTip)}">${escapeHtml(ai.questions)}</span>` : '');
16897
17592
  }
16898
17593
  function lastRunTip(r) {
@@ -16913,6 +17608,10 @@
16913
17608
  // #2241 S5: a run with an AI step says so, and says how many questions it left for you.
16914
17609
  const ai = globalThis.flolessAgentSteps?.routineAiParts(lr);
16915
17610
  const aiWords = ai ? ` — ${ai.ai}${ai.questions ? ' · ' + ai.questions : ''}` : '';
17611
+ // #3229: a run its AI step's check stopped ended "ok"; the row never reads as a finished run.
17612
+ const head = ai && ai.stoppedAt
17613
+ ? `Last run stopped at the AI step “${ai.stoppedAt.length > 40 ? `${ai.stoppedAt.slice(0, 39)}…` : ai.stoppedAt}”, so the steps after it did not run${ai.questions ? ' · ' + ai.questions : ''}`
17614
+ : `Last run ${lr.status}${aiWords}`;
16916
17615
  // A run that finished on a stated assumption says so with its outcome, never only in the report.
16917
17616
  const warnings = Array.isArray(lr.warnings) ? lr.warnings.filter((warning) => typeof warning === 'string' && warning) : [];
16918
17617
  // #1998: a run made under an approval carried forward to newer tool versions says so, in AWARE's words.
@@ -16924,7 +17623,7 @@
16924
17623
  && typeof w.detail === 'string' && w.detail.trim() && (w.via === null || typeof w.via === 'string')
16925
17624
  && Array.isArray(w.choices) && w.choices.every((choice) => typeof choice === 'string')) : [];
16926
17625
  const bridge = bridgeWarnings.map((w) => `\n${w.status === 'declaration-invalid' ? 'Ran with an invalid bridge declaration' : 'Ran with a bridge mismatch'}: ${w.via ? w.via + ' → ' : ''}${w.name}. ${w.detail}`).join('');
16927
- return `Last run ${lr.status}${aiWords}${lr.reason ? ' — ' + lr.reason : ''}${warnings.length ? ' — ' + warnings.join(' ') : ''} · ${absTime(lr.at)}${dur}${carried}${bridge}`;
17626
+ return `${head}${lr.reason ? ' — ' + lr.reason : ''}${warnings.length ? ' — ' + warnings.join(' ') : ''} · ${absTime(lr.at)}${dur}${carried}${bridge}`;
16928
17627
  }
16929
17628
 
16930
17629
  // ── Trigger-routine row helpers ─────────────────────────────────────────────
@@ -16982,9 +17681,19 @@
16982
17681
  return { label: 'stopped', dotClass: '', tip: 'Not running', sr: 'Status: stopped' };
16983
17682
  }
16984
17683
 
16985
- async function loadRoutinesData() {
17684
+ let routinesLoadSeq = 0;
17685
+ let routinesLoadLatest = Promise.resolve();
17686
+ // Several loads can be in flight (each routine-changed event starts one): only the newest answer is applied, so an
17687
+ // older list arriving last never brings back a question already answered. A superseded load resolves with the newest
17688
+ // one, so a caller that awaits it still reads the fresh list.
17689
+ function loadRoutinesData() {
17690
+ routinesLoadLatest = applyRoutinesLoad(++routinesLoadSeq);
17691
+ return routinesLoadLatest;
17692
+ }
17693
+ async function applyRoutinesLoad(seq) {
16986
17694
  try {
16987
17695
  const res = await api('/api/routines');
17696
+ if (seq !== routinesLoadSeq) return routinesLoadLatest;
16988
17697
  // The Workflows landing repaints only when the routines its "Scheduled" chips read change, not on every
16989
17698
  // scheduler tick.
16990
17699
  const chipKey = (list) => JSON.stringify(list.filter((r) => r.enabled && !r.broken).map((r) => [r.workflow, r.name]));
@@ -17002,6 +17711,9 @@
17002
17711
  }
17003
17712
  for (const id of live) void refreshRoutineReportDiscovery(id);
17004
17713
  if (routinesData.some((r) => r.agent)) void refreshRoutineAgents();
17714
+ // Owner ruling 2026-11-06: the card asking whether to run what was missed while FloLess was closed.
17715
+ try { window.flolessMissedRoutines?.update(routinesData, { api, reportErr, reload: loadRoutinesData }); }
17716
+ catch (err) { console.error('Missed-routines card failed', err); }
17005
17717
  if ($routinesModal.classList.contains('show')) renderRoutinesList();
17006
17718
  // Last, and on its own: a landing repaint that throws must not skip the reconcile above.
17007
17719
  if (wfLanding && chipsChanged) {
@@ -17133,7 +17845,8 @@
17133
17845
  const savedPath = typeof m.savedPath === 'string' ? m.savedPath : '';
17134
17846
  const fromChat = m.from !== 'terminal';
17135
17847
  const entry = { nodeId: m.nodeId || null, label: fromChat ? 'from AI Chat' : 'from a terminal', html: m.html, interactive, savedPath,
17136
- withFiles: m.withFiles === true, runId: typeof m.runId === 'string' ? m.runId : null };
17848
+ withFiles: m.withFiles === true, runId: typeof m.runId === 'string' ? m.runId : null,
17849
+ aiStop: globalThis.flolessAgentSteps?.stoppedRunView?.(m) ?? null }; // #3229: the same banner as after this window's own Run
17137
17850
  lastReportByApp.set(m.workflow, entry);
17138
17851
  const open = $reportModal && $reportModal.classList.contains('show');
17139
17852
  if (!open || currentId !== m.workflow || reportRunning) return;
@@ -17148,7 +17861,8 @@
17148
17861
  if (!m || !m.workflow || typeof m.html !== 'string') return;
17149
17862
  const prev = lastReportByApp.get(m.workflow);
17150
17863
  const changed = !prev || prev.html !== m.html;
17151
- const entry = { nodeId: m.nodeId || null, label: 'scheduled', html: m.html, withFiles: m.withFiles === true, runId: typeof m.runId === 'string' ? m.runId : null };
17864
+ const entry = { nodeId: m.nodeId || null, label: 'scheduled', html: m.html, withFiles: m.withFiles === true, runId: typeof m.runId === 'string' ? m.runId : null,
17865
+ aiStop: globalThis.flolessAgentSteps?.stoppedRunView?.(m) ?? null }; // #3229: a scheduled run that stopped at an AI step says so too
17152
17866
  lastReportByApp.set(m.workflow, entry);
17153
17867
  const open = $reportModal && $reportModal.classList.contains('show');
17154
17868
  if (open && currentId === m.workflow && !reportRunning && !foregroundTrigger) {
@@ -17364,6 +18078,33 @@
17364
18078
  }
17365
18079
  // ── tab signal (end)
17366
18080
 
18081
+ /** A run-live, node-progress or run-finished event from the server's event stream. */
18082
+ function onRunEvent(m) {
18083
+ // #2228: live progress of a long run. This tab's own run is matched by its token; a run of the
18084
+ // workflow this tab shows that someone else started is followed read-only (no Stop).
18085
+ // #2241: a run that FAILED after an Agent answered ends with run-finished, not run-ended: its AI record is read then too.
18086
+ if (m.type === 'run-finished' && m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id);
18087
+ // Workflows → History: a run starting shows as Running, and a failed run ends with run-finished alone.
18088
+ if (m.type !== 'node-progress') window.flolessRunHistory?.refresh?.();
18089
+ // #3253: the one rule for every branch below (this tab's own run, one it follows, the report overlay, the tab
18090
+ // signal): the ending of another attempt (a Run anyway's refused one, however late) never ends, settles or forgets
18091
+ // the attempt this tab is watching now.
18092
+ if (m.type === 'run-finished' && m.clientRunToken && liveRun && liveRun.token && m.clientRunToken !== liveRun.token) return;
18093
+ signalRunEvent(m); // the browser tab hears its run's ending even when the strip already settled
18094
+ if (liveRunOwns(m)) {
18095
+ if (m.type === 'run-live') { if (m.runId) { liveRun.runId = m.runId; signalRunNote(liveRun); } }
18096
+ else if (m.type === 'node-progress') onLiveProgress(m);
18097
+ else finishLiveRun(typeof m.outcome === 'string' ? m.outcome : 'failed');
18098
+ } else if (m.id === currentId && !(liveRun && liveRun.owner && !liveRun.ended)) {
18099
+ if (m.type === 'run-finished') {
18100
+ if (liveRun && !liveRun.owner && (!m.runId || m.runId === liveRun.runId)) finishLiveRun(typeof m.outcome === 'string' ? m.outcome : 'failed');
18101
+ } else {
18102
+ if (!liveRun || liveRun.ended || (m.runId && liveRun.runId && m.runId !== liveRun.runId)) observeLiveRun(m);
18103
+ if (m.type === 'node-progress') onLiveProgress(m);
18104
+ }
18105
+ }
18106
+ }
18107
+
17367
18108
  function liveRunOwns(m) {
17368
18109
  if (!liveRun || liveRun.ended) return false;
17369
18110
  if (m.clientRunToken && m.clientRunToken === liveRun.token) return true;
@@ -17434,6 +18175,12 @@
17434
18175
  syncRunStrip();
17435
18176
  }
17436
18177
 
18178
+ /** A Run's own ending: settle the tracked attempt it holds (by token), never a later one that replaced it. */
18179
+ function finishOwnLiveRun(token, outcome) {
18180
+ if (!token || !liveRun || liveRun.token !== token) return;
18181
+ if (outcome === 'no-answer') settleLiveRunWithoutAnswer(); else finishLiveRun(outcome);
18182
+ }
18183
+
17437
18184
  function finishLiveRun(outcome) {
17438
18185
  if (pageLeaving) return; // the page is going away mid-run: keep the token so the next page resumes it
17439
18186
  if (liveRun && liveRun.ended && signalRunIs(liveRun)) {
@@ -17688,7 +18435,9 @@
17688
18435
  $reportSub.innerHTML = `Live run of <code>${escapeHtml(id)}</code> — the report re-renders on every event.`;
17689
18436
  showModal($reportModal);
17690
18437
  try {
17691
- const res = await api('/api/trigger-run', { method: 'POST', body: JSON.stringify({ id, inputs: currentInputs() }) });
18438
+ const res = await postAskingElsewhere('/api/trigger-run', { id, inputs: currentInputs() }, { onApprove: () => {
18439
+ if ($compileBtn && !$compileBtn.disabled) $compileBtn.click();
18440
+ } });
17692
18441
  foregroundTrigger = { appId: id, sessionId: res.sessionId, firedCount: 0 };
17693
18442
  paintForegroundListening();
17694
18443
  beatLiveViewer();
@@ -17824,6 +18573,38 @@
17824
18573
  return null;
17825
18574
  }
17826
18575
 
18576
+ /** #3232: how a routine's workflow reads — an owned one by its name and owner (server-resolved), else its id. */
18577
+ function routineWorkflowText(r) {
18578
+ const label = r.workflowLabel;
18579
+ return label?.name ? (label.owner ? `${label.name} · ${label.owner}` : label.name) : r.workflow;
18580
+ }
18581
+
18582
+ /**
18583
+ * #3232: the row's "what it runs" span. An owned workflow's name and project stay on one line beside the schedule:
18584
+ * the name shortens first, the project after it, and the whole label is the tip.
18585
+ */
18586
+ function routineWorkflowHtml(r, whatText) {
18587
+ const label = r.agent ? null : r.workflowLabel;
18588
+ if (!label?.name) return `<span class="rtn-wf">${escapeHtml(whatText)}</span>`;
18589
+ return `<span class="rtn-wf named" data-tip="${escapeAttr(whatText)}"><span class="rtn-wf-name">${escapeHtml(label.name)}</span>`
18590
+ + (label.owner ? `<span class="rtn-wf-owner">· ${escapeHtml(label.owner)}</span>` : '') + '</span>';
18591
+ }
18592
+
18593
+ /**
18594
+ * #3232: the workflows a routine can run, read from `/api/apps?names=1` each time the form opens — every installed workflow
18595
+ * it could run before, by its id, except an owned workflow's publications: the server names the ACTIVE one
18596
+ * (`ownedWorkflowLabel`), listed once as "<name> · <project>", and a superseded one is left out. The value stays the
18597
+ * runtime id the server stores; the label is what the person recognises. When the server could not read the names
18598
+ * (`ownedNamesUnavailable`), `namesUnavailable` says so, so the form tells the person rather than quietly leaving them out.
18599
+ */
18600
+ async function routineWorkflowChoices() {
18601
+ const { apps: installed, ownedNamesUnavailable } = await api('/api/apps?names=1');
18602
+ const choices = installed.filter((a) => a.execution !== 'internal' && (!a.ownedPublication || a.ownedWorkflowLabel?.name))
18603
+ .map((a) => ({ id: a.id, label: a.ownedPublication ? `${a.ownedWorkflowLabel.name} · ${a.ownedWorkflowLabel.owner}` : a.id }))
18604
+ .sort((x, y) => x.label.localeCompare(y.label));
18605
+ return { choices, namesUnavailable: ownedNamesUnavailable === true };
18606
+ }
18607
+
17827
18608
  function renderRoutinesList() {
17828
18609
  const $list = document.getElementById('routines-list');
17829
18610
  const $quota = document.getElementById('rtn-quota');
@@ -17879,8 +18660,8 @@
17879
18660
  if (held) { nextLabel = held.label; nextTip = held.tip; }
17880
18661
  }
17881
18662
  const whenText = isTrigger ? triggerWhenText(r) : scheduleText(r.schedule);
17882
- // #2035: an agent routine names its agent, not a workflow id.
17883
- const whatText = r.agent ? `Agent · ${routineAgentNames.get(r.agent.agentId) || 'agent'}` : r.workflow;
18663
+ // #2035: an agent routine names its agent, not a workflow id; #3232: an owned workflow is named, not its runtime id.
18664
+ const whatText = r.agent ? `Agent · ${routineAgentNames.get(r.agent.agentId) || 'agent'}` : routineWorkflowText(r);
17884
18665
  const toggleTip = isTrigger ? (r.enabled ? 'Stop listening' : 'Start listening') : `${r.enabled ? 'Disable' : 'Enable'} this routine`;
17885
18666
  // One sentence for all three surfaces a blocked ▶ speaks through: the hover tip, the `?`
17886
18667
  // band (which reads data-blocked-reason), and the toast when a click still reaches the
@@ -17899,7 +18680,7 @@
17899
18680
  <div class="rtn-item ${isTrigger ? 'trigger ' : ''}${r.enabled ? '' : 'disabled'} ${running ? 'running' : ''}" data-id="${escapeAttr(r.id)}">
17900
18681
  <div class="rtn-main">
17901
18682
  <div class="rtn-name">${escapeHtml(r.name)}</div>
17902
- <div class="rtn-sub"><span class="rtn-wf">${escapeHtml(whatText)}</span><span class="rtn-dot">·</span><span>${escapeHtml(whenText)}</span>${broken}${routineAiHtml(r)}</div>
18683
+ <div class="rtn-sub">${routineWorkflowHtml(r, whatText)}<span class="rtn-dot">·</span><span>${escapeHtml(whenText)}</span>${broken}${routineAiHtml(r)}</div>
17903
18684
  ${reportLine}
17904
18685
  </div>
17905
18686
  <div class="rtn-meta"${isTrigger ? ' aria-live="polite" aria-atomic="true"' : ''}>
@@ -17935,7 +18716,12 @@
17935
18716
  }
17936
18717
  async function runRoutineNow(id) {
17937
18718
  try {
17938
- await api(`/api/routines/${encodeURIComponent(id)}/run`, { method: 'POST' });
18719
+ const workflow = routinesData.find((r) => r.id === id)?.workflow;
18720
+ await postAskingElsewhere(`/api/routines/${encodeURIComponent(id)}/run`, {}, { routine: true, onApprove: async () => {
18721
+ if (!workflow) return;
18722
+ hideModal($routinesModal);
18723
+ await selectComboById(workflow);
18724
+ } });
17939
18725
  runningRoutines.add(id); // optimistic, for immediate feedback; SSE confirms it moments later
17940
18726
  renderRoutinesList();
17941
18727
  // #2062: a hand run starts a paused agent; its schedule stays held. Queued, not yet started — the row says how it went.
@@ -17946,6 +18732,7 @@
17946
18732
  // and nothing was started, so never say it was. Keyed on the FLAG rather than the status: this
17947
18733
  // route is lifecycle-gated, so a 409 can also mean "aware is busy with maintenance", which is a
17948
18734
  // different sentence and belongs in the error path.
18735
+ if (e.body && e.body.elsewhereStopped) return; // the person chose not to run it; nothing started
17949
18736
  if (!(e.body && e.body.running)) { reportErr(e, 'run this routine now'); return; }
17950
18737
  showToast(RTN_ALREADY_RUNNING, 'info');
17951
18738
  // RECONCILE rather than add: the 409 is a point-in-time snapshot, and the run can end while the
@@ -18228,17 +19015,22 @@
18228
19015
  const r = id ? routinesData.find((x) => x.id === id) : null;
18229
19016
  editReturnFocus = opts.returnFocus || null;
18230
19017
  const $wf = document.getElementById('rtn-workflow');
18231
- try {
18232
- const { apps: list } = await api('/api/apps');
18233
- editWorkflows = list.filter((a) => a.execution !== 'internal');
18234
- } catch { editWorkflows = []; }
18235
- $wf.innerHTML = editWorkflows.map((a) => `<option value="${escapeAttr(a.id)}">${escapeHtml(a.id)}</option>`).join('');
19018
+ let namesUnavailable = false;
19019
+ try { ({ choices: editWorkflows, namesUnavailable } = await routineWorkflowChoices()); } catch { editWorkflows = []; }
19020
+ document.getElementById('rtn-workflow-unnamed').hidden = !(namesUnavailable && !r);
19021
+ // Editing a routine whose workflow is no longer listed (archived, locked) still shows what it runs.
19022
+ if (r && !r.agent && r.workflow && !editWorkflows.some((a) => a.id === r.workflow)) {
19023
+ editWorkflows = [{ id: r.workflow, label: routineWorkflowText(r) }, ...editWorkflows];
19024
+ }
19025
+ $wf.innerHTML = editWorkflows.map((a) => `<option value="${escapeAttr(a.id)}">${escapeHtml(a.label)}</option>`).join('');
18236
19026
  document.getElementById('rtn-edit-title').textContent = r ? 'Edit routine' : 'New routine';
18237
19027
  document.getElementById('rtn-name').value = r ? r.name : '';
18238
19028
  // #2046: a Guide suggestion names the workflow; it is preselected only when it is one of the choices.
18239
19029
  const suggested = !r && opts.workflowId && editWorkflows.some((a) => a.id === opts.workflowId) ? opts.workflowId : null;
18240
19030
  if (!r && opts.workflowId && !suggested) {
18241
- showToast(`${opts.workflowId} can’t be scheduled from here, so no workflow is chosen yet. Pick the one to run in the list.`, 'warn');
19031
+ showToast(namesUnavailable
19032
+ ? 'FloLess couldn’t read the names of your own workflows just now, so no workflow is chosen yet. Close this and open it again in a moment.'
19033
+ : `${workflowLabelOf(opts.workflowId)} can’t be scheduled from here, so no workflow is chosen yet. Pick the one to run in the list.`, 'warn');
18242
19034
  }
18243
19035
  const wfId = r ? r.workflow : opts.workflowId && !suggested ? '' : (suggested || (editWorkflows[0] ? editWorkflows[0].id : ''));
18244
19036
  $wf.value = wfId;
@@ -18325,7 +19117,8 @@
18325
19117
  await loadRoutinesData();
18326
19118
  } catch (e) {
18327
19119
  // #2035: the server words an agent routine's refusal for the person (archived, another folder…); say that.
18328
- const said = asAgent && typeof e?.body?.error === 'string' && e.status < 500 ? e.body.error : null;
19120
+ // #3097 3c.4: so does every routine refusal it marks as its own (`refusal: 'routine'`), for a workflow routine too.
19121
+ const said = (asAgent || e?.body?.refusal === 'routine') && typeof e?.body?.error === 'string' && e.status < 500 ? e.body.error : null;
18329
19122
  showToast(said || 'We couldn’t save this routine because FloLess could not save the change. Try again.', 'err');
18330
19123
  }
18331
19124
  }
@@ -18780,7 +19573,8 @@
18780
19573
  riRenderSuccess(r.ref || '', importFailure && r.importDetailsAttached === false ? importFailure.operationId : null, r.queued === true);
18781
19574
  } catch (e) {
18782
19575
  riSubmitting = false;
18783
- const err = (e && e.body && e.body.error) || '';
19576
+ // A code that picks the branch (riSendFailureCopy says the sentence), so the raw `error`, never shown.
19577
+ const err = (e && e.body && typeof e.body.error === 'string' && e.body.error) || '';
18784
19578
  if (err === 'signed_out') {
18785
19579
  riRenderSignIn(); // the action isn't possible until signed in — hide the form, don't grey it out
18786
19580
  } else if (err === 'rate_limited') {
@@ -19029,11 +19823,11 @@
19029
19823
  if (error?.code === 'chat-start-cancelled' || gone()) return;
19030
19824
  const notReady = error?.code === 'chat-runtime-not-ready';
19031
19825
  const explained = notReady ? '' : chatStartErrorText(error);
19032
- if (notReady) showToast(error.message, 'warn');
19826
+ if (notReady) showToast(errorText(error), 'warn');
19033
19827
  else reportChatStartErr(error);
19034
19828
  setRequestHelpBusy(null);
19035
19829
  const sub = document.getElementById('request-help-sub');
19036
- if (sub) sub.textContent = notReady ? error.message : explained || (requestHelpCopied
19830
+ if (sub) sub.textContent = notReady ? errorText(error) : explained || (requestHelpCopied
19037
19831
  ? 'The request is still in Requests. Try again, start it in the background, or use the copied instruction in your terminal.'
19038
19832
  : 'The request is still in Requests. Try again, start it in the background, or copy the terminal instruction.');
19039
19833
  // A Request with no safe instruction has nothing to copy either — AI Chat's sentence says to
@@ -19188,13 +19982,16 @@
19188
19982
  const duplicate = duplicateNames.get(account.displayName) > 1;
19189
19983
  const role = account.role === 'owner' ? 'Owner' : 'Member';
19190
19984
  const discriminator = duplicate ? ` · account …${String(account.accountId).slice(-8)}` : '';
19985
+ // Named before the discriminator so it survives wrapping; the row stays selectable (the gate then explains).
19986
+ const core = account.coreStatus === 'inactive' ? ' · No active subscription' : '';
19191
19987
  return `<div class="wf-option" role="option" aria-selected="false" tabindex="${index === 0 ? '0' : '-1'}" data-account-id="${escapeHtml(account.accountId)}">
19192
19988
  <span class="ag-option-copy"><span class="wf-option-name">${escapeHtml(account.displayName)}</span>
19193
- <span class="wf-option-meta">${role}${escapeHtml(discriminator)}</span></span></div>`;
19989
+ <span class="wf-option-meta">${role}${core}${escapeHtml(discriminator)}</span></span></div>`;
19194
19990
  }).join('');
19195
19991
  wrap.innerHTML = `<section class="ag-card" role="dialog"${moduleOnly ? '' : ' aria-modal="true"'} aria-labelledby="ag-title" aria-describedby="ag-copy">
19196
19992
  <h1 id="ag-title">Choose an account</h1>
19197
- <p class="ag-copy" id="ag-copy">Your sign-in belongs to more than one FloLess account. Choose which account to use for ${escapeHtml(moduleLabel)} access.</p>
19993
+ <p class="ag-copy" id="ag-copy">Your sign-in belongs to more than one FloLess account. ${moduleOnly
19994
+ ? `Choose which account to use for ${escapeHtml(moduleLabel)} access.` : 'Choose the account to use FloLess with.'}</p>
19198
19995
  ${rows.length ? `<div class="ag-list" id="ag-list" role="listbox" aria-label="FloLess accounts">${options}</div>`
19199
19996
  : '<p class="ag-copy" role="alert">No account is available for this sign-in. Ask your FloLess account owner to add you, or sign in with a different account.</p>'}
19200
19997
  <div class="ag-actions">${moduleOnly ? '<button type="button" id="ag-not-now">Not now</button>' : '<button type="button" id="ag-signout">Sign out</button>'}
@@ -19249,6 +20046,19 @@
19249
20046
  try {
19250
20047
  const response = await api('/api/license/account', { method: 'POST', body: JSON.stringify({ accountId: selected.dataset.accountId }) });
19251
20048
  const access = response.desktopAccess || {};
20049
+ if (access.state === 'active' && !moduleOnly) {
20050
+ // #3134: the choice decides Core. Open FloLess through the ordinary start (live updates, workspace) once the
20051
+ // licence confirms it; an account without an active subscription is asked about here, with the others still listed.
20052
+ let licence = null;
20053
+ try { licence = await api('/api/license/status'); } catch { /* the reload below shows whatever holds */ }
20054
+ if (licence?.reason === 'account-selection-required') {
20055
+ setStatus('That account has no active FloLess subscription. Choose another account, or sign out.', true);
20056
+ return;
20057
+ }
20058
+ setStatus('Confirmed. Opening FloLess…');
20059
+ location.reload();
20060
+ return;
20061
+ }
19252
20062
  if (access.state === 'active') {
19253
20063
  wrap.remove();
19254
20064
  if (appRoot) appRoot.inert = false;
@@ -19322,6 +20132,14 @@
19322
20132
  'signed-out': { headline: 'Sign in to continue',
19323
20133
  body: 'Sign in with your FloLess account to use floless.app.',
19324
20134
  secondary: { label: 'No subscription yet? Subscribe →', href: subUrl } },
20135
+ // #3134: FloLess opens only on floless.io's signed answer about the subscription. Neither of these is fixed by
20136
+ // signing in, so Try again comes first and signing in stays available as a plain link-style button.
20137
+ 'core-unavailable': { headline: 'Can’t confirm your subscription',
20138
+ body: 'FloLess couldn’t reach floless.io to check your subscription. Check your internet connection, then try again.',
20139
+ secondary: null, retry: 'Still couldn’t reach floless.io. Check your connection, then try again.' },
20140
+ 'update-required': { headline: 'Update FloLess to continue',
20141
+ body: 'floless.io no longer accepts this version of FloLess. Install the latest FloLess, then open it again.',
20142
+ secondary: null, retry: 'This version still isn’t accepted. Install the latest FloLess, then open it again.' },
19325
20143
  };
19326
20144
  let copy = COPY[reason] || COPY['signed-out']; // neutral fallback for an unknown/absent reason
19327
20145
  // A lost seat carries a sub-reason; only a genuine takeover should claim "another device".
@@ -19354,6 +20172,11 @@
19354
20172
  #license-gate .lg-status{min-height:18px;margin:14px 0 0;font-size:12.5px;color:var(--text-muted,#9aa5b6);}
19355
20173
  #license-gate .lg-sub{display:inline-block;margin-top:6px;font-size:12.5px;color:var(--accent,#3b82f6);text-decoration:none;}
19356
20174
  #license-gate .lg-sub:hover{text-decoration:underline;}
20175
+ #license-gate .lg-link{appearance:none;background:none;border:none;padding:2px 4px;margin-top:6px;cursor:pointer;
20176
+ font:inherit;font-size:12.5px;color:var(--accent,#3b82f6);}
20177
+ #license-gate .lg-link:hover{text-decoration:underline;}
20178
+ #license-gate .lg-link:disabled{opacity:.6;cursor:default;text-decoration:none;}
20179
+ #license-gate .primary:focus-visible,#license-gate .lg-link:focus-visible{outline:2px solid var(--accent,#3b82f6);outline-offset:2px;}
19357
20180
  #license-gate .lg-version{margin:18px 0 0;font-size:11px;font-family:var(--mono,monospace);color:var(--text-muted,#9aa5b6);}`;
19358
20181
  document.head.appendChild(style);
19359
20182
  const wrap = document.createElement('div');
@@ -19373,8 +20196,10 @@
19373
20196
  </svg></div>
19374
20197
  <h1>${escapeHtml(copy.headline)}</h1>
19375
20198
  <p>${escapeHtml(copy.body)}</p>
19376
- <button id="lg-signin" class="primary" data-command-id="shell.license-sign-in" aria-describedby="lg-status">Sign in at floless.io</button>
20199
+ ${copy.retry ? '<button id="lg-retry" class="primary" data-command-id="shell.license-retry" aria-describedby="lg-status">Try again</button>'
20200
+ : '<button id="lg-signin" class="primary" data-command-id="shell.license-sign-in" aria-describedby="lg-status">Sign in at floless.io</button>'}
19377
20201
  <p class="lg-status" id="lg-status" role="status"></p>
20202
+ ${copy.retry ? '<button id="lg-signin" class="lg-link" data-command-id="shell.license-sign-in" aria-describedby="lg-status">Sign in again</button>' : ''}
19378
20203
  ${copy.secondary ? `<a class="lg-sub" href="${copy.secondary.href}" target="_blank" rel="noopener">${escapeHtml(copy.secondary.label)}</a>` : ''}
19379
20204
  <p class="lg-version" id="lg-version"></p>
19380
20205
  </div>`;
@@ -19391,7 +20216,8 @@
19391
20216
  // #2786: one watcher, while a sign-in is under way. It reloads once FloLess is signed in, and says how the latest
19392
20217
  // sign-in ended wherever it was started (here, the report dialog, AI Chat or `floless login`), once per sign-in.
19393
20218
  const view = { waiting: false, shown: null, doneOnly: false };
19394
- const stop = (message) => { view.waiting = false; s.textContent = message; signIn.textContent = 'Try again'; };
20219
+ const signInLabel = copy.retry ? 'Sign in again' : 'Sign in at floless.io';
20220
+ const stop = (message) => { view.waiting = false; s.textContent = message; signIn.textContent = copy.retry ? signInLabel : 'Try again'; };
19395
20221
  let generation = 0;
19396
20222
  const watch = async (g = ++generation) => {
19397
20223
  let st; try { st = await api('/api/license/status'); } catch { st = null; }
@@ -19405,7 +20231,7 @@
19405
20231
  generation += 1; // an older watch stops here, so it cannot write over this sign-in while it registers
19406
20232
  view.waiting = false;
19407
20233
  s.textContent = 'Opening sign-in in your browser…';
19408
- signIn.textContent = 'Sign in at floless.io';
20234
+ signIn.textContent = signInLabel;
19409
20235
  // Starting registers the sign-in with floless.io first, so it can take a moment: one start at a time.
19410
20236
  signIn.disabled = true;
19411
20237
  signIn.setAttribute('data-blocked-reason', SIGN_IN_STARTING);
@@ -19420,6 +20246,46 @@
19420
20246
  watch();
19421
20247
  };
19422
20248
  watch(); // a sign-in started before this screen showed (or one that already ended) is said here too
20249
+ const retry = document.getElementById('lg-retry');
20250
+ if (retry) {
20251
+ // Asks the server again. FloLess opens through its ordinary start once floless.io confirms the subscription (or
20252
+ // asks which account to use); otherwise the screen says it still could not, and the button stays.
20253
+ // Anything but the same answer opens FloLess or shows the screen that answer needs, through the ordinary start.
20254
+ const changed = (st) => !!st && (st.state === 'valid' || st.state === 'offline-grace'
20255
+ || (st.state === 'expired' ? 'expired' : st.reason) !== reason);
20256
+ retry.onclick = async () => {
20257
+ if (retry.disabled) return;
20258
+ retry.disabled = true; retry.setAttribute('aria-busy', 'true');
20259
+ s.textContent = 'Checking with floless.io…';
20260
+ let st = null;
20261
+ try { st = await api('/api/license/status?fresh=1'); } catch { st = null; }
20262
+ if (changed(st)) {
20263
+ s.textContent = st.state === 'valid' || st.state === 'offline-grace' ? 'Confirmed. Opening FloLess…' : '';
20264
+ location.reload();
20265
+ return;
20266
+ }
20267
+ retry.disabled = false; retry.removeAttribute('aria-busy');
20268
+ s.textContent = copy.retry;
20269
+ retry.focus();
20270
+ };
20271
+ retry.focus();
20272
+ // A passing outage (floless.io slow to answer, or this PC still busy starting FloLess) should not need a click:
20273
+ // while this screen shows, ask again quietly every 20 s. Each ask is a fresh check (the server keeps any answer a
20274
+ // minute otherwise, and lets at most one fresh check through every few seconds whoever asks).
20275
+ if (reason === 'core-unavailable') {
20276
+ const quiet = async () => {
20277
+ if (!retry.isConnected) return;
20278
+ if (!retry.disabled) {
20279
+ let st = null;
20280
+ try { st = await api('/api/license/status?fresh=1'); } catch { st = null; }
20281
+ if (!retry.isConnected) return;
20282
+ if (changed(st)) { location.reload(); return; }
20283
+ }
20284
+ setTimeout(quiet, 20_000);
20285
+ };
20286
+ setTimeout(quiet, 20_000);
20287
+ }
20288
+ }
19423
20289
  }
19424
20290
 
19425
20291
  // ── Custom Panels bridge (web/panels.js) ─────────────────────────────────────
@@ -19515,6 +20381,9 @@
19515
20381
  // The Workflows tab's home, the counterpart of the Workspaces landing: a create card and one card per workflow. It
19516
20382
  // renders AWARE's library listing; it composes nothing.
19517
20383
  const $wfLanding = document.getElementById('wf-landing');
20384
+ // The workflow card ⋯ menu (openWorkflowCardMenu) and which card it is open for: { key (the owned workflowId), name, canCopy }.
20385
+ const $wfCardMenu = document.getElementById('wf-card-menu');
20386
+ let wfCardMenuFor = null;
19518
20387
  // #2866: a changed Sort by choice repaints the Workflows tab (the render keeps search, focus and open sections).
19519
20388
  globalThis.flolessLandingSort?.onChange('workflows', () => { if (wfLanding) renderWorkflowsLanding(); });
19520
20389
  // The landing search's query, kept outside the input because the landing re-renders with innerHTML.
@@ -19530,6 +20399,7 @@
19530
20399
  if (next && !wfLanding) wfLandingQuery = ''; // a fresh visit starts unfiltered
19531
20400
  wfLanding = next;
19532
20401
  if (wfLanding) closeDraftView();
20402
+ syncWorkflowCardMenu();
19533
20403
  document.body.classList.toggle('wf-landing-open', wfLanding);
19534
20404
  if ($wfLanding) $wfLanding.hidden = !wfLanding;
19535
20405
  // Nothing reads routines at startup (only the Routines window, routine events and a few report paths do), so the
@@ -19539,10 +20409,20 @@
19539
20409
  notifyChatScope();
19540
20410
  }
19541
20411
 
20412
+ // #3234: the card names what the workflow needs ("Tekla model", the author's "Steel model", "AI step"), never the
20413
+ // runner its steps use. The server derives it (app-reader appListFacts); a row from an older server falls back to the
20414
+ // provider it sent.
19542
20415
  function workflowCardMeta(row) {
19543
20416
  const nodes = Number(row.nodes) || 0;
19544
- const provider = PROVIDER_LABELS[row.provider] || row.provider || '';
19545
- return `${nodes} node${nodes === 1 ? '' : 's'}${provider ? ` · ${provider}` : ''}`;
20417
+ const count = `${nodes} node${nodes === 1 ? '' : 's'}`;
20418
+ if (Array.isArray(row.needs)) return [count, ...row.needs.filter((n) => typeof n === 'string')].join(' · ');
20419
+ const provider = row.provider && row.provider !== 'other' ? (PROVIDER_LABELS[row.provider] || row.provider) : '';
20420
+ return `${count}${provider ? ` · ${provider}` : ''}`;
20421
+ }
20422
+ // …and, on a line of its own that is never cut short, that this computer's AWARE is too old to run it.
20423
+ function workflowCardAwareLine(row) {
20424
+ const minimum = row.needsAware && typeof row.needsAware.minimum === 'string' ? row.needsAware.minimum : '';
20425
+ return minimum ? `<div class="ws-meta wf-card-aware">Needs AWARE ${escapeHtml(minimum)} or newer</div>` : '';
19546
20426
  }
19547
20427
 
19548
20428
  // The card's "Scheduled" chip and its tip ('' = no chip). A routine runs the installed app it names, which is the
@@ -19650,8 +20530,152 @@
19650
20530
  if (keepCaret) { const box = $wfLanding.querySelector('#wf-landing-search'); box?.focus(); box?.setSelectionRange?.(keepCaret[0], keepCaret[1]); }
19651
20531
  }
19652
20532
 
20533
+ // ── Workflow card ⋯ menu (Workflows page) — the same Rename… / Duplicate / Archive a project card offers, run
20534
+ // through the dialogs the workflow picker already uses, so every check and message is the picker's own. Only a card of
20535
+ // a workflow of yours (compiled or draft) has one. An installed card has none: renaming or copying an installed
20536
+ // workflow makes an installed app the Workflows page does not list, so a renamed one vanishes and a copy never
20537
+ // appears (#3182).
20538
+ function placeWorkflowCardMenu(anchor) {
20539
+ const r = anchor.getBoundingClientRect();
20540
+ // 288 = the menu's 280px width (.menu) + an 8px margin; flip above the ⋯ when the window has no room below.
20541
+ $wfCardMenu.style.left = Math.round(Math.max(8, Math.min(r.right - 280, window.innerWidth - 288))) + 'px';
20542
+ const below = r.bottom + 6;
20543
+ const height = $wfCardMenu.offsetHeight;
20544
+ $wfCardMenu.style.top = Math.round(below + height <= window.innerHeight - 8 ? below : Math.max(8, r.top - 6 - height)) + 'px';
20545
+ anchor.setAttribute('aria-expanded', 'true');
20546
+ // Where the ⋯ was when the menu was placed: a scroll that moves it from here closes the menu.
20547
+ if (wfCardMenuFor) wfCardMenuFor.placedAt = { top: r.top, left: r.left };
20548
+ }
20549
+ function workflowCardMenuAnchor() {
20550
+ return wfCardMenuFor && $wfLanding?.querySelector(`[data-wf-kebab="${CSS.escape(wfCardMenuFor.key)}"]`);
20551
+ }
20552
+ // focusInstead: a visible control to take focus when the ⋯ may be out of view (a scroll closed the menu).
20553
+ function closeWorkflowCardMenu(returnFocus, focusInstead = null) {
20554
+ if (!$wfCardMenu || $wfCardMenu.hidden) { wfCardMenuFor = null; return; }
20555
+ const anchor = workflowCardMenuAnchor();
20556
+ // Focus on the menu or on its own ⋯ (a click there focuses it) belongs to the menu, and moves with it.
20557
+ const hadFocus = $wfCardMenu.contains(document.activeElement) || (!!anchor && document.activeElement === anchor);
20558
+ $wfCardMenu.hidden = true;
20559
+ $wfCardMenu.classList.remove('show');
20560
+ anchor?.setAttribute('aria-expanded', 'false');
20561
+ // Give focus back to the ⋯ before an item's dialog opens, so the dialog returns it to a live control, not <body>.
20562
+ // Closing never scrolls the page (preventScroll).
20563
+ const target = focusInstead || anchor;
20564
+ if (target && (returnFocus || hadFocus)) target.focus(target === anchor ? { focusVisible: true, preventScroll: true } : { preventScroll: true });
20565
+ wfCardMenuFor = null;
20566
+ }
20567
+ // Called after each repaint of the landing (any tab) and on show/hide: the menu lives outside the landing, so a repaint
20568
+ // leaves it open. Keep it pinned to the rebuilt ⋯, or close it when the landing is hidden, another tab is showing, or
20569
+ // that card is gone (archived). A rename keeps the card: the menu is keyed by the workflow's id, not its name.
20570
+ function syncWorkflowCardMenu() {
20571
+ if (!wfCardMenuFor) return;
20572
+ const anchor = wfLanding && wfLandingTab === 'workflows' ? workflowCardMenuAnchor() : null;
20573
+ if (!anchor) { closeWorkflowCardMenu(false); return; }
20574
+ // A card the search filter hid (it hides every card it rules out, then any section left empty), or one in a closed
20575
+ // section, has left the page too: focus goes to the title.
20576
+ const card = anchor.closest('.ws-card');
20577
+ if (!card || card.hidden || card.closest('details.wf-section:not([open])')) {
20578
+ closeWorkflowCardMenu(false, $wfLanding.querySelector('#wf-landing-title'));
20579
+ return;
20580
+ }
20581
+ // Renamed elsewhere, or a draft that gained its file: rebuild the items, so they name it and offer what it has now.
20582
+ if (anchor.dataset.wfKebabName !== wfCardMenuFor.name || (anchor.dataset.wfKebabNoCopy !== '1') !== wfCardMenuFor.canCopy) {
20583
+ openWorkflowCardMenu(anchor, $wfCardMenu.contains(document.activeElement));
20584
+ } else placeWorkflowCardMenu(anchor);
20585
+ }
20586
+ function openWorkflowCardMenu(anchor, focusFirst = false) {
20587
+ if (!$wfCardMenu) return;
20588
+ closeWorkflowCardMenu(false);
20589
+ const d = anchor.dataset;
20590
+ wfCardMenuFor = { key: d.wfKebab, name: d.wfKebabName, canCopy: d.wfKebabNoCopy !== '1' };
20591
+ const { key, name } = wfCardMenuFor;
20592
+ // Each item's Instructor carrier is passed whole by its caller: a command id is never assembled from parts.
20593
+ const item = (act, carrier, text) => `<button type="button" class="menu-item" role="menuitem" tabindex="-1" data-wf-card-act="${act}" ${carrier}`
20594
+ + ` data-command-instance-label="${escapeAttr(name)}"><span class="menu-label">${escapeHtml(text)}</span></button>`;
20595
+ $wfCardMenu.setAttribute('aria-label', `Actions for ${name}`);
20596
+ $wfCardMenu.innerHTML = item('rename', `data-command-id="shell.workflows-landing-rename#${escapeAttr(key)}"`, 'Rename…')
20597
+ + (wfCardMenuFor.canCopy ? item('duplicate', `data-command-id="shell.workflows-landing-duplicate#${escapeAttr(key)}"`, 'Duplicate') : '')
20598
+ + '<div class="menu-divider" role="separator"></div>' + item('archive', `data-command-id="shell.workflows-landing-archive#${escapeAttr(key)}"`, 'Archive');
20599
+ document.dispatchEvent(new Event('floless:passive-overlay-yield'));
20600
+ $wfCardMenu.hidden = false;
20601
+ $wfCardMenu.classList.add('show');
20602
+ placeWorkflowCardMenu(anchor);
20603
+ if (focusFirst) $wfCardMenu.querySelector('.menu-item')?.focus();
20604
+ }
20605
+ if ($wfCardMenu) {
20606
+ $wfCardMenu.addEventListener('click', (event) => {
20607
+ const act = event.target.closest('[data-wf-card-act]');
20608
+ if (!act || !wfCardMenuFor) return;
20609
+ const t = wfCardMenuFor;
20610
+ closeWorkflowCardMenu(true);
20611
+ const which = act.dataset.wfCardAct;
20612
+ // The dialogs report their own failures; this catches one that escapes them (before their try), so a click never
20613
+ // ends in silence.
20614
+ const run = (pending, what) => Promise.resolve(pending).catch((error) => reportErr(error, what));
20615
+ if (which === 'rename') void run(renameOwnedWorkflow(t.key, t.name), 'rename this workflow');
20616
+ else if (which === 'duplicate') void run(copyOwnedWorkflow(t.key, t.name), 'copy this workflow');
20617
+ else if (which === 'archive') {
20618
+ // An archived card and its ⋯ are gone after the repaint: focus goes to the Your workflows heading (which now
20619
+ // counts one fewer), or the page title once that section is empty. Cancel leaves focus on the ⋯, so it is untouched.
20620
+ void run(archiveOwnedWorkflow(t.key, t.name), 'archive this workflow').then(() => {
20621
+ if (!wfLanding || document.activeElement !== document.body) return;
20622
+ ($wfLanding.querySelector('.wf-section[data-wf-section="yours"] > summary') || $wfLanding.querySelector('#wf-landing-title'))?.focus();
20623
+ });
20624
+ }
20625
+ });
20626
+ $wfCardMenu.addEventListener('keydown', (event) => {
20627
+ // A shortcut (Ctrl+R Routines, Ctrl+G…) opens its own surface without moving focus: close the menu first and let
20628
+ // the shortcut through, so the next Escape reaches that surface instead of this menu.
20629
+ if (event.ctrlKey || event.metaKey || event.altKey) { closeWorkflowCardMenu(false); return; }
20630
+ const items = [...$wfCardMenu.querySelectorAll('.menu-item')];
20631
+ const at = items.indexOf(document.activeElement);
20632
+ if (event.key === 'Escape' || event.key === 'Tab') {
20633
+ event.preventDefault(); event.stopPropagation(); closeWorkflowCardMenu(true);
20634
+ } else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
20635
+ event.preventDefault();
20636
+ const step = event.key === 'ArrowDown' ? 1 : -1;
20637
+ items[(at + step + items.length) % items.length]?.focus();
20638
+ } else if (event.key === 'Home' || event.key === 'End') {
20639
+ event.preventDefault();
20640
+ items[event.key === 'Home' ? 0 : items.length - 1]?.focus();
20641
+ }
20642
+ });
20643
+ // The menu follows focus: it closes once focus moves anywhere but the menu or its own ⋯ (Tab to another card, a
20644
+ // dialog or a shortcut taking focus), so it never stays open under something else.
20645
+ document.addEventListener('focusin', (event) => {
20646
+ if (!$wfCardMenu.hidden && !$wfCardMenu.contains(event.target) && event.target !== workflowCardMenuAnchor()) closeWorkflowCardMenu(false);
20647
+ });
20648
+ // Focus is normally inside the open menu, whose own handler takes Escape. When it is on the ⋯ itself or nowhere (a
20649
+ // click on the divider), Escape still closes the menu. Capture phase, so nothing under the menu takes that Escape.
20650
+ document.addEventListener('keydown', (event) => {
20651
+ if (event.key !== 'Escape' || $wfCardMenu.hidden || document.querySelector('.modal-backdrop.show')) return;
20652
+ if (event.target !== document.body && event.target !== workflowCardMenuAnchor()) return;
20653
+ event.preventDefault(); event.stopPropagation(); closeWorkflowCardMenu(true);
20654
+ }, true);
20655
+ document.addEventListener('mousedown', (event) => {
20656
+ if ($wfCardMenu.hidden) return;
20657
+ if (!$wfCardMenu.contains(event.target) && !event.target.closest?.('[data-wf-kebab]')) closeWorkflowCardMenu(false);
20658
+ });
20659
+ window.addEventListener('resize', () => closeWorkflowCardMenu(false));
20660
+ // A scroll that moves the ⋯ (the card list, or the whole page in the narrow layout) would leave the fixed menu hanging
20661
+ // away from it, so it closes the menu. A scroll that does not move it is ignored: AI Chat streaming beside the page,
20662
+ // the page's own scroll a moment after coming back to Workflows, a scroll that had already landed when the ⋯ was
20663
+ // clicked. 2px of slack: the card's hover lift moves the ⋯ 1px when the pointer goes into the menu. Focus that was
20664
+ // in the menu or on the ⋯ goes to the Workflows title: in the sticky heading it stays in view; in the narrow layout,
20665
+ // where the whole page scrolls, it is the top of the page, with the search box next in Tab order.
20666
+ document.addEventListener('scroll', (event) => {
20667
+ if ($wfCardMenu.hidden || $wfCardMenu.contains(event.target)) return;
20668
+ const anchor = workflowCardMenuAnchor();
20669
+ const at = wfCardMenuFor?.placedAt;
20670
+ const r = anchor?.getBoundingClientRect();
20671
+ if (anchor && at && Math.abs(r.top - at.top) <= 2 && Math.abs(r.left - at.left) <= 2) return;
20672
+ closeWorkflowCardMenu(false, $wfLanding.querySelector('#wf-landing-title'));
20673
+ }, true);
20674
+ }
20675
+
19653
20676
  function renderWorkflowsLanding() {
19654
20677
  if (!$wfLanding) return;
20678
+ if (wfLandingTab !== 'workflows') syncWorkflowCardMenu(); // the card ⋯ menu lives on the Workflows tab only
19655
20679
  if (wfLandingTab === 'pages') { renderWorkflowsPagesTab(); return; }
19656
20680
  if (wfLandingTab === 'history') { renderWorkflowsHistoryTab(); return; }
19657
20681
  const focusedTab = document.activeElement?.closest?.('#wf-landing [data-wf-tab]')?.dataset.wfTab || null;
@@ -19660,6 +20684,7 @@
19660
20684
  const keepCaret = search ? [search.selectionStart, search.selectionEnd] : null;
19661
20685
  const clearFocused = document.activeElement?.id === 'wf-search-clear';
19662
20686
  const focusedDraft = document.activeElement?.closest?.('#wf-landing [data-wf-draft]')?.dataset.wfDraft || null;
20687
+ const focusedKebab = document.activeElement?.closest?.('#wf-landing [data-wf-kebab]')?.dataset.wfKebab || null;
19663
20688
  const focusedRestore = document.activeElement?.closest?.('[data-wf-restore]')?.dataset.wfRestore || null;
19664
20689
  // Every section (Your workflows, Installed, Archived) is the same disclosure, and each keeps its open state across
19665
20690
  // repaints (apps-changed, search, restore, coming back to the tab); focus on a card inside implies open. Focus on
@@ -19675,6 +20700,8 @@
19675
20700
  const focusedRestored = document.activeElement?.closest?.('[data-wf-restored]')?.dataset.wfRestored || null;
19676
20701
  // #2866: a background repaint (apps-changed, routines) must not drop a keyboard user off the Sort by controls.
19677
20702
  const focusedSort = document.activeElement?.closest?.('#wf-landing .ls-sort button')?.id || null;
20703
+ // The page title takes focus when the landing opens and when a scroll closes a card menu; keep it across a repaint.
20704
+ const titleFocused = document.activeElement?.id === 'wf-landing-title';
19678
20705
  const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
19679
20706
  // #2866: the page's Sort by choice orders the cards inside each section; the sections keep their order. Your own
19680
20707
  // workflows carry FloLess's record of when they were created and last changed (made, compiled, renamed, archived);
@@ -19715,6 +20742,13 @@
19715
20742
  // C12 (#1337): owned workflows whose installed copy AWARE could not read show as drafts that need compiling again.
19716
20743
  const unreadableOwned = new Set(wfUnreadable.map((row) => row.workflowId).filter(Boolean));
19717
20744
  const unreadableNote = unreadableWorkflowsNoteHtml(wfUnreadable, esc);
20745
+ // The ⋯ on a card of a workflow of yours (openWorkflowCardMenu): Rename… / Duplicate / Archive. The menu reads what it
20746
+ // acts on from these attributes. A draft with no workflow file yet has nothing to copy, so it is not offered Duplicate.
20747
+ // Installed cards get none (#3182).
20748
+ const kebabHtml = (workflowId, name, canCopy = true) =>
20749
+ `<button type="button" class="ws-kebab wf-kebab" data-wf-kebab="${esc(workflowId)}" data-wf-kebab-name="${esc(name)}"${canCopy ? '' : ' data-wf-kebab-no-copy="1"'}`
20750
+ + ` data-command-id="shell.workflows-landing-actions#${esc(workflowId)}" data-command-instance-label="${esc(name)}"`
20751
+ + ` aria-label="Actions for ${esc(name)}" aria-haspopup="menu" aria-expanded="false" data-tip="${canCopy ? 'Rename · Duplicate · Archive' : 'Rename · Archive'}">⋯</button>`;
19718
20752
  const draftCard = (row) => {
19719
20753
  const recompile = Boolean(row.activePublication);
19720
20754
  const name = row.displayName;
@@ -19723,19 +20757,22 @@
19723
20757
  return `<div class="ws-card wf-card wf-card-draft" role="button" tabindex="0" data-wf-draft="${esc(row.workflowId)}" data-command-id="shell.workflows-landing-open-draft#${esc(name)}" data-command-instance-label="${esc(name)}">`
19724
20758
  + `<div class="ws-body"><div class="wf-card-text"><span class="ws-kind wf-kind is-draft">${chip}</span>`
19725
20759
  + `<div class="ws-name">${esc(name)}</div><div class="ws-meta">${esc(meta)}</div>`
19726
- + (dateLine(row) ? `<div class="ws-meta wf-card-nodes">${esc(dateLine(row))}</div>` : '') + `</div></div></div>`;
20760
+ + (dateLine(row) ? `<div class="ws-meta wf-card-nodes">${esc(dateLine(row))}</div>` : '') + `</div>`
20761
+ + kebabHtml(row.workflowId, name, Boolean(row.hasSource)) + `</div></div>`;
19727
20762
  };
19728
20763
  const card = (row) => {
19729
20764
  const ownedRow = row.ownedWorkflow;
19730
20765
  const name = ownedRow ? ownedRow.displayName : (row.displayName || row.name || row.id);
19731
20766
  const chip = ownedRow ? 'Yours' : 'Installed';
19732
- const where = ownedRow ? (row.ownerLabel || 'Standalone') : (PROVIDER_LABELS[row.provider] || 'Installed workflow');
20767
+ const where = ownedRow ? (row.ownerLabel || 'Standalone') : 'Installed workflow'; // #3234: what it needs is on the next line
19733
20768
  const scheduledTip = scheduledRoutineTip(routinesData, row.id);
19734
20769
  return `<div class="ws-card wf-card" role="button" tabindex="0" data-wf-id="${esc(row.id)}" data-command-id="shell.workflows-landing-open#${esc(name)}" data-command-instance-label="${esc(name)}">`
19735
20770
  + `<div class="ws-body"><div class="wf-card-text"><span class="ws-kind wf-kind">${chip}</span>`
19736
20771
  + (scheduledTip ? `<span class="ws-kind wf-kind wf-scheduled" data-tip="${esc(scheduledTip)}">Scheduled</span>` : '')
19737
20772
  + `<div class="ws-name">${esc(name)}</div><div class="ws-meta">${esc(where)}</div>`
19738
- + `<div class="ws-meta wf-card-nodes">${esc(workflowCardMeta(row) + (dateLine(row) ? ` · ${dateLine(row)}` : ''))}</div></div></div></div>`;
20773
+ + `<div class="ws-meta wf-card-nodes">${esc(workflowCardMeta(row) + (dateLine(row) ? ` · ${dateLine(row)}` : ''))}</div>`
20774
+ + `${workflowCardAwareLine(row)}</div>`
20775
+ + (ownedRow ? kebabHtml(ownedRow.workflowId, name) : '') + `</div></div>`;
19739
20776
  };
19740
20777
  // One section: a disclosure whose summary names it and counts its cards. Your workflows and Installed start open,
19741
20778
  // Archived starts closed; a section the person opened or closed stays that way (keptSections). The summary's
@@ -19772,14 +20809,19 @@
19772
20809
  if (focusedTab) $wfLanding.querySelector(`[data-wf-tab="${focusedTab}"]`)?.focus();
19773
20810
  if (focusedId) $wfLanding.querySelector(`[data-wf-id="${CSS.escape(focusedId)}"]`)?.focus();
19774
20811
  if (focusedDraft) $wfLanding.querySelector(`[data-wf-draft="${CSS.escape(focusedDraft)}"]`)?.focus();
20812
+ if (focusedKebab) $wfLanding.querySelector(`[data-wf-kebab="${CSS.escape(focusedKebab)}"]`)?.focus();
19775
20813
  if (focusedRestore) $wfLanding.querySelector(`[data-wf-restore="${CSS.escape(focusedRestore)}"]:not(:disabled)`)?.focus();
19776
20814
  if (focusedRestored) $wfLanding.querySelector(`[data-wf-restored="${CSS.escape(focusedRestored)}"]`)?.focus();
19777
20815
  if (focusedSort) $wfLanding.querySelector(`#${CSS.escape(focusedSort)}`)?.focus({ preventScroll: true });
20816
+ if (titleFocused) $wfLanding.querySelector('#wf-landing-title')?.focus({ preventScroll: true });
19778
20817
  // #2603: project-workflows.js paints the set-apart folders it owns the answers for (globalThis: harnesses lack it).
19779
20818
  globalThis.flolessProjectWorkflows?.renderLandingSetApart?.($wfLanding.querySelector('.wf-setapart-slot'), wfSetApart, () => loadApps());
19780
20819
  if (keepCaret) $wfLanding.querySelector('#wf-landing-search')?.focus();
19781
20820
  applyWorkflowsLandingSearch(keepCaret);
19782
20821
  if (clearFocused) $wfLanding.querySelector('#wf-search-clear')?.focus(); // it only exists once the filter ran
20822
+ // Last, once the search filter and the set-apart folders have painted: the open card menu is measured and placed
20823
+ // against the cards as they finally sit, or closed if the filter hid its card.
20824
+ syncWorkflowCardMenu();
19783
20825
  }
19784
20826
 
19785
20827
  /** Hide the workflow cards that don't match the landing search: every typed word must appear somewhere in the
@@ -20107,6 +21149,13 @@
20107
21149
  if (event.target.closest('[data-wf-new]')) { requestNewWorkflow(); return; }
20108
21150
  // Clearing empties the message the button sits in, so focus goes back to the search box.
20109
21151
  if (event.target.closest('#wf-search-clear')) { setWorkflowsLandingQuery(''); $wfLanding.querySelector('#wf-landing-search')?.focus(); return; }
21152
+ const kebab = event.target.closest('[data-wf-kebab]');
21153
+ if (kebab) {
21154
+ // A click opens with focus on the first item, as Enter does, so Tab, the arrows and Escape work straight away.
21155
+ if (wfCardMenuFor?.key === kebab.dataset.wfKebab) closeWorkflowCardMenu(true);
21156
+ else openWorkflowCardMenu(kebab, true);
21157
+ return;
21158
+ }
20110
21159
  const draftEl = event.target.closest('[data-wf-draft]');
20111
21160
  if (draftEl) { if (!landingOpening) openDraftWorkflow(draftEl.dataset.wfDraft); return; }
20112
21161
  const cardEl = event.target.closest('[data-wf-id]');
@@ -20133,6 +21182,13 @@
20133
21182
  setWorkflowsLandingTab(order[to], true);
20134
21183
  return;
20135
21184
  }
21185
+ // Opening the ⋯ menu from the keyboard puts focus on its first item, so the arrows work straight away.
21186
+ const kebab = event.target.closest?.('[data-wf-kebab]');
21187
+ if (kebab && (event.key === 'Enter' || event.key === ' ' || event.key === 'ArrowDown')) {
21188
+ event.preventDefault();
21189
+ openWorkflowCardMenu(kebab, true);
21190
+ return;
21191
+ }
20136
21192
  if (event.key !== 'Enter' && event.key !== ' ') return;
20137
21193
  const target = event.target.closest('[data-wf-id], [data-wf-new], [data-wf-draft]');
20138
21194
  if (!target || target !== event.target) return;
@@ -20216,26 +21272,26 @@
20216
21272
  // opened after the run) holds a different one or none. Say so instead of showing the wrong report.
20217
21273
  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.';
20218
21274
  const cached = lastReportByApp.get(appId);
20219
- if (!runId) throw new Error(gone);
21275
+ if (!runId) throw Object.assign(new Error(gone), { forPerson: true });
20220
21276
  // #2266: a window opened (or reloaded) after the run reads the copy FloLess kept of THAT run's report, in the
20221
21277
  // workflow's Page. Never another run's: a report no longer kept says so.
20222
21278
  if (cached?.runId !== runId) {
20223
21279
  let kept = null;
20224
21280
  try { kept = await api(`/api/pages/workflow?app=${encodeURIComponent(appId)}&run=${encodeURIComponent(runId)}`); }
20225
- 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.'); }
21281
+ catch { throw Object.assign(new Error('FloLess couldn’t read that run’s report just now. Try again, or open the workflow to see its latest results.'), { forPerson: true }); }
20226
21282
  if (kept?.home && kept.page?.id && kept.shown?.kept === true) {
20227
- 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.');
21283
+ if (typeof window.flolessPages?.open !== 'function') throw Object.assign(new Error('FloLess kept that run’s report, but this window cannot open Pages. Open it from the Pages list.'), { forPerson: true });
20228
21284
  return await window.flolessPages.open(kept.home, kept.page.id, kept.shown.version);
20229
21285
  }
20230
- throw new Error(kept?.shown?.note
21286
+ throw Object.assign(new Error(kept?.shown?.note
20231
21287
  ? `${kept.shown.note} Open the workflow to see its latest results.`
20232
- : 'FloLess did not keep a copy of that run’s report. Open the workflow to see its latest results.');
21288
+ : 'FloLess did not keep a copy of that run’s report. Open the workflow to see its latest results.'), { forPerson: true });
20233
21289
  }
20234
21290
  await this.openApp(appId);
20235
21291
  // Opening the workflow waits; a newer report may have arrived meanwhile. Show this run's report or nothing.
20236
- if (lastReportByApp.get(appId) !== cached) throw new Error(gone);
21292
+ if (lastReportByApp.get(appId) !== cached) throw Object.assign(new Error(gone), { forPerson: true });
20237
21293
  const nodeId = reportNodeId();
20238
- if (!nodeId) throw new Error('This workflow has no report view, so there is nothing to open. Its results are in the workflow.');
21294
+ if (!nodeId) throw Object.assign(new Error('This workflow has no report view, so there is nothing to open. Its results are in the workflow.'), { forPerson: true });
20239
21295
  showReport(nodeId);
20240
21296
  return true;
20241
21297
  },
@@ -20247,13 +21303,13 @@
20247
21303
  await window.flolessWorkspaces?.setMode?.('workflows');
20248
21304
  // The switch can stay on the current tab (another workflow's read failed): never focus a card nobody can see.
20249
21305
  if (document.body.classList.contains('mode-workspaces') || document.body.classList.contains('mode-agents')) {
20250
- throw new Error('FloLess could not switch to the Workflows tab just now. Open it and find the workflow under Archived.');
21306
+ throw Object.assign(new Error('FloLess could not switch to the Workflows tab just now. Open it and find the workflow under Archived.'), { forPerson: true });
20251
21307
  }
20252
21308
  // The list is what is needed here, not any one workflow: a reload that fails keeps the list already on screen.
20253
21309
  try { await loadApps(); } catch (error) { console.warn('[project-access] the workflow list could not be read again', error); }
20254
21310
  showWorkflowsLanding(true);
20255
21311
  const card = [...($wfLanding?.querySelectorAll('[data-wf-archived]') || [])].find((el) => el.getAttribute('data-wf-archived') === workflowId);
20256
- 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.');
21312
+ if (!card) throw Object.assign(new Error('That workflow is no longer in the Archived list, so FloLess cannot show it. It may have been restored or removed.'), { forPerson: true });
20257
21313
  const box = card.closest('.wf-archived');
20258
21314
  if (box) box.open = true;
20259
21315
  card.scrollIntoView?.({ block: 'center' });
@@ -20272,13 +21328,13 @@
20272
21328
  // #2185: a draft built a moment ago is not in the cached list yet: read it once more before saying it is gone.
20273
21329
  if (!wfOwned.some((row) => row.workflowId === workflowId)) {
20274
21330
  try { ({ workflows: wfOwned } = await api('/api/workflows/owned')); }
20275
- catch { throw new Error('FloLess couldn’t load your workflows just now. Try again, or open it from the Workflows page.'); }
21331
+ catch { throw Object.assign(new Error('FloLess couldn’t load your workflows just now. Try again, or open it from the Workflows page.'), { forPerson: true }); }
20276
21332
  }
20277
21333
  if (wfOwned.some((row) => row.workflowId === workflowId && row.status !== 'archived')) {
20278
21334
  openDraftWorkflow(workflowId);
20279
21335
  return true;
20280
21336
  }
20281
- throw new Error('That workflow is no longer here, so its conversation can’t be opened.');
21337
+ throw Object.assign(new Error('That workflow is no longer here, so its conversation can’t be opened.'), { forPerson: true });
20282
21338
  },
20283
21339
  // The New project dialog's AI choice (#1605): the installed Claude/Codex rows as last read, and
20284
21340
  // a fresh read of them. The same shared runtime state preferredChatProvider() answers from, so
@@ -20386,6 +21442,8 @@
20386
21442
  // writer — the workflow combo keeps updating underneath in Workspaces mode). Pass the open
20387
21443
  // project's name, 'Workspaces' on the landing, or null to hand the tab back to the workflow.
20388
21444
  setWorkspaceTitle(name, landing = false, projectId = null, kind = null) {
21445
+ // Every mode switch ends here; a name means Workspaces or Agents is on screen, where no workflow card is.
21446
+ if (name) closeWorkflowCardMenu(false);
20389
21447
  wsTitleName = name || null;
20390
21448
  wsTitleKind = wsTitleName && kind === 'agents' ? 'agents' : null;
20391
21449
  wsTitleLanding = !!(wsTitleName && landing);