@floless/app 0.134.0 → 0.134.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
@@ -2214,7 +2214,7 @@
2214
2214
  // see the HEAD note below for why that is the wrong price for a word. "model or drawing" is never
2215
2215
  // WRONG, only vaguer, so the failure mode is a less specific warning rather than a false one.
2216
2216
  const noun = id === 'steel-model' ? 'steel model' : id === 'vectorize' ? 'traced drawing' : 'model or drawing';
2217
- // HEAD, not GET: this only needs the STATUS, and a contract can be 25 MB (the PUT route's body
2217
+ // HEAD, not GET: this only needs the STATUS, and a contract can be 64 MB (the PUT route's body
2218
2218
  // limit — they embed sheet rasters). Downloading that to choose a word would stall the dialog on
2219
2219
  // exactly the models most worth warning about. Fastify serves HEAD for every GET route, and the
2220
2220
  // three cases the copy distinguishes come back identically: 200 = something saved, 204 = nothing,
@@ -2754,7 +2754,7 @@
2754
2754
  // These two card tips are owned by this renderer. Clear them before recomputing state so an
2755
2755
  // in-place contract/project refresh cannot leave "Double-click to open…" over disabled actions.
2756
2756
  if (card.dataset.tip === 'Double-click to open the contract editor'
2757
- || card.dataset.tip === 'Double-click to open the steel filter') {
2757
+ || card.dataset.tip === 'Double-click to open the Drawing Filter') {
2758
2758
  delete card.dataset.tip;
2759
2759
  }
2760
2760
  if (isInput) addNodeInputs(card); // current values, above the button
@@ -2847,7 +2847,7 @@
2847
2847
  }
2848
2848
  const filterBtn = addNodeAction(card, 'Filter ▸', () => openFilterView(currentId));
2849
2849
  if (publication) filterBtn.disabled = true;
2850
- else if (!card.dataset.tip) card.dataset.tip = 'Double-click to open the steel filter';
2850
+ else if (!card.dataset.tip) card.dataset.tip = 'Double-click to open the Drawing Filter';
2851
2851
  }
2852
2852
  });
2853
2853
  if (hasTeklaAction && !teklaReadinessState) refreshTeklaReadiness();
@@ -3384,7 +3384,7 @@
3384
3384
  const ap = document.getElementById('contract-editor-approve'); if (ap) ap.hidden = true;
3385
3385
  $contractEditorTitle.replaceChildren(
3386
3386
  Object.assign(document.createElement('span'), { textContent: appId, style: 'color:var(--text);font-weight:600' }),
3387
- Object.assign(document.createElement('span'), { textContent: ' · steel filter', style: 'color:var(--text-muted)' }),
3387
+ Object.assign(document.createElement('span'), { textContent: ' · Drawing Filter', style: 'color:var(--text-muted)' }),
3388
3388
  );
3389
3389
  $contractEditorFrame.onload = () => { try { $contractEditorFrame.contentWindow.focus(); } catch (_) {} };
3390
3390
  $contractEditorFrame.src = '/steel-filter.html?app=' + encodeURIComponent(appId);
@@ -3399,7 +3399,7 @@
3399
3399
  try { guard = $contractEditorFrame.contentWindow && $contractEditorFrame.contentWindow.__floGuard; }
3400
3400
  catch (_) { guard = null; }
3401
3401
  if (guard && typeof guard.isDirty === 'function' && guard.isDirty()) {
3402
- const choice = await confirmUnsavedSwitch('', 'You have unsaved changes to the steel filter. What would you like to do?', 'Unsaved filter changes');
3402
+ const choice = await confirmUnsavedSwitch('', 'You have unsaved changes to the Drawing Filter. What would you like to do?', 'Unsaved Drawing Filter changes');
3403
3403
  if (choice === 'cancel') return; // keep the view open
3404
3404
  if (choice === 'save') { const ok = await guard.save(); if (!ok) return; } // save failed → stay open
3405
3405
  else if (choice === 'discard') { try { guard.discard(); } catch (_) {} } // silence the backstop
@@ -3881,6 +3881,16 @@
3881
3881
  return new Promise((resolve) => {
3882
3882
  if (_confirmModalOpen) { console.warn('confirmUnsavedSwitch: confirmation already open'); resolve('cancel'); return; }
3883
3883
  const returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
3884
+ // This confirmation can open above Requests. Hide and inert every lower modal from assistive
3885
+ // technology while it owns the screen; two exposed aria-modal dialogs give screen-reader and
3886
+ // keyboard users two competing interaction roots. Restore each exact prior state on settlement.
3887
+ const coveredModals = Array.from(document.querySelectorAll('.modal-backdrop.show'))
3888
+ .filter((modal) => modal !== $confirmModal)
3889
+ .map((modal) => ({ modal, inert: !!modal.inert, ariaHidden: modal.getAttribute('aria-hidden') }));
3890
+ coveredModals.forEach(({ modal }) => {
3891
+ modal.inert = true;
3892
+ modal.setAttribute('aria-hidden', 'true');
3893
+ });
3884
3894
  const $title = document.getElementById('confirm-modal-title');
3885
3895
  const $sub = document.getElementById('confirm-modal-sub');
3886
3896
  const $save = document.getElementById('confirm-save');
@@ -3901,14 +3911,23 @@
3901
3911
  settled = true;
3902
3912
  _confirmModalOpen = false;
3903
3913
  hideModal($confirmModal);
3914
+ coveredModals.forEach(({ modal, inert, ariaHidden }) => {
3915
+ modal.inert = inert;
3916
+ if (ariaHidden === null) modal.removeAttribute('aria-hidden');
3917
+ else modal.setAttribute('aria-hidden', ariaHidden);
3918
+ });
3904
3919
  $dont.hidden = false;
3905
- $save.onclick = $dont.onclick = $cancel.onclick = $confirmModal.onclick = $confirmModal.onkeydown = null;
3920
+ document.removeEventListener('keydown', onKey, true);
3921
+ $save.onclick = $dont.onclick = $cancel.onclick = $confirmModal.onclick = null;
3906
3922
  if (returnFocus && returnFocus.isConnected && !returnFocus.matches(':disabled,[aria-disabled="true"]')) returnFocus.focus();
3907
3923
  resolve(result);
3908
3924
  };
3909
3925
  const onKey = (e) => {
3910
3926
  if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); done('cancel'); }
3911
3927
  else if (e.key === 'Tab') {
3928
+ // This confirmation can sit above Requests. Own Tab here so the lower dialog's document-level
3929
+ // trap cannot pull focus behind the topmost modal.
3930
+ e.stopPropagation();
3912
3931
  const focusable = Array.from($confirmModal.querySelectorAll('button:not([disabled]):not([hidden]), [tabindex]:not([tabindex="-1"])'))
3913
3932
  .filter((el) => el instanceof HTMLElement && !el.hidden && el.getClientRects().length);
3914
3933
  if (!focusable.length) { e.preventDefault(); return; }
@@ -3924,7 +3943,10 @@
3924
3943
  $dont.onclick = () => done('discard');
3925
3944
  $cancel.onclick = () => done('cancel');
3926
3945
  onBackdropDismiss($confirmModal, () => done('cancel'));
3927
- $confirmModal.onkeydown = onKey;
3946
+ // Own these keys at the document capture boundary. Focus is moved on the next task, and a
3947
+ // nested confirmation can open above Requests while focus still sits in that lower dialog;
3948
+ // listening only on the confirmation would let that first Tab/Escape reach Requests instead.
3949
+ document.addEventListener('keydown', onKey, true);
3928
3950
  });
3929
3951
  }
3930
3952
 
@@ -4010,6 +4032,11 @@
4010
4032
  const $body = document.getElementById('form-modal-body');
4011
4033
  const $ok = document.getElementById('form-modal-ok');
4012
4034
  const $cancel = document.getElementById('form-modal-cancel');
4035
+ // The run-options form may open above Requests. Preserve and cover every lower dialog exactly
4036
+ // as the shared confirmation does: one screen must never expose two competing aria-modal roots.
4037
+ const coveredModals = Array.from(document.querySelectorAll('.modal-backdrop.show'))
4038
+ .filter((modal) => modal !== $formModal)
4039
+ .map((modal) => ({ modal, inert: !!modal.inert, ariaHidden: modal.getAttribute('aria-hidden') }));
4013
4040
  $title.textContent = title;
4014
4041
  $sub.textContent = sub || '';
4015
4042
  $sub.hidden = !sub;
@@ -4137,6 +4164,10 @@
4137
4164
  $ok.classList.toggle('primary', !danger);
4138
4165
  $cancel.classList.toggle('primary', !!danger);
4139
4166
  $cancel.hidden = !!hideCancel;
4167
+ coveredModals.forEach(({ modal }) => {
4168
+ modal.inert = true;
4169
+ modal.setAttribute('aria-hidden', 'true');
4170
+ });
4140
4171
  showModal($formModal);
4141
4172
  // Prefer a real text input; else a select's trigger; else a file drop zone (so keyboard
4142
4173
  // users land somewhere actionable rather than a possibly-disabled OK button).
@@ -4583,6 +4614,11 @@
4583
4614
  _formModalOpen = false;
4584
4615
  modalClosed = true;
4585
4616
  hideModal($formModal);
4617
+ coveredModals.forEach(({ modal, inert, ariaHidden }) => {
4618
+ modal.inert = inert;
4619
+ if (ariaHidden === null) modal.removeAttribute('aria-hidden');
4620
+ else modal.setAttribute('aria-hidden', ariaHidden);
4621
+ });
4586
4622
  $ok.onclick = null; $cancel.onclick = null; $formModal.onclick = null; $formModal.onkeydown = null; $body.onpaste = null; $body.onclick = null; $body.ondragover = null; $body.ondrop = null;
4587
4623
  $ok.classList.remove('danger'); $ok.classList.add('primary'); $cancel.classList.remove('primary'); $cancel.hidden = false; $ok.disabled = false; // reset chrome for the next caller
4588
4624
  let focusTarget = returnFocus;
