@floless/app 0.140.0 → 0.141.1

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
@@ -42,6 +42,9 @@
42
42
  // type→view registry lives in renderers.js (a global, loaded before this file).
43
43
  const $contractEditor = document.getElementById('contract-editor');
44
44
  const $contractEditorFrame = document.getElementById('contract-editor-frame');
45
+ // The full-window editor overlay (model/drawing editor or Drawing Filter) — probed for unsaved work
46
+ // before Stop FloLess / Sign Out (web/leave-guard.js).
47
+ if (window.flolessLeaveGuard) window.flolessLeaveGuard.registerFrame($contractEditorFrame, 'editor-overlay');
45
48
  const $contractEditorTitle = document.getElementById('contract-editor-title');
46
49
 
47
50
  // One persistent array the inspect Execution tab reads; we mutate in place so
@@ -2747,8 +2750,42 @@
2747
2750
  // Refresh/close guard: unsaved input values live only in memory, so warn before
2748
2751
  // the page unloads while dirty (the browser shows its own generic confirm).
2749
2752
  window.addEventListener('beforeunload', (e) => {
2753
+ // __flolessLeaving / __flolessStopped: the user already answered the leave guard's question
2754
+ // (Sign Out, Stop FloLess) — asking again with the browser's own prompt would be a second,
2755
+ // uglier copy of the same decision.
2756
+ if (window.__flolessLeaving || window.__flolessStopped) return;
2750
2757
  if (!selfUpdating && isInputsDirty(currentId)) { e.preventDefault(); e.returnValue = ''; }
2751
2758
  });
2759
+ // Unsaved workflow inputs, for the leave guard (Stop FloLess / Sign Out). Every open workflow
2760
+ // with edits is listed — not only the one on screen — and "Save" writes each one the same way
2761
+ // Ctrl+S does for the current workflow.
2762
+ if (window.flolessLeaveGuard) {
2763
+ window.flolessLeaveGuard.register(() => [...dirtyBaseline.keys()].filter((id) => isInputsDirty(id)).map((id) => {
2764
+ const app = apps.get(id);
2765
+ return {
2766
+ id: `inputs:${id}`,
2767
+ label: `Workflow inputs for “${(app && app.displayName) || id}”`,
2768
+ detail: 'have changes that are not saved yet.',
2769
+ save: async () => {
2770
+ try {
2771
+ localStorage.setItem(lsInputsKey(id), JSON.stringify(appInputValues.get(id) || {}));
2772
+ setInputBaseline(id);
2773
+ refreshDirtyIndicator();
2774
+ } catch { return false; }
2775
+ return !isInputsDirty(id);
2776
+ },
2777
+ };
2778
+ }));
2779
+ // A workflow run in progress is warned about, never "saved".
2780
+ window.flolessLeaveGuard.register(leaveGuardRunItems);
2781
+ }
2782
+ // Read from the run-in-flight flags — the same ones that show the header ■ Stop run — never
2783
+ // from the painted run-state label, which can already read "Ready" while a run is still going
2784
+ // (seen in the browser QA after the HTML Viewer opened and was closed mid-run).
2785
+ function leaveGuardRunItems() {
2786
+ const inFlight = reportRunning || state.running || foregroundStarting || foregroundStopping || !!foregroundTrigger;
2787
+ return inFlight ? [{ id: 'run', kind: 'running', label: 'A workflow run' }] : [];
2788
+ }
2752
2789
  // Persist the active app's inputs to localStorage (the new build restores them on load).
2753
2790
  // Used before a self-update reload so an in-place adoption never drops unsaved edits.
2754
2791
  function persistCurrentInputs() {
@@ -3279,20 +3316,37 @@
3279
3316
  // and the section speaks to that editor while it is open — the same tabs, by the same code, as the
3280
3317
  // workspace's Model step (web/model-panel-bridge.js).
3281
3318
  let contractEditorApp = null; // the workflow the editor was opened for: Approve bakes that one
3282
- // The regions of #app the overlay covers. Covering them is not enough: Tab from the left panel would still reach
3283
- // the header, canvas and footer under it. Cards drawn above the overlay (#fullscreen-nudge, #ix-ask-menu) are not
3284
- // covered, so they are not listed and stay usable.
3319
+ // The regions of #app the overlay covers. Covering them is not enough: Tab from the Close button or the left panel
3320
+ // would still reach the header, canvas and footer under it, and Enter there runs or compiles the workflow. Cards
3321
+ // drawn above the overlay (#fullscreen-nudge, #ix-ask-menu) are not covered, so they are not listed and stay usable.
3322
+ // A model editor keeps the left panel and its edge above it (OVERLAY_COVERS); every other overlay — the Drawing
3323
+ // Filter, the local 3D viewer, an editor with no Model section — covers the whole window, so those go too (#1445).
3285
3324
  const OVERLAY_COVERS = '#app > header, #canvas-main, #app > .pane-rail-right, #inspect-panel, #whats-new-panel, #instructor, #app > footer';
3325
+ const FULL_WINDOW_COVERS = OVERLAY_COVERS + ', #chat-panel, #app > .pane-rail-left';
3286
3326
  let shellInertBefore = null; // each covered region, with the inert it had before
3287
- function overlayModelPanel(on) {
3288
- document.getElementById('app').classList.toggle('contract-editor-beside', on);
3289
- if (on && !shellInertBefore) {
3290
- shellInertBefore = [...document.querySelectorAll(OVERLAY_COVERS)]
3291
- .map((region) => { const before = region.inert; region.inert = true; return [region, before]; });
3292
- } else if (!on && shellInertBefore) {
3327
+ let overlayOpener = null; // what had focus before the first overlay opened, to give it back on close
3328
+ // Make the regions `covers` names unreachable, or none when it is null. Whatever was covered before is restored
3329
+ // first, so switching from one overlay to another covers exactly the new set and closing leaves nothing inert
3330
+ // that was not inert already. Closing also returns focus to the control that opened the overlay, when it is
3331
+ // still there and reachable — otherwise focus would be left on the page itself.
3332
+ function coverShell(covers) {
3333
+ const opening = covers && !shellInertBefore;
3334
+ if (shellInertBefore) {
3293
3335
  for (const [region, before] of shellInertBefore) region.inert = before;
3294
3336
  shellInertBefore = null;
3295
3337
  }
3338
+ if (opening) overlayOpener = document.activeElement !== document.body ? document.activeElement : null;
3339
+ if (covers) {
3340
+ shellInertBefore = [...document.querySelectorAll(covers)]
3341
+ .map((region) => { const before = region.inert; region.inert = true; return [region, before]; });
3342
+ } else {
3343
+ const opener = overlayOpener;
3344
+ overlayOpener = null;
3345
+ if (opener?.isConnected && !opener.closest('[inert]')) opener.focus?.({ preventScroll: true });
3346
+ }
3347
+ }
3348
+ function overlayModelPanel(on) {
3349
+ document.getElementById('app').classList.toggle('contract-editor-beside', on);
3296
3350
  window.flolessLeftPane?.useOverlayModelFrame(on ? $contractEditorFrame : null);
3297
3351
  }
3298
3352
  function openContractEditor(appId, type) {
@@ -3300,6 +3354,7 @@
3300
3354
  if (!r) return false;
3301
3355
  contractEditorApp = appId;
3302
3356
  overlayModelPanel(!!r.modelPanel);
3357
+ coverShell(r.modelPanel ? OVERLAY_COVERS : FULL_WINDOW_COVERS);
3303
3358
  // The editor bakes the .lock on Approve — that control belongs to an editable contract editor, not
3304
3359
  // the filter view (own Save) nor a view-only renderer. Show it unless the renderer is viewOnly.
3305
3360
  const ap0 = document.getElementById('contract-editor-approve'); if (ap0) ap0.hidden = !!r.viewOnly;
@@ -3324,6 +3379,7 @@
3324
3379
  const r = window.CONTRACT_RENDERERS && window.CONTRACT_RENDERERS[type];
3325
3380
  if (!r || !r.viewerUrl) return false;
3326
3381
  overlayModelPanel(false);
3382
+ coverShell(FULL_WINDOW_COVERS);
3327
3383
  const ap = document.getElementById('contract-editor-approve'); if (ap) ap.hidden = true;
3328
3384
  $contractEditorTitle.replaceChildren(
3329
3385
  Object.assign(document.createElement('span'), { textContent: appId, style: 'color:var(--text);font-weight:600' }),
@@ -3339,6 +3395,7 @@
3339
3395
  // iframe talks to /api/contract directly and Save writes contract.filter.
3340
3396
  function openFilterView(appId) {
3341
3397
  overlayModelPanel(false);
3398
+ coverShell(FULL_WINDOW_COVERS);
3342
3399
  // The filter view has its own Save; the overlay's "Approve & bake lock" (editor-only) would
3343
3400
  // be a confusing no-op here, so hide it. openContractEditor restores it.
3344
3401
  const ap = document.getElementById('contract-editor-approve'); if (ap) ap.hidden = true;
@@ -3366,10 +3423,55 @@
3366
3423
  }
3367
3424
  $contractEditor.hidden = true;
3368
3425
  overlayModelPanel(false); // the left Model section goes back to the workspace
3426
+ // Unhook the focus-on-load first: about:blank loading would otherwise pull focus into the now-hidden frame,
3427
+ // away from the shell the next line hands back.
3428
+ $contractEditorFrame.onload = null;
3429
+ coverShell(null); // and the shell under the overlay is reachable again
3369
3430
  $contractEditorFrame.src = 'about:blank'; // tear down the editor session + its draft listeners
3370
3431
  }
3371
3432
  document.getElementById('contract-editor-close').onclick = closeContractEditor;
3372
3433
 
3434
+ // Esc closes the overlay (#1571) — the Instructor has always said so (`shell.editor-close`, "Also: Esc") and
3435
+ // nothing did. Through closeContractEditor, never around it, so the Drawing Filter's unsaved question still asks.
3436
+ // `overlayEscClosing` makes a second Esc while that question is up a no-op instead of a second question.
3437
+ let overlayEscClosing = false;
3438
+ async function closeOverlayOnEscape() {
3439
+ if ($contractEditor.hidden || overlayEscClosing) return false;
3440
+ overlayEscClosing = true;
3441
+ try { await closeContractEditor(); } finally { overlayEscClosing = false; }
3442
+ return true;
3443
+ }
3444
+ // Focus in the shell: only while it sits on the overlay's own bar (Close, Approve) or on nothing at all. Focus in
3445
+ // the left panel beside a model editor is that panel's, and its Esc is its own. Bound on window, so it runs after
3446
+ // every document-level Esc handler, and a press one of them already used (preventDefault) is left alone. A keydown
3447
+ // inside the editor's iframe never arrives here; that half is web/overlay-escape.js, which calls the hook below.
3448
+ // Several shell dialogs, the menu and the find bar close on Esc WITHOUT marking it (app.js, the routines and guide
3449
+ // modals), and by the time this bubble listener runs they are already hidden. So whether one was showing is read in
3450
+ // the capture phase, before any of them acts: that Esc was theirs, and closing the overlay too would be two actions.
3451
+ const SHELL_ESC_OWNERS = '.modal-backdrop.show, #menu.show, #find-overlay.show';
3452
+ let shellEscOwned = false;
3453
+ window.addEventListener('keydown', (e) => {
3454
+ if (e.key === 'Escape') shellEscOwned = !!document.querySelector(SHELL_ESC_OWNERS);
3455
+ }, true);
3456
+ window.addEventListener('keydown', (e) => {
3457
+ if (e.key !== 'Escape' || e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.isComposing) return;
3458
+ if ($contractEditor.hidden || shellEscOwned) return;
3459
+ const ae = document.activeElement;
3460
+ if (ae !== document.body && ae !== null && (!$contractEditor.contains(ae) || ae === $contractEditorFrame)) return;
3461
+ e.preventDefault();
3462
+ closeOverlayOnEscape();
3463
+ });
3464
+ // The iframe's half: an Esc the page left unused. Only the page the overlay is SHOWING may close it — the same
3465
+ // editor embedded in a workspace step, or a stale frame still unloading, gets false and nothing happens.
3466
+ window.__floOverlayEscape = (win) => {
3467
+ if ($contractEditor.hidden || document.querySelector(SHELL_ESC_OWNERS)) return false; // a shell dialog above it goes first
3468
+ let current = null;
3469
+ try { current = $contractEditorFrame.contentWindow; } catch (_) { current = null; }
3470
+ if (!win || win !== current) return false;
3471
+ closeOverlayOnEscape();
3472
+ return true;
3473
+ };
3474
+
3373
3475
  // Export 3D ▸ — render the approved model as an interactive 3D model. Calls the server's
3374
3476
  // export-3d (transform → companion viewer-3d app → compile → run) and paints the returned
3375
3477
  // interactive report in the same viewer a normal run uses. api() throws on any failure (non-2xx
@@ -5453,7 +5555,11 @@
5453
5555
  `<dt>Tekla host</dt><dd>${escapeHtml(proof.hostVersion)} · PID ${escapeHtml(String(proof.hostPid))}</dd>` +
5454
5556
  `<dt>Library used</dt><dd>${escapeHtml(proof.sourcePath)}</dd>` +
5455
5557
  `<dt>Checked</dt><dd>${escapeHtml(proof.verifiedAt)}</dd></dl>` +
5456
- `<p>The generated agent's commands remain unverified.</p></div>`);
5558
+ `<p>The generated agent's commands remain unverified.</p>` +
5559
+ `<button type="button" class="graft-verify-button graft-continue-chat" id="graft-continue-chat" data-command-id="shell.graft-continue-chat">Continue in AI Chat</button></div>`);
5560
+ // Only the successful receipt carries this action. It hands the receipt to Chat as an
5561
+ // editable, unsent draft; opening Chat never re-runs the Tekla read.
5562
+ document.getElementById('graft-continue-chat')?.addEventListener('click', () => { void continueGraftReadInChat(proof); });
5457
5563
  } catch (error) {
5458
5564
  if (generation !== graftGeneration || graftState.preview !== preview || !$graftModal.classList.contains('show') || !result.isConnected || state.commitInFlight) return;
5459
5565
  const message = graftTeklaReadErrorMessage(error);
@@ -5480,6 +5586,29 @@
5480
5586
  }
5481
5587
  }
5482
5588
 
5589
+ async function continueGraftReadInChat(proof) {
5590
+ const receipt = {
5591
+ sourcePath: proof.sourcePath, hostVersion: proof.hostVersion, modelName: proof.modelName,
5592
+ hostPid: proof.hostPid, verifiedAt: proof.verifiedAt, operation: proof.operation,
5593
+ };
5594
+ if (graftState.verifyInFlight || graftState.commitInFlight) return;
5595
+ if (typeof window.flolessChat?.openVerifiedTeklaDraft !== 'function') {
5596
+ showToast('AI Chat is not available right now. Reload FloLess, then verify the model read again.', 'warn');
5597
+ return;
5598
+ }
5599
+ // Close Graft only once Chat holds the draft: a failure keeps the receipt on screen to retry.
5600
+ try {
5601
+ await window.flolessChat.openVerifiedTeklaDraft(receipt);
5602
+ } catch (e) {
5603
+ console.warn('Continue in AI Chat failed', e);
5604
+ showToast(e?.plainEnglish && e.message
5605
+ ? e.message
5606
+ : 'FloLess could not open AI Chat. Open a project or workflow, then verify the model read again.', 'warn');
5607
+ return;
5608
+ }
5609
+ closeGraftModal();
5610
+ }
5611
+
5483
5612
  async function runGraftCommit(force) {
5484
5613
  if (!graftState.stagedRef || graftState.verifyInFlight || graftState.commitInFlight) return;
5485
5614
  const state = graftState;
@@ -5497,6 +5626,11 @@
5497
5626
  verifyButton.disabled = true;
5498
5627
  verifyButton.setAttribute('data-blocked-reason', 'Agent creation is in progress. Wait for it to finish.');
5499
5628
  }
