@floless/app 0.139.1 → 0.141.0

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.
Files changed (41) hide show
  1. package/dist/floless-server.cjs +32765 -36490
  2. package/dist/skills/floless-app-steel-takeoff/SKILL.md +8 -3
  3. package/dist/skills/floless-app-vectorize/SKILL.md +1 -1
  4. package/dist/skills/floless-app-vectorize/scripts/extract_pdf.py +7 -1
  5. package/dist/skills/floless-app-vectorize/scripts/vision_to_contract.py +7 -1
  6. package/dist/web/app.css +163 -3
  7. package/dist/web/aware.js +657 -66
  8. package/dist/web/chat.css +387 -25
  9. package/dist/web/chat.js +2005 -108
  10. package/dist/web/commands-filter.js +86 -8
  11. package/dist/web/commands-revit.js +2 -1
  12. package/dist/web/commands-shell.js +249 -13
  13. package/dist/web/commands-steel.js +34 -24
  14. package/dist/web/commands.js +19 -0
  15. package/dist/web/filter-ai-context.js +57 -0
  16. package/dist/web/filter-ai-proposal.js +87 -0
  17. package/dist/web/filter-guidance.js +8 -0
  18. package/dist/web/index.html +72 -11
  19. package/dist/web/instructor.js +231 -33
  20. package/dist/web/left-pane.js +185 -18
  21. package/dist/web/local-discovery.js +297 -0
  22. package/dist/web/model-editor-revit-adapter.js +3 -1
  23. package/dist/web/model-editor-steel-adapter.js +3 -1
  24. package/dist/web/model-editor.css +4 -4
  25. package/dist/web/model-revit-module.js +63 -0
  26. package/dist/web/model-viewport-toolbar.js +13 -1
  27. package/dist/web/model-viewport.js +16 -1
  28. package/dist/web/overlay-escape.js +79 -0
  29. package/dist/web/revit-editor.css +7 -0
  30. package/dist/web/revit-editor.html +5 -5
  31. package/dist/web/revit-editor.js +20 -10
  32. package/dist/web/steel-detail-refs.js +0 -69
  33. package/dist/web/steel-editor.html +103 -264
  34. package/dist/web/steel-filter-core.js +298 -12
  35. package/dist/web/steel-filter-hit.js +526 -0
  36. package/dist/web/steel-filter.html +1647 -75
  37. package/dist/web/steel-split-view.js +1 -1
  38. package/dist/web/vector-3d.html +3 -0
  39. package/dist/web/vector-editor.html +9 -1
  40. package/dist/web/workspaces.js +198 -25
  41. package/package.json +5 -2
package/dist/web/aware.js CHANGED
@@ -3279,20 +3279,37 @@
3279
3279
  // and the section speaks to that editor while it is open — the same tabs, by the same code, as the
3280
3280
  // workspace's Model step (web/model-panel-bridge.js).
3281
3281
  let contractEditorApp = null; // the workflow the editor was opened for: Approve bakes that one
3282
- // The regions of #app the overlay covers. Covering them is not enough: Tab from the left panel would still reach
3283
- // the header, canvas and footer under it. Cards drawn above the overlay (#fullscreen-nudge, #ix-ask-menu) are not
3284
- // covered, so they are not listed and stay usable.
3282
+ // The regions of #app the overlay covers. Covering them is not enough: Tab from the Close button or the left panel
3283
+ // would still reach the header, canvas and footer under it, and Enter there runs or compiles the workflow. Cards
3284
+ // drawn above the overlay (#fullscreen-nudge, #ix-ask-menu) are not covered, so they are not listed and stay usable.
3285
+ // A model editor keeps the left panel and its edge above it (OVERLAY_COVERS); every other overlay — the Drawing
3286
+ // Filter, the local 3D viewer, an editor with no Model section — covers the whole window, so those go too (#1445).
3285
3287
  const OVERLAY_COVERS = '#app > header, #canvas-main, #app > .pane-rail-right, #inspect-panel, #whats-new-panel, #instructor, #app > footer';
3288
+ const FULL_WINDOW_COVERS = OVERLAY_COVERS + ', #chat-panel, #app > .pane-rail-left';
3286
3289
  let shellInertBefore = null; // each covered region, with the inert it had before
