@floless/app 0.159.0 → 0.161.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 +76823 -65608
  2. package/dist/schemas/steel.model.v2.schema.json +24 -0
  3. package/dist/skills/floless-app-onboarding/SKILL.md +4 -3
  4. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +1 -2
  5. package/dist/skills/floless-app-rfi/SKILL.md +44 -3
  6. package/dist/skills/floless-app-steel-model/SKILL.md +2 -2
  7. package/dist/skills/floless-app-steel-takeoff/SKILL.md +417 -261
  8. package/dist/templates/steel-model.flo +6 -2
  9. package/dist/templates/viewer-3d-demo.flo +8 -2
  10. package/dist/web/app.css +342 -160
  11. package/dist/web/app.js +17 -51
  12. package/dist/web/aware.js +656 -574
  13. package/dist/web/chat-question-card.js +27 -1
  14. package/dist/web/chat.css +185 -30
  15. package/dist/web/chat.js +2099 -255
  16. package/dist/web/commands-drawing-check.js +1 -0
  17. package/dist/web/commands-filter.js +11 -0
  18. package/dist/web/commands-shell.js +1118 -134
  19. package/dist/web/commands-steel.js +41 -38
  20. package/dist/web/drawing-check-editor.js +76 -3
  21. package/dist/web/guide.js +8 -0
  22. package/dist/web/index.html +68 -42
  23. package/dist/web/instructor.js +17 -6
  24. package/dist/web/pages.js +158 -30
  25. package/dist/web/panels.js +19 -1
  26. package/dist/web/project-history.js +349 -0
  27. package/dist/web/project-reconciliation.js +1 -0
  28. package/dist/web/project-rfis.js +954 -0
  29. package/dist/web/project-workflows.js +236 -4
  30. package/dist/web/run-history.js +198 -0
  31. package/dist/web/run-page-view.js +12 -2
  32. package/dist/web/startup-admission.js +53 -7
  33. package/dist/web/steel-3d-core.js +144 -7
  34. package/dist/web/steel-3d-view.js +61 -5
  35. package/dist/web/steel-editor.html +510 -128
  36. package/dist/web/steel-filter.html +139 -0
  37. package/dist/web/steel-model-v2-commands.js +3 -3
  38. package/dist/web/steel-model-v2-projection.js +139 -4
  39. package/dist/web/steel-plan-transform.js +78 -0
  40. package/dist/web/tool-updates.js +5 -0
  41. package/dist/web/workspaces.js +1438 -159
  42. package/launch.mjs +36 -5
  43. package/package.json +7 -4
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
  }
@@ -2068,93 +1826,9 @@
2068
1826
  // #1890 PR 3b-0: the new draft opens, so it is somewhere to come back to — not only a toast.
2069
1827
  try { ({ workflows: wfOwned } = await api('/api/workflows/owned')); openDraftWorkflow(workflow.workflowId); }
2070
1828
  catch { /* the draft is still on the Workflows page after the next refresh */ }
2071
- 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.' : ''}`);
2072
1829
  loadRequests();
2073
1830
  }
2074
1831
 
2075
- // ── First-open spotlight (one-time per workflow) ────────────────────────────
2076
- // Dims the canvas, raises the beacon, and points a small caption at it; Esc /
2077
- // click-away / either button dismiss it for good. Slice 2 of the onboarding beacon.
2078
- let _spotlightKey = null;
2079
- let _spotlightResize = null;
2080
- // The spotlight points at the workflow canvas, so it lives only while that canvas is on screen (#2007): it is held
2081
- // back (not used up) while Workspaces, Agents or the Workflows list covers it, and syncSpotlightToMode() follows
2082
- // every tab switch and the list closing.
2083
- const canvasHidden = () => document.body.classList.contains('mode-agents') || inWorkspacesMode() || wfLanding;
2084
- function maybeSpotlight(app) {
2085
- if (!app) return;
2086
- const g = guideFor(app.id);
2087
- if (g.spotlightShown || g.dismissed || g.firstRunDone) return;
2088
- if (document.querySelector('.modal-backdrop.show')) return; // don't pile on a dialog
2089
- if ($contractEditor && !$contractEditor.hidden) return;
2090
- setTimeout(() => {
2091
- // Checked when it would open, so a workflow loaded behind Workspaces or Agents keeps its spotlight for later.
2092
- if (currentId !== app.id || canvasHidden()) return; // switched away during the delay
2093
- if (guideFor(app.id).spotlightShown) return;
2094
- if (document.querySelector('.modal-backdrop.show')) return;
2095
- if ($contractEditor && !$contractEditor.hidden) return; // the editor opened during the delay
2096
- showSpotlight(app);
2097
- }, 700);
2098
- }
2099
- // Where the first-open caption bubble sits: just under the anchor (right-aligned to it), clamped so the
2100
- // whole bubble stays inside the viewport. A zero-sized / missing anchor (the beacon is not laid out on
2101
- // the landing) falls back to the top-right corner instead of the window origin (#2020).
2102
- function spotlightBubblePosition(anchor, vw, vh, bw, bh) {
2103
- const M = 8;
2104
- const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
2105
- const laidOut = !!anchor && Number.isFinite(anchor.right) && Number.isFinite(anchor.bottom)
2106
- && (anchor.width > 0 || anchor.height > 0);
2107
- const left = laidOut ? anchor.right - bw : vw - bw - 16;
2108
- const top = laidOut ? anchor.bottom + 10 : 64;
2109
- return { left: clamp(left, M, Math.max(M, vw - bw - M)), top: clamp(top, M, Math.max(M, vh - bh - M)) };
2110
- }
2111
- // Anchor the caption bubble just under the beacon, right-aligned to it, and keep the whole bubble
2112
- // (so its Got it / Show me buttons) inside the window even when the beacon is not laid out (#2020).
2113
- function placeSpotlightBubble($sp, $b) {
2114
- const bubble = $sp.querySelector('.guide-spotlight-bubble');
2115
- if (!bubble) return;
2116
- bubble.style.maxWidth = Math.max(0, Math.min(280, window.innerWidth - 16)) + 'px';
2117
- bubble.style.left = '0px'; bubble.style.top = '0px'; bubble.style.right = 'auto';
2118
- const pos = spotlightBubblePosition($b.getBoundingClientRect(), window.innerWidth, window.innerHeight,
2119
- bubble.offsetWidth, bubble.offsetHeight);
2120
- bubble.style.left = pos.left + 'px';
2121
- bubble.style.top = pos.top + 'px';
2122
- }
2123
- function showSpotlight(app) {
2124
- const $sp = document.getElementById('guide-spotlight');
2125
- const $b = document.getElementById('guide-beacon');
2126
- if (!$sp || !$b || $b.hidden) return;
2127
- setGuide(app.id, { spotlightShown: true });
2128
- $b.classList.add('spotlit');
2129
- $sp.hidden = false;
2130
- const bubble = $sp.querySelector('.guide-spotlight-bubble');
2131
- placeSpotlightBubble($sp, $b);
2132
- // The window can narrow while the tip is open: re-clamp so Got it / Show me never leave the screen (#2020).
2133
- releaseSpotlightListeners(); // a repeated show (guide state could not be saved) must not stack listeners
2134
- _spotlightResize = () => placeSpotlightBubble($sp, $b);
2135
- window.addEventListener('resize', _spotlightResize);
2136
- _spotlightKey = (e) => { if (e.key === 'Escape') { e.preventDefault(); hideSpotlight(); } };
2137
- document.addEventListener('keydown', _spotlightKey);
2138
- if (bubble) { try { bubble.focus(); } catch { /* */ } }
2139
- }
2140
- // Called by workspaces.js after every tab switch: leaving Workflows closes an open spotlight; coming back offers one
2141
- // that was held back while the canvas was hidden. One already shown stays shown-once.
2142
- function syncSpotlightToMode() {
2143
- if (canvasHidden()) { hideSpotlight(); return; }
2144
- maybeSpotlight(currentId && apps.get(currentId));
2145
- }
2146
- function hideSpotlight() {
2147
- const $sp = document.getElementById('guide-spotlight');
2148
- const $b = document.getElementById('guide-beacon');
2149
- if ($sp) $sp.hidden = true;
2150
- if ($b) $b.classList.remove('spotlit');
2151
- releaseSpotlightListeners();
2152
- }
2153
- function releaseSpotlightListeners() {
2154
- if (_spotlightKey) { document.removeEventListener('keydown', _spotlightKey); _spotlightKey = null; }
2155
- if (_spotlightResize) { window.removeEventListener('resize', _spotlightResize); _spotlightResize = null; }
2156
- }
2157
-
2158
1832
  // ── load / select / compile / run ───────────────────────────────────────────
2159
1833
 
2160
1834
  let _wfUpdates = []; // workflow updates available, keyed by app id — polled by refreshWorkflowUpdates() below
@@ -2211,15 +1885,96 @@
2211
1885
  runRecordChanged: (appId) => { if (appId === currentId && state.currentTab === 'execution') renderInspect(); },
2212
1886
  });
2213
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
+
2214
1952
  async function loadApp(id) {
2215
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.
2216
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.)
2217
1955
  selectionTargetId = id;
2218
- hideSpotlight(); // a spotlight pointing at the previous app's beacon must clear on switch
2219
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);
2220
1961
  const payload = api(`/api/app/${encodeURIComponent(id)}`);
2221
1962
  const read = beginPublicationAvailabilityRead(id, payload);
2222
- 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); }
2223
1978
  if (ticket !== selectionTicket) return; // something newer was opened while this one loaded
2224
1979
  closeDraftView();
2225
1980
  apps.set(id, app);
@@ -2258,10 +2013,8 @@
2258
2013
  paintGate(app);
2259
2014
  refreshKbInformed(id); // detached: provenance is additive, and must not hold up the canvas paint
2260
2015
  void refreshWorkflowUnits(id);
2261
- paintBeacon(app); // pulse "Start here" while this workflow is new to the user
2262
2016
  refreshDirtyIndicator(); // clean app → dot off; switched back to a dirty one → dot on
2263
2017
  renderWfUpdatePill(); // show the "↑ Update to vX" pill when THIS app has a newer published version
2264
- maybeSpotlight(app); // one-time first-open spotlight pointing at the beacon (slice 2)
2265
2018
  globalThis.flolessAgentSteps?.paintCanvasControl();
2266
2019
  void globalThis.flolessAgentSteps?.refreshChecks(app); // #2241: newer-instructions banner; a failed check says nothing
2267
2020
  void globalThis.flolessAgentSteps?.refreshRunRecord(app.id); // #2241 S5: how the last run's AI steps went, and what it left for you
@@ -2286,7 +2039,17 @@
2286
2039
  const read = ++publicationAvailabilityRead;
2287
2040
  publicationAvailabilityReads.set(id, read);
2288
2041
  const task = (async () => {
2289
- 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
+ }
2290
2053
  // A workflow switch or newer availability read can overtake this request. Only the latest
2291
2054
  // response for the still-open workflow may repaint its cards.
2292
2055
  if (currentId !== id || publicationAvailabilityReads.get(id) !== read) return;
@@ -2359,11 +2122,13 @@
2359
2122
  let unreadable = [];
2360
2123
  try {
2361
2124
  ({ apps: list, unreadable = [] } = await api('/api/workflows/library'));
2362
- 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')); }
2363
2127
  catch { /* the owned list is additive here: a failed read keeps the drafts last shown */ }
2364
2128
  // An older refresh that finishes after a newer one must not overwrite what the newer one showed.
2365
2129
  if (generation !== appsLoadGeneration) return;
2366
2130
  if (owned) wfOwned = owned;
2131
+ if (owned) wfSetApart = Array.isArray(setApart) ? setApart : [];
2367
2132
  list = list.filter((a) => a.execution !== 'internal');
2368
2133
  rememberWorkflowOwners(list);
2369
2134
  wfLibrary = list;
@@ -2422,8 +2187,6 @@
2422
2187
  if ($menuBakeItem) $menuBakeItem.disabled = true;
2423
2188
  if ($wfTrigger) $wfTrigger.disabled = true;
2424
2189
  setComboTriggerLabel('no workflows installed');
2425
- paintBeacon(null); // no workflow open → hide the per-workflow beacon
2426
- hideSpotlight();
2427
2190
  renderCanvasPlaceholder('empty');
2428
2191
  // #1890: an empty library is where the landing matters most: its New workflow card is the way in.
2429
2192
  if (!wfLandingBooted) { wfLandingBooted = true; showWorkflowsLanding(true); }
@@ -2456,11 +2219,9 @@
2456
2219
  return;
2457
2220
  }
2458
2221
  }
2459
- let startId = list[0].id;
2460
- try {
2461
- const saved = localStorage.getItem(LS_LAST_APP);
2462
- if (saved && list.some((a) => a.id === saved)) startId = saved;
2463
- } catch { /* ignore */ }
2222
+ let saved = null;
2223
+ try { saved = localStorage.getItem(LS_LAST_APP); } catch { /* ignore */ }
2224
+ const startId = chooseStartWorkflow(list, saved);
2464
2225
  const ticketBefore = selectionTicket;
