@floless/app 0.126.3 → 0.126.5

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
@@ -16,6 +16,9 @@
16
16
  const $simBtn = document.getElementById('sim-btn');
17
17
  const $runState = document.getElementById('run-state');
18
18
  const $notesStrip = document.getElementById('notes-strip');
19
+ const $kbInformed = document.getElementById('kb-informed');
20
+ const $kbInformedPages = document.getElementById('kb-informed-pages');
21
+ const $kbDriftChip = document.getElementById('kb-drift-chip');
19
22
  const $reportModal = document.getElementById('report-modal');
20
23
  const $reportFrame = document.getElementById('report-frame');
21
24
  const $reportFrame3d = document.getElementById('report-frame-3d');
@@ -627,6 +630,72 @@
627
630
  }
628
631
  }
629
632
 
633
+ // ── "Informed by" — which knowledge built this workflow ────────────────────
634
+ //
635
+ // WORKFLOW-LEVEL, not per node. The pin the server keeps is app-scoped — a project, a knowledge
636
+ // generation, and the pages that were cited — with no node granularity, so rendering it under each
637
+ // node's Description would repeat one identical list down the Inspect panel while implying each
638
+ // node had its own sources. Attribution that fine needs the AI to report which page informed which
639
+ // node, which is a different record than the one that exists. (Decided with Pawel, 2026-08-10.)
640
+ //
641
+ // Never blocks Run, and that is deliberate: the determinism gate is the `.flo`↔`.lock` pair, and
642
+ // treating stale knowledge as the same class of problem would make a workflow that runs perfectly
643
+ // well look broken. Say it, don't block it.
644
+ let kbPinRead = 0;
645
+
646
+ /** Paint the strip, or hide it outright. No pin → nothing at all: not a disabled control, not an
647
+ * "unknown" row. Most workflows were never built against a knowledge base, and that is ordinary. */
648
+ function paintKbInformed(pin, drift) {
649
+ if (!$kbInformed) return;
650
+ if (!pin || !pin.pages || !pin.pages.length) {
651
+ $kbInformed.hidden = true;
652
+ $kbInformedPages.innerHTML = '';
653
+ delete $kbInformed.dataset.kbProject;
654
+ return;
655
+ }
656
+ // The pin's own project, so the click handler opens the KB that actually informed this workflow
657
+ // rather than whichever project Workspaces happens to have open.
658
+ $kbInformed.dataset.kbProject = String(pin.projectId || '');
659
+ // Every value here is file-derived (a wiki page's own slug and title) and lands in innerHTML, so
660
+ // it is escaped exactly like the node/agent strings in buildAgentEntry above.
661
+ $kbInformedPages.innerHTML = pin.pages.map((pg, i) => {
662
+ const slug = String(pg.slug || '');
663
+ // The TITLE reads as a sentence; the slug reads as a filename. The slug still rides the tooltip
664
+ // so a user can trace the citation back to the page as the KB names it. `|| slug` rather than a
665
+ // humanizer: a title is always present in a well-formed pin, and inventing prose from a slug
666
+ // would be guessing at the one place this feature must not guess.
667
+ const label = String(pg.title || slug);
668
+ const sep = i ? '<span class="kb-informed-sep">·</span>' : '';
669
+ return `${sep}<button type="button" class="kb-page-link" data-kb-slug="${escapeAttr(slug)}"`
670
+ + ` data-tip="Open “${escapeAttr(label)}” (${escapeAttr(slug)}) in the Knowledge Base"`
671
+ // The visible label alone does not say this leaves Workflows, and `data-tip` is a purely
672
+ // VISUAL tooltip (web/app.js wires no aria-describedby), so the full action goes in an
673
+ // aria-label or a screen-reader user loses it entirely.
674
+ + ` aria-label="Open ${escapeAttr(label)} in the Knowledge Base">`
675
+ + `<span class="kb-page-ico" aria-hidden="true">↗</span>${escapeHtml(label)}</button>`;
676
+ }).join('');
677
+ $kbDriftChip.hidden = !drift;
678
+ $kbInformed.hidden = false;
679
+ }
680
+
681
+ /** Read the pin for `id`. Guarded by a read counter, not by the response: the user can switch
682
+ * workflows while this is in flight, and a late answer must never paint another workflow's
683
+ * provenance over the one now on screen. A failed read hides the strip rather than guessing. */
684
+ async function refreshKbInformed(id) {
685
+ const read = ++kbPinRead;
686
+ paintKbInformed(null, false); // clear the previous workflow's row before the await, not after
687
+ if (!id) return;
688
+ try {
689
+ const r = await fetch(`/api/kb-pin/${encodeURIComponent(id)}`, { cache: 'no-store' });
690
+ const d = await r.json();
691
+ if (read !== kbPinRead || currentId !== id) return; // superseded — a newer workflow owns the strip
692
+ if (r.ok && d.ok) paintKbInformed(d.pin, !!d.drift);
693
+ } catch {
694
+ /* Offline or a route that isn't there: provenance is additive, so its absence is not an error
695
+ the user needs told about. The strip stays hidden, cleared above. */
696
+ }
697
+ }
698
+
630
699
  function paintModes() {
631
700
  document.querySelectorAll('.agent-card').forEach((card) => {
632
701
  const a = AGENTS[card.dataset.agentId];
@@ -997,6 +1066,7 @@
997
1066
  seedAppInputs(app);
998
1067
  markSpecialNodes();
999
1068
  paintGate(app);
1069
+ refreshKbInformed(id); // detached: provenance is additive, and must not hold up the canvas paint
1000
1070
  paintBeacon(app); // pulse "Start here" while this workflow is new to the user
1001
1071
  refreshDirtyIndicator(); // clean app → dot off; switched back to a dirty one → dot on
1002
1072
  renderWfUpdatePill(); // show the "↑ Update to vX" pill when THIS app has a newer published version
@@ -1033,6 +1103,18 @@
1033
1103
  return waitForPublicationAvailabilityIdle();
1034
1104
  }
1035
1105
 
1106
+ // Workspaces keeps the existing workflow selected underneath its project surface. Returning to
1107
+ // Workflows is therefore a re-open of that workflow: refresh both its publication state and the
1108
+ // additive provenance strip, so a KB organize that happened while the project was open cannot
1109
+ // leave a stale "Informed by" answer on the canvas.
1110
+ function refreshCurrentWorkflow() {
1111
+ const id = currentId;
1112
+ return Promise.all([
1113
+ refreshCurrentWorkflowAvailability(),
1114
+ refreshKbInformed(id),
1115
+ ]).then(() => {});
1116
+ }
1117
+
1036
1118
  async function loadApps() {
1037
1119
  // …and mean it: the trigger said "loading…" but stayed CLICKABLE, so a click during the fetch
1038
1120
  // opened the popover onto an empty #wf-list — the exact "picker opens and stays empty, it never
@@ -1060,6 +1142,8 @@
1060
1142
  // don't also raise the warn-coloured notes strip (it's for real compiler
1061
1143
  // notes, and a yellow band for a neutral first-run reads as a false alarm).
1062
1144
  $notesStrip.hidden = true;
1145
+ currentId = null;
1146
+ refreshKbInformed(null); // invalidate any in-flight app read and remove workflow-only provenance
1063
1147
  $runBtn.disabled = true;
1064
1148
  $compileBtn.disabled = true;
1065
1149
  if ($menuBakeItem) $menuBakeItem.disabled = true;
@@ -6506,6 +6590,10 @@
6506
6590
  if (typeof m.appId !== 'string' || m.appId === currentId) {
6507
6591
  refreshCurrentWorkflowAvailability().catch(reportErr);
6508
6592
  }
6593
+ } else if (m.type === 'kb-pin-changed' && m.id === currentId && !inWorkspacesMode()) {
6594
+ // The event is only an invalidation. Re-read the workflow-scoped pin so the server remains
6595
+ // the source of truth; refresh clears first and its epoch rejects any older response.
6596
+ refreshKbInformed(currentId);
6509
6597
  } else if (m.type === 'trace' && m.id === currentId) {
6510
6598
  pushTrace(m.event);
6511
6599
  if (state.currentTab === 'execution') renderInspect();
@@ -6548,6 +6636,7 @@
6548
6636
  const isUpdate = m.action === 'update';
6549
6637
  installingIds.delete(m.id);
6550
6638
  if (m.ok) {
6639
+ if (isUpdate) agentUpdateFailures.delete(m.id);
6551
6640
  if (isUpdate) {
6552
6641
  showToast(`Updated “${m.id}”`, 'ok');
6553
6642
  } else {
@@ -6587,7 +6676,12 @@
6587
6676
  importFailedOfferRetry();
6588
6677
  });
6589
6678
  } else {
6590
- showToast(`${isUpdate ? 'Update' : 'Install'} failed: ${String(m.error || '').slice(0, 80)}`, 'err');
6679
+ if (isUpdate) {
6680
+ agentUpdateFailures.set(m.id, String(m.error || `Could not update ${m.id}.`));
6681
+ showToast(`Could not update ${m.id} — see the card for details.`, 'err');
6682
+ } else {
6683
+ showToast(`Could not install ${m.id}: ${String(m.error || '').slice(0, 120)}`, 'err');
6684
+ }
6591
6685
  if (_importFailedVersions.has(m.id)) {
6592
6686
  // A failed update is NOT the "nothing to update" answer — say which it was, and re-arm the
6593
6687
  // row's own button so the user can try that one again without redoing the others.
@@ -6881,6 +6975,155 @@
6881
6975
  ? ['Nothing to copy — this request has no instruction', 'err']
6882
6976
  : ['copy failed', 'err']);
6883
6977
 
6978
+ // ── Headless runs (#571 slice 3) ────────────────────────────────────────────
6979
+ // floless starting the user's OWN terminal AI on a queued request, instead of them pasting it.
6980
+ // The browser holds NO copy of which request types may run: every row arrives carrying `canRun`
6981
+ // and `runWhy` from the server's one policy table, so the two cannot drift and a type this build
6982
+ // has never heard of is answered fail-closed at the source rather than guessed at here.
6983
+ //
6984
+ // Detection is a workspace-level fact (which CLIs exist) fetched per surface-open and cached; the
6985
+ // FOLDER is per project, so anything that needs it re-reads with the project key rather than
6986
+ // trusting this. Server-side detection spawns nothing — it is statSync work — so an open is cheap.
6987
+ let headlessInfo = null;
6988
+ async function refreshHeadless() {
6989
+ // A detection failure HIDES the feature rather than leaving a button that cannot work. There is
6990
+ // no honest middle: without the runtime list we do not know that anything is installed.
6991
+ try { headlessInfo = await api('/api/terminal-runtimes'); }
6992
+ catch { headlessInfo = null; }
6993
+ return headlessInfo;
6994
+ }
6995
+ const headlessRuntimes = () => (headlessInfo && Array.isArray(headlessInfo.runtimes) ? headlessInfo.runtimes : []);
6996
+ /** Zero runtimes found ⇒ no run affordance anywhere (§E4). Hidden, never disabled. */
6997
+ const headlessReady = () => headlessRuntimes().some((r) => r && r.state === 'found');
6998
+ const runtimeLabel = (id) => {
6999
+ const m = headlessRuntimes().find((r) => r && r.id === id);
7000
+ return (m && m.label) || String(id || 'your terminal AI');
7001
+ };
7002
+ /** Which project's folder a request runs in — the same key the server derives. */
7003
+ const runProjectKey = (r) => (r && (r.project || r.appId)) || null;
7004
+
7005
+ // How each run state reads to a human. Deliberately absent: `succeeded` — the success path DELETES
7006
+ // the request, so no row can ever display it; success IS the row disappearing, exactly as it does
7007
+ // when a human pastes the prompt themselves. An unmapped state falls through to its own name in
7008
+ // the muted tier rather than rendering blank, which is the honest miss-path for a newer server.
7009
+ const RUN_VIEW = {
7010
+ queued: { badge: 'Queued', cls: 'active', spin: true, note: (rt) => `Starting ${rt}.` },
7011
+ running: { badge: 'Running', cls: 'active', spin: true, note: (rt) => `${rt} is working on this. It clears itself when it’s done.` },
7012
+ 'needs-you': { badge: 'Needs you', cls: 'warn', note: () => 'Your terminal AI stopped because this needs a decision from you:' },
7013
+ interrupted: { badge: 'Interrupted', cls: 'warn', note: () => 'floless restarted while this was running, so the run stopped. The request is still queued — pick the session up in your terminal, or run it again.' },
7014
+ // Never the identifier `contract-violation` — the user did not write the contract.
7015
+ 'contract-violation': { badge: 'Unverified', cls: 'err', note: () => 'The run ended without a final answer floless could read, so it may or may not have changed anything. Check in your terminal before running it again.' },
7016
+ 'exited-unresolved': { badge: 'Finished, unconfirmed', cls: 'warn', note: () => 'The run ended cleanly but left this request queued, so floless can’t say the work was done.' },
7017
+ failed: { badge: 'Failed', cls: 'err', note: () => 'The run failed.' },
7018
+ stopped: { badge: 'Stopped', cls: 'muted', note: () => 'You stopped this run.' },
7019
+ };
7020
+
7021
+ function runStatusHtml(run) {
7022
+ if (!run || !run.state) return '';
7023
+ const v = RUN_VIEW[run.state] || { badge: String(run.state), cls: 'muted', note: () => '' };
7024
+ const rt = runtimeLabel(run.runtime);
7025
+ const note = v.note(rt);
7026
+ return `
7027
+ <div class="req-run-status">
7028
+ <div class="req-run-head">
7029
+ ${v.spin ? '<span class="rtn-spinner" aria-hidden="true"></span>' : ''}
7030
+ <span class="req-run-badge req-run-badge-${v.cls}">${escapeHtml(v.badge)}</span>
7031
+ </div>
7032
+ ${note ? `<p class="req-run-note">${escapeHtml(note)}</p>` : ''}
7033
+ ${run.question ? `<p class="req-run-question">${escapeHtml(run.question)}</p>` : ''}
7034
+ ${run.cwd ? `<div class="req-run-where">${escapeHtml(rt)} · ${escapeHtml(run.cwd)}</div>` : ''}
7035
+ ${run.lastOutput ? `<details class="req-run-output"><summary>Show what it printed</summary><pre>${escapeHtml(run.lastOutput)}</pre></details>` : ''}
7036
+ </div>`;
7037
+ }
7038
+
7039
+ // Start a run. `runtime` is the §E4 per-run override — omitted, the server resolves the default.
7040
+ async function runRequestHeadless(req, runtime) {
7041
+ try {
7042
+ const res = await api(`/api/requests/${encodeURIComponent(req.id)}/run`, {
7043
+ method: 'POST', body: JSON.stringify(runtime ? { runtime } : {}),
7044
+ });
7045
+ showToast(`Running in ${runtimeLabel((res.run && res.run.runtime) || runtime)} — the row updates as it goes`, 'ok');
7046
+ await loadRequests();
7047
+ renderRequests();
7048
+ return res;
7049
+ } catch (err) {
7050
+ const code = err && err.body && err.body.code;
7051
+ // No folder yet (or one that has since gone) is not an error to report — it is the one
7052
+ // question the user has not been asked. Ask it, pre-loaded with the server's own sentence.
7053
+ if (code === 'no-folder' || code === 'bad-folder') { await openRunOptions(req, err.body.error); return null; }
7054
+ showToast((err && err.message) || 'could not start the run', 'err');
7055
+ return null;
7056
+ }
7057
+ }
7058
+
7059
+ async function stopRequestRun(req) {
7060
+ try {
7061
+ await api(`/api/requests/${encodeURIComponent(req.id)}/run/stop`, { method: 'POST' });
7062
+ await loadRequests();
7063
+ renderRequests();
7064
+ } catch (e) { reportErr(e); }
7065
+ }
7066
+
7067
+ /**
7068
+ * Folder + which terminal AI, then run. Reached from the split button's ▾ and automatically
7069
+ * whenever a run is refused for want of a usable folder.
7070
+ *
7071
+ * A LOOP, not recursion, because the refusal path can repeat: §B says an unusable folder is a
7072
+ * MODAL, not a toast, so a bad path re-opens this same form carrying the server's whole sentence
7073
+ * and the value the user typed — never a toast they have to remember while retyping.
7074
+ */
7075
+ async function openRunOptions(req, problem) {
7076
+ const key = runProjectKey(req);
7077
+ let info;
7078
+ try { info = await api(`/api/terminal-runtimes${key ? `?project=${encodeURIComponent(key)}` : ''}`); }
7079
+ catch (e) { reportErr(e); return null; }
7080
+ const found = (info.runtimes || []).filter((r) => r && r.state === 'found');
7081
+ if (!found.length) { showToast('No terminal AI found on this machine.', 'warn'); return null; }
7082
+ let folder = info.folder || '';
7083
+ let sub = problem || '';
7084
+ // Tracked SEPARATELY from `sub`, because the two are different messages. `problem` on the first
7085
+ // open is "you haven't chosen a folder yet" — nothing was refused, and titling that
7086
+ // "That folder won't work" blames the user for a folder they never typed.
7087
+ let refused = false;
7088
+ for (;;) {
7089
+ const res = await formModal({
7090
+ // The TITLE carries the refusal too, not just the sub. Both are re-set per open, so this
7091
+ // leaks nothing to the next caller — and without it the only thing that changes on a bad
7092
+ // folder is one line of muted grey, in the same tier as the explanation it replaced.
7093
+ title: refused ? 'That folder won’t work' : 'Run this for me',
7094
+ sub: sub || 'floless starts your own terminal AI in a folder you choose and hands it this request. It runs on your machine, with your login.',
7095
+ fields: [
7096
+ {
7097
+ name: 'folder', label: 'Folder to work in', value: folder,
7098
+ placeholder: 'C:\\Repos\\my-project',
7099
+ },
7100
+ {
7101
+ name: 'runtime', label: 'Which terminal AI', type: 'select', value: info.provider || found[0].id,
7102
+ options: found.map((r) => ({ value: r.id, label: r.label, meta: r.command })),
7103
+ },
7104
+ ],
7105
+ // §D2, stated once at the moment the user picks the folder — the point at which they still
7106
+ // have the context to judge. NOT re-shown on every run, which only trains dismissal.
7107
+ footnote: 'Your terminal AI reads and edits this folder unattended, including any instructions it finds in files there. Point it at a folder you trust — and open your own terminal in the same folder later to pick the session up.',
7108
+ okLabel: 'Run it',
7109
+ });
7110
+ if (!res) return null;
7111
+ folder = String(res.folder || '').trim();
7112
+ try {
7113
+ // Always re-nominated, even unchanged: it is also the only re-validation that the folder is
7114
+ // still there and still writable at the moment the user asks for a run.
7115
+ await api('/api/terminal-runtimes/folder', {
7116
+ method: 'PUT', body: JSON.stringify({ project: key, folder }),
7117
+ });
7118
+ } catch (e) {
7119
+ sub = (e && e.message) || 'That folder can’t be used.';
7120
+ refused = true;
7121
+ continue;
7122
+ }
7123
+ return runRequestHeadless(req, res.runtime);
7124
+ }
7125
+ }
7126
+
6884
7127
  let requestHelpReq = null;
6885
7128
  let requestHelpReturnFocus = null;
6886
7129
  function closeRequestHelp({ restoreFocus = true } = {}) {
@@ -6917,9 +7160,61 @@
6917
7160
  ? 'The web UI queues the drawing read; your terminal agent applies it and reports progress back here.'
6918
7161
  : 'The web UI queues the request; your terminal agent applies it and reports progress back here.';
6919
7162
  if ($copy) $copy.hidden = copied;
7163
+ // Back to the "not started" face on every open — the previous request's run status must never
7164
+ // be the first thing the next one shows.
7165
+ setRequestHelpRunning(null);
6920
7166
  showModal($m);
6921
7167
  const shell = $m.querySelector('.modal.request-help');
6922
7168
  if (shell) { try { shell.focus(); } catch { /* not focusable */ } }
7169
+ // Detection is a fetch, and this modal is opened synchronously by the caller. Reveal the split
7170
+ // when the answer lands rather than blocking the modal on it — and only if THIS request is
7171
+ // still the one on screen, since a second queue can land while the first fetch is in flight.
7172
+ refreshHeadless().then(() => { if (requestHelpReq === req) syncRequestHelpRun(); });
7173
+ syncRequestHelpRun();
7174
+ }
7175
+
7176
+ /** Show the run split only when this request's type can run AND a runtime exists (§E1/§E4). */
7177
+ function syncRequestHelpRun() {
7178
+ const $split = document.getElementById('request-help-run-split');
7179
+ const $open = document.getElementById('request-help-open');
7180
+ if (!$split || !$open) return;
7181
+ const can = !!(requestHelpReq && requestHelpReq.canRun && headlessReady());
7182
+ $split.hidden = !can;
7183
+ // Exactly one primary in the row: Run takes it when it is there, Open Requests reclaims it
7184
+ // when it is not — a modal with no emphasized action reads as unfinished.
7185
+ $open.classList.toggle('primary', !can);
7186
+ }
7187
+
7188
+ /**
7189
+ * Swap the modal's three "what you must do" steps for what floless is doing instead.
7190
+ *
7191
+ * The steps are REPLACED, not relabelled: after "Run it for me" there is no paste to describe,
7192
+ * and a rewritten step 2 would still be a numbered instruction for the user.
7193
+ */
7194
+ function setRequestHelpRunning(run) {
7195
+ const $steps = document.getElementById('request-help-steps');
7196
+ const $status = document.getElementById('request-help-run-status');
7197
+ const $title = document.getElementById('request-help-run-title');
7198
+ const $split = document.getElementById('request-help-run-split');
7199
+ const $note = document.getElementById('request-help-note');
7200
+ if (!$steps || !$status) return;
7201
+ $steps.hidden = !!run;
7202
+ $status.hidden = !run;
7203
+ if (!run) {
7204
+ // Cleared, not merely hidden. Leaving the previous request's "Running in Claude Code · <cwd>"
7205
+ // in the DOM means one CSS slip away from the next request opening on somebody else's run.
7206
+ if ($title) $title.textContent = '';
7207
+ return;
7208
+ }
7209
+ if ($split) $split.hidden = true; // it started; there is nothing left to start
7210
+ // …which leaves the row with no emphasized action, so Open Requests takes the primary back.
7211
+ // `syncRequestHelpRun` can't do this: it would re-show the split it just retired.
7212
+ const $open = document.getElementById('request-help-open');
7213
+ if ($open) $open.classList.add('primary');
7214
+ if ($title) {
7215
+ $title.innerHTML = `Running in <strong>${escapeHtml(runtimeLabel(run.runtime))}</strong>${run.cwd ? ` · <code>${escapeHtml(run.cwd)}</code>` : ''}`;
7216
+ }
7217
+ if ($note) $note.textContent = 'Your terminal AI does the work and clears the request itself. Nothing was sent anywhere — this is the same CLI you would have opened yourself.';
6923
7218
  }
6924
7219
 
6925
7220
  async function useTemplate(templateId) {
@@ -7227,6 +7522,12 @@
7227
7522
  if ($showAll) $showAll.onclick = () => setRequestScopeAll(true);
7228
7523
  return;
7229
7524
  }
7525
+ // Whether a non-runnable row explains itself, decided ONCE per paint over what is actually on
7526
+ // screen. A user who has never seen a ▶ has nothing to wonder about, so a queue of nothing but
7527
+ // guides stays quiet; the moment a runnable row sits beside a `guide`, the guide says why it
7528
+ // has no button. Derived from this paint — deliberately not a stored "has run before" flag,
7529
+ // which would make the same list read differently for two people.
7530
+ const anyRunnable = headlessReady() && shown.some((r) => r && r.canRun);
7230
7531
  $list.innerHTML = shown.map((r) => {
7231
7532
  const label = requestLabel(r);
7232
7533
  const badgeCls = r.type === 'tweak' || r.type === 'ui-customize' || r.type === 'rebake' || r.type === 'revision-read' || r.type === 'knowledge-organize' || r.type === 'knowledge-adjust' || r.type === 'tweak-contract' ? 'req-type req-type-tweak' : 'req-type';
@@ -7244,23 +7545,54 @@
7244
7545
  // A knowledge-organize is resolved by its own finish/fail lifecycle POST. Offering a ✕ here
7245
7546
  // would let the user delete a request the terminal AI is mid-way through, 404-ing finish/fail
7246
7547
  // and stranding the organize lock until its stale timeout. Show why it can't be cleared instead.
7548
+ const run = r.run || null;
7549
+ const inFlight = !!run && (run.state === 'queued' || run.state === 'running');
7247
7550
  const lifecycleOwned = r.type === 'knowledge-organize';
7551
+ // ✕ goes away while a run is live, for the same reason it goes away on a knowledge-organize:
7552
+ // deleting the request out from under a working agent leaves it unable to clear its own work,
7553
+ // and the run then lands in `exited-unresolved` for a reason the user caused and cannot see.
7248
7554
  const del = lifecycleOwned
7249
7555
  ? '<span class="req-lifecycle" data-tip="This clears itself when your terminal AI finishes or fails the organize">finishing in your terminal</span>'
7250
- : `<button class="req-del" data-id="${escapeAttr(r.id)}" data-tip="Clear this request">×</button>`;
7556
+ : inFlight
7557
+ ? '<span class="req-lifecycle" data-tip="Stop the run first — clearing it now would leave the agent working on a request that no longer exists">running</span>'
7558
+ : `<button class="req-del" data-id="${escapeAttr(r.id)}" data-tip="Clear this request">×</button>`;
7559
+ // A parked run gets NO re-run: it is waiting on a decision only the human can make, and a
7560
+ // second headless attempt would either abandon that question or look like floless answering
7561
+ // it. Every other terminal state has nothing pending, so running again is a fair offer.
7562
+ const canRunNow = headlessReady() && r.canRun && !inFlight && !(run && run.state === 'needs-you');
7563
+ const runBtn = inFlight
7564
+ ? `<button class="req-stop" data-id="${escapeAttr(r.id)}" data-tip="Stop this run">■</button>`
7565
+ : canRunNow
7566
+ ? `<button class="req-run" data-id="${escapeAttr(r.id)}" data-tip="${run ? 'Run it again in your terminal AI, headless' : 'Let floless run this in your terminal AI'}">▶</button>`
7567
+ : '';
7251
7568
  return `
7252
7569
  <div class="req-item" data-id="${escapeAttr(r.id)}">
7253
7570
  <div class="req-info">
7254
7571
  <div class="req-head"><span class="${badgeCls}">${label}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, requestQuery)}</span>` : ''}${time}</div>
7255
7572
  <div class="req-instruction">${highlightQuery(instructionFor(r), requestQuery) || 'This request has no instruction, so it can’t be handed to your terminal AI. Clear it and queue it again.'}</div>
7256
7573
  ${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>` : ''}
7574
+ ${runStatusHtml(run)}
7575
+ ${!r.canRun && r.runWhy && anyRunnable ? `<div class="req-why-not">Runs only from your terminal — ${escapeHtml(r.runWhy)}</div>` : ''}
7257
7576
  </div>
7258
7577
  <div class="req-actions">
7578
+ ${runBtn}
7259
7579
  <button class="req-copy" data-id="${escapeAttr(r.id)}" data-tip="Copy this instruction">⧉</button>
7260
7580
  ${del}
7261
7581
  </div>
7262
7582
  </div>`;
7263
7583
  }).join('');
7584
+ $list.querySelectorAll('.req-run').forEach((b) => {
7585
+ b.onclick = () => {
7586
+ const r = pendingRequests.find((x) => x.id === b.dataset.id);
7587
+ if (r) void runRequestHeadless(r);
7588
+ };
7589
+ });
7590
+ $list.querySelectorAll('.req-stop').forEach((b) => {
7591
+ b.onclick = () => {
7592
+ const r = pendingRequests.find((x) => x.id === b.dataset.id);
7593
+ if (r) void stopRequestRun(r);
7594
+ };
7595
+ });
7264
7596
  $list.querySelectorAll('.req-copy').forEach((b) => {
7265
7597
  b.onclick = async () => {
7266
7598
  const r = pendingRequests.find((x) => x.id === b.dataset.id);
@@ -7335,7 +7667,10 @@
7335
7667
  // Scroll only: the flash belongs to the authoritative paint below, or the cached one would flash a
7336
7668
  // row the refresh is about to replace.
7337
7669
  revealRequestRow(targetId, true /* scrollOnly */);
7338
- await loadRequests();
7670
+ // Detection rides ALONGSIDE the queue fetch, never in front of it: whether a ▶ is offered must
7671
+ // not be able to delay the list itself, and a detection that fails simply leaves the rows
7672
+ // button-less rather than leaving the window empty.
7673
+ await Promise.all([loadRequests(), refreshHeadless()]);
7339
7674
  // NOTHING here may touch requestScopeAll. Scoping the window to what you have open is a
7340
7675
  // deliberate decision (#633), and revealing a row is not a licence to override it: a reveal that
7341
7676
  // widened would answer a different question than the one asked, and the destructive verb is
@@ -7533,6 +7868,10 @@
7533
7868
  // not disabled, when up to date. A pull in flight shows a spinner instead.
7534
7869
  const latest = availableLoaded ? latestVersionFor(a.id) : null;
7535
7870
  const canUpdate = !!latest && cmpVer(latest, a.version) > 0;
7871
+ const failure = agentUpdateFailures.get(a.id);
7872
+ const failureHtml = failure
7873
+ ? `<p class="lib-update-error"><strong>Update stopped.</strong> ${escapeHtml(failure)} <button class="lib-update" data-update="${id}" aria-label="Retry update for ${id}" data-tip="Retry update for ${id}">Retry</button></p>`
7874
+ : '';
7536
7875
  const updateBtn = installingIds.has(a.id)
7537
7876
  ? `<button class="lib-update" aria-busy="true" aria-label="Updating ${escapeAttr(a.id)}…" data-tip="Downloading update from the registry — this can take a minute"><span class="rtn-spinner"></span></button>`
7538
7877
  : canUpdate
@@ -7550,6 +7889,7 @@
7550
7889
  <button class="lib-fav" data-expand="${id}" data-tip="Show commands">⌄</button>
7551
7890
  </div>
7552
7891
  </div>
7892
+ ${failureHtml}
7553
7893
  <div class="lib-commands" id="cmds-${id}" hidden></div>
7554
7894
  </div>`;
7555
7895
  }).join('') || '<div class="empty-state">No agents match.</div>';
@@ -7629,6 +7969,10 @@
7629
7969
  let availableUnsupported = false; // CLI too old to know `agent catalog`
7630
7970
  let libTab = 'installed';
7631
7971
  const installingIds = new Set(); // ids with an install in flight (server runs it async)
7972
+ // A failed background update must stay visible on its originating card after
7973
+ // renderLibrary() restores the button. A toast alone disappears before someone
7974
+ // can read the reason or decide whether retrying is appropriate.
7975
+ const agentUpdateFailures = new Map(); // id -> safe, user-facing failure reason
7632
7976
 
7633
7977
  async function loadAvailableAgents() {
7634
7978
  const { agents, unsupported } = await api('/api/agents/available');
@@ -7769,6 +8113,8 @@
7769
8113
  function updateAgent(id, btn, onStartError) {
7770
8114
  if (installingIds.has(id)) return; // already in flight (server dedupes too)
7771
8115
  installingIds.add(id);
8116
+ agentUpdateFailures.delete(id);
8117
+ if ($libModal && $libModal.classList.contains('show') && libTab === 'installed') renderLibrary();
7772
8118
  if (btn) { // immediate feedback before the next render
7773
8119
  btn.setAttribute('aria-busy', 'true');
7774
8120
  btn.setAttribute('aria-label', `Updating ${id}…`);
@@ -7831,8 +8177,95 @@
7831
8177
  $integrationsModal.classList.add('show');
7832
8178
  renderIntegrations();
7833
8179
  refreshIntegrations();
8180
+ refreshHeadless().then(renderRuntimeSection);
7834
8181
  };
7835
8182
 
8183
+ /**
8184
+ * Which terminal AIs are installed, which one headless runs use, and the folder they run in.
8185
+ *
8186
+ * Its own section rather than a card in the integrations grid: a detected CLI is not an OAuth
8187
+ * connection. There is no Connect, no expiry — and deliberately no "ready", because a signed-out
8188
+ * CLI resolves to a binary exactly like a working one. So `Installed` / `Not installed` are both
8189
+ * NEUTRAL: --ok green two rows under a real "Connected" badge would claim readiness floless has
8190
+ * not earned, and the first the user would hear of it is a run that dies on a login prompt.
8191
+ */
8192
+ function renderRuntimeSection() {
8193
+ const $sec = document.getElementById('int-runtimes-section');
8194
+ const $list = document.getElementById('int-runtimes');
8195
+ const $folder = document.getElementById('int-folder');
8196
+ if (!$sec || !$list || !$folder) return;
8197
+ const rts = headlessRuntimes();
8198
+ // Hidden entirely when detection failed — an empty "Headless runs" box explains nothing. When
8199
+ // detection SUCCEEDED and found nothing, the rows are the explanation (each carries its command).
8200
+ $sec.hidden = !rts.length;
8201
+ if (!rts.length) return;
8202
+ const active = headlessInfo && headlessInfo.provider;
8203
+ $list.innerHTML = rts.map((r) => {
8204
+ const found = r.state === 'found';
8205
+ const isDefault = found && r.id === active;
8206
+ return `
8207
+ <div class="int-rt${isDefault ? ' is-default' : ''}${found ? '' : ' is-missing'}">
8208
+ <div>
8209
+ <div class="int-rt-name">${escapeHtml(r.label)}${isDefault ? '<span class="int-rt-pill">Default</span>' : ''}</div>
8210
+ <div class="int-rt-blurb">${escapeHtml(r.blurb)} · <code>${escapeHtml(r.command)}</code></div>
8211
+ <div class="int-rt-where">${found
8212
+ ? `Found at ${escapeHtml(r.path || '')}`
8213
+ : `Not installed — floless looks for <code>${escapeHtml(r.command)}</code>`}</div>
8214
+ </div>
8215
+ <div class="int-rt-side">
8216
+ <span class="int-rt-badge">${found ? 'Installed' : 'Not installed'}</span>
8217
+ ${found && !isDefault ? `<button class="int-action" data-rt="${escapeAttr(r.id)}">Use this one</button>` : ''}
8218
+ </div>
8219
+ </div>`;
8220
+ }).join('');
8221
+ $list.querySelectorAll('[data-rt]').forEach((b) => {
8222
+ b.onclick = async () => {
8223
+ try {
8224
+ await api('/api/terminal-runtimes/provider', { method: 'PUT', body: JSON.stringify({ provider: b.dataset.rt }) });
8225
+ await refreshHeadless();
8226
+ renderRuntimeSection();
8227
+ showToast(`Headless runs will use ${runtimeLabel(b.dataset.rt)}`, 'ok');
8228
+ } catch (e) { reportErr(e); }
8229
+ };
8230
+ });
8231
+ const folder = headlessInfo && headlessInfo.folder;
8232
+ $folder.innerHTML = `
8233
+ <span>Runs in</span>
8234
+ <span class="int-folder-path${folder ? '' : ' is-unset'}"${folder ? ` data-tip="${escapeAttr(folder)}"` : ''}>${folder ? escapeHtml(folder) : 'not chosen yet — floless will ask the first time you run one'}</span>
8235
+ <button class="int-action" id="int-folder-set">${folder ? 'Change…' : 'Choose…'}</button>`;
8236
+ const $set = document.getElementById('int-folder-set');
8237
+ if ($set) $set.onclick = () => { void nominateDefaultFolder(); };
8238
+ }
8239
+
8240
+ /**
8241
+ * The workspace-level default folder. Per-project folders are nominated from the run itself,
8242
+ * where the user can see which request they are answering for.
8243
+ *
8244
+ * A refusal re-opens THIS form carrying the server's whole sentence — §B: an unusable folder is a
8245
+ * modal, not a toast. Same loop as `openRunOptions` for the same reason.
8246
+ */
8247
+ async function nominateDefaultFolder() {
8248
+ let folder = (headlessInfo && headlessInfo.folder) || '';
8249
+ let sub = '';
8250
+ for (;;) {
8251
+ const res = await formModal({
8252
+ title: sub ? 'That folder won’t work' : 'Folder for headless runs',
8253
+ sub: sub || 'Where floless starts your terminal AI when it runs a request for you. Individual projects can override this.',
8254
+ fields: [{ name: 'folder', label: 'Folder', value: folder, placeholder: 'C:\\Repos\\my-project' }],
8255
+ footnote: 'Your terminal AI reads and edits this folder unattended, including any instructions it finds in files there. Point it at a folder you trust — and open your own terminal in the same folder later to pick a session up.',
8256
+ okLabel: 'Save',
8257
+ });
8258
+ if (!res) return;
8259
+ folder = String(res.folder || '').trim();
8260
+ try {
8261
+ await api('/api/terminal-runtimes/folder', { method: 'PUT', body: JSON.stringify({ project: null, folder }) });
8262
+ } catch (e) { sub = (e && e.message) || 'That folder can’t be used.'; continue; }
8263
+ await refreshHeadless();
8264
+ renderRuntimeSection();
8265
+ return;
8266
+ }
8267
+ }
8268
+
7836
8269
  // Re-fetch live connection state from the local vault; re-render if the modal
7837
8270
  // is open. Called on open and whenever a credential file changes (SSE), so an
7838
8271
  // open window flips to Connected the moment `aware connect` writes the token.
@@ -8885,6 +9318,23 @@
8885
9318
  if (id && sig) saveNotesCollapsed(id, sig, $notesStrip.classList.contains('collapsed'));
8886
9319
  });
8887
9320
 
9321
+ // "Informed by" → open that page in the Knowledge Base. Delegated, since the row is rebuilt on
9322
+ // every workflow open. The viewer lives in workspaces.js's own closure, so this hands off through
9323
+ // the one seam it publishes — and degrades to a toast if that seam is absent, because the two files
9324
+ // are separate IIFEs and nothing guarantees load order at this callsite.
9325
+ if ($kbInformedPages) $kbInformedPages.addEventListener('click', (e) => {
9326
+ const btn = e.target.closest('[data-kb-slug]');
9327
+ if (!btn) return;
9328
+ const ws = window.flolessWorkspaces;
9329
+ if (!ws || typeof ws.openKnowledgePage !== 'function') {
9330
+ showToast('Open the project’s Knowledge step to read this page.', 'warn');
9331
+ return;
9332
+ }
9333
+ // The pin's OWN projectId, stashed on the row when it was painted — never a guess about which
9334
+ // project is "current" in the other mode.
9335
+ ws.openKnowledgePage($kbInformed.dataset.kbProject, btn.dataset.kbSlug);
9336
+ });
9337
+
8888
9338
  // Take over the menu/keyboard Save from app.js's demo stub: in the real app the
8889
9339
  // UI can't author the .flo (that's the terminal AI's job), so "Save" persists the
8890
9340
  // current workflow's input values locally. "Save to…" (demo .flo download) is
@@ -8965,6 +9415,21 @@
8965
9415
  if ($sub) $sub.textContent = 'Terminal instructions copied. Open the terminal agent and paste them there.';
8966
9416
  }
8967
9417
  };
9418
+ // ▶ runs with the resolved default; ▾ asks folder + which terminal AI first. Both leave the modal
9419
+ // OPEN on success and swap its steps for the run status — closing it would hide the one sentence
9420
+ // that says what floless just started on the user's behalf.
9421
+ const runFromHelpModal = async (withOptions) => {
9422
+ const req = requestHelpReq;
9423
+ if (!req) return;
9424
+ const res = withOptions ? await openRunOptions(req) : await runRequestHeadless(req);
9425
+ // Still the same request on screen? A slow spawn plus a fast second queue could otherwise
9426
+ // stamp this run's status onto somebody else's modal.
9427
+ if (res && res.run && requestHelpReq === req) setRequestHelpRunning(res.run);
9428
+ };
9429
+ const $requestHelpRun = document.getElementById('request-help-run');
9430
+ const $requestHelpRunOpts = document.getElementById('request-help-run-opts');
9431
+ if ($requestHelpRun) $requestHelpRun.onclick = () => { void runFromHelpModal(false); };
9432
+ if ($requestHelpRunOpts) $requestHelpRunOpts.onclick = () => { void runFromHelpModal(true); };
8968
9433
  if ($requestHelpModal) onBackdropDismiss($requestHelpModal, () => closeRequestHelp());
8969
9434
  document.addEventListener('keydown', (e) => {
8970
9435
  if (e.key === 'Escape' && $requestHelpModal && $requestHelpModal.classList.contains('show')) {
@@ -9173,7 +9638,12 @@
9173
9638
  if ($rm && $rm.classList.contains('show')) renderRequests();
9174
9639
  },
9175
9640
  refreshCurrentWorkflow() {
9176
- return refreshCurrentWorkflowAvailability();
9641
+ return refreshCurrentWorkflow();
9642
+ },
9643
+ // Workspaces is a replacement surface. Invalidate a pending workflow-pin read as soon as it
9644
+ // opens, rather than allowing a late answer to survive behind the project UI until the return.
9645
+ clearKbInformed() {
9646
+ refreshKbInformed(null);
9177
9647
  },
9178
9648
  copyToClipboard,
9179
9649
  instructionFor,