@floless/app 0.133.2 → 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
@@ -171,6 +171,15 @@
171
171
  const readInstructorAnswerIds = storedAnswerIds(ANSWER_READ_KEY);
172
172
  let answerGlowTimer = null;
173
173
  let leftPaneTab = 'narrative';
174
+ // Per-id collapse state (session only, never persisted): a card is collapsed iff its id is here.
175
+ // Keyed by id, never position — cards insert at the TOP, so an index would drift under new arrivals.
176
+ const collapsedAnswerIds = new Set();
177
+ // Deferred-commit removal. `×` hides the card immediately and starts a timer; the DELETE fires only
178
+ // when the timer elapses, so an Undo within the window is a pure client-side restore with no server
179
+ // round-trip. The id stays in `pendingDeleteAnswerIds` (filtered out of every render) until then.
180
+ const pendingDeleteAnswerIds = new Set();
181
+ const answerDeleteTimers = new Map();
182
+ const ANSWER_UNDO_MS = 6000;
174
183
 
175
184
  function selectLeftPaneTab(tab, { focus = false, explicit = false } = {}) {
176
185
  leftPaneTab = tab === 'answers' ? 'answers' : 'narrative';
@@ -289,7 +298,8 @@
289
298
  }
290
299
 
291
300
  function answerCard(answer, isNew) {
292
- const subject = escapeHtml(answer.instructorContext.subject || 'this context');
301
+ const subjectText = answer.instructorContext.subject || 'this context';
302
+ const subject = escapeHtml(subjectText);
293
303
  const prose = answerProse(answer.answer);
294
304
  const runtime = answer.runtime === 'claude' ? 'Claude' : answer.runtime === 'codex' ? 'Codex' : 'terminal AI';
295
305
  const card = msgEl(`aware instructor-answer${isNew ? ' instructor-answer-new' : ''}`,
@@ -297,9 +307,226 @@
297
307
  `<span class="answer-new-badge">New answer</span>${prose}`,
298
308
  answer.finishedAt);
299
309
  card.dataset.answerId = answer.id;
310
+
311
+ // A fresh arrival always renders expanded — the glow-and-scroll is meant to reveal its content, so
312
+ // a card that lit up and then hid its own body would be actively confusing. Otherwise honour the
313
+ // per-id collapse the user set.
314
+ const collapsed = !isNew && collapsedAnswerIds.has(answer.id);
315
+ if (collapsed) card.classList.add('answer-collapsed');
316
+ const body = card.querySelector('.body');
317
+ const bodyId = `answer-body-${answer.id}`;
318
+ if (body) body.id = bodyId;
319
+ const who = card.querySelector('.who');
320
+ if (who) who.classList.add('answer-who');
321
+
322
+ // The chevron owns the disclosure and the × owns the removal — two independent buttons, never one
323
+ // nested in the other. A header that wraps a nested × steals the delete button's hit box the moment
324
+ // closest() routes a click (see reference_nested_control_in_role_button_card.md).
325
+ const chevron = document.createElement('button');
326
+ chevron.type = 'button';
327
+ chevron.className = 'answer-collapse-toggle';
328
+ chevron.textContent = '▸';
329
+ chevron.setAttribute('aria-controls', bodyId);
330
+ setCollapseToggleState(chevron, collapsed, `${runtime} · ${subjectText}`);
331
+ chevron.onclick = () => toggleAnswerCollapse(answer.id);
332
+
333
+ const del = document.createElement('button');
334
+ del.type = 'button';
335
+ del.className = 'answer-del';
336
+ del.textContent = '×';
337
+ del.setAttribute('aria-label', `Remove this answer, ${runtime} · ${subjectText}`);
338
+ del.setAttribute('data-tip', 'Remove this answer');
339
+ del.onclick = () => removeAnswerWithUndo(answer.id);
340
+
341
+ if (who) {
342
+ who.insertBefore(chevron, who.firstChild); // chevron | name … time | ×
343
+ who.appendChild(del);
344
+ }
300
345
  return card;
301
346
  }
302
347
 
