@floless/app 0.160.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.
@@ -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.
@@ -779,10 +782,14 @@
779
782
  },
780
783
  editor: '/steel-editor.html',
781
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,
782
788
  steps: [
783
789
  { key: 'knowledge', label: 'Knowledge' }, // per-project KB — the job's context, consulted by everything
784
790
  { key: 'drawings', label: 'Drawing Filter' },
785
791
  { key: 'model', label: 'Model' },
792
+ { key: 'rfis', label: 'RFIs' }, // #2470 R6.6c: owner ruling 2026-10-25, right after Model
786
793
  { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages; #2568: just before Exports (both are output)
787
794
  { key: 'exports', label: 'Exports' },
788
795
  { key: 'history', label: 'History' },
@@ -1016,6 +1023,9 @@
1016
1023
  { key: 'workflows', label: 'Workflows' }, // #2470 R6.2: the workflows this project owns
1017
1024
  { key: 'rfis', label: 'RFIs' }, // #2470 R6.6: the project's questions for the engineer, client or architect
1018
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' },
1019
1029
  ],
1020
1030
  diff: false,
1021
1031
  exports: [],
@@ -1971,6 +1981,9 @@
1971
1981
  window.addEventListener('floless:contract-changed', (e) => {
1972
1982
  const m = (e && e.detail) || {};
1973
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);
1974
1987
  });
1975
1988
  window.addEventListener('floless:projects-changed', (e) => {
1976
1989
  // Sent after the event stream reconnects too (aware.js), with no detail: frames may have been missed, so the
@@ -3796,6 +3809,9 @@
3796
3809
  const $projectSetupError = document.getElementById('project-setup-error');
3797
3810
  const $projectSetupProvider = document.getElementById('project-setup-provider');
3798
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');
3799
3815
  const $projectSetupCancel = document.getElementById('project-setup-cancel');
3800
3816
  const $projectSetupCreateOnly = document.getElementById('project-setup-create-only');
3801
3817
  const $projectSetupCreate = document.getElementById('project-setup-create');
@@ -4034,6 +4050,38 @@
4034
4050
 
4035
4051
  // Repaint only the AI lines while the dialog waits for a setup; a full render would re-enable the
4036
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
+
4037
4085
  function renderProjectSetupWhileBusy(state) {
4038
4086
  if (projectSetupState !== state) return;
4039
4087
  paintProjectSetupProviders(state, projectSetupProvider(state));
@@ -4068,6 +4116,7 @@
4068
4116
  : 'FloLess stores this project here, and AI starts in this folder.';
4069
4117
  if ($projectSetupName.value !== state.name) $projectSetupName.value = state.name;
4070
4118
  $projectSetupStandard.hidden = !state.askCatalogue;
4119
+ paintProjectSetupBuild(state, provider);
4071
4120
  $projectSetupStandard.querySelectorAll('[data-environment]').forEach((button) => {
4072
4121
  button.setAttribute('aria-pressed', String(button.dataset.environment === state.environment));
4073
4122
  });
@@ -4221,6 +4270,8 @@
4221
4270
  let snapshots = state.snapshots || null;
4222
4271
  if (!snapshots) snapshots = await Promise.all(state.files.map(readFileAsSnapshot));
4223
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;
4224
4275
  const submissionId = state.submissionId || crypto.randomUUID();
4225
4276
  state.submissionId = submissionId;
4226
4277
  rememberProjectChatIntake(submissionId);
@@ -4231,10 +4282,12 @@
4231
4282
  directorySelectionId: state.directory.selectionId,
4232
4283
  snapshots,
4233
4284
  provider,
4285
+ ...(state.sentBuildMode === 'quick' ? { buildMode: 'quick' } : {}),
4234
4286
  });
4235
4287
  const project = result.project;
4236
4288
  state.project = project;
4237
4289
  state.request = result.request;
4290
+ state.buildModeNotice = result.buildModeNotice || null;
4238
4291
  if (!projects.some((item) => item.id === project.id)) {
4239
4292
  projects.unshift(project);
4240
4293
  track('workspace_project_created', { app: state.appId });
@@ -4262,9 +4315,12 @@
4262
4315
  setProjectSetupBusy(false);
4263
4316
  closeProjectSetup({ restoreFocus: false });
4264
4317
  // A General project's chat is Flo's kickoff; its first reply may still be on its way (#2470 R6.4).
4265
- 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'
4266
4321
  ? 'Project created — Flo will help you set it up in AI Chat.'
4267
- : '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');
4268
4324
  }
4269
4325
 
4270
4326
  async function resumeInterruptedProjectChatIntake() {
@@ -4280,7 +4336,9 @@
4280
4336
  await openProject(result.project.id, result.project.app === 'floless-general' ? 'knowledge' : 'drawings');
4281
4337
  await bridge.openChatConversation(result.chat.chatId);
4282
4338
  forgetProjectChatIntake(submissionId);
4283
- 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');
4284
4342
  } catch (error) {
4285
4343
  const code = error && (error.code || error.body && error.body.code);
4286
4344
  if (code === 'project-intake-not-found' || code === 'project-intake-damaged') {
@@ -4325,6 +4383,8 @@
4325
4383
  linkFrom,
4326
4384
  askCatalogue: kind === 'drawings' && templateId === 'steel-model',
4327
4385
  environment: null,
4386
+ // #2521 row 7a: Precise unless the person presses Quick; what was sent is kept in `sentBuildMode`.
4387
+ buildMode: 'precise',
4328
4388
  directory: null,
4329
4389
  name: '',
4330
4390
  nameDirty: false,
@@ -4381,6 +4441,9 @@
4381
4441
  projectSetupState.environment = button.dataset.environment;
4382
4442
  renderProjectSetup();
4383
4443
  });
4444
+ $projectSetupBuild?.addEventListener('click', (event) => {
4445
+ chooseProjectSetupBuildMode(event.target.closest('[data-build-mode]'));
4446
+ });
4384
4447
  $projectSetupProvider?.addEventListener('click', (event) => {
4385
4448
  chooseProjectSetupProvider(event.target.closest('[data-chat-provider]'));
4386
4449
  });
@@ -5192,6 +5255,9 @@
5192
5255
  if (unwanted()) return STAYED_IN_PROJECT;
5193
5256
  if (current?.uuid !== p.uuid) revisionNoteEditorGeneration++;
5194
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;
5195
5261
  // #1890: a new workspace conversation suggests this project's units (the one opened last).
5196
5262
  try { localStorage.setItem('floless:last-project', p.id); } catch { /* private mode: no suggestion */ }
5197
5263
  revitSourceState = null;
@@ -5207,6 +5273,7 @@
5207
5273
  pendingPresenceToast = null;
5208
5274
  exportState = null;
5209
5275
  exportStateFrom = null;
5276
+ exportDrafts = [];
5210
5277
  exportUnits = null; // a new project's units arrive with its export listing; never inherit the last one's
5211
5278
  renderReadinessState = null;