2465
2226
  try {
2466
2227
  await loadApp(startId);
@@ -2530,6 +2291,8 @@
2530
2291
  // #1890 PR 3b-0: every owned workflow, drafts included (/api/workflows/owned), and the draft open in the canvas
2531
2292
  // area, if any. A draft has no runtime app, so it is never `currentId` and never goes to loadApp.
2532
2293
  let wfOwned = [];
2294
+ // #2603: workflow folders set apart because their details name another owner (GET /api/workflows/owned).
2295
+ let wfSetApart = [];
2533
2296
  const restoringWorkflows = new Set();
2534
2297
  let draftWorkflow = null;
2535
2298
  // Opening anything (a workflow or a draft) takes a new ticket; a workflow load that finishes after a newer open
@@ -2604,8 +2367,13 @@
2604
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>`
2605
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>`
2606
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>`;
2607
- 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}>`
2608
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>` : '')
2609
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>` : '')
2610
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>` : '')
2611
2379
  + `<span class="wf-option-actions">`
@@ -2764,18 +2532,8 @@
2764
2532
  if (v != null) localStorage.setItem(lsInputsKey(toId), v);
2765
2533
  } catch { /* private mode / quota */ }
2766
2534
  }
2767
- // A rename is the SAME workflow under a new id → carry its onboarding-seen state so it
2768
- // doesn't re-pulse "Start here" / re-show the spotlight. (Not done on duplicate: a copy
2769
- // is a genuinely new workflow that the user hasn't run, so it should start new.)
2770
- function migrateGuideLS(fromId, toId) {
2771
- try {
2772
- const all = guideStateAll();
2773
- if (all[fromId]) { all[toId] = all[fromId]; localStorage.setItem(LS_GUIDE, JSON.stringify(all)); }
2774
- } catch { /* private mode / quota */ }
2775
- }
2776
2535
  function dropClientAppState(id) {
2777
2536
  try { localStorage.removeItem(lsInputsKey(id)); } catch { /* ignore */ }
2778
- try { const all = guideStateAll(); if (all[id]) { delete all[id]; localStorage.setItem(LS_GUIDE, JSON.stringify(all)); } } catch { /* ignore */ }
2779
2537
  appInputValues.delete(id); dirtyBaseline.delete(id); apps.delete(id); contractStates.delete(id);
2780
2538
  }
2781
2539
 
@@ -2900,7 +2658,6 @@
2900
2658
  // so a rename never silently drops the user's inputs (#85 review). loadApp() only seeds
2901
2659
  // inputs when the id is absent, so pre-setting them here preserves unsaved edits.
2902
2660
  migrateInputsLS(oldId, r.id);
2903
- migrateGuideLS(oldId, r.id); // carry onboarding-seen state so the renamed workflow doesn't re-pulse
2904
2661
  if (appInputValues.has(oldId)) appInputValues.set(r.id, appInputValues.get(oldId));
2905
2662
  if (dirtyBaseline.has(oldId)) dirtyBaseline.set(r.id, dirtyBaseline.get(oldId));
2906
2663
  const wasOpen = currentId === oldId;
@@ -3699,7 +3456,6 @@
3699
3456
  const out = await r.json().catch(() => ({ ok: false, error: `re-bake failed (${r.status})` }));
3700
3457
  if (!out || !out.ok) { showToast((out && out.error) || 'could not queue re-bake', 'err'); return; }
3701
3458
  showToast(`Queued — your terminal AI will re-read ${n} drawing${n > 1 ? 's' : ''} and update this workflow, then ask you to approve.`, 'ok');
3702
- 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.`);
3703
3459
  } catch { showToast('could not queue re-bake', 'err'); }
3704
3460
  }
3705
3461
 
@@ -3856,15 +3612,61 @@
3856
3612
  const APP_LABELS = { 'steel-model': 'Steel model', vectorize: 'Vectorize' };
3857
3613
  const appLabel = (a) => APP_LABELS[a] || String(a || '').replace(/[-_]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
3858
3614
 
3859
- // Approved Workspace projects for a `widget: workspace-project` input picker. Returns
3860
- // [] 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).
3861
3618
  async function fetchApprovedProjects(appFilter) {
3862
3619
  try {
3863
3620
  const url = '/api/workspace-projects/approved' + (appFilter ? `?app=${encodeURIComponent(appFilter)}` : '');
3864
3621
  const r = await fetch(url);
3865
3622
  const j = await r.json().catch(() => null);
3866
- return j && j.ok && Array.isArray(j.projects) ? j.projects : [];
3867
- } 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
+ };
3868
3670
  }
3869
3671
 
3870
3672
  // Knowledge reads are scoped by a published knowledge base, never by a model approval. Keep this
@@ -4009,26 +3811,8 @@
4009
3811
  };
4010
3812
  if (isProject(inp)) {
4011
3813
  // Already filtered, by the server, for THIS input's `workspaceApp` — see above.
4012
- const options = (approvedByFilter.get(typeof inp.workspaceApp === 'string' && inp.workspaceApp ? inp.workspaceApp : '') || [])
4013
- .slice().sort((a, b) => String(a.name).localeCompare(String(b.name)))
4014
- .map((p) => ({
4015
- value: p.id,
4016
- // Name the KIND from the lineage root — after a rename `p.app` is a slug that says
4017
- // nothing about what the project IS. The live id stays searchable below.
4018
- meta: `${appLabel(p.templateId || p.app)} · v${p.latestApprovedVersion}`,
4019
- label: p.name,
4020
- search: `${p.name} ${p.app} ${appLabel(p.templateId || p.app)}`,
4021
- }));
4022
- return {
4023
- name: inp.name,
4024
- label: inp.name + (inp.description ? ` — ${inp.description}` : ''),
4025
- type: 'select',
4026
- options,
4027
- value: cur[inp.name] != null ? cur[inp.name] : '',
4028
- placeholder: 'Select an approved project…',
4029
- disabledLabel: 'Approve a project first',
4030
- emptyNote: 'No approved projects yet — open <strong>Workspaces</strong>, create a project, and Approve it to use it here.',
4031
- };
3814
+ return workspaceProjectField(inp,
3815
+ approvedByFilter.get(typeof inp.workspaceApp === 'string' && inp.workspaceApp ? inp.workspaceApp : '') || { projects: [], omitted: [] }, cur);
4032
3816
  }
4033
3817
  if (isKnowledgeProject(inp)) {
4034
3818
  const options = knowledgeProjects
@@ -4142,7 +3926,6 @@
4142
3926
  markSpecialNodes();
4143
3927
  refreshDirtyIndicator(); // values changed → reflect unsaved state in the header/menu
4144
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(' · ');
4145
- appendNarration(`Inputs set — <strong>${escapeHtml(badge)}</strong>. Run with <strong>▶ Run workflow</strong>.`);
4146
3929
  showToast('Inputs set: ' + badge, 'ok');
4147
3930
  }
4148
3931
 
@@ -4228,7 +4011,7 @@
4228
4011
  if (m.relabelled === 'live-failed' && typeof m.home === 'string' && typeof m.pageId === 'string') {
4229
4012
  // A failed live session's versions changed label: an open copy of that Page must not keep the old one.
4230
4013
  window.flolessPages?.reloadIfOpen?.(m.home, m.pageId);
4231
- window.flolessPages?.refresh?.();
4014
+ window.flolessPages?.refresh?.(true); // quiet: the open list keeps its rows until the new ones arrive (#2724)
4232
4015
  return;
4233
4016
  }
4234
4017
  if (typeof m.home !== 'string' || typeof m.pageId !== 'string' || !Number.isInteger(m.version) || m.version < 1) {
@@ -4239,7 +4022,7 @@
4239
4022
  workflowPageByRun.set(captureKeyOf(m.runId, m.fireKey) || m.runId, page);
4240
4023
  if (workflowPageByRun.size > WORKFLOW_PAGE_RUNS_KEPT) workflowPageByRun.delete(workflowPageByRun.keys().next().value);
4241
4024
  noteWorkflowPageLatest(m.app, page);
4242
- window.flolessPages?.refresh?.();
4025
+ window.flolessPages?.refresh?.(true); // quiet, as every re-read for a change (#2724)
4243
4026
  if (currentId === m.app) paintReportPageLinks();
4244
4027
  }
4245
4028
 
@@ -4510,6 +4293,12 @@
4510
4293
  for (;;) {
4511
4294
  let ordinal = asked;
4512
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
+ }
4513
4302
  let index = await api(`/api/model-reports/${handle}/index?at=${ordinal ?? 0}`);
4514
4303
  if (request !== reportSectionRequest) return false;
4515
4304
  // Start with the first object's data, while First still opens Model information.
@@ -4697,6 +4486,13 @@
4697
4486
  if ($reportPage) $reportPage.hidden = true;
4698
4487
  }
4699
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
+
4700
4496
  // Double-click the HTML Viewer node → LOAD the last report (no run; running is
4701
4497
  // the header "▶ Run workflow" button's job). Shows a prompt if nothing has run yet.
4702
4498
  function showReport(nodeId) {
@@ -4872,8 +4668,8 @@
4872
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
4873
4669
  // every document-level Esc handler, and a press one of them already used (preventDefault) is left alone. A keydown
4874
4670
  // inside the editor's iframe never arrives here; that half is web/overlay-escape.js, which calls the hook below.
4875
- // Several shell dialogs, the menu and the find bar close on Esc WITHOUT marking it (app.js, the routines and guide
4876
- // 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
4877
4673
  // the capture phase, before any of them acts: that Esc was theirs, and closing the overlay too would be two actions.
4878
4674
  const SHELL_ESC_OWNERS = '.modal-backdrop.show, #menu.show, #find-overlay.show';
4879
4675
  let shellEscOwned = false;
@@ -4899,6 +4695,57 @@
4899
4695
  return true;
4900
4696
  };
4901
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
+
4902
4749
  // Export 3D ▸ — render the approved model as an interactive 3D model. Calls the server's
4903
4750
  // export-3d (transform → companion viewer-3d app → compile → run) and paints the returned
4904
4751
  // interactive report in the same viewer a normal run uses. api() throws on any failure (non-2xx
@@ -4952,14 +4799,24 @@
4952
4799
  // to name the right one, so it names none, which is true in every environment.
4953
4800
  if (rfi) parts.push(`${rfi} with no resolved section size (RFI)`);
4954
4801
  if (noFit) parts.push(`${noFit} priced but not drawn (no tabulated footprint)`);
4955
- $reportSub.textContent = (parts.length ? `${parts.join(', ')} — not shown. ` : '')
4956
- + 'Live 3D view from the approved model — drag to orbit, scroll to zoom, click an element to inspect.';
4957
- 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');
4958
4815
  paintReport(html, true);
4959
4816
  lastReportByApp.set(currentId, { nodeId: res.report.nodeId, label: '3D', html, interactive: true });
4960
4817
  $reportModal.dataset.html = '1';
4961
4818
  } catch (e) {
4962
- 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);
4963
4820
  $reportOverlay.innerHTML = `<div>${escapeHtml(recovery)}</div>`;
4964
4821
  showToast(recovery, 'warn');
4965
4822
  }
@@ -5467,12 +5324,10 @@
5467
5324
  lastReportByApp.set(app.id, { nodeId, label: inputBadge, ...res.report, runId: typeof res.runId === 'string' ? res.runId : null });
5468
5325
  // #2539: the run is over once the server answered. Showing its report may still wait for the workflow's Page to
5469
5326
  // save its copy, so the run controls are released now (not awaited) and the viewer opens the report by itself.
5470
- const runApp = app.id;
5471
5327
  void paintCompleteReport(res.report).then((painted) => {
5472
5328
  if (!painted || !currentCompleteReport || !$reportOverlay.hidden) return;
5473
- markFirstRunDone(runApp);
5474
5329
  $reportModal.dataset.html = '1';
5475
- appendNarration(`Rendered the complete read-only property report from <strong>${escapeHtml(nodeId)}</strong>.`);
5330
+ reportReadyNote(app, nodeId);
5476
5331
  });
5477
5332
  return;
5478
5333
  }
@@ -5490,11 +5345,10 @@
5490
5345
  // ⧉ Open file / ▤ Reveal buttons and cache it so a later double-click restores them (#209).
5491
5346
  const savedPath = res && typeof res.savedPath === 'string' ? res.savedPath : '';
5492
5347
  showSavedPathActions(savedPath);
5493
- 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)
5494
5348
  lastReportByApp.set(currentId, { nodeId, label: inputBadge, html, interactive, savedPath, withFiles, runId: typeof res.runId === 'string' ? res.runId : null });
5495
5349
  paintReportPageLinks();
5496
5350
  $reportModal.dataset.html = '1';
5497
- appendNarration(`Rendered the ${interactive ? '3D view' : 'report'} from <strong>${escapeHtml(nodeId)}</strong>${inputBadge ? ' (' + escapeHtml(inputBadge) + ')' : ''} — live run against the model.`);
5351
+ reportReadyNote(app, nodeId);
5498
5352
  } catch (e) {
5499
5353
  const msg = e && e.message ? e.message : String(e);
5500
5354
  liveOutcome = (e && e.body && e.body.cancelled) ? 'stopped' : !(e && e.status) ? 'no-answer'
@@ -5518,7 +5372,9 @@
5518
5372
  // in the viewer overlay + a toast. No console.error — the server returns the
5519
5373
  // failure in-band, so a failed run isn't a console-worthy fault.
5520
5374
  $reportSub.textContent = 'Execution ended without a report.';
5521
- showRunFailure(e.body || {}, runFailureMessage(msg), app);
5375
+ // #2796: Try again only once the server has answered that this run ended. With no answer the run may still be
5376
+ // going on the host, and a second one could do its work twice.
5377
+ showRunFailure(e.body || {}, runFailureMessage(msg), app, opts.debug || liveOutcome === 'no-answer' ? null : () => runReport(nodeId));
5522
5378
  }
5523
5379
  }