348
+ // One place that writes the chevron's per-state ARIA/tooltip, so the toggle and the card class can
349
+ // never drift. `expanded` name folds the subject in so a screen reader tells the per-card toggles
350
+ // apart from each other and from the bulk one.
351
+ function setCollapseToggleState(chevron, collapsed, name) {
352
+ chevron.setAttribute('aria-expanded', String(!collapsed));
353
+ chevron.setAttribute('aria-label', `${collapsed ? 'Expand' : 'Collapse'} this answer, ${name}`);
354
+ chevron.setAttribute('data-tip', collapsed ? 'Expand this answer' : 'Collapse this answer');
355
+ }
356
+
357
+ function announceAnswers(message) {
358
+ const status = document.getElementById('narrative-answer-status');
359
+ if (status) status.textContent = message;
360
+ }
361
+
362
+ // Toggle one card in place (no full re-render): flip the class + the chevron's ARIA, then re-derive
363
+ // the bulk button's aggregate label from what is now on screen.
364
+ function toggleAnswerCollapse(id) {
365
+ const willCollapse = !collapsedAnswerIds.has(id);
366
+ if (willCollapse) collapsedAnswerIds.add(id); else collapsedAnswerIds.delete(id);
367
+ const card = document.querySelector(`#ai-answers [data-answer-id="${CSS.escape(id)}"]`);
368
+ if (card) {
369
+ card.classList.toggle('answer-collapsed', willCollapse);
370
+ const chevron = card.querySelector('.answer-collapse-toggle');
371
+ const name = card.querySelector('.who-name')?.textContent || 'this context';
372
+ if (chevron) setCollapseToggleState(chevron, willCollapse, name);
373
+ }
374
+ syncAnswerBulkToggle();
375
+ }
376
+
377
+ // The bulk toggle's label is DERIVED, never stored: any card expanded → it offers "Collapse all";
378
+ // none expanded → "Expand all". A fresh arrival (always expanded) naturally returns it to the mixed
379
+ // state with no special-casing. Reads the live DOM so a single-card toggle keeps it honest too.
380
+ function syncAnswerBulkToggle() {
381
+ const button = document.getElementById('answers-collapse-all');
382
+ if (!button) return;
383
+ const cards = [...document.querySelectorAll('#ai-answers [data-answer-id]')];
384
+ const anyExpanded = cards.some((card) => !card.classList.contains('answer-collapsed'));
385
+ button.textContent = anyExpanded ? 'Collapse all' : 'Expand all';
386
+ button.setAttribute('aria-expanded', String(anyExpanded));
387
+ button.setAttribute('data-tip', anyExpanded ? 'Collapse every answer shown here' : 'Expand every answer shown here');
388
+ }
389
+
390
+ function toggleAllAnswers(visible) {
391
+ const anyExpanded = visible.some((answer) => !collapsedAnswerIds.has(answer.id));
392
+ for (const answer of visible) {
393
+ if (anyExpanded) collapsedAnswerIds.add(answer.id); else collapsedAnswerIds.delete(answer.id);
394
+ }
395
+ renderInstructorAnswers({ revealNew: false });
396
+ announceAnswers(`${anyExpanded ? 'Collapsed' : 'Expanded'} ${visible.length} answer${visible.length === 1 ? '' : 's'}`);
397
+ }
398
+
399
+ // The bulk row: a count on the left, the two actions on the right — the same shape as the Requests
400
+ // scope row. Built fresh each render (its handlers close over THIS paint's `visible`), which is also
401
+ // why "Clear all" acts on the snapshot the user is looking at, never a freshly re-derived scope.
402
+ function answersToolbar(visible) {
403
+ const bar = document.createElement('div');
404
+ bar.className = 'answers-toolbar';
405
+ bar.id = 'answers-toolbar';
406
+
407
+ const count = document.createElement('span');
408
+ count.className = 'answers-count';
409
+ count.textContent = `${visible.length} answer${visible.length === 1 ? '' : 's'}`;
410
+
411
+ const spacer = document.createElement('span');
412
+ spacer.className = 'answers-toolbar-spacer';
413
+ spacer.setAttribute('aria-hidden', 'true');
414
+
415
+ const collapseAll = document.createElement('button');
416
+ collapseAll.type = 'button';
417
+ collapseAll.id = 'answers-collapse-all';
418
+ collapseAll.className = 'answers-bulk';
419
+ collapseAll.setAttribute('data-command-id', 'shell.answers-collapse-all');
420
+ collapseAll.setAttribute('aria-label', 'Collapse or expand all answers');
421
+ collapseAll.textContent = 'Collapse all';
422
+ collapseAll.onclick = () => toggleAllAnswers(visible);
423
+
424
+ const clearAll = document.createElement('button');
425
+ clearAll.type = 'button';
426
+ clearAll.id = 'answers-clear-all';
427
+ clearAll.className = 'answers-bulk answers-clear';
428
+ clearAll.setAttribute('data-command-id', 'shell.answers-clear');
429
+ clearAll.textContent = 'Clear all';
430
+ clearAll.setAttribute('data-tip', visible.length === 1 ? 'Remove this answer' : `Remove all ${visible.length} answers shown here`);
431
+ clearAll.onclick = () => clearAllAnswers(visible);
432
+
433
+ bar.append(count, spacer, collapseAll, clearAll);
434
+ return bar;
435
+ }
436
+
437
+ // `×` on a card: hide it now, offer Undo, and only commit the (permanent) server delete once the
438
+ // window elapses. Keyed by id throughout so a card arriving mid-window can't shift what a timer or a
439
+ // focus target points at.
440
+ function removeAnswerWithUndo(id) {
441
+ if (pendingDeleteAnswerIds.has(id)) return;
442
+ // The card that will take this one's on-screen slot, captured BEFORE the re-render, so focus never
443
+ // falls to <body>. nextElementSibling first (the one just below), else the one above — a heuristic
444
+ // that holds whatever the sort order is.
445
+ const removing = document.querySelector(`#ai-answers [data-answer-id="${CSS.escape(id)}"]`);
446
+ const neighbourId = removing?.nextElementSibling?.dataset?.answerId
447
+ || removing?.previousElementSibling?.dataset?.answerId
448
+ || null;
449
+
450
+ pendingDeleteAnswerIds.add(id);
451
+ renderInstructorAnswers({ revealNew: false });
452
+ const focusTarget = neighbourId
453
+ ? document.querySelector(`#ai-answers [data-answer-id="${CSS.escape(neighbourId)}"] .answer-collapse-toggle`)
454
+ : (document.getElementById('answers-collapse-all') || document.querySelector('.ai-answers-empty'));
455
+ focusTarget?.focus?.({ preventScroll: true });
456
+ announceAnswers('Answer removed');
457
+
458
+ const commit = async () => {
459
+ answerDeleteTimers.delete(id);
460
+ // The reload is INSIDE the guard: a blip on loadRequests() after the DELETE already landed would
461
+ // otherwise reject this setTimeout-fired async fn as an unhandled rejection (no toast, no log) and
462
+ // strand the id in pendingDeleteAnswerIds forever. `finally` drops the pending id and repaints on
463
+ // every path, matching how deleteOneRequest wraps DELETE + reload + render in one try.
464
+ try {
465
+ await api(`/api/requests/${encodeURIComponent(id)}`, { method: 'DELETE' });
466
+ await loadRequests(); // refreshes instructorAnswers (the row is gone server-side now)
467
+ } catch (error) {
468
+ reportErr(error);
469
+ } finally {
470
+ pendingDeleteAnswerIds.delete(id);
471
+ renderInstructorAnswers({ revealNew: false });
472
+ }
473
+ };
474
+ answerDeleteTimers.set(id, setTimeout(commit, ANSWER_UNDO_MS));
475
+
476
+ // Pass ANSWER_UNDO_MS so the visible toast and the commit window are ONE number, not two literals
477
+ // that happen to match — bump the constant and the toast follows.
478
+ showUndoToast('Answer removed', () => {
479
+ const timer = answerDeleteTimers.get(id);
480
+ if (!timer) return; // already committed — a late Undo is a safe no-op
481
+ clearTimeout(timer);
482
+ answerDeleteTimers.delete(id);
483
+ pendingDeleteAnswerIds.delete(id);
484
+ renderInstructorAnswers({ revealNew: false });
485
+ document.querySelector(`#ai-answers [data-answer-id="${CSS.escape(id)}"] .answer-collapse-toggle`)?.focus?.({ preventScroll: true });
486
+ announceAnswers('Removal undone');
487
+ }, ANSWER_UNDO_MS);
488
+ }
489
+
490
+ // "Clear all" removes every answer in the SHOWN scope, confirmed once. No undo here (that was the
491
+ // deliberate split: undo for a single mis-click, a confirm for the bulk wipe). Per-id DELETE in a
492
+ // loop, exactly how the Requests dialog clears a scoped set — an answer's id IS its request id.
493
+ async function clearAllAnswers(visible) {
494
+ const ids = visible.map((answer) => answer.id);
495
+ if (!ids.length) return;
496
+ if (!(await confirmClearAnswers(ids.length))) return;
497
+ try {
498
+ for (const id of ids) await api(`/api/requests/${encodeURIComponent(id)}`, { method: 'DELETE' });
499
+ await loadRequests();
500
+ renderInstructorAnswers({ revealNew: false });
501
+ announceAnswers(`Cleared ${ids.length} answer${ids.length === 1 ? '' : 's'}`);
502
+ showToast(`Cleared ${ids.length} answer${ids.length === 1 ? '' : 's'}`, 'ok');
503
+ } catch (error) { reportErr(error); }
504
+ }
505
+
506
+ function confirmClearAnswers(count) {
507
+ return new Promise((resolve) => {
508
+ const modal = document.getElementById('answers-clear-modal');
509
+ const sub = document.getElementById('answers-clear-sub');
510
+ const confirm = document.getElementById('answers-clear-confirm');
511
+ const cancel = document.getElementById('answers-clear-cancel');
512
+ if (!modal || !confirm || !cancel) { resolve(false); return; }
513
+ if (sub) sub.textContent = `Remove ${count === 1 ? 'this answer' : `all ${count} answers`} shown here? This can’t be undone.`;
514
+ showModal(modal);
515
+ setTimeout(() => cancel.focus(), 0); // Cancel holds default focus, mirroring the routine delete
516
+ const done = (result) => {
517
+ hideModal(modal);
518
+ confirm.onclick = cancel.onclick = modal.onclick = null;
519
+ document.removeEventListener('keydown', onKey, true);
520
+ resolve(result);
521
+ };
522
+ const onKey = (event) => { if (event.key === 'Escape') { event.preventDefault(); done(false); } };
523
+ confirm.onclick = () => done(true);
524
+ cancel.onclick = () => done(false);
525
+ onBackdropDismiss(modal, () => done(false));
526
+ document.addEventListener('keydown', onKey, true);
527
+ });
528
+ }
529
+
303
530
  function acceptInstructorAnswers(answers, { initial = false } = {}) {
304
531
  instructorAnswers = answers;
305
532
  if (initial) {
@@ -327,8 +554,13 @@
327
554
  function renderInstructorAnswers({ revealNew = true } = {}) {
328
555
  const feed = document.getElementById('ai-answers');
329
556
  if (!feed) return;
330
- const visible = instructorAnswers.filter(answerInVisibleScope);
331
- const wasNearBottom = feed.scrollHeight - feed.scrollTop - feed.clientHeight < 72;
557
+ // A card mid-way through the deferred-delete window is filtered out of every render, so a poll
558
+ // that refreshes the feed can't flash it back into view before its Undo window closes.
559
+ const visible = instructorAnswers.filter(answerInVisibleScope).filter((answer) => !pendingDeleteAnswerIds.has(answer.id));
560
+ // Newest-first: the latest answer sits at the top. A blind reverse of the stored order would ride
561
+ // on filesystem read order; sorting on finishedAt is the ordering the user actually asked for.
562
+ const ordered = [...visible].sort((a, b) => String(b.finishedAt || '').localeCompare(String(a.finishedAt || '')));
563
+ const wasNearTop = feed.scrollTop < 72;
332
564
  const unseen = revealNew ? visible.filter((answer) => arrivedInstructorAnswerIds.has(answer.id)) : [];
333
565
  const unreadCount = visible.filter((answer) => !readInstructorAnswerIds.has(answer.id)).length;
334
566
  const unreadBadge = document.getElementById('answer-unread');
@@ -341,12 +573,14 @@
341
573
  else answersTab?.removeAttribute('aria-label');
342
574
  const newAnswer = unseen.length ? unseen[unseen.length - 1] : null;
343
575
  feed.innerHTML = '';
344
- if (!visible.length) {
576
+ if (!ordered.length) {
345
577
  const scope = wsRequestScope?.kind === 'project' ? 'this project' : wsRequestScope ? 'Workspaces' : 'this workflow';
346
- feed.innerHTML = `<div class="ai-answers-empty">No AI answers for ${scope} yet. Direct answers you start from Instructor will appear here.</div>`;
578
+ feed.innerHTML = `<div class="ai-answers-empty" tabindex="-1">No AI answers for ${scope} yet. Direct answers you start from Instructor will appear here.</div>`;
347
579
  } else {
348
- visible.forEach((answer) => feed.appendChild(answerCard(answer, answer === newAnswer)));
580
+ feed.appendChild(answersToolbar(ordered)); // sticky bulk row — first child, hidden with an empty feed by simply not existing
581
+ ordered.forEach((answer) => feed.appendChild(answerCard(answer, answer === newAnswer)));
349
582
  }
583
+ syncAnswerBulkToggle();
350
584
  if (!newAnswer) {
351
585
  return;
352
586
  }
@@ -369,7 +603,9 @@
369
603
  document.getElementById('ai-answers-tab')?.classList.add('instructor-answer-new');
370
604
  }
371
605
  const card = feed.querySelector(`[data-answer-id="${CSS.escape(newAnswer.id)}"]`);
372
- if (card && !obscured && (wasCollapsed || (paneAlreadyOpenOnAnswers && wasNearBottom))) requestAnimationFrame(() => card.scrollIntoView({ block: 'nearest' }));
606
+ // Newest-first puts the arrival at the TOP, so the auto-scroll follows a reader sitting near the
607
+ // top — not the bottom, which now holds the oldest answers someone may be mid-read of.
608
+ if (card && !obscured && (wasCollapsed || (paneAlreadyOpenOnAnswers && wasNearTop))) requestAnimationFrame(() => card.scrollIntoView({ block: 'nearest' }));
373
609
  const status = document.getElementById('narrative-answer-status');
374
610
  if (status) status.textContent = wasCollapsed && !obscured
375
611
  ? `Terminal AI answered about ${newAnswer.instructorContext.subject}. AI answers opened.`
@@ -1978,7 +2214,7 @@
1978
2214
  // see the HEAD note below for why that is the wrong price for a word. "model or drawing" is never
1979
2215
  // WRONG, only vaguer, so the failure mode is a less specific warning rather than a false one.
1980
2216
  const noun = id === 'steel-model' ? 'steel model' : id === 'vectorize' ? 'traced drawing' : 'model or drawing';
1981
- // 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
1982
2218
  // limit — they embed sheet rasters). Downloading that to choose a word would stall the dialog on
1983
2219
  // exactly the models most worth warning about. Fastify serves HEAD for every GET route, and the
1984
2220
  // three cases the copy distinguishes come back identically: 200 = something saved, 204 = nothing,
@@ -2518,7 +2754,7 @@
2518
2754
  // These two card tips are owned by this renderer. Clear them before recomputing state so an
2519
2755
  // in-place contract/project refresh cannot leave "Double-click to open…" over disabled actions.
2520
2756
  if (card.dataset.tip === 'Double-click to open the contract editor'
2521
- || card.dataset.tip === 'Double-click to open the steel filter') {
2757
+ || card.dataset.tip === 'Double-click to open the Drawing Filter') {
2522
2758
  delete card.dataset.tip;
2523
2759
  }
2524
2760
  if (isInput) addNodeInputs(card); // current values, above the button
@@ -2611,7 +2847,7 @@
2611
2847
  }
2612
2848
  const filterBtn = addNodeAction(card, 'Filter ▸', () => openFilterView(currentId));
2613
2849
  if (publication) filterBtn.disabled = true;
2614
- 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';
2615
2851
  }
2616
2852
  });
