@floless/app 0.158.0 → 0.160.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 (43) hide show
  1. package/dist/floless-server.cjs +140655 -117708
  2. package/dist/schemas/drawing-check.profile.v1.schema.json +33 -1
  3. package/dist/schemas/steel.model.v2.schema.json +1 -0
  4. package/dist/skills/floless-app-actions/SKILL.md +23 -5
  5. package/dist/skills/floless-app-bridge/SKILL.md +5 -3
  6. package/dist/skills/floless-app-onboarding/SKILL.md +69 -5
  7. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +8 -6
  8. package/dist/skills/floless-app-queue/SKILL.md +3 -1
  9. package/dist/skills/floless-app-rfi/SKILL.md +29 -1
  10. package/dist/skills/floless-app-steel-model/SKILL.md +11 -5
  11. package/dist/skills/floless-app-steel-takeoff/SKILL.md +28 -8
  12. package/dist/skills/floless-app-workflows/SKILL.md +6 -3
  13. package/dist/web/agents.js +12 -5
  14. package/dist/web/app.css +266 -159
  15. package/dist/web/app.js +23 -51
  16. package/dist/web/aware.js +533 -546
  17. package/dist/web/chat-question-card.js +24 -1
  18. package/dist/web/chat.css +170 -48
  19. package/dist/web/chat.js +1406 -208
  20. package/dist/web/commands-shell.js +1104 -177
  21. package/dist/web/commands-steel.js +2 -0
  22. package/dist/web/drawing-check-editor.html +10 -0
  23. package/dist/web/drawing-check-editor.js +44 -0
  24. package/dist/web/guide.js +12 -2
  25. package/dist/web/index.html +62 -48
  26. package/dist/web/instructor.js +33 -12
  27. package/dist/web/pages.js +186 -31
  28. package/dist/web/panels.js +19 -1
  29. package/dist/web/project-access.js +67 -8
  30. package/dist/web/project-modules.js +474 -0
  31. package/dist/web/project-rfis.js +715 -0
  32. package/dist/web/project-workflows.js +506 -0
  33. package/dist/web/run-history.js +198 -0
  34. package/dist/web/run-page-view.js +12 -2
  35. package/dist/web/steel-3d-core.js +75 -1
  36. package/dist/web/steel-3d-view.js +8 -38
  37. package/dist/web/steel-editor.html +263 -59
  38. package/dist/web/steel-model-v2-projection.js +7 -0
  39. package/dist/web/workspace-root-recovery.js +119 -0
  40. package/dist/web/workspaces.js +493 -161
  41. package/launch-starting-page.mjs +5 -2
  42. package/launch.mjs +136 -78
  43. package/package.json +6 -1
package/dist/web/aware.js CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Loaded AFTER app.js, so it shares its globals (PROMPTS, AGENTS, state,
5
5
  * renderTopology, renderInspect, selectAgent, renderChat, $promptSel, $runBtn,
6
- * escapeHtml, showToast, appendNarration). It mutates PROMPTS/AGENTS from real
6
+ * escapeHtml, showToast). It mutates PROMPTS/AGENTS from real
7
7
  * /api data and reuses the existing renderers — the canvas stays the demo's.
8
8
  *
9
9
  * The UI never becomes the brain: it reads AWARE state, triggers `aware` verbs
@@ -74,7 +74,11 @@
74
74
  const workflowOwners = new Map();
75
75
  function ownedWorkflowOf(id) { return (id && workflowOwners.get(id)) || null; }
76
76
  /** What a workflow is called on screen: an owned workflow's own name, never its runtime app id (#1890 PR 3b-0). */
77
- function workflowLabelOf(id) { return ownedWorkflowOf(id)?.ownedWorkflow?.displayName || id; }
77
+ function workflowLabelOf(id) {
78
+ const name = ownedWorkflowOf(id)?.ownedWorkflow?.displayName || id;
79
+ // #2644: the picker trigger says a locked module workflow is locked, whichever path chose it.
80
+ return lockedWorkflowMessage(wfLibrary.find((item) => item.id === id)) ? `${name} · locked` : name;
81
+ }
78
82
  function rememberWorkflowOwners(list) {
79
83
  workflowOwners.clear();
80
84
  for (const row of list) {
@@ -634,7 +638,7 @@
634
638
  const userText = escapeHtml(app.description?.trim()
635
639
  ? app.description.trim().split('\n')[0]
636
640
  : `${app.displayName} — ${app.nodes.length} node${app.nodes.length === 1 ? '' : 's'}.`);
637
- // Escape interpolated values (not the literal **/`` markup, which mdInline renders).
641
+ // Escape interpolated values (not the literal **/`` markup, which is authored).
638
642
  const narration = [
639
643
  `Reading **${escapeHtml(app.name)}** from \`~/.aware/apps/${escapeHtml(app.id)}\` — the canvas is a view of the real \`.flo\`.`,
640
644
  ...app.nodes.map((n) => `**${escapeHtml(n.id)}** → \`${escapeHtml(n.agent || n.kind)}${n.command ? '/' + escapeHtml(n.command) : ''}\` · ${escapeHtml(n.mode)}`),
@@ -1533,250 +1537,7 @@
1533
1537
  });
1534
1538
  }
1535
1539
 
1536
- // ── Per-workflow onboarding beacon ──────────────────────────────────────────
1537
- // "New to you" = the user hasn't completed a first real Run of this workflow and
1538
- // hasn't dismissed its guide. Three bits per app id, persisted per origin; all
1539
- // default false, so every workflow starts new. Never touches the .flo or lock.
1540
- const LS_GUIDE = 'floless:guide';
1541
- function guideStateAll() {
1542
- try { const v = JSON.parse(localStorage.getItem(LS_GUIDE) || '{}'); return (v && typeof v === 'object') ? v : {}; }
1543
- catch { return {}; }
1544
- }
1545
- function guideFor(id) { return guideStateAll()[id] || {}; }
1546
- function setGuide(id, patch) {
1547
- if (!id) return;
1548
- try {
1549
- const all = guideStateAll();
1550
- all[id] = { ...(all[id] || {}), ...patch };
1551
- localStorage.setItem(LS_GUIDE, JSON.stringify(all));
1552
- } catch { /* private mode / quota */ }
1553
- }
1554
- // The beacon pulses while a workflow is new to the user.
1555
- function beaconIsNew(id) { const g = guideFor(id); return !g.firstRunDone && !g.dismissed; }
1556
-
1557
- // ── Workspaces variant of the SAME beacon ───────────────────────────────────
1558
- // Workspaces is the DOCUMENT archetype (drop → review → approve → export), not the
1559
- // pipeline archetype (inputs → compile → run). One beacon element, two content
1560
- // sources: in Workspaces mode with a project open, this layer drives #guide-beacon +
1561
- // #guide-modal instead of the workflow layer. It REUSES the LS_GUIDE store and its
1562
- // get/set helpers — no parallel system — but keys its record under `ws:<app>` so a
1563
- // Workflows Run of an app (firstRunDone) never calms its Workspaces beacon and vice
1564
- // versa (vectorize is BOTH a pipeline app and a workspace app). "New" here calms on the
1565
- // first Approve for the app, mirroring how the workflow beacon calms on the first Run.
1566
- // workspaces.js owns the project state, so it hands us a small snapshot (app id + which
1567
- // lifecycle signals are true) via flolessBridge; we own the chrome, glyphs, and copy.
1568
- let wsGuideCtx = null; // { app, name, displayName, approved, exported } | null (name = the open project's name)
1569
- const wsGuideKey = (app) => `ws:${app}`;
1570
1540
  const inWorkspacesMode = () => { const a = document.getElementById('app'); return !!(a && a.classList.contains('mode-workspaces')); };
1571
- // The Workspaces beacon is active only in Workspaces mode with a project open (a ctx set).
1572
- const wsGuideActive = () => inWorkspacesMode() && !!wsGuideCtx;
1573
- function wsBeaconIsNew(app) { const g = guideFor(wsGuideKey(app)); return !g.approveDone && !g.dismissed; }
1574
-
1575
- // The document-lifecycle checklist. Approve/Export carry an honest boolean from project
1576
- // state; "Review" borrows Approve's boolean (you can't sign off without having looked —
1577
- // Approve sits next to the editor), never a faked "opened the tab" signal; "Drop" is
1578
- // done whenever the guide is open (a project only exists after a drawing was dropped —
1579
- // a cancelled/failed drop is rolled back, never left as an empty project). The current
1580
- // step = the first not-done row, so the arrow lands on the next real action.
1581
- function workspaceGuideSteps(ctx) {
1582
- return [
1583
- { label: 'Drop a drawing', note: 'PDF or image — traced linework comes out editable', done: true },
1584
- { label: 'Review the traced lines', note: 'check layers, isolate low-confidence traces', done: !!ctx.approved },
1585
- { label: 'Approve', note: 'signs off this version, unlocks Export', done: !!ctx.approved },
1586
- { label: 'Export SVG', note: 'clean SVG linework, take it anywhere', done: !!ctx.exported },
1587
- ];
1588
- }
1589
-
1590
- // Paint #guide-beacon for the open workspace project (called by paintBeacon when in
1591
- // Workspaces mode). Same glyphs/label/pulse dialect as the workflow beacon; names the
1592
- // open PROJECT (not the app id), matching the crumb/picker.
1593
- function paintWorkspaceBeacon() {
1594
- const $b = document.getElementById('guide-beacon');
1595
- if (!$b) return;
1596
- const ctx = wsGuideCtx;
1597
- if (!ctx) { $b.hidden = true; $b.classList.remove('is-new', 'spotlit'); return; }
1598
- const isNew = wsBeaconIsNew(ctx.app);
1599
- $b.hidden = false;
1600
- $b.classList.remove('spotlit');
1601
- $b.classList.toggle('is-new', isNew);
1602
- const ico = $b.querySelector('.guide-beacon-ico');
1603
- const label = $b.querySelector('.guide-beacon-label');
1604
- if (ico) ico.textContent = isNew ? '✦' : '?';
1605
- // #2046: "Guide" is the onboarding agent now; at rest this beacon is about the open project.
1606
- if (label) label.textContent = isNew ? 'Start here' : 'About this project';
1607
- // No "workflow"/"Run" vocabulary — this is a document project.
1608
- $b.dataset.tip = isNew
1609
- ? 'New here? See what this project does and how to take it from drawing to export.'
1610
- : 'See what this project does and how to use it.';
1611
- $b.setAttribute('aria-label', (isNew ? 'Start here — about ' : 'About ') + (ctx.name || ctx.displayName || ctx.app));
1612
- }
1613
-
1614
- function paintBeacon(app) {
1615
- // In Workspaces mode the beacon belongs to the open project, not the last-loaded
1616
- // workflow — hand off to the workspace layer (which hides it when no project is open).
1617
- if (inWorkspacesMode()) { paintWorkspaceBeacon(); return; }
1618
- const $b = document.getElementById('guide-beacon');
1619
- if (!$b) return;
1620
- if (!app) { $b.hidden = true; $b.classList.remove('is-new', 'spotlit'); return; }
1621
- const isNew = beaconIsNew(app.id);
1622
- $b.hidden = false;
1623
- $b.classList.toggle('is-new', isNew);
1624
- const ico = $b.querySelector('.guide-beacon-ico');
1625
- const label = $b.querySelector('.guide-beacon-label');
1626
- // Monochrome dingbats (✦ / ?), not colour emoji — the locked baseline uses text
1627
- // glyphs (★, ▸); the pulse, not an emoji, is the "new" signal.
1628
- if (ico) ico.textContent = isNew ? '✦' : '?';
1629
- // #2046: "Guide" is the onboarding agent now; at rest this beacon is about the open workflow.
1630
- if (label) label.textContent = isNew ? 'Start here' : 'About this workflow';
1631
- $b.dataset.tip = isNew
1632
- ? 'New here? See what this workflow does and how to run it.'
1633
- : 'See what this workflow does and how to run it.';
1634
- $b.setAttribute('aria-label', (isNew ? 'Start here — about ' : 'About ') + (app.displayName || app.id));
1635
- }
1636
-
1637
- // Record a completed real run → the workflow is no longer new; calm the beacon (and
1638
- // refresh an open guide so the Run step ticks). Idempotent.
1639
- function markFirstRunDone(id) {
1640
- if (!id || guideFor(id).firstRunDone) return;
1641
- setGuide(id, { firstRunDone: true });
1642
- if (id === currentId) {
1643
- const app = apps.get(id);
1644
- if (app) paintBeacon(app);
1645
- const $m = document.getElementById('guide-modal');
1646
- if ($m && $m.classList.contains('show')) renderGuide();
1647
- }
1648
- }
1649
-
1650
- // The guide panel's live checklist — each step ticks from real app state. The
1651
- // "Set inputs" row is omitted for a workflow with no declared inputs.
1652
- function guideSteps(app) {
1653
- const steps = [];
1654
- if (Array.isArray(app.inputs) && app.inputs.length) {
1655
- const vals = currentInputs();
1656
- const allSet = app.inputs.every((i) => {
1657
- const v = vals[i.name];
1658
- return v !== undefined && v !== null && String(v).trim() !== '';
1659
- });
1660
- steps.push({ label: 'Set inputs', note: 'the values this workflow runs with', done: allSet });
1661
- }
1662
- steps.push({ label: 'Compile', note: 'freeze the approved lock', done: gateStateFor(app) === 'ready' });
1663
- steps.push({ label: 'Run', note: 'against the live host — results render here', done: !!guideFor(app.id).firstRunDone });
1664
- return steps;
1665
- }
1666
-
1667
- // Shared checklist renderer — shape carries state (✓ done · → current · ☐ to-do), never
1668
- // colour alone. The current step is the first not-done row. Labels/notes are authored
1669
- // constants but still pass escapeHtml (defence-in-depth; the security hook forbids raw
1670
- // string→DOM). Both the workflow and workspace guides render through this.
1671
- function guideStepsHtml(steps) {
1672
- const curIdx = steps.findIndex((s) => !s.done);
1673
- return `<ol class="guide-steps" role="list">${steps.map((s, i) => {
1674
- const state = s.done ? 'done' : i === curIdx ? 'current' : 'todo';
1675
- const box = s.done ? '✓' : i === curIdx ? '→' : '☐';
1676
- const cur = i === curIdx ? ' aria-current="step"' : '';
1677
- return `<li class="guide-step ${state}"${cur}><span class="guide-box" aria-hidden="true">${box}</span>` +
1678
- `<span class="guide-step-text"><span class="guide-step-label">${escapeHtml(s.label)}</span> ` +
1679
- `<span class="guide-step-note">— ${escapeHtml(s.note)}</span></span>` +
1680
- `<span class="sr-only">${s.done ? '(done)' : i === curIdx ? '(next step)' : '(to do)'}</span></li>`;
1681
- }).join('')}</ol>`;
1682
- }
1683
-
1684
- // The Workspaces guide body — the document life-cycle, not node mechanics. No
1685
- // "Compile"/"Run"/"Save" language (those pipeline verbs are absent here; the verb is
1686
- // Approve). "Walk me through it" is a Workflows relay (terminal AI + the workflow's own
1687
- // skill), so it's hidden for a workspace — the beacon is a self-contained checklist here.
1688
- // The title is the open project's user-authored name → set via textContent only (never
1689
- // into innerHTML); the body innerHTML is authored constants + escaped step labels/notes.
1690
- function renderWorkspaceGuide() {
1691
- const ctx = wsGuideCtx;
1692
- const $body = document.getElementById('guide-body');
1693
- const $title = document.getElementById('guide-title');
1694
- const $eyebrow = document.getElementById('guide-eyebrow');
1695
- const $sub = document.querySelector('#guide-modal .modal-sub');
1696
- if (!ctx || !$body) return;
1697
- if ($title) $title.textContent = ctx.name || ctx.displayName || ctx.app;
1698
- if ($eyebrow) $eyebrow.textContent = wsBeaconIsNew(ctx.app) ? '✦ Start here' : '✦ Project guide';
1699
- if ($sub) $sub.textContent = 'What this project does, and how to take it from drawing to export.';
1700
- const descHtml = `<div class="guide-desc"><p>Drop in a drawing — a PDF, scan, or photo — and it comes back as clean, editable traced linework. Anything the trace wasn’t sure about gets flagged for you to check before you approve and export.</p></div>`;
1701
- const stepsHtml = guideStepsHtml(workspaceGuideSteps(ctx));
1702
- $body.innerHTML =
1703
- `<div class="guide-section-label">What this does</div>` + descHtml +
1704
- `<div class="guide-section-label">How to go through it</div>` + stepsHtml;
1705
- }
1706
-
1707
- function renderGuide() {
1708
- // In Workspaces mode with a project open, the guide describes the document life-cycle.
1709
- if (wsGuideActive()) { renderWorkspaceGuide(); return; }
1710
- const app = currentId && apps.get(currentId);
1711
- const $body = document.getElementById('guide-body');
1712
- const $title = document.getElementById('guide-title');
1713
- const $eyebrow = document.getElementById('guide-eyebrow');
1714
- const $sub = document.querySelector('#guide-modal .modal-sub');
1715
- if (!app || !$body) return;
1716
- if ($title) $title.textContent = app.displayName || app.id;
1717
- if ($eyebrow) $eyebrow.textContent = beaconIsNew(app.id) ? '✦ Start here' : '✦ Workflow guide';
1718
- // Restore the workflow sub in case a prior Workspaces open overwrote it.
1719
- if ($sub) $sub.textContent = 'What this workflow does, and how to go through it.';
1720
- const desc = (app.description || '').trim();
1721
- const descHtml = desc
1722
- ? `<div class="guide-desc">${desc.split(/\n{2,}/).map((p) => `<p>${mdInline(escapeHtml(p.trim()))}</p>`).join('')}</div>`
1723
- : `<div class="guide-desc guide-desc-empty"><p>A ${app.nodes.length}-step workflow. Set its inputs, Compile to freeze the approved lock, then Run it against your live host.</p></div>`;
1724
- // Static authored strings + escapeHtml on every dynamic value (app.description, step
1725
- // label/note) — no raw user string reaches the DOM (the established guide pattern).
1726
- const stepsHtml = guideStepsHtml(guideSteps(app));
1727
- const walkHint = `<div class="guide-walk-hint">A bigger workflow? <strong>Walk me through it</strong> hands off to your terminal AI for a step-by-step tour using this workflow's own skill.</div>`;
1728
- $body.innerHTML =
1729
- `<div class="guide-section-label">What this does</div>` + descHtml +
1730
- `<div class="guide-section-label">How to go through it</div>` + stepsHtml + walkHint;
1731
- }
1732
-
1733
- function openGuide() {
1734
- const ws = wsGuideActive();
1735
- if (!ws && !currentId) { showToast('open a workflow first', 'warn'); return; }
1736
- renderGuide();
1737
- const $m = document.getElementById('guide-modal');
1738
- // "Walk me through it →" relays to the terminal AI using a WORKFLOW's own skill — a
1739
- // pipeline concept with no document-workspace analog. Hide it (never disable — an
1740
- // absent control, not a dead one) for the self-contained workspace guide.
1741
- const $walk = document.getElementById('guide-walk');
1742
- if ($walk) $walk.hidden = ws;
1743
- showModal($m);
1744
- // Focus the dialog shell (not a button) so the checklist is read first; Tab then
1745
- // moves to Got it → Walk me through it. Focus returns to the beacon on close.
1746
- const shell = $m && $m.querySelector('.modal.guide');
1747
- if (shell) { try { shell.focus(); } catch { /* not focusable */ } }
1748
- }
1749
- // Closing the guide (Got it / backdrop / Esc) marks it seen → the beacon stops
1750
- // pulsing even before a first run/approve (the user has looked; don't nag). In
1751
- // Workspaces mode this marks the project's app workspace-guide key, not the workflow.
1752
- function closeGuide() {
1753
- if (wsGuideActive()) {
1754
- setGuide(wsGuideKey(wsGuideCtx.app), { dismissed: true });
1755
- paintWorkspaceBeacon();
1756
- } else if (currentId) {
1757
- setGuide(currentId, { dismissed: true });
1758
- const app = apps.get(currentId);
1759
- if (app) paintBeacon(app);
1760
- }
1761
- hideModal(document.getElementById('guide-modal'));
1762
- const $b = document.getElementById('guide-beacon');
1763
- if ($b && !$b.hidden) { try { $b.focus(); } catch { /* */ } }
1764
- }
1765
-
1766
- // "Walk me through it" → relay the ask to the terminal AI, the house way: queue a
1767
- // request AND copy the prompt, toast, light the footer requests pill, list it in the
1768
- // Requests window. The UI never guides itself; it hands intent to the assistant.
1769
- async function requestGuide() {
1770
- if (!currentId) { showToast('open a workflow first', 'warn'); return; }
1771
- try {
1772
- const { request } = await api('/api/guide', { method: 'POST', body: JSON.stringify({ appId: currentId }) });
1773
- const copied = await copyToClipboard(markedInstruction(request));
1774
- showToast(copied ? 'Sent to your assistant · copied to clipboard' : 'Sent to your assistant', 'ok');
1775
- appendNarration(`Asked your terminal AI to walk you through <code>${escapeHtml(currentId)}</code> — watch the glowing <strong>requests</strong> pill (bottom-right), or switch to your terminal.${copied ? ' The prompt is also on your clipboard.' : ''}`);
1776
- loadRequests();
1777
- closeGuide(); // engaging with the guidance also calms the beacon
1778
- } catch (e) { reportErr(e); }
1779
- }
1780
1541
 