5524
5380
  } finally {
@@ -5548,9 +5404,9 @@
5548
5404
 
5549
5405
  // A run that failed for any reason other than Stop or an expired sign-in (#1912, #1851): the
5550
5406
  // plain sentence the server or runFailureMessage produced, the fix when there is one (Compile, for
5551
- // an approval AWARE refused), and Report this problem every time. Reuses the reconnect card's
5407
+ // an approval AWARE refused, or Try again through `runAgain`), and Report this problem every time. Reuses the reconnect card's
5552
5408
  // amber-topped layout; built with textContent only, so nothing the server says becomes markup.
5553
- function showRunFailure(body, message, app) {
5409
+ function showRunFailure(body, message, app, runAgain = null) {
5554
5410
  const code = body && typeof body.code === 'string' ? body.code : '';
5555
5411
  const compileFix = (code === 'agent-version-changed' || code === 'needs-compile') && !$compileBtn.hidden;
5556
5412
  const reinstall = code === 'agent-files-changed';
@@ -5591,6 +5447,22 @@
5591
5447
  compile.onclick = () => { hideModal($reportModal); $compileBtn.click(); };
5592
5448
  actions.append(compile);
5593
5449
  }
5450
+ // #2796: a run that stopped can be run again from here, with the same inputs and every check Run makes, so a card
5451
+ // whose sentence says "try again" offers it. Not where the server says running again cannot help (`retryable:
5452
+ // false`: the account cannot read the model, or FloLess lost its connection to AWARE and a restart comes first), not
5453
+ // where Compile or a reinstall is the fix, and not for a run that never started.
5454
+ if (runAgain && !notRun && !compileFix && !reinstall && body.retryable !== false) {
5455
+ const retry = mkEl('button', 'primary cred-reconnect run-fail-retry', 'Try again');
5456
+ retry.type = 'button';
5457
+ retry.dataset.commandId = 'shell.run-failure-retry';
5458
+ // One run per click, however fast the clicks. A run that starts replaces this card; one that does not (an inputs
5459
+ // prompt or a confirmation the person cancelled) leaves it, so Try again works again.
5460
+ retry.onclick = async () => {
5461
+ retry.disabled = true;
5462
+ try { await runAgain(); } finally { if (retry.isConnected) retry.disabled = false; }
5463
+ };
5464
+ actions.append(retry);
5465
+ }
5594
5466
  const report = mkEl('button', 'cred-open-integrations run-fail-report', 'Report this problem');
5595
5467
  report.type = 'button';
5596
5468
  report.dataset.commandId = 'shell.run-failure-report';
@@ -5687,6 +5559,7 @@
5687
5559
  reconnect.focus();
5688
5560
  }
5689
5561
 
5562
+ const CRED_SIGN_IN_FAILED = 'Sign-in didn’t finish. Click Reconnect to try again, or open Integrations.';
5690
5563
  function credReconnectStart(cred, card, btn, body) {
5691
5564
  const reset = (errMsg) => {
5692
5565
  credReconnect = null;
@@ -5713,11 +5586,13 @@
5713
5586
  if ($reportOverlay.querySelector('.cred-fail-card')) { $reportOverlay.hidden = true; $reportOverlay.replaceChildren(); }
5714
5587
  }, 2000);
5715
5588
  },
5716
- onFail: () => reset('Sign-in failed — try again, or use the device code flow in Integrations.'),
5589
+ // #2649: the server's own sentence when it sent one (a device code is not offered for Google any more).
5590
+ onFail: (message) => reset(message || CRED_SIGN_IN_FAILED),
5717
5591
  };
5592
+ // No Drive choice is sent: the server keeps whatever Drive access the account already has.
5718
5593
  api(`/api/connect/${encodeURIComponent(cred.id)}`, { method: 'POST', body: '{}' })
5719
- .then((res) => { if (res && res.started === false) reset('Couldn’t start sign-in — open Integrations to retry.'); })
5720
- .catch(() => reset('Sign-in failed — try again, or use the device code flow in Integrations.'));
5594
+ .then((res) => { if (res && res.started === false) reset(typeof res.message === 'string' ? res.message : 'Couldn’t start sign-in. Open Integrations to try again.'); })
5595
+ .catch(() => reset(CRED_SIGN_IN_FAILED));
5721
5596
  }
5722
5597
 
5723
5598
  // Shared by both run paths: when the server flags a credential issue, show the
@@ -5725,7 +5600,6 @@
5725
5600
  function surfaceCredentialIssue(cred) {
5726
5601
  showCredentialReconnect(cred);
5727
5602
  showToast(`Session expired — reconnect ${cred.label} to continue.`, 'warn');
5728
- appendNarration(`Run stopped — your <strong>${escapeHtml(cred.label)}</strong> session expired. Reconnect and run again.`);
5729
5603
  }
5730
5604
 
5731
5605
  function showModal(el) { el.classList.add('show'); }
@@ -6004,6 +5878,9 @@
6004
5878
  const isOn = (o) => String(o.value) === val;
6005
5879
  const sel = opts.find(isOn);
6006
5880
  const disabled = !opts.length;
5881
+ // #2645: rows that are listed only to say why they can't be chosen. When they are all there is, the list
5882
+ // still opens (to show why) and the trigger and note say none can be used, never that none exist.
5883
+ const noneUsable = !disabled && !opts.some((o) => !o.unavailable);
6007
5884
  // A search box only earns its place once the list is too long to scan. Offering one over
6008
5885
  // two choices ("Still image" / "Turntable video") reads as clutter and makes a two-item
6009
5886
  // decision look like a database lookup. Count-based rather than a per-caller flag, so
@@ -6011,7 +5888,8 @@
6011
5888
  // list here (approved projects, unbounded) crosses the threshold on its own.
6012
5889
  const searchable = opts.length > SELECT_SEARCH_MIN;
6013
5890
  const trigLabel = disabled ? (f.disabledLabel || 'None available')
6014
- : sel ? (sel.triggerLabel || (sel.label + (sel.meta ? ` (${sel.meta})` : ''))) : (f.placeholder || 'Select…');
5891
+ : sel && !sel.unavailable ? (sel.triggerLabel || (sel.label + (sel.meta ? ` (${sel.meta})` : '')))
5892
+ : noneUsable ? (f.unavailableLabel || 'None can be used here') : (f.placeholder || 'Select…');
6015
5893
  // Command IDs are literal registry identities. Only the selected runtime is dynamic;
6016
5894
  // never interpolate an arbitrary form field into the Instructor trust boundary.
6017
5895
  let commandCarrier = '';
@@ -6019,22 +5897,23 @@
6019
5897
  else if (f.commandId === 'shell.requests-runtime') commandCarrier = ' data-command-id="shell.requests-runtime"';
6020
5898
  else if (f.commandId === 'shell.new-workflow-location') commandCarrier = ' data-command-id="shell.new-workflow-location"';
6021
5899
  else if (f.commandId === 'workflow.select-model-revision') commandCarrier = ' data-command-id="workflow.select-model-revision"';
5900
+ else if (f.commandId === 'shell.render-caption-choice') commandCarrier = ' data-command-id="shell.render-caption-choice"';
6022
5901
  let optionIndex = 0;
6023
- 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>`;
5902
+ 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>`;
6024
5903
  const grouped = opts.some((o) => o.group);
6025
5904
  const rows = grouped
6026
5905
  ? [...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('')
6027
5906
  : opts.map(optionRow).join('');
6028
5907
  ctl = `<div class="wf-combo fm-select">
6029
5908
  <input type="hidden" data-fm="${escapeHtml(f.name)}" value="${escapeAttr(val)}">
6030
- <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' : ''}>
6031
- <span class="wf-trigger-label fm-select-label"${sel ? '' : ' data-empty="1"'}>${escapeHtml(trigLabel)}</span>
5909
+ <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' : ''}>
5910
+ <span class="wf-trigger-label fm-select-label"${sel && !sel.unavailable ? '' : ' data-empty="1"'}>${escapeHtml(trigLabel)}</span>
6032
5911
  <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>
6033
5912
  </button>
6034
5913
  <div id="${id}-listbox" class="wf-popover fm-select-popover" role="listbox" aria-label="${escapeAttr(f.label || f.name)}" hidden>
6035
5914
  ${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>' : ''}
6036
5915
  <div class="wf-list fm-select-list">${rows}${searchable ? '<div class="wf-empty-search" hidden>No matches</div>' : ''}</div>
6037
- </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>` : ''}
5916
+ </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>` : ''}
6038
5917
  </div>`;