2617
2853
  if (hasTeklaAction && !teklaReadinessState) refreshTeklaReadiness();
@@ -3148,7 +3384,7 @@
3148
3384
  const ap = document.getElementById('contract-editor-approve'); if (ap) ap.hidden = true;
3149
3385
  $contractEditorTitle.replaceChildren(
3150
3386
  Object.assign(document.createElement('span'), { textContent: appId, style: 'color:var(--text);font-weight:600' }),
3151
- 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)' }),
3152
3388
  );
3153
3389
  $contractEditorFrame.onload = () => { try { $contractEditorFrame.contentWindow.focus(); } catch (_) {} };
3154
3390
  $contractEditorFrame.src = '/steel-filter.html?app=' + encodeURIComponent(appId);
@@ -3163,7 +3399,7 @@
3163
3399
  try { guard = $contractEditorFrame.contentWindow && $contractEditorFrame.contentWindow.__floGuard; }
3164
3400
  catch (_) { guard = null; }
3165
3401
  if (guard && typeof guard.isDirty === 'function' && guard.isDirty()) {
3166
- 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');
3167
3403
  if (choice === 'cancel') return; // keep the view open
3168
3404
  if (choice === 'save') { const ok = await guard.save(); if (!ok) return; } // save failed → stay open
3169
3405
  else if (choice === 'discard') { try { guard.discard(); } catch (_) {} } // silence the backstop
@@ -3645,6 +3881,16 @@
3645
3881
  return new Promise((resolve) => {
3646
3882
  if (_confirmModalOpen) { console.warn('confirmUnsavedSwitch: confirmation already open'); resolve('cancel'); return; }
3647
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
+ });
3648
3894
  const $title = document.getElementById('confirm-modal-title');
3649
3895
  const $sub = document.getElementById('confirm-modal-sub');
3650
3896
  const $save = document.getElementById('confirm-save');
@@ -3665,14 +3911,23 @@
3665
3911
  settled = true;
3666
3912
  _confirmModalOpen = false;
3667
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
+ });
3668
3919
  $dont.hidden = false;