5212
5279
  let sourceStateProbe = null;
@@ -5254,7 +5321,7 @@
5254
5321
  // A sourceless project (General, #2470) has no Model, Drawings, Exports or History step; a step carried
5255
5322
  // over from another project lands on its first step instead of a pane it does not have.
5256
5323
  if (d.sourceless && !d.steps.some((step) => step.key === initialStep)) initialStep = d.steps[0].key;
5257
- if ((d.filter || isModelSourceProject(p)) && ['model', 'exports', 'history'].includes(initialStep)) {
5324
+ if ((d.filter || isModelSourceProject(p)) && ['model', 'rfis', 'exports', 'history'].includes(initialStep)) {
5258
5325
  pendingPresenceStep = { projectId: p.id, step: initialStep };
5259
5326
  }
5260
5327
  // The LIVE app id, deliberately: the frames address the server with it (contract reads, saves),
@@ -5464,6 +5531,9 @@
5464
5531
  }
5465
5532
  function closeProject() {
5466
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;
5467
5537
  current = null;
5468
5538
  approvalStateGen++;
5469
5539
  approvalState = { status: 'unavailable', review: null, pendingCount: 0, headVersion: null, error: '' };
@@ -5471,6 +5541,7 @@
5471
5541
  closeApprovalReview();
5472
5542
  exportState = null;
5473
5543
  exportStateFrom = null;
5544
+ exportDrafts = [];
5474
5545
  exportUnits = null; // a new project's units arrive with its export listing; never inherit the last one's
5475
5546
  renderReadinessState = null;
5476
5547
  resetRevisionState();
@@ -5985,7 +6056,7 @@
5985
6056
 
5986
6057
  function stageGateFor(step) {
5987
6058
  const d = wsApp();
5988
- if (!d || !d.filter || !['model', 'exports', 'history'].includes(step)) return '';
6059
+ if (!d || !d.filter || !['model', 'rfis', 'exports', 'history'].includes(step)) return '';
5989
6060
  const initialRead = revCardReq && isInitialRevisionRead(revCardReq);
5990
6061
  const waitingForInitial = initialRead && lastRevState === 'pending';
5991
6062
  const stagedInitial = initialRead && lastRevState === 'staged';
@@ -6014,10 +6085,12 @@
6014
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)}`;
6015
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.`;
6016
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.';
6017
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.';
6018
6090
  return 'Read and save a Drawing Filter first. The model will unlock after the first drawing read.';
6019
6091
  }