5629
+ const continueButton = document.getElementById('graft-continue-chat');
5630
+ if (continueButton) {
5631
+ continueButton.disabled = true;
5632
+ continueButton.setAttribute('data-blocked-reason', 'Agent creation is in progress. Wait for it to finish.');
5633
+ }
5500
5634
  try {
5501
5635
  const body = { stagedRef: graftState.stagedRef };
5502
5636
  if (force) body.force = true;
@@ -5529,6 +5663,10 @@
5529
5663
  } finally {
5530
5664
  state.commitInFlight = false;
5531
5665
  for (const control of [$graftPrimary, $graftBack, $graftCancel]) control.removeAttribute('data-blocked-reason');
5666
+ if (continueButton?.isConnected) {
5667
+ continueButton.disabled = false;
5668
+ continueButton.removeAttribute('data-blocked-reason');
5669
+ }
5532
5670
  if (verifyButton?.isConnected) {
5533
5671
  verifyButton.disabled = false;
5534
5672
  verifyButton.removeAttribute('data-blocked-reason');
@@ -7896,6 +8034,7 @@
7896
8034
  stat.appendChild(btn);
7897
8035
  }
7898
8036
  function setServerStatus(online) {
8037
+ if (window.__flolessStopped) return; // stopped on purpose — the "FloLess has stopped" screen owns the page
7899
8038
  if (online === serverOnline) return;
7900
8039
  const wasOnline = serverOnline;
7901
8040
  serverOnline = online;
@@ -7920,10 +8059,22 @@
7920
8059
  let awareRuntimeVersion = null; // installed AWARE version (from /api/health) — gates the freeze menu
7921
8060
  let freezeHintAppended = false; // append the right-click-to-freeze canvas hint once, when supported
7922
8061
  function startHealthPoll() {
8062
+ // One health check at a time (#1604). When the server answered slower than this 5-second poll, each
8063
+ // tick added another open request, and the pile held the browser's ~6 connections to this server —
8064
+ // AI Chat and every other request then waited behind it. Skip a tick instead. The check still gives
8065
+ // up after 45 s — past the licence check's own bounds — so a request that never answers cannot stop
8066
+ // the poll for good.
8067
+ let healthInFlight = false;
7923
8068
  const tick = async () => {
8069
+ if (window.__flolessStopped) return; // nothing to poll: the user stopped FloLess
8070
+ if (healthInFlight) return;
8071
+ healthInFlight = true;
8072
+ try { await healthTick(); } finally { healthInFlight = false; }
8073
+ };
8074
+ const healthTick = async () => {
7924
8075
  let ok = false;
7925
8076
  try {
7926
- const r = await fetch('/api/health', { cache: 'no-store' });
8077
+ const r = await fetch('/api/health', { cache: 'no-store', signal: AbortSignal.timeout(45_000) });
7927
8078
  ok = r.ok;
7928
8079
  if (ok) {
7929
8080
  const h = await r.json();
@@ -8558,6 +8709,12 @@
8558
8709
  // failure, or an unfamiliar terminal state after its Copy carrier rendered. The row already uses
8559
8710
  // requestCanCopy; enforcing it again here prevents a stale click from claiming obsolete
8560
8711
  // instructions were copied successfully.
8712
+ // AI Chat ownership gets its OWN result, because it is not an absence. Falling through to
8713
+ // `empty` told the user "this request has no instruction" about a request whose instruction is
8714
+ // complete and simply already held — and `settled` would claim it had moved on. For a revision
8715
+ // read the check runs against the freshly re-read row above, so a conversation another tab
8716
+ // started between paint and click is caught here rather than handed a second writer.
8717
+ if (requestRunsInChat(current)) return 'chat-owned';
8561
8718
  if (!requestCanCopy(current)) return revisionReadCannotRestart(current) ? 'settled' : 'empty';
8562
8719
  const line = current ? markedInstruction(current) : '';
8563
8720
  if (!line) return 'empty';
@@ -8572,6 +8729,8 @@
8572
8729
  ? ['This drawing read has moved on — open Requests for the next step', 'warn']
8573
8730
  : res === 'unavailable'
8574
8731
  ? ['FloLess couldn’t check the latest drawing-read state — open Requests and try again', 'warn']
8732
+ : res === 'chat-owned'
8733
+ ? ['AI Chat holds this request — open AI Chat on the left (expand that panel if it is collapsed) to see where it stands', 'warn']
8575
8734
  : res === 'empty'
8576
8735
  ? ['Nothing to copy — this request has no instruction', 'err']
8577
8736
  : ['copy failed', 'err']);
@@ -8609,32 +8768,230 @@
8609
8768
  // from is cached 10 s server-side (one CLI status call per provider per window at most), so an
8610
8769
  // open is still cheap.
8611
8770
  let headlessInfo = null;
8771
+ // Several surfaces read the runtimes at once, and their answers can arrive in any order. Every read
8772
+ // claims the next epoch BEFORE it asks (`headlessFetchEpoch`), and its answer is published to the
8773
+ // shared rows only when it is newer than the answer they already hold (`headlessPublishedEpoch`).
8774
+ // So the newest answer always wins, and a slow older one never overwrites it. A launch read or a
8775
+ // keeping-last re-read that fails publishes nothing, so it buries nothing: an older read that did get
8776
+ // an answer is still shared. refreshHeadless is the one exception, on purpose: it publishes its
8777
+ // failure (null) as the newest thing known, because a detection failure hides the feature (#1621).
8612
8778
  let headlessFetchEpoch = 0;
8779
+ let headlessPublishedEpoch = 0;
8780
+ function publishHeadless(epoch, info) {
8781
+ if (epoch <= headlessPublishedEpoch) return false;
8782
+ headlessPublishedEpoch = epoch;
8783
+ headlessInfo = info;
8784
+ return true;
8785
+ }
8613
8786
  async function refreshHeadless() {
8614
8787
  // A detection failure HIDES the feature rather than leaving a button that cannot work. There is
8615
- // no honest middle: without the runtime list we do not know that anything is installed.
8788
+ // no honest middle: without the runtime list we do not know that anything is installed. So this
8789
+ // read publishes its failure too, as the newest thing known, unless a newer answer is already in.
8616
8790
  const epoch = ++headlessFetchEpoch;
8617
8791
  let next;
8618
8792
  try { next = await api('/api/terminal-runtimes'); }
8619
8793
  catch { next = null; }
8620
- // Several surfaces can ask at once. A slow earlier probe must not overwrite a newer answer and
8621
- // leave the visible Start guidance disagreeing with the shared runtime state.
8622
- if (epoch !== headlessFetchEpoch) return headlessInfo;
8623
- headlessInfo = next;
8794
+ publishHeadless(epoch, next);
8624
8795
  return headlessInfo;
8625
8796
  }
8797
+ // The New project dialog's read (#1605), also the re-read after a setup that did not finish (#1607).
8798
+ // NOT refreshHeadless(): that one NULLS the shared runtime state on a failed read, so one blip while
8799
+ // the dialog is open would hide its chat path and every Start affordance in Requests with it. Only a
8800
+ // well-formed answer is published; a failed read publishes nothing, says so in the console, and
8801
+ // returns false so the dialog can ask again.
8802
+ async function refreshChatProvidersKeepingLast() {
8803
+ const epoch = ++headlessFetchEpoch;
8804
+ try {
8805
+ const info = await api('/api/terminal-runtimes');
8806
+ if (info && Array.isArray(info.runtimes)) {
8807
+ publishHeadless(epoch, info);
8808
+ return true;
8809
+ }
8810
+ console.warn('floless: a re-read of the terminal runtimes had no runtime list', info);
8811
+ } catch (error) {
8812
+ console.warn('floless: could not re-read the terminal runtimes', error);
8813
+ }
8814
+ return false;
8815
+ }
8626
8816
  const headlessRuntimes = () => (headlessInfo && Array.isArray(headlessInfo.runtimes) ? headlessInfo.runtimes : []);
8627
- /** Zero runtimes found ⇒ no run affordance anywhere (§E4). Hidden, never disabled. */
8628
- const headlessReady = () => headlessRuntimes().some((r) => r && r.state === 'found');
8817
+ /**
8818
+ * Whether FloLess can start Claude or Codex from one of its runtime rows — THE one answer every
8819
+ * way into a conversation or a run shares (#1607): 'ready', 'setup' (FloLess sets up its own copy
8820
+ * when the conversation opens, and the chat waits for it), or 'unavailable'.
8821
+ *
8822
+ * It follows what FloLess would LAUNCH. A row carries `managed` exactly when FloLess launches its
8823
+ * own tested copy (`isManagedLaunch`, server/terminal-runtime.ts); then the user's own install is
8824
+ * irrelevant and only that copy's state counts. Without managed launch, the user's install is what
8825
+ * runs, so `state: 'found'` is the test. Anything this build cannot name fails closed.
8826
+ */
8827
+ function chatRuntimeReadiness(runtime) {
8828
+ if (!runtime || (runtime.id !== 'claude' && runtime.id !== 'codex')) return 'unavailable';
8829
+ const managed = runtime.managed;
8830
+ if (managed && typeof managed === 'object') {
8831
+ if (managed.state === 'installed') return 'ready';
8832
+ if (managed.state === 'not-installed' || managed.state === 'preparing') return 'setup';
8833
+ if (managed.state === 'failed') return managed.retryable === true ? 'setup' : 'unavailable';
8834
+ return 'unavailable';
8835
+ }
8836
+ return runtime.state === 'found' ? 'ready' : 'unavailable';
8837
+ }
8838
+ const chatRuntimeCanStart = (runtime) => chatRuntimeReadiness(runtime) !== 'unavailable';
8839
+ const chatRuntimeRow = (id) => headlessRuntimes().find((runtime) => runtime && runtime.id === id) || null;
8840
+ /** No AI FloLess can start ⇒ no run affordance anywhere (§E4). Hidden, never disabled. */
8841
+ const headlessReady = () => headlessRuntimes().some(chatRuntimeCanStart);
8842
+ // Which AI a new conversation or run starts with: the open conversation's AI, then the default,
8843
+ // then an AI that is ready now before one FloLess still has to set up. Each is checked against
8844
+ // what can start — the open conversation's AI may since have become unable to (#1607).
8629
8845
  const preferredChatProvider = () => {
8630
8846
  const current = window.flolessChat?.currentProvider?.();
8631
- if (current === 'claude' || current === 'codex') return current;
8847
+ if ((current === 'claude' || current === 'codex') && chatRuntimeCanStart(chatRuntimeRow(current))) return current;
8632
8848
  const chosen = headlessInfo?.provider;
8633
- if ((chosen === 'claude' || chosen === 'codex')
8634
- && headlessRuntimes().some((runtime) => runtime?.id === chosen && runtime.state === 'found')) return chosen;
8635
- return headlessRuntimes().find((runtime) => (runtime?.id === 'claude' || runtime?.id === 'codex')
8636
- && runtime.state === 'found')?.id || null;
8849
+ if ((chosen === 'claude' || chosen === 'codex') && chatRuntimeCanStart(chatRuntimeRow(chosen))) return chosen;
8850
+ const rows = headlessRuntimes();
8851
+ return rows.find((runtime) => chatRuntimeReadiness(runtime) === 'ready')?.id
8852
+ || rows.find((runtime) => chatRuntimeReadiness(runtime) === 'setup')?.id || null;
8637
8853
  };
8854
+
8855
+ // ── Set up first, then start (#1607) ────────────────────────────────────────
8856
+ // A project intake or a Request started in AI Chat sends its first message the moment the
8857
+ // conversation exists. If FloLess's own copy of that AI is not installed yet, that message is
8858
+ // refused ("Not sent") and nothing re-sends it after setup. So an entry point that starts a chat
8859
+ // with an AI in the 'setup' state first has FloLess set it up, waits for it, and only then starts.
8860
+ // Nothing is created while waiting, so a setup that fails or is cancelled leaves nothing behind.
8861
+ const CHAT_RUNTIME_NAMES = { claude: 'Claude', codex: 'Codex' };
8862
+ const CHAT_RUNTIME_POLL_MS = 2000;
8863
+ const CHAT_RUNTIME_READ_FAILURES = 3;
8864
+ // Why this AI could not be set up, in the AI Chat panel's own words when it can give them.
8865
+ function chatRuntimeSetupFailure(provider, status) {
8866
+ const name = CHAT_RUNTIME_NAMES[provider] || 'This AI';
8867
+ const notice = status ? window.flolessChat?.runtimeNotice?.(provider, status) : null;
8868
+ return notice && notice.title && notice.body
8869
+ ? `${notice.title}. ${notice.body}`
8870
+ : `${name} couldn’t be set up. Open AI Chat with ${name} to see why and try again.`;
8871
+ }
8872
+ /**
8873
+ * Resolves `{ ok: true }` once `provider` can take a first message, or `{ ok: false, reason }`
8874
+ * (`cancelled: true` when the caller gave up). `onProgress(status)` reports each setup status;
8875
+ * `isCancelled()` is checked between reads, so a late finish after Cancel starts nothing. The
8876
+ * install itself carries on server-side either way, as it does when AI Chat is left.
8877
+ */
8878
+ async function ensureChatRuntimeReady(provider, options = {}) {
8879
+ const result = await waitForChatRuntime(provider, options);
8880
+ // A setup that did not finish changed this AI's state: re-read it, so every Start and the
8881
+ // New project dialog show where it now stands (for example "couldn't be set up").
8882
+ if (!result.ok && !result.cancelled) await refreshChatProvidersKeepingLast();
8883
+ return result;
8884
+ }
8885
+ // What launching `provider` would see now, from a read of its own. It answers with exactly one of:
8886
+ // { row } the AI's row from THIS read's answer, whether or not that answer is published;
8887
+ // { missing: true } the read answered but lists no row for this AI, which asking again cannot fix;
8888
+ // { failed: true } the read failed, or answered without a runtime list.
8889
+ // No start decision is ever taken from the shared rows: they can predate a change, and a surface can
8890
+ // stay open for a long time between its read and the start (#1607, #1621). The answer is published
8891
+ // like every read's (publishHeadless); a failed launch read publishes nothing, so it buries nothing,
8892
+ // and every failure is logged.
8893
+ async function readChatRuntimeLaunch(provider) {
8894
+ const epoch = ++headlessFetchEpoch;
8895
+ let fresh;
8896
+ try { fresh = await api('/api/terminal-runtimes'); }
8897
+ catch (error) {
8898
+ console.warn(`floless: could not read whether ${provider} can start`, error);
8899
+ return { failed: true };
8900
+ }
8901
+ if (!fresh || !Array.isArray(fresh.runtimes)) {
8902
+ console.warn(`floless: the read of whether ${provider} can start had no runtime list`, fresh);
8903
+ return { failed: true };
8904
+ }
8905
+ publishHeadless(epoch, fresh);
8906
+ const row = fresh.runtimes.find((candidate) => candidate && candidate.id === provider) || null;
8907
+ if (!row) {
8908
+ console.warn(`floless: the runtimes read lists no ${provider} row`, fresh.runtimes.map((candidate) => candidate?.id));
8909
+ return { missing: true };
8910
+ }
8911
+ return { row };
8912
+ }
8913
+ async function waitForChatRuntime(provider, { isCancelled = () => false, onProgress = () => {} } = {}) {
8914
+ const name = CHAT_RUNTIME_NAMES[provider] || 'This AI';
8915
+ const cancelled = { ok: false, cancelled: true, reason: '' };
8916
+ const unchecked = { ok: false, reason: `FloLess couldn’t check the ${name} setup. Try again.` };
8917
+ // The server lists every AI FloLess can run, so a missing row is no blip a retry would fix.
8918
+ const unlisted = { ok: false, reason: `FloLess can’t offer ${name} right now. Choose the other AI, or restart FloLess and try again.` };
8919
+ // A cancel is honoured before and after every wait below: once the caller has given up, nothing more
8920
+ // is asked, set up or started.
8921
+ if (isCancelled()) return cancelled;
8922
+ // Decided from a fresh read, never the rows a surface was painted from: those may say "ready" for a
8923
+ // copy that has failed or gone since, and starting on them sends a first message that comes back
8924
+ // "Not sent" (#1621).
8925
+ const launch = await readChatRuntimeLaunch(provider);
8926
+ if (isCancelled()) return cancelled;
8927
+ if (launch.failed) return unchecked;
8928
+ if (launch.missing) return unlisted;
8929
+ const readiness = chatRuntimeReadiness(launch.row);
8930
+ if (readiness === 'ready') return { ok: true };
8931
+ if (readiness !== 'setup') return { ok: false, reason: `${name} can’t start on this computer. Choose the other AI, or open AI Chat with ${name} to see why.` };
8932
+ let status;
8933
+ try {
8934
+ // The Retry route: idempotent, and it retries a failed setup at once (a press is explicit intent).
8935
+ status = (await api(`/api/managed-runtimes/${encodeURIComponent(provider)}/prepare`, { method: 'POST', body: '{}' }))?.runtime;
8936
+ } catch (error) {
8937
+ console.warn(`floless: could not ask FloLess to set up ${provider}`, error);
8938
+ // A wait that ends in an error still ends after a cancel: honour it, or the re-read that follows a
8939
+ // failed setup would still be asked for a start nobody is waiting for.
8940
+ if (isCancelled()) return cancelled;
8941
+ return { ok: false, reason: `FloLess couldn’t start setting up ${name}. Try again.` };
8942
+ }
8943
+ let failedReads = 0;
8944
+ for (;;) {
8945
+ if (isCancelled()) return cancelled;
8946
+ if (status && status.state === 'installed') break;
8947
+ if (status && status.state === 'failed') return { ok: false, reason: chatRuntimeSetupFailure(provider, status), status };
8948
+ if (status) onProgress(status);
8949
+ await new Promise((resolve) => setTimeout(resolve, CHAT_RUNTIME_POLL_MS));
8950
+ if (isCancelled()) return cancelled;
8951
+ try {
8952
+ const body = await api('/api/managed-runtimes');
8953
+ const next = Array.isArray(body?.runtimes) ? body.runtimes.find((row) => row && row.runtime === provider) : null;
8954
+ if (!next) throw new Error('no status for this AI');
8955
+ status = next;
8956
+ failedReads = 0;
8957
+ } catch (error) {
8958
+ failedReads += 1;
8959
+ console.warn(`floless: could not read how the ${provider} setup is going`, error);
8960
+ if (failedReads >= CHAT_RUNTIME_READ_FAILURES) return isCancelled() ? cancelled : unchecked;
8961
+ }
8962
+ }
8963
+ // Installed is not yet launchable: read what launching would see NOW, and start only on 'ready'.
8964
+ // Published like any read, so every Start and the New project dialog see the post-install rows too.
8965
+ const installed = await readChatRuntimeLaunch(provider);
8966
+ if (isCancelled()) return cancelled;
8967
+ if (installed.failed) return unchecked;
8968
+ if (installed.missing) return unlisted;
8969
+ if (chatRuntimeReadiness(installed.row) === 'ready') return { ok: true };
8970
+ return installed.row.managed?.state === 'failed'
8971
+ ? { ok: false, reason: chatRuntimeSetupFailure(provider, installed.row.managed) }
8972
+ : unchecked;
8973
+ }
8974
+ // The one way a Request is started in AI Chat: sets the AI up first when it needs it (`discuss`
8975
+ // sends nothing, so it never waits). A setup that does not finish throws with its reason, marked
8976
+ // `chat-runtime-not-ready` so callers can show that reason instead of a generic failure. The
8977
+ // caller's `isCancelled()` (the surface closed, or the Request changed) stops it before anything is
8978
+ // started, with `chat-start-cancelled`, which callers drop silently.
8979
+ async function startRequestChatWithSetup(requestId, provider, mode, { onSetup, isCancelled = () => false } = {}) {
8980
+ if (typeof window.flolessChat?.startRequest !== 'function') throw new Error('AI Chat is still starting. Try again in a moment.');
8981
+ if (mode === 'start') {
8982
+ const ready = await ensureChatRuntimeReady(provider, { onProgress: (status) => onSetup?.(status), isCancelled });
8983
+ if (ready.cancelled || isCancelled()) throw Object.assign(new Error('The start was cancelled.'), { code: 'chat-start-cancelled' });
8984
+ if (!ready.ok) throw Object.assign(new Error(ready.reason), { code: 'chat-runtime-not-ready' });
8985
+ }
8986
+ return window.flolessChat.startRequest(requestId, provider, mode);
8987
+ }
8988
+ // Requests being started in AI Chat while FloLess sets their AI up, by request id → { label } of the
8989
+ // busy button. Kept outside the list, so a repaint during a long setup shows the same busy button
8990
+ // instead of a fresh one that invites a second start (#1607). Each Start sets its own entry object and
8991
+ // clears the entry only while it is still that object, so nothing else (a failing Discuss on the
8992
+ // same request, #1651) can end a Start that is still running.
8993
+ const requestChatStarts = new Map();
8994
+ const chatRuntimeSetupLabel = (provider) => `Setting up ${CHAT_RUNTIME_NAMES[provider] || 'AI'}…`;
8638
8995
  const runtimeLabel = (id) => {
8639
8996
  const m = headlessRuntimes().find((r) => r && r.id === id);
8640
8997
  return (m && m.label) || String(id || 'your terminal AI');
@@ -8672,6 +9029,52 @@
8672
9029
  // response must not turn an arbitrary terminal state into an implied "resume" instruction.
8673
9030
  const RESUMABLE_RUN_STATES = new Set(['needs-you', 'stopped', 'interrupted', 'contract-violation', 'exited-unresolved']);
8674
9031
 
9032
+ /**
9033
+ * A Drawing Filter answer's proposal when it passes the same strict shape AI Chat uses; null when it
9034
+ * cannot be shown. Requests has no current filter or allowed-control snapshot, so it cannot claim a
9035
+ * proposal still applies: it only mirrors the structural boundary and shows it for reference.
9036
+ */
9037
+ function filterGuideProposal(answer) {
9038
+ if (typeof answer !== 'string' || answer.length > 8_000) return null;
9039
+ let suggestion;
9040
+ try { suggestion = JSON.parse(answer); } catch { return null; }
9041
+ if (!suggestion || typeof suggestion !== 'object' || Array.isArray(suggestion)
9042
+ || Object.keys(suggestion).sort().join(',') !== 'changes,explanation,mode'
9043
+ || typeof suggestion.explanation !== 'string' || !suggestion.explanation.trim() || suggestion.explanation.length > 500
9044
+ || !Array.isArray(suggestion.changes) || suggestion.changes.length > 30
9045
+ || (suggestion.mode !== null && (typeof suggestion.mode !== 'string' || !suggestion.mode
9046
+ || suggestion.mode !== ['thickness', 'layer', 'color'].filter(dim => suggestion.mode.split('+').includes(dim)).join('+')))) return null;
9047
+ const seen = new Set();
9048
+ for (const item of suggestion.changes) {
9049
+ if (!item || typeof item !== 'object' || Array.isArray(item)
9050
+ || Object.keys(item).sort().join(',') !== 'dimension,on,value'
9051
+ || !['layer', 'thickness', 'color'].includes(item.dimension) || typeof item.on !== 'boolean'
9052
+ || (item.dimension === 'thickness' ? typeof item.value !== 'number' || !Number.isFinite(item.value)
9053
+ : typeof item.value !== 'string')) return null;
9054
+ // Match the filter core's facetKey identity: case-sensitive layers, two-decimal line
9055
+ // weights, and case-insensitive colours. A generic lowercase key mislabels both cases.
9056
+ const canonical = item.dimension === 'thickness' ? Number(item.value.toFixed(2))
9057
+ : item.dimension === 'color' ? item.value.toLowerCase() : item.value;
9058
+ const identity = `${item.dimension}\0${String(canonical)}`;
9059
+ if (seen.has(identity)) return null;
9060
+ seen.add(identity);
9061
+ }
9062
+ return suggestion;
9063
+ }
9064
+
9065
+ // Question and change share one path, so only a proposal with ticks or a match mode is a suggestion.
9066
+ function filterGuideSuggestionHtml(answer) {
9067
+ const suggestion = filterGuideProposal(answer);
9068
+ if (!suggestion) return `<div class="req-run-answer">AI's answer could not be shown. Nothing was applied or saved. Open the Drawing Filter and ask again in AI Chat.</div>`;
9069
+ const rows = suggestion.changes.map((item) => {
9070
+ const value = item.dimension === 'thickness' ? `line weight ${item.value} pt` : `${item.dimension} ${item.value}`;
9071
+ return `<li>${escapeHtml(`${item.on ? 'Include' : 'Exclude'} ${value}`)}</li>`;
9072
+ });
9073
+ if (suggestion.mode) rows.push(`<li>${escapeHtml(`Match on ${suggestion.mode.replaceAll('+', ', ')}`)}</li>`);
9074
+ if (!rows.length) return `<div class="req-run-answer"><p>${escapeHtml(suggestion.explanation)}</p></div>`;
9075
+ return `<div class="req-run-answer"><p>${escapeHtml(suggestion.explanation)}</p><ul>${rows.join('')}</ul><p>For reference only. To apply a suggestion, open the Drawing Filter and ask again in AI Chat; nothing was saved.</p></div>`;
9076
+ }
9077
+
8675
9078
  async function copyResumeCommand(command, stillOwned = () => true) {
8676
9079
  if (!command) return 'empty';
8677
9080
  if (!stillOwned()) return 'stale';
@@ -8680,14 +9083,22 @@
8680
9083
  return copied ? 'ok' : 'denied';
8681
9084
  }
8682
9085
 
8683
- function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId, commandInstance, ownRecoverySurface) {
9086
+ function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId, commandInstance, ownRecoverySurface, filterGuide = null, filterNotStarted = false) {
8684
9087
  if (!run || !run.state) return '';
9088
+ // A Drawing Filter message the run route refused before anything started (#1650). Its row already
9089
+ // says so (filterGuideRequestNote); the failed run a late refusal leaves behind adds no second note,
9090
+ // badge or private folder, only what the refused attempt printed.
9091
+ if (filterGuide && filterNotStarted) {
9092
+ return run.lastOutput
9093
+ ? `<div class="req-run-status"><details class="req-run-output"><summary>Show what it printed</summary><pre>${escapeHtml(run.lastOutput)}</pre></details></div>`
9094
+ : '';
9095
+ }
8685
9096
  const v = RUN_VIEW[run.state] || { badge: String(run.state), cls: 'muted', note: () => '' };
8686
9097
  const rt = runtimeLabel(run.runtime);
8687
9098
  // `resumeCommand` belongs to the SERVER'S request view, not persisted `run` metadata: the
8688
9099
  // store deliberately carries only runtime/session identity, while terminal-runtime.ts owns argv.
8689
- const resumeCommand = RESUMABLE_RUN_STATES.has(run.state) ? stampedResumeCommand : null;
8690
- const handoffs = desktopHandoffs && RESUMABLE_RUN_STATES.has(run.state) ? desktopHandoffs : null;
9100
+ const resumeCommand = !filterGuide && RESUMABLE_RUN_STATES.has(run.state) ? stampedResumeCommand : null;
9101
+ const handoffs = !filterGuide && desktopHandoffs && RESUMABLE_RUN_STATES.has(run.state) ? desktopHandoffs : null;
8691
9102
  const claim = handoffs && handoffs.claim;
8692
9103
  const providers = handoffs && handoffs.preferredProvider === 'claude' ? ['claude', 'codex'] : ['codex', 'claude'];
8693
9104
  const availableProviders = handoffs ? providers.filter((provider) => handoffs[provider].available) : [];
@@ -8726,7 +9137,18 @@
8726
9137
  // read is waiting on Save in Drawing Filter, not on an answer to a stopped session. So those rows
8727
9138
  // keep the note master gives them. The refusal below keeps its own separate test: having a next
8728
9139
  // action is why the generic "can't be continued" is withheld there, not a reason to state it.
8729
- const note = v.note(rt, !noRecovery || !!ownRecoverySurface);
9140
+ // An unreadable answer claims nothing is available: its body below already says it could not be shown.
9141
+ const proposal = filterGuide === 'change' && run.state === 'answered' ? filterGuideProposal(run.answer) : null;
9142
+ // A waiting Drawing Filter row already says its answer is being prepared and where it will appear
9143
+ // (filterGuideRequestNote); the generic running note beside it would say the same thing twice.
9144
+ const filterWaiting = filterGuide && ['queued', 'running', 'starting'].includes(run.state);
9145
+ const note = filterGuide && run.state === 'answered'
9146
+ ? (filterGuide !== 'change' ? 'AI answer available here for reference. No selection was changed by this question.'
9147
+ : !proposal ? ''
9148
+ : proposal.changes.length || proposal.mode ? 'AI suggestion available here for reference. Nothing was applied or saved.'
9149
+ : 'AI answer available here for reference. Nothing was applied or saved.')
9150
+ : filterWaiting ? ''
9151
+ : v.note(rt, !noRecovery || !!ownRecoverySurface);
8730
9152
  // The refusal answers "why is there no button", so it is owed whenever the recovery is missing —
8731
9153
  // never conditioned on the folder, which is the one part of this row that may legitimately be
8732
9154
  // absent. A run with neither would otherwise show the same dead end with even less to read.
@@ -8748,7 +9170,8 @@
8748
9170
  <span class="req-run-badge req-run-badge-${v.cls}">${escapeHtml(v.badge)}</span>
8749
9171
  </div>
8750
9172
  ${note ? `<p class="req-run-note">${escapeHtml(note)}</p>` : ''}
8751
- ${run.state === 'answered' && typeof run.answer === 'string' ? `<div class="req-run-answer">${escapeHtml(run.answer)}</div>` : ''}
9173
+ ${run.state === 'answered' && typeof run.answer === 'string' && filterGuide === 'change' ? filterGuideSuggestionHtml(run.answer) : ''}
9174
+ ${run.state === 'answered' && typeof run.answer === 'string' && filterGuide !== 'change' ? `<div class="req-run-answer">${escapeHtml(run.answer)}</div>` : ''}
8752
9175
  ${run.question ? `<p class="req-run-question">${escapeHtml(run.question)}</p>` : ''}
8753
9176
  ${desktop}
8754
9177
  ${terminalFallback}
@@ -8816,7 +9239,8 @@
8816
9239
  let info;
8817
9240
  try { info = await api(`/api/terminal-runtimes${key ? `?project=${encodeURIComponent(key)}` : ''}`); }
8818
9241
  catch (e) { reportErr(e); return null; }
8819
- const found = (info.runtimes || []).filter((r) => r && r.state === 'found');
9242
+ // Every AI FloLess can start (#1607): a copy FloLess sets up itself counts, as it does for ▶.
9243
+ const found = (info.runtimes || []).filter((r) => chatRuntimeCanStart(r));
8820
9244
  if (!found.length) { showToast('No supported AI provider is installed on this computer.', 'warn'); return null; }
8821
9245
  let folder = info.folder || '';
8822
9246
  let sub = problem || '';
@@ -8929,6 +9353,9 @@
8929
9353
  showModal($m);
8930
9354
  const shell = $m.querySelector('.modal.request-help');
8931
9355
  if (shell) { try { shell.focus(); } catch { /* not focusable */ } }
9356
+ // Only a read that begins after this point may move the handoff (see loadRequests), and the
9357
+ // caller's own refreshes began before it — so ask for one, or the handoff could keep a stale Start.
9358
+ void loadRequests();
8932
9359
  // Detection is a fetch, and this modal is opened synchronously by the caller. Reveal the split
8933
9360
  // when the answer lands rather than blocking the modal on it — and only if THIS request is
8934
9361
  // still the one on screen, since a second queue can land while the first fetch is in flight.
@@ -8947,6 +9374,31 @@
8947
9374
  return requestHelpEpoch === epoch && !requestHelpReq && !modal.classList.contains('show');
8948
9375
  }
8949
9376
 
9377
+ // Who is driving a Request. `chatConversation` is server-owned: `executionOwner: 'chat'` is
9378
+ // stamped only when the read was really STARTED in the AI Chat panel ('discussion' means a
9379
+ // conversation is open but nothing was started). Ownership never expires, so it cannot say
9380
+ // whether AI Chat is working RIGHT NOW — the conversation's own state is the part that moves, and
9381
+ // an unrecognised state counts as not working so no surface claims motion nothing can see.
9382
+ // WORKING means the conversation is moving on its own. `awaiting-approval` (parked on an approval
9383
+ // only the person can answer) and `recovery` (the turn broke; AI Chat disables its own composer and
9384
+ // shows a recovery control) are the opposite of that, and calling them working told someone to
9385
+ // leave a stalled read running. Kept byte-identical to web/workspaces.js — a drift guard compares
9386
+ // the two declarations, because the banner and this window paint the same request on one screen.
9387
+ const CHAT_WORKING_STATES = ['starting', 'running'];
9388
+ const CHAT_BLOCKED_ACTIONS = { 'awaiting-approval': 'answer the question it is waiting on', recovery: 'use its recovery control' };
9389
+ const requestRunsInChat = (req) => req?.chatConversation?.executionOwner === 'chat';
9390
+ const requestChatStateOf = (req) => (requestRunsInChat(req) ? req?.chatConversation?.chatState ?? null : null);
9391
+ const requestWorkingInChat = (req) => CHAT_WORKING_STATES.includes(requestChatStateOf(req));
9392
+ const requestChatBlockedAction = (req) => CHAT_BLOCKED_ACTIONS[requestChatStateOf(req)] || '';
9393
+ const requestChatUnreadable = (req) => requestChatStateOf(req) === 'unreadable';
9394
+ /** One conversation can hold several Requests, so a moving chat is not proof THIS read is moving. */
9395
+ const requestChatBusyElsewhere = (req) => requestChatStateOf(req) === 'busy-elsewhere';
9396
+ // A failed or interrupted reply is not merely paused (#1611) — each names its own next step.
9397
+ const requestChatFailed = (req) => requestChatStateOf(req) === 'failed';
9398
+ const requestChatInterrupted = (req) => requestChatStateOf(req) === 'interrupted';
9399
+ /** An archived conversation's composer is disabled, so "tell it to continue" needs a restore first. */
9400
+ const requestChatArchived = (req) => requestChatStateOf(req) === 'archived';
9401
+
8950
9402
  /** Keep the upload handoff's words on the exact same runtime gate as its Start control. */
8951
9403
  function renderRequestHelpGuidance(req) {
8952
9404
  if (!req) return;
@@ -8962,21 +9414,48 @@
8962
9414
  const retainedRevisionWhy = retainedRevisionRecovery
8963
9415
  ? (req.clearWhy || 'FloLess cannot safely release this drawing read yet. Restart FloLess and open Requests again.')
8964
9416
  : '';
9417
+ // A Request AI Chat already owns must not be offered a second start: `status` stays 'pending'
9418
+ // while the conversation works, because it tracks the server-side read and not who is executing
9419
+ // it. Without this the modal re-offered "Start in AI Chat" on a read already running there.
9420
+ // ONLY while the request is still pending. `executionOwner` never expires — that is this work's
9421
+ // own premise — so a read AI Chat started and then finished, failed, or left in a status this
9422
+ // build does not know still satisfies it. Leading with the chat arm replaced "the drawing read
9423
+ // is complete, choose Review changes" with "go and nag that conversation", and dropped the
9424
+ // failed/unrecognised recovery instructions entirely.
9425
+ const chatOwnsRequest = requestRunsInChat(req) && (!isRevisionRead || isPendingRevisionRead);
8965
9426
  const canStartInChat = Boolean((req.project || req.workflowId) && preferredChatProvider()
8966
- && (!isRevisionRead || req.status === 'pending'));
9427
+ && !chatOwnsRequest && (!isRevisionRead || req.status === 'pending'));
8967
9428
  const ownerNoun = req.project ? 'project' : 'workflow';
8968
9429
  const canStartUpdatedRead = isRevisionRead && req.status === 'pending' && !isInitial && req.canRun && headlessReady();
8969
9430
  const $steps = document.getElementById('request-help-steps');
8970
9431
  const $note = document.getElementById('request-help-note');
8971
9432
  if ($steps) {
8972
- $steps.innerHTML = canStartInChat
9433
+ $steps.innerHTML = chatOwnsRequest
9434
+ ? `<div class="request-help-step"><span>1</span><p>This request is already ${requestWorkingInChat(req) ? 'running' : requestChatBusyElsewhere(req) ? 'waiting on a reply' : 'open'} in AI Chat, in the panel on the left.</p></div>`
9435
+ + `<div class="request-help-step"><span>2</span><p>${requestChatBlockedAction(req)
9436
+ ? `That conversation is waiting for you: ${escapeHtml(requestChatBlockedAction(req))}.`
9437
+ : requestChatUnreadable(req)
9438
+ ? 'FloLess could not read that conversation. Open it to check; if it will not open, use Report an issue.'
9439
+ : requestChatArchived(req)
9440
+ ? 'That conversation is archived, so its composer is disabled. Restore it first, then tell it to continue.'
9441
+ : requestChatBusyElsewhere(req)
9442
+ ? escapeHtml(requestChatBusyNextStep(req))
9443
+ : requestWorkingInChat(req)
9444
+ ? 'Continue there — there is nothing to start in this window.'
9445
+ : requestChatFailed(req)
9446
+ ? 'AI Chat’s last reply ended with an error. Open that conversation to see what went wrong, then ask it to try again — do not start this request again here.'
9447
+ : requestChatInterrupted(req)
9448
+ ? 'AI Chat’s reply stopped before it finished. Open that conversation and tell it to continue — do not start this request again here.'
9449
+ : 'Open AI Chat and tell it to continue — do not start this request again here.'}</p></div>`
9450
+ + '<div class="request-help-step"><span>3</span><p>FloLess updates the project as that conversation makes progress. A drawing read still needs you to review the Drawing Filter and press Save filter.</p></div>'
9451
+ : canStartInChat
8973
9452
  ? `<div class="request-help-step"><span>1</span><p>Choose Start in AI Chat below. The conversation opens in this ${ownerNoun}’s folder.</p></div>`
8974
9453
  + `<div class="request-help-step"><span>2</span><p>Continue in AI Chat while Claude or Codex reads the ${allPdf ? 'PDF set' : 'drawing files'}.</p></div>`
8975
9454
  + '<div class="request-help-step"><span>3</span><p>Review any question or proposed change in the same conversation before it continues.</p></div>'
8976
9455
  : canStartUpdatedRead
8977
9456
  ? '<div class="request-help-step"><span>1</span><p>Choose Start automatically below. FloLess will run the Drawing Filter preparation with your terminal AI.</p></div>'
8978
9457
  + '<div class="request-help-step"><span>2</span><p>Keep FloLess open. You can do other work while the updated drawing is prepared.</p></div>'
8979
- + '<div class="request-help-step"><span>3</span><p>When it stops, open Drawing Filter, review the selected lines, then press Save filter in the top-right corner. After Save, return to the same terminal AI and tell it to continue the drawing read.</p></div>'
9458
+ + '<div class="request-help-step"><span>3</span><p>When it stops, open Drawing Filter. Check steel, member marks, grids, dimensions, and relevant callouts; ask in AI Chat on the left if you are unsure. Then press Save filter in the top-right corner. After Save, return to the same terminal AI and tell it to continue the drawing read.</p></div>'
8980
9459
  : isRevisionRead && !isPendingRevisionRead
8981
9460
  ? req.status === 'staged'
8982
9461
  ? '<div class="request-help-step"><span>1</span><p>This drawing read is complete. Open Requests and choose Review changes.</p></div>'
@@ -8986,14 +9465,30 @@
8986
9465
  : '<div class="request-help-step"><span>1</span><p>This drawing read failed. Attach the drawing set again from Drawing Filter to retry safely.</p></div>'
8987
9466
  : '<div class="request-help-step"><span>1</span><p>Open Requests to inspect this drawing request. Update FloLess before retrying a status this version does not recognize.</p></div>'
8988
9467
  : isRevisionRead
8989
- ? '<div class="request-help-step"><span>1</span><p>Open Claude Code, Codex, or OpenCode in your project folder.</p></div>'
9468
+ ? '<div class="request-help-step"><span>1</span><p>Open Claude Code or Codex in your project folder.</p></div>'
8990
9469
  + `<div class="request-help-step"><span>2</span><p>Paste the copied request. It will read the ${allPdf ? 'PDF' : 'drawing file'} and prepare the Drawing Filter.</p></div>`
8991
- + '<div class="request-help-step"><span>3</span><p>When it stops, open Drawing Filter, review the selected lines, then press Save filter in the top-right corner. After Save, return to the same terminal AI and tell it to continue the drawing read.</p></div>'
8992
- : '<div class="request-help-step"><span>1</span><p>Open Claude Code, Codex, or OpenCode in your project folder.</p></div>'
9470
+ + '<div class="request-help-step"><span>3</span><p>When it stops, open Drawing Filter. Check steel, member marks, grids, dimensions, and relevant callouts; ask in AI Chat on the left if you are unsure. Then press Save filter in the top-right corner. After Save, return to the same terminal AI and tell it to continue the drawing read.</p></div>'
9471
+ : '<div class="request-help-step"><span>1</span><p>Open Claude Code or Codex in your project folder.</p></div>'
8993
9472
  + '<div class="request-help-step"><span>2</span><p>Paste the copied request and let your terminal AI apply it.</p></div>'
8994
9473
  + '<div class="request-help-step"><span>3</span><p>Return here to check the result in FloLess.</p></div>';
8995
9474
  }
8996
- if ($note) $note.textContent = canStartInChat
9475
+ if ($note) $note.textContent = chatOwnsRequest
9476
+ ? requestChatBlockedAction(req)
9477
+ ? `AI Chat on the left owns this request and is waiting for you: open that conversation and ${requestChatBlockedAction(req)}. It carries on once you do.`
9478
+ : requestChatUnreadable(req)
9479
+ ? 'AI Chat on the left owns this request, but FloLess could not read that conversation. Open it to check. If it will not open, use Report an issue rather than starting the request again.'
9480
+ : requestChatArchived(req)
9481
+ ? 'AI Chat on the left owns this request, and that conversation is archived — its composer is disabled until you restore it. Restore it and tell it to continue, rather than starting the request again.'
9482
+ : requestChatBusyElsewhere(req)
9483
+ ? `AI Chat on the left owns this request. ${requestChatBusyNextStep(req)}`
9484
+ : requestWorkingInChat(req)
9485
+ ? 'AI Chat on the left already owns this request and is working on it. Leave it running; FloLess updates the project as it goes.'
9486
+ : requestChatFailed(req)
9487
+ ? 'AI Chat on the left owns this request, but its last reply ended with an error. Open that conversation to see what went wrong and ask it to try again, rather than starting the request again.'
9488
+ : requestChatInterrupted(req)
9489
+ ? 'AI Chat on the left owns this request, but its reply stopped before it finished. Open that conversation and tell it to continue, rather than starting the request again.'
9490
+ : 'AI Chat on the left owns this request but is not working on it right now. Open that conversation and tell it to continue, rather than starting the request again.'
9491
+ : canStartInChat
8997
9492
  ? `The request and its conversation stay with this ${ownerNoun}. If chat cannot start, the request remains queued and the terminal copy remains available.`
8998
9493
  : isUnknownRevisionStatus
8999
9494
  ? retainedRevisionRecovery
@@ -9011,7 +9506,7 @@
9011
9506
  : canStartUpdatedRead
9012
9507
  ? 'If a supported terminal AI is available, choose Start automatically. You can also paste the request into your terminal AI. After Save, return to that same terminal AI and tell it to continue; FloLess will show the result here.'
9013
9508
  : req.canRun
9014
- ? 'No supported terminal AI is available for automatic start here. Paste this request into Claude Code, Codex, or OpenCode. After Save, return to that same terminal AI and tell it to continue.'
9509
+ ? 'No supported terminal AI is available for automatic start here. Paste this request into Claude Code or Codex. After Save, return to that same terminal AI and tell it to continue.'
9015
9510
  : `Paste this request into your terminal AI to continue.${req.runWhy ? ` ${req.runWhy}` : ''}`
9016
9511
  : 'FloLess queues the request; your terminal AI applies it and reports the result back here.';
9017
9512
  }
@@ -9023,11 +9518,14 @@
9023
9518
  const $chat = document.getElementById('request-help-chat');
9024
9519
  const $chatMeta = document.getElementById('request-help-chat-meta');
9025
9520
  if (!$split || !$open || !$chat || !$chatMeta) return;
9026
- const can = !!(!requestHelpBusyMode && !requestHelpRunActive && requestHelpReq && requestHelpReq.canRun
9521
+ // Same gate as the wording above, for the same reason: `status` stays 'pending' while AI Chat
9522
+ // works the request, so neither start control may key off it alone.
9523
+ const chatOwns = requestRunsInChat(requestHelpReq);
9524
+ const can = !!(!requestHelpBusyMode && !requestHelpRunActive && requestHelpReq && requestHelpReq.canRun && !chatOwns
9027
9525
  && (requestHelpReq.type !== 'revision-read' || requestHelpReq.status === 'pending') && headlessReady());
9028
9526
  $split.hidden = !can;
9029
9527
  const canChat = Boolean(!requestHelpRunActive && requestHelpReq && (requestHelpReq.project || requestHelpReq.workflowId)
9030
- && preferredChatProvider() && requestHelpReq.status === 'pending');
9528
+ && preferredChatProvider() && !chatOwns && requestHelpReq.status === 'pending');
9031
9529
  $chat.hidden = !canChat;
9032
9530
  $chat.disabled = !!requestHelpBusyMode;
9033
9531
  const provider = canChat ? preferredChatProvider() : null;
@@ -9063,8 +9561,13 @@
9063
9561
  /** Fields whose change makes the upload handoff modal's guidance or Start policy stale. */
9064
9562
  function requestHelpStateKey(r) {
9065
9563
  if (!r) return '';
9564
+ // Who owns the request, and whether that conversation is working, decide this modal's steps, its
9565
+ // note AND whether its two Start controls render. Without them another tab starting the request
9566
+ // in AI Chat leaves the old handoff modal open with a live Start button on a request that now
9567
+ // has an owner — the same stale-repaint defect the revision card's key exists to stop.
9066
9568
  return [r.status, !!r.prepassReady, !!r.filterCheckpointCurrent, !!r.canRun, r.runWhy || '',
9067
- r.run && r.run.state || '', r.resumeCommand || '', !!r.desktopHandoffs].join('|');
9569
+ r.run && r.run.state || '', r.resumeCommand || '', !!r.desktopHandoffs,
9570
+ r.chatConversation?.executionOwner || '', r.chatConversation?.chatState || ''].join('|');
9068
9571
  }
9069
9572
 
9070
9573
  /**
@@ -9159,13 +9662,27 @@
9159
9662
  // has not been delivered — cleared only once it has actually flashed on a visible list, or once the
9160
9663
  // request it names is gone.
9161
9664
  let pendingRevealId = null;
9162
- let requestFetchEpoch = 0;
9665
+ // One read in flight and at most one queued behind it. Every call made during a read joins the
9666
+ // queued one, which starts only after that read is applied, so it sees whatever changed since and
9667
+ // responses land in order. Keeping only the newest response instead starved the open list and the
9668
+ // header count whenever calls (SSE, ~25 call sites) arrived faster than a read returned.
9669
+ let requestLoadInFlight = null;
9670
+ let requestLoadQueued = null;
9163
9671
  let publishedAnswerChatIds = null;
9164
9672
  async function loadRequests() {
9673
+ if (requestLoadInFlight) {
9674
+ requestLoadQueued ||= requestLoadInFlight.then(() => { requestLoadQueued = null; return loadRequests(); });
9675
+ return requestLoadQueued;
9676
+ }
9677
+ let settled;
9678
+ requestLoadInFlight = new Promise((resolve) => { settled = resolve; });
9679
+ // Every response is applied now, including one that began before the upload handoff opened. Such a
9680
+ // read predates the request, so its absence proves nothing about it — only a later read may move it.
9681
+ const helpEpochAtStart = requestHelpEpoch;
9165
9682
  try {
9166
- const epoch = ++requestFetchEpoch;
9167
- const { requests, chatPublications = [] } = await api('/api/requests');
9168
- if (epoch !== requestFetchEpoch) return;
9683
+ // Bounded: every later read waits behind this one, so a response that never arrives must not
9684
+ // freeze the list for good. The route's own lock waits give up after 60 s.
9685
+ const { requests, chatPublications = [] } = await api('/api/requests', { signal: AbortSignal.timeout(90_000) });
9169
9686
  reconcileActiveInstructorRuns(requests, chatPublications);
9170
9687
  pendingRequests = requests;
9171
9688
  const nextPublishedChatIds = new Set(chatPublications.map((publication) => publication?.chatId).filter(Boolean));
@@ -9183,7 +9700,7 @@
9183
9700
  // staged, failed, or disappears. Move to the live row, which already renders every lifecycle state.
9184
9701
  const help = requestHelpReq;
9185
9702
  const helpModal = document.getElementById('request-help-modal');
9186
- if (help && helpModal && helpModal.classList.contains('show')) {
9703
+ if (help && helpModal && helpModal.classList.contains('show') && requestHelpEpoch === helpEpochAtStart) {
9187
9704
  const fresh = requests.find((request) => request && request.id === help.id) || null;
9188
9705
  if (!fresh || requestHelpStateKey(fresh) !== requestHelpStateKey(help)) {
9189
9706
  const returnFocus = requestHelpReturnFocus;
@@ -9225,7 +9742,10 @@
9225
9742
  previousRequestIds = ids;
9226
9743
  const $rm = document.getElementById('requests-modal');
9227
9744
  if ($rm && $rm.classList.contains('show')) renderRequests(); // keep an open list live
9228
- } catch { /* non-fatal */ }
9745
+ } catch { /* non-fatal */ } finally {
9746
+ requestLoadInFlight = null;
9747
+ settled();
9748
+ }
9229
9749
  }