3669
- $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;
3670
3922
  if (returnFocus && returnFocus.isConnected && !returnFocus.matches(':disabled,[aria-disabled="true"]')) returnFocus.focus();
3671
3923
  resolve(result);
3672
3924
  };
3673
3925
  const onKey = (e) => {
3674
3926
  if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); done('cancel'); }
3675
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();
3676
3931
  const focusable = Array.from($confirmModal.querySelectorAll('button:not([disabled]):not([hidden]), [tabindex]:not([tabindex="-1"])'))
3677
3932
  .filter((el) => el instanceof HTMLElement && !el.hidden && el.getClientRects().length);
3678
3933
  if (!focusable.length) { e.preventDefault(); return; }
@@ -3688,7 +3943,10 @@
3688
3943
  $dont.onclick = () => done('discard');
3689
3944
  $cancel.onclick = () => done('cancel');
3690
3945
  onBackdropDismiss($confirmModal, () => done('cancel'));
3691
- $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);
3692
3950
  });
3693
3951
  }
3694
3952
 
@@ -3774,6 +4032,11 @@
3774
4032
  const $body = document.getElementById('form-modal-body');
3775
4033
  const $ok = document.getElementById('form-modal-ok');
3776
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') }));
3777
4040
  $title.textContent = title;
3778
4041
  $sub.textContent = sub || '';
3779
4042
  $sub.hidden = !sub;
@@ -3901,6 +4164,10 @@
3901
4164
  $ok.classList.toggle('primary', !danger);
3902
4165
  $cancel.classList.toggle('primary', !!danger);
3903
4166
  $cancel.hidden = !!hideCancel;
4167
+ coveredModals.forEach(({ modal }) => {
4168
+ modal.inert = true;
4169
+ modal.setAttribute('aria-hidden', 'true');
4170
+ });
3904
4171
  showModal($formModal);
3905
4172
  // Prefer a real text input; else a select's trigger; else a file drop zone (so keyboard
3906
4173
  // users land somewhere actionable rather than a possibly-disabled OK button).
@@ -4347,6 +4614,11 @@
4347
4614
  _formModalOpen = false;
4348
4615
  modalClosed = true;
4349
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
+ });
4350
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;
4351
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
4352
4624
  let focusTarget = returnFocus;
@@ -4363,6 +4635,10 @@
4363
4635
  // destructive confirm where focus sits on Cancel, not in the (empty) body. Enter
4364
4636
  // commits only for a normal form (never a danger confirm; never inside a textarea).
4365
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();
4366
4642
  if (e.key === 'Escape') { e.preventDefault(); done(null); }
4367
4643
  else if (e.key === 'Tab') {
4368
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"])'))
@@ -7524,16 +7800,55 @@
7524
7800
  // tweakNode, requestGuide, requestNewWorkflow, panels.js's customize box) say only "queued, not
7525
7801
  // copied" and name no cause, so they cannot conflate anything and are deliberately left alone. Add
7526
7802
  // a new surface that names a cause and it belongs here.
7527
- async function copyRequest(req) {
7528
- 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) : '';
7529
7837
  if (!line) return 'empty';
7530
- return (await copyToClipboard(line)) ? 'ok' : 'denied';
7838
+ const copied = await copyToClipboard(line);
7839
+ return owns() ? (copied ? 'ok' : 'denied') : 'stale';
7531
7840
  }