6020
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.';
6021
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.`;
6022
6095
  return `Create the first steel model before opening ${step === 'exports' ? 'Exports' : 'History'}.`;
6023
6096
  }
@@ -6162,6 +6235,10 @@
6162
6235
  ? `Drawing read is paused in AI Chat · ${OPEN_AI_CHAT} and tell it to continue the drawing read.`
6163
6236
  : waitingForInitial
6164
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.')
6165
6242
  : projectContractLifecycle === 'filter-checkpoint'
6166
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.'
6167
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.';
@@ -6174,7 +6251,7 @@
6174
6251
  function deferStageUntilLifecycle(s) {
6175
6252
  const d = wsApp();
6176
6253
  if (!current || !d?.filter || projectContractLifecycle !== 'unknown'
6177
- || !['model', 'exports', 'history'].includes(s)) return false;
6254
+ || !['model', 'rfis', 'exports', 'history'].includes(s)) return false;
6178
6255
  pendingPresenceStep = { projectId: current.id, step: s };
6179
6256
  const projectId = current.id;
6180
6257
  if (pendingPresenceToast) pendingPresenceToast();
@@ -6233,6 +6310,9 @@
6233
6310
  showToast(lockedReason, 'warn');
6234
6311
  return;
6235
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;
6236
6316
  currentStep = s;
6237
6317
  $stepTabs.querySelectorAll('button').forEach((b) => {
6238
6318
  const on = b.dataset.step === s;
@@ -6243,18 +6323,22 @@
6243
6323
  // step shows a lightweight placeholder pane instead of an about:blank iframe.
6244
6324
  const d = wsApp();
6245
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);
6246
6328
  for (const [k, f] of Object.entries(frames)) {
6247
- const show = k === s && (k !== 'drawings' || drawingsHasFrame);
6329
+ const show = (k === s || (k === 'model' && s === 'rfis' && rfisInEditor)) && (k !== 'drawings' || drawingsHasFrame);
6248
6330
  f.hidden = !show;
6249
6331
  if (show && !f.dataset.loaded && f.dataset.want) { f.src = f.dataset.want; f.dataset.loaded = '1'; }
6250
6332
  // Coming back to an editor that stayed loaded while hidden: tell it, so it can read again what changed on
6251
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.
6252
6335
  else if (show && k === 'model' && f.dataset.loaded) {
6253
6336
  const project = typeof current !== 'undefined' ? current : null;
6254
- 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); }
6255
6338
  catch { /* the frame is between documents */ }
6256
6339
  }
6257
6340
  }
6341
+ if (rfisInEditor) postStepToEditor(s);
6258
6342
  if (window.flolessLeftPane) {
6259
6343
  window.flolessLeftPane.setWorkspaceModelVisible(s === 'model');
6260
6344
  }
@@ -6322,7 +6406,7 @@
6322
6406
  // reached through globalThis, so a harness that lifts setStep without it still runs.
6323
6407
  const $rfisPane = document.getElementById('ws-rfis');
6324
6408
  if ($rfisPane) {
6325
- const showRfis = s === 'rfis';
6409
+ const showRfis = s === 'rfis' && !rfisInEditor;
6326
6410
  $rfisPane.hidden = !showRfis;
6327
6411
  const project = typeof current !== 'undefined' ? current : null;
6328
6412
  if (showRfis && project) globalThis.flolessProjectRfis?.render?.($rfisPane, project);
@@ -6336,6 +6420,15 @@
6336
6420
  const project = typeof current !== 'undefined' ? current : null;
6337
6421
  if (showModules && project && window.flolessProjectModules) window.flolessProjectModules.render($modulesPane, project);
6338
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
+ }
6339
6432
  // Knowledge is a shell-rendered pane too: the project's Knowledge Base (References column).
6340
6433
  const showKnowledge = s === 'knowledge';
6341
6434
  $wsKnowledge.hidden = !showKnowledge;
@@ -6386,6 +6479,69 @@
6386
6479
  || !['clean', 'dirty', 'saving', 'error', 'conflict'].includes(message.state)) return;
6387
6480
  modelContractSaveState = { projectId: current.id, appId: current.app, state: message.state, generation: message.generation };
6388
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
+
6389
6545
  // The Drawing Checker's "Use the design set" sends a person to this project's Knowledge step, where the design
6390
6546
  // set lives (epic #2399 0d-dc). Only from the editor frame of the project on screen, and only to Knowledge.
6391
6547
  window.addEventListener('message', (event) => {
@@ -6395,50 +6551,117 @@
6395
6551
  setStep('knowledge');
6396
6552
  });
6397
6553
  const approvalPhaseText = {
6398
- saving: 'Saving model edits…', comparing: 'Comparing changes…', approving: 'Approving and compiling…',
6399
- 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.',
6400
6556
  abandoned: 'Nothing was approved. The previous approval attempt ended safely.',
6401
6557
  };
6402
- 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);
6403
6560
 
6404
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
+
6405
6608
  const st = approvalDialogState;
6406
6609
  if (!st) return;
6407
6610
  const changed = st.phase !== phase;
6611
+ const wasBusy = approvalBusy(st.phase);
6408
6612
  st.phase = phase;
6409
6613
  if ($approvalRevisionNote) $approvalRevisionNote.hidden = !['ready', 'failed'].includes(phase);
6410
6614
  // Recovery may be dismissed, but it must never unlock a second mutation while the durable
6411
6615
  // outcome is pending or unreadable. Dismissibility and mutation safety are separate concerns.
6412
- const locked = !approvalDismissible(phase) || ['abandoned', 'recovery-close'].includes(phase);
6616
+ const locked = !approvalDismissible(phase) || ['abandoned', 'recovery-close', 'reconciling'].includes(phase);
6413
6617
  const cancelVisible = ['saving', 'comparing', 'ready', 'failed', 'stale'].includes(phase);
6618
+ const closeVisible = ['approved', 'abandoned', 'recovery-close'].includes(phase) || phase === 'reconciling';
6414
6619
  const active = document.activeElement;
6415
6620
  const activeControlWillHide = (active === $approvalCancel && !cancelVisible)
6416
6621
  || (active === $approvalRetry && phase !== 'failed')
6417
6622
  || (active === $approvalReload && phase !== 'stale')
6418
- || (active === $approvalClose && !['approved', 'abandoned', 'recovery-close'].includes(phase))
6623
+ || (active === $approvalClose && !closeVisible)
6419
6624
  || (active === $approvalConfirm && !['ready', 'abandoned'].includes(phase));
6420
6625
  if (activeControlWillHide || (locked && active && $approvalBody.contains(active))) $approvalDialog.focus();
6421
- if (changed && $approvalLive) $approvalLive.textContent = message || approvalPhaseText[phase] || '';
6422
- $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));
6423
6636
  $approvalCancel.hidden = !cancelVisible;
6424
6637
  $approvalRetry.hidden = phase !== 'failed';
6425
6638
  $approvalReload.hidden = phase !== 'stale';
6426
- $approvalClose.hidden = !['approved', 'abandoned', 'recovery-close'].includes(phase);
6427
- $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…'; }
6428
6646
  // Unlocking never re-enables a control the review blocked with a reason (nothing drawn, or a
6429
6647
  // refusal no new choice can fix): it stays disabled, and focus skips it.
6430
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'); });
6431
- if (phase === 'saving' || phase === 'comparing') {
6432
- const text = message || approvalPhaseText[phase];
6433
- $approvalBody.innerHTML = `<div class="approval-loading"><span class="rtn-spinner" aria-hidden="true"></span><span aria-hidden="true">${escapeHtml(text)}</span></div>`;
6434
- $approvalSub.textContent = phase === 'saving' ? 'Finishing the model edits already on screen…' : 'Loading the server comparison…';
6435
- } else if (phase === 'approving' || phase === 'reconciling') {
6436
- $approvalSub.textContent = message || approvalPhaseText[phase];
6437
- } else if (['approved', 'failed', 'stale', 'abandoned', 'recovery-close'].includes(phase)) {
6438
- // A terminal/recovery outcome replaces the in-flight phase visibly as well as in the live region.
6439
- // Leaving "Approving and compiling…" above an Approved/failed body makes a finished command look
6440
- // stuck — the exact ambiguity this state machine exists to remove.
6441
- $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
+ }
6442
6665
  }
6443
6666
  }
6444
6667
 
@@ -6535,15 +6758,81 @@
6535
6758
  const approvalRefusalDetail = (sentence) => String(sentence || '').replace(/\s*Nothing was approved\.\s*/g, ' ').trim();
6536
6759
  /** Refusals whose sentence the server writes for people. Any other error text (a bake or compile
6537
6760
  * message, an internal conflict) stays behind the generic copy instead of reaching the screen. */
6538
- 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];
6539
6762
  function knownApprovalFailureReason(error) {
6540
6763
  const body = error && error.body;
6541
6764
  if (!body || typeof body.error !== 'string' || !body.error.trim()) return '';
6542
6765
  return APPROVAL_REASON_CODES.includes(body.code) ? body.error.trim() : '';
6543
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
+ }
6544
6820
 
6545
6821
  function renderApprovalReview() {
6546
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
+
6547
6836
  const review = approvalDialogState.review;
6548
6837
  const groups = Array.isArray(review.groups) ? review.groups : [];
6549
6838
  const findings = review.importFindings && Number(review.importFindings.open) > 0 ? review.importFindings : null;
@@ -6563,15 +6852,29 @@
6563
6852
  ? review.moveForward.replacesLatest
6564
6853
  ? `This model will replace v${review.moveForward.toVersion} as the approved version`
6565
6854
  : `Your changes from v${review.moveForward.fromVersion} will be applied on top of approved v${review.moveForward.toVersion}`
6566
- : review.base ? `Compared with approved v${review.base.version}` : 'First approval · full-model baseline';
6567
- $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;
6568
6859
  const groupHtml = groups.map((group) => {
6569
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);
6570
6869
  const facts = Array.isArray(group.technicalFacts) && group.technicalFacts.length
6571
- ? `<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');
6572
6875
  const discard = review.selective ? `<button type="button" class="approval-discard" data-approval-discard="${escapeAttr(group.id)}">Discard change…</button>` : '';
6573
6876
  return `<section class="approval-group"><div class="approval-group-head"><div>`
6574
- + `<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>`
6575
6878
  + `<span>${escapeHtml(String(group.location || ''))}</span></div><p>${escapeHtml(String(group.detail || ''))}</p>`
6576
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'))}">`
6577
6880
  + ['approve', 'leave-pending'].map((decision) => approvalDecisionButtonHtml(group, decision, picked, findingsCopy, blockedReason)).join('')
@@ -6602,7 +6905,7 @@
6602
6905
  : '';
6603
6906
  const findingsHtml = nothingDrawn ? nothingDrawnHtml(nothingDrawn) : unreadable ? unreadableFindingsHtml(unreadable)
6604
6907
  : findings ? importFindingsWarningHtml(findings, !!blockedReason) : '';
6605
- $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>');
6606
6909
  const values = Object.values(decisions);
6607
6910
  const approved = values.filter((value) => value === 'approve').length;
6608
6911
  const remaining = groups.length - values.length;
@@ -6629,6 +6932,17 @@
6629
6932
  const st = approvalDialogState;
6630
6933
  if (st && !approvalDismissible(st.phase)) return;
6631
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
+ }
6632
6946
  if ($approvalRevisionNoteText) $approvalRevisionNoteText.value = '';