9230
9750
 
9231
9751
  // What the Requests window is scoped to right now: the open Workspaces project, else the open
@@ -9317,6 +9837,9 @@
9317
9837
  }
9318
9838
 
9319
9839
  function requestLabel(r) {
9840
+ if (isFilterAiGuideRequest(r))
9841
+ // One path for a question and a change, so a waiting message is never labelled a suggestion.
9842
+ return r.instructorContext.commandId === 'filter.ask-ai-change' ? 'filter answer' : 'filter question';
9320
9843
  if (r.type === 'revision-read') return (!r.baseVersion || r.baseVersion <= 0) ? 'initial drawing read' : 'updated drawing read';
9321
9844
  return r.type === 'use-template' ? 'template' : r.type === 'ui-customize' ? 'dashboard' : r.type === 'rebake' ? 're-bake' : r.type === 'guide' ? 'guide' : r.type === 'new-workflow' ? 'new workflow' : r.type === 'knowledge-organize' ? 'organize' : r.type === 'knowledge-adjust' ? 'adjust' : r.type === 'knowledge-consult' ? 'knowledge' : r.type === 'tweak-contract' ? 'contract' : 'tweak';
9322
9845
  }
@@ -9342,10 +9865,23 @@
9342
9865
  && (r.status !== 'pending' || revisionReadHasTerminalOwner(r) || requestHasActiveRun(r));