6039
5918
  } else {
6040
5919
  const fieldCommand = f.commandId === 'shell.new-workflow-name'
@@ -6366,6 +6245,8 @@
6366
6245
  const close = (focusTrig) => { popover.hidden = true; trigger.classList.remove('open'); trigger.setAttribute('aria-expanded', 'false'); clearHi(); if (focusTrig) trigger.focus(); };
6367
6246
  const nameOf = (o) => { const n = o.querySelector('.wf-option-name'); return n ? n.textContent : o.dataset.id; };
6368
6247
  const choose = (opt) => {
6248
+ // #2645: a row listed only to say why it can't be used is reachable (a screen reader hears why) but never chosen.
6249
+ if (opt.getAttribute('aria-disabled') === 'true') return;
6369
6250
  if (hidden) hidden.value = opt.dataset.id;
6370
6251
  if (trigger.dataset.commandId) {
6371
6252
  trigger.dataset.commandInstance = opt.dataset.id;
@@ -6801,6 +6682,17 @@
6801
6682
  // markup) so a server-returned URL can never inject HTML.
6802
6683
  $reportShare.onclick = async () => {
6803
6684
  const cached = currentId && lastReportByApp.get(currentId);
6685
+ // #2706: when this run's report became a version of the workflow's Page, Share shares THAT Page: the Page viewer opens at
6686
+ // the version this run made with its share menu open, so the link is the updating one ("the same link updates"), with the
6687
+ // same words, state and confirmation. A frozen one-off copy is made only when there is no Page version to share.
6688
+ const page = cached ? reportPageOf(cached) : null;
6689
+ if (page && typeof window.flolessPages?.open === 'function') {
6690
+ try {
6691
+ // The report stays open until the Page is known to open (beforeShow); a Page that cannot be opened says why and leaves it.
6692
+ await window.flolessPages.open(page.home, page.pageId, page.version, { share: true, beforeShow: () => closeReportViewer() });
6693
+ } catch (e) { showToast(`FloLess couldn’t open the workflow’s Page to share it. ${e && e.message ? e.message : ''}`.trim(), 'warn'); }
6694
+ return;
6695
+ }
6804
6696
  // Share exactly what's on screen — the HTML we painted — so the link can never carry a different
6805
6697
  // report than the one the user is looking at (e.g. another app's cache). `lastPaintedHtml` covers
6806
6698
  // the INTERACTIVE 3D frame too, which has no srcdoc (it renders from a data: URL); the srcdoc
@@ -6813,7 +6705,9 @@
6813
6705
  // so measure the SERIALIZED body, not the raw HTML, or quote-heavy markup slips past the check
6814
6706
  // and 413s anyway.
6815
6707
  const app = apps.get(currentId);
6816
- const title = `${app ? app.displayName : currentId}${cached.label ? ' · ' + cached.label : ''}`;
6708
+ // #2706: the public title is the workflow's name alone. The run's inputs (`cached.label`) carry local paths and internal
6709
+ // rates, and a link's title is shown to whoever opens it.
6710
+ const title = `${app ? app.displayName : currentId}`;
6817
6711
  // Declare an interactive 3D document so the server can hold it to the AWARE display-mode floor.
6818
6712
  // This path renders via export-3d without `for=share`, so this is the only place it gets gated.
6819
6713
  const body = JSON.stringify(lastPaintedInteractive ? { title, html, kind: 'model-3d' } : { title, html });
@@ -6890,11 +6784,9 @@
6890
6784
  if (r.warning) {
6891
6785
  // The rename did not land exactly as previewed (or could not be checked): the person looks before anything compiles.
6892
6786
  showToast(r.warning, 'warn');
6893
- appendNarration(`Renamed the step <strong>${escapeHtml(r.renamed?.from || '')}</strong> to <strong>${escapeHtml(r.renamed?.to || '')}</strong>. ${escapeHtml(r.warning)}`);
6894
6787
  if (currentId === id) { try { await loadApp(id); } catch (e) { reportErr(e); } }
6895
6788
  return;
6896
6789
  }
6897
- 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.`);
6898
6790
  if (currentId !== id) return;
6899
6791
  try { await loadApp(id); } catch (e) { reportErr(e); return; }
6900
6792
  if (currentId === id) await compileCurrentWorkflow();
@@ -6942,17 +6834,30 @@
6942
6834
  const consent = globalThis.flolessAgentSteps?.consentStatus ? await globalThis.flolessAgentSteps.consentStatus(newId) : null;
6943
6835
  const unconfirmed = consent && (consent.state === 'needed' || consent.state === 'changed');
6944
6836
  if (unconfirmed) {
6945
- 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.');
6946
6837
  showToast('Workflow compiled. Confirm its AI step before it runs.', 'ok');
6947
6838
  } else {
6948
- appendNarration(app?.runnable
6949
- ? 'Workflow compiled. Review any notices above the canvas before running.'
6950
- : `Compiled, but ${app?.notes?.length ?? 0} notice(s) remain — review them above the canvas.`);
6951
- showToast('Workflow compiled', 'ok');
6839
+ compiledToast(app);
6952
6840
  }
6953
6841
  maybeAskPolicyAfterApproval();
6954
6842
  }
6955
6843
 
6844
+ // One outcome per surface (a run, a compile): the next one replaces it, so repeats never pile up. Outcomes that need the
6845
+ // person stay until closed; a plain "complete" goes by itself (persistent = false).
6846
+ const standingToasts = new Map();
6847
+ function standingToast(surface, text, type, persistent = true) {
6848
+ standingToasts.get(surface)?.(true);
6849
+ standingToasts.set(surface, text ? showToast(text, type, persistent ? { persistent: true } : undefined) : null);
6850
+ }
6851
+
6852
+ /** After a Compile: a workflow that still cannot run says why, and where to look. */
6853
+ function compiledToast(app) {
6854
+ if (!app || app.runnable) { standingToast('compile'); showToast('Workflow compiled', 'ok'); return; }
6855
+ const notices = app.notes?.length ?? 0;
6856
+ standingToast('compile', notices
6857
+ ? `Workflow compiled, but ${notices} notice${notices === 1 ? '' : 's'} above the canvas still need${notices === 1 ? 's' : ''} you before it can run.`
6858
+ : 'Workflow compiled, but it can’t run yet. The status above the canvas says why.', 'warn');
6859
+ }
6860
+
6956
6861
  async function compileCurrentWorkflow() {
6957
6862
  if (!currentId || $compileBtn.disabled || $compileBtn.hidden) return; // hidden = suppressed for a maintained drift
6958
6863
  const id = currentId;
@@ -6969,11 +6874,7 @@
6969
6874
  try {
6970
6875
  if (consent !== 'approved') await api('/api/compile', { method: 'POST', body: JSON.stringify({ id }) });
6971
6876
  await loadApp(id);
6972
- const app = apps.get(id);
6973
- appendNarration(app.runnable
6974
- ? 'Workflow compiled. Review any notices above the canvas before running.'
6975
- : `Compiled, but ${app.notes.length} notice(s) remain — review them above the canvas.`);
6976
- showToast('Workflow compiled', 'ok');
6877
+ compiledToast(apps.get(id));
6977
6878
  // #1998: a person just approved a workflow — the moment to ask, once, about small read-only tool fixes.
6978
6879
  maybeAskPolicyAfterApproval();
6979
6880
  } catch (e) {
@@ -6981,6 +6882,9 @@
6981
6882
  $compileBtn.disabled = false;
6982
6883
  const ask = globalThis.flolessStepRename ? globalThis.flolessStepRename.askOf(e) : null;
6983
6884
  if (ask) { await renameStepThenCompile(id, ask); return; }
6885
+ // #2740: in the Compile slot, so a second refusal replaces the first and a later clean compile clears it.
6886
+ const refused = compileRefusalText(e);
6887
+ if (refused) { standingToast('compile', authoredToastCopy(refused), 'warn'); return; }
6984
6888
  reportErr(e);
6985
6889
  }
6986
6890
  }
@@ -7030,7 +6934,6 @@
7030
6934
  await api('/api/bake', { method: 'POST', body: JSON.stringify({ id }) });
7031
6935
  hideModal($bakeModal);
7032
6936
  await loadApp(id);
7033
- appendNarration(`Baked <strong>${escapeHtml(id)}</strong> as a reusable tool — find it in the Tools library (<strong>≡ menu → Tools</strong>).`);
7034
6937
  showToast(`Baked — now in the Tools library as “${id}”`, 'ok');
7035
6938
  } catch (e) {
7036
6939
  hideModal($bakeModal);
@@ -7706,7 +7609,6 @@
7706
7609
  $graftPrimary.setAttribute('data-command-id', 'shell.graft-done');
7707
7610
  graftState.onPrimary = closeGraftModal;
7708
7611
  loadAgentCatalog().catch(() => {}); // refresh count immediately (SSE also fires for other tabs)
7709
- appendNarration(`Grafted <strong>${escapeHtml(res.agentId)}</strong> from ${escapeHtml(graftState.preview.sourceRef)} — find it in the Tools library (<strong>≡ menu → Tools</strong>).`);
7710
7612
  showToast(`Tool created — “${res.agentId}” is now in the Tools library`, 'ok');
7711
7613
  } catch (e) {
7712
7614
  $graftBack.disabled = false; $graftCancel.disabled = false;
@@ -8141,11 +8043,14 @@
8141
8043
  let content;
8142
8044
  try { content = await file.text(); } catch { showToast('Could not read that file', 'err'); return; }
8143
8045
  try {
8144
- const { id } = await api('/api/import', { method: 'POST', body: JSON.stringify({ filename: file.name, content }) });
8145
- await loadApps();
8146
- $promptSel.value = id;
8147
- $promptSel.dispatchEvent(new Event('change', { bubbles: true })); // → loadApp(id), arms Compile
8148
- showToast(`Imported "${id}" — Compile to run`, 'ok');
8046
+ // #2742: the file is kept as a Standalone draft (not installed under its app: id, which no list showed), so it
8047
+ // opens as a draft with Compile, and Compile publishes it into the picker like any workflow built in AI Chat.
8048
+ const { workflow } = await api('/api/import', { method: 'POST', body: JSON.stringify({ filename: file.name, content }) });
8049
+ try { await loadApps({ preserveSelection: true }); } catch { /* the draft is still on the Workflows page after the next refresh */ }
8050
+ const opened = openDraftWorkflow(workflow.workflowId);
8051
+ showToast(opened
8052
+ ? `Imported "${workflow.displayName}" as a draft — Compile to add it to your picker`
8053
+ : `Imported "${workflow.displayName}" as a draft — find it under Standalone on the Workflows page, then Compile it to add it to your picker`, 'ok');
8149
8054
  } catch (e) {
8150
8055
  const body = e && e.body;
8151
8056
  const reason = body && typeof body.reason === 'string' ? body.reason.trim() : '';
@@ -8157,12 +8062,14 @@
8157
8062
  openImportFailedModal(reason, Array.isArray(body.agentsUnavailable) ? body.agentsUnavailable : [], file);
8158
8063
  return;
8159
8064
  }
8160
- showToast(body && body.code === 'exists'
8161
- ? 'A workflow with that name already exists. Choose a different name, then try again.'
8162
- // #2470: the server's sentence names the General project id and a name to use instead.
8163
- : body && body.code === 'reserved-id' && typeof body.error === 'string' && body.error
8164
- ? `${body.error} Change the app: line in the file, then import it again.`
8165
- : 'We couldn’t import that workflow because FloLess could not read it. Check the file, then try again.', 'err');
8065
+ // A file FloLess could not read is a 400. The Workspace refusing to keep it (no Workspace folder, a folder it
8066
+ // cannot write) is labelled by the server, whose sentence names why. Anything else is unconfirmed: it may have been kept.
8067
+ showToast(body && body.stage === 'workspace' && typeof body.error === 'string' && body.error
8068
+ ? `We couldn’t save that workflow to your Workspace: ${body.error.replace(/[.\s]+$/, '')}. Try again.`
8069
+ // Only a 400 is a verdict on the file; a lost response (no status) may follow a kept draft.
8070
+ : e && e.status === 400
8071
+ ? 'We couldn’t import that workflow because FloLess could not read it. Check the file, then try again.'
8072
+ : 'FloLess couldn’t confirm the import just now. Check Standalone on the Workflows page before you try again.', 'err');
8166
8073
  }
8167
8074
  } finally {
8168
8075
  _importing = false; // every path, including an unreadable file and the dialog's early return
@@ -9671,6 +9578,7 @@
9671
9578
  // every fired event until Stop. (Simulate still takes the normal stubbed path.)
9672
9579
  if (!simulate && app.triggerSource) { startForegroundTrigger(app); return; }
9673
9580
 
9581
+ standingToast('run'); // a new run makes the last one's outcome old news
9674
9582
  markCanvasRunning(); // immediate during-run feedback; the trace refines per node
9675
9583
 
9676
9584
  // Real run + a report node → the HTML Viewer path (renders the report,
@@ -9705,22 +9613,19 @@
9705
9613
  if (res.credentialIssue) { surfaceCredentialIssue(res.credentialIssue); return; }
9706
9614
  switchToExecution();
9707
9615
  const steps = liveTrace.filter((r) => r.kind === 'node-start').length;
9708
- appendNarration(simulate
9709
- ? `Simulated run complete · ${steps} node${steps === 1 ? '' : 's'} stubbed (no host needed) · see the <strong>Execution</strong> tab.`
9710
- : `Run complete · ${steps} node${steps === 1 ? '' : 's'} against the live model · see the <strong>Execution</strong> tab.`);
9711
- if (!simulate) markFirstRunDone(app.id); // a real run completed → calm the beacon (app captured pre-await)
9616
+ standingToast('run', simulate ? `Simulated run complete · ${steps} node${steps === 1 ? '' : 's'} stubbed. See the Execution tab.`
9617
+ : `Run complete · ${steps} node${steps === 1 ? '' : 's'}. See the Execution tab.`, 'ok', false);
9712
9618
  } catch (e) {
9713
9619
  liveOutcome = (e && e.body && e.body.cancelled) ? 'stopped'
9714
9620
  : !(e && e.status) ? 'no-answer' // the request itself was lost (reload, dropped connection), not the run
9715
9621
  : (e && e.body && (e.body.notRun || e.body.refusal)) ? 'not-run' : 'failed';
9716
9622
  if (e.body && e.body.cancelled) {
9717
9623
  clearNodeStatus();
9718
- showToast('Run cancelled', 'info');
9719
- appendNarration(stoppedRunCopy(e.body, !simulate && (app.templateId === 'floless-workspace-model-report' || app.templateId === 'tekla-model-report')) + ' Click <strong>▶ Run workflow</strong> to run again.');
9624
+ standingToast('run', stoppedRunCopy(e.body, !simulate && (app.templateId === 'floless-workspace-model-report' || app.templateId === 'tekla-model-report')), 'info');
9720
9625
  } else if (liveOutcome === 'no-answer' && clientRunToken) {
9721
9626
  // #2228: the request was lost, not the run — which may still be working. The strip says how it ends
9722
9627
  // once FloLess answers again; reporting a failure here would contradict it.
9723
- appendNarration('Lost touch with FloLess while the run was working. The strip above the canvas shows how it ends once FloLess is back.');
9628
+ 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');
9724
9629
  } else {
9725
9630
  const cred = e.body && e.body.credentialIssue;
9726
9631
  if (cred) {
@@ -9738,12 +9643,9 @@
9738
9643
  if (e && e.body && (e.body.refusal || notRun)) clearNodeStatus();
9739
9644
  // A not-run answer is already a whole sentence ("…, so it didn’t run. …"); "Run failed:" would misstate it.
9740
9645
  // Nothing failed — it was declined with a reason — so the toast is informational, not a warning.
9741
- showToast(notRun ? runFailureMessage(msg) : (simulate ? 'Simulate failed' : 'Run failed') + ': ' + runFailureMessage(msg), notRun ? 'info' : 'warn');
9742
- appendNarration(notRun
9743
- ? escapeHtml(runFailureMessage(msg))
9744
- : simulate
9745
- ? `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.`
9746
- : `Run failed: ${escapeHtml(runFailureMessage(msg))}`);
9646
+ standingToast('run', notRun ? runFailureMessage(msg)
9647
+ : simulate ? `Simulate failed: ${runFailureMessage(msg).replace(/([^.!?])$/, '$1.')} Simulate can’t check code steps, so ▶ Run workflow is the real test.`
9648
+ : 'Run failed: ' + runFailureMessage(msg), notRun ? 'info' : 'warn');
9747
9649
  }
9748
9650
  }
9749
9651
  } finally {
@@ -10752,6 +10654,7 @@
10752
10654
  pendingCatchup = null;
10753
10655
  window.dispatchEvent(new CustomEvent('floless:apps-changed', { detail: {} }));
10754
10656
  window.dispatchEvent(new CustomEvent('floless:projects-changed', { detail: {} }));
10657
+ window.dispatchEvent(new CustomEvent('floless:pages-changed', { detail: { home: null, id: null } })); // a reconnect missed whatever changed while away
10755
10658
  window.dispatchEvent(new CustomEvent('floless:action-proposal', { detail: { resync: true } }));
10756
10659
  loadRequests();
10757
10660
  const workflowId = currentId;
@@ -10829,6 +10732,8 @@
10829
10732
  // workflow this tab shows that someone else started is followed read-only (no Stop).
10830
10733
  // #2241: a run that FAILED after an Agent answered ends with run-finished, not run-ended: its AI record is read then too.
10831
10734
  if (m.type === 'run-finished' && m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id);
10735
+ // Workflows → History: a run starting shows as Running, and a failed run ends with run-finished alone.
10736
+ if (m.type !== 'node-progress') window.flolessRunHistory?.refresh?.();
10832
10737
  signalRunEvent(m); // the browser tab hears its run's ending even when the strip already settled
10833
10738
  if (liveRunOwns(m)) {
10834
10739
  if (m.type === 'run-live') { if (m.runId) { liveRun.runId = m.runId; signalRunNote(liveRun); } }
@@ -10872,6 +10777,10 @@
10872
10777
  // #2482: a PROJECT's contract changed (a checklist draft, a reference added from AI Chat). workspaces.js relays
10873
10778
  // it to that project's open editor frame, which has no event stream of its own.
10874
10779
  window.dispatchEvent(new CustomEvent('floless:contract-changed', { detail: m }));
10780
+ } else if (m.type === 'pages-changed') {
10781
+ // #2702: a Page was created, got a version, was shared, published, revoked or deleted — from the chat, a workflow
10782
+ // run or the viewer. Open Pages lists re-read (pages.js is the only listener); nothing is polled.
10783
+ window.dispatchEvent(new CustomEvent('floless:pages-changed', { detail: { home: typeof m.home === 'string' ? m.home : null, id: typeof m.id === 'string' ? m.id : null } }));
10875
10784
  } else if (m.type === 'projects-changed') {
10876
10785
  // Relayed as a DOM event for the same reason apps-changed is (see that arm below):
10877
10786
  // workspaces.js owns the project view and is the only listener. It reconciles the project it
@@ -11035,6 +10944,7 @@
11035
10944
  if (window.flolessPanels) window.flolessPanels.refreshData();
11036
10945
  // #2470 R6.2: a project's Workflows step shows each workflow's last run; it re-reads only while on screen.
11037
10946
  window.flolessProjectWorkflows?.refresh?.();
10947
+ window.flolessRunHistory?.refresh?.(); // Workflows → History re-reads only while on screen
11038
10948
  if (m.id && m.id === currentId) void globalThis.flolessAgentSteps?.refreshRunRecord(m.id); // #2241 S5
11039
10949
  } else if (m.type === 'routine-changed') {
11040
10950
  loadRoutinesData();
@@ -11053,6 +10963,7 @@
11053
10963
  } else if (m.type === 'routine-run-ended') {
11054
10964
  runningRoutines.delete(m.id);
11055
10965
  window.flolessProjectWorkflows?.refresh?.(); // #2470 R6.2, as run-ended
10966
+ window.flolessRunHistory?.refresh?.();
11056
10967
  loadRoutinesData();
11057
10968
  if (window.flolessPanels) window.flolessPanels.refreshData(); // routine runs also refresh bindings
11058
10969
  window.flolessAgents?.refreshRuns?.(); // #2035: an open agent page shows the run its routine just started
@@ -11069,6 +10980,7 @@
11069
10980
  applyRoutineReport(m);
11070
10981
  } else if (m.type === 'workflow-page-captured') {
11071
10982
  applyWorkflowPageCaptured(m);
10983
+ window.flolessRunHistory?.refresh?.(); // the report was saved after run-ended: its row gains View report
11072
10984
  } else if (m.type === 'action-run-report') {
11073
10985
  applyActionRunReport(m);
11074
10986
  } else if (m.type === 'routine-report-changed') {
@@ -11078,7 +10990,7 @@
11078
10990
  // drive its success/fail state from the same SSE result.
11079
10991
  if (credReconnect && credReconnect.id === m.id) {
11080
10992
  if (m.status === 'connected') credReconnect.onSuccess();
11081
- else credReconnect.onFail(m.error);
10993
+ else credReconnect.onFail(typeof m.message === 'string' ? m.message : null);
11082
10994
  }
11083
10995
  // The device-code sign-in resolved. On success, refresh so the card flips
11084
10996
  // to Connected; otherwise surface the outcome in the integration's slot.
@@ -11089,7 +11001,7 @@
11089
11001
  showToast(`Connected ${m.id}`, 'ok');
11090
11002
  refreshIntegrations(`Connected ${m.id}. Account readiness updated.`);
11091
11003
  } else if (slot) {
11092
- slot.innerHTML = `Sign-in ${escapeHtml(m.status || 'failed')}${m.error ? ' — ' + escapeHtml(m.error) : ''}. Click Connect to retry.`;
11004
+ slot.innerHTML = connectResultSlotHtml(m);
11093
11005
  }
11094
11006
  } else if (m.type === 'fs-change' && m.kind === 'credential') {
11095
11007
  // `aware connect`/`disconnect` wrote/removed a token in the local vault —
@@ -11174,6 +11086,11 @@
11174
11086
  return text;
11175
11087
  }
11176
11088
 
11089
+ /** #2740: the sentence the server wrote from AWARE's reason when it refused to compile a workflow, or ''. */
11090
+ function compileRefusalText(e) {
11091
+ return e?.body?.ok === false && e.body.code === 'workflow-compile-refused' && typeof e.body.userMessage === 'string' ? e.body.userMessage.trim() : '';
11092
+ }
11093
+
11177
11094
  function reportErr(e) {
11178
11095
  if (awarePageUnloading && e instanceof TypeError && e.message === 'Failed to fetch') return;
11179
11096
  console.error(e);
@@ -11188,6 +11105,13 @@
11188
11105
  showToast(owned, 'warn');
11189
11106
  return;
11190
11107
  }
11108
+ // #2740: AWARE refused to compile the workflow and said why (a pin mismatch names both versions). Retrying cannot fix
11109
+ // that, so the person reads AWARE's reason and the choices, and it stays until they close it.
11110
+ const refused = compileRefusalText(e);
11111
+ if (refused) {
11112
+ showToast(authoredToastCopy(refused), 'warn', { persistent: true });
11113
+ return;
11114
+ }
11191
11115
  showToast('We couldn’t finish that. Your work is still here. Try again. If it keeps happening, reopen FloLess.', 'err');
11192
11116
  }
11193
11117
 
@@ -11317,7 +11241,6 @@
11317
11241
  try {
11318
11242
  const { request } = await api('/api/knowledge-consult', { method: 'POST', body: JSON.stringify({ appId: app.id }) });
11319
11243
  const copied = await copyToClipboard(markedInstruction(request));
11320
- 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.' : ''}`);
11321
11244
  showToast(copied ? 'Knowledge read + gate queued · copied to clipboard' : 'Knowledge read + gate queued', 'ok');
11322
11245
  loadRequests();
11323
11246
  } catch (e) { reportErr(e); }
@@ -11396,7 +11319,7 @@
11396
11319
  //
11397
11320
  // WHICH SURFACES MUST USE THIS: every one whose failure message BLAMES a cause — the row ⧉, the
11398
11321
  // request-help modal, the revision card. The queue-then-best-effort-copy callers (useTemplate,
11399
- // tweakNode, requestGuide, requestNewWorkflow, panels.js's customize box) say only "queued, not
11322
+ // tweakNode, requestNewWorkflow, panels.js's customize box) say only "queued, not
11400
11323
  // copied" and name no cause, so they cannot conflate anything and are deliberately left alone. Add
11401
11324
  // a new surface that names a cause and it belongs here.
11402
11325
  async function copyRequest(req, stillOwned = () => true) {
@@ -12620,7 +12543,6 @@
12620
12543
  const { request } = await api('/api/use-template', { method: 'POST', body: JSON.stringify({ appId: currentId, templateId }) });
12621
12544
  const line = markedInstruction(request);
12622
12545
  const copied = await copyToClipboard(line);
12623
- 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.'}`);
12624
12546
  showToast(copied ? 'Queued for your terminal AI · copied to clipboard' : 'Queued for your terminal AI', 'ok');
12625
12547
  loadRequests();
12626
12548
  } catch (e) { reportErr(e); }
@@ -12644,7 +12566,6 @@
12644
12566
  const snaps = Array.isArray(res.snapshots) ? res.snapshots.map((s) => ({ name: s.name, dataUrl: s.dataUrl })) : [];
12645
12567
  const { request } = await api('/api/tweak', { method: 'POST', body: JSON.stringify({ appId: currentId, nodeId: node, instruction, snapshots: snaps }) });
12646
12568
  const copied = await copyToClipboard(markedInstruction(request));
12647
- appendNarration(`Tweak queued for <code>${escapeHtml(node)}</code> — your terminal AI can pull it (floless skill) ${copied ? 'or paste the copied instruction' : ''}.`);
12648
12569
  const toastMsg = snaps.length
12649
12570
  ? `Tweak + ${snaps.length} snapshot(s) queued${copied ? ' + copied' : ''}`
12650
12571
  : copied ? 'Tweak queued + copied' : 'Tweak queued';
@@ -15596,6 +15517,14 @@
15596
15517
  });