6633
6947
  $approvalModal.classList.remove('show');
6634
6948
  $approvalModal.removeAttribute('aria-busy');
@@ -6815,50 +7129,95 @@
6815
7129
  $quick.hidden = false;
6816
7130
  }
6817
7131
 
6818
- async function finishApprovalSuccess(res, project) {
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;
6819
7136
  const revisionNoteStatus = await finishApprovalRevisionNote(res, project);
6820
- 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 = '';
6821
7143
  if (res && res.approvedAt) project.approvedAt = res.approvedAt;
6822
- const n = res && res.version && Number(res.version.n);
6823
- if (Number.isInteger(n)) expandDiffOnce = { projectId: project.id, n };
6824
- reloadModelFromServerTruth();
6825
- await refreshApprovalState(project.id);
6826
- 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.';
6827
7164
  const saved = res && res.savedWorkCheckpoint;
6828
- // #1840: the outcome says what the server recorded. An approval that accepted open import
6829
- // findings is never announced as a plain "Approved".
6830
- const accepted = res && res.version && res.version.approval && res.version.approval.acceptedImportFindings;
6831
- const headline = accepted ? importFindingsCopy(accepted).approved(Number.isInteger(n) ? n : null)
6832
- : `Approved${Number.isInteger(n) ? ` as v${n}` : ''}.`;
6833
- // #2449: an approval resting on connection assumptions (or one whose record could not be read) is never announced
6834
- // as a plain approval either; the server's own sentence, the same one History shows.
6835
- const assumed = res && res.connectionAssumptions && typeof res.connectionAssumptions.note === 'string' ? res.connectionAssumptions.note : '';
6836
- // #2521 row 5: an approved Quick model says so in the same breath, read from the approved version itself.
6837
- const quick = res && res.quick && (res.quick.state === 'quick' || res.quick.state === 'unknown') && typeof res.quick.label === 'string'
6838
- ? `${res.quick.label}. ` : '';
6839
- showToast(`${headline} ${quick}${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');
6840
7169
  track('workspace_project_approved', { app: project.app });
6841
- if (!$wsExports.hidden) safeRenderExports('after approving this version');
6842
- if (!$wsHistory.hidden) await renderHistory();
6843
- if (!approvalDialogState) return;
6844
- $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
6845
7174
  ? `${pending} change${pending === 1 ? ' remains' : 's remain'} pending${saved ? ' in Saved work' : ''}.`
6846
7175
  : 'No changes remain pending.';
6847
7176
  // The footer described the decision ("…will be approved…"); the decision has happened.
6848
7177
  $approvalCounts.textContent = '';
6849
- $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>`;
6850
- 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}` : ''}`);
6851
7180
  $approvalClose.focus();
6852
7181
  }
6853
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.
6854
7208
  async function reconcileApprovalOperation(project, operationId, operationToken) {
6855
- setApprovalPhase('reconciling');
6856
7209
  try {
6857
7210
  const response = await fetch(`/api/projects/${encodeURIComponent(project.id)}/approval-operations/${encodeURIComponent(operationId)}?token=${encodeURIComponent(operationToken)}`, {
6858
- signal: AbortSignal.timeout(4000),
7211
+ signal: AbortSignal.timeout(30000),
6859
7212
  });
6860
7213
  if (response.status === 404) return { status: 'not-found' };
6861
- 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
+ }
6862
7221
  const receipt = await response.json();
6863
7222
  return receipt && ['complete', 'pending', 'abandoned'].includes(receipt.status) ? receipt : { status: 'unknown' };
6864
7223
  } catch { return { status: 'unknown' }; }
@@ -6868,9 +7227,126 @@
6868
7227
  : receipt?.status === 'abandoned' ? 'abandoned'
6869
7228
  : receipt?.status === 'not-found' ? 'continue' : 'locked';
6870
7229
 
6871
- 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) {
6872
7328
  const pending = receipt?.status === 'pending';
6873
- $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 = '';
6874
7350
  setApprovalPhase('recovery-close', pending ? 'Approval recovery is still in progress.' : 'The approval result is not available yet.');
6875
7351
  $approvalClose.focus();
6876
7352
  }
@@ -6879,7 +7355,9 @@
6879
7355
  // "Nothing was approved" is said because the reconcile answered `abandoned` (the operation was
6880
7356
  // retired with no committed row); the reason says WHY, instead of generic recovery copy. (A refusal
6881
7357
  // made before any write says it in the review itself; see confirmApprovalReview.)
6882
- 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>` : '';
6883
7361
  const st = approvalDialogState;
6884
7362
  if (!st) return;
6885
7363
  rememberApprovalOperation(project, null);
@@ -6892,7 +7370,10 @@
6892
7370
  $approvalImpact.textContent = '';
6893
7371
  $approvalCounts.textContent = '';
6894
7372
  const detail = approvalRefusalDetail(reason);
6895
- $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>`;
6896
7377
  $approvalConfirm.setAttribute('data-command-id', 'shell.approval-start-new-review');
6897
7378
  $approvalConfirm.removeAttribute('data-blocked-reason');
6898
7379
  $approvalConfirm.textContent = 'Start a new review';
@@ -6901,6 +7382,57 @@
6901
7382
  $approvalConfirm.focus();
6902
7383
  }
6903
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
+
6904
7436
  async function startNewApprovalReview() {
6905
7437
  const st = approvalDialogState;
6906
7438
  if (!st || st.phase !== 'abandoned' || !current || current.id !== st.projectId) return;
@@ -6929,23 +7461,21 @@
6929
7461
  $approvalConfirm.disabled = true;
6930
7462
  // A fresh dialog starts with no blocked reason; the review's own render sets one if it needs it.
6931
7463
  $approvalConfirm.removeAttribute('data-blocked-reason');
6932
- 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' };
6933
7467
  const dialogState = approvalDialogState;
6934
- setApprovalPhase('comparing');
7468
+ setApprovalPhase(remembered ? 'reconciling' : 'comparing');
6935
7469
  $approvalDialog.focus();
6936
7470
  try {
6937
- const remembered = rememberedApprovalOperation(project);
6938
7471
  if (remembered && $approvalRevisionNoteText) { $approvalRevisionNoteText.value = remembered.revisionNoteText || ''; approvalDialogState.revisionNoteText = $approvalRevisionNoteText.value; }
6939
7472
  if (remembered) {
6940
7473
  approvalDialogState.operationId = remembered.operationId;
6941
7474
  approvalDialogState.operationToken = remembered.operationToken;
6942
- let receipt = await reconcileApprovalOperation(project, remembered.operationId, remembered.operationToken);
6943
- for (let attempt = 0; approvalRecoveryDisposition(receipt) === 'locked' && attempt < 20; attempt += 1) {
6944
- await new Promise((resolve) => setTimeout(resolve, 500));
6945
- receipt = await reconcileApprovalOperation(project, remembered.operationId, remembered.operationToken);
6946
- }
7475
+ const receipt = await checkApprovalOutcome(project, remembered.operationId, remembered.operationToken);
7476
+ if (!receipt || approvalDialogState !== dialogState) return;
6947
7477
  if (approvalRecoveryDisposition(receipt) === 'complete') {
6948
- await finishApprovalSuccess(receipt, project);
7478
+ await finishApprovalSuccess(receipt, project, { recovered: true });
6949
7479
  return;
6950
7480
  }
6951
7481
  if (approvalRecoveryDisposition(receipt) === 'abandoned') {
@@ -6957,6 +7487,9 @@
6957
7487
  return;
6958
7488
  }
6959
7489
  }
7490
+ // No earlier attempt to finish: this is the ordinary save-and-compare preparation.
7491
+ dialogState.flow = 'prepare';
7492
+ dialogState.busySince = Date.now();
6960
7493
  const win = frames.model && frames.model.contentWindow;
6961
7494
  // History is server-owned after partial approval and may hide an editor whose in-memory draft
6962
7495
  // predates that partition. Other tabs can be reached immediately after an edit, before the
@@ -7015,10 +7548,20 @@
7015
7548
  if (approvalDialogState !== dialogState) return;
7016
7549
  approvalDialogState.stale = false;
7017
7550
  approvalDialogState.retryAction = 'prepare';
7018
- $approvalSub.textContent = 'Approval status unavailable';
7019
- $approvalImpact.textContent = (error && error.message) || 'Could not load the comparison.';
7020
- $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>';
7021
- 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
+ }
7022
7565
  $approvalRetry.focus();
7023
7566
  }