9343
9866
  }
9344
9867
 
9345
- // Once the terminal AI has prepared the Drawing Filter, copying or automatically starting the
9346
- // original request would launch a second reader against the same project. The existing terminal
9347
- // session owns the continuation; Requests must point the user back to that checkpoint instead.
9868
+ // Filter AI requests are reference-only in Requests. A copied instruction cannot restore a
9869
+ // proposal's current-sheet and current-selection checks in the Drawing Filter.
9870
+ function isFilterAiGuideRequest(r) {
9871
+ return r?.type === 'guide' && r.instructorContext?.surface === 'steel-filter'
9872
+ && ['filter.ask-ai-question', 'filter.ask-ai-change'].includes(r.instructorContext.commandId);
9873
+ }
9874
+
9348
9875
  function requestCanCopy(r) {
9876
+ // The Drawing Filter's read-only AI protocol (sent from AI Chat) must never turn into a terminal copy/retry path,
9877
+ // even when an older Requests response still carries canCopy: true.
9878
+ if (isFilterAiGuideRequest(r)) return false;
9879
+ // Nor may a request AI Chat is EXECUTING. `canCopy` is server policy about the request's
9880
+ // lifecycle and says nothing about who holds it, so it stays true throughout a chat-driven read;
9881
+ // the row button, the bulk copy and the help modal's own Copy all funnel through here. Pasting
9882
+ // that instruction into a terminal is how a second reader lands in one project folder — the
9883
+ // exact handoff this work removed from the cards. 'discussion' is not execution and keeps Copy.
9884
+ if (requestRunsInChat(r)) return false;
9349
9885
  // Current servers own this lifecycle decision together with automatic Retry and the manifest
9350
9886
  // route. The fallback is only for an older server response already cached in this tab.
9351
9887
  if (typeof r?.canCopy === 'boolean') return r.canCopy;
@@ -9379,9 +9915,19 @@
9379
9915
  && r?.preparationState !== 'blocked'
9380
9916
  && !(r?.preparationState === 'manifest-published' && !r?.prepassReady)
9381
9917
  && revisionReadCannotRestart(r)).length;
