@floless/app 0.126.2 → 0.126.4

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
@@ -484,18 +484,66 @@
484
484
 
485
485
  // ── gate + notes UI ────────────────────────────────────────────────────────
486
486
 
487
- function paintGate(app) {
488
- // Task-language label (AEC users don't know "lock"/"drift"); the tooltip carries
489
- // the why + the Compile step.
490
- const labels = { ready: 'Ready to run', drift: 'Needs refresh', uncompiled: 'Not set up' };
491
- $runState.className = `run-state ${app.runState}`;
492
- $runState.textContent = labels[app.runState] || '';
493
- const stateTips = {
487
+ // Execution state has precedence over the compile gate. Keep this decision pure so every repaint
488
+ // path (including an async loadApp/paintGate landing mid-run) resolves the same visible status.
489
+ function runStatePresentation(runState, activity = {}) {
490
+ const gate = {
491
+ ready: { label: 'Ready to run', className: 'ready' },
492
+ drift: { label: 'Needs refresh', className: 'drift' },
493
+ uncompiled: { label: 'Not set up', className: 'uncompiled' },
494
+ };
495
+ const finiteRunning = !!(activity.reportRunning || activity.stateRunning);
496
+ if (activity.foregroundStopping || (activity.cancelRequested && finiteRunning)) {
497
+ return { label: 'Cancelling…', className: 'cancelling' };
498
+ }
499
+ if (activity.foregroundStarting) return { label: 'Starting live run…', className: 'running' };
500
+ if (activity.foregroundTrigger) return { label: 'Listening…', className: 'running' };
501
+ if (finiteRunning) {
502
+ return activity.simulating
503
+ ? { label: 'Simulating…', className: 'running' }
504
+ : { label: 'Running…', className: 'running' };
505
+ }
506
+ return gate[runState] || { label: '', className: '' };
507
+ }
508
+
509
+ let reportRunning = false;
510
+ let cancelRequested = false;
511
+ let runningSimulation = false;
512
+ let foregroundTrigger = null;
513
+ let foregroundStarting = false;
514
+ let foregroundStopping = false;
515
+
516
+ function paintRunState(app) {
517
+ const status = runStatePresentation(app.runState, {
518
+ reportRunning,
519
+ stateRunning: state.running,
520
+ simulating: runningSimulation,
521
+ foregroundStarting,
522
+ foregroundTrigger: !!foregroundTrigger,
523
+ foregroundStopping,
524
+ cancelRequested,
525
+ });
526
+ $runState.className = `run-state ${status.className}`;
527
+ $runState.textContent = status.label;
528
+ const gateTips = {
494
529
  ready: 'Ready to run.\nThis workflow was compiled from exactly the current .flo (the approved “lock” matches the source), so ▶ Run workflow is enabled.',
495
530
  drift: 'Needs refresh.\nThe .flo changed since the last Compile, so the approved lock is out of date and Run is blocked. Hit ⎙ Compile to re-approve it.',
496
531
  uncompiled: 'Not set up yet.\nThere is no approved lock for this workflow, so Run is blocked. Hit ⎙ Compile to freeze one — then ▶ Run workflow turns on.',
497
532
  };
498
- $runState.dataset.tip = stateTips[app.runState] || '';
533
+ const activeTips = {
534
+ 'Running…': 'The approved workflow is running against the live host.',
535
+ 'Simulating…': 'The workflow composition is being simulated without contacting the live host.',
536
+ 'Starting live run…': 'The live trigger session is starting.',
537
+ 'Listening…': 'The live trigger session is listening for the next host event.',
538
+ 'Cancelling…': 'The current run is being cancelled.',
539
+ };
540
+ $runState.dataset.tip = activeTips[status.label] || gateTips[app.runState] || '';
541
+ }
542
+
543
+ function paintGate(app) {
544
+ // Task-language label (AEC users don't know "lock"/"drift"); the tooltip carries
545
+ // the why + the Compile step.
546
+ paintRunState(app);
499
547
 
500
548
  // Keep Run disabled (and the header Stop shown) if a gate re-paint lands mid-run (#39) —
501
549
  // never let a re-render re-arm Run while a run is still in flight.
@@ -503,8 +551,8 @@
503
551
  // gate repaint mid-session (e.g. an fs-change → loadApp) must not re-arm Run or
504
552
  // hide the Stop while the watcher is still live. The in-modal Stop tracks the
505
553
  // same state (it's the reachable Stop while the Viewer covers the header one).
506
- $runBtn.disabled = !app.runnable || reportRunning || state.running || !!foregroundTrigger;
507
- if ($stopRunBtn) $stopRunBtn.hidden = !(reportRunning || state.running || foregroundTrigger);
554
+ $runBtn.disabled = !app.runnable || reportRunning || state.running || foregroundStarting || foregroundStopping || !!foregroundTrigger;
555
+ if ($stopRunBtn) $stopRunBtn.hidden = !(reportRunning || state.running || foregroundStopping || foregroundTrigger);
508
556
  if ($reportStop) $reportStop.hidden = !foregroundTrigger;
509
557
  $runBtn.dataset.tip = app.runnable
510
558
  ? 'Run the approved workflow'
@@ -2370,11 +2418,9 @@
2370
2418
  showToast('Inputs set: ' + badge, 'ok');
2371
2419
  }
2372
2420
 
2373
- let reportRunning = false;
2374
2421
  // Set when the user hits Stop. api() throws a bare Error on the cancelled
2375
2422
  // response (the {cancelled:true} flag is lost), so we read this flag in the
2376
2423
  // run catch blocks to show "cancelled" rather than a misleading "run failed".
2377
- let cancelRequested = false;
2378
2424
  // The most recent rendered report per app id: { nodeId, label, html }. Lets a
2379
2425
  // double-click LOAD the last result instantly instead of re-running.
2380
2426
  const lastReportByApp = new Map();
@@ -2387,7 +2433,6 @@
2387
2433
  // (reportRunning). Its session id is server-namespaced with this prefix so its SSE
2388
2434
  // snapshots route here, never to the Routines list.
2389
2435
  const FG_SESSION_PREFIX = '__run__:';
2390
- let foregroundTrigger = null;
2391
2436
 
2392
2437
  // Reflect run-in-flight state in the ALWAYS-VISIBLE header so a run is stoppable even
2393
2438
  // when the HTML Viewer modal is closed (#39). The header ■ Stop run appears for the whole
@@ -2397,14 +2442,15 @@
2397
2442
  // the user, on the modal's × tooltip, that closing leaves the run going (Stop is in the
2398
2443
  // header) — the canvas keeps showing progress (markCanvasRunning), by design.
2399
2444
  function syncRunControls() {
2400
- const running = reportRunning || state.running || !!foregroundTrigger;
2445
+ const running = reportRunning || state.running || foregroundStarting || foregroundStopping || !!foregroundTrigger;
2446
+ const stoppable = reportRunning || state.running || foregroundStopping || !!foregroundTrigger;
2401
2447
  // The in-modal Stop is reachable only for a live foreground session (the header
2402
2448
  // Stop is occluded by the report-modal backdrop). Show it while one is live.
2403
2449
  if ($reportStop) $reportStop.hidden = !foregroundTrigger;
2404
2450
  if ($stopRunBtn) {
2405
- $stopRunBtn.hidden = !running;
2451
+ $stopRunBtn.hidden = !stoppable;
2406
2452
  // Reset to a fresh, clickable Stop each run; stopRun() flips it to "Cancelling…".
2407
- if (running && !cancelRequested) { $stopRunBtn.disabled = false; $stopRunBtn.textContent = '■ Stop run'; }
2453
+ if (stoppable && !cancelRequested && !foregroundStopping) { $stopRunBtn.disabled = false; $stopRunBtn.textContent = '■ Stop run'; }
2408
2454
  }
2409
2455
  if (running) {
2410
2456
  $runBtn.disabled = true;
@@ -2412,6 +2458,8 @@
2412
2458
  const app = currentId && apps.get(currentId);
2413
2459
  $runBtn.disabled = !(app && app.runnable);
2414
2460
  }
2461
+ const app = currentId && apps.get(currentId);
2462
+ if (app) paintRunState(app);
2415
2463
  // Rely on the native `disabled` attribute for AT state (paintGate also flips it); a
2416
2464
  // separate aria-disabled would be redundant and could go stale on a gate re-paint.
2417
2465
  if ($reportClose) {
@@ -2432,17 +2480,22 @@
2432
2480
  // `stopped` SSE snapshot is a harmless no-op rather than a double-handle.
2433
2481
  if (foregroundTrigger) {
2434
2482
  const ft = foregroundTrigger;
2483
+ foregroundStopping = true;
2435
2484
  foregroundTrigger = null;
2436
2485
  if ($stopRunBtn) { $stopRunBtn.disabled = true; $stopRunBtn.textContent = 'Stopping…'; }
2437
2486
  const ovStop = document.querySelector('.overlay-stop');
2438
2487
  if (ovStop) { ovStop.disabled = true; ovStop.textContent = 'Stopping…'; }
2439
- try { await api(`/api/trigger-run/${encodeURIComponent(ft.appId)}/stop`, { method: 'POST' }); } catch { /* best effort — the session may already be gone */ }
2440
- // Clear the canvas "running" pulse just like the regular-run stop below — the
2441
- // early return here previously skipped it, leaving nodes stuck on `running` (#116).
2442
- clearNodeStatus();
2443
- // A deliberate stop needs no toast — the subtitle change is the confirmation.
2444
- paintForegroundStopped('stopped');
2445
2488
  syncRunControls();
2489
+ try { await api(`/api/trigger-run/${encodeURIComponent(ft.appId)}/stop`, { method: 'POST' }); } catch { /* best effort — the session may already be gone */ }
2490
+ finally {
2491
+ // Clear the canvas "running" pulse just like the regular-run stop below — the
2492
+ // early return here previously skipped it, leaving nodes stuck on `running` (#116).
2493
+ clearNodeStatus();
2494
+ // A deliberate stop needs no toast — the subtitle change is the confirmation.
2495
+ paintForegroundStopped('stopped');
2496
+ foregroundStopping = false;
2497
+ syncRunControls();
2498
+ }
2446
2499
  return;
2447
2500
  }
2448
2501
  cancelRequested = true;
@@ -2451,6 +2504,7 @@
2451
2504
  const stopBtn = document.querySelector('.overlay-stop');
2452
2505
  if (stopBtn) { stopBtn.disabled = true; stopBtn.textContent = 'Cancelling…'; }
2453
2506
  if ($stopRunBtn) { $stopRunBtn.disabled = true; $stopRunBtn.textContent = 'Cancelling…'; }
2507
+ syncRunControls();
2454
2508
  try { await api('/api/run/stop', { method: 'POST' }); } catch { /* the run's own catch surfaces it */ }
2455
2509
  }
2456
2510
 
@@ -5747,7 +5801,7 @@
5747
5801
  const app = currentId && apps.get(currentId);
5748
5802
  if (!app) return;
5749
5803
  if (!app.runnable) { showToast($runBtn.dataset.tip, 'warn'); return; }
5750
- if (state.running || reportRunning || foregroundTrigger) return;
5804
+ if (state.running || reportRunning || foregroundStarting || foregroundStopping || foregroundTrigger) return;
5751
5805
 
5752
5806
  // Streaming/watch app → a LIVE FOREGROUND session, not a finite run (which would
5753
5807
  // never complete and time out at 60s). It re-renders the report in the Viewer on
@@ -5761,6 +5815,7 @@
5761
5815
  const rid = reportNodeId();
5762
5816
  if (!simulate && rid) { runReport(rid); return; }
5763
5817
 
5818
+ runningSimulation = simulate;
5764
5819
  state.running = true;
5765
5820
  cancelRequested = false;
5766
5821
  $runBtn.disabled = true;
@@ -5803,6 +5858,7 @@
5803
5858
  }
5804
5859
  } finally {
5805
5860
  state.running = false;
5861
+ runningSimulation = false;
5806
5862
  $runBtn.disabled = false;
5807
5863
  if ($simBtn) $simBtn.disabled = false;
5808
5864
  $runBtn.textContent = '▶ Run workflow';
@@ -6825,6 +6881,155 @@
6825
6881
  ? ['Nothing to copy — this request has no instruction', 'err']
6826
6882
  : ['copy failed', 'err']);
6827
6883
 
6884
+ // ── Headless runs (#571 slice 3) ────────────────────────────────────────────
6885
+ // floless starting the user's OWN terminal AI on a queued request, instead of them pasting it.
6886
+ // The browser holds NO copy of which request types may run: every row arrives carrying `canRun`
6887
+ // and `runWhy` from the server's one policy table, so the two cannot drift and a type this build
6888
+ // has never heard of is answered fail-closed at the source rather than guessed at here.
6889
+ //
6890
+ // Detection is a workspace-level fact (which CLIs exist) fetched per surface-open and cached; the
6891
+ // FOLDER is per project, so anything that needs it re-reads with the project key rather than
6892
+ // trusting this. Server-side detection spawns nothing — it is statSync work — so an open is cheap.
6893
+ let headlessInfo = null;
6894
+ async function refreshHeadless() {
6895
+ // A detection failure HIDES the feature rather than leaving a button that cannot work. There is
6896
+ // no honest middle: without the runtime list we do not know that anything is installed.
6897
+ try { headlessInfo = await api('/api/terminal-runtimes'); }
6898
+ catch { headlessInfo = null; }
6899
+ return headlessInfo;
6900
+ }
6901
+ const headlessRuntimes = () => (headlessInfo && Array.isArray(headlessInfo.runtimes) ? headlessInfo.runtimes : []);
6902
+ /** Zero runtimes found ⇒ no run affordance anywhere (§E4). Hidden, never disabled. */
6903
+ const headlessReady = () => headlessRuntimes().some((r) => r && r.state === 'found');
6904
+ const runtimeLabel = (id) => {
6905
+ const m = headlessRuntimes().find((r) => r && r.id === id);
6906
+ return (m && m.label) || String(id || 'your terminal AI');
6907
+ };
6908
+ /** Which project's folder a request runs in — the same key the server derives. */
6909
+ const runProjectKey = (r) => (r && (r.project || r.appId)) || null;
6910
+
6911
+ // How each run state reads to a human. Deliberately absent: `succeeded` — the success path DELETES
6912
+ // the request, so no row can ever display it; success IS the row disappearing, exactly as it does
6913
+ // when a human pastes the prompt themselves. An unmapped state falls through to its own name in
6914
+ // the muted tier rather than rendering blank, which is the honest miss-path for a newer server.
6915
+ const RUN_VIEW = {
6916
+ queued: { badge: 'Queued', cls: 'active', spin: true, note: (rt) => `Starting ${rt}.` },
6917
+ running: { badge: 'Running', cls: 'active', spin: true, note: (rt) => `${rt} is working on this. It clears itself when it’s done.` },
6918
+ 'needs-you': { badge: 'Needs you', cls: 'warn', note: () => 'Your terminal AI stopped because this needs a decision from you:' },
6919
+ 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.' },
6920
+ // Never the identifier `contract-violation` — the user did not write the contract.
6921
+ '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.' },
6922
+ '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.' },
6923
+ failed: { badge: 'Failed', cls: 'err', note: () => 'The run failed.' },
6924
+ stopped: { badge: 'Stopped', cls: 'muted', note: () => 'You stopped this run.' },
6925
+ };
6926
+
6927
+ function runStatusHtml(run) {
6928
+ if (!run || !run.state) return '';
6929
+ const v = RUN_VIEW[run.state] || { badge: String(run.state), cls: 'muted', note: () => '' };
6930
+ const rt = runtimeLabel(run.runtime);
6931
+ const note = v.note(rt);
6932
+ return `
6933
+ <div class="req-run-status">
6934
+ <div class="req-run-head">
6935
+ ${v.spin ? '<span class="rtn-spinner" aria-hidden="true"></span>' : ''}
6936
+ <span class="req-run-badge req-run-badge-${v.cls}">${escapeHtml(v.badge)}</span>
6937
+ </div>
6938
+ ${note ? `<p class="req-run-note">${escapeHtml(note)}</p>` : ''}
6939
+ ${run.question ? `<p class="req-run-question">${escapeHtml(run.question)}</p>` : ''}
6940
+ ${run.cwd ? `<div class="req-run-where">${escapeHtml(rt)} · ${escapeHtml(run.cwd)}</div>` : ''}
6941
+ ${run.lastOutput ? `<details class="req-run-output"><summary>Show what it printed</summary><pre>${escapeHtml(run.lastOutput)}</pre></details>` : ''}
6942
+ </div>`;
6943
+ }
6944
+
6945
+ // Start a run. `runtime` is the §E4 per-run override — omitted, the server resolves the default.
6946
+ async function runRequestHeadless(req, runtime) {
6947
+ try {
6948
+ const res = await api(`/api/requests/${encodeURIComponent(req.id)}/run`, {
6949
+ method: 'POST', body: JSON.stringify(runtime ? { runtime } : {}),
6950
+ });
6951
+ showToast(`Running in ${runtimeLabel((res.run && res.run.runtime) || runtime)} — the row updates as it goes`, 'ok');
6952
+ await loadRequests();
6953
+ renderRequests();
6954
+ return res;
6955
+ } catch (err) {
6956
+ const code = err && err.body && err.body.code;
6957
+ // No folder yet (or one that has since gone) is not an error to report — it is the one
6958
+ // question the user has not been asked. Ask it, pre-loaded with the server's own sentence.
6959
+ if (code === 'no-folder' || code === 'bad-folder') { await openRunOptions(req, err.body.error); return null; }
6960
+ showToast((err && err.message) || 'could not start the run', 'err');
6961
+ return null;
6962
+ }
6963
+ }
6964
+
6965
+ async function stopRequestRun(req) {
6966
+ try {
6967
+ await api(`/api/requests/${encodeURIComponent(req.id)}/run/stop`, { method: 'POST' });
6968
+ await loadRequests();
6969
+ renderRequests();
6970
+ } catch (e) { reportErr(e); }
6971
+ }
6972
+
6973
+ /**
6974
+ * Folder + which terminal AI, then run. Reached from the split button's ▾ and automatically
6975
+ * whenever a run is refused for want of a usable folder.
6976
+ *
6977
+ * A LOOP, not recursion, because the refusal path can repeat: §B says an unusable folder is a
6978
+ * MODAL, not a toast, so a bad path re-opens this same form carrying the server's whole sentence
6979
+ * and the value the user typed — never a toast they have to remember while retyping.
6980
+ */
6981
+ async function openRunOptions(req, problem) {
6982
+ const key = runProjectKey(req);
6983
+ let info;
6984
+ try { info = await api(`/api/terminal-runtimes${key ? `?project=${encodeURIComponent(key)}` : ''}`); }
6985
+ catch (e) { reportErr(e); return null; }
6986
+ const found = (info.runtimes || []).filter((r) => r && r.state === 'found');
6987
+ if (!found.length) { showToast('No terminal AI found on this machine.', 'warn'); return null; }
6988
+ let folder = info.folder || '';
6989
+ let sub = problem || '';
6990
+ // Tracked SEPARATELY from `sub`, because the two are different messages. `problem` on the first
6991
+ // open is "you haven't chosen a folder yet" — nothing was refused, and titling that
6992
+ // "That folder won't work" blames the user for a folder they never typed.
6993
+ let refused = false;
6994
+ for (;;) {
6995
+ const res = await formModal({
6996
+ // The TITLE carries the refusal too, not just the sub. Both are re-set per open, so this
6997
+ // leaks nothing to the next caller — and without it the only thing that changes on a bad
6998
+ // folder is one line of muted grey, in the same tier as the explanation it replaced.
6999
+ title: refused ? 'That folder won’t work' : 'Run this for me',
7000
+ 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.',
7001
+ fields: [
7002
+ {
7003
+ name: 'folder', label: 'Folder to work in', value: folder,
7004
+ placeholder: 'C:\\Repos\\my-project',
7005
+ },
7006
+ {
7007
+ name: 'runtime', label: 'Which terminal AI', type: 'select', value: info.provider || found[0].id,
7008
+ options: found.map((r) => ({ value: r.id, label: r.label, meta: r.command })),
7009
+ },
7010
+ ],
7011
+ // §D2, stated once at the moment the user picks the folder — the point at which they still
7012
+ // have the context to judge. NOT re-shown on every run, which only trains dismissal.
7013
+ 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.',
7014
+ okLabel: 'Run it',
7015
+ });
7016
+ if (!res) return null;
7017
+ folder = String(res.folder || '').trim();
7018
+ try {
7019
+ // Always re-nominated, even unchanged: it is also the only re-validation that the folder is
7020
+ // still there and still writable at the moment the user asks for a run.
7021
+ await api('/api/terminal-runtimes/folder', {
7022
+ method: 'PUT', body: JSON.stringify({ project: key, folder }),
7023
+ });
7024
+ } catch (e) {
7025
+ sub = (e && e.message) || 'That folder can’t be used.';
7026
+ refused = true;
7027
+ continue;
7028
+ }
7029
+ return runRequestHeadless(req, res.runtime);
7030
+ }
7031
+ }
7032
+
6828
7033
  let requestHelpReq = null;