1781
1542
  const activeInstructorRuns = new Map();
1782
1543
 
@@ -1902,9 +1663,6 @@
1902
1663
  // may turn a successfully queued request into a false failure report.
1903
1664
  const copied = await copyToClipboard(markedInstruction(request));
1904
1665
  showToast(copied ? 'Sent to your terminal AI · copied to clipboard' : 'Sent to your terminal AI', 'ok');
1905
- try {
1906
- appendNarration(`Asked your terminal AI about <strong>${escapeHtml(instructorContext.subject)}</strong> — watch the glowing <strong>requests</strong> pill (bottom-right), or switch to your terminal.${copied ? ' The prompt is also on your clipboard.' : ''}`);
1907
- } catch (e) { console.error(e); }
1908
1666
  try { await loadRequests(); } catch (e) { console.error(e); }
1909
1667
  return true;
1910
1668
  }
@@ -1945,7 +1703,8 @@
1945
1703
  .map((project) => ({
1946
1704
  value: `project:${project.id}`,
1947
1705
  label: project.name || project.id,
1948
- meta: `${project.templateId || project.app || 'Workspace'} project`,
1706
+ // #2470 R6.2: a General project is named as the person sees it, never by FloLess's type id.
1707
+ meta: (project.templateId || project.app) === 'floless-general' ? 'General project' : `${project.templateId || project.app || 'Workspace'} project`,
1949
1708
  })),
1950
1709
  ];
1951
1710
  }
@@ -1982,6 +1741,10 @@
1982
1741
  try {
1983
1742
  const { projects = [] } = await api('/api/projects');
1984
1743
  const ownerOptions = workflowOwnerOptions(projects);
1744
+ const wantedOwner = typeof prefill.ownerProjectId === 'string' && prefill.ownerProjectId ? `project:${prefill.ownerProjectId}` : null;
1745
+ const preselectedOwner = wantedOwner && ownerOptions.some((o) => o.value === wantedOwner) ? wantedOwner : 'standalone';
1746
+ // The project may have been archived meanwhile: the dialog still opens, on Standalone, and says why.
1747
+ if (wantedOwner && preselectedOwner !== wantedOwner) showToast('That project isn’t in the Location list any more, so the new workflow starts as Standalone. Choose its location in the dialog.', 'warn');
1985
1748
  const result = await formModal({
1986
1749
  title: guide ? 'Build this workflow' : 'Start a workflow',
1987
1750
  sub: 'Choose where it belongs. Its files, chat, history and AI working folder stay with that location.',
@@ -1993,7 +1756,8 @@
1993
1756
  ...(typeof prefill.name === 'string' && prefill.name ? { value: prefill.name } : {}),
1994
1757
  },
1995
1758
  {
1996
- name: 'owner', label: 'Location', type: 'select', value: 'standalone',
1759
+ // #2470 R6.2: opened from a project's Workflows step, the project is already chosen (the person can change it).
1760
+ name: 'owner', label: 'Location', type: 'select', value: preselectedOwner,
1997
1761
  commandId: 'shell.new-workflow-location', options: ownerOptions,
1998
1762
  },
1999
1763
  ...(guide ? [] : [{
@@ -2062,93 +1826,9 @@
2062
1826
  // #1890 PR 3b-0: the new draft opens, so it is somewhere to come back to — not only a toast.
2063
1827
  try { ({ workflows: wfOwned } = await api('/api/workflows/owned')); openDraftWorkflow(workflow.workflowId); }
2064
1828
  catch { /* the draft is still on the Workflows page after the next refresh */ }
2065
- appendNarration(`Created <strong>${escapeHtml(name)}</strong> in its chosen location and asked your terminal AI to start there — watch the glowing <strong>requests</strong> pill (bottom-right), or switch to your terminal.${copied ? ' The prompt is also on your clipboard.' : ''}`);
2066
1829
  loadRequests();
2067
1830
  }
2068
1831
 
2069
- // ── First-open spotlight (one-time per workflow) ────────────────────────────
2070
- // Dims the canvas, raises the beacon, and points a small caption at it; Esc /
2071
- // click-away / either button dismiss it for good. Slice 2 of the onboarding beacon.
2072
- let _spotlightKey = null;
2073
- let _spotlightResize = null;
2074
- // The spotlight points at the workflow canvas, so it lives only while that canvas is on screen (#2007): it is held
2075
- // back (not used up) while Workspaces, Agents or the Workflows list covers it, and syncSpotlightToMode() follows
2076
- // every tab switch and the list closing.
2077
- const canvasHidden = () => document.body.classList.contains('mode-agents') || inWorkspacesMode() || wfLanding;
2078
- function maybeSpotlight(app) {
2079
- if (!app) return;
2080
- const g = guideFor(app.id);
2081
- if (g.spotlightShown || g.dismissed || g.firstRunDone) return;
2082
- if (document.querySelector('.modal-backdrop.show')) return; // don't pile on a dialog
2083
- if ($contractEditor && !$contractEditor.hidden) return;
2084
- setTimeout(() => {
2085
- // Checked when it would open, so a workflow loaded behind Workspaces or Agents keeps its spotlight for later.
2086
- if (currentId !== app.id || canvasHidden()) return; // switched away during the delay
2087
- if (guideFor(app.id).spotlightShown) return;
2088
- if (document.querySelector('.modal-backdrop.show')) return;
2089
- if ($contractEditor && !$contractEditor.hidden) return; // the editor opened during the delay
2090
- showSpotlight(app);
2091
- }, 700);
2092
- }
2093
- // Where the first-open caption bubble sits: just under the anchor (right-aligned to it), clamped so the
2094
- // whole bubble stays inside the viewport. A zero-sized / missing anchor (the beacon is not laid out on
2095
- // the landing) falls back to the top-right corner instead of the window origin (#2020).
2096
- function spotlightBubblePosition(anchor, vw, vh, bw, bh) {
2097
- const M = 8;
2098
- const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
2099
- const laidOut = !!anchor && Number.isFinite(anchor.right) && Number.isFinite(anchor.bottom)
2100
- && (anchor.width > 0 || anchor.height > 0);
2101
- const left = laidOut ? anchor.right - bw : vw - bw - 16;
2102
- const top = laidOut ? anchor.bottom + 10 : 64;
2103
- return { left: clamp(left, M, Math.max(M, vw - bw - M)), top: clamp(top, M, Math.max(M, vh - bh - M)) };
2104
- }
2105
- // Anchor the caption bubble just under the beacon, right-aligned to it, and keep the whole bubble
2106
- // (so its Got it / Show me buttons) inside the window even when the beacon is not laid out (#2020).
2107
- function placeSpotlightBubble($sp, $b) {
2108
- const bubble = $sp.querySelector('.guide-spotlight-bubble');
2109
- if (!bubble) return;
2110
- bubble.style.maxWidth = Math.max(0, Math.min(280, window.innerWidth - 16)) + 'px';
2111
- bubble.style.left = '0px'; bubble.style.top = '0px'; bubble.style.right = 'auto';
2112
- const pos = spotlightBubblePosition($b.getBoundingClientRect(), window.innerWidth, window.innerHeight,
2113
- bubble.offsetWidth, bubble.offsetHeight);
2114
- bubble.style.left = pos.left + 'px';
2115
- bubble.style.top = pos.top + 'px';
2116
- }
2117
- function showSpotlight(app) {
2118
- const $sp = document.getElementById('guide-spotlight');
2119
- const $b = document.getElementById('guide-beacon');
2120
- if (!$sp || !$b || $b.hidden) return;
2121
- setGuide(app.id, { spotlightShown: true });
2122
- $b.classList.add('spotlit');
2123
- $sp.hidden = false;
2124
- const bubble = $sp.querySelector('.guide-spotlight-bubble');
2125
- placeSpotlightBubble($sp, $b);
2126
- // The window can narrow while the tip is open: re-clamp so Got it / Show me never leave the screen (#2020).
2127
- releaseSpotlightListeners(); // a repeated show (guide state could not be saved) must not stack listeners
2128
- _spotlightResize = () => placeSpotlightBubble($sp, $b);
2129
- window.addEventListener('resize', _spotlightResize);
2130
- _spotlightKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); hideSpotlight(); } };
2131
- document.addEventListener('keydown', _spotlightKey);
2132
- if (bubble) { try { bubble.focus(); } catch { /* */ } }
2133
- }
2134
- // Called by workspaces.js after every tab switch: leaving Workflows closes an open spotlight; coming back offers one
2135
- // that was held back while the canvas was hidden. One already shown stays shown-once.
2136
- function syncSpotlightToMode() {
2137
- if (canvasHidden()) { hideSpotlight(); return; }
2138
- maybeSpotlight(currentId && apps.get(currentId));
2139
- }
2140
- function hideSpotlight() {
2141
- const $sp = document.getElementById('guide-spotlight');
2142
- const $b = document.getElementById('guide-beacon');
2143
- if ($sp) $sp.hidden = true;
2144
- if ($b) $b.classList.remove('spotlit');
2145
- releaseSpotlightListeners();
2146
- }
2147
- function releaseSpotlightListeners() {
2148
- if (_spotlightKey) { document.removeEventListener('keydown', _spotlightKey); _spotlightKey = null; }
2149
- if (_spotlightResize) { window.removeEventListener('resize', _spotlightResize); _spotlightResize = null; }
2150
- }
2151
-
2152
1832
  // ── load / select / compile / run ───────────────────────────────────────────
2153
1833
 
2154
1834
  let _wfUpdates = []; // workflow updates available, keyed by app id — polled by refreshWorkflowUpdates() below
@@ -2205,15 +1885,96 @@
2205
1885
  runRecordChanged: (appId) => { if (appId === currentId && state.currentTab === 'execution') renderInspect(); },
2206
1886
  });
2207
1887
 