7024
7567
  }
@@ -7055,6 +7598,20 @@
7055
7598
  }
7056
7599
 
7057
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
+
7058
7615
  const st = approvalDialogState;
7059
7616
  if (!st || $approvalConfirm.disabled || !current || current.id !== st.projectId) return;
7060
7617
  const project = current;
@@ -7077,6 +7634,10 @@
7077
7634
  const findings = st.review.importFindings;
7078
7635
  const acceptOpenImportFindings = findings && Number(findings.open) > 0 && Object.values(st.decisions).includes('approve')
7079
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 = '';
7080
7641
  setApprovalPhase('approving');
7081
7642
  $approvalConfirm.disabled = true;
7082
7643
  st.refusal = null;
@@ -7120,17 +7681,30 @@
7120
7681
  setApprovalPhase('stale', 'The review changed. Reload current review.');
7121
7682
  $approvalReload.focus();
7122
7683
  } else if (approvalDialogState) {
7123
- 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;
7124
7690
  if (approvalRecoveryDisposition(recovered) === 'complete') {
7125
7691
  await finishApprovalSuccess(recovered, project);
7126
7692
  return;
7127
7693
  }
7128
- if (approvalRecoveryDisposition(recovered) === 'abandoned') {
7129
- 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);
7130
7699
  return;
7131
7700
  }
7132
- if (approvalRecoveryDisposition(recovered) === 'locked') {
7133
- 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);
7134
7708
  return;
7135
7709
  }
7136
7710
  approvalDialogState.decisions = decisionSnapshot.decisions;
@@ -7220,6 +7794,7 @@
7220
7794
  if (again) again.focus();
7221
7795
  return;
7222
7796
  }
7797
+ if (event.target.closest('[data-approval-check-again]')) { checkApprovalAgain(); return; }
7223
7798
  const openAudit = event.target.closest('[data-approval-open-audit]');
7224
7799
  if (openAudit && approvalDialogState && approvalDismissible(approvalDialogState.phase)) {
7225
7800
  // #1840: show the findings themselves. Nothing is approved; the review can be reopened.
@@ -7300,7 +7875,8 @@
7300
7875
  // model would mislead). Same-origin contentWindow call, like the Approve flush above.
7301
7876
  function wsFindActive() {
7302
7877
  if (!$app.classList.contains('mode-workspaces')) return false;
7303
- 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;
7304
7880
  const w = frames.model.contentWindow;
7305
7881
  if (!w || typeof w.findMember !== 'function') return false;
7306
7882
  try { if (w.document.getElementById('aiUpdateBanner')) return false; } catch { return false; }
@@ -7753,7 +8329,8 @@
7753
8329
  `<div class="kb-ds-ph" id="kb-ds-ph-${escapeAttr(issue.issueId)}">Read “${escapeHtml(issue.label)}” into the model</div>` +
7754
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>` +
7755
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>` +
7756
- (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 +
7757
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>' +
7758
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>` : '') +
7759
8336
  '</div></div>';
@@ -10631,26 +11208,50 @@
10631
11208
  const proj = current;
10632
11209
  if (!proj) return;
10633
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);
10634
11215
  let plan;
10635
11216
  try { plan = await api(`${kbDsBase(proj)}/issues/${encodeURIComponent(issueId)}/read-plan`); }
10636
11217
  catch (err) {
10637
- if (current !== proj || !kbDsPanel || kbDsPanel.issueId !== issueId) return;
11218
+ if (current !== proj || kbDsPanel !== panel) return;
10638
11219
  kbDsPanel = null;
10639
11220
  showToast(kbDsErrorText(err, 'Couldn’t check the files of this issue. Try again.'), 'warn');
10640
11221
  kbDsRepaint();
10641
11222
  return;
10642
11223
  }
10643
- 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: '' };
10644
11229
  kbDsPanel.plan = plan;
10645
11230
  kbDsPanel.chosen = new Set(plan.included.map((f) => f.index));
10646
11231
  kbDsFocus = { issueId, control: '.kb-ds-panel input[type="checkbox"], .kb-ds-panel .btn-mini' };
10647
11232
  kbDsRepaint();
10648
11233
  }
10649
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
+
10650
11244
  async function kbDsReadGo(issueId, returnFocus) {
10651
11245
  const proj = current;
10652
11246
  const panel = kbDsPanel;
10653
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
10654
11255
  const chosen = [...panel.chosen].sort((a, b) => a - b);
10655
11256
  const asPlanned = panel.plan.chosenByDefault && chosen.length === panel.plan.included.length
10656
11257
  && chosen.every((n, i) => n === panel.plan.included[i].index);
@@ -10660,6 +11261,7 @@
10660
11261
  : await api(`${kbDsBase(proj)}/issues/${encodeURIComponent(issueId)}/read-plan?files=${chosen.join(',')}`);
10661
11262
  // The panel promised the ticked files (40 at most). If the server would take a different set — a copy changed
10662
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
10663
11265
  const promised = chosen.slice(0, 40).join(',');
10664
11266
  if (!asPlanned && plan.included.map((f) => f.index).join(',') !== promised) {
10665
11267
  if (current !== proj || !kbDsPanel) return;
@@ -10671,11 +11273,11 @@
10671
11273
  return;
10672
11274
  }
10673
11275
  const res = await api(`/api/projects/${encodeURIComponent(proj.id)}/revision-requests`, { method: 'POST',
10674
- 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 }) });
10675
11277
  if (current !== proj) return;
10676
11278
  const n = plan.included.length;
10677
11279
  const issue = kbDsIssueById(issueId);
10678
- 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`);
10679
11281
  track('kb_design_issue_read', { app: proj.app, n });
10680
11282
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
10681
11283
  kbDsClosePanel({ issueId, control: '[data-kb-ds-read]' });
@@ -10801,6 +11403,7 @@
10801
11403
  }
10802
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; }
10803
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;
10804
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; }
10805
11408
  if ((b = t('[data-kb-ds-requests]'))) { if (bridge.openRequest) bridge.openRequest(null); return true; }