6829
7034
  let requestHelpReturnFocus = null;
6830
7035
  function closeRequestHelp({ restoreFocus = true } = {}) {
@@ -6861,9 +7066,61 @@
6861
7066
  ? 'The web UI queues the drawing read; your terminal agent applies it and reports progress back here.'
6862
7067
  : 'The web UI queues the request; your terminal agent applies it and reports progress back here.';
6863
7068
  if ($copy) $copy.hidden = copied;
7069
+ // Back to the "not started" face on every open — the previous request's run status must never
7070
+ // be the first thing the next one shows.
7071
+ setRequestHelpRunning(null);
6864
7072
  showModal($m);
6865
7073
  const shell = $m.querySelector('.modal.request-help');
6866
7074
  if (shell) { try { shell.focus(); } catch { /* not focusable */ } }
7075
+ // Detection is a fetch, and this modal is opened synchronously by the caller. Reveal the split
7076
+ // when the answer lands rather than blocking the modal on it — and only if THIS request is
7077
+ // still the one on screen, since a second queue can land while the first fetch is in flight.
7078
+ refreshHeadless().then(() => { if (requestHelpReq === req) syncRequestHelpRun(); });
7079
+ syncRequestHelpRun();
7080
+ }
7081
+
7082
+ /** Show the run split only when this request's type can run AND a runtime exists (§E1/§E4). */
7083
+ function syncRequestHelpRun() {
7084
+ const $split = document.getElementById('request-help-run-split');
7085
+ const $open = document.getElementById('request-help-open');
7086
+ if (!$split || !$open) return;
7087
+ const can = !!(requestHelpReq && requestHelpReq.canRun && headlessReady());
7088
+ $split.hidden = !can;
7089
+ // Exactly one primary in the row: Run takes it when it is there, Open Requests reclaims it
7090
+ // when it is not — a modal with no emphasized action reads as unfinished.
7091
+ $open.classList.toggle('primary', !can);
7092
+ }
7093
+
7094
+ /**
7095
+ * Swap the modal's three "what you must do" steps for what floless is doing instead.
7096
+ *
7097
+ * The steps are REPLACED, not relabelled: after "Run it for me" there is no paste to describe,
7098
+ * and a rewritten step 2 would still be a numbered instruction for the user.
7099
+ */
7100
+ function setRequestHelpRunning(run) {
7101
+ const $steps = document.getElementById('request-help-steps');
7102
+ const $status = document.getElementById('request-help-run-status');
7103
+ const $title = document.getElementById('request-help-run-title');
7104
+ const $split = document.getElementById('request-help-run-split');
7105
+ const $note = document.getElementById('request-help-note');
7106
+ if (!$steps || !$status) return;
7107
+ $steps.hidden = !!run;
7108
+ $status.hidden = !run;
7109
+ if (!run) {
7110
+ // Cleared, not merely hidden. Leaving the previous request's "Running in Claude Code · <cwd>"
7111
+ // in the DOM means one CSS slip away from the next request opening on somebody else's run.
7112
+ if ($title) $title.textContent = '';
7113
+ return;
7114
+ }
7115
+ if ($split) $split.hidden = true; // it started; there is nothing left to start
7116
+ // …which leaves the row with no emphasized action, so Open Requests takes the primary back.
7117
+ // `syncRequestHelpRun` can't do this: it would re-show the split it just retired.
7118
+ const $open = document.getElementById('request-help-open');
7119
+ if ($open) $open.classList.add('primary');
7120
+ if ($title) {
7121
+ $title.innerHTML = `Running in <strong>${escapeHtml(runtimeLabel(run.runtime))}</strong>${run.cwd ? ` · <code>${escapeHtml(run.cwd)}</code>` : ''}`;
7122
+ }
7123
+ 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.';
6867
7124
  }