@@ -4599,6 +4635,10 @@
4599
4635
  // destructive confirm where focus sits on Cancel, not in the (empty) body. Enter
4600
4636
  // commits only for a normal form (never a danger confirm; never inside a textarea).
4601
4637
  $formModal.onkeydown = (e) => {
4638
+ // Requests can remain open underneath this shared dialog. Keep its document-level trap from
4639
+ // seeing Tab/Escape: otherwise it drags focus behind the topmost form, and one Escape closes
4640
+ // both layers after `done()` synchronously removes this form's `.show` class.
4641
+ if (e.key === 'Escape' || e.key === 'Tab') e.stopPropagation();
4602
4642
  if (e.key === 'Escape') { e.preventDefault(); done(null); }
4603
4643
  else if (e.key === 'Tab') {
4604
4644
  const focusable = Array.from($formModal.querySelectorAll('button:not([disabled]):not([hidden]), input:not([disabled]):not([type="hidden"]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'))
@@ -7760,16 +7800,55 @@
7760
7800
  // tweakNode, requestGuide, requestNewWorkflow, panels.js's customize box) say only "queued, not
7761
7801
  // copied" and name no cause, so they cannot conflate anything and are deliberately left alone. Add
7762
7802
  // a new surface that names a cause and it belongs here.
7763
- async function copyRequest(req) {
7764
- const line = req ? markedInstruction(req) : '';
7803
+ async function copyRequest(req, stillOwned = () => true) {
7804
+ // Copy is a delayed UI action: a revision-read revalidates over the network and the clipboard
7805
+ // write is asynchronous too. Every rendered caller may therefore disappear or be replaced while
7806
+ // this is pending. The caller owns that surface, so let it provide the exact lifetime fence and
7807
+ // check it on BOTH sides of the authority read. `stale` is intentionally silent at the surface —
7808
+ // the newer row/card/modal now explains the truth.
7809
+ const owns = () => {
7810
+ try { return stillOwned(); } catch { return false; }
7811
+ };
7812
+ if (!owns()) return 'stale';
7813
+ let current = req;
7814
+ // A workspace card or upload modal can outlive the poll that advanced this drawing read in another
7815
+ // tab. Re-read the authoritative queue at the moment of Copy; checking only the rendered object
7816
+ // would still let that cross-tab gap copy a second writer's obsolete handoff.
7817
+ if (req?.type === 'revision-read' && req.id) {
7818
+ try {
7819
+ const latest = await api('/api/requests');
7820
+ current = Array.isArray(latest?.requests)
7821
+ ? latest.requests.find((candidate) => candidate && candidate.id === req.id)
7822
+ : null;
7823
+ } catch {
7824
+ return 'unavailable';
7825
+ }
7826
+ if (!current) return 'settled';
7827
+ }
7828
+ if (!owns()) return 'stale';
7829
+ // Refuse at the shared copy boundary too, so no rendered race can launch a second handoff.
7830
+ if (requestHasActiveRun(current)) return 'active';
7831
+ // The same boundary must also reject a drawing read that moved to Filter review, completion,
7832
+ // failure, or an unfamiliar terminal state after its Copy carrier rendered. The row already uses
7833
+ // requestCanCopy; enforcing it again here prevents a stale click from claiming obsolete
7834
+ // instructions were copied successfully.
7835
+ if (!requestCanCopy(current)) return revisionReadCannotRestart(current) ? 'settled' : 'empty';
7836
+ const line = current ? markedInstruction(current) : '';
7765
7837
  if (!line) return 'empty';
7766
- return (await copyToClipboard(line)) ? 'ok' : 'denied';
7838
+ const copied = await copyToClipboard(line);
7839
+ return owns() ? (copied ? 'ok' : 'denied') : 'stale';
7767
7840
  }
7768
7841
  // Total by construction: a lookup miss here would spread `undefined` into showToast and throw inside
7769
7842
  // an async onclick — silence, which is worse than the wrong message this exists to replace.
7770
- const copyFailToast = (res) => (res === 'empty'
7771
- ? ['Nothing to copy — this request has no instruction', 'err']
7772
- : ['copy failed', 'err']);
7843
+ const copyFailToast = (res) => (res === 'active'
7844
+ ? ['This request is already running — open Requests to watch it or stop it', 'warn']
7845
+ : res === 'settled'
7846
+ ? ['This drawing read has moved on — open Requests for the next step', 'warn']
7847
+ : res === 'unavailable'
7848
+ ? ['FloLess couldn’t check the latest drawing-read state — open Requests and try again', 'warn']
7849
+ : res === 'empty'
7850
+ ? ['Nothing to copy — this request has no instruction', 'err']
7851
+ : ['copy failed', 'err']);
7773
7852
 
7774
7853
  // ── Headless runs (#571 slice 3) ────────────────────────────────────────────
7775
7854
  // floless starting the user's OWN terminal AI on a queued request, instead of them pasting it.
@@ -7781,11 +7860,18 @@
7781
7860
  // FOLDER is per project, so anything that needs it re-reads with the project key rather than
7782
7861
  // trusting this. Server-side detection spawns nothing — it is statSync work — so an open is cheap.
7783
7862
  let headlessInfo = null;
7863
+ let headlessFetchEpoch = 0;
7784
7864
  async function refreshHeadless() {
7785
7865
  // A detection failure HIDES the feature rather than leaving a button that cannot work. There is
7786
7866
  // no honest middle: without the runtime list we do not know that anything is installed.
7787
- try { headlessInfo = await api('/api/terminal-runtimes'); }
7788
- catch { headlessInfo = null; }
7867
+ const epoch = ++headlessFetchEpoch;
7868
+ let next;
7869
+ try { next = await api('/api/terminal-runtimes'); }
7870
+ catch { next = null; }
7871
+ // Several surfaces can ask at once. A slow earlier probe must not overwrite a newer answer and
7872
+ // leave the visible Start guidance disagreeing with the shared runtime state.
7873
+ if (epoch !== headlessFetchEpoch) return headlessInfo;
7874
+ headlessInfo = next;
7789
7875
  return headlessInfo;
7790
7876
  }
7791
7877
  const headlessRuntimes = () => (headlessInfo && Array.isArray(headlessInfo.runtimes) ? headlessInfo.runtimes : []);
@@ -7819,12 +7905,15 @@
7819
7905
  // response must not turn an arbitrary terminal state into an implied "resume" instruction.
7820
7906
  const RESUMABLE_RUN_STATES = new Set(['needs-you', 'stopped', 'interrupted', 'contract-violation', 'exited-unresolved']);
7821
7907
 
7822
- async function copyResumeCommand(command) {
7908
+ async function copyResumeCommand(command, stillOwned = () => true) {
7823
7909
  if (!command) return 'empty';
7824
- return (await copyToClipboard(command)) ? 'ok' : 'denied';
7910
+ if (!stillOwned()) return 'stale';
7911
+ const copied = await copyToClipboard(command);
7912
+ if (!stillOwned()) return 'stale';
7913
+ return copied ? 'ok' : 'denied';
7825
7914
  }
7826
7915
 
7827
- function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId) {
7916
+ function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId, commandInstance) {
7828
7917
  if (!run || !run.state) return '';
7829
7918
  const v = RUN_VIEW[run.state] || { badge: String(run.state), cls: 'muted', note: () => '' };
7830
7919
  const rt = runtimeLabel(run.runtime);
@@ -7840,18 +7929,18 @@
7840
7929
  const appButtons = handoffs && !claim ? availableProviders.map((provider, i) => {
7841
7930
  const app = handoffs[provider];
7842
7931
  const label = provider === 'codex' ? 'Codex' : 'Claude';
7843
- return `<button type="button" class="req-app-handoff ${i === 0 ? 'req-app-handoff-primary' : ''}" data-id="${escapeAttr(requestId)}" data-attempt-id="${escapeAttr(run.leaseId)}" data-provider="${provider}" data-handoff-prompt="${escapeAttr(app.prompt)}" data-tip="Open this request in ${label} Desktop">Open ${label}</button>`;
7932
+ return `<button type="button" class="req-app-handoff ${i === 0 ? 'req-app-handoff-primary' : ''}" data-id="${escapeAttr(requestId)}" data-attempt-id="${escapeAttr(run.leaseId)}" data-provider="${provider}" data-handoff-prompt="${escapeAttr(app.prompt)}" data-command-id="shell.requests-desktop-open#${escapeAttr(`${requestId}:${run.leaseId}:${provider}`)}" data-command-instance-label="${escapeAttr(`${label} Desktop for ${commandInstance}`)}" data-tip="Open this request in ${label} Desktop">Open ${label}</button>`;
7844
7933
  }).join('') : '';
7845
7934
  const desktop = handoffs
7846
7935
  ? claim
7847
- ? `<div class="req-app-claimed"><strong>Continuing in ${claim.provider === 'claude' ? 'Claude' : 'Codex'}</strong><span>That app owns this recovery.</span><button type="button" class="req-app-release" data-id="${escapeAttr(requestId)}" data-attempt-id="${escapeAttr(claim.attemptId)}" data-claim-id="${escapeAttr(claim.claimId)}">Release and choose another app</button></div>`
7848
- : `<div class="req-app-recovery"><div class="req-app-actions">${appButtons}</div><div class="req-app-launch-status" aria-live="polite"></div><button type="button" class="req-app-copy" data-handoff-prompt="${escapeAttr(handoffs[copyProvider].prompt)}" data-tip="Copy this handoff to paste in a desktop app or terminal AI">${appButtons ? 'Didn’t open? Copy handoff' : 'Copy handoff'}</button></div>`
7936
+ ? `<div class="req-app-claimed"><strong>Continuing in ${claim.provider === 'claude' ? 'Claude' : 'Codex'}</strong><span>That app owns this recovery.</span><button type="button" class="req-app-release" data-id="${escapeAttr(requestId)}" data-attempt-id="${escapeAttr(claim.attemptId)}" data-claim-id="${escapeAttr(claim.claimId)}" data-command-id="shell.requests-desktop-release#${escapeAttr(`${requestId}:${claim.attemptId}`)}" data-command-instance-label="${escapeAttr(`desktop recovery for ${commandInstance}`)}">Release and choose another app</button></div>`
7937
+ : `<div class="req-app-recovery"><div class="req-app-actions">${appButtons}</div><div class="req-app-launch-status" aria-live="polite"></div><button type="button" class="req-app-copy" data-id="${escapeAttr(requestId)}" data-attempt-id="${escapeAttr(run.leaseId)}" data-handoff-prompt="${escapeAttr(handoffs[copyProvider].prompt)}" data-command-id="shell.requests-handoff-copy#${escapeAttr(`${requestId}:${run.leaseId}`)}" data-command-instance-label="${escapeAttr(`desktop recovery for ${commandInstance}`)}" data-tip="Copy this handoff to paste in a desktop app or terminal AI">${appButtons ? 'Didn’t open? Copy handoff' : 'Copy handoff'}</button></div>`
7849
7938
  : '';
7850
7939
  // Never expose a reusable resume command beside a claim-aware handoff bootstrap. A user could
7851
7940
  // copy one, claim the other, and later start two writers in the same folder. The bootstrap remains
7852
7941
  // copyable even when native launch fails or no protocol fits, and is safe to paste in an app or CLI.
7853
7942
  const terminalFallback = !handoffs && resumeCommand
7854
- ? `<details class="req-terminal-fallback"><summary>Terminal fallback</summary><div class="req-run-resume"><button type="button" class="req-run-resume-command" data-resume-command="${escapeAttr(resumeCommand)}" data-tip="Copy command to continue this session" aria-label="Copy terminal fallback command"><code>${escapeHtml(resumeCommand)}</code></button></div>${run.cwd ? `<div class="req-run-where">Run in · ${escapeHtml(run.cwd)}</div>` : ''}</details>`
7943
+ ? `<details class="req-terminal-fallback"><summary>Terminal fallback</summary><div class="req-run-resume"><button type="button" class="req-run-resume-command" data-id="${escapeAttr(requestId)}" data-attempt-id="${escapeAttr(run.leaseId)}" data-resume-command="${escapeAttr(resumeCommand)}" data-command-id="shell.requests-resume-copy#${escapeAttr(`${requestId}:${run.leaseId}`)}" data-command-instance-label="${escapeAttr(`terminal session for ${commandInstance}`)}" data-tip="Copy command to continue this session" aria-label="Copy terminal fallback command"><code>${escapeHtml(resumeCommand)}</code></button></div>${run.cwd ? `<div class="req-run-where">Run in · ${escapeHtml(run.cwd)}</div>` : ''}</details>`
7855
7944
  : '';
7856
7945
  return `
7857
7946
  <div class="req-run-status">
@@ -7888,11 +7977,24 @@
7888
7977
  }
7889
7978
  }
7890
7979
 
7980
+ function focusRequestContinuation(requestId) {
7981
+ const list = document.getElementById('requests-list');
7982
+ const row = Array.from(list?.querySelectorAll('.req-item') || [])
7983
+ .find((candidate) => candidate.dataset.id === requestId);
7984
+ if (!row) return;
7985
+ const continuation = row.querySelector('.req-app-handoff, .req-app-copy, .req-run-resume-command');
7986
+ if (continuation) { continuation.focus(); return; }
7987
+ row.setAttribute('tabindex', '-1');
7988
+ row.focus();
7989
+ row.addEventListener('blur', () => row.removeAttribute('tabindex'), { once: true });
7990
+ }
7991
+
7891
7992
  async function stopRequestRun(req) {
7892
7993
  try {
7893
7994
  await api(`/api/requests/${encodeURIComponent(req.id)}/run/stop`, { method: 'POST' });
7894
7995
  await loadRequests();
7895
7996
  renderRequests();
7997
+ focusRequestContinuation(req.id);
7896
7998
  } catch (e) { reportErr(e); }
7897
7999
  }
7898
8000
 
@@ -7922,7 +8024,7 @@
7922
8024
  // The TITLE carries the refusal too, not just the sub. Both are re-set per open, so this
7923
8025
  // leaks nothing to the next caller — and without it the only thing that changes on a bad
7924
8026
  // folder is one line of muted grey, in the same tier as the explanation it replaced.
7925
- title: refused ? 'That folder won’t work' : 'Run this for me',
8027
+ title: refused ? 'That folder won’t work' : 'Start this request automatically',
7926
8028
  sub: sub || 'floless starts your own terminal AI in a folder you choose and hands it this request. It runs on your machine, with your login.',
7927
8029
  fields: [
7928
8030
  {
@@ -7959,11 +8061,14 @@
7959
8061
 
7960
8062
  let requestHelpReq = null;
7961
8063
  let requestHelpReturnFocus = null;
8064
+ let requestHelpEpoch = 0;
7962
8065
  function closeRequestHelp({ restoreFocus = true } = {}) {
8066
+ requestHelpEpoch += 1;
7963
8067
  const $m = document.getElementById('request-help-modal');
7964
8068
  if ($m) hideModal($m);
7965
8069
  const target = requestHelpReturnFocus;
7966
8070
  requestHelpReturnFocus = null;
8071
+ requestHelpReq = null;
7967
8072
  if (restoreFocus && target && target.isConnected) {
7968
8073
  try { target.focus(); } catch { /* focus is best-effort */ }
7969
8074
  }
@@ -7971,28 +8076,40 @@
7971
8076
  function showRequestQueuedModal(req, opts = {}) {
7972
8077
  const $m = document.getElementById('request-help-modal');
7973
8078
  if (!$m || !req) return;
8079
+ requestHelpEpoch += 1;
7974
8080
  requestHelpReq = req;
7975
8081
  requestHelpReturnFocus = opts.returnFocus || document.activeElement;
7976
8082
  const copied = opts.copied !== false;
7977
- const n = Number(opts.fileCount || (req.snapshots && req.snapshots.length) || 1);
8083
+ const n = Number(opts.fileCount || (req.sourceRefs && req.sourceRefs.length) || (req.snapshots && req.snapshots.length) || 1);
8084
+ const sourceNames = Array.isArray(req.sourceRefs) ? req.sourceRefs.map((ref) => String(ref?.name || ref?.path || ref || '')) : [];
8085
+ const allPdf = sourceNames.length > 0 && sourceNames.every((name) => /\.pdf$/i.test(name));
8086
+ const fileKind = allPdf ? `PDF${n === 1 ? '' : 's'}` : `drawing file${n === 1 ? '' : 's'}`;
7978
8087
  const isRevisionRead = req.type === 'revision-read';
7979
8088
  const isInitial = isRevisionRead && (!req.baseVersion || req.baseVersion <= 0);
8089
+ const canUseManualHandoff = !isRevisionRead || req.status === 'pending';
7980
8090
  const $title = document.getElementById('request-help-title');
7981
8091
  const $sub = document.getElementById('request-help-sub');
7982
- const $note = document.getElementById('request-help-note');
7983
8092
  const $copy = document.getElementById('request-help-copy');
7984
8093
  if ($title) $title.textContent = isRevisionRead
7985
- ? `${isInitial ? 'Initial drawing read' : 'Revision read'} queued`
8094
+ ? canUseManualHandoff
8095
+ ? `${isInitial ? 'Initial drawing read' : 'Updated drawing read'} ready to start`
8096
+ : 'Drawing request needs attention'
7986
8097
  : 'Request queued';
7987
8098
  if ($sub) {
7988
- $sub.textContent = copied
7989
- ? `${n} drawing file${n === 1 ? '' : 's'} added to Requests. The terminal instructions were copied to your clipboard.`
7990
- : `${n} drawing file${n === 1 ? '' : 's'} added to Requests. Copy the terminal instructions from here or from the Requests panel.`;
7991
- }
7992
- if ($note) $note.textContent = isRevisionRead
7993
- ? 'The web UI queues the drawing read; your terminal agent applies it and reports progress back here.'
7994
- : 'The web UI queues the request; your terminal agent applies it and reports progress back here.';
7995
- if ($copy) $copy.hidden = copied;
8099
+ $sub.textContent = isRevisionRead && !canUseManualHandoff
8100
+ ? `${n} ${fileKind} added to Requests. Open Requests to see the current status and recovery step.`
8101
+ : isRevisionRead
8102
+ ? copied
8103
+ ? `${n} ${fileKind} added to Requests. The request was copied to your clipboard.`
8104
+ : `${n} ${fileKind} added to Requests. Copy the request here or from the Requests panel.`
8105
+ : copied
8106
+ ? 'Your request was added to Requests, and the instructions were copied to your clipboard.'
8107
+ : 'Your request was added to Requests. Copy the instructions here or from the Requests panel.';
8108
+ }
8109
+ renderRequestHelpGuidance(req);
8110
+ // Only a pending drawing read may be handed to another terminal. A future or settled status may
8111
+ // already have an owner, so showing Copy here could start a second writer from a stale POST view.
8112
+ if ($copy) $copy.hidden = copied || !canUseManualHandoff;
7996
8113
  // Back to the "not started" face on every open — the previous request's run status must never
7997
8114
  // be the first thing the next one shows.
7998
8115
  setRequestHelpRunning(null);
@@ -8002,22 +8119,101 @@
8002
8119
  // Detection is a fetch, and this modal is opened synchronously by the caller. Reveal the split
8003
8120
  // when the answer lands rather than blocking the modal on it — and only if THIS request is
8004
8121
  // still the one on screen, since a second queue can land while the first fetch is in flight.
8005
- refreshHeadless().then(() => { if (requestHelpReq === req) syncRequestHelpRun(); });
8122
+ refreshHeadless().then(() => {
8123
+ if (requestHelpReq !== req) return;
8124
+ // Runtime discovery may change the available path after the modal is already visible. Repaint
8125
+ // BOTH the control and its numbered instructions so Start never appears beside stale
8126
+ // "no terminal AI" guidance.
8127
+ renderRequestHelpGuidance(req);
8128
+ syncRequestHelpRun();
8129
+ });
8006
8130
  syncRequestHelpRun();
8007
8131
  }
8008
8132
 
8133
+ function requestHelpTransitionStillOwned(epoch, modal) {
8134
+ return requestHelpEpoch === epoch && !requestHelpReq && !modal.classList.contains('show');
8135
+ }
8136
+
8137
+ /** Keep the upload handoff's words on the exact same runtime gate as its Start control. */
8138
+ function renderRequestHelpGuidance(req) {
8139
+ if (!req) return;
8140
+ const sourceNames = Array.isArray(req.sourceRefs) ? req.sourceRefs.map((ref) => String(ref?.name || ref?.path || ref || '')) : [];
8141
+ const allPdf = sourceNames.length > 0 && sourceNames.every((name) => /\.pdf$/i.test(name));
8142
+ const isRevisionRead = req.type === 'revision-read';
8143
+ const isInitial = isRevisionRead && (!req.baseVersion || req.baseVersion <= 0);
8144
+ const isPendingRevisionRead = isRevisionRead && req.status === 'pending';
8145
+ const isUnknownRevisionStatus = isRevisionRead && !['pending', 'staged', 'failed'].includes(req.status);
8146
+ // `canClear: false` means the old request still owns recovery state. In that state another
8147
+ // upload is not a retry: the server must reject it to preserve single-writer ownership.
8148
+ const retainedRevisionRecovery = isRevisionRead && req.canClear === false;
8149
+ const retainedRevisionWhy = retainedRevisionRecovery
8150
+ ? (req.clearWhy || 'FloLess cannot safely release this drawing read yet. Restart FloLess and open Requests again.')
8151
+ : '';
8152
+ const canStartUpdatedRead = isRevisionRead && req.status === 'pending' && !isInitial && req.canRun && headlessReady();
8153
+ const $steps = document.getElementById('request-help-steps');
8154
+ const $note = document.getElementById('request-help-note');
8155
+ if ($steps) {
8156
+ $steps.innerHTML = canStartUpdatedRead
8157
+ ? '<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>'
8158
+ + '<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>'
8159
+ + '<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>'
8160
+ : isRevisionRead && !isPendingRevisionRead
8161
+ ? req.status === 'staged'
8162
+ ? '<div class="request-help-step"><span>1</span><p>This drawing read is complete. Open Requests and choose Review changes.</p></div>'
8163
+ : req.status === 'failed'
8164
+ ? retainedRevisionRecovery
8165
+ ? '<div class="request-help-step"><span>1</span><p>This drawing read still owns its terminal workspace. Open Requests and follow the recovery message before attaching drawings again.</p></div>'
8166
+ : '<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>'
8167
+ : '<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>'
8168
+ : isRevisionRead
8169
+ ? '<div class="request-help-step"><span>1</span><p>Open Claude Code, Codex, or OpenCode in your project folder.</p></div>'
8170
+ + `<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>`
8171
+ + '<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>'
8172
+ : '<div class="request-help-step"><span>1</span><p>Open Claude Code, Codex, or OpenCode in your project folder.</p></div>'
8173
+ + '<div class="request-help-step"><span>2</span><p>Paste the copied request and let your terminal AI apply it.</p></div>'
8174
+ + '<div class="request-help-step"><span>3</span><p>Return here to check the result in FloLess.</p></div>';
8175
+ }
8176
+ if ($note) $note.textContent = isUnknownRevisionStatus
8177
+ ? retainedRevisionRecovery
8178
+ ? `FloLess does not recognize this drawing request status. Do not paste or start it again. Update FloLess, then open Requests again. ${retainedRevisionWhy} Do not attach the drawings again until this recovery is complete.`
8179
+ : 'FloLess does not recognize this drawing request status. Do not paste or start it again. Open Requests for details and update FloLess; if the request cannot be recovered, attach the drawing set again.'
8180
+ : isRevisionRead && req.status === 'staged'
8181
+ ? 'The drawing read is complete. Open Requests and choose Review changes.'
8182
+ : isRevisionRead && req.status === 'failed'
8183
+ ? retainedRevisionRecovery
8184
+ ? `The drawing read failed. ${retainedRevisionWhy} Do not attach the drawings again until this recovery is complete.`
8185
+ : 'The drawing read failed. Attach the drawing set again from Drawing Filter to retry safely.'
8186
+ : isRevisionRead
8187
+ ? isInitial
8188
+ ? 'FloLess cannot start the first read automatically yet: your terminal AI must create the starting project checkpoint, then wait for you to review and save the Drawing Filter. After you save, tell the terminal AI to continue.'
8189
+ : canStartUpdatedRead
8190
+ ? '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.'
8191
+ : req.canRun
8192
+ ? '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.'
8193
+ : `Paste this request into your terminal AI to continue.${req.runWhy ? ` ${req.runWhy}` : ''}`
8194
+ : 'FloLess queues the request; your terminal AI applies it and reports the result back here.';
8195
+ }
8196
+
8009
8197
  /** Show the run split only when this request's type can run AND a runtime exists (§E1/§E4). */
8010
8198
  function syncRequestHelpRun() {
8011
8199
  const $split = document.getElementById('request-help-run-split');
8012
8200
  const $open = document.getElementById('request-help-open');
8013
8201
  if (!$split || !$open) return;
8014
- const can = !!(requestHelpReq && requestHelpReq.canRun && headlessReady());
8202
+ const can = !!(requestHelpReq && requestHelpReq.canRun
8203
+ && (requestHelpReq.type !== 'revision-read' || requestHelpReq.status === 'pending') && headlessReady());
8015
8204
  $split.hidden = !can;
8016
8205
  // Exactly one primary in the row: Run takes it when it is there, Open Requests reclaims it
8017
8206
  // when it is not — a modal with no emphasized action reads as unfinished.
8018
8207
  $open.classList.toggle('primary', !can);
8019
8208
  }
8020
8209
 
8210
+ /** Fields whose change makes the upload handoff modal's guidance or Start policy stale. */
8211
+ function requestHelpStateKey(r) {
8212
+ if (!r) return '';
8213
+ return [r.status, !!r.prepassReady, !!r.filterSaved, !!r.canRun, r.runWhy || '',
8214
+ r.run && r.run.state || '', r.resumeCommand || '', !!r.desktopHandoffs].join('|');
8215
+ }
8216
+
8021
8217
  /**
8022
8218
  * Swap the modal's three "what you must do" steps for what floless is doing instead.
8023
8219
  *
@@ -8119,6 +8315,33 @@
8119
8315
  acceptInstructorAnswers(answers);
8120
8316
  }
8121
8317
  pendingRequests = requests;
8318
+ // The upload modal starts with the POST response, but polling owns the live request state. Do not
8319
+ // leave an old Start button or first-step explanation visible after the request becomes prepared,
8320
+ // staged, failed, or disappears. Move to the live row, which already renders every lifecycle state.
8321
+ const help = requestHelpReq;
8322
+ const helpModal = document.getElementById('request-help-modal');
8323
+ if (help && helpModal && helpModal.classList.contains('show')) {
8324
+ const fresh = requests.find((request) => request && request.id === help.id) || null;
8325
+ if (!fresh || requestHelpStateKey(fresh) !== requestHelpStateKey(help)) {
8326
+ const returnFocus = requestHelpReturnFocus;
8327
+ closeRequestHelp({ restoreFocus: false });
8328
+ if (fresh) {
8329
+ const transitionEpoch = requestHelpEpoch;
8330
+ setTimeout(() => {
8331
+ // Another upload may have reused the shared handoff modal before this deferred move.
8332
+ // Only the exact close that scheduled the transition may replace the screen with Requests.
8333
+ if (!requestHelpTransitionStillOwned(transitionEpoch, helpModal)) return;
8334
+ void openRequests(fresh.id, returnFocus);
8335
+ }, 0);
8336
+ }
8337
+ else {
8338
+ if (returnFocus && returnFocus.isConnected) returnFocus.focus();
8339
+ // Disappearance proves only that the row left Requests: it may have completed, been
8340
+ // cleared in another tab, or been aborted. Never turn absence into a success claim.
8341
+ showToast('The drawing request is no longer in Requests', 'info');
8342
+ }
8343
+ }
8344
+ }
8122
8345
  const $rc = document.getElementById('req-count');
8123
8346
  const $rs = document.getElementById('req-stat');
8124
8347
  if ($rc) $rc.textContent = requests.length;
@@ -8219,12 +8442,169 @@
8219
8442
  // Both the NAME and the raw ids are searchable: you may know a project as "Cedar Mill Warehouse"
8220
8443
  // or as the `take-5-6677ee` in its URL, and either should find it.
8221
8444
  function requestSearchText(r) {
8222
- return [requestLabel(r), requestOwnerName(r), r.appId, r.project, r.nodeId, r.inputName, r.instruction, instructionFor(r)]
8445
+ return [requestLabel(r), requestOwnerName(r), r.appId, r.project, r.nodeId, r.inputName, r.instruction, requestSummary(r), instructionFor(r)]
8223
8446
  .filter(Boolean).join(' ');
8224
8447
  }
8225
8448
 
8226
8449
  function requestLabel(r) {
8227
- return r.type === 'use-template' ? 'template' : r.type === 'ui-customize' ? 'dashboard' : r.type === 'rebake' ? 're-bake' : r.type === 'revision-read' ? 'revision' : 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';
8450
+ if (r.type === 'revision-read') return (!r.baseVersion || r.baseVersion <= 0) ? 'initial drawing read' : 'updated drawing read';
8451
+ 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';
8452
+ }
8453
+
8454
+ function isInitialDrawingRead(r) {
8455
+ return !!r && r.type === 'revision-read' && (!r.baseVersion || r.baseVersion <= 0);
8456
+ }
8457
+
8458
+ function revisionReadAwaitsUser(r) {
8459
+ return !!r && r.type === 'revision-read' && r.status === 'pending' && !!r.prepassReady;
8460
+ }
8461
+
8462
+ function revisionReadHasTerminalOwner(r) {
8463
+ return !!r && r.type === 'revision-read' && !!r.prepassReady;
8464
+ }
8465
+
8466
+ function requestHasActiveRun(r) {
8467
+ return !!r?.run && (r.run.state === 'queued' || r.run.state === 'running');
8468
+ }
8469
+
8470
+ function revisionReadCannotRestart(r) {
8471
+ return !!r && r.type === 'revision-read'
8472
+ && (r.status !== 'pending' || revisionReadHasTerminalOwner(r) || requestHasActiveRun(r));
8473
+ }
8474
+
8475
+ // Once the terminal AI has prepared the Drawing Filter, copying or automatically starting the
8476
+ // original request would launch a second reader against the same project. The existing terminal
8477
+ // session owns the continuation; Requests must point the user back to that checkpoint instead.
8478
+ function requestCanCopy(r) {
8479
+ // A terminal revision state is an outcome, never a queued instruction. This also covers a read
8480
+ // that failed before its prepass checkpoint existed: its card says attach again, so offering Copy
8481
+ // beside it would be a contradictory retry path.
8482
+ return !requestHasActiveRun(r) && !revisionReadCannotRestart(r) && !!markedInstruction(r);
8483
+ }
8484
+
8485
+ function requestCanClear(r) {
8486
+ if (!r) return false;
8487
+ // New servers stamp the exact lease-aware decision. The fallback preserves the previous
8488
+ // lifecycle guards while a cached response from an older server is still on screen.
8489
+ if (typeof r.canClear === 'boolean') return r.canClear;
8490
+ return r.type !== 'knowledge-organize'
8491
+ && !requestHasActiveRun(r)
8492
+ && !(r.desktopHandoffs && r.desktopHandoffs.claim);
8493
+ }
8494
+
8495
+ function bulkCopyPlan(shown) {
8496
+ const lines = shown.filter(requestCanCopy).map(markedInstruction).filter(Boolean);
8497
+ const dropped = shown.length - lines.length;
8498
+ // Active work wins over its request type. A running drawing read also cannot restart, but telling
8499
+ // the user it needs review/reattachment while its terminal AI is visibly working is the wrong
8500
+ // lifecycle. Keep these categories disjoint so the bulk result names the immediate truth.
8501
+ const activeSkipped = shown.filter(requestHasActiveRun).length;
8502
+ const drawingSkipped = shown.filter((r) => !requestHasActiveRun(r) && revisionReadCannotRestart(r)).length;
8503
+ return { lines, dropped, drawingSkipped, activeSkipped, incompleteSkipped: dropped - drawingSkipped - activeSkipped };
8504
+ }
8505
+
8506
+ async function revalidateBulkCopyRequests(shown) {
8507
+ let latest;
8508
+ try { latest = await api('/api/requests'); }
8509
+ catch { return null; }
8510
+ if (!Array.isArray(latest?.requests)) return null;
8511
+ const liveById = new Map(latest.requests.filter((r) => r && r.id).map((r) => [r.id, r]));
8512
+ // Preserve the exact painted order and count, but never preserve a stale instruction. A missing
8513
+ // drawing row is represented as a terminal lifecycle outcome so the bulk result explains why it
8514
+ // was skipped; another missing request is simply an incomplete instruction.
8515
+ return shown.map((painted) => liveById.get(painted?.id)
8516
+ || (painted?.type === 'revision-read'
8517
+ ? { ...painted, status: 'removed', marker: '', prompt: '', run: null }
8518
+ : null));
8519
+ }
8520
+
8521
+ /** Copy only the handoffs that are still safe at click time, in the order currently painted. */
8522
+ async function copyPaintedRequests() {
8523
+ const shown = paintedRequests(); // what was PAINTED, not a re-derived scope — see shownSnapshot
8524
+ if (!shown.length) return;
8525
+ const current = await revalidateBulkCopyRequests(shown);
8526
+ if (!current) {
8527
+ showToast('Could not refresh Requests — nothing was copied', 'err');
8528
+ return;
8529
+ }
8530
+ // Count what actually made it, not what was in the list. `.filter(Boolean)` silently drops a
8531
+ // request with no instruction body, and reporting the list length over that is the
8532
+ // original bug wearing a bulk hat: the user pastes, the AI applies the ones that copied, and the
8533
+ // dropped request never reaches the terminal while the toast said it did.
8534
+ const { lines, dropped, drawingSkipped, activeSkipped, incompleteSkipped } = bulkCopyPlan(current);
8535
+ if (!lines.length) {
8536
+ showToast(bulkCopyEmptyMessage({ drawingSkipped, activeSkipped }, shown.length), 'warn');
8537
+ return;
8538
+ }
8539
+ const copied = await copyToClipboard(lines.join('\n\n'));
8540
+ if (!copied) { showToast('copy failed', 'err'); return; }
8541
+ showToast(
8542
+ bulkCopySuccessMessage({ lines, dropped, drawingSkipped, activeSkipped, incompleteSkipped }, shown.length),
8543
+ dropped ? 'warn' : 'ok',
8544
+ );
8545
+ }
8546
+
8547
+ function bulkCopyEmptyMessage(plan, total) {
8548
+ return plan.drawingSkipped === total
8549
+ ? 'Nothing to copy — these drawing reads need review, continuation, or reattachment'
8550
+ : plan.activeSkipped === total
8551
+ ? 'Nothing to copy — these requests are already running'
8552
+ : 'Nothing to copy — these requests are already running, need drawing review, or have no complete terminal instruction';
8553
+ }
8554
+
8555
+ function bulkCopySuccessMessage(plan, total) {
8556
+ if (!plan.dropped) return `Copied ${plan.lines.length} request(s) — paste to your terminal AI`;
8557
+ const drawing = plan.drawingSkipped
8558
+ ? `${plan.drawingSkipped} drawing read${plan.drawingSkipped === 1 ? ' needs' : 's need'} review, continuation, or reattachment`
8559
+ : '';
8560
+ const active = plan.activeSkipped ? `${plan.activeSkipped} already running` : '';
8561
+ const incomplete = plan.incompleteSkipped ? `${plan.incompleteSkipped} had no complete instruction` : '';
8562
+ return `Copied ${plan.lines.length} of ${total} — ${[drawing, active, incomplete].filter(Boolean).join(', ')}`;
8563
+ }
8564
+
8565
+ /** The sentence a steel detailer needs first; the exact API handoff stays available below it. */
8566
+ function requestSummary(r) {
8567
+ if (!r || r.type !== 'revision-read') return '';
8568
+ if (r.status === 'failed') {
8569
+ if (r.canClear === false) {
8570
+ return `The drawing read failed. ${r.clearWhy || 'FloLess cannot safely release this drawing read yet. Restart FloLess and open Requests again.'} Do not attach the drawings again until this recovery is complete.`;
8571
+ }
8572
+ return 'The drawing read failed. Return to Drawing Filter to see what happened, then attach the drawing set again to retry.';
8573
+ }
8574
+ if (r.status === 'staged') {
8575
+ return 'The drawing read is complete and waiting for your review. Open Drawing Filter and choose Review changes.';
8576
+ }
8577
+ if (r.status !== 'pending') {
8578
+ if (r.canClear === false) {
8579
+ return `This drawing read uses a status this version of FloLess does not recognize. Update FloLess, then open Requests again. ${r.clearWhy || 'FloLess cannot safely release this drawing read yet. Restart FloLess and open Requests again.'} Do not attach the drawings again until this recovery is complete.`;
8580
+ }
8581
+ 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.';
8582
+ }
8583
+ if (r.filterSaved) {
8584
+ return 'Drawing Filter saved. Return to the same terminal AI session that prepared it and tell it to continue the drawing read.';
8585
+ }
8586
+ if (r.prepassReady) {
8587
+ return 'Drawing Filter ready. Review the selected lines, then press Save filter in the top-right corner.';
8588
+ }
8589
+ return (!r.baseVersion || r.baseVersion <= 0)
8590
+ ? 'Read the attached drawing and create the first steel model for this project.'
8591
+ : 'Read the updated drawing and apply the changes to this steel model.';
8592
+ }
8593
+
8594
+ /** One exact next step above the request rows; automatic start is offered only when policy allows it. */
8595
+ function drawingRequestGuidance(r) {
8596
+ if (!r) return '';
8597
+ if (r.status && r.status !== 'pending') return '';
8598
+ if (r.filterSaved) {
8599
+ 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.';
8600
+ }
8601
+ if (r.prepassReady) {
8602
+ 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.';
8603
+ }
8604
+ const start = r.canRun && headlessReady()
8605
+ ? 'copy this request into Claude Code, Codex, or OpenCode, or press Start'
8606
+ : 'copy this request into Claude Code, Codex, or OpenCode';
8607
+ return `Next step: ${start}. When the Drawing Filter is ready, review the selected lines and press Save filter in the top-right corner.`;
8228
8608
  }
8229
8609
 
8230
8610
  // Escape `text`, wrapping every case-insensitive occurrence of `q` in <mark>. Splits the RAW
@@ -8253,8 +8633,8 @@
8253
8633
 
8254
8634
  // The set the window is currently showing — the ONE definition of "these requests", so the
8255
8635
  // rows and the counts on the scope tabs can never disagree.
8256
- function shownRequests() {
8257
- return visibleRequests(pendingRequests, requestScopeAll ? null : activeRequestScope(), requestQuery, requestSearchText);
8636
+ function shownRequests(query = requestQuery) {
8637
+ return visibleRequests(pendingRequests, requestScopeAll ? null : activeRequestScope(), query, requestSearchText);
8258
8638
  }
8259
8639
 
8260
8640
  // Exactly what the OPEN window last painted. The bulk actions read THIS, never shownRequests().
@@ -8293,13 +8673,13 @@
8293
8673
  * per-id loop rather than the atomic verb.
8294
8674
  */
8295
8675
  function bulkClearPlan(painted, all, filterActive) {
8296
- const keep = painted.filter((r) => r && (r.type === 'knowledge-organize' || (r.desktopHandoffs && r.desktopHandoffs.claim)));
8297
- const drop = painted.filter((r) => r && r.type !== 'knowledge-organize' && !(r.desktopHandoffs && r.desktopHandoffs.claim));
8676
+ const keep = painted.filter((r) => !requestCanClear(r));
8677
+ const drop = painted.filter(requestCanClear);
8298
8678
  return { atomic: !filterActive && !keep.length && painted.length === all.length, keep, drop };
8299
8679
  }
8300
8680
 
8301
- // The Requests window: every queued change in a list, each copyable + clearable,
8302
- // plus copy-all / clear-all. The server-composed prompt (which embeds file-derived
8681
+ // The Requests window: every queued change in a list, with only the actions the server says are
8682
+ // currently safe, plus bulk actions over the available rows. The server-composed prompt (which embeds file-derived
8303
8683
  // appId/nodeId/instruction) is rendered via textContent-equivalent escaping — which matters MORE
8304
8684
  // now that the string arrives over the wire rather than being built from local state.
8305
8685
  function renderRequests() {
@@ -8308,6 +8688,11 @@
8308
8688
  const $copy = document.getElementById('requests-copy');
8309
8689
  const $search = document.getElementById('requests-search');
8310
8690
  if (!$list) return;
8691
+ // Object identity is a cheap render generation: every repaint replaces this token. Async row
8692
+ // actions capture it, so a poll/search/scope repaint retires their completion even if another
8693
+ // row later reuses the same request id.
8694
+ const paintOwner = {};
8695
+ $list.__requestPaintOwner = paintOwner;
8311
8696
  // Search is pointless over an empty queue, and over a single request it is just clutter.
8312
8697
  // Drop the query WITH the box, and before anything is filtered by it: a hidden filter still
8313
8698
  // filtering is how a list ends up inexplicably empty (the last two requests clear while a
@@ -8316,9 +8701,10 @@
8316
8701
  $search.hidden = pendingRequests.length < 2;
8317
8702
  if ($search.hidden && requestQuery) { requestQuery = ''; $search.value = ''; }
8318
8703
  }
8704
+ const normalizedRequestQuery = requestQuery.trim();
8319
8705
  const scope = activeRequestScope();
8320
8706
  const inScope = visibleRequests(pendingRequests, scope, '', requestSearchText);
8321
- const shown = shownRequests();
8707
+ const shown = shownRequests(normalizedRequestQuery);
8322
8708
  shownSnapshot = shown; // the bulk actions act on THIS paint — see the note on shownSnapshot
8323
8709
  const nothingQueued = pendingRequests.length === 0;
8324
8710
 
@@ -8328,6 +8714,7 @@
8328
8714
  const $scope = document.getElementById('requests-scope');
8329
8715
  const $here = document.getElementById('requests-scope-here');
8330
8716
  const $all = document.getElementById('requests-scope-all');
8717
+ const $guidance = document.getElementById('requests-guidance');
8331
8718
  if ($scope) $scope.hidden = !scope || nothingQueued;
8332
8719
  if (scope && $here && $all) {
8333
8720
  const kind = scope.kind === 'project' ? 'project' : 'workflow';
@@ -8342,6 +8729,13 @@
8342
8729
  $all.classList.toggle('active', requestScopeAll);
8343
8730
  $all.setAttribute('aria-selected', String(requestScopeAll));
8344
8731
  }
8732
+ const initialDrawingRead = shown.find((request) => request.status === 'pending' && isInitialDrawingRead(request));
8733
+ const checkpointDrawingRead = shown.find(revisionReadAwaitsUser);
8734
+ const guidedDrawingRead = checkpointDrawingRead || initialDrawingRead;
8735
+ if ($guidance) {
8736
+ $guidance.hidden = !guidedDrawingRead;
8737
+ $guidance.textContent = drawingRequestGuidance(guidedDrawingRead);
8738
+ }
8345
8739
 
8346
8740
  // Hide (not just disable) the bulk actions when there's nothing to act on — a
8347
8741
  // disabled "Clear all"/"Copy all" over an empty list reads as broken UI. They act on
@@ -8349,16 +8743,30 @@
8349
8743
  const bulkTip = (verb) => (shown.length === pendingRequests.length
8350
8744
  ? `${verb} all ${pendingRequests.length} queued request${pendingRequests.length === 1 ? '' : 's'}`
8351
8745
  : `${verb} the ${shown.length} request${shown.length === 1 ? '' : 's'} shown here`);
8352
- if ($clear) { $clear.hidden = shown.length === 0; $clear.setAttribute('data-tip', bulkTip('Clear')); }
8353
- if ($copy) { $copy.hidden = shown.length === 0; $copy.setAttribute('data-tip', bulkTip('Copy')); }
8746
+ const copyableShown = shown.filter(requestCanCopy);
8747
+ const clearableShown = shown.filter(requestCanClear);
8748
+ const protectedShown = shown.length - clearableShown.length;
8749
+ if ($clear) {
8750
+ $clear.hidden = clearableShown.length === 0;
8751
+ $clear.textContent = protectedShown ? 'Clear available' : 'Clear all';
8752
+ $clear.setAttribute('data-tip', protectedShown
8753
+ ? 'Clear requests that are ready to remove. Running and saved sessions will be kept.'
8754
+ : bulkTip('Clear'));
8755
+ }
8756
+ if ($copy) {
8757
+ $copy.hidden = copyableShown.length === 0;
8758
+ $copy.setAttribute('data-tip', copyableShown.length === shown.length
8759
+ ? bulkTip('Copy')
8760
+ : `Copy ${copyableShown.length} request${copyableShown.length === 1 ? '' : 's'} that still need to be started`);
8761
+ }
8354
8762
 
8355
8763
  if (shown.length === 0) {
8356
8764
  // Three different nothings, and conflating them is what makes a filter feel broken: an
8357
8765
  // empty queue, a queue with nothing for THIS project, and a search that missed.
8358
8766
  const msg = nothingQueued
8359
8767
  ? 'No requests queued. Save a Template or ✎ Tweak a node to send a change to your terminal AI.'
8360
- : requestQuery.trim()
8361
- ? `No request matches “${escapeHtml(requestQuery.trim())}”.${!requestScopeAll && inScope.length < pendingRequests.length ? ' Try All to search every queued request.' : ''}`
8768
+ : normalizedRequestQuery
8769
+ ? `No request matches “${escapeHtml(normalizedRequestQuery)}”.${!requestScopeAll && inScope.length < pendingRequests.length ? ' Try All to search every queued request.' : ''}`
8362
8770
  : `Nothing queued for ${escapeHtml(scope ? scope.label : 'this')} — ${pendingRequests.length} request${pendingRequests.length === 1 ? '' : 's'} waiting elsewhere. <button type="button" class="req-showall">Show all</button>`;
8363
8771
  $list.innerHTML = `<div class="empty-state">${msg}</div>`;
8364
8772
  const $showAll = $list.querySelector('.req-showall');
@@ -8371,7 +8779,7 @@
8371
8779
  // has no button. Derived from this paint — deliberately not a stored "has run before" flag,
8372
8780
  // which would make the same list read differently for two people.
8373
8781
  const anyRunnable = headlessReady() && shown.some((r) => r && r.canRun);
8374
- $list.innerHTML = shown.map((r) => {
8782
+ $list.innerHTML = shown.map((r, shownIndex) => {
8375
8783
  const label = requestLabel(r);
8376
8784
  const badgeCls = r.type === 'tweak' || r.type === 'ui-customize' || r.type === 'rebake' || r.type === 'revision-read' || r.type === 'knowledge-organize' || r.type === 'knowledge-adjust' || r.type === 'tweak-contract' ? 'req-type req-type-tweak' : 'req-type';
8377
8785
  // One name, and only the name. The node/input/sheet chips that used to sit here ("· node
@@ -8384,44 +8792,67 @@
8384
8792
  // chip has nothing left to rescue.
8385
8793
  const owner = requestOwnerName(r);
8386
8794
  const when = r.createdAt ? new Date(r.createdAt) : null;
8387
- const time = when && !isNaN(when) ? `<span class="req-time">${escapeHtml(nowStamp(when))}</span>` : '';
8795
+ const whenLabel = when && !isNaN(when) ? nowStamp(when) : '';
8796
+ const time = whenLabel ? `<span class="req-time">${escapeHtml(whenLabel)}</span>` : '';
8797
+ // Every generated action needs a human identity as well as its opaque request id. Instructor
8798
+ // lists all visible instances, so "Copy this request" five times is not guidance. Owner + type +
8799
+ // the visible timestamp map back to the row; the shown position is the deterministic tie-breaker.
8800
+ const commandInstance = `${label}${owner ? ` for ${owner}` : ''}${whenLabel ? `, queued ${whenLabel}` : ''}, item ${shownIndex + 1}`;
8388
8801
  // A knowledge-organize is resolved by its own finish/fail lifecycle POST. Offering a ✕ here
8389
8802
  // would let the user delete a request the terminal AI is mid-way through, 404-ing finish/fail
8390
8803
  // and stranding the organize lock until its stale timeout. Show why it can't be cleared instead.
8391
- const run = r.run || null;
8804
+ // The server strips terminal recovery from settled drawing reads, and the browser repeats that
8805
+ // boundary so a stale/malformed response cannot resurrect an old Save question or recovery
8806
+ // control beside staged, failed, or unfamiliar lifecycle guidance.
8807
+ const settledRevision = r.type === 'revision-read' && r.status !== 'pending';
8808
+ const run = settledRevision ? null : (r.run || null);
8809
+ const resumeCommand = settledRevision ? null : r.resumeCommand;
8810
+ const desktopHandoffs = settledRevision ? null : r.desktopHandoffs;
8392
8811
  const inFlight = !!run && (run.state === 'queued' || run.state === 'running');
8393
- const desktopClaimed = !!(r.desktopHandoffs && r.desktopHandoffs.claim);
8812
+ const desktopClaimed = !!(desktopHandoffs && desktopHandoffs.claim);
8394
8813
  const lifecycleOwned = r.type === 'knowledge-organize';
8814
+ const canClear = requestCanClear(r);
8395
8815
  // ✕ goes away while a run is live, for the same reason it goes away on a knowledge-organize:
8396
8816
  // deleting the request out from under a working agent leaves it unable to clear its own work,
8397
8817
  // and the run then lands in `exited-unresolved` for a reason the user caused and cannot see.
8398
8818
  const del = lifecycleOwned
8399
8819
  ? '<span class="req-lifecycle" data-tip="This clears itself when your terminal AI finishes or fails the organize">finishing in your terminal</span>'
8400
8820
  : inFlight || desktopClaimed
8401
- ? '<span class="req-lifecycle" data-tip="Stop the run first — clearing it now would leave the agent working on a request that no longer exists">running</span>'
8402
- : `<button class="req-del" data-id="${escapeAttr(r.id)}" data-tip="${r.resumeCommand ? 'Clear this request and discard its saved terminal session' : 'Clear this request'}">×</button>`;
8821
+ ? '<span class="req-lifecycle" data-tip="Stop the run if you need to pause it. Clear stays unavailable until the saved session is continued and finished">running</span>'
8822
+ : !canClear && r.clearState === 'session-saved'
8823
+ ? `<span class="req-lifecycle" role="status" aria-live="polite" data-tip="${escapeAttr(r.clearWhy || 'This stopped session is saved so you can continue where you left off. Continue or finish it before clearing this request.')}"><span aria-hidden="true">session saved</span><span class="sr-only">Session saved. Continue or finish it before clearing this request.</span></span>`
8824
+ : !canClear
8825
+ ? `<span class="req-lifecycle" data-tip="${escapeAttr(r.clearWhy || 'This request cannot be cleared yet.')}">kept</span>`
8826
+ : `<button class="req-del" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-clear#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" data-tip="${resumeCommand ? 'Clear this request and discard its saved terminal session' : 'Clear this request'}">×</button>`;
8403
8827
  // A server-stamped handoff gets NO re-run. The original terminal session may already be live;
8404
- // starting a second headless agent would put two writers in one folder. The browser decides no
8405
- // policy here: it simply withholds ▶ whenever the server supplied the resume command.
8406
- const canRunNow = headlessReady() && r.canRun && !inFlight && !r.desktopHandoffs && !r.resumeCommand;
8828
+ // starting a second headless agent would put two writers in one folder. The server still owns
8829
+ // run policy; this row repeats only the lifecycle-integrity guards needed to fail closed on a
8830
+ // stale or malformed response.
8831
+ // `canRun` is server-owned policy, but persisted request JSON can outlive or be newer than this
8832
+ // client. A revision lifecycle this build cannot name must never gain Start through a stale or
8833
+ // malformed response; only the exact queued state is safe to launch.
8834
+ const canRunNow = headlessReady() && r.canRun && (r.type !== 'revision-read' || r.status === 'pending')
8835
+ && !revisionReadHasTerminalOwner(r) && !inFlight && !desktopHandoffs && !resumeCommand;
8407
8836
  const runBtn = inFlight
8408
- ? `<button class="req-stop" data-id="${escapeAttr(r.id)}" data-tip="Stop this run">■</button>`
8837
+ ? `<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>`
8409
8838
  : canRunNow
8410
- ? `<button class="req-run" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-run" data-command-instance="${escapeAttr(r.id)}" aria-label="Run this request" data-tip="${run ? 'Run it again in your terminal AI, headless' : 'Let floless run this in your terminal AI'}">▶</button>`
8839
+ ? `<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 automatically" data-tip="${run ? 'Start it again automatically in your terminal AI' : 'Start this request automatically in your terminal AI'}">▶</button>`
8411
8840
  : '';
8412
8841
  return `
8413
8842
  <div class="req-item" data-id="${escapeAttr(r.id)}">
8414
8843
  <div class="req-info">
8415
- <div class="req-head"><span class="${badgeCls}">${label}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, requestQuery)}</span>` : ''}${time}</div>
8416
- <div class="req-instruction">${highlightQuery(instructionFor(r), requestQuery) || 'This request has no instruction, so it can’t be handed to your terminal AI. Clear it and queue it again.'}</div>
8844
+ <div class="req-head"><span class="${badgeCls}">${label}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, normalizedRequestQuery)}</span>` : ''}${time}</div>
8845
+ ${r.type === 'revision-read'
8846
+ ? `<div class="req-instruction req-summary">${highlightQuery(requestSummary(r), normalizedRequestQuery)}</div><details class="req-technical"${normalizedRequestQuery && instructionFor(r).toLowerCase().includes(normalizedRequestQuery.toLowerCase()) ? ' open' : ''}><summary data-command-id="shell.requests-technical#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}">Show technical instructions</summary><div class="req-technical-body">${highlightQuery(instructionFor(r), normalizedRequestQuery)}</div></details>`
8847
+ : `<div class="req-instruction">${highlightQuery(instructionFor(r), normalizedRequestQuery) || 'This request has no instruction, so it can’t be handed to your terminal AI. Clear it and queue it again.'}</div>`}
8417
8848
  ${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>` : ''}
