@floless/app 0.159.0 → 0.161.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 (43) hide show
  1. package/dist/floless-server.cjs +76823 -65608
  2. package/dist/schemas/steel.model.v2.schema.json +24 -0
  3. package/dist/skills/floless-app-onboarding/SKILL.md +4 -3
  4. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +1 -2
  5. package/dist/skills/floless-app-rfi/SKILL.md +44 -3
  6. package/dist/skills/floless-app-steel-model/SKILL.md +2 -2
  7. package/dist/skills/floless-app-steel-takeoff/SKILL.md +417 -261
  8. package/dist/templates/steel-model.flo +6 -2
  9. package/dist/templates/viewer-3d-demo.flo +8 -2
  10. package/dist/web/app.css +342 -160
  11. package/dist/web/app.js +17 -51
  12. package/dist/web/aware.js +656 -574
  13. package/dist/web/chat-question-card.js +27 -1
  14. package/dist/web/chat.css +185 -30
  15. package/dist/web/chat.js +2099 -255
  16. package/dist/web/commands-drawing-check.js +1 -0
  17. package/dist/web/commands-filter.js +11 -0
  18. package/dist/web/commands-shell.js +1118 -134
  19. package/dist/web/commands-steel.js +41 -38
  20. package/dist/web/drawing-check-editor.js +76 -3
  21. package/dist/web/guide.js +8 -0
  22. package/dist/web/index.html +68 -42
  23. package/dist/web/instructor.js +17 -6
  24. package/dist/web/pages.js +158 -30
  25. package/dist/web/panels.js +19 -1
  26. package/dist/web/project-history.js +349 -0
  27. package/dist/web/project-reconciliation.js +1 -0
  28. package/dist/web/project-rfis.js +954 -0
  29. package/dist/web/project-workflows.js +236 -4
  30. package/dist/web/run-history.js +198 -0
  31. package/dist/web/run-page-view.js +12 -2
  32. package/dist/web/startup-admission.js +53 -7
  33. package/dist/web/steel-3d-core.js +144 -7
  34. package/dist/web/steel-3d-view.js +61 -5
  35. package/dist/web/steel-editor.html +510 -128
  36. package/dist/web/steel-filter.html +139 -0
  37. package/dist/web/steel-model-v2-commands.js +3 -3
  38. package/dist/web/steel-model-v2-projection.js +139 -4
  39. package/dist/web/steel-plan-transform.js +78 -0
  40. package/dist/web/tool-updates.js +5 -0
  41. package/dist/web/workspaces.js +1438 -159
  42. package/launch.mjs +36 -5
  43. package/package.json +7 -4
@@ -660,6 +660,9 @@
660
660
  let exportState = null; // kind → { path, exportedAt } after a successful list; null = unknown/failed
661
661
  // #2449: { version, hash } of the approved version exportState's files came from, from the SAME listing; null = unknown.
662
662
  let exportStateFrom = null;
663
+ // #2781: DRAFT exports (working copy / checkpoint) from the same listing. Receipt-less by design and kept apart from
664
+ // `exportState`, so nothing that reads the approved rows can ever count one.
665
+ let exportDrafts = [];
663
666
  /*
664
667
  * THE UNITS THE SERVER SAYS THIS PROJECT'S BILL IS IN — from the same response the card is built
665
668
  * from, refreshed every time the card is. `null` until it has answered.
@@ -764,7 +767,8 @@
764
767
  accessCopy: {
765
768
  'access-required': {
766
769
  status: 'Not in your plan',
767
- body: 'Steel Model is not included in this account’s plan. Add it on floless.io, or sign in with an account that has it. Steel models already on this computer stay viewable.',
770
+ // No "stay viewable": Steel Model has no recovery view since 2026-10-23 (owner ruling, #1894/#2360).
771
+ body: 'Steel Model is not included in this account’s plan. Add it on floless.io, or sign in with an account that has it.',
768
772
  action: 'See plans', aria: 'Steel Model is not in your plan — see plans on floless.io (opens in a new tab)',
769
773
  },
770
774
  'account-selection-required': {
@@ -778,10 +782,14 @@
778
782
  },
779
783
  editor: '/steel-editor.html',
780
784
  filter: '/steel-filter.html',
785
+ // #2470 R6.6c: the RFIs step shows this editor's own RFI page, in the same frame as Model (plan
786
+ // 2026-10-25-2470-r6-6c-steel-rfis-step-PLAN.md): one document, so the list keeps the model state it works from.
787
+ rfisInEditor: true,
781
788
  steps: [
782
789
  { key: 'knowledge', label: 'Knowledge' }, // per-project KB — the job's context, consulted by everything
783
790
  { key: 'drawings', label: 'Drawing Filter' },
784
791
  { key: 'model', label: 'Model' },
792
+ { key: 'rfis', label: 'RFIs' }, // #2470 R6.6c: owner ruling 2026-10-25, right after Model
785
793
  { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages; #2568: just before Exports (both are output)
786
794
  { key: 'exports', label: 'Exports' },
787
795
  { key: 'history', label: 'History' },
@@ -816,7 +824,6 @@
816
824
  cardIcon: '<path d="M5 16C8 6 16 6 19 16"/><rect x="3.25" y="16" width="3.5" height="3.5" rx=".5"/><rect x="17.25" y="16" width="3.5" height="3.5" rx=".5"/><rect x="10.5" y="7" width="3" height="3" rx=".5"/><path d="M6.5 8.5h4M13.5 8.5h4"/><circle cx="5" cy="8.5" r="1.5"/><circle cx="19" cy="8.5" r="1.5"/>', // a curve with anchors and handles
817
825
  displayName: 'Trace',
818
826
  projectCapability: 'editable 2D drawing',
819
- docGuide: true,
820
827
  createActions: [
821
828
  {
822
829
  kind: 'drawing',
@@ -1014,7 +1021,11 @@
1014
1021
  { key: 'knowledge', label: 'Knowledge' },
1015
1022
  { key: 'pages', label: 'Pages' },
1016
1023
  { key: 'workflows', label: 'Workflows' }, // #2470 R6.2: the workflows this project owns
1024
+ { key: 'rfis', label: 'RFIs' }, // #2470 R6.6: the project's questions for the engineer, client or architect
1017
1025
  { key: 'modules', label: 'Modules' }, // #2470 R6.7: the module projects linked to this one
1026
+ // #2470 R6.5: what happened in the project. Keyed `journal`, not `history`: the module kinds' `history` step is
1027
+ // their approval ledger, which setStep renders under that key.
1028
+ { key: 'journal', label: 'History' },
1018
1029
  ],
1019
1030
  diff: false,
1020
1031
  exports: [],
@@ -1295,6 +1306,7 @@
1295
1306
  $approveBtn.classList.toggle('approval-clean', s.status === 'ready' && !!s.headVersion && s.pendingCount === 0);
1296
1307
  $approveBtn.classList.toggle('approval-findings-accepted', s.status === 'ready' && !!s.headVersion && s.pendingCount === 0
1297
1308
  && !!(s.review && s.review.approvedHeadImportFindings));
1309
+ renderQuickHeader();
1298
1310
  }
1299
1311
 
1300
1312
  /**
@@ -1405,7 +1417,6 @@
1405
1417
  approvalState = { status: 'unreviewable', reason: review.reason, review: null, pendingCount: 0,
1406
1418
  headVersion: null, error: review.message || 'This project cannot be approved.' };
1407
1419
  renderApprovalHeader();
1408
- syncWorkspaceGuide();
1409
1420
  if (!$wsExports.hidden) paintExports(current.approvedAt);
1410
1421
  // No History re-render here. An earlier cut of this change had one, to repair a History
1411
1422
  // that had painted while the status was still `loading` — but `renderHistory` now parks on
@@ -1420,7 +1431,6 @@
1420
1431
  approvalState = { status: 'ready', review, pendingCount: groups.length, headVersion, error: '' };
1421
1432
  renderApprovalHeader();
1422
1433
  settleImportedSourceCard(projectId);
1423
- syncWorkspaceGuide();
1424
1434
  if (!$wsExports.hidden) paintExports(current.approvedAt);
1425
1435
  return review;
1426
1436
  } catch (error) {
@@ -1446,21 +1456,6 @@
1446
1456
  return (st && st.label) || (key.charAt(0).toUpperCase() + key.slice(1));
1447
1457
  };
1448
1458
 
1449
- // ── Workspaces guide beacon (aware.js owns #guide-beacon; we own project state) ──────
1450
- // The document-lifecycle guide (drop → review → approve → export) is for the lightweight
1451
- // Trace document archetype. Steel can now also start from drawings, but its guide/capability
1452
- // surface is broader and should not inherit Trace-specific SVG guidance.
1453
- const wsHasDocGuide = () => { const d = wsApp(); return !!(d && d.docGuide); };
1454
- function syncWorkspaceGuide() {
1455
- if (!bridge.setWorkspaceGuide) return; // older bridge — no-op (beacon simply stays hidden)
1456
- if (!current || !wsHasDocGuide()) { bridge.clearWorkspaceGuide && bridge.clearWorkspaceGuide(); return; }
1457
- // `exported` = an SVG export file exists (from the last export listing); best-known from
1458
- // exportState, which renderExports() populates. Unknown before Exports is opened → false.
1459
- const exported = !!(exportState && exportState.svg && exportState.svg.exportedAt);
1460
- bridge.setWorkspaceGuide({ app: current.app, name: current.name, displayName: projectAppName(current),
1461
- approved: approvalState.status === 'ready' && !!approvalState.headVersion && approvalState.pendingCount === 0, exported });
1462
- }
1463
-
1464
1459
  // ── mode ────────────────────────────────────────────────────────────────────
1465
1460
  // Which subject the browser tab should name. Pure and named so it can be driven over its three
1466
1461
  // real states in a test rather than grepped for out of applyMode() — review found four realistic
@@ -1519,8 +1514,6 @@
1519
1514
  $app.classList.toggle('mode-workspaces', ws);
1520
1515
  document.body.classList.toggle('mode-workspaces', ws);
1521
1516
  document.documentElement.classList.remove('mode-workspaces-boot');
1522
- // #2007: with both mode classes set, the workflow spotlight closes off Workflows and is offered again on it.
1523
- if (bridge.syncGuideSpotlight) bridge.syncGuideSpotlight();
1524
1517
  // The provenance strip is workflow-level data. Workspaces replaces that surface (including its
1525
1518
  // landing), so cancel any late workflow-pin paint before the project UI starts loading.
1526
1519
  if (ws && bridge.clearKbInformed) bridge.clearKbInformed();
@@ -1567,11 +1560,6 @@
1567
1560
  if (!ws) bridge.setRequestScope(null);
1568
1561
  else bridge.setRequestScope(current ? { project: current.id, appId: current.app, label: current.name } : {});
1569
1562
  }
1570
- // Keep the shared guide beacon in step with mode: in Workflows mode (or the Workspaces
1571
- // landing) it must NOT show a workspace guide — clear it so aware.js reverts to the
1572
- // workflow beacon; in a Workspaces project it points at that project's lifecycle.
1573
- if (!ws || !current) { if (bridge.clearWorkspaceGuide) bridge.clearWorkspaceGuide(); }
1574
- else syncWorkspaceGuide();
1575
1563
  if (window.flolessLeftPane) {
1576
1564
  // Any Model step may offer the left Model section; it appears only once that editor sends a snapshot.
1577
1565
  const modelPanelVisible = ws && !!current && currentStep === 'model';
@@ -1993,6 +1981,9 @@
1993
1981
  window.addEventListener('floless:contract-changed', (e) => {
1994
1982
  const m = (e && e.detail) || {};
1995
1983
  if (current && m.project === current.id) tellModelFrame(m);
1984
+ // A published edit changes the comparison too, including this editor's own save. Re-read the
1985
+ // server's pending groups rather than leaving the last approved verdict in the header (#2775).
1986
+ if (current && m.project === current.id && m.appId === current.app) refreshApprovalState(current.id);
1996
1987
  });
1997
1988
  window.addEventListener('floless:projects-changed', (e) => {
1998
1989
  // Sent after the event stream reconnects too (aware.js), with no detail: frames may have been missed, so the
@@ -2800,6 +2791,8 @@
2800
2791
  thumbBandHtml(p, displayApp) +
2801
2792
  `<span class="ws-body"><span><span class="ws-name">${escapeHtml(p.name)}</span>` +
2802
2793
  (projectCapability ? `<span class="ws-meta">${escapeHtml(projectCapability)}</span>` : '') +
2794
+ // #2521 row 5: the card speaks for the WORKING COPY only, and says so in its tip.
2795
+ (p.quick && quickPillHtml(p.quick) ? `<span class="ws-meta ws-quick">${quickPillHtml(p.quick, { scope: 'Working copy', focusable: false })}</span>` : '') +
2803
2796
  (p.importedMidSave ? `<span class="ws-meta ws-unverified" data-tip="${escapeAttr(UNVERIFIED_IMPORT_TIP)}">Imported mid-save · not verified. Export again on the source computer.</span>` : '') +
2804
2797
  `<span class="ws-meta ws-registration-status"${p.registrationState === 'unavailable' ? '' : ' hidden'}>${escapeHtml(p.registrationReason || 'Project folder unavailable. Locate or restore it.')}</span>` +
2805
2798
  `<span class="ws-meta ws-registration-location-note"${p.registrationState !== 'unavailable' && p.registrationLocationWarning ? '' : ' hidden'}>${escapeHtml(p.registrationLocationWarning || '')}</span>` +
@@ -3816,6 +3809,9 @@
3816
3809
  const $projectSetupError = document.getElementById('project-setup-error');
3817
3810
  const $projectSetupProvider = document.getElementById('project-setup-provider');
3818
3811
  const $projectSetupKickoffNote = document.getElementById('project-setup-kickoff-note');
3812
+ const $projectSetupBuild = document.getElementById('project-setup-build');
3813
+ const $projectSetupQuickTerms = document.getElementById('project-setup-quick-terms');
3814
+ const $projectSetupBuildLocked = document.getElementById('project-setup-build-locked');
3819
3815
  const $projectSetupCancel = document.getElementById('project-setup-cancel');
3820
3816
  const $projectSetupCreateOnly = document.getElementById('project-setup-create-only');
3821
3817
  const $projectSetupCreate = document.getElementById('project-setup-create');
@@ -4054,6 +4050,38 @@
4054
4050
 
4055
4051
  // Repaint only the AI lines while the dialog waits for a setup; a full render would re-enable the
4056
4052
  // create buttons under the wait.
4053
+ /**
4054
+ * #2521 row 7a: the Model choice is offered only where this dialog starts a read: a Steel model from drawings, with an
4055
+ * AI to start the chat with. Once a submission was sent its choice is fixed, so a retry is the same intake (a changed
4056
+ * choice would be a different one, which the server answers as a conflict).
4057
+ */
4058
+ function projectSetupBuildShown(state, provider) {
4059
+ return !!(state.askCatalogue && provider);
4060
+ }
4061
+ function paintProjectSetupBuild(state, provider) {
4062
+ if (!$projectSetupBuild) return;
4063
+ const shown = projectSetupBuildShown(state, provider);
4064
+ $projectSetupBuild.hidden = !shown;
4065
+ const locked = !!state.submissionId;
4066
+ const mode = (locked ? state.sentBuildMode : state.buildMode) === 'quick' ? 'quick' : 'precise';
4067
+ for (const button of $projectSetupBuild.querySelectorAll('[data-build-mode]')) {
4068
+ button.setAttribute('aria-pressed', String(button.dataset.buildMode === mode));
4069
+ if (locked) button.setAttribute('aria-disabled', 'true');
4070
+ else button.removeAttribute('aria-disabled');
4071
+ }
4072
+ $projectSetupQuickTerms.hidden = mode !== 'quick';
4073
+ $projectSetupBuildLocked.hidden = !locked;
4074
+ if (shown && mode === 'quick') $projectSetupCreateOnly.setAttribute('aria-describedby', 'project-setup-quick-create-only');
4075
+ else $projectSetupCreateOnly.removeAttribute('aria-describedby');
4076
+ }
4077
+
4078
+ function chooseProjectSetupBuildMode(button) {
4079
+ if (!button || !projectSetupState || projectSetupState.busy || projectSetupState.submissionId) return;
4080
+ projectSetupState.buildMode = button.dataset.buildMode === 'quick' ? 'quick' : 'precise';
4081
+ renderProjectSetup();
4082
+ if (projectSetupState.buildMode === 'quick') $projectSetupQuickTerms.scrollIntoView?.({ block: 'nearest' });
4083
+ }
4084
+
4057
4085
  function renderProjectSetupWhileBusy(state) {
4058
4086
  if (projectSetupState !== state) return;
4059
4087
  paintProjectSetupProviders(state, projectSetupProvider(state));
@@ -4088,6 +4116,7 @@
4088
4116
  : 'FloLess stores this project here, and AI starts in this folder.';
4089
4117
  if ($projectSetupName.value !== state.name) $projectSetupName.value = state.name;
4090
4118
  $projectSetupStandard.hidden = !state.askCatalogue;
4119
+ paintProjectSetupBuild(state, provider);
4091
4120
  $projectSetupStandard.querySelectorAll('[data-environment]').forEach((button) => {
4092
4121
  button.setAttribute('aria-pressed', String(button.dataset.environment === state.environment));
4093
4122
  });
@@ -4241,6 +4270,8 @@
4241
4270
  let snapshots = state.snapshots || null;
4242
4271
  if (!snapshots) snapshots = await Promise.all(state.files.map(readFileAsSnapshot));
4243
4272
  state.snapshots = snapshots;
4273
+ // #2521 row 7a: the choice is settled with the first send and every retry repeats it.
4274
+ if (!state.submissionId) state.sentBuildMode = projectSetupBuildShown(state, provider) && state.buildMode === 'quick' ? 'quick' : null;
4244
4275
  const submissionId = state.submissionId || crypto.randomUUID();
4245
4276
  state.submissionId = submissionId;
4246
4277
  rememberProjectChatIntake(submissionId);
@@ -4251,10 +4282,12 @@
4251
4282
  directorySelectionId: state.directory.selectionId,
4252
4283
  snapshots,
4253
4284
  provider,
4285
+ ...(state.sentBuildMode === 'quick' ? { buildMode: 'quick' } : {}),
4254
4286
  });
4255
4287
  const project = result.project;
4256
4288
  state.project = project;
4257
4289
  state.request = result.request;
4290
+ state.buildModeNotice = result.buildModeNotice || null;
4258
4291
  if (!projects.some((item) => item.id === project.id)) {
4259
4292
  projects.unshift(project);
4260
4293
  track('workspace_project_created', { app: state.appId });
@@ -4282,9 +4315,12 @@
4282
4315
  setProjectSetupBusy(false);
4283
4316
  closeProjectSetup({ restoreFocus: false });
4284
4317
  // A General project's chat is Flo's kickoff; its first reply may still be on its way (#2470 R6.4).
4285
- showToast(state.kind === 'general-project'
4318
+ // #2521 row 7a: said from what was queued, never from the button still pressed.
4319
+ if (state.buildModeNotice?.why) showToast(`Project created. ${state.buildModeNotice.why}`, 'warn');
4320
+ else showToast(state.kind === 'general-project'
4286
4321
  ? 'Project created — Flo will help you set it up in AI Chat.'
4287
- : 'Project created — the drawing task is running in AI Chat.', 'ok');
4322
+ : state.request?.buildMode === 'quick' ? 'Project created — the Quick model read is running in AI Chat.'
4323
+ : 'Project created — the drawing task is running in AI Chat.', 'ok');
4288
4324
  }
4289
4325
 
4290
4326
  async function resumeInterruptedProjectChatIntake() {
@@ -4300,7 +4336,9 @@
4300
4336
  await openProject(result.project.id, result.project.app === 'floless-general' ? 'knowledge' : 'drawings');
4301
4337
  await bridge.openChatConversation(result.chat.chatId);
4302
4338
  forgetProjectChatIntake(submissionId);
4303
- showToast('Recovered the project and its AI Chat.', 'ok');
4339
+ // #2521 row 7a: a Quick choice queued Precise is said on recovery too, from the saved receipt.
4340
+ if (result.buildModeNotice?.why) showToast(`Recovered the project and its AI Chat. ${result.buildModeNotice.why}`, 'warn');
4341
+ else showToast('Recovered the project and its AI Chat.', 'ok');
4304
4342
  } catch (error) {
4305
4343
  const code = error && (error.code || error.body && error.body.code);
4306
4344
  if (code === 'project-intake-not-found' || code === 'project-intake-damaged') {
@@ -4345,6 +4383,8 @@
4345
4383
  linkFrom,
4346
4384
  askCatalogue: kind === 'drawings' && templateId === 'steel-model',
4347
4385
  environment: null,
4386
+ // #2521 row 7a: Precise unless the person presses Quick; what was sent is kept in `sentBuildMode`.
4387
+ buildMode: 'precise',
4348
4388
  directory: null,
4349
4389
  name: '',
4350
4390
  nameDirty: false,
@@ -4401,6 +4441,9 @@
4401
4441
  projectSetupState.environment = button.dataset.environment;
4402
4442
  renderProjectSetup();
4403
4443
  });
4444
+ $projectSetupBuild?.addEventListener('click', (event) => {
4445
+ chooseProjectSetupBuildMode(event.target.closest('[data-build-mode]'));
4446
+ });
4404
4447
  $projectSetupProvider?.addEventListener('click', (event) => {
4405
4448
  chooseProjectSetupProvider(event.target.closest('[data-chat-provider]'));
4406
4449
  });
@@ -5212,6 +5255,9 @@
5212
5255
  if (unwanted()) return STAYED_IN_PROJECT;
5213
5256
  if (current?.uuid !== p.uuid) revisionNoteEditorGeneration++;
5214
5257
  current = p;
5258
+ // #2470 R6.6c: whatever editor is still loaded belongs to the project as it was before this open, and the frame is
5259
+ // reset below; until the new document says it is ready, no step message goes to the old one.
5260
+ editorBridge = null;
5215
5261
  // #1890: a new workspace conversation suggests this project's units (the one opened last).
5216
5262
  try { localStorage.setItem('floless:last-project', p.id); } catch { /* private mode: no suggestion */ }
5217
5263
  revitSourceState = null;
@@ -5227,6 +5273,7 @@
5227
5273
  pendingPresenceToast = null;
5228
5274
  exportState = null;
5229
5275
  exportStateFrom = null;
5276
+ exportDrafts = [];
5230
5277
  exportUnits = null; // a new project's units arrive with its export listing; never inherit the last one's
5231
5278
  renderReadinessState = null;
5232
5279
  let sourceStateProbe = null;
@@ -5274,7 +5321,7 @@
5274
5321
  // A sourceless project (General, #2470) has no Model, Drawings, Exports or History step; a step carried
5275
5322
  // over from another project lands on its first step instead of a pane it does not have.
5276
5323
  if (d.sourceless && !d.steps.some((step) => step.key === initialStep)) initialStep = d.steps[0].key;
5277
- if ((d.filter || isModelSourceProject(p)) && ['model', 'exports', 'history'].includes(initialStep)) {
5324
+ if ((d.filter || isModelSourceProject(p)) && ['model', 'rfis', 'exports', 'history'].includes(initialStep)) {
5278
5325
  pendingPresenceStep = { projectId: p.id, step: initialStep };
5279
5326
  }
5280
5327
  // The LIVE app id, deliberately: the frames address the server with it (contract reads, saves),
@@ -5312,7 +5359,6 @@
5312
5359
  // first actionable stage, and restore the destination only after an explicit `model` answer.
5313
5360
  setStep(pendingPresenceStep ? 'drawings' : initialStep);
5314
5361
  applyMode();
5315
- syncWorkspaceGuide(); // point the shared beacon at THIS project's document lifecycle
5316
5362
  }
5317
5363
 