6868
7125
 
6869
7126
  async function useTemplate(templateId) {
@@ -7171,6 +7428,12 @@
7171
7428
  if ($showAll) $showAll.onclick = () => setRequestScopeAll(true);
7172
7429
  return;
7173
7430
  }
7431
+ // Whether a non-runnable row explains itself, decided ONCE per paint over what is actually on
7432
+ // screen. A user who has never seen a ▶ has nothing to wonder about, so a queue of nothing but
7433
+ // guides stays quiet; the moment a runnable row sits beside a `guide`, the guide says why it
7434
+ // has no button. Derived from this paint — deliberately not a stored "has run before" flag,
7435
+ // which would make the same list read differently for two people.
7436
+ const anyRunnable = headlessReady() && shown.some((r) => r && r.canRun);
7174
7437
  $list.innerHTML = shown.map((r) => {
7175
7438
  const label = requestLabel(r);
7176
7439
  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';
@@ -7188,23 +7451,54 @@
7188
7451
  // A knowledge-organize is resolved by its own finish/fail lifecycle POST. Offering a ✕ here
7189
7452
  // would let the user delete a request the terminal AI is mid-way through, 404-ing finish/fail
7190
7453
  // and stranding the organize lock until its stale timeout. Show why it can't be cleared instead.
7454
+ const run = r.run || null;
7455
+ const inFlight = !!run && (run.state === 'queued' || run.state === 'running');
7191
7456
  const lifecycleOwned = r.type === 'knowledge-organize';
7457
+ // ✕ goes away while a run is live, for the same reason it goes away on a knowledge-organize:
7458
+ // deleting the request out from under a working agent leaves it unable to clear its own work,
7459
+ // and the run then lands in `exited-unresolved` for a reason the user caused and cannot see.
7192
7460
  const del = lifecycleOwned
7193
7461
  ? '<span class="req-lifecycle" data-tip="This clears itself when your terminal AI finishes or fails the organize">finishing in your terminal</span>'
7194
- : `<button class="req-del" data-id="${escapeAttr(r.id)}" data-tip="Clear this request">×</button>`;
7462
+ : inFlight
7463
+ ? '<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>'
7464
+ : `<button class="req-del" data-id="${escapeAttr(r.id)}" data-tip="Clear this request">×</button>`;
7465
+ // A parked run gets NO re-run: it is waiting on a decision only the human can make, and a
7466
+ // second headless attempt would either abandon that question or look like floless answering
7467
+ // it. Every other terminal state has nothing pending, so running again is a fair offer.
7468
+ const canRunNow = headlessReady() && r.canRun && !inFlight && !(run && run.state === 'needs-you');
7469
+ const runBtn = inFlight
7470
+ ? `<button class="req-stop" data-id="${escapeAttr(r.id)}" data-tip="Stop this run">■</button>`
7471
+ : canRunNow
7472
+ ? `<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>`
7473
+ : '';
7195
7474
  return `
7196
7475
  <div class="req-item" data-id="${escapeAttr(r.id)}">
7197
7476
  <div class="req-info">
7198
7477
  <div class="req-head"><span class="${badgeCls}">${label}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, requestQuery)}</span>` : ''}${time}</div>
7199
7478
  <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>
7200
7479
  ${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>` : ''}
7480
+ ${runStatusHtml(run)}
7481
+ ${!r.canRun && r.runWhy && anyRunnable ? `<div class="req-why-not">Runs only from your terminal — ${escapeHtml(r.runWhy)}</div>` : ''}
7201
7482
  </div>
7202
7483
  <div class="req-actions">
7484
+ ${runBtn}
7203
7485
  <button class="req-copy" data-id="${escapeAttr(r.id)}" data-tip="Copy this instruction">⧉</button>
7204
7486
  ${del}
7205
7487
  </div>
7206
7488
  </div>`;
7207
7489
  }).join('');