1888
+ /** #2644: the module sentence a library row carries when its workflow is locked for this account, else ''. */
1889
+ function lockedWorkflowMessage(row) {
1890
+ const text = row?.moduleLock?.userMessage;
1891
+ return typeof text === 'string' ? text.trim() : '';
1892
+ }
1893
+
1894
+ /**
1895
+ * #2644: the workflow startup opens: the remembered one if it is listed and open to this account, else the first one
1896
+ * that is. A locked module workflow is chosen only when every listed workflow is locked, and then loadApp shows its
1897
+ * locked canvas, never the offline screen.
1898
+ */
1899
+ function chooseStartWorkflow(list, saved) {
1900
+ if (saved && list.some((a) => a.id === saved && !lockedWorkflowMessage(a))) return saved;
1901
+ return (list.find((a) => !lockedWorkflowMessage(a)) || list[0]).id;
1902
+ }
1903
+
1904
+ /**
1905
+ * #2644: a Drawing Checker or Steel Model workflow this account's plan does not include. Nothing of it opens (owner
1906
+ * ruling 2026-10-23), so the canvas says so in the module's own words: never the offline screen, never an error. Every
1907
+ * way of opening a workflow (the picker, startup, the Workflows landing, a draft's publication) reaches it through
1908
+ * loadApp, which is why the check lives there.
1909
+ */
1910
+ function showLockedWorkflow(id, sentence) {
1911
+ closeDraftView();
1912
+ currentId = null;
1913
+ workflowSelectionGeneration += 1;
1914
+ // Nothing of the workflow that was open before may stay beside the locked canvas: its nodes, Inspector, run
1915
+ // state, approval strip, live run strip, Customize, update pill, unsaved dot and Agent-step banner all clear.
1916
+ state.promptKey = null;
1917
+ state.selectedAgentId = null;
1918
+ state.hasRun = false;
1919
+ liveTrace.length = 0;
1920
+ if ($promptSel.value !== '') $promptSel.value = '';
1921
+ refreshKbInformed(null);
1922
+ void refreshWorkflowUnits(null);
1923
+ notifyChatScope();
1924
+ $notesStrip.hidden = true;
1925
+ $runBtn.disabled = true;
1926
+ $compileBtn.disabled = true;
1927
+ if ($menuBakeItem) $menuBakeItem.disabled = true;
1928
+ if ($customizeBtn) $customizeBtn.hidden = true;
1929
+ if ($restoreBtn) $restoreBtn.hidden = true;
1930
+ if ($wfForked) $wfForked.hidden = true;
1931
+ if ($wfAgentStep) $wfAgentStep.hidden = true;
1932
+ $runBtn.dataset.tip = sentence;
1933
+ if ($runState) { $runState.textContent = ''; delete $runState.dataset.tip; }
1934
+ paintApprovalStrip(null);
1935
+ syncRunStrip();
1936
+ refreshDirtyIndicator();
1937
+ renderWfUpdatePill();
1938
+ globalThis.flolessAgentSteps?.paintCanvasControl();
1939
+ renderInspect();
1940
+ const row = wfLibrary.find((item) => item.id === id);
1941
+ setComboTriggerLabel(`${row?.ownedWorkflow?.displayName || ownedWorkflowOf(id)?.ownedWorkflow?.displayName || id} · locked`);
1942
+ setComboSelected(id);
1943
+ renderCanvasPlaceholder('locked', sentence);
1944
+ // Instructor (`?`) describes the locked workflow and why, not the one that was open before.
1945
+ window.Instructor?.setWorkflow({ name: row?.ownedWorkflow?.displayName || id, runState: 'locked', statusLabel: 'Locked',
1946
+ reason: sentence, totalInputs: 0, inputsSet: 0 });
1947
+ // Startup must not come back to it next time: the remembered workflow is one that opens.
1948
+ try { if (localStorage.getItem(LS_LAST_APP) === id) localStorage.removeItem(LS_LAST_APP); } catch { /* private mode */ }
1949
+ return { locked: sentence };
1950
+ }
1951
+
2208
1952
  async function loadApp(id) {
2209
1953
  // (globalThis, not window: this function is also lifted into a test harness that has no window; in the page they are the same object.
2210
1954
  // It never awaits the Agent-step status probe: opening a workflow must not wait on anything new, or the boot race below it gets likelier.)
2211
1955
  selectionTargetId = id;
2212
- hideSpotlight(); // a spotlight pointing at the previous app's beacon must clear on switch
2213
1956
  const ticket = ++selectionTicket;
1957
+ // #2644: the server decides, fresh, every time: a lock the library listed may be stale (access renewed since), so it
1958
+ // is asked again. Its refusal shows the locked canvas instead of failing the caller, which would paint the server
1959
+ // as offline; returns { locked } so a caller that leaves the landing or reports the open (AI Chat) knows.
1960
+ const listedRow = wfLibrary.find((item) => item.id === id);
2214
1961
  const payload = api(`/api/app/${encodeURIComponent(id)}`);
2215
1962
  const read = beginPublicationAvailabilityRead(id, payload);
2216
- const { app, contractState } = await payload;
1963
+ const barrierOfRead = publicationAvailabilityBarrier;
1964
+ let app;
1965
+ let contractState;
1966
+ try {
1967
+ ({ app, contractState } = await payload);
1968
+ } catch (error) {
1969
+ const refused = moduleRefusalText(error);
1970
+ if (!refused) throw error;
1971
+ // The refusal is answered here, so the shared availability barrier must not keep rejecting with it — but only
1972
+ // while it is still this read's: a newer read's barrier (another workflow opening) is never released early.
1973
+ if (publicationAvailabilityBarrier === barrierOfRead) setPublicationAvailabilityBarrier(Promise.resolve());
1974
+ return ticket === selectionTicket ? showLockedWorkflow(id, refused) : undefined;
1975
+ }
1976
+ // Opened: a lock the listing showed is out of date, so the row and the picker stop saying locked.
1977
+ if (listedRow?.moduleLock) { delete listedRow.moduleLock; buildWorkflowCombo(wfLibrary); }
2217
1978
  if (ticket !== selectionTicket) return; // something newer was opened while this one loaded
2218
1979
  closeDraftView();
2219
1980
  apps.set(id, app);
@@ -2252,10 +2013,8 @@
2252
2013
  paintGate(app);
2253
2014
  refreshKbInformed(id); // detached: provenance is additive, and must not hold up the canvas paint
2254
2015
  void refreshWorkflowUnits(id);
2255
- paintBeacon(app); // pulse "Start here" while this workflow is new to the user
2256
2016
  refreshDirtyIndicator(); // clean app → dot off; switched back to a dirty one → dot on
2257
2017
  renderWfUpdatePill(); // show the "↑ Update to vX" pill when THIS app has a newer published version
2258
- maybeSpotlight(app); // one-time first-open spotlight pointing at the beacon (slice 2)
2259
2018
  globalThis.flolessAgentSteps?.paintCanvasControl();
2260
2019
  void globalThis.flolessAgentSteps?.refreshChecks(app); // #2241: newer-instructions banner; a failed check says nothing
2261
2020
  void globalThis.flolessAgentSteps?.refreshRunRecord(app.id); // #2241 S5: how the last run's AI steps went, and what it left for you
@@ -2280,7 +2039,17 @@
2280
2039
  const read = ++publicationAvailabilityRead;
2281
2040
  publicationAvailabilityReads.set(id, read);
2282
2041
  const task = (async () => {
2283
- const { contractState } = await api(`/api/app/${encodeURIComponent(id)}`);
2042
+ let contractState;
2043
+ try {
2044
+ ({ contractState } = await api(`/api/app/${encodeURIComponent(id)}`));
2045
+ } catch (error) {
2046
+ // #2644: the module lapsed while this workflow was open. Show it locked (a completed refresh, so returning to
2047
+ // Workflows still works) when it is still the one open; any other failure is the caller's, as before.
2048
+ const refused = moduleRefusalText(error);
2049
+ if (!refused) throw error;
2050
+ if (currentId === id && publicationAvailabilityReads.get(id) === read) showLockedWorkflow(id, refused);
2051
+ return;
2052
+ }
2284
2053
  // A workflow switch or newer availability read can overtake this request. Only the latest
2285
2054
  // response for the still-open workflow may repaint its cards.
2286
2055
  if (currentId !== id || publicationAvailabilityReads.get(id) !== read) return;
@@ -2353,11 +2122,13 @@
2353
2122
  let unreadable = [];
2354
2123
  try {
2355
2124
  ({ apps: list, unreadable = [] } = await api('/api/workflows/library'));
2356
- try { ({ workflows: owned } = await api('/api/workflows/owned?archived=1')); }
2125
+ let setApart = null;
2126
+ try { ({ workflows: owned, quarantined: setApart = [] } = await api('/api/workflows/owned?archived=1')); }
2357
2127
  catch { /* the owned list is additive here: a failed read keeps the drafts last shown */ }
2358
2128
  // An older refresh that finishes after a newer one must not overwrite what the newer one showed.
2359
2129
  if (generation !== appsLoadGeneration) return;
2360
2130
  if (owned) wfOwned = owned;
2131
+ if (owned) wfSetApart = Array.isArray(setApart) ? setApart : [];
2361
2132
  list = list.filter((a) => a.execution !== 'internal');
2362
2133
  rememberWorkflowOwners(list);
2363
2134
  wfLibrary = list;
@@ -2416,8 +2187,6 @@
2416
2187
  if ($menuBakeItem) $menuBakeItem.disabled = true;
2417
2188
  if ($wfTrigger) $wfTrigger.disabled = true;
2418
2189
  setComboTriggerLabel('no workflows installed');
2419
- paintBeacon(null); // no workflow open → hide the per-workflow beacon
2420
- hideSpotlight();
2421
2190
  renderCanvasPlaceholder('empty');
2422
2191
  // #1890: an empty library is where the landing matters most: its New workflow card is the way in.
2423
2192
  if (!wfLandingBooted) { wfLandingBooted = true; showWorkflowsLanding(true); }
@@ -2450,11 +2219,9 @@
2450
2219
  return;
2451
2220
  }
2452
2221
  }
2453
- let startId = list[0].id;
2454
- try {
2455
- const saved = localStorage.getItem(LS_LAST_APP);
2456
- if (saved && list.some((a) => a.id === saved)) startId = saved;
2457
- } catch { /* ignore */ }
2222
+ let saved = null;
2223
+ try { saved = localStorage.getItem(LS_LAST_APP); } catch { /* ignore */ }
2224
+ const startId = chooseStartWorkflow(list, saved);
2458
2225
  const ticketBefore = selectionTicket;
2459
2226
  try {
2460
2227
  await loadApp(startId);
@@ -2524,6 +2291,8 @@
2524
2291
  // #1890 PR 3b-0: every owned workflow, drafts included (/api/workflows/owned), and the draft open in the canvas
2525
2292
  // area, if any. A draft has no runtime app, so it is never `currentId` and never goes to loadApp.
2526
2293
  let wfOwned = [];
2294
+ // #2603: workflow folders set apart because their details name another owner (GET /api/workflows/owned).
2295
+ let wfSetApart = [];
2527
2296
  const restoringWorkflows = new Set();
2528
2297
  let draftWorkflow = null;
2529
2298
  // Opening anything (a workflow or a draft) takes a new ticket; a workflow load that finishes after a newer open
@@ -2598,8 +2367,13 @@
2598
2367
  : `<button type="button" class="wf-act act-edit" data-wf-act="rename" data-command-id="workflow.rename#${escapeAttr(aid)}" data-id="${aid}" tabindex="-1" data-tip="Rename" aria-label="Rename ${escapeAttr(workflowName)}">✎</button>`
2599
2368
  + `<button type="button" class="wf-act act-dup" data-wf-act="duplicate" data-command-id="workflow.duplicate#${escapeAttr(aid)}" data-id="${aid}" tabindex="-1" data-tip="Duplicate" aria-label="Duplicate ${escapeAttr(workflowName)}">⧉</button>`
2600
2369
  + `<button type="button" class="wf-act act-del" data-wf-act="delete" data-command-id="workflow.delete#${escapeAttr(aid)}" data-id="${aid}" tabindex="-1" data-tip="Delete" aria-label="Delete ${escapeAttr(workflowName)}">×</button>`;
2601
- html += `<div class="wf-option" role="option" id="wf-opt-${aid}" data-id="${aid}" data-workflow-id="${escapeAttr(ownedId)}" data-workflow-name="${escapeAttr(workflowName)}" data-command-id="workflow.select#${escapeAttr(aid)}" data-baked="${a.baked ? '1' : ''}" data-search="${escapeAttr((workflowName + ' ' + a.id + ' ' + (a.ownerLabel || '') + ' ' + p).toLowerCase())}" tabindex="-1" aria-selected="false">`
2370
+ // #2644: a module workflow this account's plan does not include stays listed (its row actions are housekeeping)
2371
+ // and says why; choosing it shows the locked canvas, never a load that would read as the server being offline.
2372
+ const lock = lockedWorkflowMessage(a);
2373
+ const lockAttrs = lock ? ` data-locked="1" aria-disabled="true" data-blocked-reason="${escapeAttr(lock)}"` : '';
2374
+ html += `<div class="wf-option" role="option" id="wf-opt-${aid}" data-id="${aid}" data-workflow-id="${escapeAttr(ownedId)}" data-workflow-name="${escapeAttr(workflowName)}" data-command-id="workflow.select#${escapeAttr(aid)}" data-baked="${a.baked ? '1' : ''}" data-search="${escapeAttr((workflowName + ' ' + a.id + ' ' + (a.ownerLabel || '') + ' ' + p).toLowerCase())}" tabindex="-1" aria-selected="false"${lockAttrs}>`
2602
2375
  + `<span class="wf-option-name">${escapeHtml(workflowName)}</span><span class="wf-option-meta">${meta}</span>`
2376
+ + (lock ? `<span class="wf-fork-badge wf-lock-badge" data-tip="${escapeAttr(lock)}">${globalThis.FLOLESS_LOCK_ICON_SVG || ''}Locked</span>` : '')
2603
2377
  + (a.agentStep ? `<span class="wf-fork-badge wf-ai-badge" data-tip="A step in this workflow is answered by an AI Agent, so that answer can differ each run.">AI step</span>` : '')
2604
2378
  + (a.forked ? `<span class="wf-fork-badge" data-tip="You forked this workflow — it no longer receives FloLess updates. You own its output.">yours</span>` : '')
2605
2379
  + `<span class="wf-option-actions">`
@@ -2758,18 +2532,8 @@
2758
2532
  if (v != null) localStorage.setItem(lsInputsKey(toId), v);
2759
2533
  } catch { /* private mode / quota */ }
2760
2534
  }
2761
- // A rename is the SAME workflow under a new id → carry its onboarding-seen state so it
2762
- // doesn't re-pulse "Start here" / re-show the spotlight. (Not done on duplicate: a copy
2763
- // is a genuinely new workflow that the user hasn't run, so it should start new.)
2764
- function migrateGuideLS(fromId, toId) {
2765
- try {
2766
- const all = guideStateAll();
2767
- if (all[fromId]) { all[toId] = all[fromId]; localStorage.setItem(LS_GUIDE, JSON.stringify(all)); }
2768
- } catch { /* private mode / quota */ }
2769
- }
2770
2535
  function dropClientAppState(id) {
2771
2536
  try { localStorage.removeItem(lsInputsKey(id)); } catch { /* ignore */ }
2772
- try { const all = guideStateAll(); if (all[id]) { delete all[id]; localStorage.setItem(LS_GUIDE, JSON.stringify(all)); } } catch { /* ignore */ }
2773
2537
  appInputValues.delete(id); dirtyBaseline.delete(id); apps.delete(id); contractStates.delete(id);
2774
2538
  }
2775
2539
 
@@ -2894,7 +2658,6 @@
2894
2658
  // so a rename never silently drops the user's inputs (#85 review). loadApp() only seeds
2895
2659
  // inputs when the id is absent, so pre-setting them here preserves unsaved edits.
2896
2660
  migrateInputsLS(oldId, r.id);
2897
- migrateGuideLS(oldId, r.id); // carry onboarding-seen state so the renamed workflow doesn't re-pulse
2898
2661
  if (appInputValues.has(oldId)) appInputValues.set(r.id, appInputValues.get(oldId));
2899
2662
  if (dirtyBaseline.has(oldId)) dirtyBaseline.set(r.id, dirtyBaseline.get(oldId));
2900
2663
  const wasOpen = currentId === oldId;
@@ -3693,7 +3456,6 @@
3693
3456
  const out = await r.json().catch(() => ({ ok: false, error: `re-bake failed (${r.status})` }));
3694
3457
  if (!out || !out.ok) { showToast((out && out.error) || 'could not queue re-bake', 'err'); return; }
3695
3458
  showToast(`Queued — your terminal AI will re-read ${n} drawing${n > 1 ? 's' : ''} and update this workflow, then ask you to approve.`, 'ok');
3696
- appendNarration(`<strong>Re-bake queued</strong> for <strong>${escapeHtml(name)}</strong> (${n} file${n > 1 ? 's' : ''}). Your terminal AI will re-read the drawing${n > 1 ? 's' : ''}, update this workflow, and ask you to approve the new lock.`);
3697
3459
  } catch { showToast('could not queue re-bake', 'err'); }
3698
3460
  }
3699
3461
 
@@ -3850,15 +3612,61 @@
3850
3612
  const APP_LABELS = { 'steel-model': 'Steel model', vectorize: 'Vectorize' };
3851
3613
  const appLabel = (a) => APP_LABELS[a] || String(a || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
3852
3614
 
3853
- // Approved Workspace projects for a `widget: workspace-project` input picker. Returns
3854
- // [] on any error (→ the picker shows its "approve a project first" empty state).
3615
+ // Approved Workspace projects for a `widget: workspace-project` input picker, and the approved ones the listing
3616
+ // omitted with why (#2645: a module the plan does not include, an approval that could not be verified). Both empty
3617
+ // on any error (→ the picker shows its "approve a project first" empty state).
3855
3618
  async function fetchApprovedProjects(appFilter) {
3856
3619
  try {
3857
3620
  const url = '/api/workspace-projects/approved' + (appFilter ? `?app=${encodeURIComponent(appFilter)}` : '');
3858
3621
  const r = await fetch(url);
3859
3622
  const j = await r.json().catch(() => null);
3860
- return j && j.ok && Array.isArray(j.projects) ? j.projects : [];
3861
- } catch { return []; }
3623
+ if (!j || !j.ok) return { projects: [], omitted: [] };
3624
+ return {
3625
+ projects: Array.isArray(j.projects) ? j.projects : [],
3626
+ omitted: Array.isArray(j.omitted) ? j.omitted.filter((p) => p && typeof p.id === 'string' && typeof p.reason === 'string') : [],
3627
+ };
3628
+ } catch { return { projects: [], omitted: [] }; }
3629
+ }
3630
+
3631
+ /**
3632
+ * The `workspace-project` picker field: the approved projects to choose from, then (#2645) the approved projects the
3633
+ * listing omitted, greyed with their reason and never choosable. It says no project is approved only when the
3634
+ * listing named none at all; when every approved project is omitted it says that, and the list says why.
3635
+ */
3636
+ function workspaceProjectField(inp, listing, cur) {
3637
+ const byName = (a, b) => String(a.name).localeCompare(String(b.name));
3638
+ const usable = (listing.projects || []).slice().sort(byName).map((p) => ({
3639
+ value: p.id,
3640
+ // Name the KIND from the lineage root — after a rename `p.app` is a slug that says
3641
+ // nothing about what the project IS. The live id stays searchable below.
3642
+ meta: `${appLabel(p.templateId || p.app)} · v${p.latestApprovedVersion}`,
3643
+ label: p.name,
3644
+ search: `${p.name} ${p.app} ${appLabel(p.templateId || p.app)}`,
3645
+ }));
3646
+ const omitted = (listing.omitted || []).slice().sort(byName).map((p) => ({
3647
+ value: `omitted:${p.id}`,
3648
+ unavailable: p.reason,
3649
+ meta: p.reason,
3650
+ label: p.name,
3651
+ ariaLabel: `${p.name}, can’t be used here: ${p.reason}`,
3652
+ search: `${p.name} ${p.app} ${appLabel(p.templateId || p.app)}`,
3653
+ }));
3654
+ const n = omitted.length;
3655
+ // A saved project is kept only while it can still be chosen: one that is omitted now (or no longer listed at all)
3656
+ // would otherwise sit in the field unseen and be submitted.
3657
+ const saved = cur[inp.name] != null ? String(cur[inp.name]) : '';
3658
+ return {
3659
+ name: inp.name,
3660
+ label: inp.name + (inp.description ? ` — ${inp.description}` : ''),
3661
+ type: 'select',
3662
+ options: [...usable, ...omitted],
3663
+ value: usable.some((o) => o.value === saved) ? saved : '',
3664
+ placeholder: 'Select an approved project…',
3665
+ disabledLabel: 'Approve a project first',
3666
+ emptyNote: 'No approved projects yet — open <strong>Workspaces</strong>, create a project, and Approve it to use it here.',
3667
+ unavailableLabel: 'No approved project can be used here',
3668
+ unavailableNote: `${n} approved project${n === 1 ? '' : 's'} can’t be used here right now. Open the list to see why.`,
3669
+ };
3862
3670
  }
3863
3671
 
3864
3672
  // Knowledge reads are scoped by a published knowledge base, never by a model approval. Keep this
@@ -4003,26 +3811,8 @@
4003
3811
  };
4004
3812
  if (isProject(inp)) {
4005
3813
  // Already filtered, by the server, for THIS input's `workspaceApp` — see above.
4006
- const options = (approvedByFilter.get(typeof inp.workspaceApp === 'string' && inp.workspaceApp ? inp.workspaceApp : '') || [])
4007
- .slice().sort((a, b) => String(a.name).localeCompare(String(b.name)))
4008
- .map((p) => ({
4009
- value: p.id,
4010
- // Name the KIND from the lineage root — after a rename `p.app` is a slug that says
4011
- // nothing about what the project IS. The live id stays searchable below.
4012
- meta: `${appLabel(p.templateId || p.app)} · v${p.latestApprovedVersion}`,
4013
- label: p.name,
4014
- search: `${p.name} ${p.app} ${appLabel(p.templateId || p.app)}`,
4015
- }));
4016
- return {
4017
- name: inp.name,
4018
- label: inp.name + (inp.description ? ` — ${inp.description}` : ''),
4019
- type: 'select',
4020
- options,
4021
- value: cur[inp.name] != null ? cur[inp.name] : '',
4022
- placeholder: 'Select an approved project…',
4023
- disabledLabel: 'Approve a project first',
4024
- emptyNote: 'No approved projects yet — open <strong>Workspaces</strong>, create a project, and Approve it to use it here.',
4025
- };
3814
+ return workspaceProjectField(inp,
3815
+ approvedByFilter.get(typeof inp.workspaceApp === 'string' && inp.workspaceApp ? inp.workspaceApp : '') || { projects: [], omitted: [] }, cur);
4026
3816
  }
