@floless/app 0.150.0 → 0.152.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.
package/dist/web/aware.js CHANGED
@@ -710,6 +710,7 @@
710
710
  function presentedGateState(app, gateState) {
711
711
  if (gateState === 'agent-changed' && app.approvalCheck && app.approvalCheck.remedy === 'publish') return 'needs-publish';
712
712
  if (gateState === 'agent-changed' && app.approvalCheck && app.approvalCheck.remedy === 'needs-you') return 'needs-you';
713
+ if (gateState === 'ready' && app.approvalCheck && app.approvalCheck.bridgeWarnings && app.approvalCheck.bridgeWarnings.length) return 'needs-you';
713
714
  return recordNeedsCheck(app, gateState) ? 'ready-check-record' : gateState;
714
715
  }
715
716
 
@@ -757,11 +758,22 @@
757
758
  function approvalStripState(app) {
758
759
  const check = app && app.approvalCheck;
759
760
  if (!check) return null;
760
- if (presentedGateState(app, gateStateFor(app)) === 'needs-you') return 'needs-you';
761
+ if (gateStateFor(app) === 'agent-changed' && check.remedy === 'needs-you') return 'needs-you';
761
762
  if (check.current && check.origin === 'successor' && Array.isArray(check.successors) && check.successors.length) return 'carried';
763
+ if (Array.isArray(check.bridgeWarnings) && check.bridgeWarnings.length) return 'bridge-warning';
762
764
  return null;
763
765
  }
764
766
 
767
+ function bridgeWarningRows(check) {
768
+ const warnings = Array.isArray(check.bridgeWarnings) ? check.bridgeWarnings : [];
769
+ if (!warnings.length) return '';
770
+ return '<div class="approval-head">⚠ Needs you · Bridge needs attention</div>'
771
+ + '<ul class="approval-rows">' + warnings.map((w) => '<li class="approval-row"><div class="approval-row-text">'
772
+ + `<div><strong>${escapeHtml(w.via ? `${w.via} → ${w.name}` : w.name)}</strong>: ${escapeHtml(w.detail)}</div>`
773
+ + '<ol>' + w.choices.map((choice) => `<li>${escapeHtml(choice)}</li>`).join('') + '</ol>'
774
+ + '<div class="approval-row-note">This bridge warning does not block Run workflow. The run record will note this warning.</div></div></li>').join('') + '</ul>';
775
+ }
776
+
765
777
  /** "Verbot 1.0.0 → 1.0.1" for every tool this link moved. */