7490
+ $list.querySelectorAll('.req-run').forEach((b) => {
7491
+ b.onclick = () => {
7492
+ const r = pendingRequests.find((x) => x.id === b.dataset.id);
7493
+ if (r) void runRequestHeadless(r);
7494
+ };
7495
+ });
7496
+ $list.querySelectorAll('.req-stop').forEach((b) => {
7497
+ b.onclick = () => {
7498
+ const r = pendingRequests.find((x) => x.id === b.dataset.id);
7499
+ if (r) void stopRequestRun(r);
7500
+ };
7501
+ });
7208
7502
  $list.querySelectorAll('.req-copy').forEach((b) => {
7209
7503
  b.onclick = async () => {
7210
7504
  const r = pendingRequests.find((x) => x.id === b.dataset.id);
@@ -7279,7 +7573,10 @@
7279
7573
  // Scroll only: the flash belongs to the authoritative paint below, or the cached one would flash a
7280
7574
  // row the refresh is about to replace.
7281
7575
  revealRequestRow(targetId, true /* scrollOnly */);
7282
- await loadRequests();
7576
+ // Detection rides ALONGSIDE the queue fetch, never in front of it: whether a ▶ is offered must
7577
+ // not be able to delay the list itself, and a detection that fails simply leaves the rows
7578
+ // button-less rather than leaving the window empty.
7579
+ await Promise.all([loadRequests(), refreshHeadless()]);
7283
7580
  // NOTHING here may touch requestScopeAll. Scoping the window to what you have open is a
7284
7581
  // deliberate decision (#633), and revealing a row is not a licence to override it: a reveal that
7285
7582
  // widened would answer a different question than the one asked, and the destructive verb is
@@ -7775,8 +8072,95 @@
7775
8072
  $integrationsModal.classList.add('show');
7776
8073
  renderIntegrations();
7777
8074
  refreshIntegrations();
8075
+ refreshHeadless().then(renderRuntimeSection);
7778
8076
  };
7779
8077
 
8078
+ /**
8079
+ * Which terminal AIs are installed, which one headless runs use, and the folder they run in.
8080
+ *
8081
+ * Its own section rather than a card in the integrations grid: a detected CLI is not an OAuth
8082
+ * connection. There is no Connect, no expiry — and deliberately no "ready", because a signed-out
8083
+ * CLI resolves to a binary exactly like a working one. So `Installed` / `Not installed` are both
8084
+ * NEUTRAL: --ok green two rows under a real "Connected" badge would claim readiness floless has
8085
+ * not earned, and the first the user would hear of it is a run that dies on a login prompt.
8086
+ */
8087
+ function renderRuntimeSection() {
8088
+ const $sec = document.getElementById('int-runtimes-section');
8089
+ const $list = document.getElementById('int-runtimes');
8090
+ const $folder = document.getElementById('int-folder');
8091
+ if (!$sec || !$list || !$folder) return;
8092
+ const rts = headlessRuntimes();
8093
+ // Hidden entirely when detection failed — an empty "Headless runs" box explains nothing. When
8094
+ // detection SUCCEEDED and found nothing, the rows are the explanation (each carries its command).
8095
+ $sec.hidden = !rts.length;
8096
+ if (!rts.length) return;
8097
+ const active = headlessInfo && headlessInfo.provider;
8098
+ $list.innerHTML = rts.map((r) => {
8099
+ const found = r.state === 'found';
8100
+ const isDefault = found && r.id === active;
8101
+ return `
8102
+ <div class="int-rt${isDefault ? ' is-default' : ''}${found ? '' : ' is-missing'}">
8103
+ <div>
8104
+ <div class="int-rt-name">${escapeHtml(r.label)}${isDefault ? '<span class="int-rt-pill">Default</span>' : ''}</div>
8105
+ <div class="int-rt-blurb">${escapeHtml(r.blurb)} · <code>${escapeHtml(r.command)}</code></div>
8106
+ <div class="int-rt-where">${found
8107
+ ? `Found at ${escapeHtml(r.path || '')}`
8108
+ : `Not installed — floless looks for <code>${escapeHtml(r.command)}</code>`}</div>
8109
+ </div>
8110
+ <div class="int-rt-side">
8111
+ <span class="int-rt-badge">${found ? 'Installed' : 'Not installed'}</span>
8112
+ ${found && !isDefault ? `<button class="int-action" data-rt="${escapeAttr(r.id)}">Use this one</button>` : ''}
8113
+ </div>
8114
+ </div>`;
8115
+ }).join('');
8116
+ $list.querySelectorAll('[data-rt]').forEach((b) => {
8117
+ b.onclick = async () => {
8118
+ try {
8119
+ await api('/api/terminal-runtimes/provider', { method: 'PUT', body: JSON.stringify({ provider: b.dataset.rt }) });
8120
+ await refreshHeadless();
8121
+ renderRuntimeSection();
8122
+ showToast(`Headless runs will use ${runtimeLabel(b.dataset.rt)}`, 'ok');
8123
+ } catch (e) { reportErr(e); }
8124
+ };
8125
+ });
8126
+ const folder = headlessInfo && headlessInfo.folder;
8127
+ $folder.innerHTML = `
8128
+ <span>Runs in</span>
8129
+ <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>
8130
+ <button class="int-action" id="int-folder-set">${folder ? 'Change…' : 'Choose…'}</button>`;
8131
+ const $set = document.getElementById('int-folder-set');
8132
+ if ($set) $set.onclick = () => { void nominateDefaultFolder(); };
8133
+ }
8134
+
8135
+ /**
8136
+ * The workspace-level default folder. Per-project folders are nominated from the run itself,
8137
+ * where the user can see which request they are answering for.
8138
+ *
8139
+ * A refusal re-opens THIS form carrying the server's whole sentence — §B: an unusable folder is a
8140
+ * modal, not a toast. Same loop as `openRunOptions` for the same reason.
8141
+ */
8142
+ async function nominateDefaultFolder() {
8143
+ let folder = (headlessInfo && headlessInfo.folder) || '';
8144
+ let sub = '';
8145
+ for (;;) {
8146
+ const res = await formModal({
8147
+ title: sub ? 'That folder won’t work' : 'Folder for headless runs',
8148
+ sub: sub || 'Where floless starts your terminal AI when it runs a request for you. Individual projects can override this.',
8149
+ fields: [{ name: 'folder', label: 'Folder', value: folder, placeholder: 'C:\\Repos\\my-project' }],
8150
+ 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.',
8151
+ okLabel: 'Save',
8152
+ });
8153
+ if (!res) return;
8154
+ folder = String(res.folder || '').trim();
8155
+ try {
8156
+ await api('/api/terminal-runtimes/folder', { method: 'PUT', body: JSON.stringify({ project: null, folder }) });
8157
+ } catch (e) { sub = (e && e.message) || 'That folder can’t be used.'; continue; }
8158
+ await refreshHeadless();
8159
+ renderRuntimeSection();
8160
+ return;
8161
+ }
8162
+ }
8163
+
7780
8164
  // Re-fetch live connection state from the local vault; re-render if the modal
7781
8165
  // is open. Called on open and whenever a credential file changes (SSE), so an
7782
8166
  // open window flips to Connected the moment `aware connect` writes the token.
@@ -8158,8 +8542,13 @@
8158
8542
  // Stop, and reflect the live state. We never compose HTML — the Viewer relays
8159
8543
  // exactly what the node returns (applyTriggerReport paints each fresh report).
8160
8544
  async function startForegroundTrigger(app) {
8161
- if (foregroundTrigger) return;
8545
+ if (foregroundTrigger || foregroundStarting || foregroundStopping) return;
8162
8546
  const id = currentId;
8547
+ // A completed finite-run cancellation leaves this flag set so its late SSE events stay ignored.
8548
+ // A new foreground lifecycle must start clean, or Stop inherits the old disabled/cancelling state.
8549
+ cancelRequested = false;
8550
+ foregroundStarting = true;
8551
+ syncRunControls();
8163
8552
  $reportTitle.textContent = `HTML Viewer · ${app.displayName}`;
8164
8553
  $reportModal.dataset.nodeId = reportNodeId() || '';
8165
8554
  const cached = lastReportByApp.get(id);
@@ -8174,7 +8563,6 @@
8174
8563
  const res = await api('/api/trigger-run', { method: 'POST', body: JSON.stringify({ id, inputs: currentInputs() }) });
8175
8564
  foregroundTrigger = { appId: id, sessionId: res.sessionId, firedCount: 0 };
8176
8565
  markFirstRunDone(id); // a real live session started → a streaming workflow's "first run" is no longer new
8177
- syncRunControls(); // header ■ Stop run becomes reachable; Run disabled while live
8178
8566
  paintForegroundListening();
8179
8567
  appendNarration(`Live session started for <strong>${escapeHtml(id)}</strong> — the report updates on every event. Click <strong>■ Stop run</strong> (top right) to end it.`);
8180
8568
  } catch (e) {
@@ -8198,7 +8586,9 @@
8198
8586
  $reportSub.textContent = 'Live session failed to start.';
8199
8587
  showToast('Live run failed: ' + msg, 'warn');
8200
8588
  }
8201
- syncRunControls();
8589
+ } finally {
8590
+ foregroundStarting = false;
8591
+ syncRunControls(); // starting → listening, or back to the compile gate after a failed start
8202
8592
  }
8203
8593
  }