3287
- function overlayModelPanel(on) {
3288
- document.getElementById('app').classList.toggle('contract-editor-beside', on);
3289
- if (on && !shellInertBefore) {
3290
- shellInertBefore = [...document.querySelectorAll(OVERLAY_COVERS)]
3291
- .map((region) => { const before = region.inert; region.inert = true; return [region, before]; });
3292
- } else if (!on && shellInertBefore) {
3290
+ let overlayOpener = null; // what had focus before the first overlay opened, to give it back on close
3291
+ // Make the regions `covers` names unreachable, or none when it is null. Whatever was covered before is restored
3292
+ // first, so switching from one overlay to another covers exactly the new set and closing leaves nothing inert
3293
+ // that was not inert already. Closing also returns focus to the control that opened the overlay, when it is
3294
+ // still there and reachable — otherwise focus would be left on the page itself.
3295
+ function coverShell(covers) {
3296
+ const opening = covers && !shellInertBefore;
3297
+ if (shellInertBefore) {
3293
3298
  for (const [region, before] of shellInertBefore) region.inert = before;
3294
3299
  shellInertBefore = null;
3295
3300
  }
3301
+ if (opening) overlayOpener = document.activeElement !== document.body ? document.activeElement : null;
3302
+ if (covers) {
3303
+ shellInertBefore = [...document.querySelectorAll(covers)]
3304
+ .map((region) => { const before = region.inert; region.inert = true; return [region, before]; });
3305
+ } else {
3306
+ const opener = overlayOpener;
3307
+ overlayOpener = null;
3308
+ if (opener?.isConnected && !opener.closest('[inert]')) opener.focus?.({ preventScroll: true });
3309
+ }
3310
+ }
3311
+ function overlayModelPanel(on) {
3312
+ document.getElementById('app').classList.toggle('contract-editor-beside', on);
3296
3313
  window.flolessLeftPane?.useOverlayModelFrame(on ? $contractEditorFrame : null);
3297
3314
  }
3298
3315
  function openContractEditor(appId, type) {
@@ -3300,6 +3317,7 @@
3300
3317
  if (!r) return false;
3301
3318
  contractEditorApp = appId;
3302
3319
  overlayModelPanel(!!r.modelPanel);
3320
+ coverShell(r.modelPanel ? OVERLAY_COVERS : FULL_WINDOW_COVERS);
3303
3321
  // The editor bakes the .lock on Approve — that control belongs to an editable contract editor, not
3304
3322
  // the filter view (own Save) nor a view-only renderer. Show it unless the renderer is viewOnly.
3305
3323
  const ap0 = document.getElementById('contract-editor-approve'); if (ap0) ap0.hidden = !!r.viewOnly;
@@ -3324,6 +3342,7 @@
3324
3342
  const r = window.CONTRACT_RENDERERS && window.CONTRACT_RENDERERS[type];
3325
3343
  if (!r || !r.viewerUrl) return false;
3326
3344
  overlayModelPanel(false);
3345
+ coverShell(FULL_WINDOW_COVERS);
3327
3346
  const ap = document.getElementById('contract-editor-approve'); if (ap) ap.hidden = true;
3328
3347
  $contractEditorTitle.replaceChildren(
3329
3348
  Object.assign(document.createElement('span'), { textContent: appId, style: 'color:var(--text);font-weight:600' }),
@@ -3339,6 +3358,7 @@
3339
3358
  // iframe talks to /api/contract directly and Save writes contract.filter.
3340
3359
  function openFilterView(appId) {
3341
3360
  overlayModelPanel(false);
3361
+ coverShell(FULL_WINDOW_COVERS);
3342
3362
  // The filter view has its own Save; the overlay's "Approve & bake lock" (editor-only) would
3343
3363
  // be a confusing no-op here, so hide it. openContractEditor restores it.
3344
3364
  const ap = document.getElementById('contract-editor-approve'); if (ap) ap.hidden = true;
@@ -3366,10 +3386,55 @@
3366
3386
  }
3367
3387
  $contractEditor.hidden = true;
3368
3388
  overlayModelPanel(false); // the left Model section goes back to the workspace
3389
+ // Unhook the focus-on-load first: about:blank loading would otherwise pull focus into the now-hidden frame,
3390
+ // away from the shell the next line hands back.
3391
+ $contractEditorFrame.onload = null;
3392
+ coverShell(null); // and the shell under the overlay is reachable again
3369
3393
  $contractEditorFrame.src = 'about:blank'; // tear down the editor session + its draft listeners
3370
3394
  }
3371
3395
  document.getElementById('contract-editor-close').onclick = closeContractEditor;
3372
3396
 
3397
+ // Esc closes the overlay (#1571) — the Instructor has always said so (`shell.editor-close`, "Also: Esc") and
3398
+ // nothing did. Through closeContractEditor, never around it, so the Drawing Filter's unsaved question still asks.
3399
+ // `overlayEscClosing` makes a second Esc while that question is up a no-op instead of a second question.
3400
+ let overlayEscClosing = false;
3401
+ async function closeOverlayOnEscape() {
3402
+ if ($contractEditor.hidden || overlayEscClosing) return false;
3403
+ overlayEscClosing = true;
3404
+ try { await closeContractEditor(); } finally { overlayEscClosing = false; }
3405
+ return true;
3406
+ }
3407
+ // Focus in the shell: only while it sits on the overlay's own bar (Close, Approve) or on nothing at all. Focus in
3408
+ // the left panel beside a model editor is that panel's, and its Esc is its own. Bound on window, so it runs after
3409
+ // every document-level Esc handler, and a press one of them already used (preventDefault) is left alone. A keydown
3410
+ // inside the editor's iframe never arrives here; that half is web/overlay-escape.js, which calls the hook below.
3411
+ // Several shell dialogs, the menu and the find bar close on Esc WITHOUT marking it (app.js, the routines and guide
3412
+ // modals), and by the time this bubble listener runs they are already hidden. So whether one was showing is read in
3413
+ // the capture phase, before any of them acts: that Esc was theirs, and closing the overlay too would be two actions.
3414
+ const SHELL_ESC_OWNERS = '.modal-backdrop.show, #menu.show, #find-overlay.show';
3415
+ let shellEscOwned = false;
3416
+ window.addEventListener('keydown', (e) => {
3417
+ if (e.key === 'Escape') shellEscOwned = !!document.querySelector(SHELL_ESC_OWNERS);
3418
+ }, true);
3419
+ window.addEventListener('keydown', (e) => {
3420
+ if (e.key !== 'Escape' || e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.isComposing) return;
3421
+ if ($contractEditor.hidden || shellEscOwned) return;
3422
+ const ae = document.activeElement;
3423
+ if (ae !== document.body && ae !== null && (!$contractEditor.contains(ae) || ae === $contractEditorFrame)) return;
3424
+ e.preventDefault();
3425
+ closeOverlayOnEscape();
3426
+ });
3427
+ // The iframe's half: an Esc the page left unused. Only the page the overlay is SHOWING may close it — the same
3428
+ // editor embedded in a workspace step, or a stale frame still unloading, gets false and nothing happens.
3429
+ window.__floOverlayEscape = (win) => {
3430
+ if ($contractEditor.hidden || document.querySelector(SHELL_ESC_OWNERS)) return false; // a shell dialog above it goes first
3431
+ let current = null;
3432
+ try { current = $contractEditorFrame.contentWindow; } catch (_) { current = null; }
3433
+ if (!win || win !== current) return false;
3434
+ closeOverlayOnEscape();
3435
+ return true;
3436
+ };
3437
+
3373
3438
  // Export 3D ▸ — render the approved model as an interactive 3D model. Calls the server's
3374
3439
  // export-3d (transform → companion viewer-3d app → compile → run) and paints the returned
3375
3440
  // interactive report in the same viewer a normal run uses. api() throws on any failure (non-2xx
@@ -5168,7 +5233,38 @@
5168
5233
  const $graftBack = document.getElementById('graft-back');
5169
5234
  const $graftCancel = document.getElementById('graft-cancel');
5170
5235
  const $graftPrimary = document.getElementById('graft-primary');
5236
+ const $graftInstructorNote = document.getElementById('graft-instructor-note');
5171
5237
  function graftFill(el, markup) { if (!el) return; el.replaceChildren(); if (markup) el.insertAdjacentHTML('beforeend', markup); }
5238
+ window.flolessGraftInstructorExplain = (guidance) => {
5239
+ if (!$graftModal.classList.contains('show') || !Array.isArray(guidance?.parts)) return;
5240
+ const chip = document.createElement('span');
5241
+ chip.className = 'ix-chip';
5242
+ chip.textContent = guidance.chip || '';
5243
+ const parts = document.createElement('div');
5244
+ parts.className = 'graft-instructor-parts';
5245
+ guidance.parts.forEach((part, index) => {
5246
+ if (index) parts.append(document.createTextNode(' · '));
5247
+ const segment = document.createElement('span');
5248
+ segment.textContent = part;
5249
+ parts.append(segment);
5250
+ });
5251
+ $graftInstructorNote.replaceChildren(chip, parts);
5252
+ $graftInstructorNote.dataset.commandId = guidance.commandId || '';
5253
+ $graftInstructorNote.hidden = false;
5254
+ };
5255
+ window.flolessGraftInstructorClear = () => {
5256
+ $graftInstructorNote.hidden = true;
5257
+ $graftInstructorNote.replaceChildren();
5258
+ delete $graftInstructorNote.dataset.commandId;
5259
+ };
5260
+ function clearGraftInstructorNote() {
5261
+ if (!$graftInstructorNote.hidden) window.Instructor?.clear();
5262
+ window.flolessGraftInstructorClear();
5263
+ }
5264
+ function closeGraftModal() {
5265
+ clearGraftInstructorNote();
5266
+ hideModal($graftModal);
5267
+ }
5172
5268
 
5173
5269
  // Featured kinds (shown first) are the AEC-relevant ones; the rest live under "More".
5174
5270
  const GRAFT_KINDS = [
@@ -5197,24 +5293,40 @@
5197
5293
  ];
5198
5294
 
5199
5295
  let graftState = {};
5296
+ let graftGeneration = 0;
5200
5297
  const graftCfg = (kind) => GRAFT_KINDS.find((k) => k.kind === kind) || GRAFT_KINDS[0];
5201
5298
  const graftBodyEl = () => document.getElementById('graft-body');
5202
- function graftFooter({ backShown = false, primaryLabel = 'Introspect', primaryDisabled = false } = {}) {
5299
+ function graftFooter({ backShown = false, primaryLabel = 'Inspect source', primaryDisabled = false, primaryCommand = 'shell.graft-inspect-source' } = {}) {
5203
5300
  $graftBack.hidden = !backShown;
5204
5301
  $graftPrimary.textContent = primaryLabel;
5205
5302
  $graftPrimary.disabled = primaryDisabled;
5206
- }
5207
-
5208
- function openGraftModal() {
5209
- graftState = { kind: 'dlls', ref: '', decompile: false, showMore: false, preview: null, stagedRef: null, onPrimary: runGraftIntrospect, onBack: null };
5303
+ $graftPrimary.setAttribute('data-command-id', primaryCommand);
5304
+ }
5305
+
5306
+ function openGraftModal(prefill) {
5307
+ graftGeneration += 1;
5308
+ clearGraftInstructorNote();
5309
+ for (const control of [$graftPrimary, $graftBack, $graftCancel]) control.removeAttribute('data-blocked-reason');
5310
+ $graftCancel.textContent = 'Cancel';
5311
+ $graftCancel.setAttribute('data-command-id', 'shell.dialog-cancel#building an agent');
5312
+ const supported = prefill && GRAFT_KINDS.some((item) => item.kind === prefill.kind)
5313
+ && typeof prefill.ref === 'string' && prefill.ref.trim();
5314
+ graftState = { kind: supported ? prefill.kind : 'dlls', ref: supported ? prefill.ref : '', decompile: false, showMore: false, preview: null, stagedRef: null, verifyInFlight: false, commitInFlight: false, onPrimary: runGraftIntrospect, onBack: null };
5210
5315
  document.getElementById('graft-title').textContent = 'Graft into agent';
5211
- document.getElementById('graft-sub').textContent = 'Point at a DLL, package, or API spec — AWARE reads it and builds an agent you can drop into any workflow.';
5316
+ document.getElementById('graft-sub').textContent = 'Choose a DLL, package, or API spec. AWARE will inspect it and prepare command descriptions for your review.';
5212
5317
  $graftBack.disabled = false; $graftCancel.disabled = false;
5213
5318
  graftRenderPicker();
5214
5319
  showModal($graftModal);
5215
5320
  }
5321
+ document.addEventListener('floless:discovery-graft', (event) => {
5322
+ const source = event.detail;
5323
+ if (!source || typeof source !== 'object') return;
5324
+ openGraftModal(source);
5325
+ document.getElementById('graft-ref')?.focus();
5326
+ });
5216
5327
 
5217
5328
  function graftRenderPicker() {
5329
+ clearGraftInstructorNote();
5218
5330
  graftState.onPrimary = runGraftIntrospect;
5219
5331
  graftState.onBack = null;
5220
5332
  const cfg = graftCfg(graftState.kind);
@@ -5236,12 +5348,12 @@
5236
5348
  const ref = document.getElementById('graft-ref');
5237
5349
  ref.oninput = () => {
5238
5350
  graftState.ref = ref.value;
5239
- graftFooter({ primaryLabel: 'Introspect', primaryDisabled: !graftState.ref.trim() });
5351
+ graftFooter({ primaryLabel: 'Inspect source', primaryDisabled: !graftState.ref.trim() });
5240
5352
  if (graftCfg(graftState.kind).match) graftMatchDebounced();
5241
5353
  };
5242
5354
  ref.onkeydown = (e) => { if (e.key === 'Enter' && graftState.ref.trim()) runGraftIntrospect(); };
5243
5355
  const dec = document.getElementById('graft-decompile'); if (dec) dec.onchange = () => { graftState.decompile = dec.checked; };
5244
- graftFooter({ backShown: false, primaryLabel: 'Introspect', primaryDisabled: !graftState.ref.trim() });
5356
+ graftFooter({ backShown: false, primaryLabel: 'Inspect source', primaryDisabled: !graftState.ref.trim() });
5245
5357
  setTimeout(() => ref.focus(), 0);
5246
5358
  if (graftCfg(graftState.kind).match && graftState.ref.trim()) graftMatch();
5247
5359
  }
@@ -5274,7 +5386,7 @@
5274
5386
  graftFill(graftBodyEl(),
5275
5387
  `<div class="graft-progress"><span class="rtn-spinner"></span><span>${escapeHtml(graftIntrospectingLabel(graftState.kind))}</span></div>` +
5276
5388
  '<div class="graft-hint">Large packages can take 30–60 seconds (a NuGet restore is included).</div>');
5277
- graftFooter({ backShown: false, primaryLabel: 'Introspecting…', primaryDisabled: true });
5389
+ graftFooter({ backShown: false, primaryLabel: 'Inspecting…', primaryDisabled: true });
5278
5390
  try {
5279
5391
  const body = { sourceKind: graftState.kind, sourceRef: graftState.ref.trim() };
5280
5392
  if (cfg.decompile && graftState.decompile) body.decompile = true;
@@ -5308,8 +5420,9 @@
5308
5420
  }
5309
5421
 
5310
5422
  function graftRenderPreview(preview) {
5311
- document.getElementById('graft-title').textContent = 'Review your new agent';
5312
- document.getElementById('graft-sub').textContent = 'Here is what AWARE found — create it to add it to your Agents library.';
5423
+ clearGraftInstructorNote();
5424
+ document.getElementById('graft-title').textContent = 'Review generated commands';
5425
+ document.getElementById('graft-sub').textContent = 'AWARE listed commands from this source. None has been run. Create the agent only if you want it in your Agents library.';
5313
5426
  const tekla = preview.recipe === 'tekla-plugin';
5314
5427
  const badge = tekla
5315
5428
  ? '<div class="graft-badge tekla">⊕ Tekla plug-in recipe</div>'
@@ -5328,35 +5441,176 @@
5328
5441
  ? `<div class="graft-cmds">${preview.commands.map(graftCmdHtml).join('')}</div>`
5329
5442
  : '<div class="graft-warn">No commands found in this source. It may have no public API surface, or the reader couldn’t parse it — try a different entry point or path.</div>';
5330
5443
  const skills = preview.skills ? `<div class="graft-skills">${preview.skills} skill${preview.skills === 1 ? '' : 's'} generated.</div>` : '';
5444
+ const modelRead = preview.sourceKind === 'dlls'
5445
+ && /[\\/]Tekla\.Structures\.Model\.dll$/i.test(preview.sourceRef);
5446
+ const verify = modelRead
5447
+ ? `<div class="graft-read-review"><strong>Check one live Tekla read</strong>` +
5448
+ `<p id="graft-verify-help">This reads the open model name using the selected library. It does not test the generated agent or its other commands.</p>` +
5449
+ `<dl class="graft-identity"><dt>Library</dt><dd>${escapeHtml(preview.sourceRef)}</dd>` +
5450
+ `<dt>Operation</dt><dd>Model.GetInfo().ModelName</dd></dl>` +
5451
+ `<button type="button" class="graft-verify-button" id="graft-verify-read" data-command-id="shell.graft-verify-tekla-read" aria-describedby="graft-verify-help">Verify model read</button>` +
5452
+ `<div id="graft-verify-result" role="status" aria-live="polite"></div></div>` : '';
5331
5453
  graftFill(graftBodyEl(),
5332
- badge + hero + warnings + cmds + skills +
5454
+ badge + hero + verify + warnings + cmds + skills +
5333
5455
  `<div class="modal-field"><label>Agent name</label><div class="bake-name"><code>${escapeHtml(preview.agentId)}</code></div></div>`);
5456
+ const verifyButton = document.getElementById('graft-verify-read');
5457
+ verifyButton?.addEventListener('click', () => runGraftVerifyRead(preview));
5458
+ verifyButton?.focus();
5334
5459
  graftState.onBack = graftRenderPicker;
5335
5460
  graftState.onPrimary = () => runGraftCommit(false);
5336
- graftFooter({ backShown: true, primaryLabel: 'Create agent', primaryDisabled: preview.commands.length === 0 });
5461
+ graftFooter({ backShown: true, primaryLabel: 'Create agent', primaryDisabled: preview.commands.length === 0, primaryCommand: 'shell.graft-create-agent' });
5462
+ }
5463
+
5464
+ function graftTeklaReadErrorMessage(error) {
5465
+ const body = error?.body;
5466
+ if (error?.status === 402 || body?.error === 'subscription required') {
5467
+ if (body?.state === 'expired') return 'Your FloLess subscription has expired. Renew your FloLess subscription, then try again.';
5468
+ if (body?.reason === 'no-subscription') return 'This account does not have a FloLess subscription. Sign in with a subscribed account or subscribe, then try again.';
5469
+ if (body?.reason === 'session-expired') return 'Your FloLess sign-in has expired. Sign in again, then try again.';
5470
+ if (body?.reason === 'signed-out') return 'You are signed out of FloLess. Sign in again, then try again.';
5471
+ if (body?.reason === 'seat-taken') return 'Your FloLess session has ended. Sign in again, then try again.';
5472
+ return 'Sign in to FloLess to check your account access, then try again.';
5473
+ }
5474
+ if (body?.bootstrap === 'failed') {
5475
+ return 'FloLess could not prepare its runtime. Choose Try again on the setup card, then verify the model read again.';
5476
+ }
5477
+ if (body?.code === 'aware-setting-up' || body?.bootstrap) {
5478
+ return 'FloLess is still preparing its runtime. Wait for setup to finish, then try again.';
5479
+ }
5480
+ if (body?.code === 'maintenance-busy' && body?.message) return body.message;
5481
+ if (body?.code === 'response-unreadable' || error?.status >= 500) {
5482
+ return 'FloLess could not complete this read. Try again. If it keeps happening, report the issue.';
5483
+ }
5484
+ // A 200 refusal is the read endpoint's in-band domain result (host closed, model closed, and
5485
+ // similar). Other HTTP failures and transport failures do not establish a Tekla problem.
5486
+ if (error?.status === 200 && body?.message) return body.message;
5487
+ if (typeof error?.status !== 'number') return 'FloLess could not be reached. Check that FloLess is still open, then try again.';
5488
+ return 'FloLess could not complete this read. Try again. If it keeps happening, report the issue.';
5489
+ }
5490
+
5491
+ async function runGraftVerifyRead(preview) {
5492
+ const button = document.getElementById('graft-verify-read');
5493
+ const result = document.getElementById('graft-verify-result');
5494
+ if (!button || !result || button.disabled || graftState.verifyInFlight || graftState.commitInFlight) return;
5495
+ const state = graftState;
5496
+ state.verifyInFlight = true;
5497
+ const generation = graftGeneration;
5498
+ let focusMoved = false;
5499
+ const trackFocus = (event) => { if (event.target !== button) focusMoved = true; };
5500
+ button.disabled = true;
5501
+ document.addEventListener('focusin', trackFocus, true);
5502
+ button.setAttribute('aria-busy', 'true');
5503
+ button.setAttribute('data-blocked-reason', 'A Tekla model read is in progress. Wait for the result.');
5504
+ result.textContent = 'Reading the open Tekla model name…';
5505
+ $graftPrimary.disabled = true;
5506
+ $graftPrimary.setAttribute('data-blocked-reason', 'A Tekla model read is in progress. Wait for the result.');
5507
+ $graftBack.disabled = true;
5508
+ $graftBack.setAttribute('data-blocked-reason', 'A Tekla model read is in progress. Wait for the result.');
5509
+ $graftCancel.textContent = 'Stop waiting';
5510
+ $graftCancel.setAttribute('data-command-id', 'shell.graft-stop-waiting');
5511
+ try {
5512
+ const data = await api('/api/graft/verify-tekla-read', { method: 'POST', body: JSON.stringify({ sourcePath: preview.sourceRef }) });
5513
+ if (generation !== graftGeneration || graftState.preview !== preview || !$graftModal.classList.contains('show') || !result.isConnected || state.commitInFlight) return;
5514
+ const proof = data.verification;
5515
+ graftFill(result, `<div class="graft-read-verified"><strong>Verified model read</strong>` +
5516
+ `<dl class="graft-identity"><dt>Operation</dt><dd>${escapeHtml(proof.operation)}</dd>` +
5517
+ `<dt>Result</dt><dd>${escapeHtml(proof.modelName)}</dd>` +
5518
+ `<dt>Tekla host</dt><dd>${escapeHtml(proof.hostVersion)} · PID ${escapeHtml(String(proof.hostPid))}</dd>` +
5519
+ `<dt>Library used</dt><dd>${escapeHtml(proof.sourcePath)}</dd>` +
5520
+ `<dt>Checked</dt><dd>${escapeHtml(proof.verifiedAt)}</dd></dl>` +
5521
+ `<p>The generated agent's commands remain unverified.</p>` +
5522
+ `<button type="button" class="graft-verify-button graft-continue-chat" id="graft-continue-chat" data-command-id="shell.graft-continue-chat">Continue in AI Chat</button></div>`);
5523
+ // Only the successful receipt carries this action. It hands the receipt to Chat as an
5524
+ // editable, unsent draft; opening Chat never re-runs the Tekla read.
5525
+ document.getElementById('graft-continue-chat')?.addEventListener('click', () => { void continueGraftReadInChat(proof); });
5526
+ } catch (error) {
5527
+ if (generation !== graftGeneration || graftState.preview !== preview || !$graftModal.classList.contains('show') || !result.isConnected || state.commitInFlight) return;
5528
+ const message = graftTeklaReadErrorMessage(error);
5529
+ graftFill(result, `<div class="graft-warn"><strong>Could not verify this read.</strong> ${escapeHtml(message)}</div>`);
5530
+ } finally {
5531
+ document.removeEventListener('focusin', trackFocus, true);
5532
+ state.verifyInFlight = false;
5533
+ if (generation === graftGeneration && graftState.preview === preview && $graftModal.classList.contains('show') && result.isConnected && !state.commitInFlight) {
5534
+ button.disabled = false;
5535
+ button.removeAttribute('aria-busy');
5536
+ button.removeAttribute('data-blocked-reason');
5537
+ if (!focusMoved && (document.activeElement === button || document.activeElement === document.body)) button.focus();
5538
+ $graftPrimary.disabled = preview.commands.length === 0;
5539
+ $graftPrimary.removeAttribute('data-blocked-reason');
5540
+ $graftBack.disabled = false;
5541
+ $graftBack.removeAttribute('data-blocked-reason');
5542
+ $graftCancel.textContent = 'Cancel';
5543
+ $graftCancel.setAttribute('data-command-id', 'shell.dialog-cancel#building an agent');
5544
+ if ($graftInstructorNote.dataset.commandId) {
5545
+ const focused = document.activeElement;
5546
+ if (![button, $graftCancel, $graftPrimary, $graftBack].includes(focused) || !window.Instructor?.refreshCarrier(focused)) clearGraftInstructorNote();
5547
+ }
5548
+ }
5549
+ }
5550
+ }
5551
+
5552
+ async function continueGraftReadInChat(proof) {
5553
+ const receipt = {
5554
+ sourcePath: proof.sourcePath, hostVersion: proof.hostVersion, modelName: proof.modelName,
5555
+ hostPid: proof.hostPid, verifiedAt: proof.verifiedAt, operation: proof.operation,
5556
+ };
5557
+ if (graftState.verifyInFlight || graftState.commitInFlight) return;
5558
+ if (typeof window.flolessChat?.openVerifiedTeklaDraft !== 'function') {
5559
+ showToast('AI Chat is not available right now. Reload FloLess, then verify the model read again.', 'warn');
5560
+ return;
5561
+ }
5562
+ // Close Graft only once Chat holds the draft: a failure keeps the receipt on screen to retry.
5563
+ try {
5564
+ await window.flolessChat.openVerifiedTeklaDraft(receipt);
5565
+ } catch (e) {
5566
+ console.warn('Continue in AI Chat failed', e);
5567
+ showToast(e?.plainEnglish && e.message
5568
+ ? e.message
5569
+ : 'FloLess could not open AI Chat. Open a project or workflow, then verify the model read again.', 'warn');
5570
+ return;
5571
+ }
5572
+ closeGraftModal();
5337
5573
  }
5338
5574
 
5339
5575
  async function runGraftCommit(force) {
5340
- if (!graftState.stagedRef) return;
5341
- graftFooter({ backShown: true, primaryLabel: 'Creating…', primaryDisabled: true });
5576
+ if (!graftState.stagedRef || graftState.verifyInFlight || graftState.commitInFlight) return;
5577
+ const state = graftState;
5578
+ state.commitInFlight = true;
5579
+ graftGeneration += 1;
5580
+ clearGraftInstructorNote();
5581
+ graftFooter({ backShown: true, primaryLabel: 'Creating…', primaryDisabled: true,
5582
+ primaryCommand: force ? 'shell.graft-overwrite-agent' : 'shell.graft-create-agent' });
5342
5583
  $graftBack.disabled = true; $graftCancel.disabled = true;
5584
+ for (const control of [$graftPrimary, $graftBack, $graftCancel]) {
5585
+ control.setAttribute('data-blocked-reason', 'Agent creation is in progress. Wait for it to finish.');
5586
+ }
5587
+ const verifyButton = document.getElementById('graft-verify-read');
5588
+ if (verifyButton) {
5589
+ verifyButton.disabled = true;
5590
+ verifyButton.setAttribute('data-blocked-reason', 'Agent creation is in progress. Wait for it to finish.');
5591
+ }
5592
+ const continueButton = document.getElementById('graft-continue-chat');
5593
+ if (continueButton) {
5594
+ continueButton.disabled = true;
5595
+ continueButton.setAttribute('data-blocked-reason', 'Agent creation is in progress. Wait for it to finish.');
5596
+ }
5343
5597
  try {
5344
5598
  const body = { stagedRef: graftState.stagedRef };
5345
5599
  if (force) body.force = true;
5346
5600
  const res = await api('/api/graft/commit', { method: 'POST', body: JSON.stringify(body) });
5347
5601
  graftFill(graftBodyEl(), `<div class="graft-success"><div class="gs-icon">⊕</div><div class="gs-msg">Agent created — now in the Agents library as <code>${escapeHtml(res.agentId)}</code>.</div></div>`);
5348
5602
  $graftBack.hidden = true; $graftCancel.disabled = false; $graftPrimary.textContent = 'Done'; $graftPrimary.disabled = false;
5349
- graftState.onPrimary = () => hideModal($graftModal);
5603
+ $graftPrimary.setAttribute('data-command-id', 'shell.graft-done');
5604
+ graftState.onPrimary = closeGraftModal;
5350
5605
  loadAgentCatalog().catch(() => {}); // refresh count immediately (SSE also fires for other tabs)
5351
5606
  appendNarration(`Grafted <strong>${escapeHtml(res.agentId)}</strong> from ${escapeHtml(graftState.preview.sourceRef)} — find it in the Agents library (<strong>⊞ Agents</strong>).`);
5352
5607
  showToast(`Agent created — “${res.agentId}” is now in the Agents library`, 'ok');
5353
- setTimeout(() => { if ($graftModal.classList.contains('show')) hideModal($graftModal); }, 1500);
5354
5608
  } catch (e) {
5355
5609
  $graftBack.disabled = false; $graftCancel.disabled = false;
5356
5610
  const msg = (e && e.message) ? e.message : 'Create failed';
5357
5611
  if (/already (installed|exists)/i.test(msg) && !force) {
5358
5612
  // The stage is kept server-side on a collision — offer to overwrite.
5359
- graftFooter({ backShown: true, primaryLabel: 'Overwrite existing', primaryDisabled: false });
5613
+ graftFooter({ backShown: true, primaryLabel: 'Overwrite existing', primaryDisabled: false, primaryCommand: 'shell.graft-overwrite-agent' });
5360
5614
  graftState.onPrimary = () => runGraftCommit(true);
5361
5615
  if (!graftBodyEl().querySelector('.graft-warn.collide')) {
5362
5616
  const warn = document.createElement('div');
@@ -5365,17 +5619,28 @@
5365
5619
  graftBodyEl().prepend(warn);
5366
5620
  }
5367
5621
  } else {
5368
- graftFooter({ backShown: true, primaryLabel: 'Create agent', primaryDisabled: false });
5622
+ graftFooter({ backShown: true, primaryLabel: 'Create agent', primaryDisabled: false, primaryCommand: 'shell.graft-create-agent' });
5369
5623
  graftState.onPrimary = () => runGraftCommit(false);
5370
5624
  showToast('We couldn’t create this agent because FloLess could not finish the setup. Try again.', 'warn');
5371
5625
  }
5626
+ } finally {
5627
+ state.commitInFlight = false;
5628
+ for (const control of [$graftPrimary, $graftBack, $graftCancel]) control.removeAttribute('data-blocked-reason');
5629
+ if (continueButton?.isConnected) {
5630
+ continueButton.disabled = false;
5631
+ continueButton.removeAttribute('data-blocked-reason');
5632
+ }
5633
+ if (verifyButton?.isConnected) {
5634
+ verifyButton.disabled = false;
5635
+ verifyButton.removeAttribute('data-blocked-reason');
5636
+ }
5372
5637
  }
5373
5638
  }
5374
5639
 
5375
- $graftBack.onclick = () => { if (graftState.onBack) graftState.onBack(); };
5376
- $graftCancel.onclick = () => hideModal($graftModal);
5640
+ $graftBack.onclick = () => { graftGeneration += 1; clearGraftInstructorNote(); if (graftState.onBack) graftState.onBack(); };
5641
+ $graftCancel.onclick = () => { graftGeneration += 1; closeGraftModal(); };
5377
5642
  $graftPrimary.onclick = () => { if (graftState.onPrimary) graftState.onPrimary(); };
5378
- onBackdropDismiss($graftModal, () => hideModal($graftModal), () => !$graftCancel.disabled);
5643
+ onBackdropDismiss($graftModal, closeGraftModal, () => !$graftCancel.disabled);
5379
5644
 
5380
5645
  // Secondary entry: "⊕ Graft new agent" inside the Agents Library modal.
5381
5646
  const $libGraft = document.getElementById('lib-graft');
@@ -7873,6 +8138,10 @@
7873
8138
  let everOpened = false;
7874
8139
  es.onopen = () => {
7875
8140
  setServerStatus(true);
8141
+ // Core provisioning may have finished after the page read /api/apps but before this
8142
+ // at-most-once stream connected. Re-read the catalogue on every open, including the
8143
+ // first one; Workspaces defers its repaint while a dialog is active.
8144
+ window.dispatchEvent(new CustomEvent('floless:apps-changed', { detail: {} }));
7876
8145
  // A RECONNECT MEANS WE MISSED WHATEVER HAPPENED WHILE WE WERE GONE — and this catches up the
7877
8146
  // PROJECT half of that, not every arm below (workflow imports, contract writes and the rest
7878
8147
  // still heal on their next event or a reload). These events are
@@ -8437,7 +8706,9 @@
8437
8706
  //
8438
8707
  // Detection is a workspace-level fact (which CLIs exist) fetched per surface-open and cached; the
8439
8708
  // FOLDER is per project, so anything that needs it re-reads with the project key rather than
8440
- // trusting this. Server-side detection spawns nothing — it is statSync work — so an open is cheap.
8709
+ // trusting this. Server-side detection is statSync work, and the account each runtime answers
8710
+ // from is cached 10 s server-side (one CLI status call per provider per window at most), so an
8711
+ // open is still cheap.
8441
8712
  let headlessInfo = null;
8442
8713
  let headlessFetchEpoch = 0;
8443
8714
  async function refreshHeadless() {
@@ -8502,6 +8773,52 @@
8502
8773
  // response must not turn an arbitrary terminal state into an implied "resume" instruction.
8503
8774
  const RESUMABLE_RUN_STATES = new Set(['needs-you', 'stopped', 'interrupted', 'contract-violation', 'exited-unresolved']);
8504
8775
 
8776
+ /**
8777
+ * A Drawing Filter answer's proposal when it passes the same strict shape AI Chat uses; null when it
8778
+ * cannot be shown. Requests has no current filter or allowed-control snapshot, so it cannot claim a
8779
+ * proposal still applies: it only mirrors the structural boundary and shows it for reference.
8780
+ */
8781
+ function filterGuideProposal(answer) {
8782
+ if (typeof answer !== 'string' || answer.length > 8_000) return null;
8783
+ let suggestion;
8784
+ try { suggestion = JSON.parse(answer); } catch { return null; }
8785
+ if (!suggestion || typeof suggestion !== 'object' || Array.isArray(suggestion)
8786
+ || Object.keys(suggestion).sort().join(',') !== 'changes,explanation,mode'
8787
+ || typeof suggestion.explanation !== 'string' || !suggestion.explanation.trim() || suggestion.explanation.length > 500
8788
+ || !Array.isArray(suggestion.changes) || suggestion.changes.length > 30
8789
+ || (suggestion.mode !== null && (typeof suggestion.mode !== 'string' || !suggestion.mode
8790
+ || suggestion.mode !== ['thickness', 'layer', 'color'].filter(dim => suggestion.mode.split('+').includes(dim)).join('+')))) return null;
8791
+ const seen = new Set();
8792
+ for (const item of suggestion.changes) {
8793
+ if (!item || typeof item !== 'object' || Array.isArray(item)
8794
+ || Object.keys(item).sort().join(',') !== 'dimension,on,value'
8795
+ || !['layer', 'thickness', 'color'].includes(item.dimension) || typeof item.on !== 'boolean'
8796
+ || (item.dimension === 'thickness' ? typeof item.value !== 'number' || !Number.isFinite(item.value)
8797
+ : typeof item.value !== 'string')) return null;
8798
+ // Match the filter core's facetKey identity: case-sensitive layers, two-decimal line
8799
+ // weights, and case-insensitive colours. A generic lowercase key mislabels both cases.
8800
+ const canonical = item.dimension === 'thickness' ? Number(item.value.toFixed(2))
8801
+ : item.dimension === 'color' ? item.value.toLowerCase() : item.value;
8802
+ const identity = `${item.dimension}\0${String(canonical)}`;
8803
+ if (seen.has(identity)) return null;
8804
+ seen.add(identity);
8805
+ }
8806
+ return suggestion;
8807
+ }
8808
+
8809
+ // Question and change share one path, so only a proposal with ticks or a match mode is a suggestion.
8810
+ function filterGuideSuggestionHtml(answer) {
8811
+ const suggestion = filterGuideProposal(answer);
8812
+ if (!suggestion) return `<div class="req-run-answer">AI's answer could not be shown. Nothing was applied or saved. Open the Drawing Filter and ask again in AI Chat.</div>`;
8813
+ const rows = suggestion.changes.map((item) => {
8814
+ const value = item.dimension === 'thickness' ? `line weight ${item.value} pt` : `${item.dimension} ${item.value}`;
8815
+ return `<li>${escapeHtml(`${item.on ? 'Include' : 'Exclude'} ${value}`)}</li>`;
8816
+ });
8817
+ if (suggestion.mode) rows.push(`<li>${escapeHtml(`Match on ${suggestion.mode.replaceAll('+', ', ')}`)}</li>`);
8818
+ if (!rows.length) return `<div class="req-run-answer"><p>${escapeHtml(suggestion.explanation)}</p></div>`;
8819
+ return `<div class="req-run-answer"><p>${escapeHtml(suggestion.explanation)}</p><ul>${rows.join('')}</ul><p>For reference only. To apply a suggestion, open the Drawing Filter and ask again in AI Chat; nothing was saved.</p></div>`;
8820
+ }
8821
+
8505
8822
  async function copyResumeCommand(command, stillOwned = () => true) {
8506
8823
  if (!command) return 'empty';
8507
8824
  if (!stillOwned()) return 'stale';
@@ -8510,14 +8827,14 @@
8510
8827
  return copied ? 'ok' : 'denied';
8511
8828
  }
8512
8829
 
8513
- function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId, commandInstance, ownRecoverySurface) {
8830
+ function runStatusHtml(run, stampedResumeCommand, desktopHandoffs, requestId, commandInstance, ownRecoverySurface, filterGuide = null) {
8514
8831
  if (!run || !run.state) return '';
8515
8832
  const v = RUN_VIEW[run.state] || { badge: String(run.state), cls: 'muted', note: () => '' };
8516
8833
  const rt = runtimeLabel(run.runtime);
8517
8834
  // `resumeCommand` belongs to the SERVER'S request view, not persisted `run` metadata: the
8518
8835
  // store deliberately carries only runtime/session identity, while terminal-runtime.ts owns argv.
8519
- const resumeCommand = RESUMABLE_RUN_STATES.has(run.state) ? stampedResumeCommand : null;
8520
- const handoffs = desktopHandoffs && RESUMABLE_RUN_STATES.has(run.state) ? desktopHandoffs : null;
8836
+ const resumeCommand = !filterGuide && RESUMABLE_RUN_STATES.has(run.state) ? stampedResumeCommand : null;
8837
+ const handoffs = !filterGuide && desktopHandoffs && RESUMABLE_RUN_STATES.has(run.state) ? desktopHandoffs : null;
8521
8838
  const claim = handoffs && handoffs.claim;
8522
8839
  const providers = handoffs && handoffs.preferredProvider === 'claude' ? ['claude', 'codex'] : ['codex', 'claude'];
8523
8840
  const availableProviders = handoffs ? providers.filter((provider) => handoffs[provider].available) : [];
@@ -8556,7 +8873,18 @@
8556
8873
  // read is waiting on Save in Drawing Filter, not on an answer to a stopped session. So those rows
8557
8874
  // keep the note master gives them. The refusal below keeps its own separate test: having a next
8558
8875
  // action is why the generic "can't be continued" is withheld there, not a reason to state it.
8559
- const note = v.note(rt, !noRecovery || !!ownRecoverySurface);
8876
+ // An unreadable answer claims nothing is available: its body below already says it could not be shown.
8877
+ const proposal = filterGuide === 'change' && run.state === 'answered' ? filterGuideProposal(run.answer) : null;
8878
+ // A waiting Drawing Filter row already says its answer is being prepared and where it will appear
8879
+ // (filterGuideRequestNote); the generic running note beside it would say the same thing twice.
8880
+ const filterWaiting = filterGuide && ['queued', 'running', 'starting'].includes(run.state);
8881
+ const note = filterGuide && run.state === 'answered'
8882
+ ? (filterGuide !== 'change' ? 'AI answer available here for reference. No selection was changed by this question.'
8883
+ : !proposal ? ''
8884
+ : proposal.changes.length || proposal.mode ? 'AI suggestion available here for reference. Nothing was applied or saved.'
8885
+ : 'AI answer available here for reference. Nothing was applied or saved.')
8886
+ : filterWaiting ? ''
8887
+ : v.note(rt, !noRecovery || !!ownRecoverySurface);
8560
8888
  // The refusal answers "why is there no button", so it is owed whenever the recovery is missing —
8561
8889
  // never conditioned on the folder, which is the one part of this row that may legitimately be
8562
8890
  // absent. A run with neither would otherwise show the same dead end with even less to read.
@@ -8578,7 +8906,8 @@
8578
8906
  <span class="req-run-badge req-run-badge-${v.cls}">${escapeHtml(v.badge)}</span>
8579
8907
  </div>
8580
8908
  ${note ? `<p class="req-run-note">${escapeHtml(note)}</p>` : ''}
8581
- ${run.state === 'answered' && typeof run.answer === 'string' ? `<div class="req-run-answer">${escapeHtml(run.answer)}</div>` : ''}
8909
+ ${run.state === 'answered' && typeof run.answer === 'string' && filterGuide === 'change' ? filterGuideSuggestionHtml(run.answer) : ''}
8910
+ ${run.state === 'answered' && typeof run.answer === 'string' && filterGuide !== 'change' ? `<div class="req-run-answer">${escapeHtml(run.answer)}</div>` : ''}
8582
8911
  ${run.question ? `<p class="req-run-question">${escapeHtml(run.question)}</p>` : ''}
8583
8912
  ${desktop}
8584
8913
  ${terminalFallback}
@@ -8759,6 +9088,9 @@
8759
9088
  showModal($m);
8760
9089
  const shell = $m.querySelector('.modal.request-help');
8761
9090
  if (shell) { try { shell.focus(); } catch { /* not focusable */ } }
9091
+ // Only a read that begins after this point may move the handoff (see loadRequests), and the
9092
+ // caller's own refreshes began before it — so ask for one, or the handoff could keep a stale Start.
9093
+ void loadRequests();
8762
9094
  // Detection is a fetch, and this modal is opened synchronously by the caller. Reveal the split
8763
9095
  // when the answer lands rather than blocking the modal on it — and only if THIS request is
8764
9096
  // still the one on screen, since a second queue can land while the first fetch is in flight.
@@ -8806,7 +9138,7 @@
8806
9138
  : canStartUpdatedRead
8807
9139
  ? '<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>'
8808
9140
  + '<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>'
8809
- + '<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>'
9141
+ + '<div class="request-help-step"><span>3</span><p>When it stops, open Drawing Filter. Check steel, member marks, grids, dimensions, and relevant callouts; ask in AI Chat on the left if you are unsure. Then press Save filter in the top-right corner. After Save, return to the same terminal AI and tell it to continue the drawing read.</p></div>'
8810
9142
  : isRevisionRead && !isPendingRevisionRead
8811
9143
  ? req.status === 'staged'
8812
9144
  ? '<div class="request-help-step"><span>1</span><p>This drawing read is complete. Open Requests and choose Review changes.</p></div>'
@@ -8818,7 +9150,7 @@
8818
9150
  : isRevisionRead
8819
9151
  ? '<div class="request-help-step"><span>1</span><p>Open Claude Code, Codex, or OpenCode in your project folder.</p></div>'
8820
9152
  + `<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>`
8821
- + '<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>'
9153
+ + '<div class="request-help-step"><span>3</span><p>When it stops, open Drawing Filter. Check steel, member marks, grids, dimensions, and relevant callouts; ask in AI Chat on the left if you are unsure. Then press Save filter in the top-right corner. After Save, return to the same terminal AI and tell it to continue the drawing read.</p></div>'
8822
9154
  : '<div class="request-help-step"><span>1</span><p>Open Claude Code, Codex, or OpenCode in your project folder.</p></div>'
8823
9155
  + '<div class="request-help-step"><span>2</span><p>Paste the copied request and let your terminal AI apply it.</p></div>'
8824
9156
  + '<div class="request-help-step"><span>3</span><p>Return here to check the result in FloLess.</p></div>';
@@ -8989,13 +9321,27 @@
8989
9321
  // has not been delivered — cleared only once it has actually flashed on a visible list, or once the
8990
9322
  // request it names is gone.
8991
9323
  let pendingRevealId = null;
8992
- let requestFetchEpoch = 0;
9324
+ // One read in flight and at most one queued behind it. Every call made during a read joins the
9325
+ // queued one, which starts only after that read is applied, so it sees whatever changed since and
9326
+ // responses land in order. Keeping only the newest response instead starved the open list and the
9327
+ // header count whenever calls (SSE, ~25 call sites) arrived faster than a read returned.
9328
+ let requestLoadInFlight = null;
9329
+ let requestLoadQueued = null;
8993
9330
  let publishedAnswerChatIds = null;
8994
9331
  async function loadRequests() {
9332
+ if (requestLoadInFlight) {
9333
+ requestLoadQueued ||= requestLoadInFlight.then(() => { requestLoadQueued = null; return loadRequests(); });
9334
+ return requestLoadQueued;
9335
+ }
9336
+ let settled;
9337
+ requestLoadInFlight = new Promise((resolve) => { settled = resolve; });
9338
+ // Every response is applied now, including one that began before the upload handoff opened. Such a
9339
+ // read predates the request, so its absence proves nothing about it — only a later read may move it.
9340
+ const helpEpochAtStart = requestHelpEpoch;
8995
9341
  try {
8996
- const epoch = ++requestFetchEpoch;
8997
- const { requests, chatPublications = [] } = await api('/api/requests');
8998
- if (epoch !== requestFetchEpoch) return;
9342
+ // Bounded: every later read waits behind this one, so a response that never arrives must not
9343
+ // freeze the list for good. The route's own lock waits give up after 60 s.
9344
+ const { requests, chatPublications = [] } = await api('/api/requests', { signal: AbortSignal.timeout(90_000) });
8999
9345
  reconcileActiveInstructorRuns(requests, chatPublications);
9000
9346
  pendingRequests = requests;
9001
9347
  const nextPublishedChatIds = new Set(chatPublications.map((publication) => publication?.chatId).filter(Boolean));
@@ -9013,7 +9359,7 @@
9013
9359
  // staged, failed, or disappears. Move to the live row, which already renders every lifecycle state.
9014
9360
  const help = requestHelpReq;
9015
9361
  const helpModal = document.getElementById('request-help-modal');
9016
- if (help && helpModal && helpModal.classList.contains('show')) {
9362
+ if (help && helpModal && helpModal.classList.contains('show') && requestHelpEpoch === helpEpochAtStart) {
9017
9363
  const fresh = requests.find((request) => request && request.id === help.id) || null;
9018
9364
  if (!fresh || requestHelpStateKey(fresh) !== requestHelpStateKey(help)) {
9019
9365
  const returnFocus = requestHelpReturnFocus;
@@ -9055,7 +9401,10 @@
9055
9401
  previousRequestIds = ids;
9056
9402
  const $rm = document.getElementById('requests-modal');
9057
9403
  if ($rm && $rm.classList.contains('show')) renderRequests(); // keep an open list live
9058
- } catch { /* non-fatal */ }
9404
+ } catch { /* non-fatal */ } finally {
9405
+ requestLoadInFlight = null;
9406
+ settled();
9407
+ }
9059
9408
  }
9060
9409
 
9061
9410
  // What the Requests window is scoped to right now: the open Workspaces project, else the open
@@ -9147,6 +9496,9 @@
9147
9496
  }
9148
9497
 
9149
9498
  function requestLabel(r) {
9499
+ if (isFilterAiGuideRequest(r))
9500
+ // One path for a question and a change, so a waiting message is never labelled a suggestion.
9501
+ return r.instructorContext.commandId === 'filter.ask-ai-change' ? 'filter answer' : 'filter question';
9150
9502
  if (r.type === 'revision-read') return (!r.baseVersion || r.baseVersion <= 0) ? 'initial drawing read' : 'updated drawing read';
9151
9503
  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';
9152
9504
  }
@@ -9172,10 +9524,17 @@
9172
9524
  && (r.status !== 'pending' || revisionReadHasTerminalOwner(r) || requestHasActiveRun(r));
9173
9525
  }
9174
9526
 
9175
- // Once the terminal AI has prepared the Drawing Filter, copying or automatically starting the
9176
- // original request would launch a second reader against the same project. The existing terminal
9177
- // session owns the continuation; Requests must point the user back to that checkpoint instead.
9527
+ // Filter AI requests are reference-only in Requests. A copied instruction cannot restore a
9528
+ // proposal's current-sheet and current-selection checks in the Drawing Filter.
9529
+ function isFilterAiGuideRequest(r) {
9530
+ return r?.type === 'guide' && r.instructorContext?.surface === 'steel-filter'
9531
+ && ['filter.ask-ai-question', 'filter.ask-ai-change'].includes(r.instructorContext.commandId);
9532
+ }
9533
+
9178
9534
  function requestCanCopy(r) {
9535
+ // The Drawing Filter's read-only AI protocol (sent from AI Chat) must never turn into a terminal copy/retry path,
9536
+ // even when an older Requests response still carries canCopy: true.
9537
+ if (isFilterAiGuideRequest(r)) return false;
9179
9538
  // Current servers own this lifecycle decision together with automatic Retry and the manifest
9180
9539
  // route. The fallback is only for an older server response already cached in this tab.
9181
9540
  if (typeof r?.canCopy === 'boolean') return r.canCopy;
@@ -9295,6 +9654,15 @@
9295
9654
  }
9296
9655
 
9297
9656
  /** The sentence a steel detailer needs first; the exact API handoff stays available below it. */
9657
+ function savedDrawingFilterNextStep(r) {
9658
+ const continuation = r?.filterSaveContinuation;
9659
+ if (continuation?.state === 'queued') return 'FloLess will continue the drawing read in the linked AI Chat when that conversation is ready.';
9660
+ if (continuation?.state === 'continuing') return 'FloLess sent the saved filter to the linked AI Chat. Follow that conversation for the drawing read.';
9661
+ if (continuation?.state === 'completed') return 'The linked AI Chat finished its response. Review its result in that conversation.';
9662
+ if (continuation?.nextAction) return continuation.nextAction;
9663
+ return 'Return to the same terminal AI session that prepared it and tell it to continue the drawing read.';
9664
+ }
9665
+
9298
9666
  function requestSummary(r) {
9299
9667
  if (!r || r.type !== 'revision-read') return '';
9300
9668
  if (r.preparationState === 'blocked') {
@@ -9303,10 +9671,13 @@
9303
9671
  if (r.preparationState === 'manifest-published' && !r.prepassReady) {
9304
9672
  return 'Drawing preparation is complete and the prepared data is saved. Return to the same terminal AI session and tell it to continue creating the Drawing Filter. Do not start or copy this request again.';
9305
9673
  }
9674
+ if (r.status === 'pending' && r.filterSaveContinuation?.state === 'recovery-needed') {
9675
+ return `Drawing Filter needs attention. ${savedDrawingFilterNextStep(r)}`;
9676
+ }
9306
9677
  if (r.status === 'pending' && r.prepassReady) {
9307
9678
  return r.filterCheckpointCurrent
9308
- ? 'Drawing Filter saved. Return to the same terminal AI session that prepared it and tell it to continue the drawing read.'
9309
- : 'Drawing Filter ready. Review the selected lines, then press Save filter in the top-right corner.';
9679
+ ? `Drawing Filter saved. ${savedDrawingFilterNextStep(r)}`
9680
+ : 'Drawing Filter ready. Check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner.';
9310
9681
  }
9311
9682
  if (r.preparationRetryable) {
9312
9683
  const active = r.run && (r.run.state === 'queued' || r.run.state === 'running');
@@ -9340,7 +9711,7 @@
9340
9711
  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.';
9341
9712
  }
9342
9713
  if (r.filterCheckpointCurrent) {
9343
- return 'Drawing Filter saved. Return to the same terminal AI session that prepared it and tell it to continue the drawing read.';
9714
+ return `Drawing Filter saved. ${savedDrawingFilterNextStep(r)}`;
9344
9715
  }
9345
9716
  return (!r.baseVersion || r.baseVersion <= 0)
9346
9717
  ? 'Read the attached drawing and create the first steel model for this project.'
@@ -9471,11 +9842,16 @@
9471
9842
  if (r.preparationState === 'manifest-published' && !r.prepassReady) {
9472
9843
  return 'Drawing preparation is complete and saved. Return to the same terminal AI session and tell it to continue creating the Drawing Filter. Do not start or copy this request again.';
9473
9844
  }
9845
+ if (r.filterSaveContinuation?.state === 'recovery-needed') {
9846
+ return `Next step: ${savedDrawingFilterNextStep(r)} Do not start the request again.`;
9847
+ }
9474
9848
  if (r.filterCheckpointCurrent) {
9475
- 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.';
9849
+ return `Next step: ${savedDrawingFilterNextStep(r)} Do not start the request again.`;
9476
9850
  }
9477
9851
  if (r.prepassReady) {
9478
- 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.';
9852
+ return r.chatConversation?.executionOwner === 'chat'
9853
+ ? 'Next step: return to Drawing Filter, check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner. FloLess will continue the drawing read in this linked AI Chat. Do not start it again.'
9854
+ : 'Next step: return to Drawing Filter, check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner. After Save, return to the terminal AI that prepared it and tell it to continue. Do not start the drawing read again.';
9479
9855
  }
9480
9856
  if (r.preparationRetryable) {
9481
9857
  const active = r.run && (r.run.state === 'queued' || r.run.state === 'running');
@@ -9488,7 +9864,7 @@
9488
9864
  const start = r.canRun && headlessReady()
9489
9865
  ? 'copy this request into Claude Code, Codex, or OpenCode, or press Start'
9490
9866
  : 'copy this request into Claude Code, Codex, or OpenCode';
9491
- return `Next step: ${start}. When the Drawing Filter is ready, review the selected lines and press Save filter in the top-right corner.`;
9867
+ return `Next step: ${start}. When the Drawing Filter is ready, check steel, member marks, grids, dimensions, and relevant callouts, then press Save filter in the top-right corner.`;
9492
9868
  }
9493
9869
 
9494
9870
  /** Prefer an active checkpoint, then an initial read, while skipping terminal rows in either group. */
@@ -9573,6 +9949,21 @@
9573
9949
  return { atomic: !filterActive && !keep.length && painted.length === all.length, keep, drop };
9574
9950
  }
9575
9951
 
9952
+ function filterGuideRequestNote(request) {
9953
+ if (request.filterAiAdmissionUnconfirmed) {
9954
+ return 'FloLess could not confirm whether AI started. A late answer may appear here or in AI Chat. If none appears, clear this request and ask again in AI Chat while the Drawing Filter is open.';
9955
+ }
9956
+ // Every Drawing Filter message takes one path, question or change alike, so the row never calls it
9957
+ // a suggestion: a plain question gets an answer with no card.
9958
+ if (request.status === 'pending' && request.run && ['queued', 'running', 'starting'].includes(request.run.state)) {
9959
+ return 'This answer is being prepared. It will appear in AI Chat.';
9960
+ }
9961
+ if (request.status === 'pending' && !request.run) {
9962
+ return 'FloLess is checking whether AI started. If an answer arrives, it will appear in AI Chat.';
9963
+ }
9964
+ return 'For reference only. It cannot be applied here; ask again in AI Chat while the Drawing Filter is open.';
9965
+ }
9966
+
9576
9967
  // The Requests window: every queued change in a list, with only the actions the server says are
9577
9968
  // currently safe, plus bulk actions over the available rows. The server-composed prompt (which embeds file-derived
9578
9969
  // appId/nodeId/instruction) is rendered via textContent-equivalent escaping — which matters MORE
@@ -9736,13 +10127,14 @@
9736
10127
  // `canRun` is server-owned policy, but persisted request JSON can outlive or be newer than this
9737
10128
  // client. A revision lifecycle this build cannot name must never gain Start through a stale or
9738
10129
  // malformed response; only the exact queued state is safe to launch.
10130
+ const filterGuide = isFilterAiGuideRequest(r);
9739
10131
  const chatExecutionOwner = r.chatConversation?.executionOwner || null;
9740
10132
  const canRunNow = headlessReady() && r.canRun && (!chatExecutionOwner || chatExecutionOwner === 'discussion')
9741
10133
  && (r.type !== 'revision-read' || r.status === 'pending')
9742
10134
  && !revisionReadHasTerminalOwner(r) && !inFlight && !desktopHandoffs && !resumeCommand;
9743
10135
  const runBtn = inFlight
9744
10136
  ? `<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>`
9745
- : canRunNow
10137
+ : canRunNow && !filterGuide
9746
10138
  ? r.preparationRetryable
9747
10139
  ? `<button class="req-run" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-retry#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Retry preparation" data-tip="Retry Steel Filter preparation with the attached drawings">▶</button>`
9748
10140
  : `<button class="req-run" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-run#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Start this request in the background" data-tip="Start this request in the background with your terminal AI">▶</button>`
@@ -9755,7 +10147,7 @@
9755
10147
  const discussBtn = chatProvider && inChatScope
9756
10148
  ? `<button class="req-chat-action" data-request-chat="discuss" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-discuss#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="${hasLinkedChat ? 'Open' : 'Discuss'} ${escapeAttr(chatLabel)} in AI Chat" data-tip="${hasLinkedChat ? 'Open the linked conversation in AI Chat' : 'Open this request in AI Chat without starting the AI'}">${hasLinkedChat ? 'Open AI Chat' : 'Discuss in AI Chat'}</button>`
9757
10149
  : '';
9758
- const startChatBtn = chatProvider && inChatScope && canRunNow
10150
+ const startChatBtn = chatProvider && inChatScope && canRunNow && !filterGuide
9759
10151
  ? `<button class="req-chat-action primary" data-request-chat="start" data-id="${escapeAttr(r.id)}" data-command-id="shell.requests-start-chat#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}" aria-label="Start ${escapeAttr(chatLabel)} in AI Chat" data-tip="Start this request in AI Chat and continue there">Start in AI Chat</button>`
9760
10152
  : '';
9761
10153
  const chatMeta = chatProvider && inChatScope
@@ -9769,9 +10161,13 @@
9769
10161
  <div class="req-head"><span class="${badgeCls}">${label}</span> ${owner ? `<span class="req-owner">${highlightQuery(owner, normalizedRequestQuery)}</span>` : ''}${time}</div>
9770
10162
  ${r.type === 'revision-read'
9771
10163
  ? `<div class="req-instruction req-summary">${highlightQuery(requestSummary(r), normalizedRequestQuery)}</div><details class="req-technical"${normalizedRequestQuery && `${instructionFor(r)} ${r.preparationDiagnostic || ''}`.toLowerCase().includes(normalizedRequestQuery.toLowerCase()) ? ' open' : ''}><summary data-command-id="shell.requests-technical#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}">Show detailed instructions</summary><div class="req-technical-body">${highlightQuery(`${instructionFor(r)}${r.preparationDiagnostic ? `\n\n${r.preparationDiagnostic}` : ''}`, normalizedRequestQuery)}</div></details>`
10164
+ : filterGuide
10165
+ ? `<div class="req-instruction req-summary">${highlightQuery(r.instructorContext.subject || 'Drawing Filter AI request', normalizedRequestQuery)}</div><p class="req-run-note">${escapeHtml(filterGuideRequestNote(r))}</p><details class="req-technical"><summary data-command-id="shell.requests-technical#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(commandInstance)}">Show detailed instructions</summary><div class="req-technical-body">${highlightQuery(instructionFor(r), normalizedRequestQuery)}</div></details>`
9772
10166
  : `<div class="req-instruction">${highlightQuery(instructionFor(r), normalizedRequestQuery) || 'This request has no instructions to send. Remove it and create the request again.'}</div>`}
9773
10167
  ${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>` : ''}
9774
- ${runStatusHtml(run, resumeCommand, desktopHandoffs, r.id, commandInstance, ownRecoverySurface)}
10168
+ ${runStatusHtml(run, resumeCommand, desktopHandoffs, r.id, commandInstance, ownRecoverySurface,
10169
+ filterGuide
10170
+ ? (r.instructorContext.commandId === 'filter.ask-ai-change' ? 'change' : 'question') : null)}
9775
10171
  ${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>` : ''}
9776
10172
  ${auditRefusalHtml(r)}
9777
10173
  </div>
@@ -10550,7 +10946,6 @@
10550
10946
  void refreshIntegrations().then(focusPendingIntegration);
10551
10947
  refreshHeadless().then(renderRuntimeSection);
10552
10948
  };
10553
-
10554
10949
  function focusPendingIntegration() {
10555
10950
  if (!pendingIntegrationFocus || !$integrationsModal.classList.contains('show')) return;
10556
10951
  const id = (window.CSS && CSS.escape) ? CSS.escape(pendingIntegrationFocus) : pendingIntegrationFocus;
@@ -10589,8 +10984,76 @@
10589
10984
  $body.hidden = !runtimeSectionExpanded;
10590
10985
  }
10591
10986
 
10987
+ // The four things the server can learn about a runtime's account, exactly as the chat Provider
10988
+ // row states them (web/chat.js). Anything that is not one of the three definite answers — a
10989
+ // missing or null field included — is 'unknown': a read that never completed is not a signed-out
10990
+ // CLI, and a working install on Bedrock/Vertex or an API key is 'no-identity', not signed out.
10991
+ function runtimeSignInAnswer(answer) {
10992
+ const state = answer && answer.state;
10993
+ if (state === 'signed-in' || state === 'signed-out' || state === 'no-identity') return answer;
10994
+ return { state: 'unknown', reason: (answer && answer.reason) || 'no answer' };
10995
+ }
10996
+
10997
+ // A stable identity for "is this a different answer than before?". Emails alone cannot see a
10998
+ // sign-OUT, because both sides of that comparison are absent.
10999
+ function runtimeAnswerKey(answer) {
11000
+ const settled = runtimeSignInAnswer(answer);
11001
+ return settled.state === 'signed-in' ? `signed-in:${settled.email}` : settled.state;
11002
+ }
11003
+
11004
+ function runtimeAccountLabel(answer) {
11005
+ const settled = runtimeSignInAnswer(answer);
11006
+ if (settled.state === 'signed-out') return 'Not signed in';
11007
+ if (settled.state === 'no-identity') return 'Signed in (no account to show)';
11008
+ if (settled.state === 'unknown') return 'Could not check';
11009
+ const plan = settled.plan ? ` · ${settled.plan.charAt(0).toUpperCase()}${settled.plan.slice(1)}` : '';
11010
+ return `Signed in as ${settled.email}${plan}`;
11011
+ }
11012
+
11013
+ // The sign-in itself happens in the window FloLess opened. Poll the runtimes read (10 s server
11014
+ // cache) until this runtime NAMES a sign-in different from the one held at click time, or give
11015
+ // up after two minutes. A different sign-in rather than "a different email": signing in with an
11016
+ // API key produces no email, and the button would stay disabled for the full two minutes. And
11017
+ // not "any definite change": the server signs the CLI out BEFORE the window opens, so signed-out
11018
+ // is what every poll sees while the user is still in it — ending there would offer "Sign in…"
11019
+ // again with the window open (the server refuses that click for its launch cooldown). And once
11020
+ // that sign-out HAS been seen, any named sign-in is the landed one — including the same account
11021
+ // again: a user who changes their mind in the browser must not wait out the deadline.
11022
+ async function waitForRuntimeSignIn(id, before, deadlineMs = 120_000, everyMs = 3_000) {
11023
+ const until = Date.now() + deadlineMs;
11024
+ let signedOutSeen = false;
11025
+ while (Date.now() < until) {
11026
+ await new Promise((resolve) => setTimeout(resolve, everyMs));
11027
+ let info = null;
11028
+ // Read the route directly rather than through refreshHeadless(): that one NULLS the shared
11029
+ // `headlessInfo` on a failed fetch, and a single blip during a two-minute poll would take the
11030
+ // Start affordances across Requests (headlessReady/preferredChatProvider) and this whole
11031
+ // section down with it. A poll is allowed to miss a beat; it is not allowed to erase state.
11032
+ try { info = await api('/api/terminal-runtimes'); } catch { continue; }
11033
+ const row = info?.runtimes?.find((r) => r && r.id === id);
11034
+ if (!row) continue;
11035
+ const answer = runtimeSignInAnswer(row.account);
11036
+ // An 'unknown' answer is a read that never completed; it is not evidence the window closed.
11037
+ if (answer.state === 'unknown') continue;
11038
+ // `headlessInfo` is not re-read until this wait ends, so any repaint meanwhile would keep
11039
+ // naming the old account for up to two minutes after the server signed it out. Text only, in
11040
+ // place: a full re-render replaces the focused button (see the click handler).
11041
+ const line = document.querySelector(`.int-rt [data-sign-in="${escapeAttr(id)}"]`)?.parentElement?.querySelector('.int-rt-account');
11042
+ if (line && line.textContent !== runtimeAccountLabel(row.account)) line.textContent = runtimeAccountLabel(row.account);
11043
+ // A 'signed-out' is FloLess's own doing (above), not the sign-in the user went off to make.
11044
+ if (answer.state === 'signed-out') { signedOutSeen = true; continue; }
11045
+ if (signedOutSeen || runtimeAnswerKey(answer) !== before) return;
11046
+ }
11047
+ }
11048
+ const pendingRuntimeSignIn = new Set();
11049
+ // The server's own sentence is the accurate one: it names which runtime problem happened, which
11050
+ // command to run by hand, or that a sign-in window is already open. reportErr would flatten all
11051
+ // of them into one line. Same rule as the chat Provider row (web/chat.js).
11052
+ const SERVER_WORDED_SIGN_IN_CODES = new Set(['chat-turn-active', 'runtime-unavailable', 'launch-unsafe', 'launch-failed', 'sign-in-active', 'sign-out-failed']);
11053
+
10592
11054
  /**
10593
- * Which terminal AIs are installed, which one headless runs use, and the folder they run in.
11055
+ * Which terminal AIs are installed, which one headless runs use, the folder they run in, and —
11056
+ * per runtime — the ACCOUNT it answers from, with the CLI's own sign-in a click away.
10594
11057
  *
10595
11058
  * Its own section rather than a card in the integrations grid: a detected CLI is not an OAuth
10596
11059
  * connection. There is no Connect, no expiry — and deliberately no "ready", because a signed-out
@@ -10616,17 +11079,34 @@
10616
11079
  if (folder) $summary.setAttribute('data-tip', folder); else $summary.removeAttribute('data-tip');
10617
11080
  $toggle.onclick = () => setRuntimeSectionExpanded(!runtimeSectionExpanded);
10618
11081
  setRuntimeSectionExpanded(runtimeSectionExpanded);
11082
+ const signInTip = 'FloLess uses whichever account is signed in to the Claude Code or Codex CLI on this computer. Signing in to the Claude desktop app or claude.ai does not change it. Switch account signs that CLI out first, then opens a window where you sign in.';
10619
11083
  $list.innerHTML = rts.map((r) => {
10620
11084
  const found = r.state === 'found';
10621
11085
  const isDefault = found && r.id === active;
11086
+ const answer = runtimeSignInAnswer(r.account);
11087
+ // A missing user install can still have a managed copy that signs in: the account line
11088
+ // follows the account, not the badge. An answer that names one — or says it is signed in with
11089
+ // nothing to name — is such a copy; "signed out" and "could not check" are not.
11090
+ const showsAccount = found || answer.state === 'signed-in' || answer.state === 'no-identity';
11091
+ const pending = pendingRuntimeSignIn.has(r.id);
11092
+ // Both cards render the same visible "Switch account…", so without a runtime-specific
11093
+ // accessible name a screen reader (and Instructor's focus proof) cannot tell them apart.
11094
+ // Only a parsed sign-OUT may offer a sign-in; the label follows the same rule as the text.
11095
+ const signInName = answer.state === 'signed-out' ? `Sign in to ${r.label}` : `Switch ${r.label} account`;
11096
+ // The sign-in sits on the account line it acts on. The side column is a flex row already
11097
+ // holding the badge and, on the non-default card, "Use this one" — a third control wraps.
10622
11098
  return `
10623
11099
  <div class="int-rt${isDefault ? ' is-default' : ''}${found ? '' : ' is-missing'}">
10624
- <div>
11100
+ <div class="int-rt-main">
10625
11101
  <div class="int-rt-name">${escapeHtml(r.label)}${isDefault ? '<span class="int-rt-pill">Default</span>' : ''}</div>
10626
11102
  <div class="int-rt-blurb">${escapeHtml(r.blurb)} · <code>${escapeHtml(r.command)}</code></div>
10627
11103
  <div class="int-rt-where">${found
10628
11104
  ? `Found at ${escapeHtml(r.path || '')}`
10629
11105
  : `Not installed — floless looks for <code>${escapeHtml(r.command)}</code>`}</div>
11106
+ ${showsAccount ? `<div class="int-rt-signin">
11107
+ <div class="int-rt-account" aria-live="polite" data-tip="${escapeAttr(signInTip)}">${escapeHtml(runtimeAccountLabel(r.account))}</div>
11108
+ <button class="int-action" data-sign-in="${escapeAttr(r.id)}" data-command-id="shell.headless-sign-in#${escapeAttr(r.id)}" data-command-instance-label="${escapeAttr(r.label)}" aria-label="${escapeAttr(signInName)}" data-tip="${escapeAttr(signInTip)}"${pending ? ' disabled data-blocked-reason="Waiting for the sign-in window."' : ''}>${pending ? 'Waiting for sign-in…' : answer.state === 'signed-out' ? 'Sign in…' : 'Switch account…'}</button>
11109
+ </div>` : ''}
10630
11110
  </div>
10631
11111
  <div class="int-rt-side">
10632
11112
  <span class="int-rt-badge">${found ? 'Installed' : 'Not installed'}</span>
@@ -10644,6 +11124,51 @@
10644
11124
  } catch (e) { reportErr(e); }
10645
11125
  };
10646
11126
  });
11127
+ $list.querySelectorAll('[data-sign-in]').forEach((b) => {
11128
+ b.onclick = async () => {
11129
+ const id = b.dataset.signIn;
11130
+ if (pendingRuntimeSignIn.has(id)) return;
11131
+ const before = runtimeAnswerKey(headlessRuntimes().find((r) => r && r.id === id)?.account);
11132
+ // Flip THIS button in place rather than re-rendering the list: a full re-render replaces the
11133
+ // focused button (dropping keyboard focus to <body> inside an aria-modal dialog for up to two
11134
+ // minutes) and swaps out the aria-live account node, which is then not reliably announced.
11135
+ // The pending id is still recorded so any OTHER re-render paints this card as waiting.
11136
+ pendingRuntimeSignIn.add(id);
11137
+ b.disabled = true;
11138
+ b.dataset.blockedReason = 'Waiting for the sign-in window.';
11139
+ b.textContent = 'Waiting for sign-in…';
11140
+ try {
11141
+ // api() has no deadline of its own. A POST that never answers would leave this button
11142
+ // disabled and `pendingRuntimeSignIn` populated for the life of the page, so bound it —
11143
+ // the chat's request() already defaults to the same 30 s.
11144
+ await api(`/api/terminal-runtimes/${encodeURIComponent(id)}/sign-in`, { method: 'POST', signal: AbortSignal.timeout(30_000) });
11145
+ await waitForRuntimeSignIn(id, before);
11146
+ } catch (e) {
11147
+ // api() rejects with the parsed body on `.body` and the HTTP status on `.status`.
11148
+ const code = e && e.body && e.body.code;
11149
+ const worded = SERVER_WORDED_SIGN_IN_CODES.has(code)
11150
+ && [e.body.error, e.message].find((s) => typeof s === 'string' && s.trim());
11151
+ if (worded) showToast(worded, 'warn');
11152
+ else reportErr(e);
11153
+ } finally {
11154
+ pendingRuntimeSignIn.delete(id);
11155
+ delete b.dataset.blockedReason;
11156
+ // NOT refreshHeadless(): that one NULLS the shared `headlessInfo` on a failed fetch, so a
11157
+ // single blip here would hide this whole section and take the Start affordances across
11158
+ // Requests down with it — the exact hazard the comment on waitForRuntimeSignIn warns
11159
+ // about. Read the route directly and merge only a well-formed answer; a failed read
11160
+ // leaves the card showing what it last knew, and says so in the console.
11161
+ try {
11162
+ const info = await api('/api/terminal-runtimes');
11163
+ if (info && Array.isArray(info.runtimes)) headlessInfo = info;
11164
+ else console.warn('floless: the runtimes read after a sign-in had no runtime list', info);
11165
+ } catch (error) {
11166
+ console.warn('floless: could not re-read the terminal runtimes after a sign-in', error);
11167
+ }
11168
+ renderRuntimeSection();
11169
+ }
11170
+ };
11171
+ });
10647
11172
  $folder.innerHTML = `
10648
11173
  <span>Runs in</span>
10649
11174
  <span class="int-folder-path${folder ? '' : ' is-unset'}"${folder ? ` data-tip="${escapeAttr(folder)}"` : ''}>${folder ? escapeHtml(folder) : 'not chosen yet — floless will ask the first time you run one'}</span>
@@ -10746,6 +11271,31 @@
10746
11271
  }).join('')}</div>`;
10747
11272
  }
10748
11273
 
11274
+ // An OAuth row's endpoint list stays on one clipped line (reference detail, not something the
11275
+ // person must read to act), but a clipped line must never be a dead end (#1524): when it
11276
+ // actually overflows it carries the full text as a themed data-tip and becomes focusable, so
11277
+ // hover AND keyboard reach the rest. A line that fits gets neither — no redundant tip, no
11278
+ // extra tab stop. It measures live layout, so its callers run it only while the modal is shown.
11279
+ function offerClippedScopeLines(root) {
11280
+ root.querySelectorAll('.int-scopes:not(.int-setup-detail)').forEach((line) => {
11281
+ if (line.scrollWidth > line.clientWidth) {
11282
+ line.setAttribute('data-tip', line.textContent);
11283
+ line.setAttribute('tabindex', '0');
11284
+ } else {
11285
+ line.removeAttribute('data-tip');
11286
+ line.removeAttribute('tabindex');
11287
+ }
11288
+ });
11289
+ }
11290
+ // A line's clip changes with the list's width (a narrower window squeezes the modal), not only
11291
+ // on render, so re-measure when the list resizes. The list lives for the whole page, so this
11292
+ // observer does too; a hidden modal measures as zero width and is skipped — opening it re-renders.
11293
+ if (typeof ResizeObserver === 'function') {
11294
+ new ResizeObserver(() => {
11295
+ if ($integrationsModal.classList.contains('show')) offerClippedScopeLines($integrationsList);
11296
+ }).observe($integrationsList);
11297
+ }
11298
+
10749
11299
  renderIntegrations = function renderIntegrationsReal() {
10750
11300
  if (integrationsLoadState === 'loading' || integrationsLoadState === 'idle') {
10751
11301
  $integrationsList.innerHTML = '<div class="empty-state">Checking integrations…</div>';
@@ -10766,12 +11316,14 @@
10766
11316
  const needsAttention = i.status === 'needs-attention';
10767
11317
  const needsAccount = i.status === 'account-selection-required';
10768
11318
  const checkUnavailable = i.status === 'check-unavailable';
11319
+ const missingReader = needsAttention && i.setup?.category === 'reader-release-unavailable';
10769
11320
  const setupDetails = {
10770
11321
  'aware-unavailable': 'FloLess couldn’t start the service used by Revit projects.',
10771
11322
  'core-workflow-provisioning': 'FloLess couldn’t prepare the built-in Workspace workflows.',
10772
11323
  'reader-verification': 'FloLess couldn’t verify the installed Revit reader.',
10773
11324
  'workspace-bootstrap': 'FloLess couldn’t prepare the Workspace connection used by Revit workflows.',
10774
11325
  'revit-workflow-provisioning': 'FloLess couldn’t prepare the Revit project workflows.',
11326
+ 'reader-release-unavailable': 'FloLess can’t set up Revit because the required reader version is unavailable. Report this issue, then try setup again after FloLess restores it.',
10775
11327
  unknown: 'FloLess couldn’t finish Revit setup.',
10776
11328
  };
10777
11329
  const badge = ready ? 'Ready' : needsAttention ? 'Needs setup'
@@ -10787,15 +11339,20 @@
10787
11339
  : 'Revit model access is not included for this account. Ask the account owner to add it.';
10788
11340
  const checkLabel = needsAttention ? 'Try setup again' : needsAccount ? 'Choose account'
10789
11341
  : ready ? 'Check status' : 'Check access again';
10790
- return `<div class="int-item int-${escapeAttr(i.status)}" data-integration-id="xeorvt" tabindex="-1">
11342
+ // The Revit detail is always a sentence the person must finish reading (#1524), so it
11343
+ // always wraps (int-setup-detail) and always describes the card — never the one-line clip
11344
+ // the OAuth rows' endpoint list uses.
11345
+ return `<div class="int-item int-${escapeAttr(i.status)}" data-integration-id="xeorvt" tabindex="-1" aria-describedby="xeorvt-setup-detail">
10791
11346
  <div class="int-icon">R</div><div class="int-info">
10792
11347
  <div class="int-name">${escapeHtml(i.name)}</div>
10793
11348
  <div class="int-kind">Revit project integration · provided by FloLess</div>
10794
- <div class="int-scopes">${escapeHtml(detail)}</div>
11349
+ <div class="int-scopes int-setup-detail" id="xeorvt-setup-detail">${escapeHtml(detail)}</div>
10795
11350
  <div class="int-row"><span class="int-badge int-badge-${ready ? 'connected' : needsAttention ? 'expired' : 'disconnected'}">${badge}</span>
11351
+ <span class="int-recovery-actions">
10796
11352
  ${ready ? '<button class="int-action" data-xeorvt-action="open">Open Revit projects</button>' : ''}
10797
- <button class="int-action" data-xeorvt-action="${needsAccount ? 'account' : 'check'}" data-xeorvt-retry="${needsAttention ? 'true' : 'false'}">${checkLabel}</button>
10798
- </div></div></div>`;
11353
+ ${missingReader ? '<button class="int-action" data-xeorvt-action="report" data-command-id="shell.revit-report-setup-issue" aria-label="Report issue: missing Revit reader" aria-describedby="xeorvt-setup-detail">Report issue</button>' : ''}
11354
+ <button class="int-action" data-xeorvt-action="${needsAccount ? 'account' : 'check'}" data-xeorvt-retry="${needsAttention ? 'true' : 'false'}"${needsAttention ? ' aria-describedby="xeorvt-setup-detail"' : ''}>${checkLabel}</button>
11355
+ </span></div></div></div>`;
10799
11356
  }
10800
11357
  const action = i.status === 'connected' ? 'Disconnect' : i.status === 'expired' ? 'Reconnect' : 'Connect';
10801
11358
  const badge = i.status === 'connected' ? 'Connected' : i.status === 'expired' ? 'Token expired' : 'Not connected';
@@ -10821,11 +11378,18 @@
10821
11378
  </div>
10822
11379
  </div>`;
10823
11380
  }).join('');
11381
+ offerClippedScopeLines($integrationsList);
10824
11382
  $integrationsList.querySelectorAll('[data-xeorvt-action]').forEach((btn) => {
10825
11383
  btn.onclick = async () => {
10826
11384
  if (btn.dataset.xeorvtAction === 'open') {
10827
11385
  $integrationsModal.classList.remove('show');
10828
11386
  if (window.flolessWorkspaces) await window.flolessWorkspaces.setMode('workspaces');
11387
+ } else if (btn.dataset.xeorvtAction === 'report') {
11388
+ hideModal($integrationsModal);
11389
+ riReturnToIntegration = true;
11390
+ openReportIssue();
11391
+ $riTitle.value = 'Revit setup: required reader unavailable';
11392
+ riSyncSend();
10829
11393
  } else if (btn.dataset.xeorvtAction === 'account') {
10830
11394
  await recheckLicenseAndGate({ forRevitAccountSelection: true });
10831
11395
  } else {
@@ -10833,9 +11397,24 @@
10833
11397
  const hadFocus = document.activeElement === btn;
10834
11398
  btn.disabled = true;
10835
11399
  btn.textContent = 'Setting up…';
10836
- try { await api('/api/rvt-defaults/retry', { method: 'POST' }); }
10837
- catch { showToast('Revit setup couldn’t finish. Try setup again.', 'warn'); }
11400
+ let retryAnnouncement = 'Revit setup is ready.';
11401
+ try {
11402
+ const setup = await api('/api/rvt-defaults/retry', { method: 'POST' });
11403
+ if (setup.status !== 'ready') {
11404
+ retryAnnouncement = 'Revit setup could not finish. The Integrations card shows what to do next.';
11405
+ showToast(setup.category === 'reader-release-unavailable'
11406
+ ? 'The required Revit reader is unavailable. Choose Report issue; try setup again after FloLess restores it.'
11407
+ : 'Revit setup couldn’t finish. Try setup again.', 'warn');
11408
+ }
11409
+ }
11410
+ catch (error) {
11411
+ retryAnnouncement = 'Revit setup could not finish. The Integrations card shows what to do next.';
11412
+ showToast(error?.body?.category === 'reader-release-unavailable'
11413
+ ? 'The required Revit reader is unavailable. Choose Report issue; try setup again after FloLess restores it.'
11414
+ : 'Revit setup couldn’t finish. Try setup again.', 'warn');
11415
+ }
10838
11416
  await refreshIntegrations();
11417
+ document.getElementById('integrations-status').textContent = retryAnnouncement;
10839
11418
  if (hadFocus) $integrationsList.querySelector('[data-integration-id="xeorvt"] [data-xeorvt-action]:last-of-type')?.focus();
10840
11419
  return;
10841
11420
  } else {
@@ -11724,10 +12303,18 @@
11724
12303
  let riAppVersion = ''; // captured from /api/health on open so the report actually carries
11725
12304
  let riAwareVersion = ''; // the versions the modal promises ("sent automatically: …")
11726
12305
  let riReturnFocus = null;
12306
+ let riReturnToIntegration = false;
11727
12307
 
11728
12308
  const riSyncSend = () => { $riSend.disabled = !($riTitle.value.trim() && $riDesc.value.trim()); };
11729
12309
  function riHideAndRestoreFocus() {
11730
12310
  hideModal($riModal);
12311
+ if (riReturnToIntegration) {
12312
+ riReturnToIntegration = false;
12313
+ riReturnFocus = null;
12314
+ showModal($integrationsModal);
12315
+ ($integrationsList.querySelector('[data-xeorvt-action="report"]') || document.getElementById('integrations-close'))?.focus();
12316
+ return;
12317
+ }
11731
12318
  const returnFocus = riReturnFocus;
11732
12319
  riReturnFocus = null;
11733
12320
  if (returnFocus && returnFocus.isConnected) returnFocus.focus();
@@ -12499,6 +13086,10 @@
12499
13086
 
12500
13087
  window.flolessBridge = {
12501
13088
  api,
13089
+ requestScopeLabel(projectId) {
13090
+ return wsRequestScope?.kind === 'project' && wsRequestScope.project === projectId
13091
+ ? wsRequestScope.label : null;
13092
+ },
12502
13093
  // Open report HTML in the existing sandboxed HTML Viewer (same modal + srcdoc
12503
13094
  // iframe the canvas report node uses — no new sandbox surface). `savedPath` is
12504
13095
  // optional: pass the run's saved_path so a dashboard-panel run surfaces the same