766
778
  function carriedMoves(link) {
767
779
  return (Array.isArray(link.moved) ? link.moved : [])
@@ -776,7 +788,7 @@
776
788
 
777
789
  function unavailableSentence(u) {
778
790
  const tool = `${u.name} ${u.version || ''}`.trim();
779
- if (u.removedBy === 'gc') return `${tool} was removed because no other workflow used it. This workflow was approved with that exact version.`;
791
+ if (u.removedBy === 'gc') return `${tool} is no longer stored on this computer. AWARE cleaned it up because it did not see this workflow using it. This workflow was approved with exactly that version.`;
780
792
  if (u.resolution === 'digest-mismatch') return `${tool} was changed after this workflow was approved with it.`;
781
793
  if (u.resolution === 'missing') return `${u.name} is not installed. This workflow was approved with version ${u.version}.`;
782
794
  return `${tool} is not installed any more. This workflow was approved with that exact version.`;
@@ -795,15 +807,25 @@
795
807
  $approvalStrip.hidden = false;
796
808
  $approvalStrip.dataset.state = state;
797
809
  $approvalStrip.dataset.appId = app.id;
810
+ const bridgeRows = bridgeWarningRows(check);
811
+ if (state === 'bridge-warning') {
812
+ $approvalStrip.className = 'approval-strip approval-needs-you';
813
+ $approvalStrip.setAttribute('role', 'note');
814
+ $approvalStrip.setAttribute('aria-label', 'Bridge needs attention; this warning does not block Run workflow');
815
+ $approvalStrip.innerHTML = bridgeRows;
816
+ return;
817
+ }
798
818
  if (state === 'needs-you') {
799
819
  const rows = (check.unavailable || []).filter((u) => u.reinstall);
800
820
  $approvalStrip.className = 'approval-strip approval-needs-you';
801
821
  $approvalStrip.setAttribute('role', 'group');
802
822
  $approvalStrip.setAttribute('aria-label', 'A tool version needs your decision');
803
- $approvalStrip.innerHTML = `<div class="approval-head">⚠ Needs you</div>`
823
+ $approvalStrip.innerHTML = bridgeRows + `<div class="approval-head">⚠ Needs you</div>`
804
824
  + `<ul class="approval-rows">${rows.map((u) => {
805
825
  const busy = approvalStripReinstalling === `${app.id}\u0000${u.agent}`;
806
- const installedNote = u.installed
826
+ const installedNote = u.storeOnly
827
+ ? `Reinstalling puts ${escapeHtml(u.name)} ${escapeHtml(u.version)} back so this workflow can run.${u.installed ? ` ${escapeHtml(u.name)} ${escapeHtml(u.installed)} stays installed.` : ''}`
828
+ : u.installed
807
829
  ? `Reinstalling makes ${escapeHtml(u.version)} the installed version again. Workflows approved with ${escapeHtml(u.installed)} keep running as they do now.`
808
830
  : `Reinstalling installs ${escapeHtml(u.name)} ${escapeHtml(u.version)}.`;
809
831
  return `<li class="approval-row" data-agent="${escapeAttr(u.agent)}">`
@@ -813,7 +835,7 @@
813
835
  + `<div class="approval-row-actions">`
814
836
  + `<button type="button" class="btn primary" data-approval-reinstall data-agent="${escapeAttr(u.agent)}" data-version="${escapeAttr(u.version)}"`
815
837
  + ` data-command-id="workflow.reinstall-approved-tool#${escapeAttr(u.agent)}" data-command-instance-label="${escapeAttr(`${u.name} ${u.version}`)}"`
816
- + ` data-tip="${escapeAttr(`Install ${u.name} ${u.version} again, so this workflow runs with the version it was approved with`)}"`
838
+ + ` data-tip="${escapeAttr(u.storeOnly ? `Put ${u.name} ${u.version} back, so this workflow runs with the version it was approved with. The installed version does not change` : `Install ${u.name} ${u.version} again, so this workflow runs with the version it was approved with`)}"`
817
839
  + `${busy ? ' disabled aria-busy="true"' : ''}>${busy ? 'Reinstalling…' : escapeHtml(`Reinstall ${u.name} ${u.version}`)}</button>`
818
840
  + `<button type="button" class="btn" data-approval-compile data-command-id="workflow.approval-compile-again"`
819
841
  + ` data-tip="Approve this workflow again with the tool versions installed when it compiles"${approvalStripReinstalling ? ' disabled' : ''}>Compile again</button>`
@@ -827,7 +849,7 @@
827
849
  $approvalStrip.className = 'approval-strip approval-carried';
828
850
  $approvalStrip.setAttribute('role', 'note');
829
851
  $approvalStrip.setAttribute('aria-label', 'Where this workflow’s approval came from');
830
- $approvalStrip.innerHTML = `<details class="approval-details">`
852
+ $approvalStrip.innerHTML = bridgeRows + `<details class="approval-details">`
831
853
  + `<summary data-command-id="workflow.approval-carried-details" data-tip="Show where this approval came from">`
832
854
  + `<span class="approval-carried-label">Approval carried over</span>`
833
855
  + `<span class="approval-carried-sep">·</span><span>${escapeHtml(carriedMoves(last))}</span>`
@@ -851,9 +873,16 @@
851
873
  function runStartApprovalNote(ev) {
852
874
  const cfg = (ev && (ev.config || ev.run_config)) || null;
853
875
  const a = cfg && cfg.approval;
854
- if (!a || a.origin === 'original') return '';
855
- if (a.origin !== 'successor') return ` · an approval FloLess does not recognise — AWARE’s record: ${escapeHtml(a.label || 'none')}`;
856
- return ` · approval carried over — AWARE’s record: ${escapeHtml(a.label || 'carried forward')}`;
876
+ const rows = cfg && cfg['agent-resolution'];
877
+ const bridge = rows && typeof rows === 'object' ? Object.entries(rows).map(([agent, row]) => {
878
+ const w = row && row.bridge;
879
+ if (!w || !['bridge-too-old', 'bridge-too-new', 'declaration-invalid'].includes(w.status) || typeof w.detail !== 'string') return '';
880
+ const label = w.status === 'declaration-invalid' ? 'Ran with an invalid bridge declaration' : 'Ran with a bridge mismatch';
881
+ return ` · ${label}: ${escapeHtml(agent.replaceAll('>', ' → '))}. ${escapeHtml(w.detail)}`;
882
+ }).join('') : '';
883
+ if (!a || a.origin === 'original') return bridge;
884
+ if (a.origin !== 'successor') return ` · an approval FloLess does not recognise — AWARE’s record: ${escapeHtml(a.label || 'none')}${bridge}`;
885
+ return ` · approval carried over — AWARE’s record: ${escapeHtml(a.label || 'carried forward')}${bridge}`;
857
886
  }
858
887
 
859
888
  if ($approvalStrip) {
@@ -897,7 +926,7 @@
897
926
  if (error) {
898
927
  repaintShown();
899
928
  const row = stillHere() && $approvalStrip.querySelector(`.approval-row[data-agent="${CSS.escape(agent)}"] .approval-row-error`);
900
- if (row) row.textContent = `${error.message} You can try again, or Compile again.`;
929
+ if (row) row.textContent = (error.body && error.body.code === 'reinstall-failed') ? `${error.message} You can try again, or Compile again.` : error.message;
901
930
  else showToast(error.message, 'warn'); // the person moved on: the failure still reaches them
902
931
  return;
903
932
  }
@@ -1115,6 +1144,9 @@
1115
1144
  }
1116
1145
  const recordTip = gateState === 'ready' ? approvalRecordTip(app.approvalCheck) : null;
1117
1146
  if (recordTip) gateTips.ready = recordTip;
1147
+ if (gateState === 'ready' && app.approvalCheck && app.approvalCheck.bridgeWarnings && app.approvalCheck.bridgeWarnings.length) {
1148
+ gateTips.ready += '\nBridge needs attention. Review the warning and choices above the canvas. Run workflow is still available; the run record will note the warning.';
1149
+ }
1118
1150
  $runState.dataset.tip = activeTips[status.label] || gateTips[gateState] || '';
1119
1151
 
1120
1152
  // Push a snapshot to the Instructor band. One-way: the band renders what it
@@ -1129,6 +1161,7 @@
1129
1161
  // #1996: what the Instructor says for a not-confirmed carried-forward approval or an incomplete record.
1130
1162
  remedy: (app.approvalCheck && app.approvalCheck.remedy) || null,
1131
1163
  recordIncomplete: recordNeedsCheck(app, gateState),
1164
+ bridgeWarning: !!(app.approvalCheck && app.approvalCheck.bridgeWarnings && app.approvalCheck.bridgeWarnings.length),
1132
1165
  totalInputs: inputs.length,
1133
1166
  inputsSet: inputs.filter((i) => {
1134
1167
  const v = values[i.name];
@@ -1447,12 +1480,13 @@
1447
1480
  const ico = $b.querySelector('.guide-beacon-ico');
1448
1481
  const label = $b.querySelector('.guide-beacon-label');
1449
1482
  if (ico) ico.textContent = isNew ? '✦' : '?';
1450
- if (label) label.textContent = isNew ? 'Start here' : 'Guide';
1483
+ // #2046: "Guide" is the onboarding agent now; at rest this beacon is about the open project.
1484
+ if (label) label.textContent = isNew ? 'Start here' : 'About this project';
1451
1485
  // No "workflow"/"Run" vocabulary — this is a document project.
1452
1486
  $b.dataset.tip = isNew
1453
1487
  ? 'New here? See what this project does and how to take it from drawing to export.'
1454
- : 'Open the guide for this project.';
1455
- $b.setAttribute('aria-label', (isNew ? 'Start here — guide for ' : 'Guide for ') + (ctx.name || ctx.displayName || ctx.app));
1488
+ : 'See what this project does and how to use it.';
1489
+ $b.setAttribute('aria-label', (isNew ? 'Start here — about ' : 'About ') + (ctx.name || ctx.displayName || ctx.app));
1456
1490
  }
1457
1491
 
1458
1492
  function paintBeacon(app) {
@@ -1470,11 +1504,12 @@
1470
1504
  // Monochrome dingbats (✦ / ?), not colour emoji — the locked baseline uses text
1471
1505
  // glyphs (★, ▸); the pulse, not an emoji, is the "new" signal.
1472
1506
  if (ico) ico.textContent = isNew ? '✦' : '?';
1473
- if (label) label.textContent = isNew ? 'Start here' : 'Guide';
1507
+ // #2046: "Guide" is the onboarding agent now; at rest this beacon is about the open workflow.
1508
+ if (label) label.textContent = isNew ? 'Start here' : 'About this workflow';
1474
1509
  $b.dataset.tip = isNew
1475
1510
  ? 'New here? See what this workflow does and how to run it.'
1476
- : 'Open the guide for this workflow.';
1477
- $b.setAttribute('aria-label', (isNew ? 'Start here — guide for ' : 'Guide for ') + (app.displayName || app.id));
1511
+ : 'See what this workflow does and how to run it.';
1512
+ $b.setAttribute('aria-label', (isNew ? 'Start here — about ' : 'About ') + (app.displayName || app.id));
1478
1513
  }
1479
1514
 
1480
1515
  // Record a completed real run → the workflow is no longer new; calm the beacon (and
@@ -1797,7 +1832,7 @@
1797
1832
  // ≡ menu "New workflow…" — create the durable owner BEFORE asking the terminal AI to author.
1798
1833
  // The UI chooses only a display name and owner; the server mints the UUID and derives the actual
1799
1834
  // directory. That makes a queued request project-safe without turning the browser into an author.
1800
- async function requestNewWorkflow() {
1835
+ async function requestNewWorkflow(prefill = {}) {
1801
1836
  try {
1802
1837
  const { projects = [] } = await api('/api/projects');
1803
1838
  const ownerOptions = workflowOwnerOptions(projects);
@@ -1808,6 +1843,8 @@
1808
1843
  {
1809
1844
  name: 'name', label: 'Workflow name', placeholder: 'e.g. Weekly model review',
1810
1845
  commandId: 'shell.new-workflow-name', required: true,
1846
+ // #2046: a Guide suggestion opens this with its name filled in; the person still chooses and confirms.
1847
+ ...(typeof prefill.name === 'string' && prefill.name ? { value: prefill.name } : {}),
1811
1848
  },
1812
1849
  {
1813
1850
  name: 'owner', label: 'Location', type: 'select', value: 'standalone',
@@ -1968,6 +2005,7 @@
1968
2005
  // belong inside it. Set unconditionally (including to undefined) so a workflow that stops being a
1969
2006
  // publication clears, rather than keeping the previous answer forever.
1970
2007
  await commitPublicationAvailability(id, read, contractState);
2008
+ if (ticket !== selectionTicket) return; // a newer selection also wins during the availability wait
1971
2009
  currentId = id;
1972
2010
  workflowSelectionGeneration += 1;
1973
2011
  if (id === 'tekla-model-report' || id === 'floless-workspace-model-report') {
@@ -2043,7 +2081,7 @@
2043
2081
  ]).then(() => {});
2044
2082
  }
2045
2083
 
2046
- async function loadApps() {
2084
+ async function loadApps({ preserveSelection = false } = {}) {
2047
2085
  // …and mean it: the trigger said "loading…" but stayed CLICKABLE, so a click during the fetch
2048
2086
  // opened the popover onto an empty #wf-list — the exact "picker opens and stays empty, it never
2049
2087
  // says loading, it just looks broken" report in #358. buildWorkflowCombo() re-enables it once
@@ -2054,9 +2092,11 @@
2054
2092
  // with no re-enable path — worst on delete, which clears the open workflow first. So a failed
2055
2093
  // refresh restores what the user had; only a load that never had a list stays disabled.
2056
2094
  const wasUsable = !!$wfTrigger && !$wfTrigger.disabled;
2057
- setComboTriggerLabel('loading…');
2058
- if ($wfTrigger) $wfTrigger.disabled = true;
2059
- renderCanvasPlaceholder('loading');
2095
+ if (!preserveSelection) {
2096
+ setComboTriggerLabel('loading…');
2097
+ if ($wfTrigger) $wfTrigger.disabled = true;
2098
+ renderCanvasPlaceholder('loading');
2099
+ }
2060
2100
  let list;
2061
2101
  // #1890 PR 3b-0: the owned workflow open now, read before the owner map is refreshed — if its installed copy is
2062
2102
  // gone after this refresh, it shows its own recovery view instead of falling back to another workflow.
@@ -2064,9 +2104,10 @@
2064
2104
  const openId = currentId;
2065
2105
  const generation = ++appsLoadGeneration;
2066
2106
  let owned = null;
2107
+ let unreadable = [];
2067
2108
  try {
2068
- ({ apps: list } = await api('/api/workflows/library'));
2069
- try { ({ workflows: owned } = await api('/api/workflows/owned')); }
2109
+ ({ apps: list, unreadable = [] } = await api('/api/workflows/library'));
2110
+ try { ({ workflows: owned } = await api('/api/workflows/owned?archived=1')); }
2070
2111
  catch { /* the owned list is additive here: a failed read keeps the drafts last shown */ }
2071
2112
  // An older refresh that finishes after a newer one must not overwrite what the newer one showed.
2072
2113
  if (generation !== appsLoadGeneration) return;
@@ -2074,12 +2115,43 @@
2074
2115
  list = list.filter((a) => a.execution !== 'internal');
2075
2116
  rememberWorkflowOwners(list);
2076
2117
  wfLibrary = list;
2118
+ wfUnreadable = Array.isArray(unreadable) ? unreadable.filter((row) => row && typeof row.id === 'string') : [];
2077
2119
  } catch (e) {
2078
2120
  // Usable before THIS refresh, or built by an earlier one (an overlapping refresh disabled it first, and its
2079
2121
  // own success was then superseded): a failed refresh never strands a picker that has workflows in it.
2080
- if ((wasUsable || $promptSel.options.length > 0) && $wfTrigger) $wfTrigger.disabled = false;
2122
+ if (!preserveSelection) {
2123
+ if ((wasUsable || $promptSel.options.length > 0) && $wfTrigger) $wfTrigger.disabled = false;
2124
+ }
2081
2125
  throw e;
2082
2126
  }
2127
+ if (preserveSelection) {
2128
+ // Read the current selection AFTER the requests: a person may have opened something newer.
2129
+ // Refreshing a restored workflow's catalogue must not change that canvas, label or picker value.
2130
+ const selected = $promptSel.value;
2131
+ const selectedText = Array.from($promptSel.options).find((option) => option.value === selected)?.textContent || selected;
2132
+ $promptSel.innerHTML = '';
2133
+ for (const entry of list) {
2134
+ const option = document.createElement('option');
2135
+ option.value = entry.id;
2136
+ option.textContent = `${entry.ownedWorkflow ? entry.ownedWorkflow.displayName : entry.id} · ${entry.nodes} node${entry.nodes === 1 ? '' : 's'} · ${entry.layout}`;
2137
+ $promptSel.appendChild(option);
2138
+ }
2139
+ if (selected && !list.some((entry) => entry.id === selected)) {
2140
+ const option = document.createElement('option');
2141
+ option.value = selected; option.textContent = selectedText; option.hidden = true;
2142
+ $promptSel.appendChild(option);
2143
+ }
2144
+ $promptSel.value = selected;
2145
+ buildWorkflowCombo(list);
2146
+ // A pending older refresh may have disabled the picker. Its transient flag is not
2147
+ // readiness: this fresh catalogue owns enablement, and a hidden selection is not a choice.
2148
+ if ($wfTrigger) $wfTrigger.disabled = !list.length;
2149
+ setComboSelected(currentId || selected);
2150
+ const count = document.getElementById('apps-count');
2151
+ if (count) count.textContent = list.length;
2152
+ if (wfLanding) renderWorkflowsLanding();
2153
+ return;
2154
+ }
2083
2155
  $promptSel.innerHTML = '';
2084
2156
  if (!list.length) {
2085
2157
  // The guided empty-state panel owns the "install a workflow" message now —
@@ -2200,9 +2272,12 @@
2200
2272
  let wfLanding = false;
2201
2273
  let wfLandingBooted = false;
2202
2274
  let wfLibrary = [];
2275
+ // C12 (#1337): installed workflows AWARE could not read ({ id, name, workflowId? }), named on the landing, never hidden.
2276
+ let wfUnreadable = [];
2203
2277
  // #1890 PR 3b-0: every owned workflow, drafts included (/api/workflows/owned), and the draft open in the canvas
2204
2278
  // area, if any. A draft has no runtime app, so it is never `currentId` and never goes to loadApp.
2205
2279
  let wfOwned = [];
2280
+ const restoringWorkflows = new Set();
2206
2281
  let draftWorkflow = null;
2207
2282
  // Opening anything (a workflow or a draft) takes a new ticket; a workflow load that finishes after a newer open
2208
2283
  // is dropped, so a slow load can never land on top of a draft opened meanwhile (#1890 PR 3b-0 review).
@@ -2266,7 +2341,7 @@
2266
2341
  const actions = owned
2267
2342
  ? `<button type="button" class="wf-act act-edit" data-wf-act="rename" data-command-id="workflow.rename-owned#${escapeAttr(ownedId)}" data-command-instance-label="${escapeAttr(workflowName)}" data-id="${aid}" tabindex="-1" data-tip="Rename" aria-label="Rename ${escapeAttr(workflowName)}">✎</button>`
2268
2343
  + `<button type="button" class="wf-act act-dup" data-wf-act="duplicate" data-command-id="workflow.copy-owned#${escapeAttr(ownedId)}" data-command-instance-label="${escapeAttr(workflowName)}" data-id="${aid}" tabindex="-1" data-tip="Copy" aria-label="Copy ${escapeAttr(workflowName)}">⧉</button>`
2269
- + `<button type="button" class="wf-act act-del" data-wf-act="delete" data-command-id="workflow.archive#${escapeAttr(ownedId)}" data-command-instance-label="${escapeAttr(workflowName)}" data-id="${aid}" tabindex="-1" data-tip="Archive" aria-label="Archive ${escapeAttr(workflowName)}">×</button>`
2344
+ + `<button type="button" class="wf-act act-del" data-wf-act="delete" data-command-id="workflow.archive#${escapeAttr(ownedId)}" data-command-instance-label="${escapeAttr(workflowName)}" data-id="${aid}" tabindex="-1" data-tip="Archive — restore from Archived on the Workflows page" aria-label="Archive ${escapeAttr(workflowName)}">×</button>`
2270
2345
  : `<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>`
2271
2346
  + `<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>`
2272
2347
  + `<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>`;
@@ -2507,7 +2582,7 @@
2507
2582
  closeCombo(false);
2508
2583
  const res = await formModal({
2509
2584
  title: 'Archive workflow?',
2510
- sub: `Hide “${name}” from Workflows and block new runs. Its source, chat, history and publications stay on this computer.`,
2585
+ sub: `Hide “${name}” from Workflows and block new runs. Its source, chat, history and publications stay on this computer. Restore it from Archived on the Workflows page.`,
2511
2586
  fields: [], okLabel: 'Archive', safeDefault: true,
2512
2587
  });
2513
2588
  if (!res) return;
@@ -4773,8 +4848,9 @@
4773
4848
  $reportShare.hidden = true; // the frame is blank — only a painted report is shareable
4774
4849
  $reportOverlay.hidden = false;
4775
4850
  $reportOverlay.innerHTML = opts.debug
4776
- ? `<div class="spinner"></div><div>Launching the .NET debugger for <code>${escapeHtml(nodeId)}</code> — a Windows picker will pop; choose your <strong>Visual Studio</strong> to attach to <code>aware-tekla.exe</code>, then step through. The report renders when you let it finish.</div>`
4777
- : `<div class="spinner"></div><div>${approvedModelReport ? 'Reading the selected approved model to make a complete, read-only report…' : `Running <code>${escapeHtml(currentId)}</code> against the live model…`}</div><button type="button" class="overlay-stop">■ Stop run</button>`;
4851
+ ? `<div>Launching the .NET debugger for <code>${escapeHtml(nodeId)}</code> — a Windows picker will pop; choose your <strong>Visual Studio</strong> to attach to <code>aware-tekla.exe</code>, then step through. The report renders when you let it finish.</div>`
4852
+ : `<div>${approvedModelReport ? 'Reading the selected approved model to make a complete, read-only report…' : `Running <code>${escapeHtml(currentId)}</code> against the live model…`}</div><button type="button" class="overlay-stop">■ Stop run</button>`;
4853
+ $reportOverlay.prepend(runningFlo());
4778
4854
  showModal($reportModal);
4779
4855
  $reportModal.dataset.nodeId = nodeId;
4780
4856
 
@@ -4870,22 +4946,35 @@
4870
4946
  const code = body && typeof body.code === 'string' ? body.code : '';
4871
4947
  const compileFix = (code === 'agent-version-changed' || code === 'needs-compile') && !$compileBtn.hidden;
4872
4948
  const reinstall = code === 'agent-files-changed';
4949
+ // #2123: FloLess refused before anything started (the workflow was archived, edited or re-published): it never
4950
+ // "stopped before it finished", and no node is running.
4951
+ const notRun = !!(body && body.notRun);
4952
+ if (notRun) clearNodeStatus();
4953
+ // A not-run answer whose fix the sentence names (restore, publish, compile, run again) is no fault: "Report this
4954
+ // problem" would imply a bug. The server says which sentences send the person to Report an issue; those keep it.
4955
+ const reportable = !notRun || body.reportable === true;
4873
4956
  clearReportFrames();
4874
4957
  $reportShare.hidden = true;
4875
4958
  $reportOverlay.hidden = false;
4876
4959
  $reportOverlay.replaceChildren();
4877
- $reportSub.textContent = 'The report could not be created.';
4960
+ $reportSub.textContent = notRun ? 'Nothing ran, so no report was made.' : 'The report could not be created.';
4878
4961
 
4879
4962
  const card = mkEl('div', 'cred-fail-card run-fail-card');
4880
4963
  card.setAttribute('role', 'status');
4881
4964
  const status = mkEl('div', 'cred-fail-status');
4882
- const icon = mkEl('span', 'cred-fail-icon', '⚠');
4965
+ // #2079: Flo, hat off (it stopped working), says this needs attention; the headline says what.
4966
+ const icon = mkEl('span', 'cred-fail-icon', typeof floAvatar === 'function' ? '' : '⚠');
4883
4967
  icon.setAttribute('aria-hidden', 'true');
4884
- status.append(icon, document.createTextNode(compileFix ? 'Needs compiling' : reinstall ? 'Tool changed' : 'Run stopped'));
4968
+ if (typeof floAvatar === 'function') { icon.classList.add('run-fail-flo'); floAvatar(icon, { size: 28, mood: 'warning' }); }
4969
+ status.append(icon, document.createTextNode(compileFix ? 'Needs compiling' : reinstall ? 'Tool changed' : notRun ? 'Didn’t run' : 'Run stopped'));
4885
4970
  const headline = mkEl('div', 'cred-fail-headline', compileFix
4886
4971
  ? 'This workflow needs compiling again'
4887
- : reinstall ? 'A tool needs reinstalling' : 'The workflow stopped before it finished');
4972
+ : reinstall ? 'A tool needs reinstalling' : notRun ? 'This workflow didn’t run' : 'The workflow stopped before it finished');
4888
4973
  const text = mkEl('div', 'cred-fail-body', message);
4974
+ for (const warning of (body && body.bridgeWarnings) || []) {
4975
+ const label = warning.status === 'declaration-invalid' ? 'Ran with an invalid bridge declaration' : 'Ran with a bridge mismatch';
4976
+ text.append(mkEl('p', '', `${label}: ${warning.via ? warning.via + ' → ' : ''}${warning.name}. ${warning.detail}`));
4977
+ }
4889
4978
  const actions = mkEl('div', 'cred-fail-actions');
4890
4979
  if (compileFix) {
4891
4980
  const compile = mkEl('button', 'primary cred-reconnect run-fail-compile', 'Compile now');
@@ -4903,11 +4992,12 @@
4903
4992
  detail: { workflow: (app && app.displayName) || currentId || '', message,
4904
4993
  reason: body && typeof body.reason === 'string' ? body.reason : '', returnFocus: report },
4905
4994
  }));
4906
- actions.append(report);
4995
+ if (reportable) actions.append(report);
4907
4996
  card.append(status, headline, text, actions);
4908
4997
  $reportOverlay.append(card);
4909
- showToast(message, 'warn');
4910
- (actions.querySelector('button') || report).focus();
4998
+ showToast(message, notRun ? 'info' : 'warn');
4999
+ const first = actions.querySelector('button');
5000
+ if (first) first.focus(); else { card.tabIndex = -1; card.focus(); } // #2123: a not-run card may have no button
4911
5001
  }
4912
5002
 
4913
5003
  const CRED_BODY_IDLE = 'Sign in again and then run the workflow — it takes about 30 seconds.';
@@ -6179,6 +6269,8 @@
6179
6269
  // markup is injected via graftFill() (replaceChildren + insertAdjacentHTML) so the
6180
6270
  // escaping discipline is explicit at each call site.
6181
6271
  const $graftModal = document.getElementById('graft-modal');
6272
+ let graftOpener = null; // #2155: the control Build a tool was opened from (see returnFromGraft)
6273
+ const $graftDialog = $graftModal?.querySelector('.modal.graft');
6182
6274
  const $graftBack = document.getElementById('graft-back');
6183
6275
  const $graftCancel = document.getElementById('graft-cancel');
6184
6276
  const $graftPrimary = document.getElementById('graft-primary');
@@ -6261,12 +6353,17 @@
6261
6353
  $graftCancel.setAttribute('data-command-instance-label', 'building a tool');
6262
6354
  const supported = prefill && GRAFT_KINDS.some((item) => item.kind === prefill.kind)
6263
6355
  && typeof prefill.ref === 'string' && prefill.ref.trim();
6264
- graftState = { kind: supported ? prefill.kind : 'dlls', ref: supported ? prefill.ref : '', decompile: false, showMore: false, preview: null, stagedRef: null, verifyInFlight: false, commitInFlight: false, probe: null, focusCheckRow: false, onPrimary: runGraftIntrospect, onBack: null };
6265
- document.getElementById('graft-title').textContent = 'Graft into tool';
6266
- document.getElementById('graft-sub').textContent = 'Choose a DLL, package, or API spec. AWARE will inspect it and prepare command descriptions for your review.';
6356
+ // #2055: a Discover program's install folder, named so Graft can say where the prefill came from (or that none was found).
6357
+ const origin = prefill && prefill.origin && typeof prefill.origin.label === 'string'
6358
+ ? { label: prefill.origin.label.slice(0, 160), folderKnown: Boolean(supported), unreadable: prefill.origin.unreadable === true, ref: supported ? prefill.ref : '' } : null;
6359
+ graftState = { origin, kind: supported ? prefill.kind : 'dlls', ref: supported ? prefill.ref : '', decompile: false, showMore: false, preview: null, stagedRef: null, verifyInFlight: false, commitInFlight: false, probe: null, focusCheckRow: false, onPrimary: runGraftIntrospect, onBack: null };
6267
6360
  $graftBack.disabled = false; $graftCancel.disabled = false;
6361
+ // #2155: where to put the person back on Cancel / Escape (the Tools library hides itself before this runs).
6362
+ const opener = document.activeElement;
6363
+ graftOpener = opener && typeof opener.focus === 'function' && opener !== document.body && !$graftModal.contains(opener) ? opener : null;
6268
6364
  graftRenderPicker();
6269
6365
  showModal($graftModal);
6366
+ graftLandFocus(); // #2128: an open modal dialog holds the keyboard from the start, wherever it was opened from
6270
6367
  }
6271
6368
  document.addEventListener('floless:discovery-graft', (event) => {
6272
6369
  const source = event.detail;
@@ -6277,6 +6374,9 @@
6277
6374
 
6278
6375
  function graftRenderPicker() {
6279
6376
  clearGraftInstructorNote();
6377
+ // #2128: Back from the preview returns here, so the picker owns its own title (not only openGraftModal).
6378
+ document.getElementById('graft-title').textContent = 'Graft into tool';
6379
+ document.getElementById('graft-sub').textContent = 'Choose a DLL, package, or API spec. AWARE will inspect it and prepare command descriptions for your review.';
6280
6380
  graftState.probe = null; // a check belongs to one inspected source; choosing again starts clean
6281
6381
  graftState.onPrimary = runGraftIntrospect;
6282
6382
  graftState.onBack = null;
@@ -6285,23 +6385,34 @@
6285
6385
  `<button type="button" class="graft-kind${k.kind === graftState.kind ? ' selected' : ''}" data-kind="${k.kind}">` +
6286
6386
  `<div class="gk-name">${escapeHtml(k.label)}</div><div class="gk-desc">${escapeHtml(k.desc)}</div></button>`).join('');
6287
6387
  const moreBtn = graftState.showMore ? '' : '<button type="button" class="graft-more" id="graft-more">▸ More source types</button>';
6388
+ const chooseBtn = GRAFT_FOLDER_KINDS[graftState.kind]
6389
+ ? '<button type="button" class="graft-choose" id="graft-choose" data-command-id="shell.graft-choose-folder" data-tip="Pick a folder instead of typing the path" aria-describedby="graft-field-label">Choose folder…</button>'
6390
+ : '';
6288
6391
  const decompile = cfg.decompile
6289
6392
  ? `<label class="rtn-toggle" style="margin-top:4px;"><input type="checkbox" id="graft-decompile"${graftState.decompile ? ' checked' : ''}><span class="rtn-toggle-track"></span><span class="rtn-toggle-label">Include decompiled private types (slower)</span></label>`
6290
6393
  : '';
6291
6394
  graftFill(graftBodyEl(),
6292
6395
  `<div class="modal-field"><label>Source type</label><div class="graft-kinds">${tiles}</div>${moreBtn}</div>` +
6293
6396
  `<div class="modal-field"><label id="graft-field-label">${escapeHtml(cfg.field.label)}</label>` +
6294
- `<div class="graft-row"><input type="text" id="graft-ref" placeholder="${escapeHtml(cfg.field.placeholder)}" value="${escapeHtml(graftState.ref)}" autocomplete="off" spellcheck="false"></div>` +
6397
+ `<p class="graft-hint graft-origin" id="graft-origin" hidden></p>` +
6398
+ `<div class="graft-row"><input type="text" id="graft-ref" placeholder="${escapeHtml(cfg.field.placeholder)}" value="${escapeHtml(graftState.ref)}" autocomplete="off" spellcheck="false" aria-describedby="graft-origin graft-hint">${chooseBtn}</div>` +
6295
6399
  `<div class="graft-hint" id="graft-hint">${escapeHtml(cfg.field.hint)}</div>` +
6296
- `<div id="graft-matched"></div>${decompile}</div>`);
6400
+ `<div id="graft-matched" role="status"></div>${decompile}</div>`);
6401
+ graftRenderOrigin();
6297
6402
  graftBodyEl().querySelectorAll('.graft-kind').forEach((el) => { el.onclick = () => { graftState.kind = el.dataset.kind; graftRenderPicker(); }; });
6298
6403
  const more = document.getElementById('graft-more'); if (more) more.onclick = () => { graftState.showMore = true; graftRenderPicker(); };
6299
6404
  const ref = document.getElementById('graft-ref');
6300
6405
  ref.oninput = () => {
6301
6406
  graftState.ref = ref.value;
6407
+ graftRenderOrigin();
6408
+ // A picker failure note is about the last attempt; typing (or a chosen folder) brings back the field's own hint.
6409
+ const hintEl = document.getElementById('graft-hint');
6410
+ if (hintEl) hintEl.textContent = graftCfg(graftState.kind).field.hint;
6302
6411
  graftFooter({ primaryLabel: 'Inspect source', primaryDisabled: !graftState.ref.trim() });
6303
6412
  if (graftCfg(graftState.kind).match) graftMatchDebounced();
6304
6413
  };
6414
+ const choose = document.getElementById('graft-choose');
6415
+ if (choose) choose.onclick = () => graftChooseFolder(choose, ref);
6305
6416
  ref.onkeydown = (e) => { if (e.key === 'Enter' && graftState.ref.trim()) runGraftIntrospect(); };
6306
6417
  const dec = document.getElementById('graft-decompile'); if (dec) dec.onchange = () => { graftState.decompile = dec.checked; };
6307
6418
  graftFooter({ backShown: false, primaryLabel: 'Inspect source', primaryDisabled: !graftState.ref.trim() });
@@ -6309,6 +6420,53 @@
6309
6420
  if (graftCfg(graftState.kind).match && graftState.ref.trim()) graftMatch();
6310
6421
  }
6311
6422
 
6423
+ // #2055: path-based sources can be picked with the native folder picker; each turns the folder into its field's form.
6424
+ const trimSlash = (folder) => folder.replace(/[\\/]+$/, '');
6425
+ const GRAFT_FOLDER_KINDS = {
6426
+ dlls: (folder) => `${trimSlash(folder)}\\*.dll`,
6427
+ headers: (folder) => `${trimSlash(folder)}\\*.h`,
6428
+ csharp: (folder) => folder,
6429
+ };
6430
+ /** The note above the field: where a Discover prefill came from, or that no install folder was found. Never a block. */
6431
+ function graftRenderOrigin() {
6432
+ const el = document.getElementById('graft-origin');
6433
+ if (!el) return;
6434
+ const origin = graftState.origin;
6435
+ let text = '';
6436
+ if (origin && graftState.kind === 'dlls' && origin.folderKnown && graftState.ref === origin.ref) {
6437
+ text = `From Discover: the install folder for ${origin.label}. Check the DLLs listed below, or choose another folder.`;
6438
+ } else if (origin && graftState.kind === 'dlls' && !origin.folderKnown && !graftState.ref.trim()) {
6439
+ text = origin.unreadable
6440
+ ? `FloLess couldn’t look in the install folder for ${origin.label}. Choose its folder, or paste the path to its DLLs.`
6441
+ : `FloLess didn’t find where ${origin.label} is installed. Choose its folder, or paste the path to its DLLs.`;
6442
+ }
6443
+ el.textContent = text;
6444
+ el.hidden = !text;
6445
+ }
6446
+ async function graftChooseFolder(button, input) {
6447
+ const toForm = GRAFT_FOLDER_KINDS[graftState.kind];
6448
+ if (!toForm) return;
6449
+ const generation = graftGeneration;
6450
+ const kind = graftState.kind;
6451
+ button.disabled = true;
6452
+ try {
6453
+ const res = await api('/api/graft/choose-folder', { method: 'POST', body: JSON.stringify({ current: graftState.ref }) });
6454
+ // The window was closed or reopened, or the source type changed, while the picker was open: nothing to fill.
6455
+ if (generation !== graftGeneration || kind !== graftState.kind || !input.isConnected) return;
6456
+ if (!res || res.cancelled || typeof res.path !== 'string') return;
6457
+ input.value = toForm(res.path);
6458
+ input.oninput();
6459
+ } catch (err) {
6460
+ const hint = document.getElementById('graft-hint');
6461
+ // The server's own sentence only when the server answered; a dropped connection says what to do instead.
6462
+ const said = err && err.status && typeof err.message === 'string' && err.message ? err.message : '';
6463
+ if (generation === graftGeneration && input.isConnected && hint) hint.textContent = said || 'FloLess couldn’t open the folder picker. Paste the folder path instead.';
6464
+ } finally {
6465
+ button.disabled = false;
6466
+ if (generation === graftGeneration && input.isConnected) input.focus();
6467
+ }
6468
+ }
6469
+
6312
6470
  let graftMatchTimer = null;
6313
6471
  function graftMatchDebounced() { clearTimeout(graftMatchTimer); graftMatchTimer = setTimeout(graftMatch, 350); }
6314
6472
  async function graftMatch() {
@@ -6317,12 +6475,26 @@
6317
6475
  if (!glob) { el.replaceChildren(); return; }
6318
6476
  try {
6319
6477
  const { files } = await api('/api/graft/match', { method: 'POST', body: JSON.stringify({ glob }) });
6320
- if (!files || !files.length) { el.replaceChildren(); return; }
6478
+ // An older answer must not describe a newer path (a Choose folder or a keystroke since it was asked).
6479
+ if (graftState.ref.trim() !== glob || !el.isConnected) return;
6480
+ if (!files || !files.length) {
6481
+ // #2055: a Discover prefill whose folder holds no DLLs says where they usually are, rather than showing nothing.
6482
+ if (graftState.origin && graftState.kind === 'dlls') {
6483
+ graftFill(el, '<div class="graft-hint graft-no-match">No DLLs in this folder. Programs often keep them in a bin folder. Choose that folder, or paste its path.</div>');
6484
+ } else el.replaceChildren();
6485
+ return;
6486
+ }
6321
6487
  graftFill(el,
6322
6488
  `<div class="graft-matched"><div class="graft-matched-h">Matched assemblies (${files.length})</div>` +
6323
6489
  `<div class="graft-matched-f">${files.map(escapeHtml).join('<br>')}</div></div>` +
6324
6490
  (files.length > 1 ? '<div class="graft-hint">All assemblies load together so AWARE can resolve references across them.</div>' : ''));
6325
- } catch { el.replaceChildren(); }
6491
+ } catch {
6492
+ if (graftState.ref.trim() !== glob || !el.isConnected) return;
6493
+ // #2055: under a Discover prefill the note promises a list below — so a failed lookup says so instead of showing nothing.
6494
+ if (graftState.origin && graftState.kind === 'dlls') {
6495
+ graftFill(el, '<div class="graft-hint graft-no-match">FloLess couldn’t list the DLLs for this path. Check the path, or choose another folder.</div>');
6496
+ } else el.replaceChildren();
6497
+ }
6326
6498
  }
6327
6499
 
6328
6500
  function graftIntrospectingLabel(kind) {
@@ -6431,8 +6603,12 @@
6431
6603
  if (graftState.focusCheckRow) {
6432
6604
  graftState.focusCheckRow = false;
6433
6605
  document.getElementById('graft-check-row')?.focus();
6606
+ } else if (verifyButton) {
6607
+ verifyButton.focus();
6434
6608
  } else {
6435
- verifyButton?.focus();
6609
+ // #2128: the Inspect button that had focus was disabled while AWARE read the source, so focus fell to
6610
+ // the page. Land on the preview's first control, never the page behind.
6611
+ graftLandFocus();
6436
6612
  }
6437
6613
  graftState.onBack = graftRenderPicker;
6438
6614
  graftState.onPrimary = () => runGraftCommit(false);
@@ -6446,10 +6622,26 @@
6446
6622
  const candidates = Array.isArray(preview.probeCandidates) ? preview.probeCandidates : [];
6447
6623
  const needs = accounts.length
6448
6624
  ? `<dt>Needs an account</dt><dd>${accounts.map(escapeHtml).join(', ')}</dd>` : '';
6625
+ // #2116: a web service at a plain-http address (or with a port number) can't carry a check — AWARE pins
6626
+ // a check to a plain https address only. Say so, instead of offering commands AWARE would then refuse.
6627
+ // A tool that names no full web address at all (no servers in its spec) can't carry one either.
6628
+ // On an AWARE known to be older than the first that builds checks, say exactly what to update.
6629
+ const reason = !check && preview.probeUnavailable ? preview.probeUnavailable : null;
6630
+ const unavailableLine = !reason ? ''
6631
+ : reason.reason === 'aware-outdated'
6632
+ ? `None. Adding a connection check needs AWARE ${escapeHtml(reason.minimum)} or newer, and this computer has ${escapeHtml(reason.version)}. Update AWARE (choose Upgrade AWARE beside the AWARE version if it shows, or run npm i -g @aware-aeco/cli@latest in a terminal), then inspect the source again. You can still create the tool and use it without one.`
6633
+ : reason.reason === 'insecure-address'
6634
+ ? `None. A connection check works only with a secure https address (no port number), and this tool uses <code class="conn-code">${escapeHtml(reason.address)}</code>. You can still create the tool and use it without one.`
6635
+ : reason.reason === 'no-address'
6636
+ ? 'None. A connection check needs the full https address of the service, and this tool’s source doesn’t name one. You can still create the tool and use it without one.'
6637
+ : '';
6449
6638
  const checkLine = check
6450
6639
  ? `<dd>${escapeHtml(check.describe || check.command)}</dd>`
6451
- : `<dd>None yet${candidates.length ? '' : ' — no command can be used for one. You can still connect without a check.'}</dd>`;
6452
- const add = !check && candidates.length
6640
+ : unavailableLine
6641
+ ? `<dd class="graft-identity-prose">${unavailableLine}</dd>`
6642
+ : `<dd>None yet${candidates.length ? '' : ' — no command can be used for one. You can still connect without a check.'}</dd>`;
6643
+ // The button only where a check can really be added: never beside a sentence saying it can't.
6644
+ const add = !check && !unavailableLine && candidates.length
6453
6645
  ? '<button type="button" class="graft-verify-button" id="graft-add-check" data-command-id="shell.graft-add-check" aria-expanded="false" aria-controls="graft-check-picker">Add a connection check</button>'
6454
6646
  + '<div id="graft-check-picker" class="graft-check-picker" hidden></div>'
6455
6647
  : '';
@@ -6724,6 +6916,9 @@
6724
6916
  const body = { stagedRef: graftState.stagedRef };
6725
6917
  if (force) body.force = true;
6726
6918
  const res = await api('/api/graft/commit', { method: 'POST', body: JSON.stringify(body) });
6919
+ // #2128: the dialog no longer shows the review, so it no longer says "Review generated commands".
6920
+ document.getElementById('graft-title').textContent = 'Tool created';
6921
+ document.getElementById('graft-sub').textContent = 'You can use it in any workflow now.';
6727
6922
  graftFill(graftBodyEl(), `<div class="graft-success"><div class="gs-icon">⊕</div><div class="gs-msg" id="graft-success-msg" tabindex="-1">Tool created — now in the Tools library as <code>${escapeHtml(res.agentId)}</code>.</div></div>`);
6728
6923
  const nextSteps = graftSuccessActions(graftState.preview, res.agentId);
6729
6924
  if (nextSteps) graftBodyEl().append(nextSteps);
@@ -6767,10 +6962,85 @@
6767
6962
  }
6768
6963
 
6769
6964
  $graftBack.onclick = () => { graftGeneration += 1; clearGraftInstructorNote(); if (graftState.onBack) graftState.onBack(); };
6770
- $graftCancel.onclick = () => { graftGeneration += 1; closeGraftModal(); };
6965
+ // #2155: Cancel and Escape both put the person back where they opened Build a tool from — the Tools library
6966
+ // (reopened, on its Graft button) or the control that opened it — instead of dropping focus on the page.
6967
+ function returnFromGraft() {
6968
+ const opener = graftOpener;
6969
+ graftOpener = null;
6970
+ if (opener?.id === 'lib-graft' && typeof openLibrary === 'function') {
6971
+ openLibrary();
6972
+ // After the library's own tab switch, which moves focus to its search box on the next task.
6973
+ setTimeout(() => document.getElementById('lib-graft')?.focus(), 0);
6974
+ return;
6975
+ }
6976
+ if (opener?.isConnected && opener.getClientRects().length > 0) { opener.focus(); if (document.activeElement === opener) return; }
6977
+ // The opener is gone or hidden (the closed ≡ menu, a Discover dialog that closed to hand over): the dialog still
6978
+ // open underneath, if any, gets focus; otherwise the menu button, so focus never drops to the page.
6979
+ const underneath = Array.from(document.querySelectorAll('.modal-backdrop.show')).find((el) => el !== $graftModal);
6980
+ const candidates = underneath ? Array.from(underneath.querySelectorAll(
6981
+ 'button, input, select, textarea, a[href], summary, [contenteditable]:not([contenteditable="false"]), audio[controls], video[controls], [tabindex]',
6982
+ )).filter((el) => !el.disabled && el.getAttribute('tabindex') !== '-1' && !el.hidden && el.getClientRects().length > 0
6983
+ && getComputedStyle(el).visibility !== 'hidden') : [];
6984
+ // The first control that really takes focus; if none does, the menu button.
6985
+ for (const el of candidates) { el.focus(); if (document.activeElement === el) return; }
6986
+ document.getElementById('menu-btn')?.focus();
6987
+ }
6988
+ function dismissGraftModal() { graftGeneration += 1; closeGraftModal(); returnFromGraft(); }
6989
+ $graftCancel.onclick = dismissGraftModal;
6990
+ document.addEventListener('keydown', (e) => {
6991
+ if (e.key !== 'Escape' || !$graftModal.classList.contains('show')) return;
6992
+ // Another dialog or the reconnect / start-up screen shown over it owns Escape; so does a combobox inside it.
6993
+ if (graftCovered() || e.defaultPrevented) return;
6994
+ const active = document.activeElement;
6995
+ if (active && active !== document.body && !$graftModal.contains(active)
6996
+ && active.closest('[role="dialog"], [role="alertdialog"]')) return;
6997
+ // While a step cannot be cancelled (Cancel is disabled mid-commit), Escape does nothing either.
6998
+ if ($graftCancel.disabled) return;
6999
+ e.preventDefault();
7000
+ e.stopPropagation();
7001
+ dismissGraftModal();
7002
+ });
6771
7003
  $graftPrimary.onclick = () => { if (graftState.onPrimary) graftState.onPrimary(); };
6772
7004
  onBackdropDismiss($graftModal, closeGraftModal, () => !$graftCancel.disabled);
6773
7005
 
7006
+ // #2128: keep keyboard focus inside the open Build a tool dialog. Tab from the last control goes to the
7007
+ // first (Shift+Tab the other way), and a Tab pressed while focus is outside it (fallen to the page after
7008
+ // a rebuild) comes back in. Another dialog, or the reconnect / AWARE start-up screen, shown with it keeps
7009
+ // the keyboard — even when focus sits on the page rather than inside it.
7010
+ const graftFocusable = () => Array.from($graftModal.querySelectorAll(
7011
+ 'button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])',
7012
+ )).filter((el) => !el.hidden && el.getClientRects().length > 0);
7013
+ const GRAFT_COVERS = '#server-offline-overlay, #aware-bootstrap-overlay, .modal-backdrop.show';
7014
+ const graftCovered = () => Array.from(document.querySelectorAll(GRAFT_COVERS))
7015
+ .some((el) => el !== $graftModal && !el.hidden && el.getClientRects().length > 0);
7016
+ // Focus lands on the first control of the step's body (the source field, a check), never a footer button: Enter on
7017
+ // a focused Cancel would throw the inspected source away. A step with nothing to fill lands on its title, which
7018
+ // a screen reader announces and from which Tab reaches the step's controls.
7019
+ function graftLandFocus() {
7020
+ const first = graftFocusable().find((el) => el.closest('#graft-body'));
7021
+ if (first) first.focus(); else (document.getElementById('graft-title') ?? $graftDialog)?.focus();
7022
+ }
7023
+ document.addEventListener('keydown', (e) => {
7024
+ if (e.key !== 'Tab' || !$graftModal.classList.contains('show')) return;
7025
+ const active = document.activeElement;
7026
+ const otherDialog = active && active !== document.body && !$graftModal.contains(active)
7027
+ && active.closest(`${GRAFT_COVERS}, [role="dialog"], [role="alertdialog"]`);
7028
+ if (otherDialog || graftCovered()) return;
7029
+ const controls = graftFocusable();
7030
+ if (!controls.length) { e.preventDefault(); $graftDialog?.focus(); return; }
7031
+ const first = controls[0];
7032
+ const last = controls[controls.length - 1];
7033
+ const inside = $graftModal.contains(active);
7034
+ // From a focused non-control inside it (the title, the dialog, a success message) Shift+Tab would walk out.
7035
+ if (e.shiftKey && (!inside || active === first || !controls.includes(active))) {
7036
+ e.preventDefault();
7037
+ last.focus();
7038
+ } else if (!e.shiftKey && (!inside || active === last)) {
7039
+ e.preventDefault();
7040
+ first.focus();
7041
+ }
7042
+ });
7043
+
6774
7044
  // Secondary entry: "⊕ Graft new agent" inside the Agents Library modal.
6775
7045
  const $libGraft = document.getElementById('lib-graft');
6776
7046
  if ($libGraft) $libGraft.onclick = () => { hideModal($libModal); openGraftModal(); };
@@ -8655,11 +8925,17 @@
8655
8925
  // person saw nothing — the node stayed "running".)
8656
8926
  const msg = e && e.message ? e.message : String(e);
8657
8927
  // #1998: AWARE refused before anything started (an approval it will not run): no node is "running".
8658
- if (e && e.body && e.body.refusal) clearNodeStatus();
8659
- showToast((simulate ? 'Simulate failed' : 'Run failed') + ': ' + runFailureMessage(msg), 'warn');
8660
- appendNarration(simulate
8661
- ? `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.`
8662
- : `Run failed: ${escapeHtml(runFailureMessage(msg))}`);
8928
+ // #2123: so did FloLess's own ownership admission (archived, edited, re-published while waiting): `notRun`.
8929
+ const notRun = !!(e && e.body && e.body.notRun);
8930
+ if (e && e.body && (e.body.refusal || notRun)) clearNodeStatus();
8931
+ // A not-run answer is already a whole sentence ("…, so it didn’t run. …"); "Run failed:" would misstate it.
8932
+ // Nothing failed — it was declined with a reason — so the toast is informational, not a warning.
8933
+ showToast(notRun ? runFailureMessage(msg) : (simulate ? 'Simulate failed' : 'Run failed') + ': ' + runFailureMessage(msg), notRun ? 'info' : 'warn');
8934
+ appendNarration(notRun
8935
+ ? escapeHtml(runFailureMessage(msg))
8936
+ : simulate
8937
+ ? `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.`
8938
+ : `Run failed: ${escapeHtml(runFailureMessage(msg))}`);
8663
8939
  }
8664
8940
  }
8665
8941
  } finally {
@@ -8861,7 +9137,7 @@
8861
9137
  // have is the exact bug this reason exists to prevent.
8862
9138
  return "Couldn't check whether Node.js is installed — the check didn't finish, which usually means the machine was busy. Nothing is necessarily missing; try again.";
8863
9139
  case 'aware-version-required':
8864
- return 'This FloLess release needs AWARE 0.143.0 or newer. Update AWARE, then try again.';
9140
+ return 'This FloLess release needs AWARE 0.157.0 or newer. Update AWARE, then try again.';
8865
9141
  case 'offline':
8866
9142
  return 'No network connection was detected. Connect to the internet, then try again.';
8867
9143
  case 'smoke-failed':
@@ -9501,6 +9777,9 @@
9501
9777
  if (window.flolessPanels) window.flolessPanels.refreshData();
9502
9778
  } else if (m.type === 'routine-changed') {
9503
9779
  loadRoutinesData();
9780
+ } else if (m.type === 'agent-changed') {
9781
+ // #2062: an agent was paused, resumed, archived or restored; an open page of it shows the new state.
9782
+ window.flolessAgents?.refreshAgent?.(m.agentId);
9504
9783
  } else if (m.type === 'routine-run-started') {
9505
9784
  runningRoutines.add(m.id);
9506
9785
  if ($routinesModal.classList.contains('show')) renderRoutinesList();
@@ -9508,6 +9787,7 @@
9508
9787
  runningRoutines.delete(m.id);
9509
9788
  loadRoutinesData();
9510
9789
  if (window.flolessPanels) window.flolessPanels.refreshData(); // routine runs also refresh bindings
9790
+ window.flolessAgents?.refreshRuns?.(); // #2035: an open agent page shows the run its routine just started
9511
9791
  } else if (m.type === 'trigger-session-changed') {
9512
9792
  // A foreground live-run session (▶ Run on a streaming app) shares this SSE
9513
9793
  // event with background routines; its server-namespaced id routes it to the
@@ -9605,6 +9885,8 @@
9605
9885
  // state.favorites holds the template list so app.js's category-suggestion code
9606
9886
  // keeps working; the chip/star/library behaviour is overridden below.
9607
9887
  let agentCatalog = [];
9888
+ // C12 (#1337): installed tools AWARE could not read ({ id }), shown in the library by name instead of left out.
9889
+ let agentUnreadable = [];
9608
9890
 
9609
9891
  async function loadTemplates() {
9610
9892
  const { templates } = await api('/api/templates');
@@ -10103,6 +10385,144 @@
10103
10385
  // `chat-runtime-not-ready` so callers can show that reason instead of a generic failure. The
10104
10386
  // caller's `isCancelled()` (the surface closed, or the Request changed) stops it before anything is
10105
10387
  // started, with `chat-start-cancelled`, which callers drop silently.
10388
+ // ── #2061: Start in AI Chat on a project something else is changing ─────────────────────────────────────────────
10389
+ // Asked, never refused: wait (the start is tried again by itself — the same link and submission, so it can never send
10390
+ // twice), open the work holding the project, or stop it. The wait lives in this window only and says so.
10391
+ const REQUEST_START_BUSY_CODES = new Set(['chat-owner-busy', 'chat-project-run-busy', 'chat-project-knowledge-busy', 'chat-host-busy']);
10392
+ const REQUEST_START_WAIT_MS = 5000;
10393
+ const REQUEST_START_WAIT_CAP_MS = 30 * 60 * 1000;
10394
+ // #2106: the remedy every waiter gives once organizing has held the project for the whole wait (server copy:
10395
+ // knowledgeStuckRemedy in project-wait-clock.ts).
10396
+ const KNOWLEDGE_STUCK_REMEDY_START = 'If organizing has stopped, restart FloLess — that clears an organize that already finished. If it still shows as organizing after that, open a terminal outside FloLess (Claude Code or Codex) and ask it to check and recover the stuck knowledge organize for this project, then start this request again.';
10397
+ const requestStartWaits = new Map();
10398
+
10399
+ function busyChoiceDialog({ title, sub, actions, focusId }) {
10400
+ return new Promise((resolve) => {
10401
+ const previous = document.activeElement;
10402
+ const backdrop = document.createElement('div');
10403
+ backdrop.className = 'modal-backdrop show req-busy-dialog';
10404
+ backdrop.setAttribute('role', 'alertdialog'); backdrop.setAttribute('aria-modal', 'true'); backdrop.setAttribute('aria-labelledby', 'req-busy-title');
10405
+ const modal = document.createElement('div'); modal.className = 'modal';
10406
+ const head = document.createElement('div'); head.className = 'modal-title'; head.id = 'req-busy-title'; head.textContent = title;
10407
+ const body = document.createElement('div'); body.className = 'modal-sub'; body.textContent = sub;
10408
+ const row = document.createElement('div'); row.className = 'modal-actions';
10409
+ const finish = (value) => { backdrop.remove(); document.removeEventListener('keydown', onKey, true); if (previous?.isConnected) previous.focus(); resolve(value); };
10410
+ const onKey = (event) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); finish(null); } };
10411
+ let focusTarget = null;
10412
+ for (const action of actions) {
10413
+ const control = document.createElement('button');
10414
+ control.type = 'button'; control.textContent = action.label; control.dataset.commandId = action.commandId;
10415
+ if (action.className) control.className = action.className;
10416
+ control.onclick = () => finish(action.id);
10417
+ if (action.commandId === focusId) focusTarget = control;
10418
+ row.append(control);
10419
+ }
10420
+ modal.append(head, body, row); backdrop.append(modal);
10421
+ backdrop.addEventListener('mousedown', (event) => { if (event.target === backdrop) finish(null); });
10422
+ document.addEventListener('keydown', onKey, true);
10423
+ document.body.append(backdrop);
10424
+ (focusTarget || row.querySelector('button'))?.focus();
10425
+ });
10426
+ }
10427
+
10428
+ /**
10429
+ * #2104: the design program a holder is using, by the name a person knows it ("Revit"), or `fallback` when FloLess
10430
+ * cannot name it (SketchUp/AutoCAD/ArchiCAD share one claim, and older records carry no key).
10431
+ */
10432
+ function hostProgramLabel(holder, fallback) {
10433
+ const kind = String(holder?.hostKey || '').split(':', 1)[0];
10434
+ return ({ tekla: 'Tekla', revit: 'Revit', rhino: 'Rhino' })[kind] || fallback;
10435
+ }
10436
+
10437
+ async function askRequestStartBusy(request, provider, holder) {
10438
+ // #2106: FloLess organizing this project's knowledge — wait or open its Knowledge step; never stopped from here.
10439
+ if (holder.kind === 'knowledge') {
10440
+ const actions = [{ id: null, label: 'Cancel', commandId: 'shell.requests-start-busy-cancel' }];
10441
+ if (holder.projectId) actions.push({ id: 'open', label: 'Open it', commandId: 'shell.requests-start-busy-open' });
10442
+ actions.push({ id: 'wait', label: 'Wait and start when it’s free', commandId: 'shell.requests-start-busy-wait', className: 'primary' });
10443
+ const choice = await busyChoiceDialog({
10444
+ title: 'FloLess is organizing this project’s knowledge right now',
10445
+ sub: 'Nothing was started. Wait, and FloLess starts this request in AI Chat by itself when organizing finishes (keep FloLess open), or open the project’s Knowledge step to see it.',
10446
+ actions, focusId: 'shell.requests-start-busy-wait',
10447
+ });
10448
+ if (choice === 'open') await openProjectWaitHolder({ projectWait: { holder } });
10449
+ else if (choice === 'wait') {
10450
+ waitToStartRequestChat(request, provider, 'knowledge organizing', 'the project', {
10451
+ waiting: 'Waiting for FloLess to finish organizing this project’s knowledge. This request starts in AI Chat by itself when it’s done.',
10452
+ toast: 'Waiting for FloLess to finish organizing this project’s knowledge — this request starts in AI Chat by itself.',
10453
+ cap: `FloLess has been organizing this project’s knowledge for over 30 minutes, so this request was not started. ${KNOWLEDGE_STUCK_REMEDY_START}`,
10454
+ started: 'Organizing finished — this request started in AI Chat.',
10455
+ });
10456
+ }
10457
+ return;
10458
+ }
10459
+ const who = holder.kind === 'chat' ? `“${holder.title || 'another AI Chat conversation'}”` : (holder.title || 'another background request');
10460
+ const canAct = holder.kind === 'chat' ? Boolean(holder.owner && holder.chatId) : Boolean(holder.requestId);
10461
+ const actions = [{ id: null, label: 'Cancel', commandId: 'shell.requests-start-busy-cancel' }];
10462
+ if (canAct) actions.push({ id: 'open', label: 'Open it', commandId: 'shell.requests-start-busy-open' });
10463
+ if (canAct) actions.push({ id: 'stop', label: 'Stop it', commandId: 'shell.requests-start-busy-stop', className: 'req-busy-stop' });
10464
+ actions.push({ id: 'wait', label: 'Wait and start when it’s free', commandId: 'shell.requests-start-busy-wait', className: 'primary' });
10465
+ const choice = await busyChoiceDialog({
10466
+ // A holder of the same design program (reason 'host') is not changing this project — say what it is doing.
10467
+ title: holder.reason === 'host' ? `${who} is using ${hostProgramLabel(holder, 'the same design program')} on this computer right now` : `${who} is changing this project right now`,
10468
+ sub: `Nothing was started. Wait, and FloLess starts this request in AI Chat by itself when ${holder.reason === 'host' ? hostProgramLabel(holder, 'the design program') : 'the project'} is free (keep FloLess open), or open or stop that work.`,
10469
+ actions, focusId: 'shell.requests-start-busy-wait',
10470
+ });
10471
+ if (choice === 'open') {
10472
+ if (holder.kind === 'chat') await openProjectWaitHolder({ projectWait: { holder } });
10473
+ else await openRequests(holder.requestId);
10474
+ return;
10475
+ }
10476
+ if (choice === 'stop') {
10477
+ try {
10478
+ if (holder.kind === 'chat') {
10479
+ await api(`/api/chat/conversations/${encodeURIComponent(holder.chatId)}/stop`, { method: 'POST', body: JSON.stringify({ owner: holder.owner, expectTurnId: holder.turnId || undefined }) });
10480
+ } else {
10481
+ await api(`/api/requests/${encodeURIComponent(holder.requestId)}/run/stop`, { method: 'POST', body: JSON.stringify(holder.leaseId ? { expectLeaseId: holder.leaseId } : {}) });
10482
+ }
10483
+ } catch (error) {
10484
+ if (error?.body?.code !== 'stop-stale') console.warn('[requests] could not stop the work holding the project:', error);
10485
+ showToast(error?.body?.code === 'stop-stale' ? 'That work had already finished, so nothing was stopped.' : 'FloLess couldn’t stop that work. This request waits for it instead.', 'warn');
10486
+ }
10487
+ }
10488
+ if (choice === 'stop' || choice === 'wait') waitToStartRequestChat(request, provider, who, holder.reason === 'host' ? hostProgramLabel(holder, 'the design program') : 'the project');
10489
+ }
10490
+
10491
+ // `copy` (#2106) replaces the sentences for work that is not "someone changing the project" — knowledge organizing.
10492
+ function waitToStartRequestChat(request, provider, who, what = 'the project', copy = null) {
10493
+ if (requestStartWaits.has(request.id)) return;
10494
+ const since = Date.now();
10495
+ const status = () => document.getElementById('requests-action-status');
10496
+ const say = (text) => { const node = status(); if (node) node.textContent = text; };
10497
+ say(copy?.waiting ?? `Waiting for ${who} to finish. This request starts in AI Chat by itself when ${what} is free.`);
10498
+ showToast(copy?.toast ?? `Waiting for ${who} to finish — this request starts in AI Chat by itself.`, 'ok');
10499
+ const tick = async () => {
10500
+ if (!requestStartWaits.has(request.id)) return;
10501
+ if (Date.now() - since >= REQUEST_START_WAIT_CAP_MS) {
10502
+ requestStartWaits.delete(request.id);
10503
+ showToast(copy?.cap ?? `Still waiting for ${who} after 30 minutes, so this request was not started. Start it again when that work is done.`, 'warn', { persistent: true });
10504
+ return;
10505
+ }
10506
+ try {
10507
+ await startRequestChatWithSetup(request.id, provider, 'start');
10508
+ requestStartWaits.delete(request.id);
10509
+ say('');
10510
+ showToast(copy?.started ?? `${what === 'the project' ? 'The project' : what === 'the design program' ? 'The design program' : what} is free — this request started in AI Chat.`, 'ok');
10511
+ await loadRequests(); renderRequests();
10512
+ } catch (error) {
10513
+ if (REQUEST_START_BUSY_CODES.has(String(error?.code || ''))) { requestStartWaits.set(request.id, setTimeout(tick, REQUEST_START_WAIT_MS)); return; }
10514
+ requestStartWaits.delete(request.id);
10515
+ // Refused for another reason once the project was free: say why, exactly as the other start surfaces do.
10516
+ const notReady = error?.code === 'chat-runtime-not-ready';
10517
+ const explained = notReady ? '' : chatStartErrorText(error);
10518
+ if (notReady) showToast(error.message, 'warn');
10519
+ else reportChatStartErr(error);
10520
+ say(notReady ? error.message : explained || `Couldn’t start ${requestLabel(request)} in AI Chat. Try again.`);
10521
+ }
10522
+ };
10523
+ requestStartWaits.set(request.id, setTimeout(tick, REQUEST_START_WAIT_MS));
10524
+ }
10525
+
10106
10526
  async function startRequestChatWithSetup(requestId, provider, mode, { onSetup, isCancelled = () => false } = {}) {
10107
10527
  if (typeof window.flolessChat?.startRequest !== 'function') throw new Error('AI Chat is still starting. Try again in a moment.');
10108
10528
  if (mode === 'start') {
@@ -10307,13 +10727,109 @@
10307
10727
  </div>`;
10308
10728
  }
10309
10729
 
10730
+ /**
10731
+ * #2061: a background request waiting for other work to finish changing its project, or one that stopped waiting
10732
+ * and needs the person. The server writes both sentences' facts; the row names who holds the project and opens it.
10733
+ */
10734
+ function projectWaitHtml(r, commandInstance) {
10735
+ const wait = r.projectWait;
10736
+ if (!wait || (wait.state !== 'waiting' && wait.state !== 'needs-you')) return '';
10737
+ const holder = wait.holder || {};
10738
+ if (holder.kind === 'knowledge') return knowledgeWaitHtml(r, wait, holder, commandInstance);
10739
+ const title = String(holder.title || (holder.kind === 'chat' ? 'another AI Chat conversation' : 'another background request'));
10740
+ // A request's name carries its own words in quotes ("the background request “…”"); shortening it must not lose the
10741
+ // closing quote, or the sentence after it reads as part of the request's words. A name that is not cut is left as is.
10742
+ const cut = title.length > 48 ? `${title.slice(0, 45).trimEnd()}…` : null;
10743
+ const quoteLost = cut !== null && title.endsWith('”') && (cut.match(/“/g) || []).length > (cut.match(/”/g) || []).length;
10744
+ const short = cut === null ? title : quoteLost ? `${cut}”` : cut;
10745
+ const who = holder.kind === 'chat' ? `“${short}”` : short;
10746
+ const target = String(wait.target?.label || 'this project');
10747
+ const canOpen = holder.kind === 'chat' ? Boolean(holder.chatId && holder.owner) : Boolean(holder.requestId);
10748
+ const open = canOpen
10749
+ ? `<button type="button" class="req-wait-open" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-wait-open#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}"${title !== short ? ` data-tip="${escapeAttr(title)}"` : ''}>${holder.kind === 'chat' ? 'Open that conversation' : 'Go to that request'}</button>`
10750
+ : '';
10751
+ const waiting = wait.state === 'waiting';
10752
+ // A holder that stopped to ask a question keeps its folder until it is answered or stopped — say so, or the wait
10753
+ // reads as if it will end by itself.
10754
+ // #2103: a holder of the same design program on this computer is not changing this project — say what it is doing.
10755
+ const host = holder.reason === 'host';
10756
+ // #2103: nothing is known to hold it yet — FloLess's own check of the design program stayed busy, and is tried again.
10757
+ const checking = holder.kind === 'check';
10758
+ const note = waiting
10759
+ ? (checking
10760
+ ? 'FloLess couldn’t yet check whether the design program this request uses is free. It keeps checking, and this starts by itself when the program is free.'
10761
+ : holder.needsAnswer
10762
+ ? `Waiting for ${who}, which needs your answer before ${host ? hostProgramLabel(holder, 'the design program') : target} is free. Answer it or stop it, and this starts by itself.`
10763
+ : host
10764
+ ? `Waiting for ${who}, which is using ${hostProgramLabel(holder, 'the same design program')} on this computer right now. This starts by itself when it’s done.`
10765
+ : `Waiting for ${who} to finish changing ${target}. This starts by itself when it’s done.`)
10766
+ : String(wait.message || `This request stopped waiting for ${target}. Press ▶ to run it again.`);
10767
+ return `
10768
+ <div class="req-run-status req-wait" role="status" aria-live="polite">
10769
+ <div class="req-run-head">
10770
+ <span class="req-run-badge req-run-badge-${waiting ? 'muted' : 'warn'}">${waiting ? 'Waiting' : 'Needs you'}</span>
10771
+ </div>
10772
+ <p class="req-run-note">${escapeHtml(note)}</p>
10773
+ ${open ? `<div class="req-wait-actions">${open}</div>` : ''}
10774
+ </div>`;
10775
+ }
10776
+
10777
+ /** #2106: a background request waiting for FloLess to finish organizing its project's knowledge (no Stop: never a run). */
10778
+ function knowledgeWaitHtml(r, wait, holder, commandInstance) {
10779
+ const target = String(wait.target?.label || 'this project');
10780
+ const waiting = wait.state === 'waiting';
10781
+ const note = waiting
10782
+ ? `Waiting for FloLess to finish organizing ${target}’s knowledge. This starts by itself when it’s done.`
10783
+ : String(wait.message || `This request stopped waiting for ${target}. Press ▶ to run it again.`);
10784
+ const open = holder.projectId
10785
+ ? `<button type="button" class="req-wait-open" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-wait-open#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}">Open its Knowledge step</button>`
10786
+ : '';
10787
+ return `
10788
+ <div class="req-run-status req-wait" role="status" aria-live="polite">
10789
+ <div class="req-run-head">
10790
+ <span class="req-run-badge req-run-badge-${waiting ? 'muted' : 'warn'}">${waiting ? 'Waiting' : 'Needs you'}</span>
10791
+ </div>
10792
+ <p class="req-run-note">${escapeHtml(note)}</p>
10793
+ ${open ? `<div class="req-wait-actions">${open}</div>` : ''}
10794
+ </div>`;
10795
+ }
10796
+
10797
+ /** #2106: a project's Knowledge step. A missing Workspaces bridge is said, never a silent no-op. */
10798
+ async function openKnowledgeStepOf(projectId) {
10799
+ const open = window.flolessWorkspaces?.openKnowledgeStep;
10800
+ if (typeof open !== 'function') throw new Error('FloLess couldn’t open that project’s Knowledge step. Open it from Workspaces.');
10801
+ await open(projectId);
10802
+ }
10803
+
10804
+ /** #2061: show the work a waiting request is waiting for — its conversation, or its row in Requests. */
10805
+ async function openProjectWaitHolder(req) {
10806
+ const holder = req?.projectWait?.holder;
10807
+ if (!holder) return;
10808
+ if (holder.kind === 'knowledge') {
10809
+ // #2106: the project's Knowledge step, where its organizing shows.
10810
+ try { await openKnowledgeStepOf(holder.projectId); }
10811
+ catch (error) { showToast(error?.message || 'FloLess couldn’t open that project’s Knowledge step. Open it from Workspaces.', 'warn'); }
10812
+ return;
10813
+ }
10814
+ if (holder.kind === 'chat' && holder.chatId && holder.owner && typeof window.flolessChat?.openConversationIn === 'function') {
10815
+ const opened = await window.flolessChat.openConversationIn({ owner: holder.owner }, holder.chatId).catch(() => false);
10816
+ if (!opened) showToast('FloLess couldn’t open that conversation. It may have finished or moved; check AI Chat.', 'warn');
10817
+ return;
10818
+ }
10819
+ if (holder.kind !== 'chat' && holder.requestId) await openRequests(holder.requestId);
10820
+ }
10821
+
10310
10822
  // Start a run. `runtime` is the §E4 per-run override — omitted, the server resolves the default.
10311
10823
  async function runRequestHeadless(req, runtime) {
10312
10824
  try {
10313
10825
  const res = await api(`/api/requests/${encodeURIComponent(req.id)}/run`, {
10314
10826
  method: 'POST', body: JSON.stringify(runtime ? { runtime } : {}),
10315
10827
  });
10316
- showToast(`Running in ${runtimeLabel((res.run && res.run.runtime) || runtime)} — the row updates as it goes`, 'ok');
10828
+ // #2061: the project is busy; the request waits and starts by itself. The row says who it is waiting for.
10829
+ // #2103: a wait for the design program (Tekla, Revit…) another piece of work is using says so, not "the project".
10830
+ if (res && res.waiting && res.projectWait?.holder?.kind === 'check') showToast('FloLess is checking whether the design program is free — this request starts by itself when it is.', 'ok');
10831
+ else if (res && res.waiting) showToast(`Waiting for ${res.projectWait?.holder?.reason === 'host' ? hostProgramLabel(res.projectWait.holder, 'the design program') : 'the project'} to be free — this request starts by itself. The row shows what it’s waiting for.`, 'ok');
10832
+ else showToast(`Running in ${runtimeLabel((res.run && res.run.runtime) || runtime)} — the row updates as it goes`, 'ok');
10317
10833
  await loadRequests();
10318
10834
  renderRequests();
10319
10835
  return res;
@@ -10355,12 +10871,22 @@
10355
10871
  }
10356
10872
 
10357
10873
  async function stopRequestRun(req) {
10874
+ // #2061: "Stop waiting" names the wait shown, so it can never stop the run that wait just started.
10875
+ const waiting = req.projectWait?.state === 'waiting' && !requestHasActiveRun(req);
10358
10876
  try {
10359
- await api(`/api/requests/${encodeURIComponent(req.id)}/run/stop`, { method: 'POST' });
10877
+ await api(`/api/requests/${encodeURIComponent(req.id)}/run/stop`, { method: 'POST',
10878
+ ...(waiting ? { body: JSON.stringify({ waitId: req.projectWait.waitId }) } : {}) });
10360
10879
  await loadRequests();
10361
10880
  renderRequests();
10362
10881
  focusRequestContinuation(req.id);
10363
- } catch (e) { reportErr(e); }
10882
+ } catch (e) {
10883
+ if (e?.body?.code === 'stop-stale') {
10884
+ showToast('This request had already stopped waiting, so nothing was stopped. The list now shows what it is doing.', 'ok');
10885
+ await loadRequests().catch(() => {}); renderRequests();
10886
+ return;
10887
+ }
10888
+ reportErr(e);
10889
+ }
10364
10890
  }
10365
10891
 
10366
10892
  /**
@@ -10831,6 +11357,197 @@
10831
11357
  let wsRequestScope = null;
10832
11358
  let requestScopeAll = false; // the scope tab: false = what's open, true = every queued request
10833
11359
  let requestQuery = '';
11360
+ // #2060: Queued is the work waiting; Done lists the Requests that left the queue (finished, or cleared), so each one's
11361
+ // conversation stays reachable — and a background run's record with it. Nothing in Done starts, re-runs or approves.
11362
+ let requestViewMode = 'queued';
11363
+ let doneRequests = null; // null: not read yet
11364
+ let doneRequestsError = null;
11365
+ let doneRequestsUnreadable = 0;
11366
+ async function loadDoneRequests() {
11367
+ try {
11368
+ const body = await api('/api/requests/done', { signal: AbortSignal.timeout(30_000) });
11369
+ doneRequests = Array.isArray(body?.requests) ? body.requests : [];
11370
+ doneRequestsUnreadable = Number(body?.unreadable) || 0;
11371
+ doneRequestsError = null;
11372
+ } catch (error) {
11373
+ console.warn('floless: could not read the done requests', error);
11374
+ doneRequestsError = 'FloLess couldn’t read the done requests.';
11375
+ }
11376
+ }
11377
+ async function setRequestViewMode(mode) {
11378
+ const next = mode === 'done' ? 'done' : 'queued';
11379
+ if (next === requestViewMode) return;
11380
+ requestViewMode = next;
11381
+ renderRequests();
11382
+ if (next === 'done') { await loadDoneRequests(); if (requestViewMode === 'done') renderRequests(); }
11383
+ }
11384
+ // What a background run's outcome reads as in Done. Leaving the queue is not success: only `succeeded` says Finished.
11385
+ const DONE_RUN_WORDS = {
11386
+ succeeded: 'Finished', answered: 'Answered', 'needs-you': 'Stopped to ask you something', 'exited-unresolved': 'Ended without finishing',
11387
+ 'contract-violation': 'Ended with a result FloLess couldn’t confirm', stopped: 'Stopped', interrupted: 'Interrupted', failed: 'Didn’t finish',
11388
+ queued: 'Still starting', running: 'Still running',
11389
+ };
11390
+ function doneRequestSearchText(r) {
11391
+ return [requestLabel(r), requestOwnerName(r), r.appId, r.project, r.summary].filter(Boolean).join(' ');
11392
+ }
11393
+ function doneRequestRowHtml(r, query) {
11394
+ const label = requestLabel(r);
11395
+ const owner = requestOwnerName(r);
11396
+ const left = r.removedAt ? new Date(r.removedAt) : null;
11397
+ const leftLabel = left && !isNaN(left) ? nowStamp(left) : '';
11398
+ const commandInstance = `${label}${owner ? ` for ${owner}` : ''}${leftLabel ? `, done ${leftLabel}` : ''}`;
11399
+ const badgeCls = r.type === 'guide' || r.type === 'new-workflow' || r.type === 'use-template' ? 'req-type' : 'req-type req-type-tweak';
11400
+ const run = r.run;
11401
+ const runWords = run ? (DONE_RUN_WORDS[run.state] || String(run.state || '').replace(/-/g, ' ')) : '';
11402
+ const reported = run ? (run.answer || run.question || run.lastOutput || '') : '';
11403
+ const runHtml = run
11404
+ ? `<p class="req-run-note req-done-run">Background run · ${escapeHtml(runtimeLabel(run.runtime))} · ${escapeHtml(runWords)}</p>`
11405
+ + `<details class="req-technical"><summary data-command-id="shell.requests-done-report#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}">What the run reported</summary><div class="req-technical-body">${escapeHtml(reported || 'The run didn’t report anything.')}</div></details>`
11406
+ : '';
11407
+ const link = r.chatConversation || null;
11408
+ const unreadable = link?.chatState === 'unreadable';
11409
+ const linked = Boolean(link?.chatId) && !unreadable;
11410
+ const provider = preferredChatProvider();
11411
+ const inScope = Boolean(r.project || r.workflowId) && requestMatchesChatScope(r);
11412
+ const chatLabel = `${label}${owner ? ` for ${owner}` : ''}`;
11413
+ let action = '';
11414
+ if (provider && inScope) {
11415
+ action = `<button class="req-chat-action" data-done-chat="${linked ? 'open' : 'discuss'}" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-done-discuss#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="${linked ? 'Open' : 'Discuss'} ${escapeAttr(chatLabel)} in AI Chat" data-tip="${linked ? 'Open this request’s conversation in AI Chat' : 'Start a conversation about this request in AI Chat. Nothing runs.'}">${linked ? 'Open AI Chat' : 'Discuss in AI Chat'}</button>`;
11416
+ } else if (provider && (r.project || r.workflowId)) {
11417
+ action = `<span class="req-chat-elsewhere" data-tip="Open ${escapeAttr(owner)} to open this request’s conversation">Open ${escapeHtml(owner)} for AI Chat</span>`;
11418
+ } else if (!provider) {
11419
+ action = '<span class="req-chat-elsewhere" data-tip="AI Chat needs Claude or Codex on this computer">AI Chat isn’t available</span>';
11420
+ }
11421
+ // "Unreadable" covers a damaged saved file but also a passing read failure, so Discuss stays offered (it may simply
11422
+ // work now) and the row says where a damaged conversation is repaired: AI Chat's list, where it can be discarded.
11423
+ const unreadableNote = unreadable
11424
+ ? '<p class="req-run-note req-done-run">FloLess couldn’t open this request’s conversation just now. Try Discuss in AI Chat. If its saved file is damaged, AI Chat’s conversation list (☷) shows it with a way to discard it. After that, Discuss adds this request to the conversation open in AI Chat if it is idle, or starts a new one.</p>'
11425
+ : '';
11426
+ return `
11427
+ <div class="req-item req-done-item" data-id="${escapeAttr(r.id)}">
11428
+ <div class="req-info">
11429
+ <div class="req-head"><span class="${badgeCls}">${escapeHtml(label)}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, query)}</span>` : ''}${leftLabel ? `<span class="req-time" data-tip="Left the queue ${escapeAttr(leftLabel)}">${escapeHtml(leftLabel)}</span>` : ''}</div>
11430
+ <div class="req-instruction">${highlightQuery(r.summary || '', query) || 'This request kept no words to show.'}</div>
11431
+ ${runHtml}${unreadableNote}
11432
+ </div>
11433
+ <div class="req-actions">${action}</div>
11434
+ </div>`;
11435
+ }
11436
+ /** Requests → Done: what left the queue, newest first. Read-only apart from opening or discussing a conversation. */
11437
+ function renderDoneRequests($list) {
11438
+ const $clear = document.getElementById('requests-clear');
11439
+ const $copy = document.getElementById('requests-copy');
11440
+ const $search = document.getElementById('requests-search');
11441
+ const $guidance = document.getElementById('requests-guidance');
11442
+ if ($clear) $clear.hidden = true;
11443
+ if ($copy) $copy.hidden = true;
11444
+ if ($guidance) $guidance.hidden = true;
11445
+ const all = doneRequests || [];
11446
+ if ($search) {
11447
+ $search.hidden = all.length < 2;
11448
+ if ($search.hidden && requestQuery) { requestQuery = ''; $search.value = ''; }
11449
+ }
11450
+ const query = requestQuery.trim();
11451
+ const scope = activeRequestScope();
11452
+ const inScope = visibleRequests(all, scope, '', doneRequestSearchText);
11453
+ const shown = visibleRequests(all, requestScopeAll ? null : scope, query, doneRequestSearchText);
11454
+ const $scope = document.getElementById('requests-scope');
11455
+ const $here = document.getElementById('requests-scope-here');
11456
+ const $all = document.getElementById('requests-scope-all');
11457
+ if ($scope) $scope.hidden = !scope || all.length === 0;
11458
+ if (scope && $here && $all) {
11459
+ const kind = scope.kind === 'project' ? 'project' : 'workflow';
11460
+ $here.innerHTML = `<span class="req-scope-name">${escapeHtml(scope.label)}</span><span class="req-scope-n">· ${inScope.length} done</span>`;
11461
+ $here.setAttribute('data-tip', `Only what was done for the ${kind} you have open — ${scope.label}`);
11462
+ $all.innerHTML = `<span class="req-scope-name">All requests</span><span class="req-scope-n">· ${all.length} done</span>`;
11463
+ $all.setAttribute('data-tip', 'Every done request, including other projects and workflows');
11464
+ $here.classList.toggle('active', !requestScopeAll);
11465
+ $here.setAttribute('aria-selected', String(!requestScopeAll));
11466
+ $all.classList.toggle('active', requestScopeAll);
11467
+ $all.setAttribute('aria-selected', String(requestScopeAll));
11468
+ }
11469
+ const skipped = doneRequestsUnreadable
11470
+ ? `<p class="req-run-note req-done-skipped">${doneRequestsUnreadable} earlier request${doneRequestsUnreadable === 1 ? '' : 's'} couldn’t be read and ${doneRequestsUnreadable === 1 ? 'isn’t' : 'aren’t'} shown.</p>`
11471
+ : '';
11472
+ if (doneRequests === null && doneRequestsError) {
11473
+ paintRequestList($list, `<div class="empty-state">${escapeHtml(doneRequestsError)} <button type="button" class="req-showall" data-done-retry>Try again</button></div>`, query);
11474
+ } else if (doneRequests === null) {
11475
+ paintRequestList($list, '<div class="empty-state">Reading the done requests…</div>', query);
11476
+ } else if (shown.length === 0) {
11477
+ const msg = all.length === 0
11478
+ ? 'Nothing done yet. Requests appear here once they leave the queue.'
11479
+ : query
11480
+ ? `No done request matches “${escapeHtml(query)}”.${!requestScopeAll && inScope.length < all.length ? ' Try All to search everything.' : ''}`
11481
+ : `Nothing done for ${escapeHtml(scope ? scope.label : 'this')} yet — ${all.length} done elsewhere. <button type="button" class="req-showall">Show all</button>`;
11482
+ paintRequestList($list, `<div class="empty-state">${msg}</div>${skipped}`, query);
11483
+ } else {
11484
+ paintRequestList($list, `${doneRequestsError ? `<p class="req-run-note req-done-skipped">${escapeHtml(doneRequestsError)} Showing what was read earlier.</p>` : ''}${shown.map((r) => doneRequestRowHtml(r, query)).join('')}${skipped}`, query);
11485
+ }
11486
+ const $showAll = $list.querySelector('.req-showall:not([data-done-retry])');
11487
+ if ($showAll) $showAll.onclick = () => setRequestScopeAll(true);
11488
+ const $retry = $list.querySelector('[data-done-retry]');
11489
+ if ($retry) $retry.onclick = async () => { await loadDoneRequests(); renderRequests(); };
11490
+ $list.querySelectorAll('[data-done-chat]').forEach((button) => {
11491
+ button.onclick = async () => {
11492
+ const request = (doneRequests || []).find((candidate) => candidate?.id === button.dataset.id);
11493
+ const provider = preferredChatProvider();
11494
+ if (!request || !provider) return;
11495
+ const original = button.textContent;
11496
+ button.disabled = true;
11497
+ button.setAttribute('aria-busy', 'true');
11498
+ button.textContent = 'Opening…';
11499
+ const actionStatus = document.getElementById('requests-action-status');
11500
+ if (actionStatus) actionStatus.textContent = `Opening ${requestLabel(request)} for ${requestOwnerName(request)} in AI Chat.`;
11501
+ const requestsModal = document.getElementById('requests-modal');
11502
+ try {
11503
+ // Discuss, never Start: the server refuses to run a Request that left the queue.
11504
+ await startRequestChatWithSetup(request.id, provider, 'discuss', {
11505
+ isCancelled: () => !requestsModal?.classList.contains('show') || requestViewMode !== 'done',
11506
+ // FloLess is installing its own copy of this AI first (#1607): say so, as the queued rows do.
11507
+ onSetup: (status) => {
11508
+ const notice = window.flolessChat?.runtimeNotice?.(provider, status);
11509
+ if (actionStatus) actionStatus.textContent = notice?.body || `FloLess is setting up ${runtimeLabel(provider)} before it opens this request.`;
11510
+ },
11511
+ });
11512
+ closeRequests();
11513
+ } catch (error) {
11514
+ if (error?.code === 'chat-start-cancelled') return;
11515
+ // The same refusal handling as the queued rows' start surface (request-chat-start-eligibility.test.ts).
11516
+ const notReady = error?.code === 'chat-runtime-not-ready';
11517
+ const explained = notReady ? '' : chatStartErrorText(error);
11518
+ if (notReady) showToast(error.message, 'warn');
11519
+ else reportChatStartErr(error);
11520
+ if (actionStatus) actionStatus.textContent = notReady
11521
+ ? error.message
11522
+ : explained || `Couldn’t open ${requestLabel(request)} in AI Chat. Try again.`;
11523
+ if (!button.isConnected) return;
11524
+ button.disabled = false;
11525
+ button.removeAttribute('aria-busy');
11526
+ button.textContent = original;
11527
+ button.focus();
11528
+ }
11529
+ };
11530
+ });
11531
+ }
11532
+ /** The Queued | Done switch, the sub-line and the footer note follow the view. */
11533
+ function paintRequestViewChrome() {
11534
+ const done = requestViewMode === 'done';
11535
+ for (const [id, mode] of [['requests-view-queued', 'queued'], ['requests-view-done', 'done']]) {
11536
+ const tab = document.getElementById(id);
11537
+ if (!tab) continue;
11538
+ tab.classList.toggle('active', requestViewMode === mode);
11539
+ tab.setAttribute('aria-selected', String(requestViewMode === mode));
11540
+ tab.tabIndex = requestViewMode === mode ? 0 : -1;
11541
+ }
11542
+ const $queued = document.getElementById('requests-view-queued');
11543
+ if ($queued) $queued.textContent = pendingRequests.length ? `Queued (${pendingRequests.length})` : 'Queued';
11544
+ const $sub = document.getElementById('requests-sub');
11545
+ if ($sub) $sub.textContent = done
11546
+ ? 'Requests that left the queue in the last 30 days. Open their conversation or discuss them in AI Chat. Nothing here runs again.'
11547
+ : 'Start queued work in AI Chat or run it in the background with your terminal AI.';
11548
+ const $note = document.getElementById('requests-done-note');
11549
+ if ($note) $note.hidden = !done;
11550
+ }
10834
11551
  let previousRequestCount = 0;
10835
11552
  let previousRequestIds = null;
10836
11553
  let reqPulseTimer = null;
@@ -10863,6 +11580,11 @@
10863
11580
  const { requests, chatPublications = [] } = await api('/api/requests', { signal: AbortSignal.timeout(90_000) });
10864
11581
  reconcileActiveInstructorRuns(requests, chatPublications);
10865
11582
  pendingRequests = requests;
11583
+ // A Request leaving the queue arrives in Done: re-read it while Done is what the open window shows.
11584
+ // Not awaited: the queue's own update never waits on the Done read.
11585
+ if (requestViewMode === 'done' && document.getElementById('requests-modal')?.classList.contains('show')) {
11586
+ void loadDoneRequests().then(() => { if (requestViewMode === 'done') renderRequests(); });
11587
+ }
10866
11588
  const nextPublishedChatIds = new Set(chatPublications.map((publication) => publication?.chatId).filter(Boolean));
10867
11589
  const newlyPublishedHere = publishedAnswerChatIds !== null && chatPublications.some((publication) => {
10868
11590
  if (!publication?.chatId || publishedAnswerChatIds.has(publication.chatId)) return false;
@@ -11822,6 +12544,8 @@
11822
12544
  // A press still held inside the list: paint once it is released (see holdRequestListRepaints).
11823
12545
  // Everything waits, not only the rows, so the bulk actions keep acting on what is on screen.
11824
12546
  if ($list.__requestsHeld) { $list.__requestsOwed = true; return; }
12547
+ paintRequestViewChrome();
12548
+ if (requestViewMode === 'done') { renderDoneRequests($list); return; }
11825
12549
  // Search is pointless over an empty queue, and over a single request it is just clutter.
11826
12550
  // Drop the query WITH the box, and before anything is filtered by it: a hidden filter still
11827
12551
  // filtering is how a list ends up inexplicably empty (the last two requests clear while a
@@ -11948,7 +12672,10 @@
11948
12672
  // generic sentence is reserved for the types with no second surface, where "no recovery" is
11949
12673
  // unambiguous — and the drawing read keeps saying what it already says, correctly.
11950
12674
  const ownRecoverySurface = r.type === 'revision-read';
11951
- const inFlight = !!run && (run.state === 'queued' || run.state === 'running');
12675
+ // #2061: waiting for another piece of work to finish changing this request's project. It holds the row like a run
12676
+ // (■ stops the wait), and nothing has started yet.
12677
+ const projectWaiting = !settledRevision && r.projectWait?.state === 'waiting';
12678
+ const inFlight = (!!run && (run.state === 'queued' || run.state === 'running')) || projectWaiting;
11952
12679
  const desktopClaimed = !!(desktopHandoffs && desktopHandoffs.claim);
11953
12680
  const lifecycleOwned = r.type === 'knowledge-organize';
11954
12681
  const canClear = requestCanClear(r);
@@ -11959,6 +12686,8 @@
11959
12686
  const discardQuestion = requestHasDiscardQuestion(r);
11960
12687
  const del = lifecycleOwned
11961
12688
  ? '<span class="req-lifecycle" data-tip="This clears itself when your terminal AI finishes or fails the organize">finishing in your terminal</span>'
12689
+ : projectWaiting
12690
+ ? '<span class="req-lifecycle" data-tip="Stop waiting first if you want to clear this request">waiting</span>'
11962
12691
  : inFlight || desktopClaimed
11963
12692
  ? '<span class="req-lifecycle" data-tip="Stop the run if you need to pause it. Clear stays unavailable until the saved session is continued and finished">running</span>'
11964
12693
  : !canClear && r.clearState === 'session-saved'
@@ -11978,7 +12707,9 @@
11978
12707
  const canRunNow = headlessReady() && r.canRun && (!chatExecutionOwner || chatExecutionOwner === 'discussion')
11979
12708
  && (r.type !== 'revision-read' || r.status === 'pending')
11980
12709
  && !revisionReadHasTerminalOwner(r) && !inFlight && !desktopHandoffs && !resumeCommand;
11981
- const runBtn = inFlight
12710
+ const runBtn = projectWaiting
12711
+ ? `<button class="req-stop" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-stop-waiting#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" data-tip="Stop waiting" aria-label="Stop waiting">■</button>`
12712
+ : inFlight
11982
12713
  ? `<button class="req-stop" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-stop#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" data-tip="Stop this run" aria-label="Stop this run">■</button>`
11983
12714
  : canRunNow && !filterGuide
11984
12715
  ? r.preparationRetryable
@@ -12012,6 +12743,7 @@
12012
12743
  ? `<div class="req-instruction req-summary">${highlightQuery(r.instructorContext.subject || 'Drawing Filter AI request', normalizedRequestQuery)}</div><p class="req-run-note">${escapeHtml(filterGuideRequestNote(r))}</p><details class="req-technical"><summary data-command-id="shell.requests-technical#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}">Show detailed instructions</summary><div class="req-technical-body">${highlightQuery(instructionFor(r), normalizedRequestQuery)}</div></details>`
12013
12744
  : `<div class="req-instruction">${highlightQuery(instructionFor(r), normalizedRequestQuery) || 'This request has no instructions to send. Remove it and create the request again.'}</div>`}
12014
12745
  ${r.snapshots && r.snapshots.length ? `<div class="req-thumbs">${r.snapshots.map((sp, i) => { const pdf = /\.pdf$/i.test(String(sp)); return `<button type="button" class="req-thumb" data-id="${escapeAttr(r.id)}" data-n="${i}" aria-label="View ${pdf ? 'PDF' : 'screenshot'} ${i + 1}">${pdf ? '<span class="req-thumb-pdf">PDF</span>' : `<img src="/api/requests/${encodeURIComponent(r.id)}/snapshot/${i}" alt="">`}</button>`; }).join('')}</div>` : ''}
12746
+ ${settledRevision ? '' : projectWaitHtml(r, commandInstance)}
12015
12747
  ${runStatusHtml(run, resumeCommand, desktopHandoffs, r.id, commandInstance, ownRecoverySurface,
12016
12748
  filterGuide
12017
12749
  ? (r.instructorContext.commandId === 'filter.ask-ai-change' ? 'change' : 'question') : null, r.filterAiNotStarted === true)}
@@ -12081,6 +12813,12 @@
12081
12813
  closeRequests();
12082
12814
  } catch (error) {
12083
12815
  if (error?.code === 'chat-start-cancelled') return;
12816
+ // #2061: the project is busy — ask (wait and start by itself / open it / stop it), never only "failed".
12817
+ if (starting && REQUEST_START_BUSY_CODES.has(String(error?.code || '')) && error?.holder) {
12818
+ if (actionStatus) actionStatus.textContent = '';
12819
+ void askRequestStartBusy(request, provider, error.holder);
12820
+ return;
12821
+ }
12084
12822
  const notReady = error?.code === 'chat-runtime-not-ready';
12085
12823
  const explained = notReady ? '' : chatStartErrorText(error);
12086
12824
  if (notReady) showToast(error.message, 'warn');
@@ -12109,6 +12847,12 @@
12109
12847
  if (r) void runRequestHeadless(r);
12110
12848
  };
12111
12849
  });