4027
3817
  if (isKnowledgeProject(inp)) {
4028
3818
  const options = knowledgeProjects
@@ -4136,7 +3926,6 @@
4136
3926
  markSpecialNodes();
4137
3927
  refreshDirtyIndicator(); // values changed → reflect unsaved state in the header/menu
4138
3928
  const badge = Object.entries(store).map(([k, v]) => `${k}=${visualNames.has(k) ? String(v).split(/[\\/]/).pop() : workflowInputDisplayValue(fields.find((field) => field.name === k), v)}`).join(' · ');
4139
- appendNarration(`Inputs set — <strong>${escapeHtml(badge)}</strong>. Run with <strong>▶ Run workflow</strong>.`);
4140
3929
  showToast('Inputs set: ' + badge, 'ok');
4141
3930
  }
4142
3931
 
@@ -4504,6 +4293,12 @@
4504
4293
  for (;;) {
4505
4294
  let ordinal = asked;
4506
4295
  try {
4296
+ // A resumed wait already past its deadline stops here and offers Try again. Otherwise a report whose own checks
4297
+ // pass but whose frame keeps finding it busy would load the frame again forever (the deadline is checked only
4298
+ // when a check is busy).
4299
+ if (busyUntil != null && Date.now() >= waitUntil) {
4300
+ throw Object.assign(new Error('Report still busy'), { status: 202, body: { ok: false, code: 'report-busy' } });
4301
+ }
4507
4302
  let index = await api(`/api/model-reports/${handle}/index?at=${ordinal ?? 0}`);
4508
4303
  if (request !== reportSectionRequest) return false;
4509
4304
  // Start with the first object's data, while First still opens Model information.
@@ -4691,6 +4486,13 @@
4691
4486
  if ($reportPage) $reportPage.hidden = true;
4692
4487
  }
4693
4488
 
4489
+ // The viewer may be closed while its run goes on (#39). When the report lands unseen, the person is told, with a way to it.
4490
+ function reportReadyNote(app, nodeId) {
4491
+ if ($reportModal.classList.contains('show') || currentId !== app.id) return;
4492
+ showToast(`${app.displayName}: the report is ready.`, 'ok', { action: { label: 'Open', commandId: 'shell.report-ready-open',
4493
+ onClick: () => { if (currentId === app.id) showReport(nodeId); } } });
4494
+ }
4495
+
4694
4496
  // Double-click the HTML Viewer node → LOAD the last report (no run; running is
4695
4497
  // the header "▶ Run workflow" button's job). Shows a prompt if nothing has run yet.
4696
4498
  function showReport(nodeId) {
@@ -4866,8 +4668,8 @@
4866
4668
  // the left panel beside a model editor is that panel's, and its Esc is its own. Bound on window, so it runs after
4867
4669
  // every document-level Esc handler, and a press one of them already used (preventDefault) is left alone. A keydown
4868
4670
  // inside the editor's iframe never arrives here; that half is web/overlay-escape.js, which calls the hook below.
4869
- // Several shell dialogs, the menu and the find bar close on Esc WITHOUT marking it (app.js, the routines and guide
4870
- // modals), and by the time this bubble listener runs they are already hidden. So whether one was showing is read in
4671
+ // Several shell dialogs, the menu and the find bar close on Esc WITHOUT marking it (app.js and the routines
4672
+ // modal), and by the time this bubble listener runs they are already hidden. So whether one was showing is read in
4871
4673
  // the capture phase, before any of them acts: that Esc was theirs, and closing the overlay too would be two actions.
4872
4674
  const SHELL_ESC_OWNERS = '.modal-backdrop.show, #menu.show, #find-overlay.show';
4873
4675
  let shellEscOwned = false;
@@ -4893,6 +4695,57 @@
4893
4695
  return true;
4894
4696
  };
4895
4697
 
4698
+ // #2629 — what the 3D view leaves out beyond the members the lines below already count: parts the viewer
4699
+ // projection or viewer-3d itself dropped (a washer whose hole is as large as it, a bolt hole outside its plate),
4700
+ // and relationships it could not apply (cuts). Pure on the server's answer so it can be tested on its own.
4701
+ // FloLess-side member rows are skipped here: `skippedDetail` already counts them in the existing wording.
4702
+ function threeDLeftOutSummary(res) {
4703
+ const KIND = { member: ['member', 'members'], plate: ['plate', 'plates'], bolt: ['bolt', 'bolts'], washer: ['washer', 'washers'],
4704
+ nut: ['nut', 'nuts'], hole: ['bolt hole', 'bolt holes'], weld: ['weld', 'welds'], cut: ['cut', 'cuts'], rod: ['rod', 'rods'],
4705
+ 'boolean-cut': ['cut', 'cuts'], 'bolt-array': ['bolt group', 'bolt groups'], 'bolt-instance': ['bolt', 'bolts'],
4706
+ 'hole-effect': ['hole effect', 'hole effects'], 'structural-grid': ['grid', 'grids'], 'grid-axis': ['grid line', 'grid lines'],
4707
+ 'elevation-datum': ['level', 'levels'] };
4708
+ const word = (kind, n) => { const k = KIND[kind]; return k ? k[n === 1 ? 0 : 1] : (n === 1 ? String(kind || 'part') : String(kind || 'part') + 's'); };
4709
+ const every = (Array.isArray(res && res.partsLeftOut) ? res.partsLeftOut : []).filter((r) => r && typeof r === 'object');
4710
+ const rows = every.filter((r) => !(r.kind === 'member' && r.source === 'floless'));
4711
+ const groups = new Map();
4712
+ for (const r of rows) {
4713
+ const key = `${r.kind}|${r.reason || ''}`;
4714
+ const g = groups.get(key) || { kind: r.kind, reason: r.reason || '', n: 0 };
4715
+ g.n += 1; groups.set(key, g);
4716
+ }
4717
+ const parts = [...groups.values()].sort((a, b) => b.n - a.n || String(a.kind).localeCompare(String(b.kind)))
4718
+ .map((g) => `${g.n} ${word(g.kind, g.n)}${g.reason ? ` (${g.reason})` : ''}`);
4719
+ const ids = every.map((r) => (r.id ? `${r.kind === 'hole' ? 'bolt hole' : r.kind} ${r.id}` : r.kind));
4720
+ const CAP = 12;
4721
+ const tip = ids.length ? ids.slice(0, CAP).join(', ') + (ids.length > CAP ? ` and ${ids.length - CAP} more` : '') : '';
4722
+ const applied = new Map();
4723
+ for (const r of (Array.isArray(res && res.notApplied) ? res.notApplied : [])) {
4724
+ if (r && typeof r === 'object') applied.set(r.kind, (applied.get(r.kind) || 0) + 1);
4725
+ }
4726
+ const notApplied = [...applied.entries()].map(([kind, n]) => `${n} ${word(kind, n)}`);
4727
+ const refs = new Map();
4728
+ for (const r of (Array.isArray(res && res.referenceRecords) ? res.referenceRecords : [])) {
4729
+ if (r && typeof r === 'object') refs.set(r.kind, (refs.get(r.kind) || 0) + 1);
4730
+ }
4731
+ const references = [...refs.entries()].map(([kind, n]) => `${n} ${word(kind, n)}`);
4732
+ return { parts, tip, notApplied, references, nothingDrawn: !!(res && res.nothingDrawn) };
4733
+ }
4734
+
4735
+ // The words a failed 3D render gives the person: AWARE's reason in plain sight instead of only the generic
4736
+ // sentence, and — on an AWARE too old to leave a bad part out — how to get the rest of the model.
4737
+ function threeDFailureMessage(body) {
4738
+ const generic = 'We couldn’t create the 3D view because FloLess could not finish preparing it. Try again.';
4739
+ const b = body && typeof body === 'object' ? body : {};
4740
+ const error = typeof b.error === 'string' ? b.error : '';
4741
+ const rest = error.replace(/^no resolvable members to render\s*(\u2014\s*)?/, '');
4742
+ let msg = /^no resolvable members to render/.test(error) ? `There is nothing to show in 3D${rest ? ': ' + rest : '.'}` : generic;
4743
+ const line = typeof b.reason === 'string' ? b.reason.split(/\r?\n/).map((x) => x.trim()).find(Boolean) : '';
4744
+ if (line && msg === generic) msg += ` The reason given: ${line.length > 240 ? line.slice(0, 237) + '…' : line}`;
4745
+ if (typeof b.hint === 'string' && b.hint) msg += ` ${b.hint}`;
4746
+ return msg;
4747
+ }
4748
+
4896
4749
  // Export 3D ▸ — render the approved model as an interactive 3D model. Calls the server's
4897
4750
  // export-3d (transform → companion viewer-3d app → compile → run) and paints the returned
4898
4751
  // interactive report in the same viewer a normal run uses. api() throws on any failure (non-2xx
@@ -4946,14 +4799,24 @@
4946
4799
  // to name the right one, so it names none, which is true in every environment.
4947
4800
  if (rfi) parts.push(`${rfi} with no resolved section size (RFI)`);
4948
4801
  if (noFit) parts.push(`${noFit} priced but not drawn (no tabulated footprint)`);
4949
- $reportSub.textContent = (parts.length ? `${parts.join(', ')} — not shown. ` : '')
4950
- + 'Live 3D view from the approved model — drag to orbit, scroll to zoom, click an element to inspect.';
4951
- if (parts.length) showToast(`3D: ${parts.join(' · ')}`, noFit ? 'warn' : 'info');
4802
+ // Parts the viewer left out, counted by kind and reason (#2629), after the member counts above.
4803
+ const left = threeDLeftOutSummary(res);
4804
+ const allParts = parts.concat(left.parts);
4805
+ const notApplied = left.notApplied.length
4806
+ ? `${left.notApplied.join(', ')} not applied in this view (the parts themselves are shown). ` : '';
4807
+ const references = left.references.length ? `Grid records not shown: ${left.references.join(', ')}. ` : '';
4808
+ $reportSub.textContent = (left.nothingDrawn ? 'Nothing in this model could be drawn' + (allParts.length ? ': ' : '. ') : '')
4809
+ + (allParts.length ? `${allParts.join(', ')} — not shown. ` : '')
4810
+ + notApplied + references
4811
+ + (left.nothingDrawn ? '' : 'Live 3D view from the approved model — drag to orbit, scroll to zoom, click an element to inspect.');
4812
+ // The ids behind the counts, on the same themed tooltip every other control uses (never a native title).
4813
+ if (left.tip) $reportSub.dataset.tip = `Not shown: ${left.tip}`; else delete $reportSub.dataset.tip;
4814
+ if (allParts.length) showToast(`3D: ${allParts.join(' · ')}`, noFit || left.parts.length ? 'warn' : 'info');
4952
4815
  paintReport(html, true);
4953
4816
  lastReportByApp.set(currentId, { nodeId: res.report.nodeId, label: '3D', html, interactive: true });
4954
4817
  $reportModal.dataset.html = '1';
4955
4818
  } catch (e) {
4956
- const recovery = 'We couldn’t create the 3D view because FloLess could not finish preparing it. Try again.';
4819
+ const recovery = threeDFailureMessage(e && e.body);
4957
4820
  $reportOverlay.innerHTML = `<div>${escapeHtml(recovery)}</div>`;
4958
4821
  showToast(recovery, 'warn');
4959
4822
  }
@@ -5461,12 +5324,10 @@
5461
5324
  lastReportByApp.set(app.id, { nodeId, label: inputBadge, ...res.report, runId: typeof res.runId === 'string' ? res.runId : null });
5462
5325
  // #2539: the run is over once the server answered. Showing its report may still wait for the workflow's Page to
5463
5326
  // save its copy, so the run controls are released now (not awaited) and the viewer opens the report by itself.
5464
- const runApp = app.id;
5465
5327
  void paintCompleteReport(res.report).then((painted) => {
5466
5328
  if (!painted || !currentCompleteReport || !$reportOverlay.hidden) return;
5467
- markFirstRunDone(runApp);
5468
5329
  $reportModal.dataset.html = '1';
5469
- appendNarration(`Rendered the complete read-only property report from <strong>${escapeHtml(nodeId)}</strong>.`);
5330
+ reportReadyNote(app, nodeId);
5470
5331
  });
5471
5332
  return;
5472
5333
  }
@@ -5484,11 +5345,10 @@
5484
5345
  // ⧉ Open file / ▤ Reveal buttons and cache it so a later double-click restores them (#209).
5485
5346
  const savedPath = res && typeof res.savedPath === 'string' ? res.savedPath : '';
5486
5347
  showSavedPathActions(savedPath);
5487
- markFirstRunDone(app.id); // a real run rendered → this workflow is no longer "new" (app captured pre-await; a mid-run switch must not mark the wrong workflow)
5488
5348
  lastReportByApp.set(currentId, { nodeId, label: inputBadge, html, interactive, savedPath, withFiles, runId: typeof res.runId === 'string' ? res.runId : null });
5489
5349
  paintReportPageLinks();
5490
5350
  $reportModal.dataset.html = '1';
5491
- appendNarration(`Rendered the ${interactive ? '3D view' : 'report'} from <strong>${escapeHtml(nodeId)}</strong>${inputBadge ? ' (' + escapeHtml(inputBadge) + ')' : ''} — live run against the model.`);
5351
+ reportReadyNote(app, nodeId);
5492
5352
  } catch (e) {
5493
5353
  const msg = e && e.message ? e.message : String(e);
5494
5354
  liveOutcome = (e && e.body && e.body.cancelled) ? 'stopped' : !(e && e.status) ? 'no-answer'
@@ -5681,6 +5541,7 @@
5681
5541
  reconnect.focus();
5682
5542
  }
5683
5543
 
5544
+ const CRED_SIGN_IN_FAILED = 'Sign-in didn’t finish. Click Reconnect to try again, or open Integrations.';
5684
5545
  function credReconnectStart(cred, card, btn, body) {
5685
5546
  const reset = (errMsg) => {
5686
5547
  credReconnect = null;
@@ -5707,11 +5568,13 @@
5707
5568
  if ($reportOverlay.querySelector('.cred-fail-card')) { $reportOverlay.hidden = true; $reportOverlay.replaceChildren(); }
5708
5569
  }, 2000);
5709
5570
  },
5710
- onFail: () => reset('Sign-in failed — try again, or use the device code flow in Integrations.'),
5571
+ // #2649: the server's own sentence when it sent one (a device code is not offered for Google any more).
5572
+ onFail: (message) => reset(message || CRED_SIGN_IN_FAILED),
5711
5573
  };
5574
+ // No Drive choice is sent: the server keeps whatever Drive access the account already has.
5712
5575
  api(`/api/connect/${encodeURIComponent(cred.id)}`, { method: 'POST', body: '{}' })
5713
- .then((res) => { if (res && res.started === false) reset('Couldn’t start sign-in — open Integrations to retry.'); })
5714
- .catch(() => reset('Sign-in failed — try again, or use the device code flow in Integrations.'));
5576
+ .then((res) => { if (res && res.started === false) reset(typeof res.message === 'string' ? res.message : 'Couldn’t start sign-in. Open Integrations to try again.'); })
5577
+ .catch(() => reset(CRED_SIGN_IN_FAILED));
5715
5578
  }
5716
5579
 
5717
5580
  // Shared by both run paths: when the server flags a credential issue, show the
@@ -5719,7 +5582,6 @@
5719
5582
  function surfaceCredentialIssue(cred) {
5720
5583
  showCredentialReconnect(cred);
5721
5584
  showToast(`Session expired — reconnect ${cred.label} to continue.`, 'warn');
5722
- appendNarration(`Run stopped — your <strong>${escapeHtml(cred.label)}</strong> session expired. Reconnect and run again.`);
5723
5585
  }
5724
5586
 
5725
5587
  function showModal(el) { el.classList.add('show'); }
@@ -5998,6 +5860,9 @@
5998
5860
  const isOn = (o) => String(o.value) === val;
5999
5861
  const sel = opts.find(isOn);
6000
5862
  const disabled = !opts.length;
5863
+ // #2645: rows that are listed only to say why they can't be chosen. When they are all there is, the list
5864
+ // still opens (to show why) and the trigger and note say none can be used, never that none exist.
5865
+ const noneUsable = !disabled && !opts.some((o) => !o.unavailable);
6001
5866
  // A search box only earns its place once the list is too long to scan. Offering one over
6002
5867
  // two choices ("Still image" / "Turntable video") reads as clutter and makes a two-item
6003
5868
  // decision look like a database lookup. Count-based rather than a per-caller flag, so
@@ -6005,7 +5870,8 @@
6005
5870
  // list here (approved projects, unbounded) crosses the threshold on its own.
6006
5871
  const searchable = opts.length > SELECT_SEARCH_MIN;
6007
5872
  const trigLabel = disabled ? (f.disabledLabel || 'None available')
6008
- : sel ? (sel.triggerLabel || (sel.label + (sel.meta ? ` (${sel.meta})` : ''))) : (f.placeholder || 'Select…');
5873
+ : sel && !sel.unavailable ? (sel.triggerLabel || (sel.label + (sel.meta ? ` (${sel.meta})` : '')))
5874
+ : noneUsable ? (f.unavailableLabel || 'None can be used here') : (f.placeholder || 'Select…');
6009
5875
  // Command IDs are literal registry identities. Only the selected runtime is dynamic;
6010
5876
  // never interpolate an arbitrary form field into the Instructor trust boundary.
6011
5877
  let commandCarrier = '';