7532
7841
  // Total by construction: a lookup miss here would spread `undefined` into showToast and throw inside
7533
7842
  // an async onclick — silence, which is worse than the wrong message this exists to replace.
7534
- const copyFailToast = (res) => (res === 'empty'
7535
- ? ['Nothing to copy — this request has no instruction', 'err']
7536
- : ['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']);
7537
7852
 
7538
7853
  // ── Headless runs (#571 slice 3) ────────────────────────────────────────────
7539
7854
  // floless starting the user's OWN terminal AI on a queued request, instead of them pasting it.
@@ -7545,11 +7860,18 @@
7545
7860
  // FOLDER is per project, so anything that needs it re-reads with the project key rather than
7546
7861
  // trusting this. Server-side detection spawns nothing — it is statSync work — so an open is cheap.
7547
7862
  let headlessInfo = null;
7863
+ let headlessFetchEpoch = 0;
7548
7864
  async function refreshHeadless() {
7549
7865
  // A detection failure HIDES the feature rather than leaving a button that cannot work. There is
7550
7866
  // no honest middle: without the runtime list we do not know that anything is installed.
7551
- try { headlessInfo = await api('/api/terminal-runtimes'); }
7552
- 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;
7553
7875
  return headlessInfo;
7554
7876
  }
7555
7877
  const headlessRuntimes = () => (headlessInfo && Array.isArray(headlessInfo.runtimes) ? headlessInfo.runtimes : []);
@@ -7583,12 +7905,15 @@
7583
7905
  // response must not turn an arbitrary terminal state into an implied "resume" instruction.
7584
7906
  const RESUMABLE_RUN_STATES = new Set(['needs-you', 'stopped', 'interrupted', 'contract-violation', 'exited-unresolved']);
7585
7907
 