12850
+ $list.querySelectorAll('.req-wait-open').forEach((b) => {
12851
+ b.onclick = () => {
12852
+ const r = pendingRequests.find((x) => x.id === b.dataset.id);
12853
+ if (r) void openProjectWaitHolder(r);
12854
+ };
12855
+ });
12112
12856
  $list.querySelectorAll('.req-stop').forEach((b) => {
12113
12857
  b.onclick = () => {
12114
12858
  const r = pendingRequests.find((x) => x.id === b.dataset.id);
@@ -12301,6 +13045,7 @@
12301
13045
  // previous visit would silently answer a different question than the one just asked.
12302
13046
  requestScopeAll = false;
12303
13047
  requestQuery = '';
13048
+ requestViewMode = 'queued';
12304
13049
  const $search = document.getElementById('requests-search');
12305
13050
  if ($search) $search.value = '';
12306
13051
  const $requestsModal = document.getElementById('requests-modal');
@@ -12456,29 +13201,37 @@
12456
13201
 
12457
13202
  // ── Agents library: real installed agents + their commands ───────────────────
12458
13203
  async function loadAgentCatalog() {
12459
- const { agents } = await api('/api/agents');
13204
+ const { agents, unreadable } = await api('/api/agents');
12460
13205
  agentCatalog = agents;
13206
+ agentUnreadable = Array.isArray(unreadable) ? unreadable.filter((row) => row && typeof row.id === 'string') : [];
12461
13207
  const $ac = document.getElementById('agents-count');
12462
- if ($ac) $ac.textContent = agents.length;
13208
+ // A damaged tool is still installed: the count matches the cards the library shows.
13209
+ if ($ac) $ac.textContent = agents.length + agentUnreadable.length;
12463
13210
  refreshAgentNotes();
12464
13211
  }
12465
13212
 
12466
13213
  // `focusId` (a connection check's "Update" offer, #1986): open on top of the dialog that asked, showing just that
12467
13214
  // tool on the Installed tab, where its own Update button lives — the update itself stays the library's.
13215
+ // `{ tab: 'available' }` (the Guide's install suggestion, #2046): the tool is not installed yet, so show it on the
13216
+ // Available tab, where its Install button lives — the install itself stays the library's.
12468
13217
  let libOpener = null; // the offer button that opened the library on top of its dialog, to return focus to
12469
- openLibrary = function openLibraryReal(focusId) {
13218
+ openLibrary = function openLibraryReal(focusId, opts) {
12470
13219
  const focus = typeof focusId === 'string' ? focusId : '';
13220
+ const toAvailable = !!focus && opts?.tab === 'available';
12471
13221
  $libModal.classList.toggle('lib-front', !!focus);
12472
13222
  libOpener = focus ? document.activeElement : null;
12473
13223
  $libSearch.value = '';
12474
- if ($libAvailSearch) $libAvailSearch.value = '';
12475
- switchLibTab('installed'); // always open on Installed (the primary job)
12476
- $libSearch.value = focus;
13224
+ if ($libAvailSearch) $libAvailSearch.value = toAvailable ? focus : '';
13225
+ switchLibTab(toAvailable ? 'available' : 'installed'); // Installed is the primary job, unless asked otherwise
13226
+ if (!toAvailable) $libSearch.value = focus;
12477
13227
  renderLibrary();
12478
13228
  $libModal.classList.add('show');
12479
13229
  // Focus moves into the library NOW (not on the tab switch's next tick), so even an immediate Escape lands on the
12480
13230
  // library's own handler instead of the dialog underneath.
12481
- if (focus) $libSearch.focus();
13231
+ // Focus moves to the open tab's search. On Available, an AWARE too old to list tools hides that search: renderAvailable
13232
+ // then hands focus on to its "Update AWARE" button, whether it knew that already or learns it when the reply lands.
13233
+ if (focus) (toAvailable && $libAvailSearch ? $libAvailSearch : $libSearch).focus();
13234
+ if (toAvailable && $libAvailSearch?.hidden) availableFocusFallback();
12482
13235
  if (!agentCatalog.length) loadAgentCatalog().then(renderLibrary).catch(reportErr);
12483
13236
  // Load the registry catalog too, so the Installed tab can flag outdated agents
12484
13237
  // with an "Update" button (and the Available tab is instant when switched to).
@@ -12540,6 +13293,18 @@
12540
13293
  renderLibrary = function renderLibraryReal() {
12541
13294
  const q = ($libSearch.value || '').toLowerCase().trim();
12542
13295
  const items = agentCatalog.filter((a) => !q || a.id.toLowerCase().includes(q) || (a.kind || '').toLowerCase().includes(q));
13296
+ const damaged = agentUnreadable.filter((a) => !q || a.id.toLowerCase().includes(q));
13297
+ // C12 (#1337): a tool AWARE could not read is named here with what to do, never silently left out of the list.
13298
+ const damagedHtml = damaged.map((a) => `
13299
+ <div class="lib-card lib-card-unreadable" data-agent-unreadable="${escapeAttr(a.id)}">
13300
+ <div class="lib-item">
13301
+ <div class="info">
13302
+ <div class="name">${escapeHtml(a.id)}</div>
13303
+ <div class="meta">Can’t be read</div>
13304
+ </div>
13305
+ </div>
13306
+ <p class="lib-update-error"><strong>FloLess couldn’t read this tool.</strong> Its files are damaged or incomplete, so workflows that use it can’t run. Install it again from the Available tab, or ask AI Chat to reinstall it.</p>
13307
+ </div>`).join('');
12543
13308
  // Each agent is ONE grid cell: the card header + its (lazy) command list live
12544
13309
  // in the same `.lib-card`, so expanding nests the commands directly under the
12545
13310
  // picked card instead of scattering them into a neighbouring grid slot.
@@ -12574,7 +13339,8 @@
12574
13339
  ${failureHtml}
12575
13340
  <div class="lib-commands" id="cmds-${id}" hidden></div>
12576
13341
  </div>`;
12577
- }).join('') || '<div class="empty-state">No tools match.</div>';
13342
+ }).join('');
13343
+ $libList.innerHTML = (damagedHtml + $libList.innerHTML) || '<div class="empty-state">No tools match.</div>';
12578
13344
  $libList.querySelectorAll('[data-expand]').forEach((btn) => {
12579
13345
  btn.onclick = () => expandAgent(btn.dataset.expand);
12580
13346
  });
@@ -12694,9 +13460,16 @@
12694
13460
  </div>`;
12695
13461
  }
12696
13462
 
13463
+ // The Available search can be hidden while it holds focus (#2049): focus then goes to a visible control in the same
13464
+ // tab, so it never sits on a hidden input outside the library's own Escape handling.
13465
+ function availableFocusFallback() {
13466
+ (document.getElementById('lib-avail-update') || $libTabs.querySelector('[data-libtab="available"]'))?.focus();
13467
+ }
13468
+
12697
13469
  function renderAvailable() {
12698
13470
  // Degradation (i): CLI predates `agent catalog` entirely — hide search, show notice.
12699
13471
  if (availableUnsupported) {
13472
+ const searchHadFocus = document.activeElement === $libAvailSearch;
12700
13473
  $libAvailSearch.hidden = true;
12701
13474
  $libAvailList.innerHTML =
12702
13475
  '<div class="empty-state">Browsing available tools needs AWARE 0.54 or later.' +
@@ -12709,6 +13482,7 @@
12709
13482
  else showToast('Update AWARE (@aware-aeco/cli) to 0.54+ to browse available tools', 'info');
12710
13483
  };
12711
13484
  $libAvailCount.textContent = '';
13485
+ if (searchHadFocus) availableFocusFallback();
12712
13486
  return;
12713
13487
  }
12714
13488
  $libAvailSearch.hidden = false;
@@ -13593,6 +14367,12 @@
13593
14367
  let editWorkflows = []; // app list for the workflow <select>, cached per edit-open
13594
14368
  let editTriggerSource = null; // picked workflow's triggerSource (null = not trigger-eligible)
13595
14369
  let editRoutineMode = 'schedule'; // 'schedule' | 'trigger' — chosen kind in the edit form
14370
+ let editTarget = 'workflow'; // #2035: 'workflow' | 'agent' — what the routine being edited runs
14371
+ let editAgents = []; // #2035: this folder's agents for the Agent <select>, cached per edit-open
14372
+ let editAgentAi = 'claude'; // #2035: the AI an agent routine starts (Claude | Codex), like the Run sheet's choice
14373
+ let editReturnFocus = null; // #2035: where focus goes back when the editor was opened from an agent's page
14374
+ const routineAgentNames = new Map(); // #2035: agentId → name, for "Agent · <name>" rows
14375
+ const routineAgentRunState = new Map(); // #2035: routine id → how its last agent run is going, read from that run
13596
14376
  const runningRoutines = new Set(); // ids executing now (SSE start → ended)
13597
14377
 
13598
14378
  function isCompleteReportRoutine(r) {
@@ -13843,13 +14623,30 @@
13843
14623
  function lastRunTip(r) {
13844
14624
  if (!r.lastRun) return 'Never run yet';
13845
14625
  const lr = r.lastRun;
14626
+ // #2062: a fire missed while FloLess was closed — the server's sentence says it all ("Missed — FloLess wasn’t running at …").
14627
+ if (lr.status === 'skipped' && lr.missed && lr.reason) return lr.reason;
14628
+ // #2035: an agent routine only starts the agent; how that run went is the agent run's own record.
14629
+ if (r.agent) {
14630
+ const when = absTime(lr.at);
14631
+ if (lr.status === 'starting') return `Starting the agent · ${when}`;
14632
+ if (lr.status === 'started') return `Started the agent · ${when}${routineAgentRunState.get(r.id) ? ` · ${routineAgentRunState.get(r.id)}` : ''}`;
14633
+ // A skip reason already begins "Skipped — …" (the server's sentence), so it is shown as is.
14634
+ if (lr.status === 'skipped') return `${lr.reason || 'Skipped'} · ${when}`;
14635
+ return `Didn’t start${lr.reason ? ' — ' + lr.reason : ''} · ${when}`;
14636
+ }
13846
14637
  const dur = lr.durationMs != null ? ` · ${(lr.durationMs / 1000).toFixed(1)} s` : '';
13847
14638
  // A run that finished on a stated assumption says so with its outcome, never only in the report.
13848
14639
  const warnings = Array.isArray(lr.warnings) ? lr.warnings.filter((warning) => typeof warning === 'string' && warning) : [];
13849
14640
  // #1998: a run made under an approval carried forward to newer tool versions says so, in AWARE's words.
13850
14641
  const carried = lr.approval && lr.approval.origin === 'successor'
13851
14642
  ? `\nApproval carried over to a newer tool version. AWARE's record: ${lr.approval.label || 'carried forward'}` : '';
13852
- return `Last run ${lr.status}${lr.reason ? ' — ' + lr.reason : ''}${warnings.length ? ' — ' + warnings.join(' ') : ''} · ${absTime(lr.at)}${dur}${carried}`;
14643
+ const bridgeWarnings = Array.isArray(lr.bridgeWarnings) ? lr.bridgeWarnings.filter((w) => w && typeof w === 'object'
14644
+ && ['bridge-too-old', 'bridge-too-new', 'declaration-invalid'].includes(w.status)
14645
+ && typeof w.agent === 'string' && w.agent.trim() && typeof w.name === 'string' && w.name.trim()
14646
+ && typeof w.detail === 'string' && w.detail.trim() && (w.via === null || typeof w.via === 'string')
14647
+ && Array.isArray(w.choices) && w.choices.every((choice) => typeof choice === 'string')) : [];
14648
+ const bridge = bridgeWarnings.map((w) => `\n${w.status === 'declaration-invalid' ? 'Ran with an invalid bridge declaration' : 'Ran with a bridge mismatch'}: ${w.via ? w.via + ' → ' : ''}${w.name}. ${w.detail}`).join('');
14649
+ return `Last run ${lr.status}${lr.reason ? ' — ' + lr.reason : ''}${warnings.length ? ' — ' + warnings.join(' ') : ''} · ${absTime(lr.at)}${dur}${carried}${bridge}`;
13853
14650
  }
13854
14651
 
13855
14652
  // ── Trigger-routine row helpers ─────────────────────────────────────────────
@@ -13924,6 +14721,7 @@
13924
14721
  completeReportDiscoveryEpoch.set(id, (completeReportDiscoveryEpoch.get(id) || 0) + 1);
13925
14722
  }
13926
14723
  for (const id of live) void refreshRoutineReportDiscovery(id);
14724
+ if (routinesData.some((r) => r.agent)) void refreshRoutineAgents();
13927
14725
  if ($routinesModal.classList.contains('show')) renderRoutinesList();
13928
14726
  // Last, and on its own: a landing repaint that throws must not skip the reconcile above.
13929
14727
  if (wfLanding && chipsChanged) {
@@ -13932,6 +14730,49 @@
13932
14730
  } catch (err) { console.warn('Routines could not be loaded', err); }
13933
14731
  }
13934
14732
 
14733
+ /** #2035: one line on how an agent run is going, from the run the routine started (never a copied count). */
14734
+ function agentRunStateText(run) {
14735
+ if (!run) return '';
14736
+ const lives = run.targets.map((t) => t.live);
14737
+ const declined = run.targets.reduce((sum, t) => sum + (t.declines ? t.declines.list.filter((d) => d.state === 'declined').length + t.declines.moreDeclined : 0), 0);
14738
+ const tail = declined ? ` · ${declined} step${declined === 1 ? '' : 's'} declined — see Questions for you on the Agents page` : '';
14739
+ // #2122: every live state has a deliberate summary; only a run whose every part finished (or was skipped up front)
14740
+ // says Done, and a state this list does not know yet reads as needing a look — never as Done.
14741
+ // Most urgent first: the person is being asked something, then work still going, then work that stopped short.
14742
+ if (lives.some((l) => l === 'waiting-for-you')) return `Waiting for your approval on the Agents page${tail}`;
14743
+ if (lives.some((l) => l === 'working' || l === 'starting' || l === 'waiting')) return `Running${tail}`;
14744
+ // #2105: 'needs-you' — it waited the full time for busy work and stopped without changing anything.
14745
+ if (lives.some((l) => l === 'failed' || l === 'failed-reply' || l === 'uncertain' || l === 'needs-recovery' || l === 'needs-you' || l === 'unreadable')) return `Needs a look on the Agents page${tail}`;
14746
+ if (lives.some((l) => l === 'stopped')) return `Stopped before it finished${tail}`;
14747
+ if (lives.some((l) => l === 'archived')) return `Its conversation was archived${tail}`;
14748
+ if (lives.some((l) => l === 'stale')) return `Belongs to an earlier workspace folder${tail}`;
14749
+ if (!lives.every((l) => l === 'done' || l === 'skipped')) return `Needs a look on the Agents page${tail}`;
14750
+ if (lives.length && lives.every((l) => l === 'skipped')) return `Skipped — see the Agents page for why${tail}`;
14751
+ if (lives.some((l) => l === 'skipped')) return `Done, with some parts skipped — see the Agents page${tail}`;
14752
+ return `Done${tail}`;
14753
+ }
14754
+
14755
+ /** #2122: only a run still going — or still asking the person — can change on its own, so only those are asked about again. */
14756
+ function agentRunStillGoing(summary) {
14757
+ return summary === '' || /^(Running|Waiting for your approval)/.test(summary);
14758
+ }
14759
+
14760
+ async function refreshRoutineAgents() {
14761
+ const agentsApi = window.flolessAgents;
14762
+ if (!agentsApi?.list) return;
14763
+ try {
14764
+ for (const agent of await agentsApi.list()) routineAgentNames.set(agent.agentId, agent.name);
14765
+ } catch (err) { console.warn('Agent names for routines could not be loaded', err); }
14766
+ await Promise.all(routinesData.filter((r) => r.agent && r.lastRun?.agentRunId).map(async (r) => {
14767
+ try {
14768
+ const body = await agentsApi.runs(r.agent.agentId);
14769
+ const run = (body.runs || []).find((row) => row.runId === r.lastRun.agentRunId);
14770
+ routineAgentRunState.set(r.id, run ? agentRunStateText(run) : '');
14771
+ } catch { routineAgentRunState.delete(r.id); }
14772
+ }));
14773
+ if ($routinesModal.classList.contains('show')) renderRoutinesList();
14774
+ }
14775
+
13935
14776
  // SSE: a trigger routine's live session snapshot changed. Update the in-memory
13936
14777
  // row and re-render; flash the row when its fired count climbs (a real event).
13937
14778
  function applyTriggerSnapshot(id, snapshot) {
@@ -13947,7 +14788,7 @@
13947
14788
  const viewerOpenForApp = currentId === r.workflow && $reportModal.classList.contains('show') && !reportRunning;
13948
14789
  if (fired && viewerOpenForApp) {
13949
14790
  showTriggerCollecting();
13950
- } else if (viewerOpenForApp && (snapshot.state === 'error' || snapshot.state === 'stopped') && $reportOverlay.querySelector('.spinner')) {
14791
+ } else if (viewerOpenForApp && (snapshot.state === 'error' || snapshot.state === 'stopped') && $reportOverlay.querySelector('.flo-run, .spinner')) {
13951
14792
  // The session ended before this fire produced a report — don't spin forever.
13952
14793
  // Fall back to the last report if we have one, else an idle prompt.
13953
14794
  clearTriggerCollecting();
@@ -14027,13 +14868,21 @@
14027
14868
  // A trigger fired (new selection) but its report is still computing on the host.
14028
14869
  // Show a spinner over the viewer — the previous report dims behind the overlay —
14029
14870
  // until applyTriggerReport paints the fresh one. Built with DOM nodes (no
14030
- // innerHTML); reuses the same .spinner the manual run overlay uses.
14871
+ // innerHTML); shows the same running Flo as the manual run overlay.
14031
14872
  function showTriggerCollecting() {
14032
14873
  $reportOverlay.hidden = false;
14033
14874
  $reportOverlay.replaceChildren();
14034
- const sp = mkEl('div', 'spinner');
14035
14875
  const msg = mkEl('div', null, 'New selection — collecting report…');
14036
- $reportOverlay.append(sp, msg);
14876
+ $reportOverlay.append(runningFlo(), msg);
14877
+ }
14878
+
14879
+ // #2079: while a workflow runs for you, Flo works over the viewer, hat on, its light looping the ring. Plain
14880
+ // loading (a report section, a 3D view, a live session starting) keeps the plain .spinner ring.
14881
+ function runningFlo() {
14882
+ const host = mkEl('div', 'flo-run');
14883
+ if (typeof floAvatar === 'function') floAvatar(host, { size: 40, mood: 'working', hat: true });
14884
+ else host.classList.add('spinner');
14885
+ return host;
14037
14886
  }
14038
14887
 
14039
14888
  // The trigger session errored/stopped while a "collecting…" spinner was up (a
@@ -14083,10 +14932,18 @@
14083
14932
  // never a dead end. Other failures are recoverable; the server returns them
14084
14933
  // in-band, so a failed start is a viewer message + toast, not a console fault.
14085
14934
  const blocked = !!(e.body && e.body.blocked);
14935
+ // #2123: FloLess declined before anything started (archived, edited, re-published) and said why in plain words.
14936
+ const notRun = !!(e.body && e.body.notRun && typeof e.body.error === 'string');
14086
14937
  $reportShare.hidden = true; // the overlay is the primary content — nothing to share
14087
14938
  $reportOverlay.hidden = false;
14088
14939
  $reportOverlay.replaceChildren();
14089
- if (blocked) {
14940
+ if (notRun) {
14941
+ // The server's plain sentence, through the same mapping every other run answer gets.
14942
+ const sentence = runFailureMessage(e.body.error);
14943
+ $reportOverlay.append(mkEl('div', null, sentence));
14944
+ $reportSub.textContent = 'Nothing ran, so no report was made.';
14945
+ showToast(sentence, 'info');
14946
+ } else if (blocked) {
14090
14947
  $reportOverlay.append(
14091
14948
  mkEl('div', null, 'One live model, one watcher — a session is already watching this host.'),
14092
14949
  mkEl('div', null, 'To run here, stop it first: open ⏱ Routines and disable the watcher, then click ▶ Run workflow.'),
@@ -14191,6 +15048,17 @@
14191
15048
  }
14192
15049
  }
14193
15050
 
15051
+ // #2062: a routine whose agent holds it says so where its next run time would be. Its own switch is untouched and
15052
+ // keeps working; a routine switched off or broken says that instead (its own state comes first).
15053
+ function routineHoldText(r) {
15054
+ if (!r.agent || !r.enabled || r.broken) return null;
15055
+ if (r.agentHold === 'paused') return { label: 'paused with the agent',
15056
+ tip: 'Its agent is paused, so this routine doesn’t start it. Resume the agent on the Agents page and this routine runs on its schedule again. Its own switch is unchanged.' };
15057
+ if (r.agentHold === 'archived') return { label: 'paused — agent archived',
15058
+ tip: 'Its agent is archived, so this routine doesn’t start it. Restore the agent on the Agents page and this routine runs on its schedule again.' };
15059
+ return null;
15060
+ }
15061
+
14194
15062
  function renderRoutinesList() {
14195
15063
  const $list = document.getElementById('routines-list');
14196
15064
  const $quota = document.getElementById('rtn-quota');
@@ -14239,11 +15107,15 @@
14239
15107
  } else {
14240
15108
  statusEl = running
14241
15109
  ? '<span class="rtn-spinner" data-tip="Running now…"></span>'
14242
- : `<span class="rtn-status ${escapeAttr(r.lastRun ? r.lastRun.status : '')}" data-tip="${escapeAttr(lastRunTip(r))}"></span>`;
15110
+ : `<span class="rtn-status ${escapeAttr(r.lastRun ? ({ started: 'ok', starting: '' }[r.lastRun.status] ?? r.lastRun.status) : '')}" data-tip="${escapeAttr(lastRunTip(r))}"></span>`;
14243
15111
  nextTip = r.nextFireAt ? `Next run: ${absTime(r.nextFireAt)}` : (r.broken ? r.broken.reason : r.enabled ? 'Not scheduled' : 'Disabled');
14244
15112
  nextLabel = !r.enabled ? 'disabled' : r.broken ? 'broken' : relTime(r.nextFireAt);
15113
+ const held = routineHoldText(r);
15114
+ if (held) { nextLabel = held.label; nextTip = held.tip; }
14245
15115
  }
14246
15116
  const whenText = isTrigger ? triggerWhenText(r) : scheduleText(r.schedule);
15117
+ // #2035: an agent routine names its agent, not a workflow id.
15118
+ const whatText = r.agent ? `Agent · ${routineAgentNames.get(r.agent.agentId) || 'agent'}` : r.workflow;
14247
15119
  const toggleTip = isTrigger ? (r.enabled ? 'Stop listening' : 'Start listening') : `${r.enabled ? 'Disable' : 'Enable'} this routine`;
14248
15120
  // One sentence for all three surfaces a blocked ▶ speaks through: the hover tip, the `?`
14249
15121
  // band (which reads data-blocked-reason), and the toast when a click still reaches the
@@ -14262,7 +15134,7 @@
14262
15134
  <div class="rtn-item ${isTrigger ? 'trigger ' : ''}${r.enabled ? '' : 'disabled'} ${running ? 'running' : ''}" data-id="${escapeAttr(r.id)}">
14263
15135
  <div class="rtn-main">
14264
15136
  <div class="rtn-name">${escapeHtml(r.name)}</div>
14265
- <div class="rtn-sub"><span class="rtn-wf">${escapeHtml(r.workflow)}</span><span class="rtn-dot">·</span><span>${escapeHtml(whenText)}</span>${broken}</div>
15137
+ <div class="rtn-sub"><span class="rtn-wf">${escapeHtml(whatText)}</span><span class="rtn-dot">·</span><span>${escapeHtml(whenText)}</span>${broken}</div>
14266
15138
  ${reportLine}
14267
15139
  </div>
14268
15140
  <div class="rtn-meta"${isTrigger ? ' aria-live="polite" aria-atomic="true"' : ''}>
@@ -14276,6 +15148,7 @@
14276
15148
  </label>
14277
15149
  ${isTrigger ? '' : `<button class="rtn-act" data-rtn-run="${escapeAttr(r.id)}" data-command-id="shell.routine-run#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.name)}" aria-label="Run ${escapeAttr(r.name)} now" data-tip="${escapeAttr(runTip)}"${running ? ` disabled data-blocked-reason="${escapeAttr(RTN_ALREADY_RUNNING)}"` : ''}>▶</button>`}
14278
15150
  ${isCompleteReport && discovery?.report && !discovery.checking ? `<button class="rtn-act rtn-report-view" data-rtn-report="${escapeAttr(r.id)}" data-command-id="shell.routine-view-report#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.name)}" aria-label="View saved report for ${escapeAttr(r.name)}" data-tip="View the verified, read-only report">View report</button>` : ''}
15151
+ ${r.agent ? `<button class="rtn-act" data-rtn-agent="${escapeAttr(r.agent.agentId)}" data-command-id="shell.routine-open-agent#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.name)}" aria-label="Open the agent that ${escapeAttr(r.name)} runs" data-tip="Open this agent and its runs on the Agents page">Agent</button>` : ''}
14279
15152
  <button class="rtn-act" data-rtn-edit="${escapeAttr(r.id)}" data-tip="Edit">✎</button>
14280
15153
  <button class="rtn-act rtn-del-act" data-rtn-del="${escapeAttr(r.id)}" data-tip="Delete">×</button>
14281
15154
  </div>
@@ -14285,6 +15158,7 @@
14285
15158
  $list.querySelectorAll('[data-rtn-run]').forEach((b) => { b.onclick = () => runRoutineNow(b.dataset.rtnRun); });
14286
15159
  $list.querySelectorAll('[data-rtn-report]').forEach((b) => { b.onclick = () => { void viewScheduledCompleteReport(b.dataset.rtnReport); }; });
14287
15160
  $list.querySelectorAll('[data-rtn-edit]').forEach((b) => { b.onclick = () => openRoutineEdit(b.dataset.rtnEdit); });
15161
+ $list.querySelectorAll('[data-rtn-agent]').forEach((b) => { b.onclick = () => { hideModal($routinesModal); void window.flolessAgents?.open?.(b.dataset.rtnAgent); }; });
14288
15162
  $list.querySelectorAll('[data-rtn-del]').forEach((b) => { b.onclick = () => deleteRoutineUi(b.dataset.rtnDel); });
14289
15163
  }
14290
15164
 
@@ -14299,7 +15173,9 @@
14299
15173
  await api(`/api/routines/${encodeURIComponent(id)}/run`, { method: 'POST' });
14300
15174
  runningRoutines.add(id); // optimistic, for immediate feedback; SSE confirms it moments later
14301
15175
  renderRoutinesList();
14302
- showToast('Routine started', 'ok');
15176
+ // #2062: a hand run starts a paused agent; its schedule stays held. Queued, not yet started — the row says how it went.
15177
+ const held = routinesData.find((r) => r.id === id)?.agentHold === 'paused';
15178
+ showToast(held ? 'Routine queued by hand. Its agent is paused, so its schedule stays off.' : 'Routine started', 'ok');
14303
15179
  } catch (e) {
14304
15180
  // 409 with running:true — the server refused because this routine is already queued or mid-run,
14305
15181
  // and nothing was started, so never say it was. Keyed on the FLAG rather than the status: this
@@ -14352,6 +15228,89 @@
14352
15228
  } catch (e) { reportErr(e); }
14353
15229
  }
14354
15230
 
15231
+ /** #2035: what the routine runs — a workflow, or an agent (always on a schedule, no inputs). */
15232
+ function setRoutineTarget(target) {
15233
+ editTarget = target === 'agent' ? 'agent' : 'workflow';
15234
+ const agent = editTarget === 'agent';
15235
+ document.querySelectorAll('#rtn-target-field .rtn-mode-btn').forEach((b) => {
15236
+ const on = b.dataset.target === editTarget;
15237
+ b.classList.toggle('active', on);
15238
+ b.setAttribute('aria-pressed', on ? 'true' : 'false');
15239
+ });
15240
+ document.getElementById('rtn-workflow-field').hidden = agent;
15241
+ document.getElementById('rtn-agent-field').hidden = !agent;
15242
+ document.getElementById('rtn-edit-sub').textContent = agent
15243
+ ? 'Pick an agent and when it should run. Nobody watches a scheduled run, so anything that would ask you is declined and listed for you afterwards.'
15244
+ : 'Pick a workflow and when it should run.';
15245
+ if (agent) {
15246
+ document.getElementById('rtn-inputs-field').hidden = true;
15247
+ document.getElementById('rtn-mode-field').hidden = true;
15248
+ setRoutineMode('schedule');
15249
+ paintRoutineAgentNote();
15250
+ } else {
15251
+ // Back to the workflow: what it already loaded comes straight back (#2035 QA), nothing is fetched again.
15252
+ document.getElementById('rtn-inputs-field').hidden = !document.getElementById('rtn-inputs').children.length;
15253
+ applyRoutineModeAvailability();
15254
+ }
15255
+ }
15256
+
15257
+ function setRoutineAgentAi(ai) {
15258
+ editAgentAi = ai === 'codex' ? 'codex' : 'claude';
15259
+ document.querySelectorAll('#rtn-agent-ai .rtn-mode-btn').forEach((b) => {
15260
+ const on = b.dataset.ai === editAgentAi;
15261
+ b.classList.toggle('active', on);
15262
+ b.setAttribute('aria-pressed', on ? 'true' : 'false');
15263
+ });
15264
+ }
15265
+
15266
+ /** The AI a new agent routine starts with: the agent's own, else the one last chosen to run an agent by hand. */
15267
+ function defaultRoutineAgentAi(agent) {
15268
+ if (agent?.provider) return agent.provider;
15269
+ try { const last = localStorage.getItem('floless:agents-provider'); if (last === 'codex' || last === 'claude') return last; } catch { /* private mode */ }
15270
+ return 'claude';
15271
+ }
15272
+
15273
+ function paintRoutineAgentNote() {
15274
+ const $note = document.getElementById('rtn-agent-note');
15275
+ const agent = editAgents.find((a) => a.agentId === document.getElementById('rtn-agent').value);
15276
+ if (!agent) { $note.textContent = ''; return; }
15277
+ const access = agent.allowChanges
15278
+ ? 'Can change files, so it runs in Auto. Anything that would ask you is declined and listed afterwards on the Agents page.'
15279
+ : 'Read only. It reads and reports.';
15280
+ $note.textContent = access;
15281
+ }
15282
+
15283
+ async function loadRoutineAgents(selectedId, fixed) {
15284
+ const $agent = document.getElementById('rtn-agent');
15285
+ const $empty = document.getElementById('rtn-agent-empty');
15286
+ try { editAgents = (await window.flolessAgents?.list?.()) || []; }
15287
+ catch { editAgents = null; }
15288
+ const usable = (editAgents || []).filter((a) => !a.archivedAt || a.agentId === selectedId);
15289
+ for (const a of usable) routineAgentNames.set(a.agentId, a.name);
15290
+ // Editing a routine whose agent is gone: say so, never show another agent's name in the locked picker.
15291
+ const gone = fixed && selectedId && editAgents && !usable.some((a) => a.agentId === selectedId);
15292
+ $agent.innerHTML = (gone ? `<option value="${escapeAttr(selectedId)}">This agent no longer exists</option>` : '')
15293
+ + usable.map((a) => `<option value="${escapeAttr(a.agentId)}">${escapeHtml(a.name)}${a.allowChanges ? '' : ' (read only)'}</option>`).join('');
15294
+ if (selectedId) $agent.value = selectedId;
15295
+ const shown = usable.length > 0 || Boolean(gone);
15296
+ // The select is shown as the shared themed combobox, its next sibling: hide that, not the hidden native control.
15297
+ const combo = $agent.nextElementSibling?.classList.contains('sel-combo') ? $agent.nextElementSibling : null;
15298
+ if (combo) combo.style.display = shown ? '' : 'none';
15299
+ $agent.hidden = !shown;
15300
+ $empty.hidden = shown;
15301
+ if (editAgents === null) {
15302
+ $empty.hidden = false;
15303
+ $empty.firstChild.textContent = 'FloLess couldn’t list your agents just now. Close this and open it again, or ';
15304
+ } else {
15305
+ $empty.firstChild.textContent = 'No agents in this workspace folder yet. ';
15306
+ }
15307
+ document.getElementById('rtn-agent-ai').hidden = !usable.length;
15308
+ $agent.disabled = Boolean(fixed);
15309
+ if (fixed) $agent.setAttribute('data-tip', 'The agent is fixed — create a new routine to run a different one');
15310
+ else $agent.removeAttribute('data-tip');
15311
+ paintRoutineAgentNote();
15312
+ }
15313
+
14355
15314
  // Schedule builder: reveal only the fields the chosen kind needs.
14356
15315
  // Switch the edit form between schedule and trigger layouts. Hides the schedule
14357
15316
  // builder and shows the read-only trigger-source line for 'trigger' (only honored
@@ -14411,7 +15370,9 @@
14411
15370
 
14412
15371
  // Render the chosen workflow's declared inputs (seeded from defaults / the routine's
14413
15372
  // saved values). Hidden when the workflow declares none.
15373
+ let routineInputsLoad = 0; // #2035: only the newest load builds the inputs; an older one that returns late is dropped
14414
15374
  async function loadRoutineInputs(workflowId, prefill) {
15375
+ const load = ++routineInputsLoad;
14415
15376
  const $field = document.getElementById('rtn-inputs-field');
14416
15377
  const $inputs = document.getElementById('rtn-inputs');
14417
15378
  $inputs.innerHTML = '';
@@ -14419,8 +15380,9 @@
14419
15380
  editTriggerSource = null;
14420
15381
  if (!workflowId) { applyRoutineModeAvailability(); return; }
14421
15382
  let app;
14422
- try { ({ app } = await api(`/api/app/${encodeURIComponent(workflowId)}`)); } catch { applyRoutineModeAvailability(); return; }
15383
+ try { ({ app } = await api(`/api/app/${encodeURIComponent(workflowId)}`)); } catch { if (editTarget === 'workflow') applyRoutineModeAvailability(); return; }
14423
15384
  if (document.getElementById('rtn-workflow').value !== workflowId) return; // a newer workflow selection superseded this fetch
15385
+ if (load !== routineInputsLoad || editTarget !== 'workflow') return; // #2035: superseded, or switched to An agent meanwhile
14424
15386
  editTriggerSource = (app && app.triggerSource) || null;
14425
15387
  applyRoutineModeAvailability(); // reveal/hide the schedule-vs-trigger chooser
14426
15388
  const inps = (app && app.inputs) || [];
@@ -14430,7 +15392,7 @@
14430
15392
  const routineModelModule = inps.find((inp) => inp.widget === 'workspace-model-revision')?.workspaceModule === 'tekla' ? 'tekla' : 'revit';
14431
15393
  const bootstrap = await bootstrapEditorSession();
14432
15394
  routineModelRevisions = bootstrap.ok ? await fetchApprovedModelRevisions(routineModelModule) : unavailableModelRevisionResult(bootstrap.error);
14433
- if (document.getElementById('rtn-workflow').value !== workflowId) return;
15395
+ if (document.getElementById('rtn-workflow').value !== workflowId || load !== routineInputsLoad || editTarget !== 'workflow') return;
14434
15396
  }
14435
15397
  $field.hidden = false;
14436
15398
  // The DOM id is index-based (not the workflow-controlled input name) so a crafted
@@ -14496,9 +15458,10 @@
14496
15458
  return out;
14497
15459
  }
14498
15460
 
14499
- async function openRoutineEdit(id) {
15461
+ async function openRoutineEdit(id, opts = {}) {
14500
15462
  editingRoutineId = id || null;
14501
15463
  const r = id ? routinesData.find((x) => x.id === id) : null;
15464
+ editReturnFocus = opts.returnFocus || null;
14502
15465
  const $wf = document.getElementById('rtn-workflow');
14503
15466
  try {
14504
15467
  const { apps: list } = await api('/api/apps');
@@ -14507,7 +15470,12 @@
14507
15470
  $wf.innerHTML = editWorkflows.map((a) => `<option value="${escapeAttr(a.id)}">${escapeHtml(a.id)}</option>`).join('');
14508
15471
  document.getElementById('rtn-edit-title').textContent = r ? 'Edit routine' : 'New routine';
14509
15472
  document.getElementById('rtn-name').value = r ? r.name : '';
14510
- const wfId = r ? r.workflow : (editWorkflows[0] ? editWorkflows[0].id : '');
15473
+ // #2046: a Guide suggestion names the workflow; it is preselected only when it is one of the choices.
15474
+ const suggested = !r && opts.workflowId && editWorkflows.some((a) => a.id === opts.workflowId) ? opts.workflowId : null;
15475
+ if (!r && opts.workflowId && !suggested) {
15476
+ showToast(`${opts.workflowId} can’t be scheduled from here, so no workflow is chosen yet. Pick the one to run in the list.`, 'warn');
15477
+ }
15478
+ const wfId = r ? r.workflow : opts.workflowId && !suggested ? '' : (suggested || (editWorkflows[0] ? editWorkflows[0].id : ''));
14511
15479
  $wf.value = wfId;
14512
15480
  // Workflow is fixed after create (inputs are coerced against it) — disable on edit.
14513
15481
  $wf.disabled = !!r;
@@ -14524,19 +15492,38 @@
14524
15492
  renderDayChips(sched.kind === 'weekly' ? (sched.days || []) : []);
14525
15493
  applySchedKind(sched.kind);
14526
15494
  document.getElementById('rtn-enabled').checked = r ? r.enabled : true;
14527
- await loadRoutineInputs(wfId, r ? r.inputs : null);
15495
+ // #2035: what it runs is fixed after create, like the workflow.
15496
+ const agentId = r?.agent?.agentId || opts.agentId || null;
15497
+ document.getElementById('rtn-target-field').hidden = Boolean(r);
15498
+ await loadRoutineAgents(agentId, Boolean(r));
15499
+ setRoutineAgentAi(r?.agent?.provider || defaultRoutineAgentAi((editAgents || []).find((a) => a.agentId === document.getElementById('rtn-agent').value)));
15500
+ if (agentId) setRoutineTarget('agent');
15501
+ else {
15502
+ setRoutineTarget('workflow');
15503
+ await loadRoutineInputs(wfId, r ? r.inputs : null);
15504
+ }
14528
15505
  showModal($routineEditModal);
14529
15506
  setTimeout(() => document.getElementById('rtn-name').focus(), 0);
14530
15507
  }
14531
15508
 
15509
+ function closeRoutineEdit() {
15510
+ hideModal($routineEditModal);
15511
+ const back = editReturnFocus;
15512
+ editReturnFocus = null;
15513
+ if (back && back.isConnected) setTimeout(() => back.focus(), 0);
15514
+ }
15515
+
14532
15516
  async function saveRoutine() {
14533
15517
  const name = document.getElementById('rtn-name').value.trim();
14534
15518
  if (!name) { showToast('Name is required', 'warn'); return; }
15519
+ const asAgent = editTarget === 'agent';
15520
+ const agentId = document.getElementById('rtn-agent').value;
15521
+ if (asAgent && !agentId && !editingRoutineId) { showToast('Pick an agent — or create one on the Agents page first', 'warn'); return; }
14535
15522
  const workflow = document.getElementById('rtn-workflow').value;
14536
- if (!workflow) { showToast('Pick a workflow', 'warn'); return; }
14537
- const inputs = collectRoutineInputs();
15523
+ if (!asAgent && !workflow) { showToast('Pick a workflow', 'warn'); return; }
15524
+ const inputs = asAgent ? {} : collectRoutineInputs();
14538
15525
  const enabled = document.getElementById('rtn-enabled').checked;
14539
- const asTrigger = editRoutineMode === 'trigger' && !!editTriggerSource;
15526
+ const asTrigger = !asAgent && editRoutineMode === 'trigger' && !!editTriggerSource;
14540
15527
  let schedule;
14541
15528
  if (!asTrigger) {
14542
15529
  const kind = document.getElementById('rtn-kind').value;
@@ -14560,23 +15547,43 @@
14560
15547
  }
14561
15548
  try {
14562
15549
  if (editingRoutineId) {
14563
- const body = asTrigger ? { name, inputs, enabled } : { name, schedule, inputs, enabled };
15550
+ const body = asAgent ? { name, schedule, enabled, provider: editAgentAi } : asTrigger ? { name, inputs, enabled } : { name, schedule, inputs, enabled };
14564
15551
  await api(`/api/routines/${encodeURIComponent(editingRoutineId)}`, { method: 'PATCH', body: JSON.stringify(body) });
14565
15552
  showToast('Routine updated', 'ok');
14566
15553
  } else {
14567
- const body = asTrigger ? { kind: 'trigger', name, workflow, inputs, enabled } : { name, workflow, schedule, inputs, enabled };
15554
+ const body = asAgent ? { name, agentId, provider: editAgentAi, schedule, enabled }
15555
+ : asTrigger ? { kind: 'trigger', name, workflow, inputs, enabled } : { name, workflow, schedule, inputs, enabled };
14568
15556
  await api('/api/routines', { method: 'POST', body: JSON.stringify(body) });
14569
15557
  showToast('Routine created', 'ok');
14570
15558
  }
14571
- hideModal($routineEditModal);
15559
+ closeRoutineEdit();
14572
15560
  await loadRoutinesData();
14573
- } catch (e) { showToast('We couldn’t save this routine because FloLess could not save the change. Try again.', 'err'); }
15561
+ } catch (e) {
15562
+ // #2035: the server words an agent routine's refusal for the person (archived, another folder…); say that.
15563
+ const said = asAgent && typeof e?.body?.error === 'string' && e.status < 500 ? e.body.error : null;
15564
+ showToast(said || 'We couldn’t save this routine because FloLess could not save the change. Try again.', 'err');
15565
+ }
15566
+ }
15567
+
15568
+ // #2035 (PR #2045 review): a routine only starts its agent, so "how the run is going" changes long after the routine's
15569
+ // own events. While the dialog is open, and an agent run it started may still be going, ask again every few seconds.
15570
+ let routineAgentPoll = null;
15571
+ function pollRoutineAgents() {
15572
+ clearTimeout(routineAgentPoll);
15573
+ routineAgentPoll = setTimeout(async () => {
15574
+ if (!$routinesModal.classList.contains('show')) return;
15575
+ const going = routinesData.some((r) => r.agent && (r.lastRun?.status === 'starting'
15576
+ || (r.lastRun?.status === 'started' && agentRunStillGoing(routineAgentRunState.get(r.id) || ''))));
15577
+ if (going) await refreshRoutineAgents();
15578
+ pollRoutineAgents();
15579
+ }, 8000);
14574
15580
  }
14575
15581
 
14576
15582
  openRoutines = function openRoutinesReal() {
14577
15583
  renderRoutinesList();
14578
15584
  showModal($routinesModal);
14579
15585
  loadRoutinesData();
15586
+ pollRoutineAgents();
14580
15587
  };
14581
15588
 
14582
15589
  // Wiring (the modal elements are static in index.html, present when this runs).
@@ -14585,15 +15592,52 @@
14585
15592
  document.getElementById('routines-close').onclick = () => hideModal($routinesModal);
14586
15593
  onBackdropDismiss($routinesModal, () => hideModal($routinesModal));
14587
15594
  document.getElementById('rtn-add').onclick = () => openRoutineEdit(null);
14588
- document.getElementById('rtn-edit-cancel').onclick = () => hideModal($routineEditModal);
15595
+ document.getElementById('rtn-edit-cancel').onclick = () => closeRoutineEdit();
14589
15596
  document.getElementById('rtn-edit-save').onclick = () => saveRoutine();
14590
- onBackdropDismiss($routineEditModal, () => hideModal($routineEditModal));
15597
+ onBackdropDismiss($routineEditModal, () => closeRoutineEdit());
14591
15598
  document.getElementById('rtn-kind').onchange = (e) => applySchedKind(e.target.value);
14592
15599
  document.querySelectorAll('#rtn-mode-field .rtn-mode-btn').forEach((b) => { b.onclick = () => setRoutineMode(b.dataset.mode); });
14593
15600
  document.getElementById('rtn-workflow').onchange = (e) => { if (!editingRoutineId) loadRoutineInputs(e.target.value, null); };
15601
+ document.querySelectorAll('#rtn-target-field .rtn-mode-btn').forEach((b) => {
15602
+ b.onclick = () => {
15603
+ setRoutineTarget(b.dataset.target);
15604
+ if (editTarget === 'agent') (document.getElementById('rtn-agent-combo-trigger') || document.getElementById('rtn-agent')).focus();
15605
+ // A load the switch to An agent cut short left nothing to restore: load it now (the newest load wins).
15606
+ else if (!document.getElementById('rtn-inputs').children.length) void loadRoutineInputs(document.getElementById('rtn-workflow').value, null);
15607
+ };
15608
+ });
15609
+ document.getElementById('rtn-agent').onchange = () => {
15610
+ paintRoutineAgentNote();
15611
+ if (!editingRoutineId) setRoutineAgentAi(defaultRoutineAgentAi((editAgents || []).find((a) => a.agentId === document.getElementById('rtn-agent').value)));
15612
+ };
15613
+ document.querySelectorAll('#rtn-agent-ai .rtn-mode-btn').forEach((b) => { b.onclick = () => setRoutineAgentAi(b.dataset.ai); });
15614
+ document.getElementById('rtn-agent-create').onclick = () => {
15615
+ closeRoutineEdit(); hideModal($routinesModal);
15616
+ void window.flolessWorkspaces?.setMode?.('agents');
15617
+ };
15618
+ // #2035: an agent's page opens a new routine with that agent chosen.
15619
+ window.flolessRoutines = {
15620
+ /** #2046: a Guide suggestion — a new routine for this workflow, opened for the person to finish. */
15621
+ async editForWorkflow(workflowId, returnFocus) {
15622
+ await loadRoutinesData();
15623
+ if (routinesData.length >= routinesMax) {
15624
+ showToast(`You already have ${routinesMax} routines. Delete one in Routines (≡ menu), then schedule this workflow.`, 'warn');
15625
+ return;
15626
+ }
15627
+ await openRoutineEdit(null, { workflowId, returnFocus });
15628
+ },
15629
+ async editForAgent(agentId, returnFocus) {
15630
+ await loadRoutinesData();
15631
+ if (routinesData.length >= routinesMax) {
15632
+ showToast(`You already have ${routinesMax} routines. Delete one in Routines (≡ menu), then schedule this agent.`, 'warn');
15633
+ return;
15634
+ }
15635
+ await openRoutineEdit(null, { agentId, returnFocus });
15636
+ },
15637
+ };
14594
15638
  document.addEventListener('keydown', (e) => {
14595
15639
  if (e.key !== 'Escape') return;
14596
- if ($routineEditModal.classList.contains('show')) hideModal($routineEditModal);
15640
+ if ($routineEditModal.classList.contains('show')) closeRoutineEdit();
14597
15641
  else if ($routinesModal.classList.contains('show')) hideModal($routinesModal);
14598
15642
  });
14599
15643
 
@@ -14624,6 +15668,25 @@
14624
15668
  const $riImportList = document.getElementById('ri-import-list');
14625
15669
  const $riImportInclude = document.getElementById('ri-import-include');
14626
15670
 
15671
+ const $riSendError = document.getElementById('ri-send-error');
15672
+ const riClearSendError = () => { if ($riSendError) { $riSendError.hidden = true; $riSendError.textContent = ''; } };
15673
+ // What a failed send says: what happened, why, and what to do next. The typed text always stays.
15674
+ function riSendFailureCopy(err, importDetailsShown) {
15675
+ if (err === 'rejected') {
15676
+ const fix = importDetailsShown ? 'shorten the description or untick “Include these import details”' : 'shorten or simplify the description';
15677
+ return `FloLess reached our support inbox, but it would not accept this report as written. Your text is still here: ${fix}, then press Send report again.`;
15678
+ }
15679
+ if (err === 'declined') {
15680
+ return 'FloLess reached our support inbox, but it refused this report. Your text is still here: update FloLess to the latest version, then press Send report again.';
15681
+ }
15682
+ if (err === 'unavailable') {
15683
+ return 'FloLess reached our support inbox, but it is having trouble right now. Your text is still here: press Send report again in a few minutes.';
15684
+ }
15685
+ if (err === 'offline') {
15686
+ return 'FloLess could not reach our support inbox, so the report was not sent. Check your internet connection, then press Send report again — your text is still here.';
15687
+ }
15688
+ return 'FloLess ran into a problem on this computer before it could send the report. Your text is still here: press Send report again, and if it keeps happening restart FloLess.';
15689
+ }
14627
15690
  const riSyncSend = () => { $riSend.disabled = !($riTitle.value.trim() && $riDesc.value.trim()); };
14628
15691
  function riHideAndRestoreFocus() {
14629
15692
  hideModal($riModal);
@@ -14693,6 +15756,7 @@
14693
15756
  riReturnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
14694
15757
  if ($menu.contains(riReturnFocus)) riReturnFocus = $menuBtn;
14695
15758
  riSubmitting = false;
15759
+ riClearSendError();
14696
15760
  $riForm.hidden = false;
14697
15761
  $riState.hidden = true;
14698
15762
  while ($riState.firstChild) $riState.removeChild($riState.firstChild);
@@ -14801,18 +15865,23 @@
14801
15865
  riSyncSend();
14802
15866
  });
14803
15867
 
14804
- function riRenderSuccess(ref, droppedImportReference = null) {
15868
+ function riRenderSuccess(ref, droppedImportReference = null, queued = false) {
14805
15869
  const wrap = document.createElement('div');
14806
- wrap.className = 'graft-success';
15870
+ // #2125: the report could not be delivered (inbox down or no connection), so the server kept it to send later.
15871
+ // `is-held` tints the check: saved, but not sent.
15872
+ wrap.className = queued ? 'graft-success is-held' : 'graft-success';
14807
15873
  const icon = document.createElement('div');
14808
15874
  icon.className = 'gs-icon';
14809
15875
  icon.setAttribute('aria-hidden', 'true');
14810
15876
  icon.appendChild(riCheckIcon());
14811
15877
  const msg = document.createElement('div');
14812
15878
  msg.className = 'gs-msg';
14813
- msg.textContent = ref
14814
- ? `Received — logged as ${ref} · We'll follow up privately.`
14815
- : "Received · We'll follow up privately.";
15879
+ msg.id = 'ri-state-msg';
15880
+ msg.textContent = queued
15881
+ ? 'Saved on this computer — not sent yet. FloLess could not deliver it just now, so it kept your report and will keep trying, sending it automatically whenever FloLess is running. You don\'t need to send it again.'
15882
+ : ref
15883
+ ? `Received — logged as ${ref} · We'll follow up privately.`
15884
+ : "Received · We'll follow up privately.";
14816
15885
  wrap.append(icon, msg);
14817
15886
  // #1757: the person chose to include the import details, but FloLess could not attach them (the
14818
15887
  // import is no longer readable to this session). Say so, and give them the reference to pass on.
@@ -14825,6 +15894,7 @@
14825
15894
  const actions = document.createElement('div');
14826
15895
  actions.className = 'modal-actions';
14827
15896
  const done = riButton('ri-done', 'Done', true, () => riClose());
15897
+ done.setAttribute('aria-describedby', 'ri-state-msg'); // focus lands on Done: let it read the outcome
14828
15898
  actions.append(done);
14829
15899
  riShowState(wrap, actions);
14830
15900
  done.focus();
@@ -14851,6 +15921,7 @@
14851
15921
  const body = $riDesc.value.trim();
14852
15922
  if (!title || !body) return;
14853
15923
  riSubmitting = true;
15924
+ riClearSendError();
14854
15925
  $riSend.disabled = true;
14855
15926
  $riSend.textContent = 'Sending…';
14856
15927
  // Versions are filled by the health fetch on open; if a fast submit beat it, fetch them
@@ -14875,7 +15946,7 @@
14875
15946
  const importFailure = riImport && $riImport && !$riImport.hidden && $riImportInclude?.checked ? riImport : undefined;
14876
15947
  const r = await api('/api/report-issue', { method: 'POST', body: JSON.stringify({ category: riCategory, title, body, context, importFailure }) });
14877
15948
  riSubmitting = false; // response in hand — Done / Escape / backdrop may close
14878
- riRenderSuccess(r.ref || '', importFailure && r.importDetailsAttached === false ? importFailure.operationId : null);
15949
+ riRenderSuccess(r.ref || '', importFailure && r.importDetailsAttached === false ? importFailure.operationId : null, r.queued === true);
14879
15950
  } catch (e) {
14880
15951
  riSubmitting = false;
14881
15952
  const err = (e && e.body && e.body.error) || '';
@@ -14885,7 +15956,10 @@
14885
15956
  showToast('Too many reports just now — please wait a moment and try again', 'warn');
14886
15957
  $riSend.disabled = false; $riSend.textContent = 'Send report';
14887
15958
  } else {
14888
- showToast("Couldn't send — check your connection and try again", 'err');
15959
+ const copy = riSendFailureCopy(err, Boolean(riImport && $riImport && !$riImport.hidden && $riImportInclude?.checked));
15960
+ $riSendError.textContent = copy;
15961
+ $riSendError.hidden = false;
15962
+ showToast('Report not sent — your text is kept', 'err');
14889
15963
  $riSend.disabled = false; $riSend.textContent = 'Send report';
14890
15964
  }
14891
15965
  }
@@ -15036,6 +16110,21 @@
15036
16110
  const b = e.target.closest('button[data-reqscope]');
15037
16111
  if (b) setRequestScopeAll(b.dataset.reqscope === 'all');
15038
16112
  };
16113
+ const $reqView = document.getElementById('requests-view');
16114
+ if ($reqView) {
16115
+ $reqView.onclick = (e) => {
16116
+ const b = e.target.closest('button[data-reqview]');
16117
+ if (b) void setRequestViewMode(b.dataset.reqview);
16118
+ };
16119
+ // A tablist moves between its tabs with the arrow keys.
16120
+ $reqView.onkeydown = (e) => {
16121
+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
16122
+ e.preventDefault();
16123
+ const next = requestViewMode === 'done' ? 'queued' : 'done';
16124
+ void setRequestViewMode(next);
16125
+ document.getElementById(`requests-view-${next}`)?.focus();
16126
+ };
16127
+ }
15039
16128
  const $reqSearch = document.getElementById('requests-search');
15040
16129
  if ($reqSearch) $reqSearch.oninput = () => { requestQuery = $reqSearch.value; renderRequests(); };
15041
16130
  const $reqList = document.getElementById('requests-list');
@@ -15529,6 +16618,57 @@
15529
16618
  }
15530
16619
 
15531
16620
  // ── Workflows landing (#1890) ─────────────────────────────────────────────────
16621
+ async function restoreOwnedWorkflow(workflowId) {
16622
+ const row = wfOwned.find((item) => item.workflowId === workflowId && item.status === 'archived');
16623
+ if (!row || restoringWorkflows.has(workflowId)) return;
16624
+ const selectionAtStart = selectionTicket;
16625
+ const ownsFocus = (element) => element?.dataset?.wfRestore === workflowId;
16626
+ let returnFocus = ownsFocus(document.activeElement);
16627
+ const trackFocus = (event) => {
16628
+ if (event.target !== document.body && !ownsFocus(event.target)) returnFocus = false;
16629
+ };
16630
+ document.addEventListener('focusin', trackFocus);
16631
+ let restored = false;
16632
+ restoringWorkflows.add(workflowId);
16633
+ renderWorkflowsLanding();
16634
+ try {
16635
+ const { workflow } = await api(`/api/workflows/owned/${encodeURIComponent(workflowId)}/archive`, {
16636
+ method: 'POST', body: JSON.stringify({ archived: false }),
16637
+ });
16638
+ restored = true;
16639
+ appsLoadGeneration += 1; // a listing started before this committed restore cannot erase it
16640
+ if (selectionTicket === selectionAtStart) selectionTicket += 1;
16641
+ const committed = { ...row, ...workflow, restoreRefreshState: 'pending' };
16642
+ wfOwned = wfOwned.filter((item) => item.workflowId !== workflowId).concat(committed);
16643
+ if (wfLanding) renderWorkflowsLanding();
16644
+ let refreshFailed = false;
16645
+ try { await loadApps({ preserveSelection: true }); }
16646
+ catch { refreshFailed = true; }
16647
+ // An unavailable additive owned list is deliberately tolerated by loadApps, but is still
16648
+ // not a fresh confirmation. The POST succeeded regardless of that later read's outcome.
16649
+ if (refreshFailed || wfOwned.some((item) => item.workflowId === workflowId && item.restoreRefreshState)) {
16650
+ wfOwned = wfOwned.map((item) => item.workflowId === workflowId && item.status !== 'archived'
16651
+ ? { ...item, restoreRefreshState: 'failed' } : item);
16652
+ showToast(`Restored “${row.displayName}”. The list could not refresh. Reload this page to show it.`, 'warn');
16653
+ } else showToast(`Restored “${row.displayName}”`, 'ok');
16654
+ } catch (error) { reportErr(error); }
16655
+ finally {
16656
+ restoringWorkflows.delete(workflowId);
16657
+ document.removeEventListener('focusin', trackFocus);
16658
+ if (wfLanding) {
16659
+ renderWorkflowsLanding();
16660
+ if (returnFocus && (document.activeElement === document.body || ownsFocus(document.activeElement))
16661
+ && !document.getElementById('app')?.classList.contains('mode-workspaces')) {
16662
+ const publication = wfLibrary.find((item) => item.ownedWorkflow?.workflowId === workflowId);
16663
+ const target = restored
16664
+ ? $wfLanding.querySelector(`[data-wf-restored="${CSS.escape(workflowId)}"]`)
16665
+ || $wfLanding.querySelector(publication ? `[data-wf-id="${CSS.escape(publication.id)}"]` : `[data-wf-draft="${CSS.escape(workflowId)}"]`)
16666
+ : $wfLanding.querySelector(`[data-wf-restore="${CSS.escape(workflowId)}"]`);
16667
+ (target && !target.hidden ? target : document.getElementById('wf-landing-title'))?.focus();
16668
+ }
16669
+ }
16670
+ }
16671
+ }
15532
16672
  // The Workflows tab's home, the counterpart of the Workspaces landing: a create card and one card per workflow. It
15533
16673
  // renders AWARE's library listing; it composes nothing.
15534
16674
  const $wfLanding = document.getElementById('wf-landing');
@@ -15562,8 +16702,25 @@
15562
16702
  function scheduledRoutineTip(routines, workflowId) {
15563
16703
  const names = routines.filter((r) => r.enabled && !r.broken && r.workflow === workflowId).map((r) => `“${r.name}”`);
15564
16704
  if (!names.length) return '';
15565
- return names.length === 1 ? `Runs automatically from the routine ${names[0]}.`
15566
- : `Runs automatically from ${names.length} routines: ${names.join(', ')}.`;
16705
+ // #2062: never read as always-on — a routine runs only while FloLess is running on this computer.
16706
+ return names.length === 1 ? `Runs from the routine ${names[0]}, only while FloLess is running on this computer.`
16707
+ : `Runs from ${names.length} routines (${names.join(', ')}), only while FloLess is running on this computer.`;
16708
+ }
16709
+
16710
+ /**
16711
+ * C12 (#1337): the Workflows landing's notice naming every installed workflow AWARE could not read. The others still
16712
+ * list; this says which one is missing from the page, why, and what to do. Empty when every workflow was readable.
16713
+ */
16714
+ function unreadableWorkflowsNoteHtml(rows, esc) {
16715
+ if (!Array.isArray(rows) || !rows.length) return '';
16716
+ const names = rows.map((row) => `“${esc(row.name || row.id)}”`);
16717
+ const list = names.length === 1 ? names[0] : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
16718
+ const one = rows.length === 1;
16719
+ // Static, rendered with the page: a plain note, not a live region (it would only be announced twice).
16720
+ return `<div class="ws-empty-note ws-load-error wf-unreadable" data-wf-unreadable="${rows.length}">`
16721
+ + `<b>FloLess couldn’t read ${one ? 'one installed workflow' : `${rows.length} installed workflows`}: ${list}.</b> `
16722
+ + `${one ? 'Its files are damaged or incomplete, so it can’t be opened or run' : 'Their files are damaged or incomplete, so they can’t be opened or run'}. `
16723
+ + `Your other workflows are not affected. Ask AI Chat to repair or reinstall ${one ? 'it' : 'them'}.</div>`;
15567
16724
  }
15568
16725
 
15569
16726
  function renderWorkflowsLanding() {
@@ -15573,16 +16730,38 @@
15573
16730
  const keepCaret = search ? [search.selectionStart, search.selectionEnd] : null;
15574
16731
  const clearFocused = document.activeElement?.id === 'wf-search-clear';
15575
16732
  const focusedDraft = document.activeElement?.closest?.('#wf-landing [data-wf-draft]')?.dataset.wfDraft || null;
16733
+ const focusedRestore = document.activeElement?.closest?.('[data-wf-restore]')?.dataset.wfRestore || null;
16734
+ const focusedRestored = document.activeElement?.closest?.('[data-wf-restored]')?.dataset.wfRestored || null;
15576
16735
  const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
15577
- const owned = wfLibrary.filter((row) => row.ownedWorkflow);
16736
+ const restoredRows = wfOwned.filter((row) => row.status !== 'archived' && row.restoreRefreshState);
16737
+ const restoredIds = new Set(restoredRows.map((row) => row.workflowId));
16738
+ const owned = wfLibrary.filter((row) => row.ownedWorkflow && !restoredIds.has(row.ownedWorkflow.workflowId));
15578
16739
  const installed = wfLibrary.filter((row) => !row.ownedWorkflow);
15579
16740
  // #1890 PR 3b-0: owned workflows the library does not list — drafts, and ones whose installed copy is gone.
15580
- const unlisted = unlistedOwnedWorkflows();
16741
+ const unlisted = unlistedOwnedWorkflows().filter((row) => !restoredIds.has(row.workflowId));
16742
+ const archived = wfOwned.filter((row) => row.status === 'archived');
16743
+ const restoredCard = (row) => `<div class="ws-card wf-card wf-card-archived" tabindex="-1" data-wf-restored="${esc(row.workflowId)}">`
16744
+ + `<div class="ws-body"><div class="wf-card-text"><span class="ws-kind wf-kind is-draft">Restored</span>`
16745
+ + `<div class="ws-name">${esc(row.displayName)}</div><div class="ws-meta">${esc(row.ownerLabel || 'Standalone')}</div>`
16746
+ + `<p class="wf-draft-body" role="status">${row.restoreRefreshState === 'failed'
16747
+ ? 'Workflow restored. The list could not refresh. Reload this page to show it.' : 'Workflow restored. Refreshing workflow list…'}</p>`
16748
+ + `</div></div></div>`;
16749
+ const archivedCard = (row) => {
16750
+ const busy = restoringWorkflows.has(row.workflowId);
16751
+ return `<div class="ws-card wf-card wf-card-archived" data-wf-archived="${esc(row.workflowId)}">`
16752
+ + `<div class="ws-body"><div class="wf-card-text"><span class="ws-kind wf-kind is-draft">Archived</span>`
16753
+ + `<div class="ws-name">${esc(row.displayName)}</div><div class="ws-meta">${esc(row.ownerLabel || 'Standalone')}</div>`
16754
+ + `<div class="wf-draft-actions"><button type="button" data-wf-restore="${esc(row.workflowId)}" data-command-id="workflow.unarchive#${esc(row.workflowId)}" data-command-instance-label="${esc(row.displayName)}" data-tip="Restore this workflow to the Workflows page with its files, chat and history"${busy ? ' disabled aria-busy="true"' : ''}>${busy ? 'Restoring…' : 'Restore'}</button></div>`
16755
+ + `</div></div></div>`;
16756
+ };
16757
+ // C12 (#1337): owned workflows whose installed copy AWARE could not read show as drafts that need compiling again.
16758
+ const unreadableOwned = new Set(wfUnreadable.map((row) => row.workflowId).filter(Boolean));
16759
+ const unreadableNote = unreadableWorkflowsNoteHtml(wfUnreadable, esc);
15581
16760
  const draftCard = (row) => {
15582
16761
  const recompile = Boolean(row.activePublication);
15583
16762
  const name = row.displayName;
15584
16763
  const chip = recompile ? 'Needs compiling' : 'Draft';
15585
- const meta = `${recompile ? 'Compiled copy missing' : 'Not compiled yet'} · ${row.ownerLabel || 'Standalone'}`;
16764
+ const meta = `${recompile ? (unreadableOwned.has(row.workflowId) ? 'Compiled copy unreadable' : 'Compiled copy missing') : 'Not compiled yet'} · ${row.ownerLabel || 'Standalone'}`;
15586
16765
  return `<div class="ws-card wf-card wf-card-draft" role="button" tabindex="0" data-wf-draft="${esc(row.workflowId)}" data-command-id="shell.workflows-landing-open-draft#${esc(name)}" data-command-instance-label="${esc(name)}">`
15587
16766
  + `<div class="ws-body"><div class="wf-card-text"><span class="ws-kind wf-kind is-draft">${chip}</span>`
15588
16767
  + `<div class="ws-name">${esc(name)}</div><div class="ws-meta">${esc(meta)}</div></div></div></div>`;
@@ -15601,24 +16780,28 @@
15601
16780
  };
15602
16781
  const group = (title, rows, show) => (rows.length
15603
16782
  ? `${show ? `<div class="wf-group-label">${esc(title)} (${rows.length})</div>` : ''}<div class="ws-grid">${rows.map(card).join('')}</div>` : '');
15604
- const yours = unlisted.length + owned.length;
16783
+ const yours = unlisted.length + owned.length + restoredRows.length;
15605
16784
  const both = yours > 0 && installed.length > 0;
15606
16785
  const yoursGroup = yours
15607
- ? `${both ? `<div class="wf-group-label">Your workflows (${yours})</div>` : ''}<div class="ws-grid">${unlisted.map(draftCard).join('')}${owned.map(card).join('')}</div>`
16786
+ ? `${both ? `<div class="wf-group-label">Your workflows (${yours})</div>` : ''}<div class="ws-grid">${unlisted.map(draftCard).join('')}${owned.map(card).join('')}${restoredRows.map(restoredCard).join('')}</div>`
15608
16787
  : '';
15609
16788
  $wfLanding.innerHTML = `<div class="ws-head"><div class="ws-head-text"><h2 tabindex="-1" id="wf-landing-title">Workflows</h2>`
15610
16789
  + `<p class="ws-sub">Build, run and manage the workflows behind your projects. Ask AI Chat on the left to build one with you.</p></div>`
15611
- + (wfLibrary.length || unlisted.length ? `<div class="ws-head-actions"><input type="search" id="wf-landing-search" class="ws-landing-search" data-command-id="shell.workflows-landing-search" placeholder="Search workflows" aria-label="Search workflows by name, project or tool" autocomplete="off" spellcheck="false" value="${esc(wfLandingQuery)}"></div>` : '')
16790
+ + (wfLibrary.length || unlisted.length || archived.length || restoredRows.length ? `<div class="ws-head-actions"><input type="search" id="wf-landing-search" class="ws-landing-search" data-command-id="shell.workflows-landing-search" placeholder="Search workflows" aria-label="Search workflows by name, project or tool" autocomplete="off" spellcheck="false" value="${esc(wfLandingQuery)}"></div>` : '')
15612
16791
  + `</div>`
15613
- + `<div class="ws-create-grid"><div class="ws-card ws-create wf-create" role="button" tabindex="0" data-wf-new="1" data-command-id="shell.workflows-landing-new">`
16792
+ + `<div class="ws-create-grid"><div class="ws-card ws-create ws-card-create wf-create" role="button" tabindex="0" data-wf-new="1" data-command-id="shell.workflows-landing-new">`
15614
16793
  + `<div class="ws-thumb">+</div><div class="ws-body"><div><div class="ws-name">New workflow</div>`
15615
16794
  + `<div class="ws-meta">Name it and choose where it belongs. AI builds it with you.</div></div></div></div></div>`
15616
- + (wfLibrary.length || unlisted.length
16795
+ + unreadableNote
16796
+ + (wfLibrary.length || unlisted.length || archived.length || restoredRows.length
15617
16797
  ? yoursGroup + group('Installed', installed, both)
15618
16798
  + '<div class="ws-empty-note ws-search-empty" id="wf-search-empty" role="status" aria-live="polite"></div>'
15619
- : '<div class="ws-empty-note">No workflows yet. Start with New workflow, or ask AI Chat on the left.</div>');
16799
+ : '<div class="ws-empty-note">No active workflows yet. Start with New workflow, or ask AI Chat on the left.</div>')
16800
+ + (archived.length ? `<div class="wf-group-label">Archived (${archived.length})</div><div class="ws-grid">${archived.map(archivedCard).join('')}</div>` : '');
15620
16801
  if (focusedId) $wfLanding.querySelector(`[data-wf-id="${CSS.escape(focusedId)}"]`)?.focus();
15621
16802
  if (focusedDraft) $wfLanding.querySelector(`[data-wf-draft="${CSS.escape(focusedDraft)}"]`)?.focus();
16803
+ if (focusedRestore) $wfLanding.querySelector(`[data-wf-restore="${CSS.escape(focusedRestore)}"]:not(:disabled)`)?.focus();
16804
+ if (focusedRestored) $wfLanding.querySelector(`[data-wf-restored="${CSS.escape(focusedRestored)}"]`)?.focus();
15622
16805
  if (keepCaret) $wfLanding.querySelector('#wf-landing-search')?.focus();
15623
16806
  applyWorkflowsLandingSearch(keepCaret);
15624
16807
  if (clearFocused) $wfLanding.querySelector('#wf-search-clear')?.focus(); // it only exists once the filter ran
@@ -15634,7 +16817,7 @@
15634
16817
  const terms = wfLandingQuery.trim().toLowerCase().split(/\s+/).filter(Boolean);
15635
16818
  let shownAll = 0;
15636
16819
  for (const grid of $wfLanding.querySelectorAll('.ws-grid')) {
15637
- const cards = grid.querySelectorAll('.wf-card[data-wf-id], .wf-card[data-wf-draft]');
16820
+ const cards = grid.querySelectorAll('.wf-card[data-wf-id], .wf-card[data-wf-draft], .wf-card[data-wf-archived], .wf-card[data-wf-restored]');
15638
16821
  let shown = 0;
15639
16822
  for (const card of cards) {
15640
16823
  const hay = Array.from(card.querySelectorAll('.ws-name, .ws-meta:not(.wf-card-nodes)'), (el) => el.textContent).join(' ').toLowerCase();
@@ -15671,7 +16854,11 @@
15671
16854
  landingOpening = true;
15672
16855
  // Leave the landing once the workflow has loaded, so the previous one never flashes up in between; a failed
15673
16856
  // load keeps the landing and reports why.
15674
- loadApp(id).then(() => showWorkflowsLanding(false)).catch(reportErr).finally(() => { landingOpening = false; });
16857
+ const loading = loadApp(id);
16858
+ const ticket = selectionTicket;
16859
+ loading.then(() => {
16860
+ if (ticket === selectionTicket && currentId === id) showWorkflowsLanding(false);
16861
+ }).catch(reportErr).finally(() => { landingOpening = false; });
15675
16862
  }
15676
16863
 
15677
16864
  // ── Draft workflows (#1890 PR 3b-0) ──────────────────────────────────────────────
@@ -15806,7 +16993,7 @@
15806
16993
  // #1949: the same Archive the published workflow has in the picker — same command, same confirm — so a draft
15807
16994
  // someone no longer wants can leave the Workflows page from its own view. Quiet (not primary): it is the exit,
15808
16995
  // not the next step.
15809
- + `<div class="wf-draft-actions wf-draft-exit"><button type="button" class="wf-draft-archive" id="wf-draft-archive" data-command-id="workflow.archive#${esc(d.workflowId)}" data-command-instance-label="${esc(d.displayName)}" data-tip="Hide this workflow from the Workflows page. Its files stay on this computer.">Archive</button></div>`
16996
+ + `<div class="wf-draft-actions wf-draft-exit"><button type="button" class="wf-draft-archive" id="wf-draft-archive" data-command-id="workflow.archive#${esc(d.workflowId)}" data-command-instance-label="${esc(d.displayName)}" data-tip="Hide this workflow from the Workflows page. Its files stay on this computer. Restore it from Archived.">Archive</button></div>`
15810
16997
  + `<div class="sr-only" role="status" aria-live="polite" id="wf-draft-status">${d.compiling ? 'Compiling…' : ''}</div>`
15811
16998
  + `</div>`;
15812
16999
  }
@@ -15887,6 +17074,16 @@
15887
17074
 
15888
17075
  if ($wfLanding) {
15889
17076
  $wfLanding.addEventListener('click', (event) => {
17077
+ const restore = event.target.closest('[data-wf-restore]');
17078
+ if (restore) {
17079
+ if (!restore.disabled) {
17080
+ // Canvas panning cancels native mouse focus. This activated control owns the return
17081
+ // focus; restoreOwnedWorkflow still yields it if the person moves elsewhere while waiting.
17082
+ restore.focus();
17083
+ void restoreOwnedWorkflow(restore.dataset.wfRestore);
17084
+ }
17085
+ return;
17086
+ }
15890
17087
  if (event.target.closest('[data-wf-new]')) { requestNewWorkflow(); return; }
15891
17088
  // Clearing empties the message the button sits in, so focus goes back to the search box.
15892
17089
  if (event.target.closest('#wf-search-clear')) { setWorkflowsLandingQuery(''); $wfLanding.querySelector('#wf-landing-search')?.focus(); return; }
@@ -15919,6 +17116,8 @@
15919
17116
 
15920
17117
  window.flolessBridge = {
15921
17118
  api,
17119
+ /** #2046: the ≡ menu's New workflow, opened from a Guide suggestion with its name filled in. */
17120
+ newWorkflow: (prefill) => requestNewWorkflow(prefill),
15922
17121
  requestScopeLabel(projectId) {
15923
17122
  return wsRequestScope?.kind === 'project' && wsRequestScope.project === projectId
15924
17123
  ? wsRequestScope.label : null;