9918
+ // A request AI Chat is EXECUTING needs its own category, because `incompleteSkipped` is the
9919
+ // arithmetic remainder: without this it lands there and the toast says "did not have a complete
9920
+ // instruction", which is untrue — the instruction is complete, it is simply already held. The
9921
+ // categories stay disjoint in the same order the others do, active run first.
9922
+ const chatOwnedSkipped = shown.filter((r) => !requestHasActiveRun(r)
9923
+ && r?.preparationState !== 'blocked'
9924
+ && !(r?.preparationState === 'manifest-published' && !r?.prepassReady)
9925
+ && !revisionReadCannotRestart(r)
9926
+ && requestRunsInChat(r)).length;
9382
9927
  return {
9383
- lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped,
9384
- incompleteSkipped: dropped - drawingSkipped - activeSkipped - preparationBlockedSkipped - preparationPublishedSkipped,
9928
+ lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, chatOwnedSkipped,
9929
+ incompleteSkipped: dropped - drawingSkipped - activeSkipped - preparationBlockedSkipped
9930
+ - preparationPublishedSkipped - chatOwnedSkipped,
9385
9931
  };
9386
9932
  }
9387
9933
 
@@ -9413,15 +9959,15 @@
9413
9959
  // request with no instruction body, and reporting the list length over that is the
9414
9960
  // original bug wearing a bulk hat: the user pastes, the AI applies the ones that copied, and the
9415
9961
  // dropped request never reaches the terminal while the toast said it did.
9416
- const { lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, incompleteSkipped } = bulkCopyPlan(current);
9962
+ const { lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, chatOwnedSkipped, incompleteSkipped } = bulkCopyPlan(current);
9417
9963
  if (!lines.length) {
9418
- showToast(bulkCopyEmptyMessage({ drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, incompleteSkipped }, shown.length), 'warn');
9964
+ showToast(bulkCopyEmptyMessage({ drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, chatOwnedSkipped, incompleteSkipped }, shown.length), 'warn');
9419
9965
  return;
9420
9966
  }
9421
9967
  const copied = await copyToClipboard(lines.join('\n\n'));
9422
9968
  if (!copied) { showToast('We couldn’t copy that request. Select the text and copy it manually.', 'err'); return; }
9423
9969
  showToast(
9424
- bulkCopySuccessMessage({ lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, incompleteSkipped }, shown.length),
9970
+ bulkCopySuccessMessage({ lines, dropped, drawingSkipped, activeSkipped, preparationBlockedSkipped, preparationPublishedSkipped, chatOwnedSkipped, incompleteSkipped }, shown.length),
9425
9971
  dropped ? 'warn' : 'ok',
9426
9972
  );
9427
9973
  }
@@ -9431,6 +9977,7 @@
9431
9977
  if (plan.preparationPublishedSkipped === total) return 'Nothing to copy — drawing preparation is complete. Continue in the same AI conversation.';
9432
9978
  if (plan.drawingSkipped === total) return 'Nothing to copy — these drawing reads need review, continuation, or reattachment';
9433
9979
  if (plan.activeSkipped === total) return 'Nothing to copy — these requests are already running';
9980
+ if (plan.chatOwnedSkipped === total) return 'Nothing to copy — AI Chat holds these. Open AI Chat on the left (expand that panel if it is collapsed) to see where each one stands.';
9434
9981
  const blocked = plan.preparationBlockedSkipped
9435
9982
  ? `${plan.preparationBlockedSkipped} drawing preparation${plan.preparationBlockedSkipped === 1 ? ' needs' : 's need'} FloLess to be restarted`
9436
9983
  : '';
@@ -9441,8 +9988,11 @@
9441
9988
  ? `${plan.drawingSkipped} drawing read${plan.drawingSkipped === 1 ? ' needs' : 's need'} review, continuation, or reattachment`
9442
9989
  : '';
9443
9990
  const active = plan.activeSkipped ? `${plan.activeSkipped} already running` : '';
9991
+ const chatOwned = plan.chatOwnedSkipped
9992
+ ? `${plan.chatOwnedSkipped} ${plan.chatOwnedSkipped === 1 ? 'is' : 'are'} held by AI Chat`
9993
+ : '';
9444
9994
  const incomplete = plan.incompleteSkipped ? `${plan.incompleteSkipped} did not have a complete instruction` : '';
9445
- const reasons = [blocked, published, drawing, active, incomplete].filter(Boolean);
9995
+ const reasons = [blocked, published, drawing, active, chatOwned, incomplete].filter(Boolean);
9446
9996
  return reasons.length
9447
9997
  ? `Nothing to copy — ${reasons.join(', ')}`
9448
9998
  : 'Nothing to copy — no complete instruction is available';
@@ -9460,23 +10010,53 @@
9460
10010
  const published = plan.preparationPublishedSkipped
9461
10011
  ? `${plan.preparationPublishedSkipped} drawing preparation${plan.preparationPublishedSkipped === 1 ? ' is' : 's are'} complete and can continue in the same AI conversation`
9462
10012
  : '';
10013
+ const chatOwned = plan.chatOwnedSkipped
10014
+ ? `${plan.chatOwnedSkipped} ${plan.chatOwnedSkipped === 1 ? 'is' : 'are'} held by AI Chat`
10015
+ : '';
9463
10016
  const incomplete = plan.incompleteSkipped ? `${plan.incompleteSkipped} did not have a complete instruction` : '';
9464
- return `Copied ${plan.lines.length} of ${total} — ${[drawing, active, blocked, published, incomplete].filter(Boolean).join(', ')}`;
10017
+ return `Copied ${plan.lines.length} of ${total} — ${[drawing, active, blocked, published, chatOwned, incomplete].filter(Boolean).join(', ')}`;
9465
10018
  }
9466
10019
 
9467
10020
  /** The sentence a steel detailer needs first; the exact API handoff stays available below it. */
10021
+ function savedDrawingFilterNextStep(r) {
10022
+ const continuation = r?.filterSaveContinuation;
10023
+ if (continuation?.state === 'queued') return 'FloLess will continue the drawing read in the linked AI Chat when that conversation is ready.';
10024
+ if (continuation?.state === 'continuing') return 'FloLess sent the saved filter to the linked AI Chat. Follow that conversation for the drawing read.';
10025
+ if (continuation?.state === 'completed') return 'The linked AI Chat finished its response. Review its result in that conversation.';
10026
+ if (continuation?.nextAction) return continuation.nextAction;
10027
+ return 'Return to the same terminal AI session that prepared it and tell it to continue the drawing read.';
10028
+ }
10029
+
10030
+ /**
10031
+ * AI Chat is replying on something FloLess cannot prove is this request's (#1610): the person may
10032
+ * have asked it to continue, or asked something else. After a Drawing Filter Save, though, FloLess
10033
+ * itself queues the continuation and retries it once the conversation is free — then the queued
10034
+ * next step is the true one, and "it will not resume on its own" would contradict it. Only QUEUED:
10035
+ * every other saved-filter answer either names a person's action or, with no continuation at all,
10036
+ * falls back to the terminal-AI sentence, which is wrong for a request AI Chat owns.
10037
+ */
10038
+ function requestChatBusyNextStep(req) {
10039
+ if (req?.filterSaveContinuation?.state === 'queued') {
10040
+ return `${savedDrawingFilterNextStep(req)} Do not start it again here.`;
10041
+ }
10042
+ return 'If you already asked AI Chat to continue, the request is moving forward and this updates on its own. If not, tell it to continue once the current reply is done — it will not resume on its own. Do not start it again here.';
10043
+ }
10044
+
9468
10045
  function requestSummary(r) {
9469
10046
  if (!r || r.type !== 'revision-read') return '';
9470
10047
  if (r.preparationState === 'blocked') {
9471
10048
  return 'FloLess could not finish drawing preparation because it could not confirm that an earlier drawing reader stopped. Your drawings are still attached. Restart FloLess; if this remains blocked, open Requests and follow the detailed instructions.';
9472
10049
  }
9473
10050
  if (r.preparationState === 'manifest-published' && !r.prepassReady) {
9474
- return 'Drawing preparation is complete and the prepared data is saved. Return to the same terminal AI session and tell it to continue creating the Drawing Filter. Do not start or copy this request again.';
10051
+ return `Drawing preparation is complete and the prepared data is saved. Return to the same ${requestRunsInChat(r) ? 'AI Chat conversation' : 'terminal AI session'} and tell it to continue creating the Drawing Filter. Do not start or copy this request again.`;
10052
+ }
10053
+ if (r.status === 'pending' && r.filterSaveContinuation?.state === 'recovery-needed') {
10054
+ return `Drawing Filter needs attention. ${savedDrawingFilterNextStep(r)}`;
9475
10055
  }
9476
10056
  if (r.status === 'pending' && r.prepassReady) {
9477
10057
  return r.filterCheckpointCurrent
9478
- ? 'Drawing Filter saved. Return to the same terminal AI session that prepared it and tell it to continue the drawing read.'
9479
- : 'Drawing Filter ready. Review the selected lines, then press Save filter in the top-right corner.';
10058
+ ? `Drawing Filter saved. ${savedDrawingFilterNextStep(r)}`
10059
+ : 'Drawing Filter ready. Check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner.';
9480
10060
  }
9481
10061
  if (r.preparationRetryable) {
9482
10062
  const active = r.run && (r.run.state === 'queued' || r.run.state === 'running');
@@ -9484,7 +10064,7 @@
9484
10064
  ? 'Retrying Steel Filter preparation with the attached drawings.'
9485
10065
  : r.canRun
9486
10066
  ? 'Steel Filter preparation was interrupted. Your drawings are still attached. Choose Retry preparation to continue this same request.'
9487
- : 'Steel Filter preparation was interrupted. Your drawings are still attached. Return to the same terminal AI and retry preparation for this same request.';
10067
+ : `Steel Filter preparation was interrupted. Your drawings are still attached. Return to the same ${requestRunsInChat(r) ? 'AI Chat conversation' : 'terminal AI'} and retry preparation for this same request.`;
9488
10068
  }
9489
10069
  // A durable terminal attempt can own a pending row while automatic start is intentionally
9490
10070
  // unavailable. Its server-owned recovery is the primary summary; generic "read the drawing"
@@ -9510,7 +10090,7 @@
9510
10090
  return 'This drawing read uses a status this version of FloLess does not recognize. Update FloLess, then open Requests again. If it still appears, clear it and attach the drawing set again.';
9511
10091
  }
9512
10092
  if (r.filterCheckpointCurrent) {
9513
- return 'Drawing Filter saved. Return to the same terminal AI session that prepared it and tell it to continue the drawing read.';
10093
+ return `Drawing Filter saved. ${savedDrawingFilterNextStep(r)}`;
9514
10094
  }
9515
10095
  return (!r.baseVersion || r.baseVersion <= 0)
9516
10096
  ? 'Read the attached drawing and create the first steel model for this project.'
@@ -9641,11 +10221,16 @@
9641
10221
  if (r.preparationState === 'manifest-published' && !r.prepassReady) {
9642
10222
  return 'Drawing preparation is complete and saved. Return to the same terminal AI session and tell it to continue creating the Drawing Filter. Do not start or copy this request again.';
9643
10223
  }
10224
+ if (r.filterSaveContinuation?.state === 'recovery-needed') {
10225
+ return `Next step: ${savedDrawingFilterNextStep(r)} Do not start the request again.`;
10226
+ }
9644
10227
  if (r.filterCheckpointCurrent) {
9645
- return 'Next step: return to the same terminal AI session that prepared this Drawing Filter and tell it to continue the drawing read. Do not start the request again.';
10228
+ return `Next step: ${savedDrawingFilterNextStep(r)} Do not start the request again.`;
9646
10229
  }