8204
8594
 
@@ -8903,6 +9293,21 @@
8903
9293
  if ($sub) $sub.textContent = 'Terminal instructions copied. Open the terminal agent and paste them there.';
8904
9294
  }
8905
9295
  };
9296
+ // ▶ runs with the resolved default; ▾ asks folder + which terminal AI first. Both leave the modal
9297
+ // OPEN on success and swap its steps for the run status — closing it would hide the one sentence
9298
+ // that says what floless just started on the user's behalf.
9299
+ const runFromHelpModal = async (withOptions) => {
9300
+ const req = requestHelpReq;
9301
+ if (!req) return;
9302
+ const res = withOptions ? await openRunOptions(req) : await runRequestHeadless(req);
9303
+ // Still the same request on screen? A slow spawn plus a fast second queue could otherwise
9304
+ // stamp this run's status onto somebody else's modal.
9305
+ if (res && res.run && requestHelpReq === req) setRequestHelpRunning(res.run);
9306
+ };
9307
+ const $requestHelpRun = document.getElementById('request-help-run');
9308
+ const $requestHelpRunOpts = document.getElementById('request-help-run-opts');
9309
+ if ($requestHelpRun) $requestHelpRun.onclick = () => { void runFromHelpModal(false); };
9310
+ if ($requestHelpRunOpts) $requestHelpRunOpts.onclick = () => { void runFromHelpModal(true); };
8906
9311
  if ($requestHelpModal) onBackdropDismiss($requestHelpModal, () => closeRequestHelp());
8907
9312
  document.addEventListener('keydown', (e) => {
8908
9313
  if (e.key === 'Escape' && $requestHelpModal && $requestHelpModal.classList.contains('show')) {