@@ -6014,21 +5880,21 @@
6014
5880
  else if (f.commandId === 'shell.new-workflow-location') commandCarrier = ' data-command-id="shell.new-workflow-location"';
6015
5881
  else if (f.commandId === 'workflow.select-model-revision') commandCarrier = ' data-command-id="workflow.select-model-revision"';
6016
5882
  let optionIndex = 0;
6017
- const optionRow = (o) => `<div id="${id}-option-${optionIndex++}" class="wf-option${isOn(o) ? ' selected' : ''}${o.volatile ? ' volatile' : ''}" role="option" data-id="${escapeAttr(String(o.value))}" data-trigger-label="${escapeAttr(o.triggerLabel || '')}"${commandCarrier}${commandCarrier ? ` data-command-instance="${escapeAttr(String(o.value))}" data-command-instance-label="${escapeAttr(String(o.label))}"` : ''} data-search="${escapeAttr(String(o.search || o.label).toLowerCase())}" tabindex="-1" aria-label="${escapeAttr(o.ariaLabel || o.label)}" aria-selected="${isOn(o) ? 'true' : 'false'}"><span class="wf-option-name">${escapeHtml(o.label)}</span>${o.meta ? `<span class="wf-option-meta">${escapeHtml(o.meta)}</span>` : ''}</div>`;
5883
+ const optionRow = (o) => `<div id="${id}-option-${optionIndex++}" class="wf-option${isOn(o) && !o.unavailable ? ' selected' : ''}${o.volatile ? ' volatile' : ''}${o.unavailable ? ' is-unavailable' : ''}" role="option" data-id="${escapeAttr(String(o.value))}" data-trigger-label="${escapeAttr(o.triggerLabel || '')}"${o.unavailable ? ` aria-disabled="true" data-blocked-reason="${escapeAttr(String(o.unavailable))}" data-tip="${escapeAttr(String(o.unavailable))}"` : ''}${commandCarrier}${commandCarrier ? ` data-command-instance="${escapeAttr(String(o.value))}" data-command-instance-label="${escapeAttr(String(o.label))}"` : ''} data-search="${escapeAttr(String(o.search || o.label).toLowerCase())}" tabindex="-1" aria-label="${escapeAttr(o.ariaLabel || o.label)}" aria-selected="${isOn(o) ? 'true' : 'false'}"><span class="wf-option-name">${escapeHtml(o.label)}</span>${o.meta ? `<span class="wf-option-meta">${escapeHtml(o.meta)}</span>` : ''}</div>`;
6018
5884
  const grouped = opts.some((o) => o.group);
6019
5885
  const rows = grouped
6020
5886
  ? [...new Set(opts.map((o) => o.group || 'Other'))].map((group, groupIndex) => { const members = opts.filter((o) => (o.group || 'Other') === group); const meta = members.find((o) => o.groupMeta)?.groupMeta; return `<div class="wf-group" role="group" aria-labelledby="${id}-group-${groupIndex}"><div class="wf-group-header" id="${id}-group-${groupIndex}">${escapeHtml(group)}${meta ? `<span>${escapeHtml(meta)}</span>` : ''}</div>${members.map(optionRow).join('')}</div>`; }).join('')
6021
5887
  : opts.map(optionRow).join('');
6022
5888
  ctl = `<div class="wf-combo fm-select">
6023
5889
  <input type="hidden" data-fm="${escapeHtml(f.name)}" value="${escapeAttr(val)}">
6024
- <button type="button" class="wf-trigger fm-select-trigger"${commandCarrier}${commandCarrier && sel ? ` data-command-instance="${escapeAttr(String(sel.value))}" data-command-instance-label="${escapeAttr(String(sel.label))}"` : ''}${sel && sel.ariaLabel ? ` data-tip="${escapeAttr(sel.ariaLabel)}"` : ''} aria-haspopup="listbox" aria-controls="${id}-listbox" aria-expanded="false"${disabled ? ' disabled' : ''}>
6025
- <span class="wf-trigger-label fm-select-label"${sel ? '' : ' data-empty="1"'}>${escapeHtml(trigLabel)}</span>
5890
+ <button type="button" class="wf-trigger fm-select-trigger"${commandCarrier}${commandCarrier && sel && !sel.unavailable ? ` data-command-instance="${escapeAttr(String(sel.value))}" data-command-instance-label="${escapeAttr(String(sel.label))}"` : ''}${sel && !sel.unavailable && sel.ariaLabel ? ` data-tip="${escapeAttr(sel.ariaLabel)}"` : ''} aria-haspopup="listbox" aria-controls="${id}-listbox" aria-expanded="false"${disabled ? ' disabled' : ''}>
5891
+ <span class="wf-trigger-label fm-select-label"${sel && !sel.unavailable ? '' : ' data-empty="1"'}>${escapeHtml(trigLabel)}</span>
6026
5892
  <svg class="wf-caret" width="10" height="6" viewBox="0 0 10 6" aria-hidden="true"><path fill="currentColor" d="M0 0l5 6 5-6z"/></svg>
6027
5893
  </button>
6028
5894
  <div id="${id}-listbox" class="wf-popover fm-select-popover" role="listbox" aria-label="${escapeAttr(f.label || f.name)}" hidden>
6029
5895
  ${searchable ? '<div class="wf-search-wrap"><input class="wf-search fm-select-search" type="text" placeholder="Search projects or approved versions…" autocomplete="off" aria-label="Search projects or approved versions"></div>' : ''}
6030
5896
  <div class="wf-list fm-select-list">${rows}${searchable ? '<div class="wf-empty-search" hidden>No matches</div>' : ''}</div>
6031
- </div>${disabled && f.emptyNote ? `<div class="fm-select-note" role="status">${f.emptyNote}${f.emptyActionLabel ? `<div class="fm-select-actions"><button type="button" class="fm-select-reload" data-command-id="workflow.reload-model-revisions" data-fm-empty-action="${escapeAttr(f.name)}">${escapeHtml(f.emptyActionLabel)}</button></div>` : ''}</div>` : ''}${f.note ? `<div class="fm-select-note" role="status">${escapeHtml(f.note)}</div>` : ''}
5897
+ </div>${noneUsable && f.unavailableNote ? `<div class="fm-select-note" role="status">${escapeHtml(f.unavailableNote)}</div>` : ''}${disabled && f.emptyNote ? `<div class="fm-select-note" role="status">${f.emptyNote}${f.emptyActionLabel ? `<div class="fm-select-actions"><button type="button" class="fm-select-reload" data-command-id="workflow.reload-model-revisions" data-fm-empty-action="${escapeAttr(f.name)}">${escapeHtml(f.emptyActionLabel)}</button></div>` : ''}</div>` : ''}${f.note ? `<div class="fm-select-note" role="status">${escapeHtml(f.note)}</div>` : ''}
6032
5898
  </div>`;