7586
- async function copyResumeCommand(command) {
7908
+ async function copyResumeCommand(command, stillOwned = () => true) {
7587
7909
  if (!command) return 'empty';
7588
- 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';
7589
7914
  }
7590
7915
 
7591
- function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId) {
7916
+ function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId, commandInstance) {
7592
7917
  if (!run || !run.state) return '';
7593
7918
  const v = RUN_VIEW[run.state] || { badge: String(run.state), cls: 'muted', note: () => '' };
7594
7919
  const rt = runtimeLabel(run.runtime);
@@ -7604,18 +7929,18 @@
7604
7929
  const appButtons = handoffs && !claim ? availableProviders.map((provider, i) => {
7605
7930
  const app = handoffs[provider];
7606
7931
  const label = provider === 'codex' ? 'Codex' : 'Claude';
7607
- 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>`;
7608
7933
  }).join('') : '';
7609
7934
  const desktop = handoffs
7610
7935
  ? claim
7611
- ? `<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>`
7612
- : `<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>`
7613
7938
  : '';
7614
7939
  // Never expose a reusable resume command beside a claim-aware handoff bootstrap. A user could
7615
7940
  // copy one, claim the other, and later start two writers in the same folder. The bootstrap remains
7616
7941
  // copyable even when native launch fails or no protocol fits, and is safe to paste in an app or CLI.
7617
7942
  const terminalFallback = !handoffs && resumeCommand
7618
- ? `<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>`
7619
7944
  : '';
7620
7945
  return `
7621
7946
  <div class="req-run-status">
@@ -7652,11 +7977,24 @@
7652
7977
  }
7653
7978
  }
7654
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
+
7655
7992
  async function stopRequestRun(req) {
7656
7993
  try {
7657
7994
  await api(`/api/requests/${encodeURIComponent(req.id)}/run/stop`, { method: 'POST' });
7658
7995
  await loadRequests();
7659
7996
  renderRequests();
7997
+ focusRequestContinuation(req.id);
7660
7998
  } catch (e) { reportErr(e); }
7661
7999
  }
7662
8000
 
@@ -7686,7 +8024,7 @@
7686
8024
  // The TITLE carries the refusal too, not just the sub. Both are re-set per open, so this
7687
8025
  // leaks nothing to the next caller — and without it the only thing that changes on a bad
7688
8026
  // folder is one line of muted grey, in the same tier as the explanation it replaced.
7689
- title: refused ? 'That folder won’t work' : 'Run this for me',
8027
+ title: refused ? 'That folder won’t work' : 'Start this request automatically',
7690
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.',
7691
8029
  fields: [
7692
8030
  {
@@ -7723,11 +8061,14 @@
7723
8061
 
7724
8062
  let requestHelpReq = null;
7725
8063
  let requestHelpReturnFocus = null;
8064
+ let requestHelpEpoch = 0;
7726
8065
  function closeRequestHelp({ restoreFocus = true } = {}) {
8066
+ requestHelpEpoch += 1;
7727
8067
  const $m = document.getElementById('request-help-modal');
7728
8068
  if ($m) hideModal($m);
7729
8069
  const target = requestHelpReturnFocus;
7730
8070
  requestHelpReturnFocus = null;
8071
+ requestHelpReq = null;
7731
8072
  if (restoreFocus && target && target.isConnected) {
7732
8073
  try { target.focus(); } catch { /* focus is best-effort */ }
7733
8074
  }
@@ -7735,28 +8076,40 @@
7735
8076
  function showRequestQueuedModal(req, opts = {}) {
7736
8077
  const $m = document.getElementById('request-help-modal');
7737
8078
  if (!$m || !req) return;
8079
+ requestHelpEpoch += 1;
7738
8080
  requestHelpReq = req;
7739
8081
  requestHelpReturnFocus = opts.returnFocus || document.activeElement;
7740
8082
  const copied = opts.copied !== false;
7741
- 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'}`;
7742
8087
  const isRevisionRead = req.type === 'revision-read';
7743
8088
  const isInitial = isRevisionRead && (!req.baseVersion || req.baseVersion <= 0);
8089
+ const canUseManualHandoff = !isRevisionRead || req.status === 'pending';
7744
8090
  const $title = document.getElementById('request-help-title');
7745
8091
  const $sub = document.getElementById('request-help-sub');
7746
- const $note = document.getElementById('request-help-note');
7747
8092
  const $copy = document.getElementById('request-help-copy');
7748
8093
  if ($title) $title.textContent = isRevisionRead
7749
- ? `${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'
7750
8097
  : 'Request queued';
7751
8098
  if ($sub) {
7752
- $sub.textContent = copied
7753
- ? `${n} drawing file${n === 1 ? '' : 's'} added to Requests. The terminal instructions were copied to your clipboard.`
7754
- : `${n} drawing file${n === 1 ? '' : 's'} added to Requests. Copy the terminal instructions from here or from the Requests panel.`;
7755
- }
7756
- if ($note) $note.textContent = isRevisionRead
7757
- ? 'The web UI queues the drawing read; your terminal agent applies it and reports progress back here.'
7758
- : 'The web UI queues the request; your terminal agent applies it and reports progress back here.';
7759
- 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;
7760
8113
  // Back to the "not started" face on every open — the previous request's run status must never
7761
8114
  // be the first thing the next one shows.
7762
8115
  setRequestHelpRunning(null);
@@ -7766,22 +8119,101 @@
7766
8119
  // Detection is a fetch, and this modal is opened synchronously by the caller. Reveal the split
7767
8120
  // when the answer lands rather than blocking the modal on it — and only if THIS request is
7768
8121
  // still the one on screen, since a second queue can land while the first fetch is in flight.
7769
- 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
+ });
7770
8130
  syncRequestHelpRun();
7771
8131
  }
7772
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
+
7773
8197
  /** Show the run split only when this request's type can run AND a runtime exists (§E1/§E4). */
7774
8198
  function syncRequestHelpRun() {
7775
8199
  const $split = document.getElementById('request-help-run-split');
7776
8200
  const $open = document.getElementById('request-help-open');
7777
8201
  if (!$split || !$open) return;
7778
- const can = !!(requestHelpReq && requestHelpReq.canRun && headlessReady());
8202
+ const can = !!(requestHelpReq && requestHelpReq.canRun
8203
+ && (requestHelpReq.type !== 'revision-read' || requestHelpReq.status === 'pending') && headlessReady());
7779
8204
  $split.hidden = !can;
7780
8205
  // Exactly one primary in the row: Run takes it when it is there, Open Requests reclaims it
7781
8206
  // when it is not — a modal with no emphasized action reads as unfinished.
7782
8207
  $open.classList.toggle('primary', !can);
7783
8208
  }
7784
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
+
7785
8217
  /**
7786
8218
  * Swap the modal's three "what you must do" steps for what floless is doing instead.
7787
8219
  *
@@ -7883,6 +8315,33 @@
7883
8315
  acceptInstructorAnswers(answers);
7884
8316
  }
7885
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
+ }
7886
8345
  const $rc = document.getElementById('req-count');
7887
8346
  const $rs = document.getElementById('req-stat');
7888
8347
  if ($rc) $rc.textContent = requests.length;
@@ -7983,12 +8442,169 @@
7983
8442
  // Both the NAME and the raw ids are searchable: you may know a project as "Cedar Mill Warehouse"
7984
8443
  // or as the `take-5-6677ee` in its URL, and either should find it.
7985
8444
  function requestSearchText(r) {
7986
- 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)]
7987
8446
  .filter(Boolean).join(' ');
7988
8447
  }
7989
8448
 
7990
8449
  function requestLabel(r) {
7991
- 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.`;
7992
8608
  }
7993
8609
 
7994
8610
  // Escape `text`, wrapping every case-insensitive occurrence of `q` in <mark>. Splits the RAW
@@ -8017,8 +8633,8 @@
8017
8633
 
8018
8634
  // The set the window is currently showing — the ONE definition of "these requests", so the
8019
8635
  // rows and the counts on the scope tabs can never disagree.
8020
- function shownRequests() {
8021
- return visibleRequests(pendingRequests, requestScopeAll ? null : activeRequestScope(), requestQuery, requestSearchText);
8636
+ function shownRequests(query = requestQuery) {
8637
+ return visibleRequests(pendingRequests, requestScopeAll ? null : activeRequestScope(), query, requestSearchText);
8022
8638
  }
8023
8639
 
8024
8640
  // Exactly what the OPEN window last painted. The bulk actions read THIS, never shownRequests().
@@ -8057,13 +8673,13 @@
8057
8673
  * per-id loop rather than the atomic verb.
8058
8674
  */
8059
8675
  function bulkClearPlan(painted, all, filterActive) {
8060
- const keep = painted.filter((r) => r && (r.type === 'knowledge-organize' || (r.desktopHandoffs && r.desktopHandoffs.claim)));
8061
- 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);
8062
8678
  return { atomic: !filterActive && !keep.length && painted.length === all.length, keep, drop };
8063
8679
  }
8064
8680
 
8065
- // The Requests window: every queued change in a list, each copyable + clearable,
8066
- // 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
8067
8683
  // appId/nodeId/instruction) is rendered via textContent-equivalent escaping — which matters MORE
8068
8684
  // now that the string arrives over the wire rather than being built from local state.
8069
8685
  function renderRequests() {
@@ -8072,6 +8688,11 @@
8072
8688
  const $copy = document.getElementById('requests-copy');
8073
8689
  const $search = document.getElementById('requests-search');
8074
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;
8075
8696
  // Search is pointless over an empty queue, and over a single request it is just clutter.
8076
8697
  // Drop the query WITH the box, and before anything is filtered by it: a hidden filter still
8077
8698
  // filtering is how a list ends up inexplicably empty (the last two requests clear while a
@@ -8080,9 +8701,10 @@
8080
8701
  $search.hidden = pendingRequests.length < 2;
8081
8702
  if ($search.hidden && requestQuery) { requestQuery = ''; $search.value = ''; }
8082
8703
  }
8704
+ const normalizedRequestQuery = requestQuery.trim();
8083
8705
  const scope = activeRequestScope();
8084
8706
  const inScope = visibleRequests(pendingRequests, scope, '', requestSearchText);
8085
- const shown = shownRequests();
8707
+ const shown = shownRequests(normalizedRequestQuery);
8086
8708
  shownSnapshot = shown; // the bulk actions act on THIS paint — see the note on shownSnapshot
8087
8709
  const nothingQueued = pendingRequests.length === 0;
8088
8710
 
@@ -8092,6 +8714,7 @@
8092
8714
  const $scope = document.getElementById('requests-scope');
8093
8715
  const $here = document.getElementById('requests-scope-here');
8094
8716
  const $all = document.getElementById('requests-scope-all');
8717
+ const $guidance = document.getElementById('requests-guidance');
8095
8718
  if ($scope) $scope.hidden = !scope || nothingQueued;
8096
8719
  if (scope && $here && $all) {
8097
8720
  const kind = scope.kind === 'project' ? 'project' : 'workflow';
@@ -8106,6 +8729,13 @@
8106
8729
  $all.classList.toggle('active', requestScopeAll);
8107
8730
  $all.setAttribute('aria-selected', String(requestScopeAll));
8108
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
+ }
8109
8739
 
8110
8740
  // Hide (not just disable) the bulk actions when there's nothing to act on — a
8111
8741
  // disabled "Clear all"/"Copy all" over an empty list reads as broken UI. They act on
@@ -8113,16 +8743,30 @@
8113
8743
  const bulkTip = (verb) => (shown.length === pendingRequests.length
8114
8744
  ? `${verb} all ${pendingRequests.length} queued request${pendingRequests.length === 1 ? '' : 's'}`
8115
8745
  : `${verb} the ${shown.length} request${shown.length === 1 ? '' : 's'} shown here`);
8116
- if ($clear) { $clear.hidden = shown.length === 0; $clear.setAttribute('data-tip', bulkTip('Clear')); }
8117
- 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
+ }
8118
8762
 
8119
8763
  if (shown.length === 0) {
8120
8764
  // Three different nothings, and conflating them is what makes a filter feel broken: an
8121
8765
  // empty queue, a queue with nothing for THIS project, and a search that missed.
8122
8766
  const msg = nothingQueued
8123
8767
  ? 'No requests queued. Save a Template or ✎ Tweak a node to send a change to your terminal AI.'
8124
- : requestQuery.trim()
8125
- ? `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.' : ''}`
8126
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>`;
8127
8771
  $list.innerHTML = `<div class="empty-state">${msg}</div>`;
8128
8772
  const $showAll = $list.querySelector('.req-showall');
@@ -8135,7 +8779,7 @@
8135
8779
  // has no button. Derived from this paint — deliberately not a stored "has run before" flag,
8136
8780
  // which would make the same list read differently for two people.
8137
8781
  const anyRunnable = headlessReady() && shown.some((r) => r && r.canRun);
8138
- $list.innerHTML = shown.map((r) => {
8782
+ $list.innerHTML = shown.map((r, shownIndex) => {
8139
8783
  const label = requestLabel(r);
8140
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';
8141
8785
  // One name, and only the name. The node/input/sheet chips that used to sit here ("· node
@@ -8148,44 +8792,67 @@
8148
8792
  // chip has nothing left to rescue.
8149
8793
  const owner = requestOwnerName(r);
8150
8794
  const when = r.createdAt ? new Date(r.createdAt) : null;
8151
- 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}`;
8152
8801
  // A knowledge-organize is resolved by its own finish/fail lifecycle POST. Offering a ✕ here
8153
8802
  // would let the user delete a request the terminal AI is mid-way through, 404-ing finish/fail
8154
8803
  // and stranding the organize lock until its stale timeout. Show why it can't be cleared instead.
8155
- 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;
8156
8811
  const inFlight = !!run && (run.state === 'queued' || run.state === 'running');
8157
- const desktopClaimed = !!(r.desktopHandoffs && r.desktopHandoffs.claim);
8812
+ const desktopClaimed = !!(desktopHandoffs && desktopHandoffs.claim);
8158
8813
  const lifecycleOwned = r.type === 'knowledge-organize';
8814
+ const canClear = requestCanClear(r);
8159
8815
  // ✕ goes away while a run is live, for the same reason it goes away on a knowledge-organize:
8160
8816
  // deleting the request out from under a working agent leaves it unable to clear its own work,
8161
8817
  // and the run then lands in `exited-unresolved` for a reason the user caused and cannot see.
8162
8818
  const del = lifecycleOwned
8163
8819
  ? '<span class="req-lifecycle" data-tip="This clears itself when your terminal AI finishes or fails the organize">finishing in your terminal</span>'
8164
8820
  : inFlight || desktopClaimed
8165
- ? '<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>'
8166
- : `<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>`;
8167
8827
  // A server-stamped handoff gets NO re-run. The original terminal session may already be live;
8168
- // starting a second headless agent would put two writers in one folder. The browser decides no
8169
- // policy here: it simply withholds ▶ whenever the server supplied the resume command.
8170
- 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;
8171
8836
  const runBtn = inFlight
8172
- ? `<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>`
8173
8838
  : canRunNow
8174
- ? `<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>`
8175
8840
  : '';
8176
8841
  return `
8177
8842
  <div class="req-item" data-id="${escapeAttr(r.id)}">
8178
8843
  <div class="req-info">
8179
- <div class="req-head"><span class="${badgeCls}">${label}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, requestQuery)}</span>` : ''}${time}</div>
8180
- <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>`}
8181
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>` : ''}
8182
- ${runStatusHtml(run, r.resumeCommand, r.desktopHandoffs, r.id)}
8183
- ${!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>` : ''}
8184
8851
  </div>
8185
8852
  <div class="req-actions">
8186
8853
  ${runBtn}
8187
- ${r.desktopHandoffs || r.resumeCommand ? '' : `<button class="req-copy" data-id="${escapeAttr(r.id)}" data-tip="Copy this instruction">⧉</button>`}
8188
- ${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"')}
8189
8856
  </div>
8190
8857
  </div>`;
8191
8858
  }).join('');
@@ -8205,14 +8872,28 @@
8205
8872
  b.onclick = async () => {
8206
8873
  const r = pendingRequests.find((x) => x.id === b.dataset.id);
8207
8874
  if (!r) return;
8208
- 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;
8209
8882
  if (res === 'ok') showToast('Copied — paste it to your terminal AI', 'ok');
8210
8883
  else showToast(...copyFailToast(res));
8211
8884
  };
8212
8885
  });