15597
15518
  }
15598
15519
 
15520
+ // #2649: what Google actually granted an account (people can untick a permission on Google's screen).
15521
+ const GOOGLE_INTEGRATION_ID = 'google-workspace';
15522
+ function googleAccessLine(granted, alias) {
15523
+ // Gmail sending is what emails RFIs, so its absence is the one real fault; a missing Drive list is a choice.
15524
+ 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.`;
15525
+ return granted.drive ? 'Allowed: Gmail sending and Drive file list.' : 'Allowed: Gmail sending. Not allowed: Drive file list (optional).';
15526
+ }
15527
+
15599
15528
  function renderIntegrationAccounts(integration) {
15600
15529
  const slots = Array.isArray(integration.accountSlots) ? integration.accountSlots : [];
15601
15530
  if (!slots.length) return integration.chatSupported
@@ -15625,19 +15554,38 @@
15625
15554
  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.'; }
15626
15555
  else if (slot.status !== 'valid') { state = 'Connect for AI Chat'; stateClass = 'is-chat-warning'; }
15627
15556
  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.'; }
15557
+ if (!why && slot.unavailableCode === 'scope-missing' && integration.id === 'google-workspace') {
15558
+ 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.`;
15559
+ }
15628
15560
  if (!why) {
15629
15561
  // A server reason is shown only when it is ordinary language; internal wording gets the plain fallback.
15630
15562
  const raw = slot.unavailableReason || '';
15631
15563
  why = raw && !/identity|stableid|binding|registry|verify|principal|capability|operation|aware/i.test(raw)
15632
15564
  ? raw : 'This account is not ready for AI Chat.';
15633
15565
  }
15566
+ // The server reports a grant only for a readable sign-in, so an unreadable one never reads as "not allowed".
15567
+ const access = integration.id === 'google-workspace' && slot.granted
15568
+ ? `<span class="int-account-access${slot.granted.gmail ? '' : ' is-warn'}">${escapeHtml(googleAccessLine(slot.granted, slot.alias))}</span>` : '';
15569
+ // #2649: a named account reconnects on its own whenever it needs a new sign-in or new consent; the card's main
15570
+ // button is the default account's. Its Drive choice is the card's checkbox, the person's current selection.
15571
+ const needsSignIn = slot.status !== 'valid' || (slot.granted && !slot.granted.gmail)
15572
+ || ['scope-missing', 'identity-unverified', 'credential-expired', 'generation-unavailable'].includes(slot.unavailableCode);
15573
+ const reconnect = slot.alias && needsSignIn
15574
+ ? `<button class="int-action int-account-reconnect" type="button" data-int="${escapeAttr(integration.id)}" data-int-action="connect"`
15575
+ + ` data-int-alias="${escapeAttr(slot.alias)}"`
15576
+ + ` data-command-id="shell.integrations-account-reconnect#${escapeAttr(`${integration.id}:${slot.alias}`)}"`
15577
+ + ` data-command-instance-label="${escapeAttr(`${integration.name} account ${slot.alias}`)}"`
15578
+ + ` aria-label="Reconnect ${escapeAttr(integration.name)} account ${escapeAttr(slot.alias)}">Reconnect this account</button>`
15579
+ : '';
15634
15580
  return `<div class="int-account ${stateClass}">
15635
15581
  <div class="int-account-copy">
15636
15582
  <span class="int-account-name">${escapeHtml(account)}</span>
15637
15583
  <span class="int-account-origin">${escapeHtml(slotName)}</span>
15638
15584
  </div>
15639
15585
  <span class="int-chat-state">${state}</span>
15586
+ ${access}
15640
15587
  <span class="int-account-reason">${escapeHtml(why)}</span>
15588
+ ${reconnect}
15641
15589
  </div>`;