6033
5899
  } else {
6034
5900
  const fieldCommand = f.commandId === 'shell.new-workflow-name'
@@ -6360,6 +6226,8 @@
6360
6226
  const close = (focusTrig) => { popover.hidden = true; trigger.classList.remove('open'); trigger.setAttribute('aria-expanded', 'false'); clearHi(); if (focusTrig) trigger.focus(); };
6361
6227
  const nameOf = (o) => { const n = o.querySelector('.wf-option-name'); return n ? n.textContent : o.dataset.id; };
6362
6228
  const choose = (opt) => {
6229
+ // #2645: a row listed only to say why it can't be used is reachable (a screen reader hears why) but never chosen.
6230
+ if (opt.getAttribute('aria-disabled') === 'true') return;
6363
6231
  if (hidden) hidden.value = opt.dataset.id;
6364
6232
  if (trigger.dataset.commandId) {
6365
6233
  trigger.dataset.commandInstance = opt.dataset.id;
@@ -6795,6 +6663,17 @@
6795
6663
  // markup) so a server-returned URL can never inject HTML.
6796
6664
  $reportShare.onclick = async () => {
6797
6665
  const cached = currentId && lastReportByApp.get(currentId);
6666
+ // #2706: when this run's report became a version of the workflow's Page, Share shares THAT Page: the Page viewer opens at
6667
+ // the version this run made with its share menu open, so the link is the updating one ("the same link updates"), with the
6668
+ // same words, state and confirmation. A frozen one-off copy is made only when there is no Page version to share.
6669
+ const page = cached ? reportPageOf(cached) : null;
6670
+ if (page && typeof window.flolessPages?.open === 'function') {
6671
+ try {
6672
+ // The report stays open until the Page is known to open (beforeShow); a Page that cannot be opened says why and leaves it.
6673
+ await window.flolessPages.open(page.home, page.pageId, page.version, { share: true, beforeShow: () => closeReportViewer() });
6674
+ } catch (e) { showToast(`FloLess couldn’t open the workflow’s Page to share it. ${e && e.message ? e.message : ''}`.trim(), 'warn'); }
6675
+ return;
6676
+ }
6798
6677
  // Share exactly what's on screen — the HTML we painted — so the link can never carry a different
6799
6678
  // report than the one the user is looking at (e.g. another app's cache). `lastPaintedHtml` covers
6800
6679
  // the INTERACTIVE 3D frame too, which has no srcdoc (it renders from a data: URL); the srcdoc
@@ -6807,7 +6686,9 @@
6807
6686
  // so measure the SERIALIZED body, not the raw HTML, or quote-heavy markup slips past the check
6808
6687
  // and 413s anyway.
6809
6688
  const app = apps.get(currentId);
6810
- const title = `${app ? app.displayName : currentId}${cached.label ? ' · ' + cached.label : ''}`;
6689
+ // #2706: the public title is the workflow's name alone. The run's inputs (`cached.label`) carry local paths and internal
6690
+ // rates, and a link's title is shown to whoever opens it.
6691
+ const title = `${app ? app.displayName : currentId}`;
6811
6692
  // Declare an interactive 3D document so the server can hold it to the AWARE display-mode floor.
6812
6693
  // This path renders via export-3d without `for=share`, so this is the only place it gets gated.
6813
6694
  const body = JSON.stringify(lastPaintedInteractive ? { title, html, kind: 'model-3d' } : { title, html });
@@ -6884,11 +6765,9 @@
6884
6765
  if (r.warning) {
6885
6766
  // The rename did not land exactly as previewed (or could not be checked): the person looks before anything compiles.
6886
6767
  showToast(r.warning, 'warn');
6887
- appendNarration(`Renamed the step <strong>${escapeHtml(r.renamed?.from || '')}</strong> to <strong>${escapeHtml(r.renamed?.to || '')}</strong>. ${escapeHtml(r.warning)}`);
6888
6768
  if (currentId === id) { try { await loadApp(id); } catch (e) { reportErr(e); } }
6889
6769
  return;
6890
6770
  }
6891
- appendNarration(`Renamed the step <strong>${escapeHtml(r.renamed?.from || '')}</strong> to <strong>${escapeHtml(r.renamed?.to || '')}</strong>. The workflow changed, so it is compiled and approved again.`);
6892
6771
  if (currentId !== id) return;
6893
6772
  try { await loadApp(id); } catch (e) { reportErr(e); return; }
6894
6773
  if (currentId === id) await compileCurrentWorkflow();
@@ -6936,17 +6815,30 @@
6936
6815
  const consent = globalThis.flolessAgentSteps?.consentStatus ? await globalThis.flolessAgentSteps.consentStatus(newId) : null;
6937
6816
  const unconfirmed = consent && (consent.state === 'needed' || consent.state === 'changed');
6938
6817
  if (unconfirmed) {
6939
- appendNarration('Workflow compiled. It has an AI step whose answer may differ each run, and this version is not confirmed yet: FloLess asks you to confirm it before it runs.');
6940
6818
  showToast('Workflow compiled. Confirm its AI step before it runs.', 'ok');
6941
6819
  } else {
6942
- appendNarration(app?.runnable
6943
- ? 'Workflow compiled. Review any notices above the canvas before running.'
6944
- : `Compiled, but ${app?.notes?.length ?? 0} notice(s) remain — review them above the canvas.`);
6945
- showToast('Workflow compiled', 'ok');
6820
+ compiledToast(app);
6946
6821
  }
6947
6822
  maybeAskPolicyAfterApproval();
6948
6823
  }
6949
6824
 
6825
+ // One outcome per surface (a run, a compile): the next one replaces it, so repeats never pile up. Outcomes that need the
6826
+ // person stay until closed; a plain "complete" goes by itself (persistent = false).
6827
+ const standingToasts = new Map();
6828
+ function standingToast(surface, text, type, persistent = true) {
6829
+ standingToasts.get(surface)?.(true);
6830
+ standingToasts.set(surface, text ? showToast(text, type, persistent ? { persistent: true } : undefined) : null);
6831
+ }
6832
+
6833
+ /** After a Compile: a workflow that still cannot run says why, and where to look. */
6834
+ function compiledToast(app) {
6835
+ if (!app || app.runnable) { standingToast('compile'); showToast('Workflow compiled', 'ok'); return; }
6836
+ const notices = app.notes?.length ?? 0;
6837
+ standingToast('compile', notices
6838
+ ? `Workflow compiled, but ${notices} notice${notices === 1 ? '' : 's'} above the canvas still need${notices === 1 ? 's' : ''} you before it can run.`
6839
+ : 'Workflow compiled, but it can’t run yet. The status above the canvas says why.', 'warn');
6840
+ }
6841
+
6950
6842
  async function compileCurrentWorkflow() {
6951
6843
  if (!currentId || $compileBtn.disabled || $compileBtn.hidden) return; // hidden = suppressed for a maintained drift
6952
6844
  const id = currentId;
@@ -6963,11 +6855,7 @@
6963
6855
  try {
6964
6856
  if (consent !== 'approved') await api('/api/compile', { method: 'POST', body: JSON.stringify({ id }) });
6965
6857
  await loadApp(id);
6966
- const app = apps.get(id);
6967
- appendNarration(app.runnable
6968
- ? 'Workflow compiled. Review any notices above the canvas before running.'
6969
- : `Compiled, but ${app.notes.length} notice(s) remain — review them above the canvas.`);
6970
- showToast('Workflow compiled', 'ok');
6858
+ compiledToast(apps.get(id));
6971
6859
  // #1998: a person just approved a workflow — the moment to ask, once, about small read-only tool fixes.
6972
6860
  maybeAskPolicyAfterApproval();
6973
6861
  } catch (e) {
@@ -7024,7 +6912,6 @@
7024
6912
  await api('/api/bake', { method: 'POST', body: JSON.stringify({ id }) });
7025
6913
  hideModal($bakeModal);
7026
6914
  await loadApp(id);
7027
- appendNarration(`Baked <strong>${escapeHtml(id)}</strong> as a reusable tool — find it in the Tools library (<strong>≡ menu → Tools</strong>).`);
7028
6915
  showToast(`Baked — now in the Tools library as “${id}”`, 'ok');
7029
6916
  } catch (e) {
7030
6917
  hideModal($bakeModal);
@@ -7700,7 +7587,6 @@
7700
7587
  $graftPrimary.setAttribute('data-command-id', 'shell.graft-done');
7701
7588
  graftState.onPrimary = closeGraftModal;
7702
7589
  loadAgentCatalog().catch(() => {}); // refresh count immediately (SSE also fires for other tabs)
7703
- appendNarration(`Grafted <strong>${escapeHtml(res.agentId)}</strong> from ${escapeHtml(graftState.preview.sourceRef)} — find it in the Tools library (<strong>≡ menu → Tools</strong>).`);
7704
7590
  showToast(`Tool created — “${res.agentId}” is now in the Tools library`, 'ok');
7705
7591
  } catch (e) {
7706
7592
  $graftBack.disabled = false; $graftCancel.disabled = false;
@@ -9665,6 +9551,7 @@
9665
9551
  // every fired event until Stop. (Simulate still takes the normal stubbed path.)
9666
9552
  if (!simulate && app.triggerSource) { startForegroundTrigger(app); return; }
9667
9553
 
9554
+ standingToast('run'); // a new run makes the last one's outcome old news
9668
9555
  markCanvasRunning(); // immediate during-run feedback; the trace refines per node
9669
9556
 
9670
9557
  // Real run + a report node → the HTML Viewer path (renders the report,
@@ -9699,22 +9586,19 @@
9699
9586
  if (res.credentialIssue) { surfaceCredentialIssue(res.credentialIssue); return; }
9700
9587
  switchToExecution();
9701
9588
  const steps = liveTrace.filter((r) => r.kind === 'node-start').length;
9702
- appendNarration(simulate
9703
- ? `Simulated run complete · ${steps} node${steps === 1 ? '' : 's'} stubbed (no host needed) · see the <strong>Execution</strong> tab.`
9704
- : `Run complete · ${steps} node${steps === 1 ? '' : 's'} against the live model · see the <strong>Execution</strong> tab.`);
9705
- if (!simulate) markFirstRunDone(app.id); // a real run completed → calm the beacon (app captured pre-await)
9589
+ standingToast('run', simulate ? `Simulated run complete · ${steps} node${steps === 1 ? '' : 's'} stubbed. See the Execution tab.`
9590
+ : `Run complete · ${steps} node${steps === 1 ? '' : 's'}. See the Execution tab.`, 'ok', false);
9706
9591
  } catch (e) {
9707
9592
  liveOutcome = (e && e.body && e.body.cancelled) ? 'stopped'
9708
9593
  : !(e && e.status) ? 'no-answer' // the request itself was lost (reload, dropped connection), not the run
9709
9594
  : (e && e.body && (e.body.notRun || e.body.refusal)) ? 'not-run' : 'failed';
9710
9595
  if (e.body && e.body.cancelled) {
9711
9596
  clearNodeStatus();
9712
- showToast('Run cancelled', 'info');
9713
- appendNarration(stoppedRunCopy(e.body, !simulate && (app.templateId === 'floless-workspace-model-report' || app.templateId === 'tekla-model-report')) + ' Click <strong>▶ Run workflow</strong> to run again.');
9597
+ standingToast('run', stoppedRunCopy(e.body, !simulate && (app.templateId === 'floless-workspace-model-report' || app.templateId === 'tekla-model-report')), 'info');
9714
9598
  } else if (liveOutcome === 'no-answer' && clientRunToken) {
9715
9599
  // #2228: the request was lost, not the run — which may still be working. The strip says how it ends
9716
9600
  // once FloLess answers again; reporting a failure here would contradict it.
9717
- appendNarration('Lost touch with FloLess while the run was working. The strip above the canvas shows how it ends once FloLess is back.');
9601
+ standingToast('run', 'Lost touch with FloLess while the run was working. The strip above the canvas shows how it ends once FloLess is back.', 'info');
9718
9602
  } else {
9719
9603
  const cred = e.body && e.body.credentialIssue;
9720
9604
  if (cred) {
@@ -9732,12 +9616,9 @@
9732
9616
  if (e && e.body && (e.body.refusal || notRun)) clearNodeStatus();
9733
9617
  // A not-run answer is already a whole sentence ("…, so it didn’t run. …"); "Run failed:" would misstate it.
9734
9618
  // Nothing failed — it was declined with a reason — so the toast is informational, not a warning.
9735
- showToast(notRun ? runFailureMessage(msg) : (simulate ? 'Simulate failed' : 'Run failed') + ': ' + runFailureMessage(msg), notRun ? 'info' : 'warn');
9736
- appendNarration(notRun
9737
- ? escapeHtml(runFailureMessage(msg))
9738
- : simulate
9739
- ? `Simulate couldn't validate <code>${escapeHtml(currentId)}</code> — it stubs each node from its output-schema, but exec nodes have none, so the cross-node templates render undefined. Use <strong>▶ Run workflow</strong> for a live run against the host.`
9740
- : `Run failed: ${escapeHtml(runFailureMessage(msg))}`);
9619
+ standingToast('run', notRun ? runFailureMessage(msg)
9620
+ : simulate ? `Simulate failed: ${runFailureMessage(msg).replace(/([^.!?])$/, '$1.')} Simulate can’t check code steps, so ▶ Run workflow is the real test.`
9621
+ : 'Run failed: ' + runFailureMessage(msg), notRun ? 'info' : 'warn');
9741
9622
  }
9742
9623
  }
9743
9624
  } finally {
@@ -10746,6 +10627,7 @@
10746
10627
  pendingCatchup = null;
10747
10628
  window.dispatchEvent(new CustomEvent('floless:apps-changed', { detail: {} }));
10748
10629
  window.dispatchEvent(new CustomEvent('floless:projects-changed', { detail: {} }));
10630
+ window.dispatchEvent(new CustomEvent('floless:pages-changed', { detail: { home: null, id: null } })); // a reconnect missed whatever changed while away
10749
10631
  window.dispatchEvent(new CustomEvent('floless:action-proposal', { detail: { resync: true } }));
10750
10632
  loadRequests();
10751
10633
  const workflowId = currentId;
@@ -10823,6 +10705,8 @@
10823
10705
  // workflow this tab shows that someone else started is followed read-only (no Stop).
10824
10706
  // #2241: a run that FAILED after an Agent answered ends with run-finished, not run-ended: its AI record is read then too.
10825
10707
  if (m.type === 'run-finished' && m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id);
10708
+ // Workflows → History: a run starting shows as Running, and a failed run ends with run-finished alone.
10709
+ if (m.type !== 'node-progress') window.flolessRunHistory?.refresh?.();
10826
10710
  signalRunEvent(m); // the browser tab hears its run's ending even when the strip already settled
10827
10711
  if (liveRunOwns(m)) {
10828
10712
  if (m.type === 'run-live') { if (m.runId) { liveRun.runId = m.runId; signalRunNote(liveRun); } }
@@ -10866,6 +10750,10 @@
10866
10750
  // #2482: a PROJECT's contract changed (a checklist draft, a reference added from AI Chat). workspaces.js relays
10867
10751
  // it to that project's open editor frame, which has no event stream of its own.
10868
10752
  window.dispatchEvent(new CustomEvent('floless:contract-changed', { detail: m }));
10753
+ } else if (m.type === 'pages-changed') {
10754
+ // #2702: a Page was created, got a version, was shared, published, revoked or deleted — from the chat, a workflow
10755
+ // run or the viewer. Open Pages lists re-read (pages.js is the only listener); nothing is polled.
10756
+ window.dispatchEvent(new CustomEvent('floless:pages-changed', { detail: { home: typeof m.home === 'string' ? m.home : null, id: typeof m.id === 'string' ? m.id : null } }));
10869
10757
  } else if (m.type === 'projects-changed') {
10870
10758
  // Relayed as a DOM event for the same reason apps-changed is (see that arm below):
10871
10759
  // workspaces.js owns the project view and is the only listener. It reconciles the project it
@@ -11027,6 +10915,9 @@
11027
10915
  } else if (m.type === 'run-ended') {
11028
10916
  // Panel data bindings (last-run-output/-status) go stale after any run.
11029
10917
  if (window.flolessPanels) window.flolessPanels.refreshData();
10918
+ // #2470 R6.2: a project's Workflows step shows each workflow's last run; it re-reads only while on screen.
10919
+ window.flolessProjectWorkflows?.refresh?.();
10920
+ window.flolessRunHistory?.refresh?.(); // Workflows → History re-reads only while on screen
11030
10921
  if (m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id); // #2241 S5
11031
10922
  } else if (m.type === 'routine-changed') {
11032
10923
  loadRoutinesData();
@@ -11044,6 +10935,8 @@
11044
10935
  if ($routinesModal.classList.contains('show')) renderRoutinesList();
11045
10936
  } else if (m.type === 'routine-run-ended') {
11046
10937
  runningRoutines.delete(m.id);
10938
+ window.flolessProjectWorkflows?.refresh?.(); // #2470 R6.2, as run-ended
10939
+ window.flolessRunHistory?.refresh?.();
11047
10940
  loadRoutinesData();
11048
10941
  if (window.flolessPanels) window.flolessPanels.refreshData(); // routine runs also refresh bindings
11049
10942
  window.flolessAgents?.refreshRuns?.(); // #2035: an open agent page shows the run its routine just started
@@ -11060,6 +10953,7 @@
11060
10953
  applyRoutineReport(m);
11061
10954
  } else if (m.type === 'workflow-page-captured') {
11062
10955
  applyWorkflowPageCaptured(m);
10956
+ window.flolessRunHistory?.refresh?.(); // the report was saved after run-ended: its row gains View report
11063
10957
  } else if (m.type === 'action-run-report') {
11064
10958
  applyActionRunReport(m);
11065
10959
  } else if (m.type === 'routine-report-changed') {
@@ -11069,7 +10963,7 @@
11069
10963
  // drive its success/fail state from the same SSE result.
11070
10964
  if (credReconnect && credReconnect.id === m.id) {
11071
10965
  if (m.status === 'connected') credReconnect.onSuccess();
11072
- else credReconnect.onFail(m.error);
10966
+ else credReconnect.onFail(typeof m.message === 'string' ? m.message : null);
11073
10967
  }
11074
10968
  // The device-code sign-in resolved. On success, refresh so the card flips
11075
10969
  // to Connected; otherwise surface the outcome in the integration's slot.
@@ -11080,7 +10974,7 @@
11080
10974
  showToast(`Connected ${m.id}`, 'ok');
11081
10975
  refreshIntegrations(`Connected ${m.id}. Account readiness updated.`);
11082
10976
  } else if (slot) {
11083
- slot.innerHTML = `Sign-in ${escapeHtml(m.status || 'failed')}${m.error ? ' — ' + escapeHtml(m.error) : ''}. Click Connect to retry.`;
10977
+ slot.innerHTML = connectResultSlotHtml(m);
11084
10978
  }
11085
10979
  } else if (m.type === 'fs-change' && m.kind === 'credential') {
11086
10980
  // `aware connect`/`disconnect` wrote/removed a token in the local vault —
@@ -11308,7 +11202,6 @@
11308
11202
  try {
11309
11203
  const { request } = await api('/api/knowledge-consult', { method: 'POST', body: JSON.stringify({ appId: app.id }) });
11310
11204
  const copied = await copyToClipboard(markedInstruction(request));
11311
- appendNarration(`Queued a deterministic <code>kb → gate</code> knowledge read for <code>${escapeHtml(app.id)}</code> — your terminal AI will add it. Choose the project and subject, then compile.${copied ? ' The instruction is on your clipboard.' : ''}`);
11312
11205
  showToast(copied ? 'Knowledge read + gate queued · copied to clipboard' : 'Knowledge read + gate queued', 'ok');
11313
11206
  loadRequests();
11314
11207
  } catch (e) { reportErr(e); }
@@ -11387,7 +11280,7 @@
11387
11280
  //
11388
11281
  // WHICH SURFACES MUST USE THIS: every one whose failure message BLAMES a cause — the row ⧉, the
11389
11282
  // request-help modal, the revision card. The queue-then-best-effort-copy callers (useTemplate,
11390
- // tweakNode, requestGuide, requestNewWorkflow, panels.js's customize box) say only "queued, not
11283
+ // tweakNode, requestNewWorkflow, panels.js's customize box) say only "queued, not
11391
11284
  // copied" and name no cause, so they cannot conflate anything and are deliberately left alone. Add
11392
11285
  // a new surface that names a cause and it belongs here.
11393
11286
  async function copyRequest(req, stillOwned = () => true) {
@@ -12611,7 +12504,6 @@
12611
12504
  const { request } = await api('/api/use-template', { method: 'POST', body: JSON.stringify({ appId: currentId, templateId }) });
12612
12505
  const line = markedInstruction(request);
12613
12506
  const copied = await copyToClipboard(line);
12614
- appendNarration(`Queued template <strong>${escapeHtml(request.template.name)}</strong> for workflow <code>${escapeHtml(currentId)}</code> — the UI can’t edit the workflow itself, so your terminal AI picks this up and applies it. ${copied ? 'Instruction copied to your clipboard — paste it in.' : 'Open the requests chip (bottom-right) to copy it.'}`);
12615
12507
  showToast(copied ? 'Queued for your terminal AI · copied to clipboard' : 'Queued for your terminal AI', 'ok');
12616
12508
  loadRequests();
12617
12509
  } catch (e) { reportErr(e); }
@@ -12635,7 +12527,6 @@
12635
12527
  const snaps = Array.isArray(res.snapshots) ? res.snapshots.map((s) => ({ name: s.name, dataUrl: s.dataUrl })) : [];
12636
12528
  const { request } = await api('/api/tweak', { method: 'POST', body: JSON.stringify({ appId: currentId, nodeId: node, instruction, snapshots: snaps }) });
12637
12529
  const copied = await copyToClipboard(markedInstruction(request));
12638
- appendNarration(`Tweak queued for <code>${escapeHtml(node)}</code> — your terminal AI can pull it (floless skill) ${copied ? 'or paste the copied instruction' : ''}.`);
12639
12530
  const toastMsg = snaps.length
12640
12531
  ? `Tweak + ${snaps.length} snapshot(s) queued${copied ? ' + copied' : ''}`
12641
12532
  : copied ? 'Tweak queued + copied' : 'Tweak queued';
@@ -13102,7 +12993,7 @@
13102
12993
  // One path for a question and a change, so a waiting message is never labelled a suggestion.
13103
12994
  return r.instructorContext.commandId === 'filter.ask-ai-change' ? 'filter answer' : 'filter question';
13104
12995
  if (r.type === 'revision-read') return (!r.baseVersion || r.baseVersion <= 0) ? 'initial drawing read' : 'updated drawing read';
13105
- return r.type === 'use-template' ? 'template' : r.type === 'ui-customize' ? 'dashboard' : r.type === 'rebake' ? 're-bake' : r.type === 'guide' ? 'guide' : r.type === 'new-workflow' ? 'new workflow' : r.type === 'knowledge-organize' ? 'organize' : r.type === 'knowledge-adjust' ? 'adjust' : r.type === 'knowledge-consult' ? 'knowledge' : r.type === 'tweak-contract' ? 'contract' : 'tweak';
12996
+ return r.type === 'use-template' ? 'template' : r.type === 'ui-customize' ? 'dashboard' : r.type === 'rebake' ? 're-bake' : r.type === 'guide' ? 'guide' : r.type === 'new-workflow' ? 'new workflow' : r.type === 'knowledge-organize' ? 'organize' : r.type === 'knowledge-adjust' ? 'adjust' : r.type === 'knowledge-consult' ? 'knowledge' : r.type === 'project-kickoff' ? 'kickoff' : r.type === 'tweak-contract' ? 'contract' : 'tweak';
13106
12997
  }
13107
12998
 
13108
12999
  function isInitialDrawingRead(r) {
@@ -15257,6 +15148,16 @@
15257
15148
  window.dispatchEvent(new CustomEvent('floless:revit-capability-changed'));
15258
15149
  });
15259
15150
 
15151
+ // And Steel Model's, under its own name.
15152
+ window.addEventListener('floless:open-steel-model-access', async (event) => {
15153
+ if (event.detail?.state === 'account-selection-required') {
15154
+ await recheckLicenseAndGate({ forRevitAccountSelection: true, moduleLabel: 'Steel Model' });
15155
+ } else {
15156
+ await recheckLicenseAndGate();
15157
+ }
15158
+ window.dispatchEvent(new CustomEvent('floless:revit-capability-changed'));
15159
+ });
15160
+
15260
15161
  function runtimeSectionSummary(runtimes, active, folder) {
15261
15162
  // What FloLess would LAUNCH (#1622): its own copy where it runs one, else the user's install.
15262
15163
  const installed = runtimes.filter(runtimeCopyInstalled);
@@ -15577,6 +15478,14 @@
15577
15478
  });
15578
15479
  }
15579
15480
 
15481
+ // #2649: what Google actually granted an account (people can untick a permission on Google's screen).
15482
+ const GOOGLE_INTEGRATION_ID = 'google-workspace';
15483
+ function googleAccessLine(granted, alias) {
15484
+ // Gmail sending is what emails RFIs, so its absence is the one real fault; a missing Drive list is a choice.
15485
+ if (!granted.gmail) return `Gmail sending isn’t allowed, so FloLess can’t email RFIs. Click ${alias ? 'Reconnect this account' : 'Reconnect'} and leave Gmail sending ticked on Google’s screen.`;
15486
+ return granted.drive ? 'Allowed: Gmail sending and Drive file list.' : 'Allowed: Gmail sending. Not allowed: Drive file list (optional).';
15487
+ }
15488
+
15580
15489
  function renderIntegrationAccounts(integration) {
15581
15490
  const slots = Array.isArray(integration.accountSlots) ? integration.accountSlots : [];
15582
15491
  if (!slots.length) return integration.chatSupported
@@ -15595,24 +15504,49 @@
15595
15504
  let state = 'Unavailable in AI Chat';
15596
15505
  let stateClass = 'is-chat-unavailable';
15597
15506
  let why;
15598
- if (!supported) { state = 'Not available in AI Chat'; why = 'AI Chat can’t use this integration yet.'; }
15507
+ // #2620: AI Chat runs any connected tool's commands with this account (tools.read / tools.change), so a service
15508
+ // without the older per-chat account picker is still usable in chat: its state follows the sign-in alone.
15509
+ if (!supported) {
15510
+ if (slot.status === 'valid') { state = 'Ready for AI Chat'; stateClass = 'is-chat-ready'; why = 'AI Chat uses this account when it runs this tool’s commands.'; }
15511
+ else if (slot.status === 'expired') { state = 'Reconnect for AI Chat'; stateClass = 'is-chat-warning'; why = 'This account’s sign-in has expired. Reconnect it to use it in AI Chat.'; }
15512
+ else why = 'Connect this account to use it in AI Chat.';
15513
+ }
15599
15514
  else if (ready) { state = 'Ready for AI Chat'; stateClass = 'is-chat-ready'; why = 'This verified account can be selected in AI Chat.'; }
15600
15515
  else if (slot.status === 'expired') { state = 'Reconnect for AI Chat'; stateClass = 'is-chat-warning'; why = 'This account’s sign-in has expired. Reconnect it to use it in AI Chat.'; }
15601
15516
  else if (slot.status !== 'valid') { state = 'Connect for AI Chat'; stateClass = 'is-chat-warning'; }
15602
15517
  else if (!verified) { state = 'Reconnect to verify account'; stateClass = 'is-chat-warning'; why = 'FloLess could not verify this account. Reconnect it to use it in AI Chat.'; }
15518
+ if (!why && slot.unavailableCode === 'scope-missing' && integration.id === 'google-workspace') {
15519
+ why = `AI Chat lists your Drive files, so it needs the Drive file list. Tick “also let FloLess list your Google Drive files” and click ${slot.alias ? 'Reconnect this account' : 'Reconnect'} to allow it.`;
15520
+ }
15603
15521
  if (!why) {
15604
15522
  // A server reason is shown only when it is ordinary language; internal wording gets the plain fallback.
15605
15523
  const raw = slot.unavailableReason || '';
15606
15524
  why = raw && !/identity|stableid|binding|registry|verify|principal|capability|operation|aware/i.test(raw)
15607
15525
  ? raw : 'This account is not ready for AI Chat.';
15608
15526
  }
15527
+ // The server reports a grant only for a readable sign-in, so an unreadable one never reads as "not allowed".
15528
+ const access = integration.id === 'google-workspace' && slot.granted
15529
+ ? `<span class="int-account-access${slot.granted.gmail ? '' : ' is-warn'}">${escapeHtml(googleAccessLine(slot.granted, slot.alias))}</span>` : '';
15530
+ // #2649: a named account reconnects on its own whenever it needs a new sign-in or new consent; the card's main
15531
+ // button is the default account's. Its Drive choice is the card's checkbox, the person's current selection.
15532
+ const needsSignIn = slot.status !== 'valid' || (slot.granted && !slot.granted.gmail)
15533
+ || ['scope-missing', 'identity-unverified', 'credential-expired', 'generation-unavailable'].includes(slot.unavailableCode);
15534
+ const reconnect = slot.alias && needsSignIn
15535
+ ? `<button class="int-action int-account-reconnect" type="button" data-int="${escapeAttr(integration.id)}" data-int-action="connect"`
15536
+ + ` data-int-alias="${escapeAttr(slot.alias)}"`
15537
+ + ` data-command-id="shell.integrations-account-reconnect#${escapeAttr(`${integration.id}:${slot.alias}`)}"`
15538
+ + ` data-command-instance-label="${escapeAttr(`${integration.name} account ${slot.alias}`)}"`
15539
+ + ` aria-label="Reconnect ${escapeAttr(integration.name)} account ${escapeAttr(slot.alias)}">Reconnect this account</button>`
15540
+ : '';
15609
15541
  return `<div class="int-account ${stateClass}">
15610
15542
  <div class="int-account-copy">
15611
15543
  <span class="int-account-name">${escapeHtml(account)}</span>
15612
15544
  <span class="int-account-origin">${escapeHtml(slotName)}</span>
15613
15545
  </div>
15614
15546
  <span class="int-chat-state">${state}</span>
15547
+ ${access}
15615
15548
  <span class="int-account-reason">${escapeHtml(why)}</span>
15549
+ ${reconnect}
15616
15550
  </div>`;
15617
15551
  }).join('')}</div>`;
15618
15552
  }
@@ -15667,6 +15601,76 @@
15667
15601
  return 'Revit Parser is not included for this account. Ask the account owner to enable it.';
15668
15602
  }
15669
15603
 
15604
+ /**
15605
+ * #2649: the Google Workspace card's extra parts. Gmail sending (for RFIs) is always asked for; the Drive file
15606
+ * list is the person's choice, and the card shows what Google actually granted, never what was asked for.
15607
+ */
15608
+ function googleCardParts(i) {
15609
+ const access = i.googleAccess || {};
15610
+ const slots = Array.isArray(i.accountSlots) ? i.accountSlots : [];
15611
+ const granted = slots.find((slot) => slot.alias == null)?.granted || null;
15612
+ const driveAllowed = !!granted?.drive;
15613
+ // One notice at a time (the server never offers the switch for the person's own app; this order is only defensive).
15614
+ let notice = '';
15615
+ if (access.client === 'own' && access.ownMessage) {
15616
+ notice = `<div class="int-notice is-warn" role="note">${escapeHtml(access.ownMessage)}</div>`;
15617
+ } else if (access.switchAvailable && i.status !== 'disconnected') {
15618
+ notice = '<div class="int-notice" role="note">FloLess has its own Google sign-in. Click Reconnect to switch to it. Your current sign-in keeps working until then.</div>';
15619
+ }
15620
+ // Connected cards reconnect with the same Drive choice the checkbox shows, preset to what Google allows now.
15621
+ const reconnect = i.status !== 'connected' ? ''
15622
+ : '<button class="int-action" type="button" data-int="google-workspace" data-int-action="connect"'
15623
+ + ` data-command-id="shell.integrations-connect#${escapeAttr(i.id)}" data-command-instance-label="${escapeAttr(i.name)}">Reconnect</button>`;
15624
+ // Shown only when the person clears a Drive permission Google already holds: Google keeps it until it is removed there.
15625
+ // The person's own Google app decides what Google asks for (its file may list scopes), so FloLess offers no choice.
15626
+ const ownApp = access.client === 'own';
15627
+ const driveNote = driveAllowed && !ownApp
15628
+ ? '<div class="int-drive-note" id="int-google-drive-note" aria-live="polite" hidden>Google will still remember the Drive permission you gave. '
15629
+ + 'To take it back, remove the app FloLess signs in with at <a href="https://myaccount.google.com/permissions" target="_blank" rel="noopener">myaccount.google.com/permissions</a>. '
15630
+ + 'That signs FloLess out of Google, Gmail sending included, so click Connect here again afterwards.</div>'
15631
+ : '';
15632
+ const driveChoice = ownApp ? '' : `
15633
+ <label class="int-flow int-flow-drive">
15634
+ <input type="checkbox" class="int-drive-toggle" data-drive-for="${escapeAttr(i.id)}" data-drive-allowed="${driveAllowed ? 'true' : 'false'}"`
15635
+ + ` data-command-id="shell.integrations-google-drive-choice" aria-describedby="int-google-drive-help"${driveAllowed ? ' checked' : ''}> also let FloLess list your Google Drive files
15636
+ </label>
15637
+ <div class="int-drive-help" id="int-google-drive-help">Optional. Gmail sending is always requested so FloLess can email your RFIs.</div>`;
15638
+ return { notice, reconnect, driveNote, driveChoice, deviceCodeAvailable: access.deviceCodeAvailable !== false };
15639
+ }
15640
+
15641
+ /** One OAuth integration's card (#2649: a named function, so its rendered carriers and controls are tested). */
15642
+ function integrationCardHtml(i) {
15643
+ const action = i.status === 'connected' ? 'Disconnect' : i.status === 'expired' ? 'Reconnect' : 'Connect';
15644
+ const badge = i.status === 'connected' ? 'Connected' : i.status === 'expired' ? 'Token expired' : 'Not connected';
15645
+ const meta = i.status === 'disconnected' ? '—' : i.expiresAt ? `expires ${new Date(i.expiresAt).toLocaleString()}` : 'connected';
15646
+ const google = i.id === GOOGLE_INTEGRATION_ID ? googleCardParts(i) : null;
15647
+ return `
15648
+ <div class="int-item int-${i.status}" data-integration-id="${escapeAttr(i.id)}" tabindex="-1">
15649
+ <div class="int-icon" aria-hidden="true">${escapeHtml(VENDOR_ICON[i.vendor] || (i.name[0] || '?'))}</div>
15650
+ <div class="int-info">
15651
+ <div class="int-name">${escapeHtml(i.name)}</div>
15652
+ <div class="int-kind">${i.agent === 'first-party' ? 'Built-in integration' : `${escapeHtml(i.vendor || 'integration')} · tool <code>${escapeHtml(i.agent)}</code>`}</div>
15653
+ <div class="int-scopes">${escapeHtml((i.network || []).join(' · ') || '—')}</div>
15654
+ <div class="int-meta">${escapeHtml(meta)}</div>
15655
+ ${renderIntegrationAccounts(i)}
15656
+ <div class="conn-int" data-conn-int="${escapeAttr(i.id)}"></div>
15657
+ ${google ? google.notice + google.driveChoice + google.driveNote : ''}
15658
+ <div class="int-row">
15659
+ <span class="int-badge int-badge-${i.status}">${badge}</span>
15660
+ <span class="int-recovery-actions">
15661
+ ${google ? google.reconnect : ''}
15662
+ <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>
15663
+ </span>
15664
+ </div>
15665
+ ${i.status === 'connected' || (google && !google.deviceCodeAvailable) ? '' : `
15666
+ <label class="int-flow" data-tip="Use a one-time device code instead of opening the browser — for headless or locked-down machines where the loopback sign-in can't run">
15667
+ <input type="checkbox" class="int-flow-toggle" data-flow="${escapeAttr(i.id)}"> use a device code instead
15668
+ </label>`}
15669
+ <div class="int-devicecode" data-dc="${escapeAttr(i.id)}" role="status" aria-live="polite"></div>
15670
+ </div>
15671
+ </div>`;
15672
+ }
15673
+
15670
15674
  renderIntegrations = function renderIntegrationsReal() {
15671
15675
  if (integrationsLoadState === 'loading' || integrationsLoadState === 'idle') {
15672
15676
  $integrationsList.innerHTML = '<div class="empty-state">Checking integrations…</div>';
@@ -15708,32 +15712,13 @@
15708
15712
  <button class="int-action" data-xeorvt-action="${needsAccount ? 'account' : 'check'}" data-xeorvt-retry="${needsAttention ? 'true' : 'false'}"${needsAttention ? ' data-command-id="shell.integrations-revit-retry-setup" aria-describedby="xeorvt-setup-detail"' : ''}>${checkLabel}</button>
15709
15713
  </span></div></div></div>`;