9647
10230
  if (r.prepassReady) {
9648
- return 'Next step: return to Drawing Filter, review the selected lines, then press Save filter in the top-right corner. After Save, return to the terminal AI that prepared it and tell it to continue. Do not start the drawing read again.';
10231
+ return requestRunsInChat(r)
10232
+ ? 'Next step: return to Drawing Filter, check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner. FloLess will continue the drawing read in this linked AI Chat. Do not start it again.'
10233
+ : 'Next step: return to Drawing Filter, check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner. After Save, return to the terminal AI that prepared it and tell it to continue. Do not start the drawing read again.';
9649
10234
  }
9650
10235
  if (r.preparationRetryable) {
9651
10236
  const active = r.run && (r.run.state === 'queued' || r.run.state === 'running');
@@ -9655,10 +10240,31 @@
9655
10240
  ? 'Next step: choose Retry preparation on this request. FloLess kept the attached drawings and will continue the same request.'
9656
10241
  : 'Next step: return to the same terminal AI and retry preparation for this same request, or copy the retry request here. FloLess kept the attached drawings.';
9657
10242
  }
10243
+ if (requestRunsInChat(r)) {
10244
+ if (requestChatBlockedAction(r)) {
10245
+ return `This drawing read is waiting for you in AI Chat: open that conversation and ${requestChatBlockedAction(r)}. It carries on once you do.`;
10246
+ }
10247
+ if (requestChatUnreadable(r)) {
10248
+ return 'This drawing read is in an AI Chat conversation FloLess could not read. Open it to check; if it will not open, use Report an issue rather than starting the request again.';
10249
+ }
10250
+ if (requestChatArchived(r)) {
10251
+ return 'This drawing read is in an archived AI Chat conversation, whose composer is disabled. Restore that conversation, then tell it to continue the read.';
10252
+ }
10253
+ if (requestChatBusyElsewhere(r)) {
10254
+ return 'This drawing read is waiting on a reply in AI Chat. If you already asked it to continue, the read is moving forward and this updates. If not, tell it to continue once that reply is done — the read will not resume on its own.';
10255
+ }
10256
+ return requestWorkingInChat(r)
10257
+ ? 'This drawing read is running in AI Chat. Leave it running; when the Drawing Filter is ready, review the selected lines and press Save filter in the top-right corner.'
10258
+ : requestChatFailed(r)
10259
+ ? 'This drawing read stopped with an error in AI Chat. Open that conversation to see what went wrong, then ask it to try again, rather than starting the request again.'
10260
+ : requestChatInterrupted(r)
10261
+ ? 'This drawing read was interrupted in AI Chat — its reply stopped before it finished. Open that conversation and tell it to continue, rather than starting the request again.'
10262
+ : 'This drawing read is open in AI Chat but is not running. Open that conversation and tell it to continue, rather than starting the request again.';
10263
+ }
9658
10264
  const start = r.canRun && headlessReady()
9659
- ? 'copy this request into Claude Code, Codex, or OpenCode, or press Start'
9660
- : 'copy this request into Claude Code, Codex, or OpenCode';
9661
- return `Next step: ${start}. When the Drawing Filter is ready, review the selected lines and press Save filter in the top-right corner.`;
10265
+ ? 'copy this request into Claude Code or Codex, or press Start'
10266
+ : 'copy this request into Claude Code or Codex';
10267
+ return `Next step: ${start}. When the Drawing Filter is ready, check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner.`;
9662
10268
  }
9663
10269
 
9664
10270
  /** Prefer an active checkpoint, then an initial read, while skipping terminal rows in either group. */
@@ -9743,6 +10349,169 @@
9743
10349
  return { atomic: !filterActive && !keep.length && painted.length === all.length, keep, drop };
9744
10350
  }
9745
10351
 
10352
+ function filterGuideRequestNote(request) {
10353
+ // The run route refused it before anything started, and recorded that (#1650).
10354
+ if (request.filterAiNotStarted === true) {
10355
+ return 'AI did not start on this Drawing Filter message, so nothing changed. Clear it here, and send it again from AI Chat while the Drawing Filter is open.';
10356
+ }
10357
+ if (request.filterAiAdmissionUnconfirmed) {
10358
+ return 'FloLess could not confirm whether AI started. A late answer may appear here or in AI Chat. If none appears, clear this request and ask again in AI Chat while the Drawing Filter is open.';
10359
+ }
10360
+ // Every Drawing Filter message takes one path, question or change alike, so the row never calls it
10361
+ // a suggestion: a plain question gets an answer with no card.
10362
+ if (request.status === 'pending' && request.run && ['queued', 'running', 'starting'].includes(request.run.state)) {
10363
+ return 'This answer is being prepared. It will appear in AI Chat.';
10364
+ }
10365
+ if (request.status === 'pending' && !request.run) {
10366
+ return 'FloLess is checking whether AI started. If an answer arrives, it will appear in AI Chat.';
10367
+ }
10368
+ return 'For reference only. It cannot be applied here; ask again in AI Chat while the Drawing Filter is open.';
10369
+ }
10370
+
10371
+ // ── Repainting the Requests list without undoing what the user was doing (#1594) ──
10372
+ //
10373
+ // renderRequests() rebuilds the list from markup, and while the window is open it runs on every
10374
+ // request event: during an active run, every few hundred milliseconds. Markup alone cannot say which
10375
+ // disclosures the user opened ("Show detailed instructions", what a run printed), where they had
10376
+ // scrolled inside one, or which control had keyboard focus, so each rebuild snapped the panel shut,
10377
+ // jumped its scroller back to the top and dropped focus out of the window. It also ate clicks: a click
10378
+ // is a press and a release on the SAME element, and a row rebuilt between the two takes the click
10379
+ // with it. paintRequestList() is the one place the list's markup is replaced, and it carries the
10380
+ // first three across; holdRequestListRepaints() keeps a repaint from landing mid-click.
10381
+
10382
+ /** A control's tag and class under its parent's: what "the same kind of control" means in a row. */
10383
+ function requestListShape(el) {
10384
+ const of = (node) => `${node.tagName}.${node.getAttribute('class') || ''}`;
10385
+ return el.parentElement ? `${of(el.parentElement)}>${of(el)}` : of(el);
10386
+ }
10387
+
10388
+ /**
10389
+ * Names an element of the list so the SAME one can be found again after a repaint. A control with
10390
+ * an Instructor id is named by it, because that id already means "this action, on this request".
10391
+ * Anything else (a disclosure, a scroller, a thumbnail) is named by its row, its shape, and its
10392
+ * position among the elements of that shape in the row.
10393
+ */
10394
+ function requestListKey($list, el) {
10395
+ if (el.dataset && el.dataset.commandId) return { cmd: el.dataset.commandId };
10396
+ const row = el.closest('.req-item');
10397
+ const shape = requestListShape(el);
10398
+ const peers = Array.from((row || $list).querySelectorAll(el.tagName)).filter((node) => requestListShape(node) === shape);
10399
+ return { row: row ? row.dataset.id : null, tag: el.tagName, shape, n: peers.indexOf(el) };
10400
+ }
10401
+
10402
+ /** The element a requestListKey names in the list as it is now, or null when it is gone. */
10403
+ function requestListFind($list, key) {
10404
+ if (key.cmd) return Array.from($list.querySelectorAll('[data-command-id]')).find((el) => el.dataset.commandId === key.cmd) || null;
10405
+ const scope = key.row === null ? $list : Array.from($list.querySelectorAll('.req-item')).find((row) => row.dataset.id === key.row);
10406
+ if (!scope || key.n < 0) return null;
10407
+ return Array.from(scope.querySelectorAll(key.tag)).filter((el) => requestListShape(el) === key.shape)[key.n] || null;
10408
+ }
10409
+
10410
+ // Only focus the keyboard can see is carried. A mouse click focuses its button too, and handing
10411
+ // that focus back after every repaint would reopen the button's tooltip each time, wherever the
10412
+ // pointer had gone. An engine that cannot answer is treated as keyboard focus.
10413
+ function requestListFocusVisible(el) {
10414
+ try { return el.matches(':focus-visible'); } catch { return true; }
10415
+ }
10416
+
10417
+ /**
10418
+ * Replace the Requests list's markup with `html`, keeping what the user was doing. It always
10419
+ * repaints, even when nothing changed, exactly as the list did before #1594: row handlers that
10420
+ * change their row in place (a busy Start, a launch status line) rely on the next renderRequests()
10421
+ * to put it back from markup.
10422
+ *
10423
+ * While the search is unchanged, every disclosure keeps the open or closed state the user left it
10424
+ * in, and every scroller inside the list keeps its offset. A different search is the one repaint
10425
+ * that re-decides them, even when it happens to paint the same markup: the markup opens exactly the
10426
+ * disclosures whose text matches, as it always has. Search is case-blind ("held" and "HELD" find
10427
+ * and open the same rows), so the search is compared the same way. Keyboard focus is always carried
10428
+ * (see requestListFocusVisible): to the same control, else to its row, else to the row that took
10429
+ * that row's place, else to the dialog, so it never falls out of the window.
10430
+ */
10431
+ function paintRequestList($list, html, query) {
10432
+ const search = String(query || '').toLowerCase();
10433
+ const previous = $list.__requestsPaint;
10434
+ const carry = !!previous && previous.search === search;
10435
+ const disclosures = carry
10436
+ ? Array.from($list.querySelectorAll('details')).map((el) => ({ key: requestListKey($list, el), open: el.open }))
10437
+ : [];
10438
+ const scrolled = carry
10439
+ ? Array.from($list.querySelectorAll('*')).filter((el) => el.scrollTop > 0)
10440
+ .map((el) => ({ key: requestListKey($list, el), top: el.scrollTop }))
10441
+ : [];
10442
+ const active = document.activeElement;
10443
+ let focus = null;
10444
+ if (active && active !== $list && $list.contains(active) && requestListFocusVisible(active)) {
10445
+ const row = active.closest('.req-item');
10446
+ focus = {
10447
+ key: requestListKey($list, active), row: row ? row.dataset.id : null,
10448
+ index: row ? Array.from($list.querySelectorAll('.req-item')).indexOf(row) : -1,
10449
+ onRow: active === row, // the row itself held focus (a control of it went on an earlier repaint)
10450
+ };
10451
+ }
10452
+ $list.innerHTML = html;
10453
+ $list.__requestsPaint = { search };
10454
+ // Object identity is a cheap render generation: every repaint replaces this token. Async row
10455
+ // actions capture it, so a poll/search/scope repaint retires their completion even if another
10456
+ // row later reuses the same request id.
10457
+ $list.__requestPaintOwner = {};
10458
+ for (const { key, open } of disclosures) {
10459
+ const el = requestListFind($list, key);
10460
+ if (el && el.tagName === 'DETAILS') el.open = open;
10461
+ }
10462
+ for (const { key, top } of scrolled) {
10463
+ const el = requestListFind($list, key);
10464
+ if (el) el.scrollTop = top;
10465
+ }
10466
+ if (focus) {
10467
+ const same = requestListFind($list, focus.key);
10468
+ if (same) same.focus({ preventScroll: true });
10469
+ if (!same || document.activeElement !== same) {
10470
+ const rows = Array.from($list.querySelectorAll('.req-item'));
10471
+ const row = rows.find((candidate) => candidate.dataset.id === focus.row)
10472
+ || (focus.index >= 0 ? rows[Math.min(focus.index, rows.length - 1)] : null);
10473
+ if (row) {
10474
+ row.setAttribute('tabindex', '-1');
10475
+ row.addEventListener('blur', () => row.removeAttribute('tabindex'), { once: true });
10476
+ row.focus({ preventScroll: true });
10477
+ // Bring the row into view only when focus has just MOVED to it. A row that already held
10478
+ // focus stays where the user scrolled it: bringing it back on every repaint would pin the
10479
+ // list to it for as long as a running request keeps sending events.
10480
+ if (!focus.onRow || row.dataset.id !== focus.row) row.scrollIntoView({ block: 'nearest' });
10481
+ } else {
10482
+ const dialog = $list.closest('[role="dialog"]');
10483
+ if (dialog) dialog.focus({ preventScroll: true });
10484
+ }
10485
+ }
10486
+ }
10487
+ }
10488
+
10489
+ /**
10490
+ * A repaint that arrives while the primary pointer, or the Space key (a button fires on its
10491
+ * release), is held inside the list waits for the release, and then runs once, after the click that
10492
+ * release produces. Wired once, on the list element itself, which outlives every repaint.
10493
+ */
10494
+ function holdRequestListRepaints($list) {
10495
+ // Each press is held on its own (every pointer by its id, and Space): letting go of one, or of a
10496
+ // pointer that began elsewhere, must not repaint under a press still held on a row.
10497
+ const holds = new Set();
10498
+ const hold = (input) => { holds.add(input); $list.__requestsHeld = true; };
10499
+ const release = (input) => {
10500
+ if (input) holds.delete(input); else holds.clear();
10501
+ if (holds.size || !$list.__requestsHeld) return;
10502
+ $list.__requestsHeld = false;
10503
+ if (!$list.__requestsOwed) return;
10504
+ $list.__requestsOwed = false;
10505
+ setTimeout(renderRequests, 0); // a new task, so it lands after this release's click
10506
+ };
10507
+ $list.addEventListener('pointerdown', (e) => { if (e.isPrimary && e.button === 0) hold(`pointer ${e.pointerId}`); });
10508
+ $list.addEventListener('keydown', (e) => { if (e.key === ' ') hold('space'); });
10509
+ window.addEventListener('pointerup', (e) => release(`pointer ${e.pointerId}`), true);
10510
+ window.addEventListener('pointercancel', (e) => release(`pointer ${e.pointerId}`), true); // a touch scroll or a drag took the press
10511
+ window.addEventListener('keyup', (e) => { if (e.key === ' ') release('space'); }, true);
10512
+ window.addEventListener('blur', () => release(null)); // the release may happen in another window
10513
+ }
10514
+
9746
10515
  // The Requests window: every queued change in a list, with only the actions the server says are
9747
10516
  // currently safe, plus bulk actions over the available rows. The server-composed prompt (which embeds file-derived
9748
10517
  // appId/nodeId/instruction) is rendered via textContent-equivalent escaping — which matters MORE
@@ -9753,11 +10522,9 @@
9753
10522
  const $copy = document.getElementById('requests-copy');
9754
10523
  const $search = document.getElementById('requests-search');
9755
10524
  if (!$list) return;
9756
- // Object identity is a cheap render generation: every repaint replaces this token. Async row
9757
- // actions capture it, so a poll/search/scope repaint retires their completion even if another
9758
- // row later reuses the same request id.
9759
- const paintOwner = {};
9760
- $list.__requestPaintOwner = paintOwner;
10525
+ // A press still held inside the list: paint once it is released (see holdRequestListRepaints).
10526
+ // Everything waits, not only the rows, so the bulk actions keep acting on what is on screen.
10527
+ if ($list.__requestsHeld) { $list.__requestsOwed = true; return; }
9761
10528
  // Search is pointless over an empty queue, and over a single request it is just clutter.
9762
10529
  // Drop the query WITH the box, and before anything is filtered by it: a hidden filter still
9763
10530
  // filtering is how a list ends up inexplicably empty (the last two requests clear while a
@@ -9834,7 +10601,7 @@
9834
10601
  : normalizedRequestQuery
9835
10602
  ? `No request matches “${escapeHtml(normalizedRequestQuery)}”.${!requestScopeAll && inScope.length < pendingRequests.length ? ' Try All to search everything.' : ''}`
9836
10603
  : `Nothing queued for ${escapeHtml(scope ? scope.label : 'this')} — ${pendingRequests.length} item${pendingRequests.length === 1 ? '' : 's'} waiting elsewhere. <button type="button" class="req-showall">Show all</button>`;
9837
- $list.innerHTML = `<div class="empty-state">${msg}</div>`;
10604
+ paintRequestList($list, `<div class="empty-state">${msg}</div>`, normalizedRequestQuery);
9838
10605
  const $showAll = $list.querySelector('.req-showall');
9839
10606
  if ($showAll) $showAll.onclick = () => setRequestScopeAll(true);