15642
15590
  }).join('')}</div>`;
15643
15591
  }
@@ -15692,6 +15640,76 @@
15692
15640
  return 'Revit Parser is not included for this account. Ask the account owner to enable it.';
15693
15641
  }
15694
15642
 
15643
+ /**
15644
+ * #2649: the Google Workspace card's extra parts. Gmail sending (for RFIs) is always asked for; the Drive file
15645
+ * list is the person's choice, and the card shows what Google actually granted, never what was asked for.
15646
+ */
15647
+ function googleCardParts(i) {
15648
+ const access = i.googleAccess || {};
15649
+ const slots = Array.isArray(i.accountSlots) ? i.accountSlots : [];
15650
+ const granted = slots.find((slot) => slot.alias == null)?.granted || null;
15651
+ const driveAllowed = !!granted?.drive;
15652
+ // One notice at a time (the server never offers the switch for the person's own app; this order is only defensive).
15653
+ let notice = '';
15654
+ if (access.client === 'own' && access.ownMessage) {
15655
+ notice = `<div class="int-notice is-warn" role="note">${escapeHtml(access.ownMessage)}</div>`;
15656
+ } else if (access.switchAvailable && i.status !== 'disconnected') {
15657
+ 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>';
15658
+ }
15659
+ // Connected cards reconnect with the same Drive choice the checkbox shows, preset to what Google allows now.
15660
+ const reconnect = i.status !== 'connected' ? ''
15661
+ : '<button class="int-action" type="button" data-int="google-workspace" data-int-action="connect"'
15662
+ + ` data-command-id="shell.integrations-connect#${escapeAttr(i.id)}" data-command-instance-label="${escapeAttr(i.name)}">Reconnect</button>`;
15663
+ // Shown only when the person clears a Drive permission Google already holds: Google keeps it until it is removed there.
15664
+ // The person's own Google app decides what Google asks for (its file may list scopes), so FloLess offers no choice.
15665
+ const ownApp = access.client === 'own';
15666
+ const driveNote = driveAllowed && !ownApp
15667
+ ? '<div class="int-drive-note" id="int-google-drive-note" aria-live="polite" hidden>Google will still remember the Drive permission you gave. '
15668
+ + '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>. '
15669
+ + 'That signs FloLess out of Google, Gmail sending included, so click Connect here again afterwards.</div>'
15670
+ : '';
15671
+ const driveChoice = ownApp ? '' : `
15672
+ <label class="int-flow int-flow-drive">
15673
+ <input type="checkbox" class="int-drive-toggle" data-drive-for="${escapeAttr(i.id)}" data-drive-allowed="${driveAllowed ? 'true' : 'false'}"`
15674
+ + ` data-command-id="shell.integrations-google-drive-choice" aria-describedby="int-google-drive-help"${driveAllowed ? ' checked' : ''}> also let FloLess list your Google Drive files
15675
+ </label>
15676
+ <div class="int-drive-help" id="int-google-drive-help">Optional. Gmail sending is always requested so FloLess can email your RFIs.</div>`;
15677
+ return { notice, reconnect, driveNote, driveChoice, deviceCodeAvailable: access.deviceCodeAvailable !== false };
15678
+ }
15679
+
15680
+ /** One OAuth integration's card (#2649: a named function, so its rendered carriers and controls are tested). */
15681
+ function integrationCardHtml(i) {
15682
+ const action = i.status === 'connected' ? 'Disconnect' : i.status === 'expired' ? 'Reconnect' : 'Connect';
15683
+ const badge = i.status === 'connected' ? 'Connected' : i.status === 'expired' ? 'Token expired' : 'Not connected';
15684
+ const meta = i.status === 'disconnected' ? '—' : i.expiresAt ? `expires ${new Date(i.expiresAt).toLocaleString()}` : 'connected';
15685
+ const google = i.id === GOOGLE_INTEGRATION_ID ? googleCardParts(i) : null;
15686
+ return `
15687
+ <div class="int-item int-${i.status}" data-integration-id="${escapeAttr(i.id)}" tabindex="-1">
15688
+ <div class="int-icon" aria-hidden="true">${escapeHtml(VENDOR_ICON[i.vendor] || (i.name[0] || '?'))}</div>
15689
+ <div class="int-info">
15690
+ <div class="int-name">${escapeHtml(i.name)}</div>
15691
+ <div class="int-kind">${i.agent === 'first-party' ? 'Built-in integration' : `${escapeHtml(i.vendor || 'integration')} · tool <code>${escapeHtml(i.agent)}</code>`}</div>
15692
+ <div class="int-scopes">${escapeHtml((i.network || []).join(' · ') || '—')}</div>
15693
+ <div class="int-meta">${escapeHtml(meta)}</div>
15694
+ ${renderIntegrationAccounts(i)}
15695
+ <div class="conn-int" data-conn-int="${escapeAttr(i.id)}"></div>
15696
+ ${google ? google.notice + google.driveChoice + google.driveNote : ''}
15697
+ <div class="int-row">
15698
+ <span class="int-badge int-badge-${i.status}">${badge}</span>
15699
+ <span class="int-recovery-actions">
15700
+ ${google ? google.reconnect : ''}
15701
+ <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>
15702
+ </span>
15703
+ </div>
15704
+ ${i.status === 'connected' || (google && !google.deviceCodeAvailable) ? '' : `
15705
+ <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">
15706
+ <input type="checkbox" class="int-flow-toggle" data-flow="${escapeAttr(i.id)}"> use a device code instead
15707
+ </label>`}
15708
+ <div class="int-devicecode" data-dc="${escapeAttr(i.id)}" role="status" aria-live="polite"></div>
15709
+ </div>
15710
+ </div>`;
15711
+ }
15712
+
15695
15713
  renderIntegrations = function renderIntegrationsReal() {
15696
15714
  if (integrationsLoadState === 'loading' || integrationsLoadState === 'idle') {
15697
15715
  $integrationsList.innerHTML = '<div class="empty-state">Checking integrations…</div>';
@@ -15733,32 +15751,13 @@
15733
15751
  <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>
15734
15752
  </span></div></div></div>`;
15735
15753
  }
15736
- const action = i.status === 'connected' ? 'Disconnect' : i.status === 'expired' ? 'Reconnect' : 'Connect';
15737
- const badge = i.status === 'connected' ? 'Connected' : i.status === 'expired' ? 'Token expired' : 'Not connected';
15738
- const meta = i.status === 'disconnected' ? '—' : i.expiresAt ? `expires ${new Date(i.expiresAt).toLocaleString()}` : 'connected';
15739
- return `
15740
- <div class="int-item int-${i.status}" data-integration-id="${escapeAttr(i.id)}" tabindex="-1">
15741
- <div class="int-icon" aria-hidden="true">${escapeHtml(VENDOR_ICON[i.vendor] || (i.name[0] || '?'))}</div>
15742
- <div class="int-info">
15743
- <div class="int-name">${escapeHtml(i.name)}</div>
15744
- <div class="int-kind">${i.agent === 'first-party' ? 'Built-in integration' : `${escapeHtml(i.vendor || 'integration')} · tool <code>${escapeHtml(i.agent)}</code>`}</div>
15745
- <div class="int-scopes">${escapeHtml((i.network || []).join(' · ') || '—')}</div>
15746
- <div class="int-meta">${escapeHtml(meta)}</div>
15747
- ${renderIntegrationAccounts(i)}
15748
- <div class="conn-int" data-conn-int="${escapeAttr(i.id)}"></div>
15749
- <div class="int-row">
15750
- <span class="int-badge int-badge-${i.status}">${badge}</span>
15751
- <button class="int-action" data-int="${escapeAttr(i.id)}" data-int-action="${action.toLowerCase()}">${action}</button>
15752
- </div>
15753
- ${i.status === 'connected' ? '' : `
15754
- <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">
15755
- <input type="checkbox" class="int-flow-toggle" data-flow="${escapeAttr(i.id)}"> use a device code instead
15756
- </label>`}
15757
- <div class="int-devicecode" data-dc="${escapeAttr(i.id)}"></div>
15758
- </div>
15759
- </div>`;
15754
+ return integrationCardHtml(i);
15760
15755
  }).join('');
15761
15756
  offerClippedScopeLines($integrationsList);
15757
+ // #2649: clearing a Drive permission Google already holds says how to really take it back.
15758
+ $integrationsList.querySelectorAll('.int-drive-toggle[data-drive-allowed="true"]').forEach((box) => {
15759
+ box.onchange = () => { const note = document.getElementById('int-google-drive-note'); if (note) note.hidden = box.checked; };
15760
+ });
15762
15761
  void decorateIntegrationConnections();
15763
15762
  $integrationsList.querySelectorAll('[data-xeorvt-action]').forEach((btn) => {
15764
15763
  btn.onclick = async () => {
@@ -15820,7 +15819,8 @@
15820
15819
  showToast(`${copied ? 'Copied — run' : 'Run'} in your terminal: ${cmd}`, 'info');
15821
15820
  return;
15822
15821
  }
15823
- await startConnect(btn.dataset.int);
15822
+ // #2649: a named account's own Reconnect carries its account; the Drive choice is the card's checkbox.
15823
+ await startConnect(btn.dataset.int, btn.dataset.intAlias ? { alias: btn.dataset.intAlias } : {});
15824
15824
  };
15825
15825
  });
15826
15826
  };
@@ -15895,7 +15895,7 @@
15895
15895
  function dcSlot(id) {
15896
15896
  return $integrationsList.querySelector(`.int-devicecode[data-dc="${(window.CSS && CSS.escape) ? CSS.escape(id) : id}"]`);
15897
15897
  }