5318
5364
  /**
@@ -5485,6 +5531,9 @@
5485
5531
  }
5486
5532
  function closeProject() {
5487
5533
  openNavSeq++;
5534
+ // #2470 R6.6c: an editor that hosts the RFIs step is away now (it may stay loaded in the hidden frame).
5535
+ if (wsApp()?.rfisInEditor) postStepToEditor(null);
5536
+ editorBridge = null;
5488
5537
  current = null;
5489
5538
  approvalStateGen++;
5490
5539
  approvalState = { status: 'unavailable', review: null, pendingCount: 0, headVersion: null, error: '' };
@@ -5492,6 +5541,7 @@
5492
5541
  closeApprovalReview();
5493
5542
  exportState = null;
5494
5543
  exportStateFrom = null;
5544
+ exportDrafts = [];
5495
5545
  exportUnits = null; // a new project's units arrive with its export listing; never inherit the last one's
5496
5546
  renderReadinessState = null;
5497
5547
  resetRevisionState();
@@ -5513,7 +5563,7 @@
5513
5563
  projectContractLifecycle = 'unknown'; exportsHasModel = false; modelPresenceGen++; modelPresenceProbe = null; pendingPresenceStep = null;
5514
5564
  if (pendingPresenceToast) pendingPresenceToast();
5515
5565
  pendingPresenceToast = null;
5516
- closeProjMenu(); applyMode(); syncWorkspaceGuide(); // revision state cleared by resetRevisionState() above
5566
+ closeProjMenu(); applyMode(); // revision state cleared by resetRevisionState() above
5517
5567
  }
5518
5568
  document.getElementById('ws-back').addEventListener('click', (e) => { void leaveProjectToList(e.currentTarget); });
5519
5569
 
@@ -6006,7 +6056,7 @@
6006
6056
 
6007
6057
  function stageGateFor(step) {
6008
6058
  const d = wsApp();
6009
- if (!d || !d.filter || !['model', 'exports', 'history'].includes(step)) return '';
6059
+ if (!d || !d.filter || !['model', 'rfis', 'exports', 'history'].includes(step)) return '';
6010
6060
  const initialRead = revCardReq && isInitialRevisionRead(revCardReq);
6011
6061
  const waitingForInitial = initialRead && lastRevState === 'pending';
6012
6062
  const stagedInitial = initialRead && lastRevState === 'staged';
@@ -6035,10 +6085,12 @@
6035
6085
  if (waitingForInitial && revCardReq?.prepassReady) return `Check steel, member marks, grids, dimensions, and relevant callouts. Ask in AI Chat on the left if you need help. ${readyFilterNextStep(revCardReq)}`;
6036
6086
  if (waitingForInitial && revCardReq?.preparationRetryable) return `Steel Filter preparation was interrupted. Your drawings are still attached. Return to the same ${readSessionName(revCardReq)} and retry preparation for this same request.`;
6037
6087
  if (waitingForInitial) return `The initial drawing read is waiting for ${readRunsInChat(revCardReq) ? 'AI Chat' : 'your terminal AI'}. The model unlocks after you review the Drawing Filter and press Save filter.`;
6088
+ if (projectContractLifecycle === 'filter-checkpoint' && !revisionListKnown) return 'Checking the drawing read. Stages open once FloLess knows where it stands.';
6038
6089
  if (projectContractLifecycle === 'filter-checkpoint') return 'Attach the drawing set again in Drawing Filter to restart the read. The earlier request is no longer available to receive a saved filter.';
6039
6090
  return 'Read and save a Drawing Filter first. The model will unlock after the first drawing read.';
6040
6091
  }
6041
6092
  if (waitingForInitial) return `The ${step === 'exports' ? 'steel model' : 'first model'} must be ready before ${step === 'exports' ? 'exports' : 'history'} is available.`;
6093
+ if (projectContractLifecycle === 'filter-checkpoint' && !revisionListKnown) return 'Checking the drawing read. Stages open once FloLess knows where it stands.';
6042
6094
  if (projectContractLifecycle === 'filter-checkpoint') return `Attach the drawing set again in Drawing Filter before opening ${step === 'exports' ? 'Exports' : 'History'}. The earlier request can no longer continue.`;
6043
6095
  return `Create the first steel model before opening ${step === 'exports' ? 'Exports' : 'History'}.`;
6044
6096
  }
@@ -6183,6 +6235,10 @@
6183
6235
  ? `Drawing read is paused in AI Chat · ${OPEN_AI_CHAT} and tell it to continue the drawing read.`
6184
6236
  : waitingForInitial
6185
6237
  ? 'Drawing read not started · Open Requests — if Start in AI Chat is shown, choose it; otherwise copy the request into Claude Code or Codex. Then return to review and save the Drawing Filter.'
6238
+ : projectContractLifecycle === 'filter-checkpoint' && !revisionListKnown
6239
+ ? (revRequestsFailed
6240
+ ? 'Checking the drawing read · FloLess cannot reach it right now and keeps trying. Your drawings are still attached.'
6241
+ : 'Checking the drawing read · FloLess is looking up this project’s drawing request.')
6186
6242
  : projectContractLifecycle === 'filter-checkpoint'
6187
6243
  ? 'Drawing read needs restarting · The earlier drawing request is no longer available. Attach the drawing set again in Drawing Filter to restart the read.'
6188
6244
  : 'Start in Drawing Filter by attaching a PDF drawing set. The Model, Exports, and History stages unlock after the first steel model is created.';
@@ -6195,7 +6251,7 @@
6195
6251
  function deferStageUntilLifecycle(s) {
6196
6252
  const d = wsApp();
6197
6253
  if (!current || !d?.filter || projectContractLifecycle !== 'unknown'
6198
- || !['model', 'exports', 'history'].includes(s)) return false;
6254
+ || !['model', 'rfis', 'exports', 'history'].includes(s)) return false;
6199
6255
  pendingPresenceStep = { projectId: current.id, step: s };
6200
6256
  const projectId = current.id;
6201
6257
  if (pendingPresenceToast) pendingPresenceToast();
@@ -6254,6 +6310,9 @@
6254
6310
  showToast(lockedReason, 'warn');
6255
6311
  return;
6256
6312
  }
6313
+ // #2521 row 7b: a design-set read panel's Model preset was read when it opened; leaving Knowledge drops it, so coming
6314
+ // back reads the model's mode afresh instead of submitting a choice the model may have moved on from.
6315
+ if (s !== 'knowledge' && kbDsPanel && kbDsPanel.kind === 'read') kbDsPanel = null;
6257
6316
  currentStep = s;
6258
6317
  $stepTabs.querySelectorAll('button').forEach((b) => {
6259
6318
  const on = b.dataset.step === s;
@@ -6264,18 +6323,22 @@
6264
6323
  // step shows a lightweight placeholder pane instead of an about:blank iframe.
6265
6324
  const d = wsApp();
6266
6325
  const drawingsHasFrame = !!(d && d.filter);
6326
+ // #2470 R6.6c: a kind whose RFIs live in its editor shows the model frame on the RFIs step too.
6327
+ const rfisInEditor = !!(d && d.rfisInEditor);
6267
6328
  for (const [k, f] of Object.entries(frames)) {
6268
- const show = k === s && (k !== 'drawings' || drawingsHasFrame);
6329
+ const show = (k === s || (k === 'model' && s === 'rfis' && rfisInEditor)) && (k !== 'drawings' || drawingsHasFrame);
6269
6330
  f.hidden = !show;
6270
6331
  if (show && !f.dataset.loaded && f.dataset.want) { f.src = f.dataset.want; f.dataset.loaded = '1'; }
6271
6332
  // Coming back to an editor that stayed loaded while hidden: tell it, so it can read again what changed on
6272
6333
  // another step meanwhile (the Drawing Checker's references after a Knowledge change, #2482). Others ignore it.
6334
+ // An editor that hosts the RFIs step hears about every step instead, below.
6273
6335
  else if (show && k === 'model' && f.dataset.loaded) {
6274
6336
  const project = typeof current !== 'undefined' ? current : null;
6275
- try { if (project) f.contentWindow?.postMessage({ type: 'floless:step-shown', step: s, projectId: project.id }, location.origin); }
6337
+ try { if (project && !rfisInEditor) f.contentWindow?.postMessage({ type: 'floless:step-shown', step: s, projectId: project.id }, location.origin); }
6276
6338
  catch { /* the frame is between documents */ }
6277
6339
  }
6278
6340
  }
6341
+ if (rfisInEditor) postStepToEditor(s);
6279
6342
  if (window.flolessLeftPane) {
6280
6343
  window.flolessLeftPane.setWorkspaceModelVisible(s === 'model');
6281
6344
  }
@@ -6339,6 +6402,15 @@
6339
6402
  const project = typeof current !== 'undefined' ? current : null;
6340
6403
  if (showWorkflows && project && window.flolessProjectWorkflows) window.flolessProjectWorkflows.render($workflowsPane, project);
6341
6404
  }
6405
+ // #2470 R6.6: RFIs is a shell-rendered pane too: the project's correspondence RFIs (project-rfis.js). Its module is
6406
+ // reached through globalThis, so a harness that lifts setStep without it still runs.
6407
+ const $rfisPane = document.getElementById('ws-rfis');
6408
+ if ($rfisPane) {
6409
+ const showRfis = s === 'rfis' && !rfisInEditor;
6410
+ $rfisPane.hidden = !showRfis;
6411
+ const project = typeof current !== 'undefined' ? current : null;
6412
+ if (showRfis && project) globalThis.flolessProjectRfis?.render?.($rfisPane, project);
6413
+ }
6342
6414
  // #2470 R6.7: Modules is a shell-rendered pane too: the module projects linked to this one (project-modules.js).
6343
6415
  // Queried here for the same reason as the Pages pane above.
6344
6416
  const $modulesPane = document.getElementById('ws-modules');
@@ -6348,6 +6420,15 @@
6348
6420
  const project = typeof current !== 'undefined' ? current : null;
6349
6421
  if (showModules && project && window.flolessProjectModules) window.flolessProjectModules.render($modulesPane, project);
6350
6422
  }
6423
+ // #2470 R6.5: a General project's History is a shell-rendered pane too: its journal (project-history.js). Reached
6424
+ // through globalThis, like the RFIs one, so a harness that lifts setStep without it still runs.
6425
+ const $journalPane = document.getElementById('ws-journal');
6426
+ if ($journalPane) {
6427
+ const showJournal = s === 'journal';
6428
+ $journalPane.hidden = !showJournal;
6429
+ const project = typeof current !== 'undefined' ? current : null;
6430
+ if (showJournal && project) globalThis.flolessProjectHistory?.render?.($journalPane, project);
6431
+ }
6351
6432
  // Knowledge is a shell-rendered pane too: the project's Knowledge Base (References column).
6352
6433
  const showKnowledge = s === 'knowledge';
6353
6434
  $wsKnowledge.hidden = !showKnowledge;
@@ -6398,6 +6479,69 @@
6398
6479
  || !['clean', 'dirty', 'saving', 'error', 'conflict'].includes(message.state)) return;
6399
6480
  modelContractSaveState = { projectId: current.id, appId: current.app, state: message.state, generation: message.generation };
6400
6481
  });
6482
+ /*
6483
+ * #2470 R6.6c — the steel editor hosts the RFIs step (plan §10). The shell tells the editor which step is showing on
6484
+ * every change (`floless:step-shown`, with a rising `seq`; `step: null` when the project closes); the editor says when
6485
+ * it is ready (`floless:editor-ready`, answered with the current step), and may ask to switch between its two steps
6486
+ * (`floless:rfis-request-step`, model or rfis only, answered with `floless:rfis-step-ack`). Only from this project's
6487
+ * own model frame: the Edit-contract overlay and a direct URL run the RFI page locally and never move these steps.
6488
+ */
6489
+ let editorStepSeq = 0;
6490
+ /** The editor document that completed the ready handshake for the project on screen — the only one that may navigate. */
6491
+ let editorBridge = null;
6492
+ /** The editor request being carried out right now: the step message it causes names it, so the editor can tell its
6493
+ * own older request's echo from the person choosing a step. */
6494
+ let editorStepCause = null;
6495
+ const sameUuid = (a, b) => String(a || '').toLowerCase() === String(b || '').toLowerCase();
6496
+ function postStepToEditor(step) {
6497
+ const win = frames.model?.contentWindow;
6498
+ // Only the document that said it is ready for the project on screen hears the step. A project reopened while its
6499
+ // old editor is still loaded would otherwise tell that old document to show RFIs and start a read the reset below
6500
+ // it then cuts off; the new document asks for the step itself once it is ready.
6501
+ if (!win || !frames.model.dataset.loaded || !editorBridge || editorBridge.win !== win) return;
6502
+ const project = typeof current !== 'undefined' ? current : null;
6503
+ try {
6504
+ win.postMessage({ type: 'floless:step-shown', step, seq: ++editorStepSeq,
6505
+ projectId: project ? project.id : null, projectUuid: project ? (project.uuid || null) : null,
6506
+ ...(editorStepCause ? { cause: editorStepCause } : {}) }, location.origin);
6507
+ } catch (error) {
6508
+ // The frame is between documents: the document that loads next sends its own ready and hears the step then.
6509
+ console.warn('[workspaces] could not tell the steel editor which step shows', error);
6510
+ }
6511
+ }
6512
+ window.addEventListener('message', (event) => {
6513
+ const message = event.data;
6514
+ if (event.origin !== location.origin || event.source !== frames.model?.contentWindow || !message || !current) return;
6515
+ const d = wsApp();
6516
+ if (!d || !d.rfisInEditor || message.projectId !== current.id) return;
6517
+ if (message.type === 'floless:editor-ready') {
6518
+ // This document now owns the bridge for this project incarnation; it learns the uuid from the step message.
6519
+ editorBridge = { win: event.source, projectId: current.id, projectUuid: current.uuid || null };
6520
+ postStepToEditor(currentStep);
6521
+ return;
6522
+ }
6523
+ if (message.type !== 'floless:rfis-request-step') return;
6524
+ // Only the document that said it is ready, for this incarnation of this project, may move the steps.
6525
+ if (!editorBridge || editorBridge.win !== event.source || editorBridge.projectId !== current.id
6526
+ || !sameUuid(editorBridge.projectUuid, current.uuid) || !sameUuid(message.projectUuid, current.uuid)) return;
6527
+ const reply = (ok, reason) => {
6528
+ try {
6529
+ event.source.postMessage({ type: 'floless:rfis-step-ack', requestId: message.requestId, ok, step: currentStep,
6530
+ projectId: current.id, projectUuid: current.uuid || null, ...(reason ? { reason } : {}) }, location.origin);
6531
+ } catch (error) { console.warn('[workspaces] could not answer the steel editor', error); }
6532
+ };
6533
+ if (message.step !== 'rfis' && message.step !== 'model') { reply(false, 'That step can’t be opened from the model.'); return; }
6534
+ editorStepCause = typeof message.requestId === 'string' ? message.requestId : null;
6535
+ try {
6536
+ if (currentStep !== message.step) chooseStep(message.step);
6537
+ // Already there (the editor disagreed with the shell): say the step again, so both agree.
6538
+ else postStepToEditor(currentStep);
6539
+ } finally { editorStepCause = null; }
6540
+ // chooseStep may wait for the project's stages or refuse with its own toast; the editor follows `step-shown`.
6541
+ if (currentStep === message.step) reply(true);
6542
+ else reply(false, 'That step isn’t available yet. FloLess said why in its notice.');
6543
+ });
6544
+
6401
6545
  // The Drawing Checker's "Use the design set" sends a person to this project's Knowledge step, where the design
6402
6546
  // set lives (epic #2399 0d-dc). Only from the editor frame of the project on screen, and only to Knowledge.
6403
6547
  window.addEventListener('message', (event) => {
@@ -6407,50 +6551,117 @@
6407
6551
  setStep('knowledge');
6408
6552
  });
6409
6553
  const approvalPhaseText = {
6410
- saving: 'Saving model edits…', comparing: 'Comparing changes…', approving: 'Approving and compiling…',
6411
- reconciling: 'Reconciling approval…', approved: 'Approved', failed: 'Nothing was approved.', stale: 'The review changed.',
6554
+ saving: 'Saving your model edits…', comparing: 'Comparing with the approved version…', approving: 'Approving and compiling…',
6555
+ reconciling: 'Checking whether the approval finished…', approved: 'Approved', failed: 'Nothing was approved.', stale: 'The review changed.',
6412
6556
  abandoned: 'Nothing was approved. The previous approval attempt ended safely.',
6413
6557
  };
6414
- const approvalDismissible = (phase) => ['saving', 'comparing', 'ready', 'failed', 'stale', 'approved', 'abandoned', 'recovery-close'].includes(phase);
6558
+ // Checking the result never needs the person: it may be closed, and FloLess keeps checking for them.
6559
+ const approvalDismissible = (phase) => ['saving', 'comparing', 'ready', 'failed', 'stale', 'approved', 'abandoned', 'recovery-close', 'reconciling'].includes(phase);
6415
6560
 