10806
11409
  if ((b = t('[data-kb-ds-jump]'))) {
@@ -10813,6 +11416,7 @@
10813
11416
  }
10814
11417
  // Ticks and typing in a panel are kept in its state, so a repaint redraws them as they were.
10815
11418
  $wsKnowledge.addEventListener('change', (e) => {
11419
+ if (e.target.closest('.kb-ds-panel [data-rev-build-auto]') && kbDsChooseBuild(e.target)) return;
10816
11420
  const pick = e.target.closest('[data-kb-ds-pick], [data-kb-ds-add-pick]');
10817
11421
  if (!pick || !kbDsPanel) return;
10818
11422
  if (kbDsPanel.kind === 'read' && pick.dataset.kbDsPick !== undefined) {
@@ -11242,6 +11846,16 @@
11242
11846
  return `Takes ${humanRange(lo * n, hi * n)}${each}. This project's other exports wait until it finishes.`;
11243
11847
  }
11244
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
+
11245
11859
  async function askRenderOptions(projectId) {
11246
11860
  // `viewpoints` (plural) — the shape doExport actually reads. This said `viewpoint` and would
11247
11861
  // have thrown on `.length` the moment it was reached.
@@ -11251,7 +11865,8 @@
11251
11865
  title: 'Render image',
11252
11866
  // The Tekla card in this same grid genuinely mutates a live host model, so users have an
11253
11867
  // earned reason to be wary of buttons here. Say plainly that this one only reads.
11254
- 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.`,
11255
11870
  okLabel: 'Render',
11256
11871
  // The estimate has to be live: it is the product of two fields (how many angles × how dear
11257
11872
  // each is), so no fixed label can state it. This is the difference between choosing five
@@ -11784,6 +12399,65 @@
11784
12399
  `</span></div>`;
11785
12400
  }
11786
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
+
11787
12461
  function receiptHtml(kind, approved) {
11788
12462
  const receipt = approved ? currentReceipt(kind) : null;
11789
12463
  if (!receipt) return '';
@@ -12582,6 +13256,55 @@
12582
13256
  };
12583
13257
  }
12584
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
+
12585
13308
  function cardHtml(c, approved) {
12586
13309
  let meta;
12587
13310
  const busy = exportBusy.has(`${current.id}:${c.kind}`);
@@ -12616,6 +13339,10 @@
12616
13339
  meta = `<span class="e-status">not exported yet</span>`;
12617
13340
  }
12618
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');
12619
13346
  const exported = approved && c.file && exportState && exportState[c.kind] && exportState[c.kind].exportedAt;
12620
13347
  // Re-labelled once a link exists, mirroring the file kinds' "Re-export" convention. Gated on the
12621
13348
  // in-memory record rather than exportState, which only ever tracks file exports.
@@ -12676,6 +13403,7 @@
12676
13403
  `<div class="e-top"><div class="e-ico">${escapeHtml(c.ico)}</div>` +
12677
13404
  `<div><div class="e-name">${escapeHtml(c.name)}</div><div class="e-fmt">${escapeHtml(c.fmt)}</div></div></div>` +
12678
13405
  `<div class="e-meta${special ? ' e-meta-stacked' : ''}">${meta}</div>` +
13406
+ drafts +
12679
13407
  // Only the still gets a preview: an MP4 has no frame to show without decoding one, and a
12680
13408
  // card is not a video player. Click opens it exactly like ⧉ Open — no lightbox.
12681
13409
  (c.kind === 'render' && approved && exportState && exportState['render-png']
@@ -12700,6 +13428,7 @@
12700
13428
  // says what the producer could not emit from what it was given, this says what was never
12701
13429
  // given to it. A model missing three heights and an AWARE weld failure are not one fact.
12702
13430
  (c.kind === 'send-host' ? '' : omittedHtml(c.kind, approved)) +
13431
+ (c.kind === 'send-host' ? '' : exportProvenanceHtml(c.kind, approved)) +
12703
13432
  // REGISTERED, because #1156a changed what this button DOES. It used to refuse an export outright
12704
13433
  // when any member's endpoint elevation was unresolved; now the file exports build what they can
12705
13434
  // and name what they left out, while a bake into a live host still refuses (and says why). A
@@ -12789,6 +13518,15 @@
12789
13518
  const key = JSON.stringify(exportSourcesState.selected);
12790
13519
  const found = options.find((option) => JSON.stringify(option.selector) === key);
12791
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
+ }
12792
13530
  }
12793
13531
  return options.find((option) => option.selector.kind === 'latest-approved') || null;
12794
13532
  }
@@ -12849,11 +13587,36 @@
12849
13587
  if (!source) return '';
12850
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>` : '');
12851
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
+ : '';
12852
13594
  const from = exportStateFrom;
12853
13595
  const files = from && from.quick && exportState && Object.values(exportState).some((e) => e && e.exportedAt)
12854
13596
  && !(source.selector.kind === 'latest-approved' && Number(source.version) === Number(from.version))
12855
13597
  ? line(from.quick, `Files below, exported from v${from.version}`) : '';
12856
- return selected + files;
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>';
12857
13620
  }
12858
13621
 
12859
13622
  /**
@@ -12956,6 +13719,7 @@
12956
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 ` +
12957
13720
  `is optional. Each writes to this project’s <button type="button" class="exports-note-link" data-open-exports-folder ` +
12958
13721
  `aria-label="Open the exports folder" data-tip="Open this project’s exports folder">▤ exports</button> folder.</div>`;
13722
+ html += exportedFromNoteHtml();
12959
13723
  const cards = (wsApp() && wsApp().exports) || [];
12960
13724
  html += '<div class="export-grid">' + cards.map((c) => cardHtml(c, approved)).join('') + '</div>';
12961
13725
  $wsExports.innerHTML = html;
@@ -13201,6 +13965,7 @@
13201
13965
  let state = null;
13202
13966
  let units = null; // the server's answer, applied below the staleness guard with the others
13203
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
13204
13969
  // SAYS THE THING THE GUARD MEANS. `if (units)` was correct only because the ternary above can
13205
13970
  // never produce a falsy value — so a later, entirely reasonable "report what the server actually
13206
13971
  // said, stop coercing" change to `units = r.units` would silently re-enable the resurrected-
@@ -13258,7 +14023,10 @@
13258
14023
  if (!sourcesRefused && sourceResult.status === 'fulfilled') {
13259
14024
  exportSourcesState.status = 'ready';
13260
14025
  exportSourcesState.data = sourceResult.value;
13261
- 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;
13262
14030
  } else {
13263
14031
  exportSourcesState = { status: 'unavailable', data: null, selected: null, open: false };
13264
14032
  }
@@ -13288,6 +14056,7 @@
13288
14056
  // there for why.
13289
14057
  answered = true;
13290
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') : [];
13291
14060
  filesFrom = r.receiptsFrom && Number.isInteger(r.receiptsFrom.version) && typeof r.receiptsFrom.hash === 'string' ? r.receiptsFrom : null;
13292
14061
  units = r.units === 'mm' ? 'mm' : 'ft-in';
13293
14062
  } else {
@@ -13318,6 +14087,7 @@
13318
14087
  if (answered) current.approvedAt = approvedAt;
13319
14088
  exportState = state;
13320
14089
  exportStateFrom = answered ? filesFrom : null;
14090
+ exportDrafts = answered ? draftRows : [];
13321
14091
  paintExports(approvedAt, restoreKind);
13322
14092
  }
13323
14093
 
@@ -13368,7 +14138,7 @@
13368
14138
  const result = await api(`/api/projects/${encodeURIComponent(projectId)}/export-raw`, {
13369
14139
  method: 'POST', body: JSON.stringify({ sourceHandle: source.handleId }),
13370
14140
  });
13371
- exportSourcesState.selected = null;
14141
+ if (!(source.kind === 'working' || source.kind === 'checkpoint')) exportSourcesState.selected = null; // a DRAFT choice is kept (#2781)
13372
14142
  showToast(`Exported raw package — ${result.filename}`, 'ok');
13373
14143
  // Through the wrapper, and that is the POINT here rather than tidiness: this `await` sits
13374
14144
  // inside a try whose catch says "Raw export failed", so a repaint bug used to be reported to
@@ -13379,6 +14149,15 @@
13379
14149
  }
13380
14150
  }
13381
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
+
13382
14161
  async function doExport(kind) {
13383
14162
  if (!current) return;
13384
14163
  // Sending to a CAD application is its own flow end to end: it asks WHERE first, then performs
@@ -13492,9 +14271,14 @@
13492
14271
  try {
13493
14272
  // Render and the BOM are the exports whose POST carries a body — the options their modal collected.
13494
14273
  const body = renderOptions || bomOptions;
13495
- const res = await api(exportUrl(kind, projectId, app, capturedSource.handleId), body
13496
- ? { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }
13497
- : { 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'); }
13498
14282
  if (kind === 'bom') {
13499
14283
  // The batch answers per format. A 200 here means SOMETHING landed, not that everything did —
13500
14284
  // so the toast names what failed rather than letting a green tick stand for a partial run, and
@@ -13509,7 +14293,10 @@
13509
14293
  + (failed[0].error || 'no reason given'),
13510
14294
  'warn');
13511
14295
  } else {
13512
- 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');
13513
14300
  }
13514
14301
  // Per FORMAT, so the analytics keep the granularity the two separate cards used to give.
13515
14302
  for (const r of ok) track('workspace_export', { app, kind: `bom-${r.format}` });
@@ -13520,15 +14307,22 @@
13520
14307
  return safeRenderExports('after that bill of materials export', undefined,
13521
14308
  () => { if (current && current.id === projectId) paintExports(current.approvedAt); });
13522
14309
  }
13523
- 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;
13524
14315
  track('workspace_export', { app, kind, sourceKind: capturedSource.kind }); // a successful export/bake
13525
- 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 ? {
13526
14319
  counts: res.counts,
13527
14320
  warnings: res.warnings || [],
13528
14321
  unsupported: res.receipt && Array.isArray(res.receipt.unsupported) ? res.receipt.unsupported : [],
13529
14322
  approvedAt,
13530
- });
13531
- 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);
13532
14326
  // #1156a: an export that LEFT MEMBERS OUT must not announce itself as clean. The two sources
13533
14327
  // are different questions - the receipt says what the producer could not emit from what it was
13534
14328
  // given, `skippedDetail` says what was never given to it - so BOTH are gathered before a single
@@ -13539,10 +14333,12 @@
13539
14333
  summary && summary.partial ? summary.text : null,
13540
14334
  omittedNow ? `${omittedNow} member${omittedNow === 1 ? '' : 's'} left out — see the card for why` : null,
13541
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` : '';
13542
14338
  showToast(gaps.length
13543
- ? `Exported with gaps — ${gaps.join(' · ')}`
13544
- : `Exported — ${res.filename || kind}`,
13545
- 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');
13546
14342
  refreshing = true;
13547
14343
  // The catch is what makes the finally's skip safe: if the refresh itself throws, nothing else
13548
14344
  // would repaint and the card would sit in its busy state forever, with exportBusy already
@@ -13554,7 +14350,7 @@
13554
14350
  } catch (err) {
13555
14351
  // The durable export listing may still show the previously published file, but its in-session
13556
14352
  // receipt must not masquerade as the result of this failed attempt.
13557
- exportReceipts.delete(`${projectId}:${kind}`);
14353
+ forgetExportReceiptAfterFailure(projectId, kind, capturedSource);
13558
14354
  // The render route ships machine-readable readiness on its 409 precisely so the card can
13559
14355
  // show WHICH dependency broke. Dropping it left the card looking ready with an enabled
13560
14356
  // button, and the only trace of the refusal was a toast that evaporates.
@@ -13588,6 +14384,66 @@
13588
14384
  }
13589
14385
  }
13590
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
+
13591
14447
  function showExportReceiptDetails(kind, returnFocusTo) {
13592
14448
  const projectId = current && current.id;
13593
14449
  const summary = receiptSummary(currentReceipt(kind), kind);
@@ -13698,9 +14554,13 @@
13698
14554
  * most recent.
13699
14555
  */
13700
14556
  async function fileAction(endpoint, kind, failMsg) {
13701
- 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(':');
13702
14560
  const row = exportState && exportState[baseKind];
13703
- 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)
13704
14564
  ? row.variants.find((v) => v.variant === variant)
13705
14565
  : row;
13706
14566
  if (!st || !st.path) return; // button only shows when a path exists; belt-and-braces
@@ -13829,6 +14689,10 @@
13829
14689
  // no SSE hook — and refreshes History on completion. Cards are DOM-built (textContent, never
13830
14690
  // innerHTML) so an AI-supplied error string can never reach the DOM as markup.
13831
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;
13832
14696
  // A reconstruction refusal is permanent for that immutable staged generation. Remember it for this
13833
14697
  // browser session so the 3-second request poll cannot resurrect a Review action that the server has
13834
14698
  // already proved will never work. The exact stage id keeps a later replacement generation eligible.
@@ -13875,13 +14739,17 @@
13875
14739
  * miss without widening that window — an unknown project falls back to 0, exactly as a cold page
13876
14740
  * load always has.
13877
14741
  */
14742
+ let revisionBuildAsk = null; // #2521 row 7b: the open confirm step after the file picker, if any (askRevisionBuild)
13878
14743
  function resetRevisionState() {
13879
14744
  lastRevState = 'none';
14745
+ revisionListKnown = false;
13880
14746
  revCardReq = null;
13881
14747
  $revisionCard._renderKey = '';
13882
14748
  revisionGen++; // voids any render still in flight for the project being left
13883
14749
  revisionRequestsSuccessGen = revisionGen; // old same-id failures cannot cross a close/re-open boundary
13884
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
13885
14753
  stopRevisionPoll();
13886
14754
  $revisionCard.hidden = true;
13887
14755
  $revisionCard.replaceChildren();
@@ -14001,16 +14869,192 @@
14001
14869
  }
14002
14870
  }