8418
- ${runStatusHtml(run, r.resumeCommand, r.desktopHandoffs, r.id)}
8419
- ${!r.canRun && r.runWhy && anyRunnable ? `<div class="req-why-not">Runs only from your terminal — ${escapeHtml(r.runWhy)}</div>` : ''}
8849
+ ${runStatusHtml(run, resumeCommand, desktopHandoffs, r.id, commandInstance)}
8850
+ ${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>` : ''}
8420
8851
  </div>
8421
8852
  <div class="req-actions">
8422
8853
  ${runBtn}
8423
- ${r.desktopHandoffs || r.resumeCommand ? '' : `<button class="req-copy" data-id="${escapeAttr(r.id)}" data-tip="Copy this instruction">⧉</button>`}
8424
- ${del}
8854
+ ${desktopHandoffs || resumeCommand || !requestCanCopy(r) ? '' : `<button class="req-copy" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-copy#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" data-tip="Copy this request for your terminal AI" aria-label="Copy this request for your terminal AI">⧉</button>`}
8855
+ ${del.replace('<button class="req-del"', '<button aria-label="Clear this request" class="req-del"')}
8425
8856
  </div>
8426
8857
  </div>`;
8427
8858
  }).join('');
@@ -8441,14 +8872,28 @@
8441
8872
  b.onclick = async () => {
8442
8873
  const r = pendingRequests.find((x) => x.id === b.dataset.id);
8443
8874
  if (!r) return;
8444
- const res = await copyRequest(r);
8875
+ const modal = document.getElementById('requests-modal');
8876
+ const owns = () => b.isConnected
8877
+ && $list.__requestPaintOwner === paintOwner
8878
+ && !!modal?.classList.contains('show')
8879
+ && pendingRequests.some((candidate) => candidate && candidate.id === r.id);
8880
+ const res = await copyRequest(r, owns);
8881
+ if (res === 'stale' || !owns()) return;
8445
8882
  if (res === 'ok') showToast('Copied — paste it to your terminal AI', 'ok');
8446
8883
  else showToast(...copyFailToast(res));
8447
8884
  };
8448
8885
  });
8449
8886
  $list.querySelectorAll('.req-run-resume-command').forEach((b) => {
8450
8887
  b.onclick = async () => {
8451
- const res = await copyResumeCommand(b.dataset.resumeCommand || '');
8888
+ const requestId = b.dataset.id || '';
8889
+ const attemptId = b.dataset.attemptId || '';
8890
+ const modal = document.getElementById('requests-modal');
8891
+ const owns = () => b.isConnected
8892
+ && $list.__requestPaintOwner === paintOwner
8893
+ && !!modal?.classList.contains('show')
8894
+ && pendingRequests.some((candidate) => candidate?.id === requestId && candidate.run?.leaseId === attemptId);
8895
+ const res = await copyResumeCommand(b.dataset.resumeCommand || '', owns);
8896
+ if (res === 'stale' || !owns()) return;
8452
8897
  if (res === 'ok') showToast('Copied — run it in the folder shown below', 'ok');
8453
8898
  else if (res === 'empty') showToast('Nothing to copy — this run has no resume command', 'err');
8454
8899
  else showToast('Could not copy — select the command and copy it manually', 'err');
@@ -8501,8 +8946,16 @@
8501
8946
  });
8502
8947
  $list.querySelectorAll('.req-app-copy').forEach((b) => {
8503
8948
  b.onclick = async () => {
8504
- const result = await copyToClipboard(b.dataset.handoffPrompt || '');
8505
- showToast(result ? 'Handoff copied — paste it into a desktop app or terminal AI' : 'Could not copy the handoff', result ? 'ok' : 'err');
8949
+ const requestId = b.dataset.id || '';
8950
+ const attemptId = b.dataset.attemptId || '';
8951
+ const modal = document.getElementById('requests-modal');
8952
+ const owns = () => b.isConnected
8953
+ && $list.__requestPaintOwner === paintOwner
8954
+ && !!modal?.classList.contains('show')
8955
+ && pendingRequests.some((candidate) => candidate?.id === requestId && candidate.run?.leaseId === attemptId);
8956
+ const result = await copyResumeCommand(b.dataset.handoffPrompt || '', owns);
8957
+ if (result === 'stale' || !owns()) return;
8958
+ showToast(result === 'ok' ? 'Handoff copied — paste it into a desktop app or terminal AI' : 'Could not copy the handoff', result === 'ok' ? 'ok' : 'err');
8506
8959
  };
8507
8960
  });
8508
8961
  $list.querySelectorAll('.req-app-release').forEach((b) => {
@@ -8555,18 +9008,30 @@
8555
9008
  showToast(`Cleared ${result.cleared} request${result.cleared === 1 ? '' : 's'} — ${result.failed} could not be cleared`, 'err');
8556
9009
  return;
8557
9010
  }
9011
+ if (result?.kept) {
9012
+ await loadRequests();
9013
+ renderRequests();
9014
+ showToast(`Cleared ${result.cleared} request${result.cleared === 1 ? '' : 's'} — kept ${result.kept} that ${result.kept === 1 ? 'is' : 'are'} still in use`, 'info');
9015
+ return;
9016
+ }
8558
9017
  } else {
8559
9018
  for (const r of drop) await api(`/api/requests/${encodeURIComponent(r.id)}`, { method: 'DELETE' });
8560
9019
  }
8561
9020
  await loadRequests();
8562
9021
  renderRequests();
9022
+ const saved = keep.filter((r) => r && r.clearState === 'session-saved').length;
9023
+ const stillRunning = keep.length - saved;
9024
+ const kept = [
9025
+ stillRunning ? `${stillRunning} still running` : '',
9026
+ saved ? `${saved} saved to continue` : '',
9027
+ ].filter(Boolean).join(' and ');
8563
9028
  showToast(
8564
9029
  keep.length
8565
- ? `Cleared ${drop.length} request${drop.length === 1 ? '' : 's'} — kept ${keep.length} in-progress organize${keep.length === 1 ? '' : 's'}`
9030
+ ? `${drop.length ? `Cleared ${drop.length} request${drop.length === 1 ? '' : 's'}` : 'Nothing cleared'} — kept ${kept}`
8566
9031
  : atomic
8567
9032
  ? 'Cleared all requests'
8568
9033
  : `Cleared ${drop.length} request${drop.length === 1 ? '' : 's'} shown here`,
8569
- 'ok',
9034
+ keep.length ? 'info' : 'ok',
8570
9035
  );
8571
9036
  } catch (e) { reportErr(e); }
8572
9037
  }
@@ -8577,14 +9042,20 @@
8577
9042
  }
8578
9043
  // Re-fetch before showing: there is no server `request-added` broadcast, so a request queued in
8579
9044
  // another tab (or by the Knowledge step) would otherwise render from a stale cache.
8580
- async function openRequests(targetId) {
9045
+ async function openRequests(targetId, returnFocusTo = null) {
8581
9046
  // Open on the scope + a clear search every time. A stuck "All" (or a leftover query) from a
8582
9047
  // previous visit would silently answer a different question than the one just asked.
8583
9048
  requestScopeAll = false;
8584
9049
  requestQuery = '';
8585
9050
  const $search = document.getElementById('requests-search');
8586
9051
  if ($search) $search.value = '';
8587
- document.getElementById('requests-modal').classList.add('show');
9052
+ const $requestsModal = document.getElementById('requests-modal');
9053
+ const $requestsDialog = $requestsModal && $requestsModal.querySelector('.modal.requests');
9054
+ requestsReturnFocus = returnFocusTo instanceof HTMLElement
9055
+ ? returnFocusTo
9056
+ : document.activeElement instanceof HTMLElement ? document.activeElement : null;
9057
+ $requestsModal.classList.add('show');
9058
+ if ($requestsDialog) $requestsDialog.focus();
8588
9059
  renderRequests(); // paint the cache immediately — no empty flash
8589
9060
  // Scroll off the CACHED paint, before the refetch. Gating the reveal on `/api/requests` means an
8590
9061
  // arbitrarily slow response leaves the list sitting at the top — precisely the state this feature
@@ -10310,33 +10781,29 @@
10310
10781
  const $debugBtn = document.getElementById('debug-btn');
10311
10782
  if ($debugBtn) $debugBtn.onclick = () => { if (state.selectedAgentId) runReport(state.selectedAgentId, { debug: true }); };
10312
10783
  const $reqStat = document.getElementById('req-stat');
10313
- if ($reqStat) $reqStat.onclick = () => openRequests();
10784
+ if ($reqStat) {
10785
+ const openFromRequestsStat = () => openRequests(null, $reqStat);
10786
+ $reqStat.onclick = openFromRequestsStat;
10787
+ $reqStat.onkeydown = (e) => {
10788
+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openFromRequestsStat(); }
10789
+ };
10790
+ }
10314
10791
  const $reqModal = document.getElementById('requests-modal');
10315
10792
  const $reqClose = document.getElementById('requests-close');
10316
- if ($reqClose) $reqClose.onclick = () => $reqModal.classList.remove('show');
10317
- if ($reqModal) onBackdropDismiss($reqModal, () => $reqModal.classList.remove('show'));
10793
+ let requestsReturnFocus = null;
10794
+ const closeRequests = () => {
10795
+ if (!$reqModal || !$reqModal.classList.contains('show')) return;
10796
+ $reqModal.classList.remove('show');
10797
+ const returnFocus = requestsReturnFocus;
10798
+ requestsReturnFocus = null;
10799
+ if (returnFocus && returnFocus.isConnected && !returnFocus.matches(':disabled,[aria-disabled="true"]')) returnFocus.focus();
10800
+ };
10801
+ if ($reqClose) $reqClose.onclick = closeRequests;
10802
+ if ($reqModal) onBackdropDismiss($reqModal, closeRequests);
10318
10803
  const $reqClear = document.getElementById('requests-clear');
10319
10804
  if ($reqClear) $reqClear.onclick = () => clearAllRequests();
10320
10805
  const $reqCopy = document.getElementById('requests-copy');
10321
- if ($reqCopy) $reqCopy.onclick = async () => {
10322
- const shown = paintedRequests(); // what was PAINTED, not a re-derived scope — see shownSnapshot
10323
- if (!shown.length) return;
10324
- // Count what actually made it, not what was in the list. `.filter(Boolean)` silently drops a
10325
- // request with no instruction body, and reporting the list length over that is the
10326
- // original bug wearing a bulk hat: the user pastes, the AI applies the ones that copied, and the
10327
- // dropped request never reaches the terminal while the toast said it did.
10328
- const lines = shown.map(markedInstruction).filter(Boolean);
10329
- const dropped = shown.length - lines.length;
10330
- if (!lines.length) { showToast('Nothing to copy — none of these requests has an instruction', 'err'); return; }
10331
- const copied = await copyToClipboard(lines.join('\n\n'));
10332
- if (!copied) { showToast('copy failed', 'err'); return; }
10333
- showToast(
10334
- dropped
10335
- ? `Copied ${lines.length} of ${shown.length} — ${dropped} had no instruction and ${dropped === 1 ? 'was' : 'were'} skipped`
10336
- : `Copied ${lines.length} request(s) — paste to your terminal AI`,
10337
- dropped ? 'warn' : 'ok',
10338
- );
10339
- };
10806
+ if ($reqCopy) $reqCopy.onclick = copyPaintedRequests;
10340
10807
  const $reqScope = document.getElementById('requests-scope');
10341
10808
  if ($reqScope) $reqScope.onclick = (e) => {
10342
10809
  const b = e.target.closest('button[data-reqscope]');
@@ -10352,14 +10819,19 @@
10352
10819
  // Read the id BEFORE closing — this button means "take me to the one I just queued", and only
10353
10820
  // this entry point knows which that is.
10354
10821
  const id = requestHelpReq && requestHelpReq.id;
10822
+ const returnFocus = requestHelpReturnFocus;
10355
10823
  closeRequestHelp({ restoreFocus: false });
10356
- openRequests(id);
10824
+ openRequests(id, returnFocus);
10357
10825
  };
10358
10826
  if ($requestHelpKeep) $requestHelpKeep.onclick = () => closeRequestHelp();
10359
- if ($requestHelpCopy) $requestHelpCopy.onclick = async () => {
10360
- if (!requestHelpReq) return;
10827
+ async function copyFromRequestHelp() {
10828
+ const req = requestHelpReq;
10829
+ if (!req) return;
10361
10830
  // Via copyRequest, so an instruction-less type says so rather than "copy failed".
10362
- const res = await copyRequest(requestHelpReq);
10831
+ const res = await copyRequest(req, () => requestHelpReq === req);
10832
+ // Revalidation adds a real network wait. The modal may have closed or been reused for another
10833
+ // upload while it was in flight; only the request that initiated Copy may consume its result.
10834
+ if (requestHelpReq !== req) return;
10363
10835
  const copied = res === 'ok';
10364
10836
  if (copied) showToast('Copied — paste it to your terminal AI', 'ok');
10365
10837
  else showToast(...copyFailToast(res));
@@ -10372,7 +10844,8 @@
10372
10844
  const $sub = document.getElementById('request-help-sub');
10373
10845
  if ($sub) $sub.textContent = 'Terminal instructions copied. Open the terminal agent and paste them there.';
10374
10846
  }
10375
- };
10847
+ }
10848
+ if ($requestHelpCopy) $requestHelpCopy.onclick = copyFromRequestHelp;
10376
10849
  // ▶ runs with the resolved default; ▾ asks folder + which terminal AI first. Both leave the modal
10377
10850
  // OPEN on success and swap its steps for the run status — closing it would hide the one sentence
10378
10851
  // that says what floless just started on the user's behalf.
@@ -10395,7 +10868,22 @@
10395
10868
  closeRequestHelp();
10396
10869
  return;
10397
10870
  }
10398
- if (e.key === 'Escape' && $reqModal && $reqModal.classList.contains('show')) $reqModal.classList.remove('show');
10871
+ if ($reqModal && $reqModal.classList.contains('show')) {
10872
+ if (e.key === 'Escape') { e.preventDefault(); closeRequests(); return; }
10873
+ if (e.key === 'Tab') {
10874
+ const dialog = $reqModal.querySelector('.modal.requests');
10875
+ const focusable = Array.from($reqModal.querySelectorAll('button:not([disabled]):not([hidden]), input:not([disabled]):not([hidden]), summary, [tabindex]:not([tabindex="-1"])'))
10876
+ .filter((el) => el.offsetParent !== null);
10877
+ if (!focusable.length) { e.preventDefault(); return; }
10878
+ const first = focusable[0];
10879
+ const last = focusable[focusable.length - 1];
10880
+ if (e.shiftKey && (document.activeElement === dialog || document.activeElement === first || !$reqModal.contains(document.activeElement))) {
10881
+ e.preventDefault(); last.focus();
10882
+ } else if (!e.shiftKey && (document.activeElement === last || !$reqModal.contains(document.activeElement))) {
10883
+ e.preventDefault(); first.focus();
10884
+ }
10885
+ }
10886
+ }
10399
10887
  });
10400
10888
 
10401
10889
  // Per-workflow onboarding beacon + guide panel + first-open spotlight.