15710
15714
  }
15711
- const action = i.status === 'connected' ? 'Disconnect' : i.status === 'expired' ? 'Reconnect' : 'Connect';
15712
- const badge = i.status === 'connected' ? 'Connected' : i.status === 'expired' ? 'Token expired' : 'Not connected';
15713
- const meta = i.status === 'disconnected' ? '—' : i.expiresAt ? `expires ${new Date(i.expiresAt).toLocaleString()}` : 'connected';
15714
- return `
15715
- <div class="int-item int-${i.status}" data-integration-id="${escapeAttr(i.id)}" tabindex="-1">
15716
- <div class="int-icon" aria-hidden="true">${escapeHtml(VENDOR_ICON[i.vendor] || (i.name[0] || '?'))}</div>
15717
- <div class="int-info">
15718
- <div class="int-name">${escapeHtml(i.name)}</div>
15719
- <div class="int-kind">${i.agent === 'first-party' ? 'Built-in integration' : `${escapeHtml(i.vendor || 'integration')} · tool <code>${escapeHtml(i.agent)}</code>`}</div>
15720
- <div class="int-scopes">${escapeHtml((i.network || []).join(' · ') || '—')}</div>
15721
- <div class="int-meta">${escapeHtml(meta)}</div>
15722
- ${renderIntegrationAccounts(i)}
15723
- <div class="conn-int" data-conn-int="${escapeAttr(i.id)}"></div>
15724
- <div class="int-row">
15725
- <span class="int-badge int-badge-${i.status}">${badge}</span>
15726
- <button class="int-action" data-int="${escapeAttr(i.id)}" data-int-action="${action.toLowerCase()}">${action}</button>
15727
- </div>
15728
- ${i.status === 'connected' ? '' : `
15729
- <label class="int-flow" data-tip="Use a one-time device code instead of opening the browser — for headless or locked-down machines where the loopback sign-in can't run">
15730
- <input type="checkbox" class="int-flow-toggle" data-flow="${escapeAttr(i.id)}"> use a device code instead
15731
- </label>`}
15732
- <div class="int-devicecode" data-dc="${escapeAttr(i.id)}"></div>
15733
- </div>
15734
- </div>`;
15715
+ return integrationCardHtml(i);
15735
15716
  }).join('');
15736
15717
  offerClippedScopeLines($integrationsList);
15718
+ // #2649: clearing a Drive permission Google already holds says how to really take it back.
15719
+ $integrationsList.querySelectorAll('.int-drive-toggle[data-drive-allowed="true"]').forEach((box) => {
15720
+ box.onchange = () => { const note = document.getElementById('int-google-drive-note'); if (note) note.hidden = box.checked; };
15721
+ });
15737
15722
  void decorateIntegrationConnections();
15738
15723
  $integrationsList.querySelectorAll('[data-xeorvt-action]').forEach((btn) => {
15739
15724
  btn.onclick = async () => {
@@ -15795,7 +15780,8 @@
15795
15780
  showToast(`${copied ? 'Copied — run' : 'Run'} in your terminal: ${cmd}`, 'info');
15796
15781
  return;
15797
15782
  }
15798
- await startConnect(btn.dataset.int);
15783
+ // #2649: a named account's own Reconnect carries its account; the Drive choice is the card's checkbox.
15784
+ await startConnect(btn.dataset.int, btn.dataset.intAlias ? { alias: btn.dataset.intAlias } : {});
15799
15785
  };
15800
15786
  });
15801
15787
  };
@@ -15870,7 +15856,7 @@
15870
15856
  function dcSlot(id) {
15871
15857
  return $integrationsList.querySelector(`.int-devicecode[data-dc="${(window.CSS && CSS.escape) ? CSS.escape(id) : id}"]`);
15872
15858
  }
15873
- async function startConnect(id) {
15859
+ async function startConnect(id, opts = {}) {
15874
15860
  if (connecting.has(id)) return;
15875
15861
  connecting.add(id);
15876
15862
  const slot = dcSlot(id);
@@ -15879,14 +15865,26 @@
15879
15865
  // loopback-blocked machines.
15880
15866
  const selectorId = (window.CSS && CSS.escape) ? CSS.escape(id) : id;
15881
15867
  const toggle = $integrationsList.querySelector(`.int-flow-toggle[data-flow="${selectorId}"]`);
15882
- const body = toggle && toggle.checked ? JSON.stringify({ flow: 'device-code' }) : '{}';
15868
+ // #2649: Google's Drive choice is the card's checkbox, preset to what Google allows the default account now. Sent
15869
+ // either way, so an unticked box really asks without Drive (a request with no choice keeps the current one).
15870
+ const driveToggle = $integrationsList.querySelector(`.int-drive-toggle[data-drive-for="${selectorId}"]`);
15871
+ const body = JSON.stringify({
15872
+ ...(toggle && toggle.checked ? { flow: 'device-code' } : {}),
15873
+ ...(driveToggle ? { drive: driveToggle.checked } : {}),
15874
+ ...(opts.alias ? { alias: opts.alias } : {}),
15875
+ });
15883
15876
  if (slot) slot.innerHTML = 'Starting sign-in…';
15884
15877
  try {
15885
15878
  const res = await api(`/api/connect/${encodeURIComponent(id)}`, { method: 'POST', body });
15886
15879
  // A managed-preset pre-flight (e.g. port 80 already in use) refuses to start
15887
15880
  // and broadcasts the reason over SSE (connect-result). Clear the guard so the
15888
- // user can retry after fixing it, and don't claim the browser opened.
15889
- if (res && res.started === false) { connecting.delete(id); return; }
15881
+ // user can retry after fixing it, and don't claim the browser opened. #2649: the
15882
+ // reason also comes back here, so a card waiting on a reconnecting SSE still says why.
15883
+ if (res && res.started === false) {
15884
+ connecting.delete(id);
15885
+ if (slot && typeof res.message === 'string') slot.innerHTML = connectResultSlotHtml({ status: 'failed', message: res.message });
15886
+ return;
15887
+ }
15890
15888
  if (slot) {
15891
15889
  if (res.flow === 'device-code' && res.prompt) {
15892
15890
  // Fallback flow: show the device code to enter at the verification URL.
@@ -15900,11 +15898,20 @@
15900
15898
  }
15901
15899
  } catch (e) {
15902
15900
  connecting.delete(id);
15903
- if (slot) slot.innerHTML = '';
15904
- reportErr(e);
15901
+ // #2649: the route's own refusal (an account name it cannot use) is shown where the person clicked. Only a 400 is
15902
+ // the route's sentence; anything else goes to the usual error report.
15903
+ const said = e && e.status === 400 && e.body && typeof e.body.error === 'string' ? e.body.error : '';
15904
+ if (slot) slot.innerHTML = said ? escapeHtml(said) : '';
15905
+ if (!said) reportErr(e);
15905
15906
  }
15906
15907
  }
15907
15908
 
15909
+ /** The sign-in result line on a card: the server's own sentence when it sent one (#2649), else the composed line. */
15910
+ function connectResultSlotHtml(m) {
15911
+ return m.message ? escapeHtml(m.message)
15912
+ : `Sign-in ${escapeHtml(m.status || 'failed')}${m.error ? ' — ' + escapeHtml(m.error) : ''}. Click Connect to retry.`;
15913
+ }
15914
+
15908
15915
  // Show the per-node Tweak button when a node is selected, and the Debug-in-VS
15909
15916
  // button only for exec nodes (those carry C# the host can run under a debugger).
15910
15917
  // Debug lives HERE in the main window, not in the report modal.
@@ -16991,10 +16998,9 @@
16991
16998
  try {
16992
16999
  const res = await api('/api/trigger-run', { method: 'POST', body: JSON.stringify({ id, inputs: currentInputs() }) });
16993
17000
  foregroundTrigger = { appId: id, sessionId: res.sessionId, firedCount: 0 };
16994
- markFirstRunDone(id); // a real live session started → a streaming workflow's "first run" is no longer new
16995
17001
  paintForegroundListening();
16996
17002
  beatLiveViewer();
16997
- appendNarration(`Live session started for <strong>${escapeHtml(id)}</strong> — the report updates on every event. Click <strong>■ Stop run</strong> (top right) to end it.`);
17003
+ showToast(`Live session started for ${id}. The report updates on every event; ■ Stop run (top right) ends it.`, 'ok');
16998
17004
  } catch (e) {
16999
17005
  // A refusal (a watcher already holds this host) names the concrete path back —
17000
17006
  // never a dead end. Other failures are recoverable; the server returns them
@@ -18345,25 +18351,6 @@
18345
18351
  }
18346
18352
  });
18347
18353
 
18348
- // Per-workflow onboarding beacon + guide panel + first-open spotlight.
18349
- const $guideBeaconBtn = document.getElementById('guide-beacon');
18350
- if ($guideBeaconBtn) $guideBeaconBtn.onclick = () => { hideSpotlight(); openGuide(); };
18351
- const $guideModal = document.getElementById('guide-modal');
18352
- const $guideGot = document.getElementById('guide-got-it');
18353
- if ($guideGot) $guideGot.onclick = () => closeGuide();
18354
- const $guideWalk = document.getElementById('guide-walk');
18355
- if ($guideWalk) $guideWalk.onclick = () => requestGuide();
18356
- if ($guideModal) onBackdropDismiss($guideModal, () => closeGuide());
18357
- document.addEventListener('keydown', (e) => {
18358
- if (e.key === 'Escape' && $guideModal && $guideModal.classList.contains('show')) closeGuide();
18359
- });
18360
- const $spotGot = document.getElementById('guide-spotlight-got');
18361
- if ($spotGot) $spotGot.onclick = () => hideSpotlight();
18362
- const $spotShow = document.getElementById('guide-spotlight-show');
18363
- if ($spotShow) $spotShow.onclick = () => { hideSpotlight(); openGuide(); };
18364
- const $spotlightEl = document.getElementById('guide-spotlight');
18365
- if ($spotlightEl) $spotlightEl.onclick = (e) => { if (e.target === $spotlightEl) hideSpotlight(); };
18366
-
18367
18354
  // Pull all workspace data (agents/templates/requests + the apps list). Factored