8213
8886
  $list.querySelectorAll('.req-run-resume-command').forEach((b) => {
8214
8887
  b.onclick = async () => {
8215
- 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;
8216
8897
  if (res === 'ok') showToast('Copied — run it in the folder shown below', 'ok');
8217
8898
  else if (res === 'empty') showToast('Nothing to copy — this run has no resume command', 'err');
8218
8899
  else showToast('Could not copy — select the command and copy it manually', 'err');
@@ -8265,8 +8946,16 @@
8265
8946
  });
8266
8947
  $list.querySelectorAll('.req-app-copy').forEach((b) => {
8267
8948
  b.onclick = async () => {
8268
- const result = await copyToClipboard(b.dataset.handoffPrompt || '');
8269
- 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');
8270
8959
  };
8271
8960
  });
8272
8961
  $list.querySelectorAll('.req-app-release').forEach((b) => {
@@ -8319,18 +9008,30 @@
8319
9008
  showToast(`Cleared ${result.cleared} request${result.cleared === 1 ? '' : 's'} — ${result.failed} could not be cleared`, 'err');
8320
9009
  return;
8321
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
+ }
8322
9017
  } else {
8323
9018
  for (const r of drop) await api(`/api/requests/${encodeURIComponent(r.id)}`, { method: 'DELETE' });
8324
9019
  }
8325
9020
  await loadRequests();
8326
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 ');
8327
9028
  showToast(
8328
9029
  keep.length
8329
- ? `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}`
8330
9031
  : atomic
8331
9032
  ? 'Cleared all requests'
8332
9033
  : `Cleared ${drop.length} request${drop.length === 1 ? '' : 's'} shown here`,
8333
- 'ok',
9034
+ keep.length ? 'info' : 'ok',
8334
9035
  );
8335
9036
  } catch (e) { reportErr(e); }