6416
6561
  function setApprovalPhase(phase, message) {
6562
+ // Long work shows WHERE it is, not one spinner: each busy phase is a step in a short list, so a slow
6563
+ // compile reads as progress and never as a hang (owner report 2026-10-24, the Camden approval).
6564
+ const APPROVAL_STEP_LABELS = Object.freeze({
6565
+ save: 'Save your model edits', compare: 'Compare with the approved version',
6566
+ approve: 'Approve and compile', confirm: 'Confirm the result', recover: 'Check the previous approval attempt',
6567
+ });
6568
+ const APPROVAL_PHASE_STEP = Object.freeze({ saving: 'save', comparing: 'compare', approving: 'approve', reconciling: 'confirm' });
6569
+ const APPROVAL_FLOW_STEPS = Object.freeze({
6570
+ prepare: ['save', 'compare'], approve: ['save', 'compare', 'approve', 'confirm'], recover: ['recover'],
6571
+ });
6572
+ const approvalBusy = (phase) => ['saving', 'comparing', 'approving', 'reconciling'].includes(phase);
6573
+ const formatApprovalElapsed = (ms) => { const s = Math.max(0, Math.floor(ms / 1000)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; };
6574
+
6575
+ function approvalProgressHtml(st, phase, headline) {
6576
+ const flow = APPROVAL_FLOW_STEPS[st.flow] || APPROVAL_FLOW_STEPS.prepare;
6577
+ const activeKey = st.flow === 'recover' ? 'recover' : APPROVAL_PHASE_STEP[phase];
6578
+ const activeIndex = Math.max(0, flow.indexOf(activeKey));
6579
+ const rows = flow.map((key, index) => {
6580
+ const state = index < activeIndex ? 'done' : index === activeIndex ? 'active' : 'waiting';
6581
+ const spoken = state === 'done' ? 'done' : state === 'active' ? 'in progress' : 'waiting';
6582
+ return `<li class="approval-step is-${state}"${state === 'active' ? ' aria-current="step"' : ''}><span class="approval-step-mark" aria-hidden="true"></span>`
6583
+ + `<span class="approval-step-label">${escapeHtml(APPROVAL_STEP_LABELS[key])}</span><span class="sr-only"> (${spoken})</span></li>`;
6584
+ }).join('');
6585
+ const what = st.flow === 'approve' && st.approvingWhat ? `<p class="approval-progress-what">${escapeHtml(st.approvingWhat)}</p>` : '';
6586
+ return `<div class="approval-progress"><div class="approval-progress-head"><b>${escapeHtml(headline)}</b>`
6587
+ + '<span class="approval-elapsed" aria-hidden="true"></span></div>'
6588
+ + `${what}<ol class="approval-steps">${rows}</ol><p class="approval-progress-note" hidden></p></div>`;
6589
+ }
6590
+
6591
+ // The elapsed time and the "this is normal" reassurance. The timer is never announced; each
6592
+ // reassurance is, once. Only a real DOM gets a ticker (there is nothing to update otherwise).
6593
+ function tickApprovalProgress() {
6594
+ const st = approvalDialogState;
6595
+ if (!st || !approvalBusy(st.phase) || typeof $approvalBody?.querySelector !== 'function') return;
6596
+ const elapsed = Date.now() - (st.busySince || Date.now());
6597
+ const clock = $approvalBody.querySelector('.approval-elapsed');
6598
+ if (clock) clock.textContent = elapsed >= 3000 ? formatApprovalElapsed(elapsed) : '';
6599
+ const note = $approvalBody.querySelector('.approval-progress-note');
6600
+ const text = st.phase === 'reconciling'
6601
+ ? (elapsed >= 4000 ? 'You can close this window. FloLess keeps checking and tells you when it knows.' : '')
6602
+ : elapsed >= 45000 ? 'Still working. Large models can take a few minutes.'
6603
+ : elapsed >= 10000 ? 'Large models can take a minute. Keep FloLess open.' : '';
6604
+ if (note) { note.textContent = text; note.hidden = !text; }
6605
+ if (text && st.announcedNote !== text && $approvalLive) { st.announcedNote = text; $approvalLive.textContent = text; }
6606
+ }
6607
+
6417
6608
  const st = approvalDialogState;
6418
6609
  if (!st) return;
6419
6610
  const changed = st.phase !== phase;
6611
+ const wasBusy = approvalBusy(st.phase);
6420
6612
  st.phase = phase;
6421
6613
  if ($approvalRevisionNote) $approvalRevisionNote.hidden = !['ready', 'failed'].includes(phase);
6422
6614
  // Recovery may be dismissed, but it must never unlock a second mutation while the durable
6423
6615
  // outcome is pending or unreadable. Dismissibility and mutation safety are separate concerns.
6424
- const locked = !approvalDismissible(phase) || ['abandoned', 'recovery-close'].includes(phase);
6616
+ const locked = !approvalDismissible(phase) || ['abandoned', 'recovery-close', 'reconciling'].includes(phase);
6425
6617
  const cancelVisible = ['saving', 'comparing', 'ready', 'failed', 'stale'].includes(phase);
6618
+ const closeVisible = ['approved', 'abandoned', 'recovery-close'].includes(phase) || phase === 'reconciling';
6426
6619
  const active = document.activeElement;
6427
6620
  const activeControlWillHide = (active === $approvalCancel && !cancelVisible)
6428
6621
  || (active === $approvalRetry && phase !== 'failed')
6429
6622
  || (active === $approvalReload && phase !== 'stale')
6430
- || (active === $approvalClose && !['approved', 'abandoned', 'recovery-close'].includes(phase))
6623
+ || (active === $approvalClose && !closeVisible)
6431
6624
  || (active === $approvalConfirm && !['ready', 'abandoned'].includes(phase));
6432
6625
  if (activeControlWillHide || (locked && active && $approvalBody.contains(active))) $approvalDialog.focus();
6433
- if (changed && $approvalLive) $approvalLive.textContent = message || approvalPhaseText[phase] || '';
6434
- $approvalBody?.setAttribute('aria-busy', String(['saving', 'comparing', 'approving', 'reconciling'].includes(phase)));
6626
+ const busy = approvalBusy(phase);
6627
+ // Also when a dialog opens straight into a busy phase (a reopened check), so its clock really starts.
6628
+ if (busy && (!wasBusy || !st.busySince)) { st.busySince = Date.now(); st.announcedNote = ''; }
6629
+ const flow = APPROVAL_FLOW_STEPS[st.flow] || APPROVAL_FLOW_STEPS.prepare;
6630
+ const stepIndex = flow.indexOf(st.flow === 'recover' ? 'recover' : APPROVAL_PHASE_STEP[phase]);
6631
+ const busyText = message || approvalPhaseText[phase];
6632
+ // One source for the subtitle, the step list and what a screen reader hears, so they cannot disagree.
6633
+ const subText = busy && flow.length > 1 && stepIndex >= 0 ? `Step ${stepIndex + 1} of ${flow.length} · ${busyText}` : busyText;
6634
+ if (changed && $approvalLive) $approvalLive.textContent = busy ? subText : (message || approvalPhaseText[phase] || '');
6635
+ $approvalBody?.setAttribute('aria-busy', String(busy));
6435
6636
  $approvalCancel.hidden = !cancelVisible;
6436
6637
  $approvalRetry.hidden = phase !== 'failed';
6437
6638
  $approvalReload.hidden = phase !== 'stale';
6438
- $approvalClose.hidden = !['approved', 'abandoned', 'recovery-close'].includes(phase);
6439
- $approvalConfirm.hidden = !['ready', 'abandoned'].includes(phase);
6639
+ $approvalClose.hidden = !closeVisible;
6640
+ // While the approval runs, its button stays where it was and says what is happening, so the footer
6641
+ // never collapses into an empty strip.
6642
+ const working = phase === 'approving';
6643
+ $approvalConfirm.hidden = !['ready', 'abandoned'].includes(phase) && !working;
6644
+ $approvalConfirm.classList?.toggle('is-working', working);
6645
+ if (working) { $approvalConfirm.disabled = true; $approvalConfirm.innerHTML = '<span class="rtn-spinner" aria-hidden="true"></span>Approving…'; }
6440
6646
  // Unlocking never re-enables a control the review blocked with a reason (nothing drawn, or a
6441
6647
  // refusal no new choice can fix): it stays disabled, and focus skips it.
6442
6648
  $approvalBody.querySelectorAll('[data-approval-decision],[data-approval-conflict],[data-approval-discard],[data-approval-open-audit]').forEach((node) => { node.disabled = locked || node.hasAttribute('data-blocked-reason'); });
6443
- if (phase === 'saving' || phase === 'comparing') {
6444
- const text = message || approvalPhaseText[phase];
6445
- $approvalBody.innerHTML = `<div class="approval-loading"><span class="rtn-spinner" aria-hidden="true"></span><span aria-hidden="true">${escapeHtml(text)}</span></div>`;
6446
- $approvalSub.textContent = phase === 'saving' ? 'Finishing the model edits already on screen…' : 'Loading the server comparison…';
6447
- } else if (phase === 'approving' || phase === 'reconciling') {
6448
- $approvalSub.textContent = message || approvalPhaseText[phase];
6449
- } else if (['approved', 'failed', 'stale', 'abandoned', 'recovery-close'].includes(phase)) {
6450
- // A terminal/recovery outcome replaces the in-flight phase visibly as well as in the live region.
6451
- // Leaving "Approving and compiling…" above an Approved/failed body makes a finished command look
6452
- // stuck — the exact ambiguity this state machine exists to remove.
6453
- $approvalSub.textContent = message || approvalPhaseText[phase] || '';
6649
+ if (busy) {
6650
+ $approvalBody.innerHTML = approvalProgressHtml(st, phase, busyText);
6651
+ $approvalSub.textContent = subText;
6652
+ if (!st.ticker && typeof $approvalBody.querySelector === 'function') {
6653
+ st.ticker = setInterval(tickApprovalProgress, 1000);
6654
+ // A display ticker never keeps a non-browser host alive (Node test harnesses run this code).
6655
+ st.ticker?.unref?.();
6656
+ }
6657
+ } else {
6658
+ if (st.ticker) { clearInterval(st.ticker); st.ticker = null; }
6659
+ if (['approved', 'failed', 'stale', 'abandoned', 'recovery-close'].includes(phase)) {
6660
+ // A terminal/recovery outcome replaces the in-flight phase visibly as well as in the live region.
6661
+ // Leaving "Approving and compiling…" above an Approved/failed body makes a finished command look
6662
+ // stuck — the exact ambiguity this state machine exists to remove.
6663
+ $approvalSub.textContent = message || approvalPhaseText[phase] || '';
6664
+ }
6454
6665
  }
6455
6666
  }
6456
6667
 
@@ -6547,15 +6758,81 @@
6547
6758
  const approvalRefusalDetail = (sentence) => String(sentence || '').replace(/\s*Nothing was approved\.\s*/g, ' ').trim();
6548
6759
  /** Refusals whose sentence the server writes for people. Any other error text (a bake or compile
6549
6760
  * message, an internal conflict) stays behind the generic copy instead of reaching the screen. */
6550
- const APPROVAL_REASON_CODES = ['tekla-approval-refused', 'grant-unavailable', ...IMPORT_FINDINGS_REFUSAL_CODES];
6761
+ const APPROVAL_REASON_CODES = ['tekla-approval-refused', 'grant-unavailable', 'approval-nothing-exportable', ...IMPORT_FINDINGS_REFUSAL_CODES];
6551
6762
  function knownApprovalFailureReason(error) {
6552
6763
  const body = error && error.body;
6553
6764
  if (!body || typeof body.error !== 'string' || !body.error.trim()) return '';
6554
6765
  return APPROVAL_REASON_CODES.includes(body.code) ? body.error.trim() : '';
6555
6766
  }
6767
+ /** The raw error, for the Technical details disclosure only: never the headline of a notice. */
6768
+ function approvalTechnicalDetail(error) {
6769
+ const body = error && error.body;
6770
+ const text = String((body && (body.error || body.message)) || (error && error.message) || '').trim().slice(0, 300);
6771
+ const code = body && typeof body.code === 'string' ? body.code : '';
6772
+ // What AWARE itself printed, when the server passed it on (a build refusal): the line that says why.
6773
+ const aware = body && typeof body.reason === 'string' ? body.reason.trim().split(/\r?\n/).find((line) => line.trim()) || '' : '';
6774
+ return [text, code && !text.includes(code) ? `(${code})` : '', error && error.status ? `HTTP ${error.status}` : '',
6775
+ aware && !text.includes(aware) ? `— ${aware.trim().slice(0, 300)}` : ''].filter(Boolean).join(' ');
6776
+ }
6777
+ /**
6778
+ * #2767: a review or approval the server REFUSED, in the person's words: the server's own sentence when it
6779
+ * wrote one (`userMessage`, or a refusal code whose sentence is written for people), else plain words for
6780
+ * the kind of refusal, each with what to do next. The raw text goes under Technical details only.
6781
+ * A sentence the server wrote for people is always said, whatever the status. Otherwise null when there
6782
+ * was no answer or the server failed (5xx), so only an attempt that really was interrupted is described
6783
+ * as one. Any other refusal (`kind: 'other'`, e.g. a 409 or a 400 about the stored model) is said in
6784
+ * general words; the caller decides whether it outranks a plain retry.
6785
+ */
6786
+ function approvalRefusalOf(error) {
6787
+ const body = error && error.body;
6788
+ const status = Number(error && error.status);
6789
+ if (!body || typeof body !== 'object' || !Number.isInteger(status) || status < 400) return null;
6790
+ const technical = approvalTechnicalDetail(error);
6791
+ const written = typeof body.userMessage === 'string' && body.userMessage.trim() ? body.userMessage.trim() : knownApprovalFailureReason(error);
6792
+ if (written) {
6793
+ // A sentence that starts a notice starts with a capital, whichever route wrote it.
6794
+ const reason = approvalRefusalDetail(written);
6795
+ return { reason: reason.charAt(0).toUpperCase() + reason.slice(1), next: '', technical };
6796
+ }
6797
+ if (status === 401) {
6798
+ return { reason: 'This computer is signed out, so FloLess could not approve this model.', next: 'Sign in again, then try again.', technical };
6799
+ }
6800
+ if (status === 403) {
6801
+ return { reason: 'FloLess couldn’t confirm that this computer may approve this project.',
6802
+ next: 'Sign in again, then try again. If that doesn’t help, check that your plan includes this module, or use Report an issue.', technical };
6803
+ }
6804
+ // Only a build AWARE refused is called one (the route's other 422s are not about the workflow).
6805
+ if (body.code === 'approval-build-failed') {
6806
+ return { reason: 'FloLess couldn’t build the workflow from this model, so it stopped before approving anything.',
6807
+ next: 'Trying again will probably give the same result. Ask the AI in the chat what went wrong, or use Report an issue; Technical details below say what FloLess saw.', technical };
6808
+ }
6809
+ if (status >= 500) return null;
6810
+ return { kind: 'other', reason: 'FloLess couldn’t approve this model as it is now, so it stopped before approving anything.',
6811
+ next: 'Start a new review to try again. If it happens again, use Report an issue; Technical details below say what FloLess saw.', technical };
6812
+ }
6813
+ /** The body of a refusal notice: the reason, what to do next, and the raw text behind a disclosure. */
6814
+ function approvalRefusalNoticeHtml(headline, refusal) {
6815
+ const tech = refusal.technical && refusal.technical !== refusal.reason
6816
+ ? `<details class="approval-tech"><summary>Technical details</summary><div><span>${escapeHtml(refusal.technical)}</span></div></details>` : '';
6817
+ return `<div class="approval-notice approval-notice-error" role="alert" data-approval-refusal><b>${escapeHtml(headline)}</b> `
6818
+ + `<p>${escapeHtml(refusal.reason)}${refusal.next ? ` ${escapeHtml(refusal.next)}` : ''}</p>${tech}</div>`;
6819
+ }
6556
6820
 
6557
6821
  function renderApprovalReview() {
6558
6822
  if (!approvalDialogState) return;
6823
+ /** A contract key as words: `read_notes` -> "read notes". */
6824
+ const approvalKeyWords = (key) => key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
6825
+
6826
+ /** The answer to "what does approving do": which version this becomes and what it replaces. */
6827
+ function approvalVersionCardHtml(review) {
6828
+ const mf = review.moveForward;
6829
+ const lead = mf ? (mf.replacesLatest ? `This replaces approved v${mf.toVersion}.` : `Your changes go on top of approved v${mf.toVersion} as the next approved version.`)
6830
+ : review.base ? `This becomes the next approved version, after approved v${review.base.version}.`
6831
+ : 'This becomes the first approved version of this model.';
6832
+ return `<div class="approval-version-card"><b>${escapeHtml(lead)}</b>`
6833
+ + '<p>Approved exports and the compiled workflow use the approved version. You can keep editing the working copy afterwards.</p></div>';
6834
+ }
6835
+
6559
6836
  const review = approvalDialogState.review;
6560
6837
  const groups = Array.isArray(review.groups) ? review.groups : [];
6561
6838
  const findings = review.importFindings && Number(review.importFindings.open) > 0 ? review.importFindings : null;
@@ -6575,15 +6852,29 @@
6575
6852
  ? review.moveForward.replacesLatest
6576
6853
  ? `This model will replace v${review.moveForward.toVersion} as the approved version`
6577
6854
  : `Your changes from v${review.moveForward.fromVersion} will be applied on top of approved v${review.moveForward.toVersion}`
6578
- : review.base ? `Compared with approved v${review.base.version}` : 'First approval · full-model baseline';
6579
- $approvalImpact.textContent = [review.summary, ...(Array.isArray(review.cautions) ? review.cautions : [])].filter(Boolean).join(' ');
6855
+ : review.base ? `Compared with approved v${review.base.version}` : 'First approval of this model';
6856
+ // A whole-model review says what it is in its version card; repeating the summary above it only adds noise.
6857
+ $approvalImpact.textContent = [review.selective === false ? '' : review.summary, ...(Array.isArray(review.cautions) ? review.cautions : [])].filter(Boolean).join(' ');
6858
+ const firstApproval = !review.base && !review.moveForward;
6580
6859
  const groupHtml = groups.map((group) => {
6581
6860
  const picked = decisions[group.id];
6861
+ // A value reads as a person would say it: a counted summary, a word or a number, never raw JSON.
6862
+ // A first approval has nothing before it, so it shows what the model now holds, not "— → value".
6863
+ const factValue = (value) => value === undefined ? '—'
6864
+ : value && typeof value === 'object' && typeof value.summary === 'string' ? value.summary
6865
+ // A small list or record is counted too: raw JSON never reaches the person, at any size.
6866
+ : Array.isArray(value) ? `${value.length.toLocaleString('en-US')} item${value.length === 1 ? '' : 's'}`
6867
+ : value && typeof value === 'object' ? `${Object.keys(value).length} field${Object.keys(value).length === 1 ? '' : 's'}`
6868
+ : typeof value === 'string' ? value : typeof value === 'number' || typeof value === 'boolean' ? String(value) : JSON.stringify(value);
6582
6869
  const facts = Array.isArray(group.technicalFacts) && group.technicalFacts.length
6583
- ? `<details class="approval-tech"><summary>Technical details</summary>${group.technicalFacts.map((fact) => `<div><b>${escapeHtml(String(fact.label || 'Detail'))}</b> <span>${escapeHtml(String(JSON.stringify(fact.before) ?? '—'))} → ${escapeHtml(String(JSON.stringify(fact.after) ?? '—'))}</span></div>`).join('')}</details>` : '';
6870
+ ? `<details class="approval-tech"><summary>Technical details</summary>${group.technicalFacts.map((fact) => `<div><b>${escapeHtml(approvalKeyWords(String(fact.label || 'Detail')))}</b> <span>${escapeHtml(firstApproval && fact.before === undefined ? factValue(fact.after) : `${factValue(fact.before)} → ${factValue(fact.after)}`)}</span></div>`).join('')}</details>` : '';
6871
+ // Nothing is replaced by a first approval, so a risk pill there would only alarm.
6872
+ const riskPill = firstApproval && review.selective === false ? ''
6873
+ : `<span class="approval-risk ${escapeAttr(String(group.risk || 'low'))}">${escapeHtml(String(group.risk || 'low'))}</span>`;
6874
+ const headline = firstApproval && review.selective === false && group.headline === 'Entire model' ? 'Everything in the model' : String(group.headline || group.category || 'Change');
6584
6875
  const discard = review.selective ? `<button type="button" class="approval-discard" data-approval-discard="${escapeAttr(group.id)}">Discard change…</button>` : '';
6585
6876
  return `<section class="approval-group"><div class="approval-group-head"><div>`
6586
- + `<span class="approval-risk ${escapeAttr(String(group.risk || 'low'))}">${escapeHtml(String(group.risk || 'low'))}</span><b>${escapeHtml(String(group.headline || group.category || 'Change'))}</b></div>`
6877
+ + `${riskPill}<b>${escapeHtml(headline)}</b></div>`
6587
6878
  + `<span>${escapeHtml(String(group.location || ''))}</span></div><p>${escapeHtml(String(group.detail || ''))}</p>`
6588
6879
  + (review.selective === false ? '<p class="approval-whole-model">This review approves the entire model as one version. To keep working without approving, cancel this review.</p>' : `<div class="approval-decisions" role="radiogroup" aria-label="Decision for ${escapeAttr(String(group.headline || 'change'))}">`
6589
6880
  + ['approve', 'leave-pending'].map((decision) => approvalDecisionButtonHtml(group, decision, picked, findingsCopy, blockedReason)).join('')
@@ -6614,7 +6905,7 @@
6614
6905
  : '';
6615
6906
  const findingsHtml = nothingDrawn ? nothingDrawnHtml(nothingDrawn) : unreadable ? unreadableFindingsHtml(unreadable)
6616
6907
  : findings ? importFindingsWarningHtml(findings, !!blockedReason) : '';
6617
- $approvalBody.innerHTML = refusalHtml + findingsHtml + (groupHtml + conflictHtml || '<div class="approval-empty">No pending changes. The working copy already matches the latest approved version.</div>');
6908
+ $approvalBody.innerHTML = refusalHtml + findingsHtml + (groups.length ? approvalVersionCardHtml(review) : '') + (groupHtml + conflictHtml || '<div class="approval-empty">No pending changes. The working copy already matches the latest approved version.</div>');
6618
6909
  const values = Object.values(decisions);
6619
6910
  const approved = values.filter((value) => value === 'approve').length;
6620
6911
  const remaining = groups.length - values.length;
@@ -6641,6 +6932,17 @@
6641
6932
  const st = approvalDialogState;
6642
6933
  if (st && !approvalDismissible(st.phase)) return;
6643
6934
  approvalDialogState = null;
6935
+ if (st && st.ticker) { clearInterval(st.ticker); st.ticker = null; }
6936
+ // Closing while FloLess checks the result never drops the check: it carries on quietly and the
6937
+ // outcome arrives as a notice. The remembered operation keeps reopening on this same check.
6938
+ const undecided = st && !st.checking && st.phase === 'recovery-close' && st.operationId && st.operationToken;
6939
+ const stProject = undecided && (projects.find((candidate) => candidate.id === st.projectId) || (current && current.id === st.projectId ? current : null));
6940
+ const handOff = st && (st.checking || (stProject ? { project: stProject, operationId: st.operationId, operationToken: st.operationToken,
6941
+ refusal: st.refusalHeard || null } : null));
6942
+ if (handOff) {
6943
+ void watchApprovalOutcomeInBackground(handOff.project, handOff.operationId, handOff.operationToken, handOff.refusal || null);
6944
+ showToast('FloLess keeps checking whether the approval finished and will tell you here.', 'info');
6945
+ }
6644
6946
  if ($approvalRevisionNoteText) $approvalRevisionNoteText.value = '';
6645
6947
  $approvalModal.classList.remove('show');
6646
6948
  $approvalModal.removeAttribute('aria-busy');
@@ -6782,48 +7084,140 @@
6782
7084
  return { operationId: state.operationId, operationToken: state.operationToken };
6783
7085
  }
6784
7086
 
6785
- async function finishApprovalSuccess(res, project) {
7087
+ /**
7088
+ * #2521 row 5: the Quick model label. The server sends the words with each document it describes
7089
+ * (`quick: { state, short, label, tip }`); this only paints them. A precise model, or a payload without
7090
+ * the field, shows nothing. `scope` names WHICH document it describes ("v3", "Working copy") in the tip,
7091
+ * and in the visible text too with `showScope`, so a label never speaks for a document it was not read from.
7092
+ * `focusable: false` inside a control (a project card, a picker option): no second tab stop, and no Instructor id
7093
+ * that would shadow the control the click really drives. Its tooltip and words stay.
7094
+ */
7095
+ function quickPillHtml(q, opts = {}) {
7096
+ if (!q || (q.state !== 'quick' && q.state !== 'unknown') || typeof q.short !== 'string' || !q.short) return '';
7097
+ const scope = opts.scope ? `${opts.scope}: ` : '';
7098
+ const tip = `${scope}${q.label || q.short}. ${q.tip || ''}`.trim();
7099
+ const nested = opts.focusable === false;
7100
+ const carrier = nested ? '' : ' data-command-id="shell.quick-model-label" tabindex="0"';
7101
+ // Nested in a control: its full words ride along as that control's text, so a keyboard or screen-reader user who
7102
+ // cannot reach the pill's own tooltip still hears the count and what it means (code review of row 5a, round 2).
7103
+ const spoken = nested ? `<span class="sr-only"> (${escapeHtml(tip)})</span>` : '';
7104
+ return `<span class="quick-pill${q.state === 'unknown' ? ' is-unknown' : ''}"${carrier} data-tip="${escapeAttr(tip)}">${escapeHtml((opts.showScope ? scope : '') + q.short)}</span>${spoken}`;
7105
+ }
7106
+
7107
+ /**
7108
+ * The header chip: ONE compact chip for the approved head and, whenever it differs from the head, the working copy.
7109
+ * Its tooltip names each document and says what it rests on, so the header never grows a second chip that pushes
7110
+ * Approve off a laptop-width header (found by the independent QA run: two chips beside "Review changes · 10" ended
7111
+ * Approve at 1418 px in a 1280 px window).
7112
+ */
7113
+ function renderQuickHeader() {
7114
+ const $quick = document.getElementById('ws-quick');
7115
+ if (!$quick) return;
7116
+ const s = approvalState;
7117
+ const q = s.status === 'ready' && s.review && s.review.quick ? s.review.quick : null;
7118
+ const parts = [];
7119
+ if (q && s.headVersion && quickPillHtml(q.head)) parts.push([`v${s.headVersion}`, q.head]);
7120
+ if (q && (s.pendingCount > 0 || !s.headVersion) && quickPillHtml(q.draft)) parts.push(['Working copy', q.draft]);
7121
+ if (!parts.length) { $quick.innerHTML = ''; $quick.hidden = true; return; }
7122
+ // "Quick model" when any document it speaks for is readably Quick; "Possibly Quick model" when none is; dashed
7123
+ // whenever one of them could not be read.
7124
+ const anyQuick = parts.some(([, label]) => label.state === 'quick');
7125
+ const anyUnknown = parts.some(([, label]) => label.state === 'unknown');
7126
+ const tip = parts.map(([scope, label]) => `${scope}: ${label.label}.`).join(' ')
7127
+ + ` ${(parts.find(([, label]) => label.state === 'quick') || parts[0])[1].tip || ''}`;
7128
+ $quick.innerHTML = `<span class="quick-pill${anyUnknown ? ' is-unknown' : ''}" data-command-id="shell.quick-model-label" tabindex="0" data-tip="${escapeAttr(tip.trim())}">${escapeHtml(anyQuick ? 'Quick model' : 'Possibly Quick model')}</span>`;
7129
+ $quick.hidden = false;
7130
+ }
7131
+
7132
+ async function finishApprovalSuccess(res, project, { recovered = false } = {}) {
7133
+ // The dialog this outcome belongs to. A background check starts with none, and a dialog opened while this
7134
+ // awaits is someone else's: neither is ever painted with this result.
7135
+ const dialog = approvalDialogState;
6786
7136
  const revisionNoteStatus = await finishApprovalRevisionNote(res, project);
6787
- if ($approvalRevisionNoteText) $approvalRevisionNoteText.value = '';
7137
+ // After that await the person may be on another project, or in another review: the editor and header are
7138
+ // touched only while this project is on screen, and the dialog only while it is still this outcome's own
7139
+ // dialog AND this project is on screen (opening another project does not close an open dialog).
7140
+ const onProject = () => !!current && current.id === project.id;
7141
+ const ownsDialog = () => !!dialog && approvalDialogState === dialog && onProject();
7142
+ if (ownsDialog() && $approvalRevisionNoteText) $approvalRevisionNoteText.value = '';
6788
7143
  if (res && res.approvedAt) project.approvedAt = res.approvedAt;
6789
- const n = res && res.version && Number(res.version.n);
6790
- if (Number.isInteger(n)) expandDiffOnce = { projectId: project.id, n };
6791
- reloadModelFromServerTruth();
6792
- await refreshApprovalState(project.id);
6793
- const pending = Number.isInteger(Number(res && res.pendingCount)) ? Number(res.pendingCount) : approvalState.pendingCount;
7144
+ const { version: n, accepted, headline, assumed, quick } = approvalOutcomeWords(res);
7145
+ if (n) expandDiffOnce = { projectId: project.id, n };
7146
+ // An outcome can land while the person is editing this project again: a background check, or a dialog
7147
+ // closed while the note above was saving. Reloading the editor then would discard edits not yet saved, so
7148
+ // an editor with unsaved edits is never reloaded, whoever finishes, and the notice says so.
7149
+ const editorHasUnsavedEdits = () => {
7150
+ const win = frames.model && frames.model.contentWindow;
7151
+ const state = win && typeof win.contractSaveState === 'function' ? win.contractSaveState()
7152
+ : modelContractSaveState?.projectId === project.id && modelContractSaveState?.appId === project.app ? modelContractSaveState.state : null;
7153
+ return !!state && state !== 'clean';
7154
+ };
7155
+ const keptEdits = onProject() && editorHasUnsavedEdits();
7156
+ if (onProject() && !keptEdits) reloadModelFromServerTruth();
7157
+ const fresh = onProject() ? await refreshApprovalState(project.id) : null;
7158
+ // A recovered receipt's count is from when it was approved; edits made since are pending now, so a
7159
+ // recovery reports the count just read back, and when that read failed it says so (null) rather than
7160
+ // claiming "No changes remain pending" over work it never looked at.
7161
+ const pending = recovered ? (fresh && Array.isArray(fresh.groups) ? fresh.groups.length : null)
7162
+ : Number.isInteger(Number(res && res.pendingCount)) ? Number(res.pendingCount) : approvalState.pendingCount;
7163
+ const pendingUnknown = 'FloLess could not check which changes are still pending; open the review to see them.';
6794
7164
  const saved = res && res.savedWorkCheckpoint;
6795
- // #1840: the outcome says what the server recorded. An approval that accepted open import
6796
- // findings is never announced as a plain "Approved".
6797
- const accepted = res && res.version && res.version.approval && res.version.approval.acceptedImportFindings;
6798
- const headline = accepted ? importFindingsCopy(accepted).approved(Number.isInteger(n) ? n : null)
6799
- : `Approved${Number.isInteger(n) ? ` as v${n}` : ''}.`;
6800
- // #2449: an approval resting on connection assumptions (or one whose record could not be read) is never announced
6801
- // as a plain approval either; the server's own sentence, the same one History shows.
6802
- const assumed = res && res.connectionAssumptions && typeof res.connectionAssumptions.note === 'string' ? res.connectionAssumptions.note : '';
6803
- showToast(`${headline} ${assumed ? `${assumed} ` : ''}${pending ? `${pending} change${pending === 1 ? ' remains' : 's remain'} pending${saved ? ' in Saved work' : ''}; approved exports omit them unless you explicitly choose DRAFT.` : 'No changes remain pending.'}`, 'ok');
7165
+ // Edits still unsaved in the editor are not in any count FloLess read, so with them on screen no pending
7166
+ // count is claimed at all: the sentence says what is known instead.
7167
+ const keptEditsNote = 'Your newer edits stay in the editor and were not reloaded; once they are saved, reopen the model to see the approved version and what is still pending.';
7168
+ showToast(`${headline} ${quick}${assumed ? `${assumed} ` : ''}${keptEdits ? keptEditsNote : pending === null ? pendingUnknown : pending ? `${pending} change${pending === 1 ? ' remains' : 's remain'} pending${saved ? ' in Saved work' : ''}; approved exports omit them unless you explicitly choose DRAFT.` : 'No changes remain pending.'}`, 'ok');
6804
7169
  track('workspace_project_approved', { app: project.app });
6805
- if (bridge.markWorkspaceApproved && wsDescOf(project)?.docGuide) bridge.markWorkspaceApproved(project.app);
6806
- if (!$wsExports.hidden) safeRenderExports('after approving this version');
6807
- if (!$wsHistory.hidden) await renderHistory();
6808
- if (!approvalDialogState) return;
6809
- $approvalImpact.textContent = pending
7170
+ if (onProject() && !$wsExports.hidden) safeRenderExports('after approving this version');
7171
+ if (onProject() && !$wsHistory.hidden) await renderHistory();
7172
+ if (!ownsDialog()) return;
7173
+ $approvalImpact.textContent = keptEdits ? keptEditsNote : pending === null ? pendingUnknown : pending
6810
7174
  ? `${pending} change${pending === 1 ? ' remains' : 's remain'} pending${saved ? ' in Saved work' : ''}.`
6811
7175
  : 'No changes remain pending.';
6812
7176
  // The footer described the decision ("…will be approved…"); the decision has happened.
6813
7177
  $approvalCounts.textContent = '';
6814
- $approvalBody.innerHTML = `<div class="approval-notice approval-notice-success"><b>${escapeHtml(headline)}</b> The approved model and compiled workflow are ready.${assumed ? ' ' + escapeHtml(assumed) : ''}${revisionNoteStatus ? ' ' + escapeHtml(revisionNoteStatus) : ''}${accepted ? ' The findings stay listed in the Audit tab.' : ''}</div>`;
6815
- setApprovalPhase('approved', accepted ? headline : `Approved${Number.isInteger(n) ? ` as v${n}` : ''}`);
7178
+ $approvalBody.innerHTML = `<div class="approval-notice approval-notice-success"><b>${escapeHtml(headline)}</b> ${quick ? `${escapeHtml(quick)}` : ''}The approved model and compiled workflow are ready.${assumed ? ' ' + escapeHtml(assumed) : ''}${revisionNoteStatus ? ' ' + escapeHtml(revisionNoteStatus) : ''}${accepted ? ' The findings stay listed in the Audit tab.' : ''}</div>`;
7179
+ setApprovalPhase('approved', accepted ? headline : `Approved${n ? ` as v${n}` : ''}`);
6816
7180
  $approvalClose.focus();
6817
7181
  }
6818
7182
 
7183
+ /**
7184
+ * What the server recorded for an approval, in the words every surface uses: the dialog, its toast and the
7185
+ * notice for an approval that finished while another project was open. One builder, so no surface can
7186
+ * announce a plain approval that the record qualifies.
7187
+ */
7188
+ function approvalOutcomeWords(res) {
7189
+ const n = res && res.version && Number(res.version.n);
7190
+ const version = Number.isInteger(n) && n > 0 ? n : null;
7191
+ // #1840: an approval that accepted open import findings is never announced as a plain "Approved".
7192
+ const accepted = res && res.version && res.version.approval && res.version.approval.acceptedImportFindings;
7193
+ const headline = accepted ? importFindingsCopy(accepted).approved(version) : `Approved${version ? ` as v${version}` : ''}.`;
7194
+ // #2449: an approval resting on connection assumptions (or one whose record could not be read) is never
7195
+ // announced as a plain approval either; the server's own sentence, the same one History shows.
7196
+ const assumed = res && res.connectionAssumptions && typeof res.connectionAssumptions.note === 'string' ? res.connectionAssumptions.note : '';
7197
+ // #2521 row 5: an approved Quick model says so in the same breath, read from the approved version itself.
7198
+ const quick = res && res.quick && (res.quick.state === 'quick' || res.quick.state === 'unknown') && typeof res.quick.label === 'string'
7199
+ ? `${res.quick.label}. ` : '';
7200
+ return { version, accepted, headline, assumed, quick, sentence: `${headline} ${quick}${assumed}`.trim() };
7201
+ }
7202
+
7203
+ // One receipt read. The server answers under the project's approval locks, which on a large model
7204
+ // takes seconds even when idle (5 s measured on the Camden read, 2026-10-24); the old 4 s deadline
7205
+ // turned every answer into "unknown" and stranded the person on "could not be confirmed". The
7206
+ // deadline now only catches a request that will never answer, and an unknown answer is simply asked
7207
+ // again (waitForApprovalOutcome) rather than reported.
6819
7208
  async function reconcileApprovalOperation(project, operationId, operationToken) {
6820
- setApprovalPhase('reconciling');
6821
7209
  try {
6822
7210
  const response = await fetch(`/api/projects/${encodeURIComponent(project.id)}/approval-operations/${encodeURIComponent(operationId)}?token=${encodeURIComponent(operationToken)}`, {
6823
- signal: AbortSignal.timeout(4000),
7211
+ signal: AbortSignal.timeout(30000),
6824
7212
  });
6825
7213
  if (response.status === 404) return { status: 'not-found' };
6826
- if (!response.ok) return { status: 'unknown' };
7214
+ if (!response.ok) {
7215
+ // #2767: a refusal written for the person (e.g. module access that could not be confirmed) is
7216
+ // kept, so "cannot tell yet" can say what is in the way instead of guessing at it.
7217
+ const body = await response.json().catch(() => null);
7218
+ const userMessage = body && typeof body.userMessage === 'string' ? body.userMessage.trim() : '';
7219
+ return { status: 'unknown', httpStatus: response.status, ...(userMessage ? { userMessage } : {}) };
7220
+ }
6827
7221
  const receipt = await response.json();
6828
7222
  return receipt && ['complete', 'pending', 'abandoned'].includes(receipt.status) ? receipt : { status: 'unknown' };
6829
7223
  } catch { return { status: 'unknown' }; }
@@ -6833,9 +7227,126 @@
6833
7227
  : receipt?.status === 'abandoned' ? 'abandoned'
6834
7228
  : receipt?.status === 'not-found' ? 'continue' : 'locked';
6835
7229
 
6836
- function showLockedApprovalRecovery(receipt) {
7230
+ // How long the dialog keeps checking on its own before it says it still cannot tell. Checking goes on
7231
+ // after that too, in the background, until the person closes the window or asks again.
7232
+ const APPROVAL_CHECK_WINDOW_MS = 120000;
7233
+ const approvalSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
7234
+
7235
+ /**
7236
+ * Ask for the operation's receipt until it is decided (complete, abandoned, or never written), backing
7237
+ * off 1 s, 2 s, 4 s, then every 5 s. `stillWanted()` going false ends the wait quietly with `null`: the
7238
+ * dialog was closed or replaced, and whoever took over asks for themselves.
7239
+ */
7240
+ async function waitForApprovalOutcome(project, operationId, operationToken, { stillWanted, limitMs = APPROVAL_CHECK_WINDOW_MS } = {}) {
7241
+ const started = Date.now();
7242
+ let delay = 1000;
7243
+ for (;;) {
7244
+ const receipt = await reconcileApprovalOperation(project, operationId, operationToken);
7245
+ if (approvalRecoveryDisposition(receipt) !== 'locked') return receipt;
7246
+ // Signed out or refused: asking again cannot help, so hand back now and let the notice say so.
7247
+ if (receipt.httpStatus === 401 || receipt.httpStatus === 403) return receipt;
7248
+ if (stillWanted && !stillWanted()) return null;
7249
+ if (Date.now() - started >= limitMs) return receipt;
7250
+ await approvalSleep(delay);
7251
+ if (stillWanted && !stillWanted()) return null;
7252
+ delay = Math.min(delay * 2, 5000);
7253
+ }
7254
+ }
7255
+
7256
+ /**
7257
+ * The dialog was closed while FloLess was still checking. Keep asking, quietly, for as long as the same
7258
+ * project is open, then say what happened. The remembered operation stays until the outcome is known,
7259
+ * so reopening the review always resumes this same check and can never start a second approval.
7260
+ */
7261
+ const approvalBackgroundWatches = new Set();
7262
+ async function watchApprovalOutcomeInBackground(project, operationId, operationToken, refusal = null) {
7263
+ if (approvalBackgroundWatches.has(operationId)) return;
7264
+ approvalBackgroundWatches.add(operationId);
7265
+ const name = String(project.name || 'this project');
7266
+ // A review of this same project, once reopened, takes the check over; switching to another project does not
7267
+ // stop it, because the person was promised an answer.
7268
+ const dialogOwns = () => !!approvalDialogState && approvalDialogState.projectId === project.id;
7269
+ try {
7270
+ let receipt;
7271
+ try {
7272
+ receipt = await waitForApprovalOutcome(project, operationId, operationToken, { stillWanted: () => !dialogOwns(), limitMs: 30 * 60000 });
7273
+ } catch {
7274
+ showToast(`FloLess could not read whether “${name}” was approved. Open its review to check again.`, 'warn');
7275
+ return;
7276
+ }
7277
+ if (!receipt || dialogOwns()) return;
7278
+ // From here the outcome is KNOWN: a later failure to refresh the screen never turns it back into
7279
+ // "could not read", and each notice says what was recorded and nothing more.
7280
+ const disposition = approvalRecoveryDisposition(receipt);
7281
+ const onScreen = !!current && current.id === project.id;
7282
+ if (disposition === 'complete') {
7283
+ if (onScreen) {
7284
+ try { await finishApprovalSuccess(receipt, project, { recovered: true }); }
7285
+ catch { showToast(`The approval of “${name}” finished, but FloLess could not refresh this screen. Reload FloLess to see the approved version.`, 'warn'); }
7286
+ } else {
7287
+ // Elsewhere: the same recorded sentence the dialog would show (findings, assumptions, Quick model
7288
+ // included), and the remembered operation stays so opening this project's review records it there.
7289
+ showToast(`“${name}”: ${approvalOutcomeWords(receipt).sentence} Open the project to see it.`, 'ok');
7290
+ }
7291
+ } else if (disposition === 'locked') {
7292
+ // #2767: the server's own sentence when it said why it would not answer (module access, for one).
7293
+ showToast(receipt.userMessage
7294
+ ? `FloLess could not check the approval of “${name}”. ${receipt.userMessage} Then open its review to check again.`
7295
+ : receipt.httpStatus === 401
7296
+ ? `FloLess could not check the approval of “${name}” because this computer is signed out. Sign in again, then open its review.`
7297
+ : receipt.httpStatus === 403
7298
+ // Refused: reopening reuses the same refused key, so point to the record that will answer.
7299
+ ? `FloLess would not show the result of the approval of “${name}” to this window. Open its History to see whether a new version was approved.`
7300
+ : `FloLess still cannot confirm whether “${name}” was approved. Nothing else is approved meanwhile; open its review to check again.`, 'warn');
7301
+ } else {
7302
+ rememberApprovalOperation(project, null);
7303
+ // #2767: a refusal says its reason here too, never "stopped before it finished".
7304
+ showToast(refusal
7305
+ ? `Nothing was approved for “${name}”. ${refusal.reason}${refusal.next ? ` ${refusal.next}` : ''}`
7306
+ : disposition === 'abandoned'
7307
+ ? `Nothing was approved for “${name}”. The approval stopped before it finished, and your model is unchanged. Open the review to try again.`
7308
+ : `FloLess has no record that the approval of “${name}” started, so nothing was approved. Open the review to try again.`, 'warn');
7309
+ // The header reports its own refresh failure; the outcome above stands either way.
7310
+ if (onScreen) { try { await refreshApprovalState(project.id); } catch { /* reported by the header */ } }
7311
+ }
7312
+ } finally { approvalBackgroundWatches.delete(operationId); }
7313
+ }
7314
+
7315
+ /** Checking runs inside the dialog with its own step; a close hands it to the background watcher. */
7316
+ async function checkApprovalOutcome(project, operationId, operationToken, refusal = null) {
7317
+ const st = approvalDialogState;
7318
+ if (!st) return null;
7319
+ // The refusal travels with the check, so a close hands the background watcher the reason too.
7320
+ st.checking = { project, operationId, operationToken, refusal };
7321
+ setApprovalPhase('reconciling');
7322
+ const receipt = await waitForApprovalOutcome(project, operationId, operationToken, { stillWanted: () => approvalDialogState === st });
7323
+ if (approvalDialogState === st) st.checking = null;
7324
+ return receipt;
7325
+ }
7326
+
7327
+ function showLockedApprovalRecovery(receipt, refusal = null) {
6837
7328
  const pending = receipt?.status === 'pending';
6838
- $approvalBody.innerHTML = `<div class="approval-notice"><b>${pending ? 'Approval is still being recovered.' : 'Approval status could not be confirmed.'}</b> Close this window and reopen the review in a moment. FloLess will not change this approval until its durable result can be read.</div>`;
7329
+ // Kept on the dialog, so "Check again" and a close (the background watcher) can still say it later.
7330
+ if (approvalDialogState && refusal) approvalDialogState.refusalHeard = refusal;
7331
+ // Signed out (401) or refused (403, e.g. this window no longer holds the approval's private key):
7332
+ // checking again by itself cannot help, so each says what will.
7333
+ const signedOut = receipt?.httpStatus === 401;
7334
+ const refused = receipt?.httpStatus === 403;
7335
+ // #2767: the server's own sentence, when it said why it would not answer (module access, for one).
7336
+ const said = typeof receipt?.userMessage === 'string' && receipt.userMessage ? receipt.userMessage : '';
7337
+ // #2767: what the approval request itself was told, when it was refused: said as what FloLess heard,
7338
+ // since only the recorded outcome may say whether anything was approved.
7339
+ const heard = refusal && refusal.reason ? `<p>The approval request was refused: ${escapeHtml(refusal.reason)}</p>` : '';
7340
+ $approvalBody.innerHTML = '<div class="approval-notice approval-notice-wait">'
7341
+ + `<b>${pending ? 'FloLess is still finishing this approval.' : 'FloLess cannot tell yet whether this approval finished.'}</b> `
7342
+ + heard
7343
+ + (said ? `It could not read the result. ${escapeHtml(said)} When that is resolved, check again. `
7344
+ : signedOut ? 'It could not read the result because this computer is signed out. Sign in again, then check again. '
7345
+ : refused ? 'FloLess would not show this approval’s result to this window. Open History to see whether a new version was approved. '
7346
+ : 'It may already have finished on this computer; FloLess shows no result it cannot confirm, and no second approval can start meanwhile. ')
7347
+ + (signedOut || refused ? '' : 'Close this window and FloLess keeps checking and tells you, or check again now.')
7348
+ + '<div class="approval-notice-actions"><button type="button" class="btn-mini" data-approval-check-again data-command-id="shell.approval-check-again">Check again</button></div></div>';
7349
+ if ($approvalCounts) $approvalCounts.textContent = '';
6839
7350
  setApprovalPhase('recovery-close', pending ? 'Approval recovery is still in progress.' : 'The approval result is not available yet.');
6840
7351
  $approvalClose.focus();
6841
7352
  }
@@ -6844,7 +7355,9 @@
6844
7355
  // "Nothing was approved" is said because the reconcile answered `abandoned` (the operation was
6845
7356
  // retired with no committed row); the reason says WHY, instead of generic recovery copy. (A refusal
6846
7357
  // made before any write says it in the review itself; see confirmApprovalReview.)
6847
- function showAbandonedApprovalRecovery(project, reason = '') {
7358
+ function showAbandonedApprovalRecovery(project, reason = '', technical = '') {
7359
+ const approvalTechHtml = (technical) => technical
7360
+ ? `<details class="approval-tech"><summary>Technical details</summary><div><span>${escapeHtml(technical)}</span></div></details>` : '';
6848
7361
  const st = approvalDialogState;
6849
7362
  if (!st) return;
6850
7363
  rememberApprovalOperation(project, null);
@@ -6857,7 +7370,10 @@
6857
7370
  $approvalImpact.textContent = '';
6858
7371
  $approvalCounts.textContent = '';
6859
7372
  const detail = approvalRefusalDetail(reason);
6860
- $approvalBody.innerHTML = `<div class="approval-notice"><b>Nothing was approved.</b> ${detail ? `${escapeHtml(detail)} ` : ''}FloLess restored your working copy. That approval attempt is finished and cannot be retried.</div>`;
7373
+ $approvalBody.innerHTML = '<div class="approval-notice approval-notice-error" role="alert"><b>Nothing was approved. Your model is unchanged.</b> '
7374
+ + `<p>${detail ? `${escapeHtml(detail)} ` : 'The approval stopped before it finished, so FloLess undid it and restored your working copy. '}`
7375
+ + 'That attempt is finished. Start a new review to approve again.</p>'
7376
+ + `${approvalTechHtml(technical && technical !== detail ? technical : '')}</div>`;
6861
7377
  $approvalConfirm.setAttribute('data-command-id', 'shell.approval-start-new-review');
6862
7378
  $approvalConfirm.removeAttribute('data-blocked-reason');
6863
7379
  $approvalConfirm.textContent = 'Start a new review';
@@ -6866,6 +7382,57 @@
6866
7382
  $approvalConfirm.focus();
6867
7383
  }
6868
7384
 
7385
+ /**
7386
+ * #2767: the server refused the approval (or the review behind it) and said why. Not the "previous attempt
7387
+ * ended safely" panel: that presents a refusal as an interruption and sends the person round "Start a new
7388
+ * review" without ever telling them what stands in the way. The attempt is over all the same, so the
7389
+ * remembered operation is forgotten (a reopen never resumes it) and a new review is one click away.
7390
+ */
7391
+ function showApprovalRefused(project, refusal) {
7392
+ const st = approvalDialogState;
7393
+ if (!st) return;
7394
+ rememberApprovalOperation(project, null);
7395
+ st.operationId = null;
7396
+ st.operationToken = null;
7397
+ st.decisions = {};
7398
+ st.conflicts = {};
7399
+ st.retryAction = null;
7400
+ $approvalImpact.textContent = '';
7401
+ $approvalCounts.textContent = '';
7402
+ $approvalBody.innerHTML = approvalRefusalNoticeHtml('Nothing was approved. Your model is unchanged.', refusal);
7403
+ $approvalConfirm.setAttribute('data-command-id', 'shell.approval-start-new-review');
7404
+ $approvalConfirm.removeAttribute('data-blocked-reason');
7405
+ $approvalConfirm.textContent = 'Start a new review';
7406
+ $approvalConfirm.disabled = false;
7407
+ // The same terminal phase as an ended attempt (Close, or a new review), with its own words.
7408
+ setApprovalPhase('abandoned', `Nothing was approved. ${refusal.reason}`);
7409
+ // A state label, distinct from an interrupted attempt's "ended safely"; the notice says what and why.
7410
+ $approvalSub.textContent = 'The approval was refused';
7411
+ $approvalConfirm.focus();
7412
+ }
7413
+
7414
+ /** "Check again" on a result FloLess could not read yet: reads it again, never sends a second approval. */
7415
+ async function checkApprovalAgain() {
7416
+ const st = approvalDialogState;
7417
+ if (!st || st.phase !== 'recovery-close' || !st.operationId || !st.operationToken || !current || current.id !== st.projectId) return;
7418
+ const project = current;
7419
+ // #2767: the refusal the approval request got, if any, still decides how the outcome is told.
7420
+ const refusal = st.refusalHeard || null;
7421
+ try {
7422
+ const receipt = await checkApprovalOutcome(project, st.operationId, st.operationToken, refusal);
7423
+ if (!receipt || approvalDialogState !== st) return;
7424
+ const disposition = approvalRecoveryDisposition(receipt);
7425
+ if (disposition === 'complete') await finishApprovalSuccess(receipt, project, { recovered: true });
7426
+ else if (disposition === 'locked') showLockedApprovalRecovery(receipt, refusal);
7427
+ else if (refusal && (disposition === 'abandoned' || refusal.kind !== 'other')) showApprovalRefused(project, refusal);
7428
+ // No receipt at all is not an undo: say only what is known.
7429
+ else showAbandonedApprovalRecovery(project, disposition === 'continue' ? 'FloLess has no record that this approval started.' : '');
7430
+ } catch {
7431
+ // Reading the outcome failed part-way: stay on the honest "cannot tell yet" notice, never a dead dialog.
7432
+ if (approvalDialogState === st) showLockedApprovalRecovery({ status: 'unknown' }, refusal);
7433
+ }
7434
+ }
7435
+
6869
7436
  async function startNewApprovalReview() {
6870
7437
  const st = approvalDialogState;
6871
7438
  if (!st || st.phase !== 'abandoned' || !current || current.id !== st.projectId) return;
@@ -6894,23 +7461,21 @@
6894
7461
  $approvalConfirm.disabled = true;
6895
7462
  // A fresh dialog starts with no blocked reason; the review's own render sets one if it needs it.
6896
7463
  $approvalConfirm.removeAttribute('data-blocked-reason');
6897
- approvalDialogState = { projectId: project.id, review: { groups: [] }, decisions: {}, conflicts: {}, returnFocus: document.activeElement, stale: false, phase: 'comparing' };
7464
+ const remembered = rememberedApprovalOperation(project);
7465
+ approvalDialogState = { projectId: project.id, review: { groups: [] }, decisions: {}, conflicts: {}, returnFocus: document.activeElement, stale: false, phase: 'comparing',
7466
+ flow: remembered ? 'recover' : 'prepare' };
6898
7467
  const dialogState = approvalDialogState;
6899
- setApprovalPhase('comparing');
7468
+ setApprovalPhase(remembered ? 'reconciling' : 'comparing');
6900
7469
  $approvalDialog.focus();
6901
7470
  try {
6902
- const remembered = rememberedApprovalOperation(project);
6903
7471
  if (remembered && $approvalRevisionNoteText) { $approvalRevisionNoteText.value = remembered.revisionNoteText || ''; approvalDialogState.revisionNoteText = $approvalRevisionNoteText.value; }
6904
7472
  if (remembered) {
6905
7473
  approvalDialogState.operationId = remembered.operationId;
6906
7474
  approvalDialogState.operationToken = remembered.operationToken;
6907
- let receipt = await reconcileApprovalOperation(project, remembered.operationId, remembered.operationToken);
6908
- for (let attempt = 0; approvalRecoveryDisposition(receipt) === 'locked' && attempt < 20; attempt += 1) {
6909
- await new Promise((resolve) => setTimeout(resolve, 500));
6910
- receipt = await reconcileApprovalOperation(project, remembered.operationId, remembered.operationToken);
6911
- }
7475
+ const receipt = await checkApprovalOutcome(project, remembered.operationId, remembered.operationToken);
7476
+ if (!receipt || approvalDialogState !== dialogState) return;
6912
7477
  if (approvalRecoveryDisposition(receipt) === 'complete') {
6913
- await finishApprovalSuccess(receipt, project);
7478
+ await finishApprovalSuccess(receipt, project, { recovered: true });
6914
7479
  return;
6915
7480
  }
6916
7481
  if (approvalRecoveryDisposition(receipt) === 'abandoned') {
@@ -6922,6 +7487,9 @@
6922
7487
  return;
6923
7488
  }
6924
7489
  }
7490
+ // No earlier attempt to finish: this is the ordinary save-and-compare preparation.
7491
+ dialogState.flow = 'prepare';
7492
+ dialogState.busySince = Date.now();
6925
7493
  const win = frames.model && frames.model.contentWindow;
6926
7494
  // History is server-owned after partial approval and may hide an editor whose in-memory draft
6927
7495
  // predates that partition. Other tabs can be reached immediately after an edit, before the
@@ -6980,10 +7548,20 @@
6980
7548
  if (approvalDialogState !== dialogState) return;
6981
7549
  approvalDialogState.stale = false;
6982
7550
  approvalDialogState.retryAction = 'prepare';
6983
- $approvalSub.textContent = 'Approval status unavailable';
6984
- $approvalImpact.textContent = (error && error.message) || 'Could not load the comparison.';
6985
- $approvalBody.innerHTML = '<div class="approval-notice approval-notice-error"><b>Nothing was approved.</b> Try again when the model can be saved and compared.</div>';
6986
- setApprovalPhase('failed', 'Nothing was approved. Try again.');
7551
+ // #2767: a review the server refused says why (module access, a signed-out computer), not "try again
7552
+ // when the model can be saved", which sends the person round the same refusal.
7553
+ const refusal = approvalRefusalOf(error);
7554
+ if (refusal && refusal.kind !== 'other') {
7555
+ $approvalImpact.textContent = '';
7556
+ $approvalBody.innerHTML = approvalRefusalNoticeHtml('Nothing was approved.', refusal);
7557
+ setApprovalPhase('failed', `Nothing was approved. ${refusal.reason}`);
7558
+ $approvalSub.textContent = 'FloLess could not open this review';
7559
+ } else {
7560
+ $approvalSub.textContent = 'Approval status unavailable';
7561
+ $approvalImpact.textContent = (error && error.message) || 'Could not load the comparison.';
7562
+ $approvalBody.innerHTML = '<div class="approval-notice approval-notice-error"><b>Nothing was approved.</b> Try again when the model can be saved and compared.</div>';
7563
+ setApprovalPhase('failed', 'Nothing was approved. Try again.');
7564
+ }
6987
7565
  $approvalRetry.focus();
6988
7566
  }
6989
7567
  }
@@ -7020,6 +7598,20 @@
7020
7598
  }
7021
7599
 
7022
7600
  async function confirmApprovalReview() {
7601
+ /** What the person is approving, in one sentence, kept on screen while it runs. */
7602
+ function approvalWhatSentence(st) {
7603
+ const review = st.review || {};
7604
+ const groups = Array.isArray(review.groups) ? review.groups : [];
7605
+ const approved = Object.values(st.decisions || {}).filter((value) => value === 'approve').length;
7606
+ const pending = groups.length - approved;
7607
+ if (review.selective === false) {
7608
+ return review.wholeVersionReason === 'first-approval' || !review.base
7609
+ ? 'Approving the whole model as its first approved version.'
7610
+ : `Approving the whole model as the next approved version after v${review.base.version}.`;
7611
+ }
7612
+ return `Approving ${approved} change${approved === 1 ? '' : 's'}${pending > 0 ? ` · ${pending} stay${pending === 1 ? 's' : ''} pending` : ''}.`;
7613
+ }
7614
+
7023
7615
  const st = approvalDialogState;
7024
7616
  if (!st || $approvalConfirm.disabled || !current || current.id !== st.projectId) return;
7025
7617
  const project = current;
@@ -7042,6 +7634,10 @@
7042
7634
  const findings = st.review.importFindings;
7043
7635
  const acceptOpenImportFindings = findings && Number(findings.open) > 0 && Object.values(st.decisions).includes('approve')
7044
7636
  ? { contractHash: findings.contractHash, digest: findings.digest, open: findings.open } : null;
7637
+ st.flow = 'approve';
7638
+ st.approvingWhat = approvalWhatSentence(st);
7639
+ // "N changes need review" is a question the person has just answered; the step list says what runs now.
7640
+ $approvalImpact.textContent = '';
7045
7641
  setApprovalPhase('approving');
7046
7642
  $approvalConfirm.disabled = true;
7047
7643
  st.refusal = null;
@@ -7085,17 +7681,30 @@
7085
7681
  setApprovalPhase('stale', 'The review changed. Reload current review.');
7086
7682
  $approvalReload.focus();
7087
7683
  } else if (approvalDialogState) {
7088
- const recovered = await reconcileApprovalOperation(project, operationId, operationToken);
7684
+ // #2767: a refusal the server explained is said as one, never as an interruption. Still checked
7685
+ // first: only the recorded outcome may say that nothing was approved.
7686
+ const refusal = approvalRefusalOf(error);
7687
+ const recovered = await checkApprovalOutcome(project, operationId, operationToken, refusal);
7688
+ // Closed while checking: the background watcher took the check over and will report it.
7689
+ if (!recovered || approvalDialogState !== st) return;
7089
7690
  if (approvalRecoveryDisposition(recovered) === 'complete') {
7090
7691
  await finishApprovalSuccess(recovered, project);
7091
7692
  return;
7092
7693
  }
7093
- if (approvalRecoveryDisposition(recovered) === 'abandoned') {
7094
- showAbandonedApprovalRecovery(project, knownApprovalFailureReason(error));
7694
+ const disposition = approvalRecoveryDisposition(recovered);
7695
+ // Retired by the server after it answered: a refusal, never an interruption. With no record of the
7696
+ // attempt, only a refusal that says what to do outranks retrying the same decisions.
7697
+ if (refusal && (disposition === 'abandoned' || (disposition === 'continue' && refusal.kind !== 'other'))) {
7698
+ showApprovalRefused(project, refusal);
7095
7699
  return;
7096
7700
  }
7097
- if (approvalRecoveryDisposition(recovered) === 'locked') {
7098
- showLockedApprovalRecovery(recovered);
7701
+ // No refusal to tell (no answer at all, or a server fault): the attempt really was interrupted.
7702
+ if (disposition === 'abandoned') {
7703
+ showAbandonedApprovalRecovery(project, '', approvalTechnicalDetail(error));
7704
+ return;
7705
+ }
7706
+ if (disposition === 'locked') {
7707
+ showLockedApprovalRecovery(recovered, refusal);
7099
7708
  return;
7100
7709
  }
7101
7710
  approvalDialogState.decisions = decisionSnapshot.decisions;
@@ -7185,6 +7794,7 @@
7185
7794
  if (again) again.focus();
7186
7795
  return;
7187
7796
  }
7797
+ if (event.target.closest('[data-approval-check-again]')) { checkApprovalAgain(); return; }
7188
7798
  const openAudit = event.target.closest('[data-approval-open-audit]');
7189
7799
  if (openAudit && approvalDialogState && approvalDismissible(approvalDialogState.phase)) {
7190
7800
  // #1840: show the findings themselves. Nothing is approved; the review can be reopened.
@@ -7265,7 +7875,8 @@
7265
7875
  // model would mislead). Same-origin contentWindow call, like the Approve flush above.
7266
7876
  function wsFindActive() {
7267
7877
  if (!$app.classList.contains('mode-workspaces')) return false;
7268
- if (!current || frames.model.hidden) return false; // Model step must be showing
7878
+ // The Model step must be showing — the same frame also shows on the RFIs step (#2470 R6.6c), where Find has no model.
7879
+ if (!current || frames.model.hidden || currentStep !== 'model') return false;
7269
7880
  const w = frames.model.contentWindow;
7270
7881
  if (!w || typeof w.findMember !== 'function') return false;
7271
7882
  try { if (w.document.getElementById('aiUpdateBanner')) return false; } catch { return false; }
@@ -7718,7 +8329,8 @@
7718
8329
  `<div class="kb-ds-ph" id="kb-ds-ph-${escapeAttr(issue.issueId)}">Read “${escapeHtml(issue.label)}” into the model</div>` +
7719
8330
  `<div class="kb-ds-note">FloLess queues one drawing read for your AI. It proposes changes to the model, and nothing is applied until you review them.${plan.beingRead.length ? ' A read of some of these files is still open in Requests.' : ''}${plan.alreadyRead === 'unknown' ? ' FloLess could not check which files were read before.' : ''}</div>` +
7720
8331
  `<div class="kb-ds-lbl">Will be read (${Math.min(n, 40)})</div><ul class="kb-ds-picks" role="list">${items || '<li class="kb-ds-opt">No file of this issue can be read just now.</li>'}</ul>` +
7721
- (out ? `<div class="kb-ds-lbl">Left out</div><ul class="kb-ds-out" role="list">${out}</ul>` : '') + over + err +
8332
+ (out ? `<div class="kb-ds-lbl">Left out</div><ul class="kb-ds-out" role="list">${out}</ul>` : '') + over +
8333
+ (kbDsPanel.build ? revisionBuildChoiceHtml(kbDsPanel.build, { idPrefix: `kb-ds-rb-${issue.issueId}`, compact: true }) : '') + err +
7722
8334
  '<div class="kb-ds-pact"><button type="button" class="btn-mini" data-kb-ds-cancel data-command-id="shell.kb-design-panel-cancel">Cancel</button>' +
7723
8335
  (n ? `<button type="button" class="btn-mini primary" data-kb-ds-read-go="${escapeAttr(issue.issueId)}" data-command-id="shell.kb-design-issue-read-go">Read ${Math.min(n, 40)} file${Math.min(n, 40) === 1 ? '' : 's'}</button>` : '') +
7724
8336
  '</div></div>';
@@ -10596,26 +11208,50 @@
10596
11208
  const proj = current;
10597
11209
  if (!proj) return;
10598
11210
  kbDsOpenPanel({ kind: 'read', issueId, plan: null }, { issueId, control: '.kb-ds-panel' });
11211
+ // #2521 row 7b: bound to THIS panel: one closed and reopened for the same issue meanwhile is another one. The Model
11212
+ // preset is read in parallel with the plan; the panel shows once both are in (the preset waits 8 s at most).
11213
+ const panel = kbDsPanel;
11214
+ const presetRead = revisionBuildPreset(proj);
10599
11215
  let plan;
10600
11216
  try { plan = await api(`${kbDsBase(proj)}/issues/${encodeURIComponent(issueId)}/read-plan`); }
10601
11217
  catch (err) {
10602
- if (current !== proj || !kbDsPanel || kbDsPanel.issueId !== issueId) return;
11218
+ if (current !== proj || kbDsPanel !== panel) return;
10603
11219
  kbDsPanel = null;
10604
11220
  showToast(kbDsErrorText(err, 'Couldn’t check the files of this issue. Try again.'), 'warn');
10605
11221
  kbDsRepaint();
10606
11222
  return;
10607
11223
  }
10608
- if (current !== proj || !kbDsPanel || kbDsPanel.kind !== 'read' || kbDsPanel.issueId !== issueId) return;
11224
+ if (current !== proj || kbDsPanel !== panel) return;
11225
+ // The same Quick / Precise choice as Attach, preset to the model's own mode.
11226
+ const preset = await presetRead;
11227
+ if (current !== proj || kbDsPanel !== panel) return;
11228
+ kbDsPanel.build = { mode: preset.mode, members: preset.members, note: preset.note, autoAccept: false, error: '' };
10609
11229
  kbDsPanel.plan = plan;
10610
11230
  kbDsPanel.chosen = new Set(plan.included.map((f) => f.index));
10611
11231
  kbDsFocus = { issueId, control: '.kb-ds-panel input[type="checkbox"], .kb-ds-panel .btn-mini' };
10612
11232
  kbDsRepaint();
10613
11233
  }
10614
11234
 
11235
+ /** #2521 row 7b: a press (or tick) on a read panel's Model choice, kept in the panel so a repaint redraws it. */
11236
+ function kbDsChooseBuild(target) {
11237
+ if (!kbDsPanel || !kbDsPanel.build || !chooseRevisionBuild(kbDsPanel.build, target)) return false;
11238
+ kbDsFocus = { issueId: kbDsPanel.issueId, control: target.closest('[data-rev-build-auto]')
11239
+ ? '.kb-ds-panel [data-rev-build-auto]' : `.kb-ds-panel [data-rev-build="${kbDsPanel.build.mode}"]` };
11240
+ kbDsRepaint();
11241
+ return true;
11242
+ }
11243
+
10615
11244
  async function kbDsReadGo(issueId, returnFocus) {
10616
11245
  const proj = current;
10617
11246
  const panel = kbDsPanel;
10618
11247
  if (!proj || !panel || panel.kind !== 'read' || !panel.plan) return;
11248
+ if (!panel.build || !panel.build.mode) {
11249
+ if (panel.build) panel.build.error = REVISION_BUILD_CHOOSE;
11250
+ kbDsFocus = { issueId, control: '.kb-ds-panel [data-rev-build="quick"]' };
11251
+ kbDsRepaint();
11252
+ return;
11253
+ }
11254
+ const consent = revisionBuildBody(panel.build); // what the person pressed, as of this press
10619
11255
  const chosen = [...panel.chosen].sort((a, b) => a - b);
10620
11256
  const asPlanned = panel.plan.chosenByDefault && chosen.length === panel.plan.included.length
10621
11257
  && chosen.every((n, i) => n === panel.plan.included[i].index);
@@ -10625,6 +11261,7 @@
10625
11261
  : await api(`${kbDsBase(proj)}/issues/${encodeURIComponent(issueId)}/read-plan?files=${chosen.join(',')}`);
10626
11262
  // The panel promised the ticked files (40 at most). If the server would take a different set — a copy changed
10627
11263
  // meanwhile — show its plan instead of starting a read the person did not see.
11264
+ if (current !== proj || kbDsPanel !== panel) return; // cancelled or replaced while the plan was checked
10628
11265
  const promised = chosen.slice(0, 40).join(',');
10629
11266
  if (!asPlanned && plan.included.map((f) => f.index).join(',') !== promised) {
10630
11267
  if (current !== proj || !kbDsPanel) return;
@@ -10636,11 +11273,11 @@
10636
11273
  return;
10637
11274
  }
10638
11275
  const res = await api(`/api/projects/${encodeURIComponent(proj.id)}/revision-requests`, { method: 'POST',
10639
- body: JSON.stringify({ appId: proj.app, designIssue: { issueId, ...(asPlanned ? {} : { files: chosen }), planKey: plan.planKey } }) });
11276
+ body: JSON.stringify({ appId: proj.app, designIssue: { issueId, ...(asPlanned ? {} : { files: chosen }), planKey: plan.planKey }, ...consent }) });
10640
11277
  if (current !== proj) return;
10641
11278
  const n = plan.included.length;
10642
11279
  const issue = kbDsIssueById(issueId);
10643
- showToast(`Read queued — ${n} file${n === 1 ? '' : 's'} of “${(issue && issue.label) || 'the issue'}” for your terminal AI`, 'ok');
11280
+ revisionQueuedToasts(res, 'Read queued', `${n} file${n === 1 ? '' : 's'} of “${(issue && issue.label) || 'the issue'}” for your terminal AI`);
10644
11281
  track('kb_design_issue_read', { app: proj.app, n });
10645
11282
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
10646
11283
  kbDsClosePanel({ issueId, control: '[data-kb-ds-read]' });
@@ -10766,6 +11403,7 @@
10766
11403
  }
10767
11404
  if ((b = t('[data-kb-ds-all]'))) { kbDsShowAll.add(b.dataset.kbDsAll); kbDsFocus = { issueId: b.dataset.kbDsAll, control: `.kb-ds-file:nth-child(${KB_DS_FILES_SHOWN + 1}) .kb-fname` }; kbDsRepaint(); return true; }
10768
11405
  if ((b = t('[data-kb-ds-read]'))) { kbDsOpenRead(b.dataset.kbDsRead); return true; }
11406
+ if ((b = t('.kb-ds-panel [data-rev-build]')) && kbDsChooseBuild(b)) return true;
10769
11407
  if ((b = t('[data-kb-ds-read-go]'))) { kbDsReadGo(b.dataset.kbDsReadGo, b.closest('.kb-ds-issue')?.querySelector('[data-kb-ds-read]')); return true; }
10770
11408
  if ((b = t('[data-kb-ds-requests]'))) { if (bridge.openRequest) bridge.openRequest(null); return true; }
10771
11409
  if ((b = t('[data-kb-ds-jump]'))) {
@@ -10778,6 +11416,7 @@
10778
11416
  }
10779
11417
  // Ticks and typing in a panel are kept in its state, so a repaint redraws them as they were.
10780
11418
  $wsKnowledge.addEventListener('change', (e) => {
11419
+ if (e.target.closest('.kb-ds-panel [data-rev-build-auto]') && kbDsChooseBuild(e.target)) return;
10781
11420
  const pick = e.target.closest('[data-kb-ds-pick], [data-kb-ds-add-pick]');
10782
11421
  if (!pick || !kbDsPanel) return;
10783
11422
  if (kbDsPanel.kind === 'read' && pick.dataset.kbDsPick !== undefined) {
@@ -11207,6 +11846,16 @@
11207
11846
  return `Takes ${humanRange(lo * n, hi * n)}${each}. This project's other exports wait until it finishes.`;
11208
11847
  }
11209
11848
 
11849
+ /** What the Render dialog says it will draw, from the export source the person has selected. */
11850
+ function renderSourceSentence(source) {
11851
+ const kind = source && source.selector && source.selector.kind;
11852
+ if (kind === 'working') return 'Renders the working copy: a DRAFT, not an approved version.';
11853
+ if (kind === 'checkpoint') return 'Renders a saved checkpoint: a DRAFT, not an approved version.';
11854
+ if (kind === 'approved' && source.version) return `Renders approved version v${source.version}, not the latest.`;
11855
+ if (kind === 'latest-approved' && source.version) return `Renders the latest approved version, v${source.version}.`;
11856
+ return 'Renders the approved model.';
11857
+ }
11858
+
11210
11859
  async function askRenderOptions(projectId) {
11211
11860
  // `viewpoints` (plural) — the shape doExport actually reads. This said `viewpoint` and would
11212
11861
  // have thrown on `.length` the moment it was reached.
@@ -11216,7 +11865,8 @@
11216
11865
  title: 'Render image',
11217
11866
  // The Tekla card in this same grid genuinely mutates a live host model, so users have an
11218
11867
  // earned reason to be wary of buttons here. Say plainly that this one only reads.
11219
- sub: 'Renders the approved model. Nothing in your model changes.',
11868
+ // Names the source it will really render (#2781): the dialog used to say "the approved model" while a DRAFT was selected.
11869
+ sub: `${renderSourceSentence(currentExportSourceOption())} Nothing in your model changes.`,
11220
11870
  okLabel: 'Render',
11221
11871
  // The estimate has to be live: it is the product of two fields (how many angles × how dear
11222
11872
  // each is), so no fixed label can state it. This is the difference between choosing five
@@ -11749,6 +12399,65 @@
11749
12399
  `</span></div>`;
11750
12400
  }
11751
12401
 
12402
+ /**
12403
+ * #2521 row 5b: the file on this card was made from a Quick (or possibly Quick) model, said after the export toast is
12404
+ * gone, and where the file itself carries it. Read from the file's own receipt. A picture saved without its caption
12405
+ * says so on a line of its own; an IFC from an older AWARE says what a newer one would add.
12406
+ */
12407
+ function exportProvenanceHtml(kind, approved) {
12408
+ if (!approved || !exportState) return '';
12409
+ // The bill card fronts three files, each with its own receipt: each format whose file carries a label gets a line.
12410
+ const BOM_FORMATS = [['bom-csv', 'CSV'], ['bom-xlsx', 'Excel workbook'], ['bom-html', 'HTML report']];
12411
+ const kinds = kind === 'bom' ? BOM_FORMATS : omittedKindsFor(kind).map((k) => [k, '']);
12412
+ const files = [];
12413
+ for (const [k, format] of kinds) {
12414
+ const entry = exportState[k];
12415
+ if (!entry) continue;
12416
+ const sources = Array.isArray(entry.variants) && entry.variants.length ? entry.variants : [entry];
12417
+ const record = (sources.find((source) => source && source.provenance) || {}).provenance;
12418
+ if (!record || typeof record.label !== 'string') continue;
12419
+ files.push({ record, format });
12420
+ if (kind !== 'bom') break;
12421
+ }
12422
+ if (!files.length) return '';
12423
+ const carriersOf = (record) => (Array.isArray(record.carriers) ? record.carriers : []);
12424
+ const lines = [];
12425
+ // The label once when every file shares it; each file on its own line, named first, when they were exported at
12426
+ // different times and say different things (design review of row 5b).
12427
+ if (files.length > 1 && files.every((f) => f.record.label === files[0].record.label)) {
12428
+ const extras = files.flatMap((f) => carriersOf(f.record).filter((c) => c !== 'file-name').map((c) => provenanceWhere(c, f.format))).filter(Boolean);
12429
+ lines.push(`${files[0].record.label}. ${files.length === 2 ? 'Both' : `All ${files.length}`} files say so: in the file name${extras.length ? `, plus ${joinAnd(extras)}` : ''}.`);
12430
+ } else {
12431
+ if (files.length > 1) lines.push('These files were exported at different times, so they don\'t all say the same thing.');
12432
+ for (const f of files) {
12433
+ const where = carriersOf(f.record).map((c) => provenanceWhere(c, '')).filter(Boolean);
12434
+ lines.push(`${f.format ? `${f.format}: ` : ''}${f.record.label}. Says so in ${joinAnd(where.length ? where : ['the file name'])}.`);
12435
+ }
12436
+ }
12437
+ if (files.some((f) => f.record.captionDeclined)) lines.push('Rendered without the caption: the label is in the file name only.');
12438
+ // What to do next is a hint, not a warning: muted, so amber stays the label's alone.
12439
+ const hint = files.some((f) => carriersOf(f.record).includes('ifc-project-name'))
12440
+ ? '<div class="e-receipt stale"><span>Update AWARE from the bottom bar, then export again, to also write it into the IFC header and project properties.</span></div>'
12441
+ : '';
12442
+ return `<div class="e-receipt partial"><ul class="e-receipt-lines">${lines.map((line) => `<li>${escapeHtml(line)}</li>`).join('')}</ul></div>${hint}`;
12443
+ }
12444
+
12445
+ /** Where a file carries its label, in the card's words; `format` names the file when several share one line. */
12446
+ function provenanceWhere(carrier, format) {
12447
+ const WHERE = {
12448
+ 'file-name': 'the file name', 'report-banner': format ? `a note at the top of the ${format}` : 'a note at the top of the report',
12449
+ 'xlsx-about': format ? `an About sheet in the ${format === 'Excel workbook' ? 'workbook' : format}` : 'an About sheet',
12450
+ 'ifc-header': 'the IFC header', 'ifc-pset': 'the project properties', 'ifc-project-name': 'the IFC project name',
12451
+ 'glb-extras': 'the 3D file metadata', 'render-caption': 'a caption drawn into the picture',
12452
+ };
12453
+ return WHERE[carrier] || '';
12454
+ }
12455
+
12456
+ /** "a", "a and b", "a, b and c". */
12457
+ function joinAnd(items) {
12458
+ return items.length <= 1 ? (items[0] || '') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`;
12459
+ }
12460
+
11752
12461
  function receiptHtml(kind, approved) {
11753
12462
  const receipt = approved ? currentReceipt(kind) : null;
11754
12463
  if (!receipt) return '';
@@ -12547,6 +13256,55 @@
12547
13256
  };
12548
13257
  }
12549
13258
 
13259
+ // #2781: the DRAFT exports on a card, from the working copy or a saved checkpoint. Kept apart from the approved rows
13260
+ // above them on purpose: no tick (a tick means deliverable), a DRAFT pill, and a sentence that says what they are.
13261
+ const DRAFT_KIND_LABELS = {
13262
+ 'bom-csv': 'CSV', 'bom-xlsx': 'Excel', 'bom-html': 'Report', ifc: 'IFC', svg: 'SVG',
13263
+ 'render-png': 'Image', 'render-mp4': 'Turntable video',
13264
+ };
13265
+ const DRAFT_ROWS_SHOWN = 4;
13266
+ /** The DRAFT files that belong on this card, newest first (the server already sorted them). */
13267
+ function draftExportsFor(c) {
13268
+ const kinds = c.kind === 'bom' ? ['bom-csv', 'bom-xlsx', 'bom-html'] : c.kind === 'render' ? ['render-png', 'render-mp4'] : [c.kind];
13269
+ return exportDrafts.filter((d) => kinds.includes(d.kind));
13270
+ }
13271
+ /** "14:02" for today; "25 Oct 14:02" otherwise, so an old draft is not mistaken for a new one. */
13272
+ function draftWhen(iso) {
13273
+ const d = new Date(iso);
13274
+ if (isNaN(d.getTime())) return '';
13275
+ const now = new Date();
13276
+ if (d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate()) return hhmm(iso);
13277
+ return `${d.getDate()} ${['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()]} ${hhmm(iso)}`;
13278
+ }
13279
+ function draftExportsHtml(c) {
13280
+ const rows = draftExportsFor(c);
13281
+ if (!rows.length) return '';
13282
+ const shown = rows.slice(0, DRAFT_ROWS_SHOWN);
13283
+ const head = rows[0];
13284
+ const from = head.source === 'checkpoint' ? 'a saved checkpoint' : 'the working copy';
13285
+ const named = new Map();
13286
+ const list = shown.map((d) => {
13287
+ const label = DRAFT_KIND_LABELS[d.kind] || d.kind;
13288
+ const when = draftWhen(d.exportedAt);
13289
+ // The instance names WHICH draft file, so `?` can tell two of them apart: two drafts of one kind made in the same
13290
+ // minute (a re-export, several viewpoints) get a number. An IFC has no Open: no default app opens one usefully,
13291
+ // so it is not offered rather than offered and refused.
13292
+ const base = `${label} draft ${when}`.trim();
13293
+ const nth = (named.get(base) || 0) + 1;
13294
+ named.set(base, nth);
13295
+ const instance = nth > 1 ? `${base} (${nth})` : base;
13296
+ const key = `draft:${d.filename}`;
13297
+ return `<li class="e-draft-row"><span class="e-draft-what">${escapeHtml(label)} <span class="t">${escapeHtml(when)}</span></span>` +
13298
+ `<span class="e-links">${d.kind === 'ifc' ? '' : fileActionButton('open', { kind: key, instance })}${fileActionButton('reveal', { kind: key, instance })}</span></li>`;
13299
+ }).join('');
13300
+ const more = rows.length > shown.length
13301
+ ? `<div class="e-draft-more">+${rows.length - shown.length} older draft file${rows.length - shown.length === 1 ? '' : 's'} in the exports folder</div>` : '';
13302
+ return `<div class="e-draft" role="group" aria-label="Draft exports, not an approved version">` +
13303
+ `<div class="e-draft-head"><span class="e-draft-pill">DRAFT</span><span class="e-draft-cap">not an approved version</span></div>` +
13304
+ `<ul class="e-draft-list">${list}</ul>${more}` +
13305
+ `<div class="e-draft-note">Made from ${from} at ${escapeHtml(draftWhen(head.exportedAt))}. The model may have changed since.</div></div>`;
13306
+ }
13307
+
12550
13308
  function cardHtml(c, approved) {
12551
13309
  let meta;
12552
13310
  const busy = exportBusy.has(`${current.id}:${c.kind}`);
@@ -12581,6 +13339,10 @@
12581
13339
  meta = `<span class="e-status">not exported yet</span>`;
12582
13340
  }
12583
13341
  }
13342
+ // #2781: with DRAFT files listed below, "not exported yet" would say the opposite of what is on screen, and the
13343
+ // approved line is about approved versions only: say that.
13344
+ const drafts = draftExportsHtml(c);
13345
+ if (drafts && meta) meta = meta.replace('not exported yet', 'no approved export yet').replace('not rendered yet', 'no approved render yet');
12584
13346
  const exported = approved && c.file && exportState && exportState[c.kind] && exportState[c.kind].exportedAt;
12585
13347
  // Re-labelled once a link exists, mirroring the file kinds' "Re-export" convention. Gated on the
12586
13348
  // in-memory record rather than exportState, which only ever tracks file exports.
@@ -12641,6 +13403,7 @@
12641
13403
  `<div class="e-top"><div class="e-ico">${escapeHtml(c.ico)}</div>` +
12642
13404
  `<div><div class="e-name">${escapeHtml(c.name)}</div><div class="e-fmt">${escapeHtml(c.fmt)}</div></div></div>` +
12643
13405
  `<div class="e-meta${special ? ' e-meta-stacked' : ''}">${meta}</div>` +
13406
+ drafts +
12644
13407
  // Only the still gets a preview: an MP4 has no frame to show without decoding one, and a
12645
13408
  // card is not a video player. Click opens it exactly like ⧉ Open — no lightbox.
12646
13409
  (c.kind === 'render' && approved && exportState && exportState['render-png']
@@ -12665,6 +13428,7 @@
12665
13428
  // says what the producer could not emit from what it was given, this says what was never
12666
13429
  // given to it. A model missing three heights and an AWARE weld failure are not one fact.
12667
13430
  (c.kind === 'send-host' ? '' : omittedHtml(c.kind, approved)) +
13431
+ (c.kind === 'send-host' ? '' : exportProvenanceHtml(c.kind, approved)) +
12668
13432
  // REGISTERED, because #1156a changed what this button DOES. It used to refuse an export outright
12669
13433
  // when any member's endpoint elevation was unresolved; now the file exports build what they can
12670
13434
  // and name what they left out, while a bake into a live host still refuses (and says why). A
@@ -12732,17 +13496,18 @@
12732
13496
  const out = [];
12733
13497
  // #2449: each approved source carries its own frozen connection-assumptions label from the server, bound to it.
12734
13498
  const frozen = (row) => (row && row.connectionAssumptions && typeof row.connectionAssumptions.note === 'string' ? row.connectionAssumptions : null);
12735
- if (data.default) out.push({ selector: { kind: 'latest-approved' }, label: `Latest approved · v${data.default.version}`, group: 'Recommended', version: data.default.version, assumptions: frozen(data.default) });
13499
+ // #2521 row 5: `quick` first, so each option keeps the exact shape the #2449 checks read.
13500
+ if (data.default) out.push({ quick: data.default.quick, selector: { kind: 'latest-approved' }, label: `Latest approved · v${data.default.version}`, group: 'Recommended', version: data.default.version, assumptions: frozen(data.default) });
12736
13501
  if (data.working) out.push({
12737
13502
  selector: {
12738
13503
  kind: 'working', expectedEtag: data.working.etag,
12739
13504
  ...(data.working.epoch !== null && Number.isInteger(Number(data.working.epoch)) ? { expectedEpoch: Number(data.working.epoch) } : {}),
12740
13505
  },
12741
- label: 'Working copy · DRAFT', group: 'Drafts',
13506
+ label: 'Working copy · DRAFT', group: 'Drafts', quick: data.working.quick,
12742
13507
  });
12743
- for (const saved of data.checkpoints || []) out.push({ selector: { kind: 'checkpoint', checkpointId: saved.checkpointId, expectedHash: saved.hash }, label: `Checkpoint ${String(saved.checkpointId).slice(0, 8)} · DRAFT`, group: 'Drafts', sub: saved.baseVersion ? `Pending work from v${saved.baseVersion}` : 'No approved baseline' });
13508
+ for (const saved of data.checkpoints || []) out.push({ selector: { kind: 'checkpoint', checkpointId: saved.checkpointId, expectedHash: saved.hash }, label: `Checkpoint ${String(saved.checkpointId).slice(0, 8)} · DRAFT`, group: 'Drafts', sub: saved.baseVersion ? `Pending work from v${saved.baseVersion}` : 'No approved baseline', quick: saved.quick });
12744
13509
  for (const row of data.defaultUnavailable?.reason === 'refused' ? [] : (data.approved || [])) {
12745
- if (!data.default || Number(row.version) !== Number(data.default.version)) out.push({ selector: { kind: 'approved', version: row.version }, label: `Older approved · v${row.version}`, group: 'Approved history', version: row.version, assumptions: frozen(row) });
13510
+ if (!data.default || Number(row.version) !== Number(data.default.version)) out.push({ quick: row.quick, selector: { kind: 'approved', version: row.version }, label: `Older approved · v${row.version}`, group: 'Approved history', version: row.version, assumptions: frozen(row) });
12746
13511
  }
12747
13512
  return out;
12748
13513
  }
@@ -12753,6 +13518,15 @@
12753
13518
  const key = JSON.stringify(exportSourcesState.selected);
12754
13519
  const found = options.find((option) => JSON.stringify(option.selector) === key);
12755
13520
  if (found) return found;
13521
+ // #2781: a DRAFT choice survives an export. Exporting saves the working copy, which moves its etag/epoch, so
13522
+ // the exact selector no longer matches the refreshed list; the person's choice is the KIND (and which
13523
+ // checkpoint), and the export re-reads the live identity when it starts anyway.
13524
+ const want = exportSourcesState.selected;
13525
+ if (want.kind === 'working' || want.kind === 'checkpoint') {
13526
+ const kept = options.find((option) => option.selector.kind === want.kind
13527
+ && (want.kind === 'working' || option.selector.checkpointId === want.checkpointId));
13528
+ if (kept) return kept;
13529
+ }
12756
13530
  }
12757
13531
  return options.find((option) => option.selector.kind === 'latest-approved') || null;
12758
13532
  }
@@ -12775,7 +13549,7 @@
12775
13549
  const rows = options.filter((option) => option.group === group);
12776
13550
  if (!rows.length) return '';
12777
13551
  return `<div class="export-source-group" role="group" aria-label="${escapeAttr(group)}"><div class="export-source-group-label">${escapeHtml(group)}</div>`
12778
- + rows.map((option) => { const key = JSON.stringify(option.selector); return `<button type="button" class="export-source-option${key === selectedKey ? ' selected' : ''}" role="option" aria-selected="${String(key === selectedKey)}" data-export-source="${escapeAttr(key)}"><span>${escapeHtml(option.label)}</span>${option.sub ? `<small>${escapeHtml(option.sub)}</small>` : ''}</button>`; }).join('') + '</div>';
13552
+ + rows.map((option) => { const key = JSON.stringify(option.selector); const quickTip = quickPillHtml(option.quick) ? ` data-tip="${escapeAttr(`${option.label}: ${option.quick.label}. ${option.quick.tip || ''}`.trim())}"` : ''; return `<button type="button" class="export-source-option${key === selectedKey ? ' selected' : ''}" role="option" aria-selected="${String(key === selectedKey)}" data-export-source="${escapeAttr(key)}"${quickTip}><span>${escapeHtml(option.label)}${quickPillHtml(option.quick, { scope: option.label, focusable: false })}</span>${option.sub ? `<small>${escapeHtml(option.sub)}</small>` : ''}</button>`; }).join('') + '</div>';
12779
13553
  }).join('');
12780
13554
  let warning = '';
12781
13555
  if (data.defaultUnavailable?.reason === 'refused') {
@@ -12804,6 +13578,47 @@
12804
13578
  return selectedSourceAssumptionsHtml(source) + exportedFilesAssumptionsHtml(source);
12805
13579
  }
12806
13580
 
13581
+ /**
13582
+ * #2521 row 5: what the SELECTED source rests on, and, separately, what the version the listed files came from rests
13583
+ * on (from the same answer as the files), so neither line speaks for the other's document.
13584
+ */
13585
+ function exportsQuickHtml() {
13586
+ const source = currentExportSourceOption();
13587
+ if (!source) return '';
13588
+ const line = (q, scope) => (quickPillHtml(q) ? `<div class="export-quick-note" role="note"><b>${escapeHtml(scope)}:</b> ${escapeHtml(q.label)}. ${escapeHtml(q.tip || '')}</div>` : '');
13589
+ const selected = line(source.quick, source.label);
13590
+ // #2521 row 5b: said BEFORE exporting, when this AWARE can only put a Quick model's label in an IFC's names.
13591
+ const ifcNamesOnly = quickPillHtml(source.quick) && exportSourcesState.data && exportSourcesState.data.exportProvenance === 'name-only'
13592
+ ? '<div class="export-quick-note" role="note">An IFC exported now carries this label in its file name and project name only. Update AWARE from the bottom bar to also write it into the file\'s header and project properties.</div>'
13593
+ : '';
13594
+ const from = exportStateFrom;
13595
+ const files = from && from.quick && exportState && Object.values(exportState).some((e) => e && e.exportedAt)
13596
+ && !(source.selector.kind === 'latest-approved' && Number(source.version) === Number(from.version))
13597
+ ? line(from.quick, `Files below, exported from v${from.version}`) : '';
13598
+ return selected + ifcNamesOnly + files;
13599
+ }
13600
+
13601
+ /**
13602
+ * #2675: the listed files come from the latest approved version even while the working copy has unapproved
13603
+ * edits, or while another source (a DRAFT, an older version) is selected. Without this line a ✓ on a card reads as if it covered those
13604
+ * edits. Neutral, not a warning: the files are correct, they are just not the current draft. Silent while
13605
+ * the working copy is still signed off, when the files and the model agree.
13606
+ */
13607
+ function exportedFromNoteHtml() {
13608
+ const from = exportStateFrom;
13609
+ if (!from || !Number.isInteger(Number(from.version))) return '';
13610
+ if (!exportState || !Object.values(exportState).some((e) => e && e.exportedAt)) return '';
13611
+ // Silent only when the selected source IS the version the files came from and the model has not moved on.
13612
+ // A DRAFT, a checkpoint or an older approved version selected is a different source from these files.
13613
+ const source = currentExportSourceOption();
13614
+ const sel = source && source.selector;
13615
+ const sameSource = !!sel && (sel.kind === 'latest-approved'
13616
+ || (sel.kind === 'approved' && Number(sel.version) === Number(from.version)));
13617
+ if (current && current.approvedAt && sameSource) return '';
13618
+ return `<div class="exports-note exports-from-note" role="note">These files were exported from approved v${escapeHtml(String(from.version))}. ` +
13619
+ 'Changes made since then are not in them.</div>';
13620
+ }
13621
+
12807
13622
  /**
12808
13623
  * The files already listed on the cards were exported from the LATEST approved version (the listing only returns
12809
13624
  * receipts for it). While another source is selected the note above describes that source, so the written files
@@ -12899,10 +13714,12 @@
12899
13714
  // caption. The note's job — per the comment above — is to justify the exports-FOLDER button
12900
13715
  // staying enabled, not to claim the export actions work unapproved. "Polishing is optional" was
12901
13716
  // the true and useful half, and it survives; only the opening clause overreached.
13717
+ html += exportsQuickHtml(); // #2521 row 5: what the selected source and the listed files rest on
12902
13718
  html += exportsAssumptionsHtml();
12903
13719
  html += `<div class="exports-note"><b>Any saved source can be exported</b> — approved is the safe default, while DRAFT and older versions stay explicit. Polishing further ` +
12904
13720
  `is optional. Each writes to this project’s <button type="button" class="exports-note-link" data-open-exports-folder ` +
12905
13721
  `aria-label="Open the exports folder" data-tip="Open this project’s exports folder">▤ exports</button> folder.</div>`;
13722
+ html += exportedFromNoteHtml();
12906
13723
  const cards = (wsApp() && wsApp().exports) || [];
12907
13724
  html += '<div class="export-grid">' + cards.map((c) => cardHtml(c, approved)).join('') + '</div>';
12908
13725
  $wsExports.innerHTML = html;
@@ -13148,6 +13965,7 @@
13148
13965
  let state = null;
13149
13966
  let units = null; // the server's answer, applied below the staleness guard with the others
13150
13967
  let filesFrom = null; // #2449: the approved version the listed files came from, same rule
13968
+ let draftRows = []; // #2781: the DRAFT files from the same answer
13151
13969
  // SAYS THE THING THE GUARD MEANS. `if (units)` was correct only because the ternary above can
13152
13970
  // never produce a falsy value — so a later, entirely reasonable "report what the server actually
13153
13971
  // said, stop coercing" change to `units = r.units` would silently re-enable the resurrected-
@@ -13205,7 +14023,10 @@
13205
14023
  if (!sourcesRefused && sourceResult.status === 'fulfilled') {
13206
14024
  exportSourcesState.status = 'ready';
13207
14025
  exportSourcesState.data = sourceResult.value;
13208
- if (!currentExportSourceOption()) exportSourcesState.selected = null;
14026
+ const keptOption = currentExportSourceOption();
14027
+ if (!keptOption) exportSourcesState.selected = null;
14028
+ // #2781: a kept DRAFT choice adopts the refreshed identity, so the list highlights it and the next export freezes it.
14029
+ else if (exportSourcesState.selected && keptOption.selector.kind !== 'latest-approved') exportSourcesState.selected = keptOption.selector;
13209
14030
  } else {
13210
14031
  exportSourcesState = { status: 'unavailable', data: null, selected: null, open: false };
13211
14032
  }
@@ -13235,6 +14056,7 @@
13235
14056
  // there for why.
13236
14057
  answered = true;
13237
14058
  approvedAt = r.approvedAt || undefined;
14059
+ draftRows = Array.isArray(r.drafts) ? r.drafts.filter((d) => d && typeof d.kind === 'string' && typeof d.filename === 'string' && typeof d.path === 'string') : [];
13238
14060
  filesFrom = r.receiptsFrom && Number.isInteger(r.receiptsFrom.version) && typeof r.receiptsFrom.hash === 'string' ? r.receiptsFrom : null;
13239
14061
  units = r.units === 'mm' ? 'mm' : 'ft-in';
13240
14062
  } else {
@@ -13265,7 +14087,7 @@
13265
14087
  if (answered) current.approvedAt = approvedAt;
13266
14088
  exportState = state;
13267
14089
  exportStateFrom = answered ? filesFrom : null;
13268
- syncWorkspaceGuide(); // fresh approve/export state → tick the Export (and re-sync Approve) guide rows
14090
+ exportDrafts = answered ? draftRows : [];
13269
14091
  paintExports(approvedAt, restoreKind);
13270
14092
  }
13271
14093
 
@@ -13273,7 +14095,11 @@
13273
14095
  })();
13274
14096
 
13275
14097
  async function captureSelectedExportSources(projectId, copies = 1, selectedSelector = null) {
13276
- const option = selectedSelector ? { selector: selectedSelector } : currentExportSourceOption();
14098
+ // A pinned selector (Send to a CAD app) is checked against the label the list shows for that same source.
14099
+ const listedOption = selectedSelector
14100
+ ? exportSourceOptions(exportSourcesState.data).find((o) => JSON.stringify(o.selector) === JSON.stringify(selectedSelector))
14101
+ : null;
14102
+ const option = selectedSelector ? { selector: selectedSelector, quick: listedOption ? (listedOption.quick || null) : undefined } : currentExportSourceOption();
13277
14103
  if (!option) throw new Error('Choose an export source first.');
13278
14104
  let selector = option.selector;
13279
14105
  if (option.selector.kind === 'working') {
@@ -13288,6 +14114,15 @@
13288
14114
  method: 'POST', body: JSON.stringify({ selector, copies }),
13289
14115
  });
13290
14116
  if (!captured || !captured.source || !captured.source.handleId) throw new Error('The export source could not be frozen.');
14117
+ // #2521 row 5: the frozen source says what IT rests on. When that differs from the label the list showed (an
14118
+ // approval or a save landed in between), say what is really being exported and repaint the list from the server.
14119
+ const listed = option.quick && option.quick.state !== 'precise' ? option.quick : null;
14120
+ const frozen = captured.source.quick && captured.source.quick.state !== 'precise' ? captured.source.quick : null;
14121
+ // A pinned selector with no listed label to compare (an older caller) is not second-guessed.
14122
+ if ((!selectedSelector || option.quick !== undefined) && (listed && listed.label) !== (frozen && frozen.label)) {
14123
+ showToast(`This source changed since the list was shown. What is being exported: ${frozen ? `${frozen.label}.` : 'a model that rests on no AI decisions.'}`, 'info');
14124
+ if (current && current.id === projectId) safeRenderExports('after the export source changed');
14125
+ }
13291
14126
  return Array.isArray(captured.sources) && captured.sources.length === copies ? captured.sources : [captured.source];
13292
14127
  }
13293
14128
 
@@ -13303,7 +14138,7 @@
13303
14138
  const result = await api(`/api/projects/${encodeURIComponent(projectId)}/export-raw`, {
13304
14139
  method: 'POST', body: JSON.stringify({ sourceHandle: source.handleId }),
13305
14140
  });
13306
- exportSourcesState.selected = null;
14141
+ if (!(source.kind === 'working' || source.kind === 'checkpoint')) exportSourcesState.selected = null; // a DRAFT choice is kept (#2781)
13307
14142
  showToast(`Exported raw package — ${result.filename}`, 'ok');
13308
14143
  // Through the wrapper, and that is the POINT here rather than tidiness: this `await` sits
13309
14144
  // inside a try whose catch says "Raw export failed", so a repaint bug used to be reported to
@@ -13314,6 +14149,15 @@
13314
14149
  }
13315
14150
  }
13316
14151
 
14152
+ /**
14153
+ * A failed attempt must not leave its in-memory receipt standing as this attempt's result, but a DRAFT attempt never
14154
+ * wrote the approved file's record in the first place (#2781), so a failed one leaves that record alone.
14155
+ */
14156
+ function forgetExportReceiptAfterFailure(projectId, kind, source) {
14157
+ if (source && (source.kind === 'working' || source.kind === 'checkpoint')) return;
14158
+ exportReceipts.delete(`${projectId}:${kind}`);
14159
+ }
14160
+
13317
14161
  async function doExport(kind) {
13318
14162
  if (!current) return;
13319
14163
  // Sending to a CAD application is its own flow end to end: it asks WHERE first, then performs
@@ -13427,9 +14271,14 @@
13427
14271
  try {
13428
14272
  // Render and the BOM are the exports whose POST carries a body — the options their modal collected.
13429
14273
  const body = renderOptions || bomOptions;
13430
- const res = await api(exportUrl(kind, projectId, app, capturedSource.handleId), body
13431
- ? { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }
13432
- : { method: 'POST' });
14274
+ // #2521 row 5b: a render of a Quick model may ask how to continue (the caption). Answered here, so the render
14275
+ // proceeds only once the person has chosen; a cancelled question ends it, having said what was saved.
14276
+ const res = kind === 'render'
14277
+ ? await postRenderAnsweringCaption(projectId, app, capturedSource.handleId, body)
14278
+ : await api(exportUrl(kind, projectId, app, capturedSource.handleId), body
14279
+ ? { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }
14280
+ : { method: 'POST' });
14281
+ if (res === null) { refreshing = true; return safeRenderExports('after that render'); }
13433
14282
  if (kind === 'bom') {
13434
14283
  // The batch answers per format. A 200 here means SOMETHING landed, not that everything did —
13435
14284
  // so the toast names what failed rather than letting a green tick stand for a partial run, and
@@ -13444,7 +14293,10 @@
13444
14293
  + (failed[0].error || 'no reason given'),
13445
14294
  'warn');
13446
14295
  } else {
13447
- showToast(`Exported — ${ok.map((r) => nameOf(r.format)).join(', ')}`, 'ok');
14296
+ // #2521 row 5b: a bill made from a Quick (or possibly Quick) model says so; the files carry it too.
14297
+ const quick = (ok.find((r) => r.quick && r.quick.label) || {}).quick;
14298
+ showToast(`Exported — ${ok.map((r) => nameOf(r.format)).join(', ')}${quick ? ` — ${quick.label}, named in the files` : ''}`,
14299
+ quick && quick.state === 'unknown' ? 'warn' : 'ok');
13448
14300
  }
13449
14301
  // Per FORMAT, so the analytics keep the granularity the two separate cards used to give.
13450
14302
  for (const r of ok) track('workspace_export', { app, kind: `bom-${r.format}` });
@@ -13455,15 +14307,22 @@
13455
14307
  return safeRenderExports('after that bill of materials export', undefined,
13456
14308
  () => { if (current && current.id === projectId) paintExports(current.approvedAt); });
13457
14309
  }
13458
- exportSourcesState.selected = null; // non-default sources are one-shot; a later export returns to latest approved
14310
+ // Non-default APPROVED sources are one-shot; a later export returns to latest approved. A DRAFT choice is kept (#2781):
14311
+ // the person chose it on purpose, the banner under the selector keeps saying it is unapproved, and the card lists
14312
+ // what it produced as DRAFT.
14313
+ const draftExport = capturedSource.kind === 'working' || capturedSource.kind === 'checkpoint';
14314
+ if (!draftExport) exportSourcesState.selected = null;
13459
14315
  track('workspace_export', { app, kind, sourceKind: capturedSource.kind }); // a successful export/bake
13460
- if (res.counts) exportReceipts.set(`${projectId}:${kind}`, {
14316
+ // A DRAFT export's counts never replace the approved file's in-memory receipt (#2781): that record is what the card
14317
+ // shows as the approved export's counts and warnings, and a draft is not one.
14318
+ const receiptNow = res.counts ? {
13461
14319
  counts: res.counts,
13462
14320
  warnings: res.warnings || [],
13463
14321
  unsupported: res.receipt && Array.isArray(res.receipt.unsupported) ? res.receipt.unsupported : [],
13464
14322
  approvedAt,
13465
- });
13466
- const summary = receiptSummary(exportReceipts.get(`${projectId}:${kind}`), kind);
14323
+ } : null;
14324
+ if (receiptNow && !draftExport) exportReceipts.set(`${projectId}:${kind}`, receiptNow);
14325
+ const summary = receiptSummary(draftExport ? receiptNow : exportReceipts.get(`${projectId}:${kind}`), kind);
13467
14326
  // #1156a: an export that LEFT MEMBERS OUT must not announce itself as clean. The two sources
13468
14327
  // are different questions - the receipt says what the producer could not emit from what it was
13469
14328
  // given, `skippedDetail` says what was never given to it - so BOTH are gathered before a single
@@ -13474,10 +14333,12 @@
13474
14333
  summary && summary.partial ? summary.text : null,
13475
14334
  omittedNow ? `${omittedNow} member${omittedNow === 1 ? '' : 's'} left out — see the card for why` : null,
13476
14335
  ].filter(Boolean);
14336
+ // #2521 row 5b: a file made from a Quick (or possibly Quick) model says so here too; the file carries it as well.
14337
+ const quickBit = res.quick && res.quick.label ? ` — ${res.quick.label}, named in the file` : '';
13477
14338
  showToast(gaps.length
13478
- ? `Exported with gaps — ${gaps.join(' · ')}`
13479
- : `Exported — ${res.filename || kind}`,
13480
- gaps.length ? 'warn' : 'ok');
14339
+ ? `Exported with gaps — ${gaps.join(' · ')}${quickBit}`
14340
+ : `Exported — ${res.filename || kind}${quickBit}`,
14341
+ gaps.length || (res.quick && res.quick.state === 'unknown') ? 'warn' : 'ok');
13481
14342
  refreshing = true;
13482
14343
  // The catch is what makes the finally's skip safe: if the refresh itself throws, nothing else
13483
14344
  // would repaint and the card would sit in its busy state forever, with exportBusy already
@@ -13489,7 +14350,7 @@
13489
14350
  } catch (err) {
13490
14351
  // The durable export listing may still show the previously published file, but its in-session
13491
14352
  // receipt must not masquerade as the result of this failed attempt.
13492
- exportReceipts.delete(`${projectId}:${kind}`);
14353
+ forgetExportReceiptAfterFailure(projectId, kind, capturedSource);
13493
14354
  // The render route ships machine-readable readiness on its 409 precisely so the card can
13494
14355
  // show WHICH dependency broke. Dropping it left the card looking ready with an enabled
13495
14356
  // button, and the only trace of the refusal was a toast that evaporates.
@@ -13523,6 +14384,66 @@
13523
14384
  }
13524
14385
  }
13525
14386
 
14387
+ /**
14388
+ * #2521 row 5b: POST a render, answering the question a Quick model's render asks when the renderer cannot draw the
14389
+ * Quick model caption (owner ruling 2026-10-24: ask, default update). Each answer renders the same frozen version
14390
+ * the server handed back; pictures already saved stay saved. Resolves the render's answer, or null when the person
14391
+ * cancelled (after saying what was and was not saved).
14392
+ */
14393
+ async function postRenderAnsweringCaption(projectId, app, handleId, body) {
14394
+ let handle = handleId;
14395
+ let request = body;
14396
+ let saved = 0;
14397
+ for (;;) {
14398
+ try {
14399
+ return await api(exportUrl('render', projectId, app, handle),
14400
+ { method: 'POST', body: JSON.stringify(request), headers: { 'content-type': 'application/json' } });
14401
+ } catch (err) {
14402
+ const ask = err && err.body && err.body.needsChoice === 'caption' ? err.body : null;
14403
+ if (!ask) throw err;
14404
+ saved += Array.isArray(ask.rendered) ? ask.rendered.length : 0;
14405
+ const choice = await askRenderCaption(ask, projectId, saved);
14406
+ if (!choice) {
14407
+ try { await releaseCapturedSources(projectId, [ask.sourceHandle]); } catch { /* it expires on its own */ }
14408
+ const pending = Array.isArray(ask.pending) && ask.pending.length ? ask.pending : request.viewpoints || [];
14409
+ showToast(saved
14410
+ ? `Render stopped. ${saved} ${saved === 1 ? 'picture is' : 'pictures are'} saved; ${pending.join(', ')} ${pending.length === 1 ? 'was' : 'were'} not saved.`
14411
+ : 'Render stopped. Nothing was rendered.', 'info');
14412
+ return null;
14413
+ }
14414
+ handle = ask.sourceHandle;
14415
+ request = {
14416
+ ...request,
14417
+ ...(Array.isArray(ask.pending) && ask.pending.length ? { viewpoints: ask.pending } : {}),
14418
+ ...(choice === 'without-caption' ? { withoutCaption: true } : {}),
14419
+ };
14420
+ }
14421
+ }
14422
+ }
14423
+
14424
+ /** The caption question itself. Resolves 'update', 'without-caption', or null when cancelled. */
14425
+ async function askRenderCaption(ask, projectId, saved) {
14426
+ if (!bridge.formModal) return null;
14427
+ const chosen = await bridge.formModal({
14428
+ title: 'Quick model caption',
14429
+ sub: `${ask.message} Nothing more is rendered until you choose${saved ? `, and the ${saved === 1 ? 'picture' : 'pictures'} already saved stay saved` : ''}.`,
14430
+ okLabel: 'Continue',
14431
+ returnFocusTo: $wsExports.querySelector('[data-export="render"]'),
14432
+ returnFocusFallback: () => (current && current.id === projectId
14433
+ ? $wsExports.querySelector('[data-export="render"]')
14434
+ : null),
14435
+ fields: [{
14436
+ name: 'choice', label: 'How to continue', type: 'select', value: 'update', commandId: 'shell.render-caption-choice',
14437
+ options: [
14438
+ { value: 'update', label: 'Update the renderer', meta: 'Recommended · tries again now' },
14439
+ { value: 'without-caption', label: 'Render without the caption', meta: 'The label goes in the file name only. This is recorded.' },
14440
+ ],
14441
+ }],
14442
+ });
14443
+ if (!chosen) return null;
14444
+ return chosen.choice === 'without-caption' ? 'without-caption' : 'update';
14445
+ }
14446
+
13526
14447
  function showExportReceiptDetails(kind, returnFocusTo) {
13527
14448
  const projectId = current && current.id;
13528
14449
  const summary = receiptSummary(currentReceipt(kind), kind);
@@ -13633,9 +14554,13 @@
13633
14554
  * most recent.
13634
14555
  */
13635
14556
  async function fileAction(endpoint, kind, failMsg) {
13636
- const [baseKind, variant] = String(kind).split(':');
14557
+ // #2781: a DRAFT file is found by its own file name in the draft list, never through the approved rows.
14558
+ const draftName = String(kind).startsWith('draft:') ? String(kind).slice(6) : null;
14559
+ const [baseKind, variant] = draftName ? ['draft', ''] : String(kind).split(':');
13637
14560
  const row = exportState && exportState[baseKind];
13638
- const st = variant && row && Array.isArray(row.variants)
14561
+ const st = draftName
14562
+ ? exportDrafts.find((d) => d.filename === draftName)
14563
+ : variant && row && Array.isArray(row.variants)
13639
14564
  ? row.variants.find((v) => v.variant === variant)
13640
14565
  : row;
13641
14566
  if (!st || !st.path) return; // button only shows when a path exists; belt-and-braces
@@ -13764,6 +14689,10 @@
13764
14689
  // no SSE hook — and refreshes History on completion. Cards are DOM-built (textContent, never
13765
14690
  // innerHTML) so an AI-supplied error string can never reach the DOM as markup.
13766
14691
  let lastRevState = 'none';
14692
+ // #2816: 'none' above also means "the request list has not answered for this project yet". Only a
14693
+ // list that HAS answered may say the earlier drawing request is gone; before that, a pending read
14694
+ // (live, just written by the reader's shell PUT) would be reported as missing.
14695
+ let revisionListKnown = false;
13767
14696
  // A reconstruction refusal is permanent for that immutable staged generation. Remember it for this
13768
14697
  // browser session so the 3-second request poll cannot resurrect a Review action that the server has
13769
14698
  // already proved will never work. The exact stage id keeps a later replacement generation eligible.
@@ -13810,13 +14739,17 @@
13810
14739
  * miss without widening that window — an unknown project falls back to 0, exactly as a cold page
13811
14740
  * load always has.
13812
14741
  */
14742
+ let revisionBuildAsk = null; // #2521 row 7b: the open confirm step after the file picker, if any (askRevisionBuild)
13813
14743
  function resetRevisionState() {
13814
14744
  lastRevState = 'none';
14745
+ revisionListKnown = false;
13815
14746
  revCardReq = null;
13816
14747
  $revisionCard._renderKey = '';
13817
14748
  revisionGen++; // voids any render still in flight for the project being left
13818
14749
  revisionRequestsSuccessGen = revisionGen; // old same-id failures cannot cross a close/re-open boundary
13819
14750
  revisionOwnerGen++; // voids Attach/Copy work, without letting a routine poll do so
14751
+ if (revisionBuildAsk) revisionBuildAsk.close(null); // #2521 row 7b: its choice was for the project being left
14752
+ if (kbDsPanel && kbDsPanel.kind === 'read') kbDsPanel = null; // …and so was a design-set read panel's preset
13820
14753
  stopRevisionPoll();
13821
14754
  $revisionCard.hidden = true;
13822
14755
  $revisionCard.replaceChildren();
@@ -13936,16 +14869,192 @@
13936
14869
  }
13937
14870
  }
13938
14871
 
13939
- async function attachRevision(files) {
13940
- const proj = current; // capture — the user may switch projects during the async file reads / POST
14872
+ /**
14873
+ * #2521 row 7b: how a read of drawings into an existing Steel model project builds the model. The person chooses Quick
14874
+ * or Precise, preset to the working copy's own mode (the copy a re-read changes): Quick only when the model readably is
14875
+ * one. A model that reads "Possibly Quick model", or whose mode FloLess could not check, presets nothing and the person
14876
+ * presses one (owner ruling 2026-10-26: "Precise default but user must choose, no auto-default"). `members` says
14877
+ * whether there are members a read could change, so auto-accept is offered only on a re-read (owner ruling 2026-10-25).
14878
+ * The same terms the chat card and the New project dialog state (QUICK_MODEL_TERMS, QUICK_AUTO_ACCEPT_TERMS).
14879
+ */
14880
+ const REVISION_QUICK_TERMS = 'The AI answers this read\'s drawing questions itself instead of asking you, and files an RFI, marked as its own, only for a question it cannot settle; nothing is sent to anyone. It records every decision it makes, so you can review them afterwards, and the model is labelled as a Quick model. The AI never approves anything: you still decide on the Drawing Filter and on the review.';
14881
+ const REVISION_AUTO_ACCEPT_TERMS = 'You also chose to have the AI’s height changes to members already in the model ticked for you in the review: untick any you do not want; nothing changes until you confirm the review.';
14882
+ const REVISION_BUILD_CHOOSE = 'Choose Quick model or Precise model first.';
14883
+ function revisionBuildDefault(state) {
14884
+ // A reviewable working copy is the evidence that a model exists, so only then is auto-accept offered (Codex plan
14885
+ // review, finding 5): no model yet, a first read still at its Filter, or a state FloLess could not read offers none.
14886
+ const ready = !!(state && state.status === 'ready');
14887
+ const unsure = (why) => ({ mode: null, members: ready,
14888
+ note: `${why} Press Quick model or Precise model to continue. Precise model is the safe choice.` });
14889
+ if (state && state.status === 'unreviewable' && state.reason === 'no-contract') return { mode: 'precise', members: false, note: '' };
14890
+ // The first read has not published its model yet: it may be building a Quick or a Precise one, so neither is preset.
14891
+ if (state && state.status === 'unreviewable' && state.reason === 'filter-checkpoint') return unsure('This project’s first drawing read has not finished, so FloLess cannot tell yet how its model is built.');
14892
+ const draft = ready && state.review && state.review.quick ? state.review.quick.draft : null;
14893
+ if (!draft) return unsure('FloLess could not check how this model was built.');
14894
+ if (draft.state === 'quick') return { mode: 'quick', members: true, note: 'This model is a Quick model, so Quick model is chosen. You can switch.' };
14895
+ if (draft.state === 'precise') return { mode: 'precise', members: true, note: '' };
14896
+ return unsure('This model reads as Possibly Quick model: FloLess could not read which AI decisions it rests on.');
14897
+ }
14898
+ /**
14899
+ * The preset for `proj`, from a FRESH approval verdict of its own (a settled one can be stale: the model may have
14900
+ * changed elsewhere), bounded so a hung read still lets the person choose. It never touches the shared approval
14901
+ * state: a read given up on must not leave the header or History waiting on it (Codex code review, round 1).
14902
+ * Computed once per surface, so a late answer never changes a choice already on screen.
14903
+ */
14904
+ async function revisionBuildPreset(proj, ms = 8000) {
14905
+ let timer;
14906
+ const late = new Promise((resolve) => { timer = setTimeout(() => resolve(null), ms); });
14907
+ const read = api(`/api/projects/${encodeURIComponent(proj.id)}/approval-review`)
14908
+ .then((review) => (review && review.reviewable === false ? { status: 'unreviewable', reason: review.reason } : { status: 'ready', review }))
14909
+ .catch(() => null);
14910
+ const state = await Promise.race([read, late]);
14911
+ clearTimeout(timer);
14912
+ return revisionBuildDefault(current === proj ? state : null);
14913
+ }
14914
+ /** What the route is sent: Quick only when pressed, auto-accept only with it; Precise sends neither (as row 7a). */
14915
+ function revisionBuildBody(choice) {
14916
+ if (!choice || choice.mode !== 'quick') return {};
14917
+ return { buildMode: 'quick', ...(choice.autoAccept && choice.members ? { quickAutoAccept: true } : {}) };
14918
+ }
14919
+ /** A press on the choice. Precise clears the auto-accept tick, which only rides with Quick. */
14920
+ function chooseRevisionBuild(choice, target) {
14921
+ if (!choice || !target) return false;
14922
+ const mode = target.closest('[data-rev-build]');
14923
+ if (mode) {
14924
+ choice.mode = mode.dataset.revBuild === 'quick' ? 'quick' : 'precise';
14925
+ if (choice.mode !== 'quick') choice.autoAccept = false;
14926
+ choice.error = '';
14927
+ return true;
14928
+ }
14929
+ const auto = target.closest('[data-rev-build-auto]');
14930
+ if (auto) { choice.autoAccept = choice.mode === 'quick' && !!auto.checked; return true; }
14931
+ return false;
14932
+ }
14933
+ /**
14934
+ * The choice, painted from its state. `compact` (the Knowledge read panel) keeps each button's trade-off in its
14935
+ * tooltip; the Quick terms are consent text and always show in full while Quick is pressed.
14936
+ */
14937
+ function revisionBuildChoiceHtml(choice, { idPrefix, compact = false }) {
14938
+ const sub = { quick: 'AI answers the drawing questions · faster · not precise', precise: 'You answer them · hours · best evidence' };
14939
+ const button = (mode, label) => {
14940
+ const pressed = choice.mode === mode;
14941
+ const suggested = mode === 'precise' && !choice.mode ? ' · suggested' : '';
14942
+ return `<button type="button" data-rev-build="${mode}" data-command-id="shell.revision-build-mode#${mode === 'quick' ? 'Quick' : 'Precise'}" aria-pressed="${pressed}"`
14943
+ + `${mode === 'quick' ? ` aria-describedby="${idPrefix}-terms"` : ''}${compact ? ` data-tip="${escapeAttr(sub[mode])}"` : ''}>`
14944
+ + `<span class="project-setup-standard-label">${escapeHtml(label + suggested)}</span>${compact ? '' : `<span>${escapeHtml(sub[mode])}</span>`}</button>`;
14945
+ };
14946
+ const quick = choice.mode === 'quick';
14947
+ const auto = quick && choice.members
14948
+ ? `<label class="modal-check"><input type="checkbox" data-rev-build-auto data-command-id="shell.revision-quick-auto-accept"${choice.autoAccept ? ' checked' : ''}`
14949
+ + ` aria-describedby="${idPrefix}-auto-terms"><span>Tick the AI’s height changes to members already in the model for me</span></label>`
14950
+ + `<p id="${idPrefix}-auto-terms"${choice.autoAccept ? '' : ' hidden'}>${escapeHtml(REVISION_AUTO_ACCEPT_TERMS)}</p>` : '';
14951
+ return `<fieldset class="project-setup-field project-setup-standard project-setup-build rev-build${compact ? ' is-compact' : ''}">`
14952
+ + `<legend class="project-setup-label">Model</legend>`
14953
+ + (choice.note ? `<div class="project-setup-note" role="status">${escapeHtml(choice.note)}</div>` : '')
14954
+ + `<div class="project-setup-standard-options">${button('quick', 'Quick model')}${button('precise', 'Precise model')}</div>`
14955
+ + (choice.error ? `<div class="ac-error rev-build-error" role="alert">${escapeHtml(choice.error)}</div>` : '')
14956
+ + `<div class="project-setup-quick-terms" id="${idPrefix}-terms" role="group" aria-label="Quick model terms"${quick ? '' : ' hidden'}>`
14957
+ + `<strong>Before you read these drawings as a Quick model</strong><p>${escapeHtml(REVISION_QUICK_TERMS)}</p>${auto}</div></fieldset>`;
14958
+ }
14959
+ /** The toasts for a queued read, phrased from what the server QUEUED, never from the press; a fallback says why. */
14960
+ function revisionQueuedToasts(res, lead, tail) {
14961
+ const req = res && res.request;
14962
+ showToast(`${lead}${req && req.buildMode === 'quick' ? ' as a Quick model' : ''} — ${tail}`, 'ok');
14963
+ if (res && res.buildModeNotice && res.buildModeNotice.why) showToast(res.buildModeNotice.why, 'warn');
14964
+ }
14965
+
14966
+ /**
14967
+ * The confirm step after the file picker (owner ruling 2026-10-26). Resolves the person's choice, or null when they
14968
+ * cancel (nothing is queued, as cancelling the picker). Leaving the project closes it (resetRevisionState).
14969
+ */
14970
+ function askRevisionBuild(files, preset) {
14971
+ const root = document.getElementById('revision-build-modal');
14972
+ if (!root) return Promise.resolve(null);
14973
+ if (revisionBuildAsk) revisionBuildAsk.close(null);
14974
+ const $choice = document.getElementById('rb-choice');
14975
+ const returnTo = document.activeElement instanceof HTMLElement ? document.activeElement : null;
14976
+ const choice = { mode: preset.mode, members: preset.members, note: preset.note, autoAccept: false, error: '' };
14977
+ const names = files.map((f) => f.name);
14978
+ document.getElementById('rb-files').textContent = names.length > 1 ? `${names[0]} and ${names.length - 1} more` : (names[0] || '');
14979
+ return new Promise((resolve) => {
14980
+ const paint = (focusSel) => {
14981
+ $choice.innerHTML = revisionBuildChoiceHtml(choice, { idPrefix: 'rb' });
14982
+ const target = focusSel && $choice.querySelector(focusSel);
14983
+ if (target) target.focus();
14984
+ };
14985
+ const close = (result) => {
14986
+ if (revisionBuildAsk !== ask) return;
14987
+ revisionBuildAsk = null;
14988
+ root.classList.remove('show');
14989
+ root.removeEventListener('click', onClick);
14990
+ root.removeEventListener('change', onChange);
14991
+ document.removeEventListener('keydown', onKey, true);
14992
+ if (returnTo && returnTo.isConnected) returnTo.focus();
14993
+ resolve(result);
14994
+ };
14995
+ const queue = () => {
14996
+ if (!choice.mode) { choice.error = REVISION_BUILD_CHOOSE; paint('[data-rev-build="quick"]'); return; }
14997
+ close({ mode: choice.mode, autoAccept: choice.autoAccept, members: choice.members });
14998
+ };
14999
+ function onClick(event) {
15000
+ const target = event.target instanceof Element ? event.target : null;
15001
+ if (!target) return;
15002
+ if (target.closest('#rb-cancel')) { close(null); return; }
15003
+ if (target.closest('#rb-ok')) { queue(); return; }
15004
+ const mode = target.closest('[data-rev-build]');
15005
+ if (mode && chooseRevisionBuild(choice, mode)) paint(`[data-rev-build="${choice.mode}"]`);
15006
+ }
15007
+ function onChange(event) {
15008
+ if (chooseRevisionBuild(choice, event.target)) paint('[data-rev-build-auto]');
15009
+ }
15010
+ function onKey(event) {
15011
+ if (!root.classList.contains('show')) return;
15012
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(null); return; }
15013
+ if (event.key !== 'Tab') return;
15014
+ const focusable = Array.from(root.querySelectorAll('button, input'))
15015
+ .filter((element) => !element.closest('[hidden]') && element.getClientRects().length);
15016
+ if (!focusable.length) return;
15017
+ const first = focusable[0]; const last = focusable[focusable.length - 1];
15018
+ if (event.shiftKey && (document.activeElement === first || !root.contains(document.activeElement))) { event.preventDefault(); last.focus(); }
15019
+ else if (!event.shiftKey && (document.activeElement === last || !root.contains(document.activeElement))) { event.preventDefault(); first.focus(); }
15020
+ }
15021
+ const ask = { close };
15022
+ revisionBuildAsk = ask;
15023
+ root.addEventListener('click', onClick);
15024
+ root.addEventListener('change', onChange);
15025
+ // On the document, as step-rename.js does: focus moved out of the dialog by another surface still comes back.
15026
+ document.addEventListener('keydown', onKey, true);
15027
+ root.classList.add('show');
15028
+ paint(choice.mode ? `[data-rev-build="${choice.mode}"]` : '[data-rev-build="quick"]');
15029
+ });
15030
+ }
15031
+
15032
+ // The backdrop dismisses only a click that also STARTED on it (onBackdropDismiss), so a drag-select of the terms that
15033
+ // ends outside the dialog never cancels the person's attach.
15034
+ onBackdropDismiss(document.getElementById('revision-build-modal'), () => { if (revisionBuildAsk) revisionBuildAsk.close(null); }, () => !!revisionBuildAsk);
15035
+
15036
+ async function attachRevision(files, owner) {
15037
+ // #2521 row 7b: `owner` is the project and generation captured before the file picker opened (the Attach click), so
15038
+ // files picked for a project the user has since left never reach the next one. Without it: the project on screen now.
15039
+ const proj = owner ? owner.proj : current; // capture — the user may switch projects during the async file reads / POST
13941
15040
  if (!proj || !files.length) return;
13942
15041
  if (!validateSteelDrawingFiles(wsDescOf(proj) === WORKSPACE_APPS['steel-model'] ? 'steel-model' : '', files)) return;
13943
- const projectGeneration = revisionOwnerGen;
15042
+ const projectGeneration = owner ? owner.gen : revisionOwnerGen;
13944
15043
  const attachGeneration = ++revisionAttachGen;
13945
15044
  const ownsAttach = () => current === proj
13946
15045
  && revisionOwnerGen === projectGeneration
13947
15046
  && revisionAttachGen === attachGeneration;
15047
+ if (!ownsAttach()) return;
13948
15048
  const returnFocus = document.activeElement;
15049
+ // #2521 row 7b: a Steel model read asks Quick or Precise first, preset to the model's own mode. Other templates
15050
+ // have no Quick model, so their attach stays one step.
15051
+ let choice = null;
15052
+ if (wsDescOf(proj) === WORKSPACE_APPS['steel-model']) {
15053
+ const preset = await revisionBuildPreset(proj);
15054
+ if (!ownsAttach()) return;
15055
+ choice = await askRevisionBuild(files, preset);
15056
+ if (!choice || !ownsAttach()) return;
15057
+ }
13949
15058
  let snapshots;
13950
15059
  try { snapshots = await Promise.all(files.map(readFileAsSnapshot)); }
13951
15060
  catch { showToast('Could not read the selected files', 'warn'); return; }
@@ -13953,7 +15062,7 @@
13953
15062
  let res;
13954
15063
  try {
13955
15064
  res = await api(`/api/projects/${encodeURIComponent(proj.id)}/revision-requests`, {
13956
- method: 'POST', body: JSON.stringify({ appId: proj.app, snapshots }),
15065
+ method: 'POST', body: JSON.stringify({ appId: proj.app, snapshots, ...revisionBuildBody(choice) }),
13957
15066
  });
13958
15067
  } catch (err) { if (ownsAttach()) showToast(err?.body?.code === 'steel-pdf-required' ? err.body.error : 'We couldn’t attach that file because FloLess could not save it. Try again.', 'warn'); return; }
13959
15068
  const req = res && res.request;
@@ -13971,7 +15080,7 @@
13971
15080
  if (!ownsAttach()) return; // don't drive a replaced project's card/poll/modal or narrate its Copy
13972
15081
  revBaseVersion = (req && typeof req.baseVersion === 'number') ? req.baseVersion : 0;
13973
15082
  revBaseProject = proj.id; // the baseline belongs to THIS project — see resetRevisionState
13974
- showToast(`${revBaseVersion <= 0 ? 'Initial' : 'Revised'} set queued — ${files.length} file${files.length > 1 ? 's' : ''} for your terminal AI`, 'ok');
15083
+ revisionQueuedToasts(res, `${revBaseVersion <= 0 ? 'Initial' : 'Revised'} set queued`, `${files.length} file${files.length > 1 ? 's' : ''} for your terminal AI`);
13975
15084
  // #2399 slice 0c: the drawings also land in the project's design set as an issue. Said either way, never silent.
13976
15085
  const landed = res && res.designSet;
13977
15086
  if (landed && landed.landed && landed.created) {
@@ -13998,8 +15107,9 @@
13998
15107
  }
13999
15108
 
14000
15109
  document.getElementById('ws-attach-revision').addEventListener('click', async () => {
15110
+ const owner = { proj: current, gen: revisionOwnerGen };
14001
15111
  const files = await pickDrawingFiles($revisionFile, wsDescOf(current) === WORKSPACE_APPS['steel-model'] ? 'steel-model' : '');
14002
- if (files.length) attachRevision(files);
15112
+ if (files.length) attachRevision(files, owner);
14003
15113
  });
14004
15114
 
14005
15115
  function buildPendingCard(req) {
@@ -14253,6 +15363,7 @@
14253
15363
  revisionGen += 1;
14254
15364
  revisionRequestsSuccessGen = revisionGen;
14255
15365
  lastRevState = 'none';
15366
+ revisionListKnown = true;
14256
15367
  await renderRevisionCard();
14257
15368
  }
14258
15369
 
@@ -14296,6 +15407,7 @@
14296
15407
  return;
14297
15408
  }
14298
15409
  revisionRequestsSuccessGen = Math.max(revisionRequestsSuccessGen, gen);
15410
+ revisionListKnown = true;
14299
15411
  } catch (e) {
14300
15412
  // The request that failed may belong to a project the user has already left. Do not let its
14301
15413
  // late failure mark the newly opened project's server state as disconnected. For the same
@@ -14763,9 +15875,14 @@
14763
15875
  if (answered) {
14764
15876
  const note = revEl('div', 'rev-row-note');
14765
15877
  const how = answered.how === 'typed' ? `typed ${answered.typed || reviewElevation(a.z.known)}` : `confirmed ${answered.shownAs || reviewElevation(a.z.known)}`;
15878
+ // #2788: where a confirmed proposal came from, so a derived height never reads as one taken off a drawing.
15879
+ const p = answered.how === 'confirmed' && answered.proposal && typeof answered.proposal === 'object' ? answered.proposal : null;
15880
+ const came = !p ? '' : p.how === 'derived' ? `, which the read derived from ${p.basis}`
15881
+ : p.how === 'measured' ? `, which the read measured on the drawings${p.basis ? ` (${p.basis})` : ''}`
15882
+ : `, read off the drawings${p.basis ? ` (${p.basis})` : ''}`;
14766
15883
  note.appendChild(document.createTextNode(`You answered the ${end.toLowerCase()} height on a height question: `));
14767
15884
  note.appendChild(revEl('b', null, how));
14768
- note.appendChild(document.createTextNode(answered.note ? ` (${answered.note}).` : '.'));
15885
+ note.appendChild(document.createTextNode(`${came}${answered.note ? ` (${answered.note})` : ''}.`));
14769
15886
  notes.push(note);
14770
15887
  const over = answered.overDrawing;
14771
15888
  if (over && typeof over.low === 'number' && typeof over.high === 'number') {
@@ -16503,7 +17620,7 @@
16503
17620
  `<td><span class="ver${v.current ? ' cur' : ''}">v${escapeHtml(String(v.n))}</span></td>` +
16504
17621
  `<td class="htime">${escapeHtml(histWhen(v.ts))}</td>` +
16505
17622
  `<td><span class="hby">${avatarFor(v.author)}${escapeHtml(v.author)}</span></td>` +
16506
- `<td>${gateBadge(v.gate, v.kind, v.n, typeof v.acceptedImportFindingsNote === 'string' ? v.acceptedImportFindingsNote : '')}</td>` +
17623
+ `<td>${gateBadge(v.gate, v.kind, v.n, typeof v.acceptedImportFindingsNote === 'string' ? v.acceptedImportFindingsNote : '')}${quickPillHtml(v.quick, { scope: `v${v.n}` })}</td>` +
16507
17624
  `<td class="change">${revisionNoteHtml(v)}${changeCellHtml(v, meta)}${diffStatus}</td>` +
16508
17625
  `<td>${action}</td></tr>`;
16509
17626
  // The disclosure row is always emitted (hidden) so toggling is a pure show/hide + lazy fetch.
@@ -16536,7 +17653,7 @@
16536
17653
  const resume = allowed.includes('resume')
16537
17654
  ? `<button type="button" class="btn-mini" data-resume-checkpoint="${escapeAttr(String(saved.id))}" data-tip="Switch the working copy to this exact saved checkpoint">Resume exact checkpoint</button>`
16538
17655
  : '';
16539
- return `<article class="saved-work-card"><div><b>${escapeHtml(base)}</b><span>${escapeHtml(histWhen(saved.capturedAt))} · ${escapeHtml(String(saved.id || '').slice(0, 8))}</span></div>`
17656
+ return `<article class="saved-work-card"><div><b>${escapeHtml(base)}</b>${quickPillHtml(saved.quick, { scope: 'This checkpoint' })}<span>${escapeHtml(histWhen(saved.capturedAt))} · ${escapeHtml(String(saved.id || '').slice(0, 8))}</span></div>`
16540
17657
  + `<p>This checkpoint stays attached to its original approved base; it is never applied backward into another revision.</p>${resume}</article>`;
16541
17658
  }).join('')}</div>`;
16542
17659
  }
@@ -16952,8 +18069,26 @@
16952
18069
  wrap.appendChild(el('span', 'hd-net-label', 'Net steel:'));
16953
18070
  wrap.appendChild(el('span', 'hd-net-arrow', net > 0 ? '▲' : net < 0 ? '▼' : '•'));
16954
18071
  wrap.appendChild(el('span', 'hd-net-val', `${net > 0 ? '+' : ''}${net} ${word}`));
18072
+ // #2735: the bill prices members on ASSUMED heights, so these totals can rest on them. Say so on its own
18073
+ // line under the figure (a label, not a reliability warning, so not an .hd-warn banner).
18074
+ const assumed = diffAssumedNoteText(t);
18075
+ if (assumed) {
18076
+ const note = el('span', 'hd-net-assumed', assumed);
18077
+ note.setAttribute('role', 'note');
18078
+ note.dataset.tip = 'Heights the drawings do not state, placed at a plan elevation.';
18079
+ wrap.appendChild(note);
18080
+ }
16955
18081
  return wrap;
16956
18082
  }
18083
+ // The line under Net steel when either side prices members on assumed heights, or '' when neither does.
18084
+ // Newer side first: it is the figure being read.
18085
+ function diffAssumedNoteText(t) {
18086
+ const count = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
18087
+ const now = count(t && t.toAssumed), before = count(t && t.fromAssumed);
18088
+ if (!now && !before) return '';
18089
+ const lead = 'Includes members priced on assumed heights: ';
18090
+ return now === before ? `${lead}${now} in both versions.` : `${lead}${now} now, ${before} before.`;
18091
+ }
16957
18092
  // The engine's four honest signals — each names its CONSEQUENCE so a withheld member/connection is
16958
18093
  // never silently absent from the panel. ALL render here (not just identity), above the numbers.
16959
18094
  function diffCautions(w) {
@@ -16989,10 +18124,18 @@
16989
18124
  wrap.appendChild(btn);
16990
18125
  return wrap;
16991
18126
  }
16992
- function renderDiffPanel(panel, diff) {
18127
+ function renderDiffPanel(panel, diff, quick) {
16993
18128
  panel.textContent = '';
16994
18129
  panel.appendChild(diffBasePicker(diff));
16995
18130
  for (const c of diffCautions(diff.warnings)) panel.appendChild(c); // above the numbers — context for reading them
18131
+ // #2521 row 5: each side says what IT rests on, above the tonnage, so a Quick side never reads as precise.
18132
+ const sides = quick ? [[quick.from, `v${diff.from}`], [quick.to, `v${diff.to}`]].filter(([q]) => quickPillHtml(q)) : [];
18133
+ if (sides.length) {
18134
+ const note = el('div', 'hd-quick');
18135
+ note.setAttribute('role', 'note');
18136
+ note.innerHTML = sides.map(([q, scope]) => quickPillHtml(q, { scope, showScope: true })).join(' ');
18137
+ panel.appendChild(note);
18138
+ }
16996
18139
  panel.appendChild(diffNetHeader(diff.tonnage));
16997
18140
  let any = false;
16998
18141
  for (const g of DIFF_GROUPS) {
@@ -17107,7 +18250,8 @@
17107
18250
  // and server ship together, so that window is a half-finished upgrade, not a supported state.
17108
18251
  if (!hasStatus && legacyUnreadableDiff(response.diff)) return { kind: 'unavailable' };
17109
18252
  if (!wellFormedDiff(response.diff)) throw new Error('invalid comparison response');
17110
- return { kind: 'available', diff: response.diff };
18253
+ return response.quick && typeof response.quick === 'object'
18254
+ ? { kind: 'available', diff: response.diff, quick: response.quick } : { kind: 'available', diff: response.diff };
17111
18255
  }
17112
18256
  function restoreDiffFocus(panel, n) {
17113
18257
  const target = panel.querySelector('.hd-base')
@@ -17170,7 +18314,7 @@
17170
18314
  panel.setAttribute('aria-busy', 'false');
17171
18315
  if (progress) progress.textContent = '';
17172
18316
  if (decoded.kind === 'unavailable') renderDiffUnavailable(panel);
17173
- else renderDiffPanel(panel, decoded.diff);
18317
+ else renderDiffPanel(panel, decoded.diff, decoded.quick);
17174
18318
  if (opts && opts.restoreBaseFocus) restoreDiffFocus(panel, n);
17175
18319
  }
17176
18320
  function toggleDiff(btn) {
@@ -17591,11 +18735,11 @@
17591
18735
  showToast(`Renamed to "${project.name}"`, 'ok');
17592
18736
  } else if (action === 'duplicate') {
17593
18737
  dismissProgress = showToast(`Duplicating “${proj ? proj.name : 'project'}”…`, 'progress');
17594
- const { project, rfiTransfer } = await api(`/api/projects/${encodeURIComponent(id)}/duplicate`, { method: 'POST', body: '{}' });
18738
+ const { project, rfiTransfer, workflowTransfer, correspondenceTransfer } = await api(`/api/projects/${encodeURIComponent(id)}/duplicate`, { method: 'POST', body: '{}' });
17595
18739
  projects.unshift(project); // newest → front, matching the server's newest-first list order
17596
18740
  renderLanding();
17597
18741
  flashCard(project.id, { scroll: true });
17598
- const resultToast = formatRfiTransferToast(rfiTransfer, 'duplicate', project.name, true);
18742
+ const resultToast = withWorkflowTransfer(formatRfiTransferToast(rfiTransfer, 'duplicate', project.name, true), workflowTransfer, 'duplicate', correspondenceTransfer);
17599
18743
  finishProgress();
17600
18744
  showToast(resultToast.message, resultToast.tone);
17601
18745
  } else if (action === 'clear-unverified') {
@@ -17775,14 +18919,14 @@
17775
18919
  };
17776
18920
  try {
17777
18921
  const buf = await file.arrayBuffer();
17778
- const { project, appInstalled, rfiTransfer, leftOut } = await api('/api/projects/import', {
18922
+ const { project, appInstalled, rfiTransfer, leftOut, workflowTransfer, correspondenceTransfer } = await api('/api/projects/import', {
17779
18923
  method: 'POST', headers: { 'content-type': 'application/zip' }, body: buf,
17780
18924
  });
17781
18925
  projects.unshift(project); // newest → front, matching duplicate/create
17782
18926
  renderLanding();
17783
18927
  flashCard(project.id, { scroll: true });
17784
18928
  track('workspace_project_imported', { app: project.app });
17785
- const resultToast = formatRfiTransferToast(rfiTransfer, 'import', project.name, appInstalled);
18929
+ const resultToast = withWorkflowTransfer(formatRfiTransferToast(rfiTransfer, 'import', project.name, appInstalled), workflowTransfer, 'import', correspondenceTransfer);
17786
18930
  const leftOutNote = importLeftOutNote(leftOut, project.name);
17787
18931
  finishProgress();
17788
18932
  showToast(leftOutNote.skipped ? `${resultToast.message} ${leftOutNote.skipped}` : resultToast.message, resultToast.tone);
@@ -17800,6 +18944,18 @@
17800
18944
  // - zipped mid-save → a persistent warning: the copy may miss that save or hold part of it;
17801
18945
  // - saved checkpoints / undo steps → a persistent warning: those stay on the source computer;
17802
18946
  // - anything else is set up fresh here → one quiet sentence on the success toast.
18947
+ /**
18948
+ * #2603: a Duplicate or Import toast also says what happened to the project's workflows (project-workflows.js writes
18949
+ * the sentence). Reached through globalThis, so a harness that lifts the callers without that module still runs.
18950
+ */
18951
+ function withWorkflowTransfer(toast, workflowTransfer, operation = 'duplicate', correspondenceTransfer = undefined) {
18952
+ // #2470 R6.6: and what happened to a General project's RFIs (project-rfis.js writes that sentence).
18953
+ const notes = [globalThis.flolessProjectWorkflows?.transferNote?.(workflowTransfer, operation) ?? null,
18954
+ globalThis.flolessProjectRfis?.transferNote?.(correspondenceTransfer, operation) ?? null].filter(Boolean);
18955
+ if (!notes.length) return toast;
18956
+ return { message: `${toast.message} ${notes.map((n) => n.text).join(' ')}`, tone: notes.some((n) => n.warn) && toast.tone === 'ok' ? 'warn' : toast.tone };
18957
+ }
18958
+
17803
18959
  function importLeftOutNote(leftOut, projectName) {
17804
18960
  const files = leftOut && Array.isArray(leftOut.files) ? leftOut.files.length : 0;
17805
18961
  if (!files) return { skipped: '', warning: '' };
@@ -18276,6 +19432,127 @@
18276
19432
  }
18277
19433
  }
18278
19434
 
19435
+ /**
19436
+ * Show one place on the drawings in a project's Drawing Filter (#2777 slice D, AI Chat's "Open in Drawing
19437
+ * Filter"): its sheet, with the area outlined. The Filter does the showing (`flolessFilterFocus`,
19438
+ * steel-filter.html); this only gets the person to the Drawings step and hands the request over.
19439
+ *
19440
+ * The same discipline as `openConnection` above, for the same reasons: one slot (a later click replaces
19441
+ * and withdraws the earlier request by its id), the project already open only switches step (so nothing
19442
+ * unsaved is reloaded away), another project goes through `openProject` and its leave guard, every wait is
19443
+ * watched, and whatever stops waiting without the Filter's answer withdraws the request.
19444
+ *
19445
+ * Resolves the Filter's own outcome — `{ok:true}` or `{ok:false,said}` — or `{superseded:true}`. What
19446
+ * cannot be done is thrown as a sentence written for the person (`plain`).
19447
+ */
19448
+ let placeRequestSeq = 0;
19449
+ let placeRequest = null;
19450
+ const withdrawPlaceRequest = (request) => {
19451
+ try { request?.page?.flolessFilterFocusCancel?.(request.id); } catch { /* that page is gone */ }
19452
+ };
19453
+ async function openDrawingAt(target) {
19454
+ const validId = (id) => typeof id === 'string' && !!id && id.length <= 200;
19455
+ const place = target && target.place;
19456
+ const again = 'Open in Drawing Filter';
19457
+ if (!target || !validId(target.projectId) || !place || !validId(place.pageId) || !validId(place.sheet) || !/^[0-9a-f]{64}$/.test(String(place.sourceHash || ''))) {
19458
+ throw connectionError('That place could not be opened. Open its project from Workspaces.');
19459
+ }
19460
+ const mine = { id: `place-${++placeRequestSeq}`, page: null };
19461
+ withdrawPlaceRequest(placeRequest);
19462
+ placeRequest = mine;
19463
+ const superseded = () => placeRequest !== mine;
19464
+ let ended = false;
19465
+ const stillWanted = () => !ended && !superseded();
19466
+ const pause = () => new Promise((resolve) => setTimeout(resolve, 100));
19467
+ const leftWorkspaces = () => connectionError(`You left Workspaces, so the place was not shown. Open the project from Workspaces, then press ${again} again.`);
19468
+ const navigating = async (work, bounded) => {
19469
+ const bound = bounded ? Date.now() + CONNECTION_NAVIGATION_WAIT_MS : Infinity;
19470
+ let done = null;
19471
+ const finished = work.then((value) => { done = { value }; }, (error) => { done = { error }; });
19472
+ for (;;) {
19473
+ await Promise.race([finished, pause()]);
19474
+ if (done) { if (done.error) throw done.error; return done.value; }
19475
+ if (superseded()) return { superseded: true };
19476
+ if (Date.now() >= bound) throw connectionError(`The project did not open in time, so the place was not shown. Open it from Workspaces, then press ${again} again.`);
19477
+ }
19478
+ };
19479
+ let until = Infinity;
19480
+ // The document the Drawings frame held before this call opened the project (#2605's trap, for this frame).
19481
+ let pageLeftBehind = null;
19482
+ const interrupted = () => {
19483
+ if (superseded()) return { superseded: true };
19484
+ if (mode !== 'workspaces') throw leftWorkspaces();
19485
+ if (current?.id !== target.projectId) throw connectionError('You moved to another project, so the place was not shown.');
19486
+ if (currentStep !== 'drawings' && !(pendingPresenceStep && pendingPresenceStep.step === 'drawings')) {
19487
+ throw connectionError(`The Drawings step is not open, so the place was not shown. Open the Drawings step, then press ${again} again.`);
19488
+ }
19489
+ if (Date.now() >= until) throw connectionError(`The Drawing Filter did not open in time, so the place was not shown. Open the Drawings step, then press ${again} again.`);
19490
+ return null;
19491
+ };
19492
+ try {
19493
+ if ((await navigating(Promise.resolve(setMode('workspaces'))))?.superseded || superseded()) return { superseded: true };
19494
+ if (mode !== 'workspaces') throw connectionError(`You stayed where you were, so the place was not shown. Open the project from Workspaces, then press ${again} again.`);
19495
+ if (current?.id !== target.projectId) {
19496
+ try { pageLeftBehind = frames.drawings.contentWindow?.document ?? null; } catch { pageLeftBehind = null; }
19497
+ const opened = await navigating(openProject(target.projectId, 'drawings', { stillWanted }), true);
19498
+ if (opened?.superseded || superseded()) return { superseded: true };
19499
+ if (opened === STAYED_IN_PROJECT) throw connectionError(`That project did not open, so the place was not shown. Open it from Workspaces to see why, then press ${again} again.`);
19500
+ if (current?.id !== target.projectId) throw connectionError('That project could not be opened. Open it from Workspaces.');
19501
+ } else if (currentStep !== 'drawings') {
19502
+ setStep('drawings');
19503
+ }
19504
+ if (!frames.drawings.dataset.want) throw connectionError('This project has no Drawing Filter to show the place in.');
19505
+ until = Date.now() + CONNECTION_FRAME_WAIT_MS;
19506
+ let answer = null, settled = null, page = null, doc = null, reloaded = false;
19507
+ const notTaken = `The Drawing Filter could not take the request. Press ${again} again.`;
19508
+ for (;;) {
19509
+ if (settled) {
19510
+ if (superseded()) return { superseded: true };
19511
+ if (mode !== 'workspaces') throw leftWorkspaces();
19512
+ if (current?.id !== target.projectId) throw connectionError('You moved to another project, so the place was not shown.');
19513
+ if (frames.drawings.contentWindow !== page || page.document !== doc) throw connectionError(`The Drawing Filter reloaded, so the place was not shown. Press ${again} again.`);
19514
+ const outcome = settled.outcome;
19515
+ return outcome && typeof outcome === 'object' ? { ...outcome } : { ok: false, said: notTaken };
19516
+ }
19517
+ const stop = interrupted();
19518
+ if (stop) return stop;
19519
+ const child = frames.drawings.contentWindow;
19520
+ if (!answer) {
19521
+ const state = child && child.flolessFilterState;
19522
+ // A Filter that showed nothing may only be out of date: the read prepared its drawings after the page loaded.
19523
+ // It has nothing unsaved, so it is reloaded once, and only what the reloaded page says is reported.
19524
+ if (state && state.project === target.projectId && state.failed === true && !reloaded
19525
+ && (!pageLeftBehind || child.document !== pageLeftBehind)) {
19526
+ reloaded = true;
19527
+ pageLeftBehind = child.document;
19528
+ frames.drawings.src = frames.drawings.dataset.want;
19529
+ until = Date.now() + CONNECTION_FRAME_WAIT_MS;
19530
+ } else if (state && state.project === target.projectId && typeof child.flolessFilterFocus === 'function'
19531
+ && (!pageLeftBehind || child.document !== pageLeftBehind)) {
19532
+ page = child; doc = child.document;
19533
+ answer = child.flolessFilterFocus({ requestId: mine.id, sourceHash: place.sourceHash, pageId: place.pageId, sheet: place.sheet,
19534
+ ...(Array.isArray(place.region) ? { region: place.region } : {}) });
19535
+ if (!answer || typeof answer.then !== 'function') return { ok: false, said: notTaken };
19536
+ mine.page = page;
19537
+ answer.then((outcome) => { settled = { outcome }; }, (error) => {
19538
+ console.error('[workspaces] the Drawing Filter could not answer for the place', error);
19539
+ settled = { outcome: { ok: false, said: notTaken } };
19540
+ });
19541
+ }
19542
+ } else if (child !== page || child.document !== doc) {
19543
+ throw connectionError(`The Drawing Filter reloaded, so the place was not shown. Press ${again} again.`);
19544
+ }
19545
+ await pause();
19546
+ }
19547
+ } catch (error) {
19548
+ if (!superseded()) withdrawPlaceRequest(mine);
19549
+ throw error;
19550
+ } finally {
19551
+ ended = true;
19552
+ if (placeRequest === mine) placeRequest = null;
19553
+ }
19554
+ }
19555
+
18279
19556
  // A cross-project object pin still belongs to its original conversation, wherever its model is shown.
18280
19557
  async function openChatOwner(owner) {
18281
19558
  const validId = (id) => typeof id === 'string' && !!id && id.length <= 200;
@@ -18328,9 +19605,11 @@
18328
19605
  async function folderDecisionCompleted(result, operation) {
18329
19606
  const project = result.project;
18330
19607
  if (operation === 'import') {
18331
- const toast = formatRfiTransferToast(result.rfiTransfer, 'import', project.name, result.appInstalled);
19608
+ const toast = withWorkflowTransfer(formatRfiTransferToast(result.rfiTransfer, 'import', project.name, result.appInstalled), result.workflowTransfer, 'import', result.correspondenceTransfer);
19609
+ // importLeftOutNote answers { skipped, warning } (it used to be appended whole, as "[object Object]").
18332
19610
  const leftOut = importLeftOutNote(result.leftOut, project.name);
18333
- showToast(toast.message + (leftOut ? ` ${leftOut}` : ''), leftOut ? 'warn' : toast.tone);
19611
+ showToast(leftOut.skipped ? `${toast.message} ${leftOut.skipped}` : toast.message, toast.tone);
19612
+ if (leftOut.warning) showToast(leftOut.warning, 'warn', { persistent: true });
18334
19613
  } else showToast(`Project folder updated for “${project.name}”.`, 'ok');
18335
19614
  await loadProjects({ quiet: true });
18336
19615
  flashCard(project.id, { scroll: true });
@@ -18476,7 +19755,7 @@
18476
19755
  tellModelFrame({ type: 'knowledge-changed', projectId });
18477
19756
  },
18478
19757
  setMode, refresh: loadProjects, findActive: wsFindActive, find: wsFind, clearFind: wsClearFind,
18479
- openHistory: wsOpenHistory, openKnowledgePage, openKnowledgeStep, openDrawingsStep, openWorkflowsStep, openConnection, drawingFilterCheckpointSaved,
19758
+ openHistory: wsOpenHistory, openKnowledgePage, openKnowledgeStep, openDrawingsStep, openWorkflowsStep, openConnection, openDrawingAt, drawingFilterCheckpointSaved,
18480
19759
  // #2470 R6.7: the Modules step of a General project (project-modules.js).
18481
19760
  moduleCreateCardsHtml, activateCreateCard, openLinkedProject, openModulesStep, showArchivedProjects,
18482
19761
  syncWorkspaceReporter, openChatOwner, openPagesHome, folderDecisionCompleted,