14003
14871
 
14004
- async function attachRevision(files) {
14005
- 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
14006
15040
  if (!proj || !files.length) return;
14007
15041
  if (!validateSteelDrawingFiles(wsDescOf(proj) === WORKSPACE_APPS['steel-model'] ? 'steel-model' : '', files)) return;
14008
- const projectGeneration = revisionOwnerGen;
15042
+ const projectGeneration = owner ? owner.gen : revisionOwnerGen;
14009
15043
  const attachGeneration = ++revisionAttachGen;
14010
15044
  const ownsAttach = () => current === proj
14011
15045
  && revisionOwnerGen === projectGeneration
14012
15046
  && revisionAttachGen === attachGeneration;
15047
+ if (!ownsAttach()) return;
14013
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
+ }
14014
15058
  let snapshots;
14015
15059
  try { snapshots = await Promise.all(files.map(readFileAsSnapshot)); }
14016
15060
  catch { showToast('Could not read the selected files', 'warn'); return; }
@@ -14018,7 +15062,7 @@
14018
15062
  let res;
14019
15063
  try {
14020
15064
  res = await api(`/api/projects/${encodeURIComponent(proj.id)}/revision-requests`, {
14021
- method: 'POST', body: JSON.stringify({ appId: proj.app, snapshots }),
15065
+ method: 'POST', body: JSON.stringify({ appId: proj.app, snapshots, ...revisionBuildBody(choice) }),
14022
15066
  });
14023
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; }
14024
15068
  const req = res && res.request;