9840
10607
  return;
@@ -9906,13 +10673,14 @@
9906
10673
  // `canRun` is server-owned policy, but persisted request JSON can outlive or be newer than this
9907
10674
  // client. A revision lifecycle this build cannot name must never gain Start through a stale or
9908
10675
  // malformed response; only the exact queued state is safe to launch.
10676
+ const filterGuide = isFilterAiGuideRequest(r);
9909
10677
  const chatExecutionOwner = r.chatConversation?.executionOwner || null;
9910
10678
  const canRunNow = headlessReady() && r.canRun && (!chatExecutionOwner || chatExecutionOwner === 'discussion')
9911
10679
  && (r.type !== 'revision-read' || r.status === 'pending')
9912
10680
  && !revisionReadHasTerminalOwner(r) && !inFlight && !desktopHandoffs && !resumeCommand;
9913
10681
  const runBtn = inFlight
9914
10682
  ? `<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>`
9915
- : canRunNow
10683
+ : canRunNow && !filterGuide
9916
10684
  ? r.preparationRetryable
9917
10685
  ? `<button class="req-run" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-retry#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Retry preparation" data-tip="Retry Steel Filter preparation with the attached drawings">▶</button>`
9918
10686
  : `<button class="req-run" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-run#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Start this request in the background" data-tip="Start this request in the background with your terminal AI">▶</button>`
@@ -9925,8 +10693,9 @@
9925
10693
  const discussBtn = chatProvider && inChatScope
9926
10694
  ? `<button class="req-chat-action" data-request-chat="discuss" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-discuss#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="${hasLinkedChat ? 'Open' : 'Discuss'} ${escapeAttr(chatLabel)} in AI Chat" data-tip="${hasLinkedChat ? 'Open the linked conversation in AI Chat' : 'Open this request in AI Chat without starting the AI'}">${hasLinkedChat ? 'Open AI Chat' : 'Discuss in AI Chat'}</button>`
9927
10695
  : '';
9928
- const startChatBtn = chatProvider && inChatScope && canRunNow
9929
- ? `<button class="req-chat-action primary" data-request-chat="start" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-start-chat#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Start ${escapeAttr(chatLabel)} in AI Chat" data-tip="Start this request in AI Chat and continue there">Start in AI Chat</button>`
10696
+ const starting = requestChatStarts.get(r.id)?.label;
10697
+ const startChatBtn = chatProvider && inChatScope && canRunNow && !filterGuide
10698
+ ? `<button class="req-chat-action primary" data-request-chat="start" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-start-chat#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Start ${escapeAttr(chatLabel)} in AI Chat" data-tip="Start this request in AI Chat and continue there"${starting ? ' disabled aria-busy="true"' : ''}>${escapeHtml(starting || 'Start in AI Chat')}</button>`
9930
10699
  : '';
9931
10700
  const chatMeta = chatProvider && inChatScope
9932
10701
  ? `<span class="req-chat-meta">AI Chat · ${escapeHtml(runtimeLabel(chatProvider))} · ${r.type === 'guide' || (r.type === 'tweak-contract' && r.mode === 'query') ? 'Read only' : 'Working folder write'}</span>`
@@ -9939,9 +10708,13 @@
9939
10708
  <div class="req-head"><span class="${badgeCls}">${label}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, normalizedRequestQuery)}</span>` : ''}${time}</div>
9940
10709
  ${r.type === 'revision-read'
9941
10710
  ? `<div class="req-instruction req-summary">${highlightQuery(requestSummary(r), normalizedRequestQuery)}</div><details class="req-technical"${normalizedRequestQuery && `${instructionFor(r)} ${r.preparationDiagnostic || ''}`.toLowerCase().includes(normalizedRequestQuery.toLowerCase()) ? ' open' : ''}><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)}${r.preparationDiagnostic ? `\n\n${r.preparationDiagnostic}` : ''}`, normalizedRequestQuery)}</div></details>`
10711
+ : filterGuide
10712
+ ? `<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>`
9942
10713
  : `<div class="req-instruction">${highlightQuery(instructionFor(r), normalizedRequestQuery) || 'This request has no instructions to send. Remove it and create the request again.'}</div>`}
9943
10714
  ${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>` : ''}
9944
- ${runStatusHtml(run, resumeCommand, desktopHandoffs, r.id, commandInstance, ownRecoverySurface)}
10715
+ ${runStatusHtml(run, resumeCommand, desktopHandoffs, r.id, commandInstance, ownRecoverySurface,
10716
+ filterGuide
10717
+ ? (r.instructorContext.commandId === 'filter.ask-ai-change' ? 'change' : 'question') : null, r.filterAiNotStarted === true)}
9945
10718
  ${r.status === 'pending' && !revisionReadHasTerminalOwner(r) && !r.canRun && r.runWhy && (anyRunnable || r.type === 'revision-read') ? `<div class="req-why-not">Why there is no automatic start: ${escapeHtml(r.runWhy)}</div>` : ''}
9946
10719
  ${auditRefusalHtml(r)}
9947
10720
  </div>
@@ -9954,35 +10727,75 @@
9954
10727
  </div>
9955
10728
  </div>`;
9956
10729
  }).join('');
9957
- $list.innerHTML = queuedHtml;
10730
+ paintRequestList($list, queuedHtml, normalizedRequestQuery);
10731
+ const paintOwner = $list.__requestPaintOwner;
9958
10732
  $list.querySelectorAll('[data-request-chat]').forEach((button) => {
9959
10733
  button.onclick = async () => {
9960
10734
  const request = pendingRequests.find((candidate) => candidate?.id === button.dataset.id);
9961
10735
  const provider = preferredChatProvider();
9962
10736
  if (!request || !provider || typeof window.flolessChat?.startRequest !== 'function') return;
9963
10737
  const original = button.textContent;
10738
+ const starting = button.dataset.requestChat === 'start';
10739
+ if (starting && requestChatStarts.has(request.id)) return;
9964
10740
  button.disabled = true;
9965
10741
  button.setAttribute('aria-busy', 'true');
9966
- button.textContent = button.dataset.requestChat === 'start' ? 'Starting…' : 'Opening…';
10742
+ button.textContent = starting ? 'Starting…' : 'Opening…';
10743
+ const startEntry = starting ? { label: button.textContent } : null;
10744
+ if (startEntry) requestChatStarts.set(request.id, startEntry);
10745
+ // Only the Start that set the entry may clear it; a Discuss never owns one (#1651).
10746
+ const endStart = () => {
10747
+ if (startEntry && requestChatStarts.get(request.id) === startEntry) requestChatStarts.delete(request.id);
10748
+ };
9967
10749
  const actionStatus = document.getElementById('requests-action-status');
9968
10750
  if (actionStatus) actionStatus.textContent = `${button.textContent} ${requestLabel(request)} for ${requestOwnerName(request)}.`;
10751
+ let settingUp = false;
9969
10752
  const slowTimer = setTimeout(() => {
9970
- if (button.disabled && button.isConnected && actionStatus) {
10753
+ if (!settingUp && button.disabled && button.isConnected && actionStatus) {
9971
10754
  actionStatus.textContent = `Still opening ${requestLabel(request)} in AI Chat… FloLess is taking longer than expected.`;
9972
10755
  }
9973
10756
  }, 4000);
10757
+ const requestsModal = document.getElementById('requests-modal');
10758
+ // Closing Requests cancels a start that is still waiting for setup, as does the Request
10759
+ // leaving the queue (cleared, or started somewhere else meanwhile).
10760
+ const cancelled = () => !requestsModal?.classList.contains('show')
10761
+ || !pendingRequests.some((candidate) => candidate && candidate.id === request.id && candidate.status === 'pending');
9974
10762
  try {
9975
- await window.flolessChat.startRequest(request.id, provider, button.dataset.requestChat === 'start' ? 'start' : 'discuss');
10763
+ await startRequestChatWithSetup(request.id, provider, starting ? 'start' : 'discuss', {
10764
+ isCancelled: cancelled,
10765
+ // FloLess is installing its own copy of this AI first (#1607): say so, once per state.
10766
+ onSetup: (status) => {
10767
+ const notice = window.flolessChat?.runtimeNotice?.(provider, status);
10768
+ const text = notice?.body || `FloLess is setting up ${runtimeLabel(provider)} before it starts this request.`;
10769
+ const label = chatRuntimeSetupLabel(provider);
10770
+ if (startEntry) startEntry.label = label;
10771
+ // The list may have been repainted meanwhile: label whichever button shows this Request now.
10772
+ const live = $list.querySelector(`[data-request-chat="start"][data-id="${CSS.escape(request.id)}"]`);
10773
+ if (live) live.textContent = label;
10774
+ if (actionStatus && (!settingUp || actionStatus.textContent !== text)) actionStatus.textContent = text;
10775
+ settingUp = true;
10776
+ },
10777
+ });
9976
10778
  closeRequests();
9977
10779
  } catch (error) {
9978
- reportErr(error);
9979
- if (actionStatus) actionStatus.textContent = `Couldn’t ${button.dataset.requestChat === 'start' ? 'start' : 'open'} ${requestLabel(request)} in AI Chat. Try again.`;
10780
+ if (error?.code === 'chat-start-cancelled') return;
10781
+ const notReady = error?.code === 'chat-runtime-not-ready';
10782
+ if (notReady) showToast(error.message, 'warn');
10783
+ else reportErr(error);
10784
+ if (actionStatus) actionStatus.textContent = notReady
10785
+ ? error.message
10786
+ : `Couldn’t ${starting ? 'start' : 'open'} ${requestLabel(request)} in AI Chat. Try again.`;
10787
+ if (notReady || !button.isConnected) {
10788
+ endStart();
10789
+ renderRequests();
10790
+ return;
10791
+ }
9980
10792
  button.disabled = false;
9981
10793
  button.removeAttribute('aria-busy');
9982
10794
  button.textContent = original;
9983
10795
  button.focus();
9984
10796
  } finally {
9985
10797
  clearTimeout(slowTimer);
10798
+ endStart();
9986
10799
  }
9987
10800
  };
9988
10801
  });
@@ -10191,6 +11004,10 @@
10191
11004
  : document.activeElement instanceof HTMLElement ? document.activeElement : null;
10192
11005
  $requestsModal.classList.add('show');
10193
11006
  if ($requestsDialog) $requestsDialog.focus();
11007
+ // A fresh open is a fresh list, like the scope and search above: nothing a previous visit opened
11008
+ // or scrolled carries into it (#1594).
11009
+ const $list = document.getElementById('requests-list');
11010
+ if ($list) $list.__requestsPaint = null;
10194
11011
  renderRequests(); // paint the cache immediately — no empty flash
10195
11012
  // Scroll off the CACHED paint, before the refetch. Gating the reveal on `/api/requests` means an
10196
11013
  // arbitrarily slow response leaves the list sitting at the top — precisely the state this feature
@@ -10741,13 +11558,60 @@
10741
11558
  });
10742
11559
 
10743
11560
  function runtimeSectionSummary(runtimes, active, folder) {
10744
- const installed = runtimes.filter((runtime) => runtime.state === 'found');
10745
- const selected = installed.find((runtime) => runtime.id === active);
11561
+ // What FloLess would LAUNCH (#1622): its own copy where it runs one, else the user's install.
11562
+ const installed = runtimes.filter(runtimeCopyInstalled);
11563
+ // The default is whichever AI FloLess would start (#1607): on a computer where FloLess runs its
11564
+ // own copy that need not be a user install, and the server's default already follows that.
11565
+ const selected = runtimes.find((runtime) => runtime.id === active && chatRuntimeCanStart(runtime));
10746
11566
  const provider = selected ? `${selected.label} default` : 'No default terminal AI';
10747
11567
  const count = `${installed.length} installed`;
10748
11568
  return `${provider} · ${count} · ${folder ? `Runs in ${folder}` : 'Folder not chosen'}`;
10749
11569
  }
10750
11570
 