18368
18355
  // out of bootWorkspace so the health poll can re-pull it after the server comes
18369
18356
  // back from a boot-time outage (setServerStatus → recovery).
@@ -18378,6 +18365,9 @@
18378
18365
  if (window.flolessPanels) window.flolessPanels.boot();
18379
18366
  return loadApps().catch((e) => {
18380
18367
  reportErr(e);
18368
+ // #2644: a module refusal means the server answered; it is never "unreachable". (loadApp already shows a refused
18369
+ // workflow as locked; this keeps any other path from painting the offline screen over that answer.)
18370
+ if (moduleRefusalText(e)) { if ($wfTrigger && wfLibrary.length) $wfTrigger.disabled = false; return; }
18381
18371
  setComboTriggerLabel('server unreachable');
18382
18372
  renderCanvasPlaceholder('offline');
18383
18373
  // Only now — the workflow-update offer must never race the data the picker needs (#358).
@@ -18754,10 +18744,11 @@
18754
18744
  const $wfLanding = document.getElementById('wf-landing');
18755
18745
  // The landing search's query, kept outside the input because the landing re-renders with innerHTML.
18756
18746
  let wfLandingQuery = '';
18757
- // #2568: the landing's two tabs. The choice is remembered by this browser window; anything unknown, or a store that
18758
- // throws (private window, blocked site data), reads as Workflows.
18747
+ // #2568: the landing's tabs (History: every run, grouped per workflow). The choice is remembered by this browser window;
18748
+ // anything unknown, or a store that throws (private window, blocked site data), reads as Workflows.
18759
18749
  const WF_TAB_KEY = 'floless.workflowsLandingTab';
18760
- let wfLandingTab = (() => { try { return localStorage.getItem(WF_TAB_KEY) === 'pages' ? 'pages' : 'workflows'; } catch { return 'workflows'; } })();
18750
+ const WF_TABS = ['workflows', 'pages', 'history'];
18751
+ let wfLandingTab = (() => { try { const t = localStorage.getItem(WF_TAB_KEY); return WF_TABS.includes(t) ? t : 'workflows'; } catch { return 'workflows'; } })();
18761
18752
  function showWorkflowsLanding(on) {
18762
18753
  const next = Boolean(on);
18763
18754
  if (next === wfLanding && (!next || $wfLanding?.childElementCount)) { if (next) renderWorkflowsLanding(); return; }
@@ -18768,8 +18759,7 @@
18768
18759
  if ($wfLanding) $wfLanding.hidden = !wfLanding;
18769
18760
  // Nothing reads routines at startup (only the Routines window, routine events and a few report paths do), so the
18770
18761
  // cards' "Scheduled" chips need a read here.
18771
- if (wfLanding) { hideSpotlight(); renderWorkflowsLanding(); void loadRoutinesData(); }
18772
- else syncSpotlightToMode(); // the canvas is back: a spotlight held back while the list covered it is offered
18762
+ if (wfLanding) { renderWorkflowsLanding(); void loadRoutinesData(); }
18773
18763
  syncTabTitle();
18774
18764
  notifyChatScope();
18775
18765
  }
@@ -18810,19 +18800,20 @@
18810
18800
  /** The Workflows landing's heading, sub line, tabs and (when there is something to search) search box, shared by both tabs. */
18811
18801
  function workflowsLandingHeadHtml(esc, showSearch) {
18812
18802
  const pages = wfLandingTab === 'pages';
18803
+ const history = wfLandingTab === 'history';
18813
18804
  const tab = (id, label) => `<button type="button" role="tab" id="wf-tab-${id}" data-wf-tab="${id}" class="${wfLandingTab === id ? 'active' : ''}"`
18814
- + ` aria-selected="${wfLandingTab === id}"${id === 'pages' ? ' aria-controls="wf-pages-panel"' : ''} tabindex="${wfLandingTab === id ? 0 : -1}"`
18805
+ + ` aria-selected="${wfLandingTab === id}"${id !== 'workflows' ? ` aria-controls="wf-${id}-panel"` : ''} tabindex="${wfLandingTab === id ? 0 : -1}"`
18815
18806
  + ` data-command-id="shell.workflows-landing-tab#${esc(id)}">${label}</button>`;
18816
18807
  return `<div class="ws-head"><div class="ws-head-text"><h2 tabindex="-1" id="wf-landing-title">Workflows</h2>`
18817
18808
  + `<p class="ws-sub">Build, run and manage the workflows behind your projects. Ask AI Chat on the left to build one with you.</p>`
18818
- + `<div class="tabs ws-step-tabs wf-landing-tabs" role="tablist" aria-label="Workflows page">${tab('workflows', 'Workflows')}${tab('pages', 'Pages')}</div></div>`
18819
- + (showSearch ? `<div class="ws-head-actions"><input type="search" id="wf-landing-search" class="ws-landing-search" data-command-id="shell.workflows-landing-search" placeholder="${pages ? 'Search pages' : 'Search workflows'}" aria-label="${pages ? 'Search Pages by workflow, Page title or project' : 'Search workflows by name, project or tool'}" autocomplete="off" spellcheck="false" value="${esc(wfLandingQuery)}"></div>` : '')
18809
+ + `<div class="tabs ws-step-tabs wf-landing-tabs" role="tablist" aria-label="Workflows page">${tab('workflows', 'Workflows')}${tab('pages', 'Pages')}${tab('history', 'History')}</div></div>`
18810
+ + (showSearch ? `<div class="ws-head-actions"><input type="search" id="wf-landing-search" class="ws-landing-search" data-command-id="shell.workflows-landing-search" placeholder="${history ? 'Search runs' : pages ? 'Search pages' : 'Search workflows'}" aria-label="${history ? 'Search runs by workflow or project' : pages ? 'Search Pages by workflow, Page title or project' : 'Search workflows by name, project or tool'}" autocomplete="off" spellcheck="false" value="${esc(wfLandingQuery)}"></div>` : '')
18820
18811
  + `</div>`;
18821
18812
  }
18822
18813
 
18823
18814
  /** Switch the landing's tab: remember it, repaint, and (for a keyboard or button move) put focus on the chosen tab. */
18824
18815
  function setWorkflowsLandingTab(tab, focusTab) {
18825
- const next = tab === 'pages' ? 'pages' : 'workflows';
18816
+ const next = WF_TABS.includes(tab) ? tab : 'workflows';
18826
18817
  if (next !== wfLandingTab) {
18827
18818
  wfLandingTab = next;
18828
18819
  try { localStorage.setItem(WF_TAB_KEY, next); } catch { /* not remembered; the tab still switches */ }
@@ -18855,9 +18846,37 @@
18855
18846
  if (keepCaret) { const box = $wfLanding.querySelector('#wf-landing-search'); box?.focus(); box?.setSelectionRange?.(keepCaret[0], keepCaret[1]); }
18856
18847
  }
18857
18848
 
18849
+ /** The History tab: the heading and tabs, the search, and a panel run-history.js fills with every run, per workflow. */
18850
+ function renderWorkflowsHistoryTab() {
18851
+ const focusedTab = document.activeElement?.closest?.('#wf-landing [data-wf-tab]')?.dataset.wfTab || null;
18852
+ const search = document.activeElement?.id === 'wf-landing-search' ? document.activeElement : null;
18853
+ const keepCaret = search ? [search.selectionStart, search.selectionEnd] : null;
18854
+ const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
18855
+ $wfLanding.innerHTML = workflowsLandingHeadHtml(esc, true)
18856
+ + '<div id="wf-history-panel" class="wf-history-panel" role="tabpanel" aria-labelledby="wf-tab-history"></div>';
18857
+ const panel = $wfLanding.querySelector('#wf-history-panel');
18858
+ if (window.flolessRunHistory?.render) {
18859
+ void window.flolessRunHistory.render(panel, {
18860
+ getQuery: () => wfLandingQuery,
18861
+ onAction: (act) => {
18862
+ if (act === 'show-workflows') setWorkflowsLandingTab('workflows', true);
18863
+ else if (act === 'clear-search') { setWorkflowsLandingQuery(''); $wfLanding.querySelector('#wf-landing-search')?.focus(); }
18864
+ },
18865
+ openWorkflow: (id) => openWorkflowFromLanding(id),
18866
+ openDraft: (workflowId) => { if (!landingOpening) openDraftWorkflow(workflowId); },
18867
+ openReport: (id, runId) => window.flolessBridge.openAppReport(id, runId),
18868
+ });
18869
+ } else {
18870
+ panel.innerHTML = '<div class="pg-empty" role="alert"><p>FloLess couldn’t load the run history. Check that FloLess is running, then try again.</p></div>';
18871
+ }
18872
+ if (focusedTab) $wfLanding.querySelector(`[data-wf-tab="${focusedTab}"]`)?.focus();
18873
+ if (keepCaret) { const box = $wfLanding.querySelector('#wf-landing-search'); box?.focus(); box?.setSelectionRange?.(keepCaret[0], keepCaret[1]); }
18874
+ }
18875
+
18858
18876
  function renderWorkflowsLanding() {
18859
18877
  if (!$wfLanding) return;
18860
18878
  if (wfLandingTab === 'pages') { renderWorkflowsPagesTab(); return; }
18879
+ if (wfLandingTab === 'history') { renderWorkflowsHistoryTab(); return; }
18861
18880
  const focusedTab = document.activeElement?.closest?.('#wf-landing [data-wf-tab]')?.dataset.wfTab || null;
18862
18881
  const focusedId = document.activeElement?.closest?.('#wf-landing [data-wf-id]')?.dataset.wfId || null;
18863
18882
  const search = document.activeElement?.id === 'wf-landing-search' ? document.activeElement : null;
@@ -18940,6 +18959,7 @@
18940
18959
  + `<div class="ws-thumb">+</div><div class="ws-body"><div><div class="ws-name">New workflow</div>`
18941
18960
  + `<div class="ws-meta">Name it and choose where it belongs. AI builds it with you.</div></div></div></div></div>`
18942
18961
  + unreadableNote
18962
+ + '<div class="wf-setapart-slot ws-workflows"></div>'
18943
18963
  + (wfLibrary.length || unlisted.length || archived.length || restoredRows.length
18944
18964
  ? yoursSection + section('installed', 'data-command-id="shell.workflows-landing-installed"', 'Installed', installed.length, installed.map(card).join(''), true)
18945
18965
  + section('archived', 'data-command-id="shell.workflows-landing-archived"', 'Archived', archived.length, archived.map(archivedCard).join(''), false)
@@ -18955,6 +18975,8 @@
18955
18975
  if (focusedDraft) $wfLanding.querySelector(`[data-wf-draft="${CSS.escape(focusedDraft)}"]`)?.focus();
18956
18976
  if (focusedRestore) $wfLanding.querySelector(`[data-wf-restore="${CSS.escape(focusedRestore)}"]:not(:disabled)`)?.focus();
18957
18977
  if (focusedRestored) $wfLanding.querySelector(`[data-wf-restored="${CSS.escape(focusedRestored)}"]`)?.focus();
18978
+ // #2603: project-workflows.js paints the set-apart folders it owns the answers for (globalThis: harnesses lack it).
18979
+ globalThis.flolessProjectWorkflows?.renderLandingSetApart?.($wfLanding.querySelector('.wf-setapart-slot'), wfSetApart, () => loadApps());
18958
18980
  if (keepCaret) $wfLanding.querySelector('#wf-landing-search')?.focus();
18959
18981
  applyWorkflowsLandingSearch(keepCaret);
18960
18982
  if (clearFocused) $wfLanding.querySelector('#wf-search-clear')?.focus(); // it only exists once the filter ran
@@ -18969,6 +18991,7 @@
18969
18991
  if (!input) return;
18970
18992
  // The Pages tab filters its own rows (pages.js), from the same query.
18971
18993
  if (wfLandingTab === 'pages') { window.flolessPages?.repaintWorkflowsList?.($wfLanding.querySelector('#wf-pages-panel')); return; }
18994
+ if (wfLandingTab === 'history') { window.flolessRunHistory?.repaint?.($wfLanding.querySelector('#wf-history-panel')); return; }
18972
18995
  const terms = wfLandingQuery.trim().toLowerCase().split(/\s+/).filter(Boolean);
18973
18996
  let shownAll = 0;
18974
18997
  for (const grid of $wfLanding.querySelectorAll('.ws-grid')) {
@@ -19015,8 +19038,9 @@
19015
19038
  // load keeps the landing and reports why.
19016
19039
  const loading = loadApp(id);
19017
19040
  const ticket = selectionTicket;
19018
- loading.then(() => {
19019
- if (ticket === selectionTicket && currentId === id) showWorkflowsLanding(false);
19041
+ loading.then((outcome) => {
19042
+ // #2644: a locked module workflow leaves the landing too, onto its locked canvas.
19043
+ if (ticket === selectionTicket && (currentId === id || outcome?.locked)) showWorkflowsLanding(false);
19020
19044
  }).catch(reportErr).finally(() => { landingOpening = false; });
19021
19045
  }
19022
19046
 
@@ -19058,8 +19082,6 @@
19058
19082
  }
19059
19083
  document.body.classList.add('wf-draft-open');
19060
19084
  $wfDraft.hidden = false;
19061
- hideSpotlight();
19062
- paintBeacon(null);
19063
19085
  renderDraftView();
19064
19086
  paintDraftChrome();
19065
19087
  syncTabTitle();
@@ -19298,7 +19320,7 @@
19298
19320
  const onTab = event.target.closest?.('[data-wf-tab]');
19299
19321
  if (onTab && ['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {
19300
19322
  event.preventDefault();
19301
- const order = ['workflows', 'pages'];
19323
+ const order = WF_TABS;
19302
19324
  const at = order.indexOf(onTab.dataset.wfTab);
19303
19325
  const to = event.key === 'Home' ? 0 : event.key === 'End' ? order.length - 1
19304
19326
  : (at + (event.key === 'ArrowRight' ? 1 : order.length - 1)) % order.length;
@@ -19360,8 +19382,10 @@
19360
19382
  else if (owned) return openDraftWorkflow(owned.workflowId);
19361
19383
  else throw new Error('That workflow is not on your Workflows page, so FloLess cannot open it. Compile it from the terminal that installed it.');
19362
19384
  }
19363
- await loadApp(appId);
19385
+ const outcome = await loadApp(appId);
19364
19386
  showWorkflowsLanding(false);
19387
+ // #2644: say why it did not open (the locked canvas shows the same sentence), never report it as opened.
19388
+ if (outcome?.locked) throw new Error(outcome.locked);
19365
19389
  return true;
19366
19390
  },
19367
19391
  // #2247: open a workflow and its report viewer on the last report (a chat card's "View report"). Shows only what
@@ -19563,8 +19587,6 @@
19563
19587
  getChatScope() {
19564
19588
  return currentChatScope();
19565
19589
  },
19566
- // #2007: the workflow spotlight follows the tab switch (see syncSpotlightToMode).
19567
- syncGuideSpotlight: () => syncSpotlightToMode(),
19568
19590
  // #1890: the active Workflows tab is the way home to the Workflows landing (as Workspaces' is to its own).
19569
19591
  // workspaces.js calls this when the user switches back into Workflows: the landing stays mounted behind
19570
19592
  // Workspaces, so showWorkflowsLanding's own fresh-visit reset never runs on that path.
@@ -19605,41 +19627,6 @@
19605
19627
  && request.chatConversation?.executionOwner === 'chat' && request.chatConversation.chatId === chatId);
19606
19628
  return read ? { requestId: read.id } : null;
19607
19629
  },
19608
- // ── Workspaces guide beacon (the SAME #guide-beacon/#guide-modal, document variant) ──
19609
- // workspaces.js owns the open project + its lifecycle state; aware.js owns the beacon
19610
- // chrome. workspaces.js calls setWorkspaceGuide() with a small snapshot whenever the
19611
- // open project (or its approve/export state) changes, clearWorkspaceGuide() on close/
19612
- // Workflows-mode, and markWorkspaceApproved() the first time an Approve succeeds (which
19613
- // calms the beacon, mirroring markFirstRunDone for a workflow's first Run).
19614
- setWorkspaceGuide(ctx) {
19615
- // ctx: { app, name, displayName?, approved, exported }. Null/!app → treat as clear.
19616
- wsGuideCtx = (ctx && ctx.app) ? { ...ctx } : null;
19617
- if (inWorkspacesMode()) {
19618
- paintWorkspaceBeacon();
19619
- const $m = document.getElementById('guide-modal');
19620
- if ($m && $m.classList.contains('show') && wsGuideCtx) renderWorkspaceGuide();
19621
- }
19622
- },
19623
- clearWorkspaceGuide() {
19624
- wsGuideCtx = null;
19625
- // Repaint through the mode-correct painter. In Workspaces mode paintWorkspaceBeacon() hides the
19626
- // (now-cleared) workspace beacon. On the mode-switch-BACK path we're already in Workflows mode,
19627
- // so repaint the WORKFLOW beacon for the current app instead of no-op'ing — otherwise the stale
19628
- // workspace label/tooltip/is-new lingers until the next workflow load. paintBeacon(null) is safe
19629
- // (it just hides the workflow beacon when no app is open).
19630
- if (inWorkspacesMode()) paintWorkspaceBeacon();
19631
- else paintBeacon(currentId ? apps.get(currentId) : null);
19632
- },
19633
- markWorkspaceApproved(app) {
19634
- if (!app || guideFor(wsGuideKey(app)).approveDone) return;
19635
- setGuide(wsGuideKey(app), { approveDone: true });
19636
- if (wsGuideCtx && wsGuideCtx.app === app) {
19637
- wsGuideCtx.approved = true;
19638
- if (inWorkspacesMode()) paintWorkspaceBeacon();
19639
- const $m = document.getElementById('guide-modal');
19640
- if ($m && $m.classList.contains('show')) renderWorkspaceGuide();
19641
- }
19642
- },
19643
19630
  };
19644
19631
 
19645
19632
  // ── boot ──────────────────────────────────────────────────────────────────────