@@ -14036,7 +15080,7 @@
14036
15080
  if (!ownsAttach()) return; // don't drive a replaced project's card/poll/modal or narrate its Copy
14037
15081
  revBaseVersion = (req && typeof req.baseVersion === 'number') ? req.baseVersion : 0;
14038
15082
  revBaseProject = proj.id; // the baseline belongs to THIS project — see resetRevisionState
14039
- 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`);
14040
15084
  // #2399 slice 0c: the drawings also land in the project's design set as an issue. Said either way, never silent.
14041
15085
  const landed = res && res.designSet;
14042
15086
  if (landed && landed.landed && landed.created) {
@@ -14063,8 +15107,9 @@
14063
15107
  }
14064
15108
 
14065
15109
  document.getElementById('ws-attach-revision').addEventListener('click', async () => {
15110
+ const owner = { proj: current, gen: revisionOwnerGen };
14066
15111
  const files = await pickDrawingFiles($revisionFile, wsDescOf(current) === WORKSPACE_APPS['steel-model'] ? 'steel-model' : '');
14067
- if (files.length) attachRevision(files);
15112
+ if (files.length) attachRevision(files, owner);
14068
15113
  });
14069
15114
 
14070
15115
  function buildPendingCard(req) {
@@ -14318,6 +15363,7 @@
14318
15363
  revisionGen += 1;
14319
15364
  revisionRequestsSuccessGen = revisionGen;
14320
15365
  lastRevState = 'none';
15366
+ revisionListKnown = true;
14321
15367
  await renderRevisionCard();
14322
15368
  }
14323
15369
 
@@ -14361,6 +15407,7 @@
14361
15407
  return;
14362
15408
  }
14363
15409
  revisionRequestsSuccessGen = Math.max(revisionRequestsSuccessGen, gen);
15410
+ revisionListKnown = true;
14364
15411
  } catch (e) {
14365
15412
  // The request that failed may belong to a project the user has already left. Do not let its
14366
15413
  // late failure mark the newly opened project's server state as disconnected. For the same
@@ -14828,9 +15875,14 @@
14828
15875
  if (answered) {
14829
15876
  const note = revEl('div', 'rev-row-note');
14830
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})` : ''}`;
14831
15883
  note.appendChild(document.createTextNode(`You answered the ${end.toLowerCase()} height on a height question: `));
14832
15884
  note.appendChild(revEl('b', null, how));
14833
- note.appendChild(document.createTextNode(answered.note ? ` (${answered.note}).` : '.'));
15885
+ note.appendChild(document.createTextNode(`${came}${answered.note ? ` (${answered.note})` : ''}.`));
14834
15886
  notes.push(note);
14835
15887
  const over = answered.overDrawing;
14836
15888
  if (over && typeof over.low === 'number' && typeof over.high === 'number') {
@@ -17017,8 +18069,26 @@
17017
18069
  wrap.appendChild(el('span', 'hd-net-label', 'Net steel:'));
17018
18070
  wrap.appendChild(el('span', 'hd-net-arrow', net > 0 ? '▲' : net < 0 ? '▼' : '•'));
17019
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
+ }
17020
18081
  return wrap;
17021
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
+ }
17022
18092
  // The engine's four honest signals — each names its CONSEQUENCE so a withheld member/connection is
17023
18093
  // never silently absent from the panel. ALL render here (not just identity), above the numbers.
17024
18094
  function diffCautions(w) {
@@ -18362,6 +19432,127 @@
18362
19432
  }
18363
19433
  }
18364
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
+
18365
19556
  // A cross-project object pin still belongs to its original conversation, wherever its model is shown.
18366
19557
  async function openChatOwner(owner) {
18367
19558
  const validId = (id) => typeof id === 'string' && !!id && id.length <= 200;
@@ -18564,7 +19755,7 @@
18564
19755
  tellModelFrame({ type: 'knowledge-changed', projectId });
18565
19756
  },
18566
19757
  setMode, refresh: loadProjects, findActive: wsFindActive, find: wsFind, clearFind: wsClearFind,
18567
- openHistory: wsOpenHistory, openKnowledgePage, openKnowledgeStep, openDrawingsStep, openWorkflowsStep, openConnection, drawingFilterCheckpointSaved,
19758
+ openHistory: wsOpenHistory, openKnowledgePage, openKnowledgeStep, openDrawingsStep, openWorkflowsStep, openConnection, openDrawingAt, drawingFilterCheckpointSaved,
18568
19759
  // #2470 R6.7: the Modules step of a General project (project-modules.js).
18569
19760
  moduleCreateCardsHtml, activateCreateCard, openLinkedProject, openModulesStep, showArchivedProjects,
18570
19761
  syncWorkspaceReporter, openChatOwner, openPagesHome, folderDecisionCompleted,