11571
+ // FloLess's own copy's launch status, when FloLess runs its own copy of this AI (#1607), else null.
11572
+ const runtimeManagedStatus = (runtime) => (runtime && runtime.managed && typeof runtime.managed === 'object' ? runtime.managed : null);
11573
+ // Whether the copy FloLess would launch is on this computer now: its own copy where it runs one,
11574
+ // else the user's install.
11575
+ function runtimeCopyInstalled(runtime) {
11576
+ const managed = runtimeManagedStatus(runtime);
11577
+ return managed ? managed.state === 'installed' : runtime.state === 'found';
11578
+ }
11579
+
11580
+ /**
11581
+ * What a Terminal AI card says about the copy FloLess actually runs (#1622), when that is FloLess's
11582
+ * own copy: the badge, one plain-English line, and whether the badge is a warning. The state is
11583
+ * `chatRuntimeReadiness`'s, so the card cannot disagree with Default, Use this one or any Start.
11584
+ * A failure is worded by the AI Chat panel's own runtimeNotice, the sentence the chat shows for it.
11585
+ * Returns null without managed launch: then the user's own install is what runs, and the card
11586
+ * describes that.
11587
+ */
11588
+ function managedRuntimeCard(runtime) {
11589
+ const managed = runtimeManagedStatus(runtime);
11590
+ if (!managed) return null;
11591
+ const readiness = chatRuntimeReadiness(runtime);
11592
+ if (readiness === 'ready') return { badge: 'Installed', line: `FloLess runs its own tested copy of ${runtime.label}.`, warn: false };
11593
+ if (managed.state === 'preparing') {
11594
+ return {
11595
+ badge: 'Setting up…',
11596
+ line: managed.owner === 'another-process'
11597
+ ? 'Another FloLess window is setting up its own tested copy.'
11598
+ : 'FloLess is setting up its own tested copy now.',
11599
+ warn: false,
11600
+ };
11601
+ }
11602
+ if (managed.state === 'not-installed') {
11603
+ return { badge: 'Not set up yet', line: 'FloLess sets up its own tested copy the first time you start a chat with it.', warn: false };
11604
+ }
11605
+ // Any other state (unsupported here, or one a newer FloLess reports) says nothing about a setup
11606
+ // having been tried, so it is not called a failure — only that FloLess cannot start this copy.
11607
+ if (managed.state !== 'failed') {
11608
+ return { badge: 'Unavailable', line: `FloLess can’t run its own copy of ${runtime.label} on this computer.`, warn: false };
11609
+ }
11610
+ const why = window.flolessChat?.runtimeNotice?.(runtime.id, managed)?.body;
11611
+ const line = why || 'FloLess couldn’t set up its own copy on this computer.';
11612
+ return { badge: 'Setup failed', line: readiness === 'setup' ? `${line} Starting a chat tries again.` : line, warn: true };
11613
+ }
11614
+
10751
11615
  function setRuntimeSectionExpanded(expanded) {
10752
11616
  runtimeSectionExpanded = !!expanded;
10753
11617
  const $toggle = document.getElementById('int-runtimes-toggle');
@@ -10856,12 +11720,20 @@
10856
11720
  const signInTip = 'FloLess uses whichever account is signed in to the Claude Code or Codex CLI on this computer. Signing in to the Claude desktop app or claude.ai does not change it. Switch account signs that CLI out first, then opens a window where you sign in.';
10857
11721
  $list.innerHTML = rts.map((r) => {
10858
11722
  const found = r.state === 'found';
10859
- const isDefault = found && r.id === active;
11723
+ // Default and "Use this one" follow what FloLess can start (#1607), like the server's default.
11724
+ const canStart = chatRuntimeCanStart(r);
11725
+ const isDefault = canStart && r.id === active;
11726
+ // Where FloLess runs its own copy, the badge and the line under the name describe THAT copy
11727
+ // (#1622): the user's own install says nothing about what a chat would launch. Otherwise they
11728
+ // describe the user's install, which is then what runs.
11729
+ const managedCard = managedRuntimeCard(r);
11730
+ // Dimmed only when FloLess cannot start it: a copy FloLess has yet to set up is not missing.
11731
+ const dimmed = managedCard ? !canStart : !found;
10860
11732
  const answer = runtimeSignInAnswer(r.account);
10861
- // A missing user install can still have a managed copy that signs in: the account line
10862
- // follows the account, not the badge. An answer that names one — or says it is signed in with
10863
- // nothing to name — is such a copy; "signed out" and "could not check" are not.
10864
- const showsAccount = found || answer.state === 'signed-in' || answer.state === 'no-identity';
11733
+ // The account is read through whatever FloLess would launch, so the line shows once that copy
11734
+ // is on this computer. An answer that names an account — or says it is signed in with nothing
11735
+ // to name — is shown whatever the badge says; "signed out" and "could not check" are not.
11736
+ const showsAccount = runtimeCopyInstalled(r) || answer.state === 'signed-in' || answer.state === 'no-identity';
10865
11737
  const pending = pendingRuntimeSignIn.has(r.id);
10866
11738
  // Both cards render the same visible "Switch account…", so without a runtime-specific
10867
11739
  // accessible name a screen reader (and Instructor's focus proof) cannot tell them apart.
@@ -10870,21 +11742,23 @@
10870
11742
  // The sign-in sits on the account line it acts on. The side column is a flex row already
10871
11743
  // holding the badge and, on the non-default card, "Use this one" — a third control wraps.
10872
11744
  return `
10873
- <div class="int-rt${isDefault ? ' is-default' : ''}${found ? '' : ' is-missing'}">
11745
+ <div class="int-rt${isDefault ? ' is-default' : ''}${dimmed ? ' is-missing' : ''}">
10874
11746
  <div class="int-rt-main">
10875
11747
  <div class="int-rt-name">${escapeHtml(r.label)}${isDefault ? '<span class="int-rt-pill">Default</span>' : ''}</div>
10876
11748
  <div class="int-rt-blurb">${escapeHtml(r.blurb)} · <code>${escapeHtml(r.command)}</code></div>
10877
- <div class="int-rt-where">${found
10878
- ? `Found at ${escapeHtml(r.path || '')}`
10879
- : `Not installed — floless looks for <code>${escapeHtml(r.command)}</code>`}</div>
11749
+ ${managedCard
11750
+ ? `<div class="int-rt-copy">${escapeHtml(managedCard.line)}</div>`
11751
+ : `<div class="int-rt-where">${found
11752
+ ? `Found at ${escapeHtml(r.path || '')}`
11753
+ : `Not installed — floless looks for <code>${escapeHtml(r.command)}</code>`}</div>`}
10880
11754
  ${showsAccount ? `<div class="int-rt-signin">
10881
11755
  <div class="int-rt-account" aria-live="polite" data-tip="${escapeAttr(signInTip)}">${escapeHtml(runtimeAccountLabel(r.account))}</div>
10882
11756
  <button class="int-action" data-sign-in="${escapeAttr(r.id)}" data-command-id="shell.headless-sign-in#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.label)}" aria-label="${escapeAttr(signInName)}" data-tip="${escapeAttr(signInTip)}"${pending ? ' disabled data-blocked-reason="Waiting for the sign-in window."' : ''}>${pending ? 'Waiting for sign-in…' : answer.state === 'signed-out' ? 'Sign in…' : 'Switch account…'}</button>
10883
11757
  </div>` : ''}
10884
11758
  </div>
10885
11759
  <div class="int-rt-side">
10886
- <span class="int-rt-badge">${found ? 'Installed' : 'Not installed'}</span>
10887
- ${found && !isDefault ? `<button class="int-action" data-rt="${escapeAttr(r.id)}" data-command-id="shell.headless-runtime#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.label)}">Use this one</button>` : ''}
11760
+ <span class="int-rt-badge${managedCard?.warn ? ' is-warn' : ''}">${escapeHtml(managedCard ? managedCard.badge : found ? 'Installed' : 'Not installed')}</span>
11761
+ ${canStart && !isDefault ? `<button class="int-action" data-rt="${escapeAttr(r.id)}" data-command-id="shell.headless-runtime#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.label)}">Use this one</button>` : ''}
10888
11762
  </div>
10889
11763
  </div>`;
10890
11764
  }).join('');
@@ -11045,6 +11919,31 @@
11045
11919
  }).join('')}</div>`;
11046
11920
  }
11047
11921
 
11922
+ // An OAuth row's endpoint list stays on one clipped line (reference detail, not something the
11923
+ // person must read to act), but a clipped line must never be a dead end (#1524): when it
11924
+ // actually overflows it carries the full text as a themed data-tip and becomes focusable, so
11925
+ // hover AND keyboard reach the rest. A line that fits gets neither — no redundant tip, no
11926
+ // extra tab stop. It measures live layout, so its callers run it only while the modal is shown.
11927
+ function offerClippedScopeLines(root) {
11928
+ root.querySelectorAll('.int-scopes:not(.int-setup-detail)').forEach((line) => {
11929
+ if (line.scrollWidth > line.clientWidth) {
11930
+ line.setAttribute('data-tip', line.textContent);
11931
+ line.setAttribute('tabindex', '0');
11932
+ } else {
11933
+ line.removeAttribute('data-tip');
11934
+ line.removeAttribute('tabindex');
11935
+ }
11936
+ });
11937
+ }
11938
+ // A line's clip changes with the list's width (a narrower window squeezes the modal), not only
11939
+ // on render, so re-measure when the list resizes. The list lives for the whole page, so this
11940
+ // observer does too; a hidden modal measures as zero width and is skipped — opening it re-renders.
11941
+ if (typeof ResizeObserver === 'function') {
11942
+ new ResizeObserver(() => {
11943
+ if ($integrationsModal.classList.contains('show')) offerClippedScopeLines($integrationsList);
11944
+ }).observe($integrationsList);
11945
+ }
11946
+
11048
11947
  renderIntegrations = function renderIntegrationsReal() {
11049
11948
  if (integrationsLoadState === 'loading' || integrationsLoadState === 'idle') {
11050
11949
  $integrationsList.innerHTML = '<div class="empty-state">Checking integrations…</div>';
@@ -11088,16 +11987,19 @@
11088
11987
  : 'Revit model access is not included for this account. Ask the account owner to add it.';
11089
11988
  const checkLabel = needsAttention ? 'Try setup again' : needsAccount ? 'Choose account'
11090
11989
  : ready ? 'Check status' : 'Check access again';
11091
- return `<div class="int-item int-${escapeAttr(i.status)}" data-integration-id="xeorvt" tabindex="-1"${missingReader ? ' aria-describedby="xeorvt-setup-detail"' : ''}>
11990
+ // The Revit detail is always a sentence the person must finish reading (#1524), so it
11991
+ // always wraps (int-setup-detail) and always describes the card — never the one-line clip
11992
+ // the OAuth rows' endpoint list uses.
11993
+ return `<div class="int-item int-${escapeAttr(i.status)}" data-integration-id="xeorvt" tabindex="-1" aria-describedby="xeorvt-setup-detail">
11092
11994
  <div class="int-icon">R</div><div class="int-info">
11093
11995
  <div class="int-name">${escapeHtml(i.name)}</div>
11094
11996
  <div class="int-kind">Revit project integration · provided by FloLess</div>
11095
- <div class="int-scopes${missingReader ? ' int-setup-detail' : ''}"${missingReader ? ' id="xeorvt-setup-detail"' : ''}>${escapeHtml(detail)}</div>
11997
+ <div class="int-scopes int-setup-detail" id="xeorvt-setup-detail">${escapeHtml(detail)}</div>
11096
11998
  <div class="int-row"><span class="int-badge int-badge-${ready ? 'connected' : needsAttention ? 'expired' : 'disconnected'}">${badge}</span>
11097
11999
  <span class="int-recovery-actions">
11098
12000
  ${ready ? '<button class="int-action" data-xeorvt-action="open">Open Revit projects</button>' : ''}
11099
12001
  ${missingReader ? '<button class="int-action" data-xeorvt-action="report" data-command-id="shell.revit-report-setup-issue" aria-label="Report issue: missing Revit reader" aria-describedby="xeorvt-setup-detail">Report issue</button>' : ''}
11100
- <button class="int-action" data-xeorvt-action="${needsAccount ? 'account' : 'check'}" data-xeorvt-retry="${needsAttention ? 'true' : 'false'}">${checkLabel}</button>
12002
+ <button class="int-action" data-xeorvt-action="${needsAccount ? 'account' : 'check'}" data-xeorvt-retry="${needsAttention ? 'true' : 'false'}"${needsAttention ? ' aria-describedby="xeorvt-setup-detail"' : ''}>${checkLabel}</button>
11101
12003
  </span></div></div></div>`;
11102
12004
  }
11103
12005
  const action = i.status === 'connected' ? 'Disconnect' : i.status === 'expired' ? 'Reconnect' : 'Connect';
@@ -11124,6 +12026,7 @@
11124
12026
  </div>
11125
12027
  </div>`;
11126
12028
  }).join('');
12029
+ offerClippedScopeLines($integrationsList);
11127
12030
  $integrationsList.querySelectorAll('[data-xeorvt-action]').forEach((btn) => {
11128
12031
  btn.onclick = async () => {
11129
12032
  if (btn.dataset.xeorvtAction === 'open') {
@@ -12369,6 +13272,8 @@
12369
13272
  };
12370
13273
  const $reqSearch = document.getElementById('requests-search');
12371
13274
  if ($reqSearch) $reqSearch.oninput = () => { requestQuery = $reqSearch.value; renderRequests(); };
13275
+ const $reqList = document.getElementById('requests-list');
13276
+ if ($reqList) holdRequestListRepaints($reqList);
12372
13277
  const $requestHelpModal = document.getElementById('request-help-modal');
12373
13278
  const $requestHelpOpen = document.getElementById('request-help-open');
12374
13279
  const $requestHelpKeep = document.getElementById('request-help-keep');
@@ -12416,16 +13321,32 @@
12416
13321
  const provider = preferredChatProvider();
12417
13322
  if (!req || !provider || typeof window.flolessChat?.startRequest !== 'function') return;
12418
13323
  setRequestHelpBusy('chat');
13324
+ const epoch = requestHelpEpoch;
13325
+ // Closing or reusing the modal cancels a start that is still waiting for setup (#1607).
13326
+ const gone = () => requestHelpEpoch !== epoch || requestHelpReq !== req;
12419
13327
  try {
12420
- await window.flolessChat.startRequest(req.id, provider, 'start');
13328
+ await startRequestChatWithSetup(req.id, provider, 'start', {
13329
+ isCancelled: gone,
13330
+ // FloLess is installing its own copy of this AI first (#1607).
13331
+ onSetup: (status) => {
13332
+ if (gone()) return;
13333
+ $requestHelpChat.textContent = chatRuntimeSetupLabel(provider);
13334
+ const sub = document.getElementById('request-help-sub');
13335
+ const text = window.flolessChat?.runtimeNotice?.(provider, status)?.body;
13336
+ if (sub && text && sub.textContent !== text) sub.textContent = text;
13337
+ },
13338
+ });
12421
13339
  closeRequestHelp({ restoreFocus: false });
12422
13340
  showToast(`Started in ${runtimeLabel(provider)} — continue in AI Chat`, 'ok');
12423
13341
  await loadRequests();
12424
13342
  } catch (error) {
12425
- reportErr(error);
13343
+ if (error?.code === 'chat-start-cancelled' || gone()) return;
13344
+ const notReady = error?.code === 'chat-runtime-not-ready';
13345
+ if (notReady) showToast(error.message, 'warn');
13346
+ else reportErr(error);
12426
13347
  setRequestHelpBusy(null);
12427
13348
  const sub = document.getElementById('request-help-sub');
12428
- if (sub) sub.textContent = requestHelpCopied
13349
+ if (sub) sub.textContent = notReady ? error.message : requestHelpCopied
12429
13350
  ? 'The request is still in Requests. Try again, start it in the background, or use the copied instruction in your terminal.'
12430
13351
  : 'The request is still in Requests. Try again, start it in the background, or copy the terminal instruction.';
12431
13352
  if ($requestHelpCopy && !requestHelpCopied) $requestHelpCopy.hidden = false;
@@ -12831,6 +13752,10 @@
12831
13752
 
12832
13753
  window.flolessBridge = {
12833
13754
  api,
13755
+ requestScopeLabel(projectId) {
13756
+ return wsRequestScope?.kind === 'project' && wsRequestScope.project === projectId
13757
+ ? wsRequestScope.label : null;
13758
+ },
12834
13759
  // Open report HTML in the existing sandboxed HTML Viewer (same modal + srcdoc
12835
13760
  // iframe the canvas report node uses — no new sandbox surface). `savedPath` is
12836
13761
  // optional: pass the run's saved_path so a dashboard-panel run surfaces the same
@@ -12848,13 +13773,22 @@
12848
13773
  return openRequests(requestId || null);
12849
13774
  },
12850
13775
  preferredChatProvider,
13776
+ // The New project dialog's AI choice (#1605): the installed Claude/Codex rows as last read, and
13777
+ // a fresh read of them. The same shared runtime state preferredChatProvider() answers from, so
13778
+ // the dialog's default and its options can never disagree.
13779
+ chatProviderRuntimes: () => headlessRuntimes().filter((runtime) => runtime && (runtime.id === 'claude' || runtime.id === 'codex')),
13780
+ // The one shared "can this AI start" answer (#1607), so the dialog cannot re-derive its own.
13781
+ chatRuntimeReadiness,
13782
+ // Set FloLess's own copy of an AI up before a start sends its first message (#1607).
13783
+ ensureChatRuntimeReady,
13784
+ refreshChatProviders: () => refreshChatProvidersKeepingLast(),
12851
13785
  async startRequestInChat(requestId, mode = 'start') {
12852
13786
  const provider = preferredChatProvider();
12853
13787
  if (!provider || typeof window.flolessChat?.startRequest !== 'function') {
12854
13788
  throw new Error('Sign in to Claude or Codex before starting this request in AI Chat.');
12855
13789
  }
12856
13790
  await window.flolessChat.refreshScope?.();
12857
- return window.flolessChat.startRequest(requestId, provider, mode);
13791
+ return startRequestChatWithSetup(requestId, provider, mode);
12858
13792
  },
12859
13793
  async startProjectChatIntake(submissionId, payload) {
12860
13794
  if (typeof window.flolessChat?.startProjectIntake !== 'function') {
@@ -12919,6 +13853,9 @@
12919
13853
  await loadRequests();
12920
13854
  return copied;
12921
13855
  },
13856
+ // The steel editor's Ask AI list: an AI the user installed that the server approved for read-only runs
13857
+ // (`canRunReadOnly`). Its start sets nothing up first, so FloLess's own copy is not offered there yet
13858
+ // (#1652). The Drawing Filter decides with `filterRuntimeLaunch` below, not with this list (#1650).
12922
13859
  async readOnlyRequestOptions() {
12923
13860
  const info = await refreshHeadless();
12924
13861
  return {
@@ -12926,6 +13863,22 @@
12926
13863
  found: headlessRuntimes().filter((runtime) => runtime && runtime.state === 'found' && runtime.canRunReadOnly === true),
12927
13864
  };
12928
13865
  },
13866
+ // The Drawing Filter's read before it sends (#1650): what launching the conversation's OWN AI would
13867
+ // see now, from a read of its own (readChatRuntimeLaunch), never the shared rows a surface was painted
13868
+ // from, which can predate FloLess's own copy going away. One read, as before, so Send waits no longer.
13869
+ // 'ready' it can start;
13870
+ // 'setup' FloLess has to set its own copy up first (not installed, being set up, gone, or a
13871
+ // failure it can retry);
13872
+ // 'unavailable' it cannot answer Drawing Filter messages on this computer (nothing FloLess can
13873
+ // start, or not approved for read-only runs);
13874
+ // 'unchecked' the read failed, so nothing is known.
13875
+ async filterRuntimeLaunch(provider) {
13876
+ const launch = await readChatRuntimeLaunch(provider);
13877
+ if (launch.failed) return { readiness: 'unchecked' };
13878
+ if (launch.missing) return { readiness: 'unavailable' };
13879
+ const readiness = chatRuntimeReadiness(launch.row);
13880
+ return { readiness: readiness !== 'unavailable' && launch.row.canRunReadOnly === true ? readiness : 'unavailable' };
13881
+ },
12929
13882
  showRequestQueuedModal,
12930
13883
  formModal, // the shared styled prompt/form modal — workspaces.js reuses it (never a native prompt)
12931
13884
  // One owner for runtime upgrades. Workspaces may open this surface but must