8336
9037
  }
@@ -8341,14 +9042,20 @@
8341
9042
  }
8342
9043
  // Re-fetch before showing: there is no server `request-added` broadcast, so a request queued in
8343
9044
  // another tab (or by the Knowledge step) would otherwise render from a stale cache.
8344
- async function openRequests(targetId) {
9045
+ async function openRequests(targetId, returnFocusTo = null) {
8345
9046
  // Open on the scope + a clear search every time. A stuck "All" (or a leftover query) from a
8346
9047
  // previous visit would silently answer a different question than the one just asked.
8347
9048
  requestScopeAll = false;
8348
9049
  requestQuery = '';
8349
9050
  const $search = document.getElementById('requests-search');
8350
9051
  if ($search) $search.value = '';
8351
- 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();
8352
9059
  renderRequests(); // paint the cache immediately — no empty flash
8353
9060
  // Scroll off the CACHED paint, before the refetch. Gating the reveal on `/api/requests` means an
8354
9061
  // arbitrarily slow response leaves the list sitting at the top — precisely the state this feature
@@ -10074,33 +10781,29 @@
10074
10781
  const $debugBtn = document.getElementById('debug-btn');
10075
10782
  if ($debugBtn) $debugBtn.onclick = () => { if (state.selectedAgentId) runReport(state.selectedAgentId, { debug: true }); };
10076
10783
  const $reqStat = document.getElementById('req-stat');
10077
- 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
+ }
10078
10791
  const $reqModal = document.getElementById('requests-modal');
10079
10792
  const $reqClose = document.getElementById('requests-close');
10080
- if ($reqClose) $reqClose.onclick = () => $reqModal.classList.remove('show');
10081
- 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);
10082
10803
  const $reqClear = document.getElementById('requests-clear');
10083
10804
  if ($reqClear) $reqClear.onclick = () => clearAllRequests();
10084
10805
  const $reqCopy = document.getElementById('requests-copy');
10085
- if ($reqCopy) $reqCopy.onclick = async () => {
10086
- const shown = paintedRequests(); // what was PAINTED, not a re-derived scope — see shownSnapshot
10087
- if (!shown.length) return;
10088
- // Count what actually made it, not what was in the list. `.filter(Boolean)` silently drops a
10089
- // request with no instruction body, and reporting the list length over that is the
10090
- // original bug wearing a bulk hat: the user pastes, the AI applies the ones that copied, and the
10091
- // dropped request never reaches the terminal while the toast said it did.
10092
- const lines = shown.map(markedInstruction).filter(Boolean);
10093
- const dropped = shown.length - lines.length;
10094
- if (!lines.length) { showToast('Nothing to copy — none of these requests has an instruction', 'err'); return; }
10095
- const copied = await copyToClipboard(lines.join('\n\n'));
10096
- if (!copied) { showToast('copy failed', 'err'); return; }
10097
- showToast(
10098
- dropped
10099
- ? `Copied ${lines.length} of ${shown.length} — ${dropped} had no instruction and ${dropped === 1 ? 'was' : 'were'} skipped`
10100
- : `Copied ${lines.length} request(s) — paste to your terminal AI`,
10101
- dropped ? 'warn' : 'ok',
10102
- );
10103
- };
10806
+ if ($reqCopy) $reqCopy.onclick = copyPaintedRequests;
10104
10807
  const $reqScope = document.getElementById('requests-scope');
10105
10808
  if ($reqScope) $reqScope.onclick = (e) => {
10106
10809
  const b = e.target.closest('button[data-reqscope]');
@@ -10116,14 +10819,19 @@
10116
10819
  // Read the id BEFORE closing — this button means "take me to the one I just queued", and only
10117
10820
  // this entry point knows which that is.
10118
10821
  const id = requestHelpReq && requestHelpReq.id;
10822
+ const returnFocus = requestHelpReturnFocus;
10119
10823
  closeRequestHelp({ restoreFocus: false });
10120
- openRequests(id);
10824
+ openRequests(id, returnFocus);
10121
10825
  };
10122
10826
  if ($requestHelpKeep) $requestHelpKeep.onclick = () => closeRequestHelp();
10123
- if ($requestHelpCopy) $requestHelpCopy.onclick = async () => {
10124
- if (!requestHelpReq) return;
10827
+ async function copyFromRequestHelp() {
10828
+ const req = requestHelpReq;
10829
+ if (!req) return;
10125
10830
  // Via copyRequest, so an instruction-less type says so rather than "copy failed".
10126
- 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;
10127
10835
  const copied = res === 'ok';
10128
10836
  if (copied) showToast('Copied — paste it to your terminal AI', 'ok');
10129
10837
  else showToast(...copyFailToast(res));
@@ -10136,7 +10844,8 @@
10136
10844
  const $sub = document.getElementById('request-help-sub');
10137
10845
  if ($sub) $sub.textContent = 'Terminal instructions copied. Open the terminal agent and paste them there.';
10138
10846
  }
10139
- };
10847
+ }
10848
+ if ($requestHelpCopy) $requestHelpCopy.onclick = copyFromRequestHelp;
10140
10849
  // ▶ runs with the resolved default; ▾ asks folder + which terminal AI first. Both leave the modal
10141
10850
  // OPEN on success and swap its steps for the run status — closing it would hide the one sentence
10142
10851
  // that says what floless just started on the user's behalf.
@@ -10159,7 +10868,22 @@
10159
10868
  closeRequestHelp();
10160
10869
  return;
10161
10870
  }
10162
- 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
+ }
10163
10887
  });
10164
10888
 
10165
10889
  // Per-workflow onboarding beacon + guide panel + first-open spotlight.