15898
- async function startConnect(id) {
15898
+ async function startConnect(id, opts = {}) {
15899
15899
  if (connecting.has(id)) return;
15900
15900
  connecting.add(id);
15901
15901
  const slot = dcSlot(id);
@@ -15904,14 +15904,26 @@
15904
15904
  // loopback-blocked machines.
15905
15905
  const selectorId = (window.CSS && CSS.escape) ? CSS.escape(id) : id;
15906
15906
  const toggle = $integrationsList.querySelector(`.int-flow-toggle[data-flow="${selectorId}"]`);
15907
- const body = toggle && toggle.checked ? JSON.stringify({ flow: 'device-code' }) : '{}';
15907
+ // #2649: Google's Drive choice is the card's checkbox, preset to what Google allows the default account now. Sent
15908
+ // either way, so an unticked box really asks without Drive (a request with no choice keeps the current one).
15909
+ const driveToggle = $integrationsList.querySelector(`.int-drive-toggle[data-drive-for="${selectorId}"]`);
15910
+ const body = JSON.stringify({
15911
+ ...(toggle && toggle.checked ? { flow: 'device-code' } : {}),
15912
+ ...(driveToggle ? { drive: driveToggle.checked } : {}),
15913
+ ...(opts.alias ? { alias: opts.alias } : {}),
15914
+ });
15908
15915
  if (slot) slot.innerHTML = 'Starting sign-in…';
15909
15916
  try {
15910
15917
  const res = await api(`/api/connect/${encodeURIComponent(id)}`, { method: 'POST', body });
15911
15918
  // A managed-preset pre-flight (e.g. port 80 already in use) refuses to start
15912
15919
  // and broadcasts the reason over SSE (connect-result). Clear the guard so the
15913
- // user can retry after fixing it, and don't claim the browser opened.
15914
- if (res && res.started === false) { connecting.delete(id); return; }
15920
+ // user can retry after fixing it, and don't claim the browser opened. #2649: the
15921
+ // reason also comes back here, so a card waiting on a reconnecting SSE still says why.
15922
+ if (res && res.started === false) {
15923
+ connecting.delete(id);
15924
+ if (slot && typeof res.message === 'string') slot.innerHTML = connectResultSlotHtml({ status: 'failed', message: res.message });
15925
+ return;
15926
+ }
15915
15927
  if (slot) {
15916
15928
  if (res.flow === 'device-code' && res.prompt) {
15917
15929
  // Fallback flow: show the device code to enter at the verification URL.
@@ -15925,11 +15937,20 @@
15925
15937
  }
15926
15938
  } catch (e) {
15927
15939
  connecting.delete(id);
15928
- if (slot) slot.innerHTML = '';
15929
- reportErr(e);
15940
+ // #2649: the route's own refusal (an account name it cannot use) is shown where the person clicked. Only a 400 is
15941
+ // the route's sentence; anything else goes to the usual error report.
15942
+ const said = e && e.status === 400 && e.body && typeof e.body.error === 'string' ? e.body.error : '';
15943
+ if (slot) slot.innerHTML = said ? escapeHtml(said) : '';
15944
+ if (!said) reportErr(e);
15930
15945
  }
15931
15946
  }
15932
15947
 
15948
+ /** The sign-in result line on a card: the server's own sentence when it sent one (#2649), else the composed line. */
15949
+ function connectResultSlotHtml(m) {
15950
+ return m.message ? escapeHtml(m.message)
15951
+ : `Sign-in ${escapeHtml(m.status || 'failed')}${m.error ? ' — ' + escapeHtml(m.error) : ''}. Click Connect to retry.`;
15952
+ }
15953
+
15933
15954
  // Show the per-node Tweak button when a node is selected, and the Debug-in-VS
15934
15955
  // button only for exec nodes (those carry C# the host can run under a debugger).
15935
15956
  // Debug lives HERE in the main window, not in the report modal.
@@ -17016,10 +17037,9 @@
17016
17037
  try {
17017
17038
  const res = await api('/api/trigger-run', { method: 'POST', body: JSON.stringify({ id, inputs: currentInputs() }) });
17018
17039
  foregroundTrigger = { appId: id, sessionId: res.sessionId, firedCount: 0 };
17019
- markFirstRunDone(id); // a real live session started → a streaming workflow's "first run" is no longer new
17020
17040
  paintForegroundListening();
17021
17041
  beatLiveViewer();
17022
- 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.`);
17042
+ showToast(`Live session started for ${id}. The report updates on every event; ■ Stop run (top right) ends it.`, 'ok');
17023
17043
  } catch (e) {
17024
17044
  // A refusal (a watcher already holds this host) names the concrete path back —
17025
17045
  // never a dead end. Other failures are recoverable; the server returns them
@@ -17999,17 +18019,76 @@
17999
18019
  done.focus();
18000
18020
  }
18001
18021
 
18022
+ // #2786: how a browser sign-in ended, in the words the sign-in screen and the report dialog both use.
18023
+ const SIGN_IN_ENDED = {
18024
+ refused: "FloLess didn't receive this sign-in from floless.io, so you're still signed out. Click Try again to start a new sign-in.",
18025
+ expired: "This sign-in expired before it was finished, so you're still signed out. Click Try again to start a new sign-in.",
18026
+ unconfirmed: "FloLess couldn't confirm that the sign-in started. If no sign-in page opened, click Try again.",
18027
+ stopped: "FloLess is no longer waiting for this sign-in, so you're still signed out. Click Try again to start a new sign-in.",
18028
+ };
18029
+ const SIGN_IN_STARTING = 'FloLess is starting the sign-in with floless.io. Wait a moment.';
18030
+
18031
+ // #2786: what a sign-in watcher does with one /api/license/status read (null when it could not be read).
18032
+ // `view.waiting`: the watcher's screen says it is waiting for a sign-in it started. `view.shown`: the sign-in
18033
+ // (by session id) whose ending is already on screen, so each ending shows once and a retry's ending always does.
18034
+ // `view.doneOnly`: only a finished sign-in counts, not a licence that was already valid. Pure, so
18035
+ // desktop-login.test.ts runs it.
18036
+ function signInWatchStep(st, view) {
18037
+ if (!st) return { act: 'again' };
18038
+ if (!view.doneOnly && (st.state === 'valid' || st.state === 'offline-grace')) return { act: 'signed-in' };
18039
+ const latest = st.signIn || null;
18040
+ if (latest && latest.state === 'waiting') return { act: 'again' };
18041
+ if (latest && latest.state === 'done') return { act: view.waiting ? 'signed-in' : 'idle' };
18042
+ if (latest && latest.sessionId !== view.shown) return { act: 'ended', ended: latest.state, shown: latest.sessionId };
18043
+ if (!latest && view.waiting) return { act: 'ended', ended: 'stopped', shown: null };
18044
+ return { act: 'idle' };
18045
+ }
18046
+
18002
18047
  function riRenderSignIn() {
18003
18048
  const sub = document.createElement('div');
18004
18049
  sub.className = 'modal-sub';
18050
+ sub.setAttribute('role', 'status');
18005
18051
  sub.textContent = 'Sign in to send a report — your session has expired.';
18006
18052
  const actions = document.createElement('div');
18007
18053
  actions.className = 'modal-actions';
18008
18054
  const close = riButton('ri-signin-close', 'Close', false, () => riClose());
18055
+ // #2786: the dialog stays open while the sign-in runs. It gives the report back once signed in, and says how
18056
+ // a sign-in that did not finish ended; the button then tries again.
18057
+ const showing = () => sub.isConnected && $riModal.classList.contains('show');
18058
+ const view = { waiting: false, shown: null, doneOnly: true }; // the report service, not the licence, asked for this
18059
+ const ended = (message) => { view.waiting = false; sub.textContent = message; signin.hidden = false; signin.textContent = 'Try again'; signin.focus(); };
18060
+ const watch = async () => {
18061
+ if (!showing() || !view.waiting) return;
18062
+ let st; try { st = await api('/api/license/status'); } catch { st = null; }
18063
+ if (!showing() || !view.waiting) return;
18064
+ const step = signInWatchStep(st, view);
18065
+ if (step.act === 'signed-in') {
18066
+ view.waiting = false;
18067
+ $riState.hidden = true; $riForm.hidden = false;
18068
+ $riSend.textContent = 'Send report'; // the send that was turned away left its "Sending…" label
18069
+ riSyncSend(); $riSend.focus();
18070
+ return;
18071
+ }
18072
+ if (step.act === 'ended') { view.shown = step.shown; ended(SIGN_IN_ENDED[step.ended]); return; }
18073
+ if (step.act === 'again') setTimeout(watch, 2000);
18074
+ };
18009
18075
  const signin = riButton('ri-signin-btn', 'Sign in', true, async () => {
18010
- try { await api('/api/license/start', { method: 'POST' }); } catch { /* surfaced via license polling */ }
18011
- riClose();
18076
+ view.waiting = false;
18077
+ signin.disabled = true;
18078
+ signin.setAttribute('data-blocked-reason', SIGN_IN_STARTING);
18079
+ sub.textContent = SIGN_IN_STARTING;
18080
+ let failed = null;
18081
+ try { await api('/api/license/start', { method: 'POST' }); }
18082
+ catch (e) { failed = e?.body?.code === 'sign-in-could-not-start' ? e.body.error : SIGN_IN_ENDED.unconfirmed; }
18083
+ signin.disabled = false;
18084
+ signin.removeAttribute('data-blocked-reason');
18085
+ if (failed) { ended(failed); return; }
18086
+ sub.textContent = 'Finish signing in in your browser. This dialog shows your report again once you are signed in.';
18087
+ signin.hidden = true;
18088
+ view.waiting = true;
18089
+ watch();
18012
18090
  });
18091
+ signin.setAttribute('data-command-id', 'shell.issue-sign-in');
18013
18092
  actions.append(close, signin);
18014
18093
  riShowState(sub, actions);
18015
18094
  }
@@ -18370,25 +18449,6 @@
18370
18449
  }
18371
18450
  });
18372
18451
 
18373
- // Per-workflow onboarding beacon + guide panel + first-open spotlight.
18374
- const $guideBeaconBtn = document.getElementById('guide-beacon');
18375
- if ($guideBeaconBtn) $guideBeaconBtn.onclick = () => { hideSpotlight(); openGuide(); };
18376
- const $guideModal = document.getElementById('guide-modal');
18377
- const $guideGot = document.getElementById('guide-got-it');
18378
- if ($guideGot) $guideGot.onclick = () => closeGuide();
18379
- const $guideWalk = document.getElementById('guide-walk');
18380
- if ($guideWalk) $guideWalk.onclick = () => requestGuide();
18381
- if ($guideModal) onBackdropDismiss($guideModal, () => closeGuide());
18382
- document.addEventListener('keydown', (e) => {
18383
- if (e.key === 'Escape' && $guideModal && $guideModal.classList.contains('show')) closeGuide();
18384
- });
18385
- const $spotGot = document.getElementById('guide-spotlight-got');
18386
- if ($spotGot) $spotGot.onclick = () => hideSpotlight();
18387
- const $spotShow = document.getElementById('guide-spotlight-show');
18388
- if ($spotShow) $spotShow.onclick = () => { hideSpotlight(); openGuide(); };
18389
- const $spotlightEl = document.getElementById('guide-spotlight');
18390
- if ($spotlightEl) $spotlightEl.onclick = (e) => { if (e.target === $spotlightEl) hideSpotlight(); };
18391
-
18392
18452
  // Pull all workspace data (agents/templates/requests + the apps list). Factored
18393
18453
  // out of bootWorkspace so the health poll can re-pull it after the server comes
18394
18454
  // back from a boot-time outage (setServerStatus → recovery).
@@ -18403,6 +18463,9 @@
18403
18463
  if (window.flolessPanels) window.flolessPanels.boot();
18404
18464
  return loadApps().catch((e) => {
18405
18465
  reportErr(e);
18466
+ // #2644: a module refusal means the server answered; it is never "unreachable". (loadApp already shows a refused
18467
+ // workflow as locked; this keeps any other path from painting the offline screen over that answer.)
18468
+ if (moduleRefusalText(e)) { if ($wfTrigger && wfLibrary.length) $wfTrigger.disabled = false; return; }
18406
18469
  setComboTriggerLabel('server unreachable');
18407
18470
  renderCanvasPlaceholder('offline');
18408
18471
  // Only now — the workflow-update offer must never race the data the picker needs (#358).
@@ -18634,7 +18697,8 @@
18634
18697
  #license-gate .primary{appearance:none;border:none;cursor:pointer;font-size:14px;font-weight:600;
18635
18698
  padding:11px 22px;border-radius:8px;background:var(--accent,#3b82f6);color:#fff;}
18636
18699
  #license-gate .primary:hover{filter:brightness(1.08);}
18637
- #license-gate .lg-status{min-height:18px;margin:14px 0 0;font-size:12.5px;color:var(--text-dim,#94a3b8);}
18700
+ #license-gate .primary:disabled{opacity:.6;cursor:default;filter:none;}
18701
+ #license-gate .lg-status{min-height:18px;margin:14px 0 0;font-size:12.5px;color:var(--text-muted,#9aa5b6);}
18638
18702
  #license-gate .lg-sub{display:inline-block;margin-top:6px;font-size:12.5px;color:var(--accent,#3b82f6);text-decoration:none;}
18639
18703
  #license-gate .lg-sub:hover{text-decoration:underline;}
18640
18704
  #license-gate .lg-version{margin:18px 0 0;font-size:11px;font-family:var(--mono,monospace);color:var(--text-muted,#9aa5b6);}`;
@@ -18656,8 +18720,8 @@
18656
18720
  </svg></div>
18657
18721
  <h1>${escapeHtml(copy.headline)}</h1>
18658
18722
  <p>${escapeHtml(copy.body)}</p>
18659
- <button id="lg-signin" class="primary">Sign in at floless.io</button>
18660
- <p class="lg-status" id="lg-status"></p>
18723
+ <button id="lg-signin" class="primary" data-command-id="shell.license-sign-in" aria-describedby="lg-status">Sign in at floless.io</button>
18724
+ <p class="lg-status" id="lg-status" role="status"></p>
18661
18725
  ${copy.secondary ? `<a class="lg-sub" href="${copy.secondary.href}" target="_blank" rel="noopener">${escapeHtml(copy.secondary.label)}</a>` : ''}
18662
18726
  <p class="lg-version" id="lg-version"></p>
18663
18727
  </div>`;
@@ -18668,20 +18732,41 @@
18668
18732
  readHealth()
18669
18733
  .then((h) => { if (h && h.appVersion) document.getElementById('lg-version').textContent = 'FloLess ' + h.appVersion; })
18670
18734
  .catch(() => { /* version is a nicety; never block the gate on it */ });
18671
- document.getElementById('lg-signin').onclick = async () => {
18672
- const s = document.getElementById('lg-status');
18735
+ const signIn = document.getElementById('lg-signin');
18736
+ const s = document.getElementById('lg-status');
18737
+ // A sign-in that cannot go on says why, and the same button starts a fresh one.
18738
+ // #2786: one watcher, while a sign-in is under way. It reloads once FloLess is signed in, and says how the latest
18739
+ // sign-in ended wherever it was started (here, the report dialog, AI Chat or `floless login`), once per sign-in.
18740
+ const view = { waiting: false, shown: null, doneOnly: false };
18741
+ const stop = (message) => { view.waiting = false; s.textContent = message; signIn.textContent = 'Try again'; };
18742
+ let generation = 0;
18743
+ const watch = async (g = ++generation) => {
18744
+ let st; try { st = await api('/api/license/status'); } catch { st = null; }
18745
+ if (g !== generation) return; // a click or a newer watch took over
18746
+ const step = signInWatchStep(st, view);
18747
+ if (step.act === 'signed-in') { location.reload(); return; }
18748
+ if (step.act === 'ended') { view.shown = step.shown; stop(SIGN_IN_ENDED[step.ended]); return; }
18749
+ if (step.act === 'again') setTimeout(() => watch(g), 2000);
18750
+ };
18751
+ signIn.onclick = async () => {
18752
+ generation += 1; // an older watch stops here, so it cannot write over this sign-in while it registers
18753
+ view.waiting = false;
18673
18754
  s.textContent = 'Opening sign-in in your browser…';
18674
- try { await api('/api/license/start', { method: 'POST' }); } catch { /* ignore */ }
18755
+ signIn.textContent = 'Sign in at floless.io';
18756
+ // Starting registers the sign-in with floless.io first, so it can take a moment: one start at a time.
18757
+ signIn.disabled = true;
18758
+ signIn.setAttribute('data-blocked-reason', SIGN_IN_STARTING);
18759
+ let failed = null;
18760
+ try { await api('/api/license/start', { method: 'POST' }); }
18761
+ catch (e) { failed = e?.body?.code === 'sign-in-could-not-start' ? e.body.error : SIGN_IN_ENDED.unconfirmed; }
18762
+ signIn.disabled = false;
18763
+ signIn.removeAttribute('data-blocked-reason');
18764
+ if (failed) { stop(failed); signIn.focus(); watch(); return; } // still follow a sign-in already under way
18765
+ view.waiting = true;
18675
18766
  s.textContent = 'Waiting for sign-in to complete…';
18676
- const deadline = Date.now() + 185000;
18677
- const tick = async () => {
18678
- let st; try { st = await api('/api/license/status'); } catch { st = {}; }
18679
- if (st.state === 'valid' || st.state === 'offline-grace') { location.reload(); return; }
18680
- if (Date.now() > deadline) { s.textContent = 'Timed out — click to try again.'; return; }
18681
- setTimeout(tick, 2000);
18682
- };
18683
- tick();
18767
+ watch();
18684
18768
  };
18769
+ watch(); // a sign-in started before this screen showed (or one that already ended) is said here too
18685
18770
  }
18686
18771
 
18687
18772
  // ── Custom Panels bridge (web/panels.js) ─────────────────────────────────────
@@ -18779,10 +18864,11 @@
18779
18864
  const $wfLanding = document.getElementById('wf-landing');
18780
18865
  // The landing search's query, kept outside the input because the landing re-renders with innerHTML.
18781
18866
  let wfLandingQuery = '';
18782
- // #2568: the landing's two tabs. The choice is remembered by this browser window; anything unknown, or a store that
18783
- // throws (private window, blocked site data), reads as Workflows.
18867
+ // #2568: the landing's tabs (History: every run, grouped per workflow). The choice is remembered by this browser window;
18868
+ // anything unknown, or a store that throws (private window, blocked site data), reads as Workflows.
18784
18869
  const WF_TAB_KEY = 'floless.workflowsLandingTab';
18785
- let wfLandingTab = (() => { try { return localStorage.getItem(WF_TAB_KEY) === 'pages' ? 'pages' : 'workflows'; } catch { return 'workflows'; } })();
18870
+ const WF_TABS = ['workflows', 'pages', 'history'];
18871
+ let wfLandingTab = (() => { try { const t = localStorage.getItem(WF_TAB_KEY); return WF_TABS.includes(t) ? t : 'workflows'; } catch { return 'workflows'; } })();
18786
18872
  function showWorkflowsLanding(on) {
18787
18873
  const next = Boolean(on);
18788
18874
  if (next === wfLanding && (!next || $wfLanding?.childElementCount)) { if (next) renderWorkflowsLanding(); return; }
@@ -18793,8 +18879,7 @@
18793
18879
  if ($wfLanding) $wfLanding.hidden = !wfLanding;
18794
18880
  // Nothing reads routines at startup (only the Routines window, routine events and a few report paths do), so the
18795
18881
  // cards' "Scheduled" chips need a read here.
18796
- if (wfLanding) { hideSpotlight(); renderWorkflowsLanding(); void loadRoutinesData(); }
18797
- else syncSpotlightToMode(); // the canvas is back: a spotlight held back while the list covered it is offered
18882
+ if (wfLanding) { renderWorkflowsLanding(); void loadRoutinesData(); }
18798
18883
  syncTabTitle();
18799
18884
  notifyChatScope();
18800
18885
  }
@@ -18835,19 +18920,20 @@
18835
18920
  /** The Workflows landing's heading, sub line, tabs and (when there is something to search) search box, shared by both tabs. */
18836
18921
  function workflowsLandingHeadHtml(esc, showSearch) {
18837
18922
  const pages = wfLandingTab === 'pages';
18923
+ const history = wfLandingTab === 'history';
18838
18924
  const tab = (id, label) => `<button type="button" role="tab" id="wf-tab-${id}" data-wf-tab="${id}" class="${wfLandingTab === id ? 'active' : ''}"`
18839
- + ` aria-selected="${wfLandingTab === id}"${id === 'pages' ? ' aria-controls="wf-pages-panel"' : ''} tabindex="${wfLandingTab === id ? 0 : -1}"`
18925
+ + ` aria-selected="${wfLandingTab === id}"${id !== 'workflows' ? ` aria-controls="wf-${id}-panel"` : ''} tabindex="${wfLandingTab === id ? 0 : -1}"`
18840
18926
  + ` data-command-id="shell.workflows-landing-tab#${esc(id)}">${label}</button>`;
18841
18927
  return `<div class="ws-head"><div class="ws-head-text"><h2 tabindex="-1" id="wf-landing-title">Workflows</h2>`
18842
18928
  + `<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>`
18843
- + `<div class="tabs ws-step-tabs wf-landing-tabs" role="tablist" aria-label="Workflows page">${tab('workflows', 'Workflows')}${tab('pages', 'Pages')}</div></div>`
18844
- + (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>` : '')
18929
+ + `<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>`
18930
+ + (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>` : '')
18845
18931
  + `</div>`;
18846
18932
  }
18847
18933
 
18848
18934
  /** Switch the landing's tab: remember it, repaint, and (for a keyboard or button move) put focus on the chosen tab. */
18849
18935
  function setWorkflowsLandingTab(tab, focusTab) {
18850
- const next = tab === 'pages' ? 'pages' : 'workflows';
18936
+ const next = WF_TABS.includes(tab) ? tab : 'workflows';
18851
18937
  if (next !== wfLandingTab) {
18852
18938
  wfLandingTab = next;
18853
18939
  try { localStorage.setItem(WF_TAB_KEY, next); } catch { /* not remembered; the tab still switches */ }
@@ -18880,9 +18966,37 @@
18880
18966
  if (keepCaret) { const box = $wfLanding.querySelector('#wf-landing-search'); box?.focus(); box?.setSelectionRange?.(keepCaret[0], keepCaret[1]); }
18881
18967
  }
18882
18968
 
18969
+ /** The History tab: the heading and tabs, the search, and a panel run-history.js fills with every run, per workflow. */
18970
+ function renderWorkflowsHistoryTab() {
18971
+ const focusedTab = document.activeElement?.closest?.('#wf-landing [data-wf-tab]')?.dataset.wfTab || null;
18972
+ const search = document.activeElement?.id === 'wf-landing-search' ? document.activeElement : null;
18973
+ const keepCaret = search ? [search.selectionStart, search.selectionEnd] : null;
18974
+ const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
18975
+ $wfLanding.innerHTML = workflowsLandingHeadHtml(esc, true)
18976
+ + '<div id="wf-history-panel" class="wf-history-panel" role="tabpanel" aria-labelledby="wf-tab-history"></div>';
18977
+ const panel = $wfLanding.querySelector('#wf-history-panel');
18978
+ if (window.flolessRunHistory?.render) {
18979
+ void window.flolessRunHistory.render(panel, {
18980
+ getQuery: () => wfLandingQuery,
18981
+ onAction: (act) => {
18982
+ if (act === 'show-workflows') setWorkflowsLandingTab('workflows', true);
18983
+ else if (act === 'clear-search') { setWorkflowsLandingQuery(''); $wfLanding.querySelector('#wf-landing-search')?.focus(); }
18984
+ },
18985
+ openWorkflow: (id) => openWorkflowFromLanding(id),
18986
+ openDraft: (workflowId) => { if (!landingOpening) openDraftWorkflow(workflowId); },
18987
+ openReport: (id, runId) => window.flolessBridge.openAppReport(id, runId),
18988
+ });
18989
+ } else {
18990
+ 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>';
18991
+ }
18992
+ if (focusedTab) $wfLanding.querySelector(`[data-wf-tab="${focusedTab}"]`)?.focus();
18993
+ if (keepCaret) { const box = $wfLanding.querySelector('#wf-landing-search'); box?.focus(); box?.setSelectionRange?.(keepCaret[0], keepCaret[1]); }
18994
+ }
18995
+
18883
18996
  function renderWorkflowsLanding() {
18884
18997
  if (!$wfLanding) return;
18885
18998
  if (wfLandingTab === 'pages') { renderWorkflowsPagesTab(); return; }
18999
+ if (wfLandingTab === 'history') { renderWorkflowsHistoryTab(); return; }
18886
19000
  const focusedTab = document.activeElement?.closest?.('#wf-landing [data-wf-tab]')?.dataset.wfTab || null;
18887
19001
  const focusedId = document.activeElement?.closest?.('#wf-landing [data-wf-id]')?.dataset.wfId || null;
18888
19002
  const search = document.activeElement?.id === 'wf-landing-search' ? document.activeElement : null;
@@ -18965,6 +19079,7 @@
18965
19079
  + `<div class="ws-thumb">+</div><div class="ws-body"><div><div class="ws-name">New workflow</div>`
18966
19080
  + `<div class="ws-meta">Name it and choose where it belongs. AI builds it with you.</div></div></div></div></div>`
18967
19081
  + unreadableNote
19082
+ + '<div class="wf-setapart-slot ws-workflows"></div>'
18968
19083
  + (wfLibrary.length || unlisted.length || archived.length || restoredRows.length
18969
19084
  ? yoursSection + section('installed', 'data-command-id="shell.workflows-landing-installed"', 'Installed', installed.length, installed.map(card).join(''), true)
18970
19085
  + section('archived', 'data-command-id="shell.workflows-landing-archived"', 'Archived', archived.length, archived.map(archivedCard).join(''), false)
@@ -18980,6 +19095,8 @@
18980
19095
  if (focusedDraft) $wfLanding.querySelector(`[data-wf-draft="${CSS.escape(focusedDraft)}"]`)?.focus();
18981
19096
  if (focusedRestore) $wfLanding.querySelector(`[data-wf-restore="${CSS.escape(focusedRestore)}"]:not(:disabled)`)?.focus();
18982
19097
  if (focusedRestored) $wfLanding.querySelector(`[data-wf-restored="${CSS.escape(focusedRestored)}"]`)?.focus();
19098
+ // #2603: project-workflows.js paints the set-apart folders it owns the answers for (globalThis: harnesses lack it).
19099
+ globalThis.flolessProjectWorkflows?.renderLandingSetApart?.($wfLanding.querySelector('.wf-setapart-slot'), wfSetApart, () => loadApps());
18983
19100
  if (keepCaret) $wfLanding.querySelector('#wf-landing-search')?.focus();
18984
19101
  applyWorkflowsLandingSearch(keepCaret);
18985
19102
  if (clearFocused) $wfLanding.querySelector('#wf-search-clear')?.focus(); // it only exists once the filter ran
@@ -18994,6 +19111,7 @@
18994
19111
  if (!input) return;
18995
19112
  // The Pages tab filters its own rows (pages.js), from the same query.
18996
19113
  if (wfLandingTab === 'pages') { window.flolessPages?.repaintWorkflowsList?.($wfLanding.querySelector('#wf-pages-panel')); return; }
19114
+ if (wfLandingTab === 'history') { window.flolessRunHistory?.repaint?.($wfLanding.querySelector('#wf-history-panel')); return; }
18997
19115
  const terms = wfLandingQuery.trim().toLowerCase().split(/\s+/).filter(Boolean);
18998
19116
  let shownAll = 0;
18999
19117
  for (const grid of $wfLanding.querySelectorAll('.ws-grid')) {
@@ -19040,8 +19158,9 @@
19040
19158
  // load keeps the landing and reports why.
19041
19159
  const loading = loadApp(id);
19042
19160
  const ticket = selectionTicket;
19043
- loading.then(() => {
19044
- if (ticket === selectionTicket && currentId === id) showWorkflowsLanding(false);
19161
+ loading.then((outcome) => {
19162
+ // #2644: a locked module workflow leaves the landing too, onto its locked canvas.
19163
+ if (ticket === selectionTicket && (currentId === id || outcome?.locked)) showWorkflowsLanding(false);
19045
19164
  }).catch(reportErr).finally(() => { landingOpening = false; });
19046
19165
  }
19047
19166
 
@@ -19083,8 +19202,6 @@
19083
19202
  }
19084
19203
  document.body.classList.add('wf-draft-open');
19085
19204
  $wfDraft.hidden = false;
19086
- hideSpotlight();
19087
- paintBeacon(null);
19088
19205
  renderDraftView();
19089
19206
  paintDraftChrome();
19090
19207
  syncTabTitle();
@@ -19323,7 +19440,7 @@
19323
19440
  const onTab = event.target.closest?.('[data-wf-tab]');
19324
19441
  if (onTab && ['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {
19325
19442
  event.preventDefault();
19326
- const order = ['workflows', 'pages'];
19443
+ const order = WF_TABS;
19327
19444
  const at = order.indexOf(onTab.dataset.wfTab);
19328
19445
  const to = event.key === 'Home' ? 0 : event.key === 'End' ? order.length - 1
19329
19446
  : (at + (event.key === 'ArrowRight' ? 1 : order.length - 1)) % order.length;
@@ -19385,8 +19502,10 @@
19385
19502
  else if (owned) return openDraftWorkflow(owned.workflowId);
19386
19503
  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.');
19387
19504
  }
19388
- await loadApp(appId);
19505
+ const outcome = await loadApp(appId);
19389
19506
  showWorkflowsLanding(false);
19507
+ // #2644: say why it did not open (the locked canvas shows the same sentence), never report it as opened.
19508
+ if (outcome?.locked) throw new Error(outcome.locked);
19390
19509
  return true;
19391
19510
  },
19392
19511
  // #2247: open a workflow and its report viewer on the last report (a chat card's "View report"). Shows only what
@@ -19588,8 +19707,6 @@
19588
19707
  getChatScope() {
19589
19708
  return currentChatScope();
19590
19709
  },
19591
- // #2007: the workflow spotlight follows the tab switch (see syncSpotlightToMode).
19592
- syncGuideSpotlight: () => syncSpotlightToMode(),
19593
19710
  // #1890: the active Workflows tab is the way home to the Workflows landing (as Workspaces' is to its own).
19594
19711
  // workspaces.js calls this when the user switches back into Workflows: the landing stays mounted behind
19595
19712
  // Workspaces, so showWorkflowsLanding's own fresh-visit reset never runs on that path.
@@ -19630,41 +19747,6 @@
19630
19747
  && request.chatConversation?.executionOwner === 'chat' && request.chatConversation.chatId === chatId);
19631
19748
  return read ? { requestId: read.id } : null;
19632
19749
  },
19633
- // ── Workspaces guide beacon (the SAME #guide-beacon/#guide-modal, document variant) ──
19634
- // workspaces.js owns the open project + its lifecycle state; aware.js owns the beacon
19635
- // chrome. workspaces.js calls setWorkspaceGuide() with a small snapshot whenever the
19636
- // open project (or its approve/export state) changes, clearWorkspaceGuide() on close/
19637
- // Workflows-mode, and markWorkspaceApproved() the first time an Approve succeeds (which
19638
- // calms the beacon, mirroring markFirstRunDone for a workflow's first Run).
19639
- setWorkspaceGuide(ctx) {
19640
- // ctx: { app, name, displayName?, approved, exported }. Null/!app → treat as clear.
19641
- wsGuideCtx = (ctx && ctx.app) ? { ...ctx } : null;
19642
- if (inWorkspacesMode()) {
19643
- paintWorkspaceBeacon();
19644
- const $m = document.getElementById('guide-modal');
19645
- if ($m && $m.classList.contains('show') && wsGuideCtx) renderWorkspaceGuide();
19646
- }
19647
- },
19648
- clearWorkspaceGuide() {
19649
- wsGuideCtx = null;
19650
- // Repaint through the mode-correct painter. In Workspaces mode paintWorkspaceBeacon() hides the
19651
- // (now-cleared) workspace beacon. On the mode-switch-BACK path we're already in Workflows mode,
19652
- // so repaint the WORKFLOW beacon for the current app instead of no-op'ing — otherwise the stale
19653
- // workspace label/tooltip/is-new lingers until the next workflow load. paintBeacon(null) is safe
19654
- // (it just hides the workflow beacon when no app is open).
19655
- if (inWorkspacesMode()) paintWorkspaceBeacon();
19656
- else paintBeacon(currentId ? apps.get(currentId) : null);
19657
- },
19658
- markWorkspaceApproved(app) {
19659
- if (!app || guideFor(wsGuideKey(app)).approveDone) return;
19660
- setGuide(wsGuideKey(app), { approveDone: true });
19661
- if (wsGuideCtx && wsGuideCtx.app === app) {
19662
- wsGuideCtx.approved = true;
19663
- if (inWorkspacesMode()) paintWorkspaceBeacon();
19664
- const $m = document.getElementById('guide-modal');
19665
- if ($m && $m.classList.contains('show')) renderWorkspaceGuide();
19666
- }
19667
- },
19668
19750
  };
19669
19751
 
19670
19752
  // ── boot ──────────────────────────────────────────────────────────────────────