@floless/app 0.138.2 → 0.139.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/autostart.mjs +6 -2
  2. package/desktop-access-production-manifest.mjs +7 -0
  3. package/dist/floless-server.cjs +157207 -70887
  4. package/dist/schemas/model.continuation.v1.schema.json +19 -0
  5. package/dist/schemas/model.continuation.v2.schema.json +19 -0
  6. package/dist/schemas/model.query-response.v1.schema.json +95 -0
  7. package/dist/schemas/model.query-response.v2.schema.json +80 -0
  8. package/dist/schemas/model.query.v1.schema.json +87 -0
  9. package/dist/schemas/model.query.v2.schema.json +87 -0
  10. package/dist/schemas/model.snap-candidate.v1.schema.json +48 -0
  11. package/dist/schemas/model.snap-constraint.v1.schema.json +18 -0
  12. package/dist/schemas/model.snap-query.v1.schema.json +24 -0
  13. package/dist/schemas/model.snap-result.v1.schema.json +33 -0
  14. package/dist/schemas/model.snapshot.v1.schema.json +136 -0
  15. package/dist/schemas/revit.model.v1.schema.json +24 -0
  16. package/dist/schemas/steel.model.v2.schema.json +45 -6
  17. package/dist/skills/floless-app-approval/SKILL.md +19 -5
  18. package/dist/skills/floless-app-bridge/SKILL.md +19 -6
  19. package/dist/skills/floless-app-knowledge/SKILL.md +22 -1
  20. package/dist/skills/floless-app-new-workflow/SKILL.md +31 -27
  21. package/dist/skills/floless-app-new-workflow/references/build-and-verify.md +13 -12
  22. package/dist/skills/floless-app-onboarding/SKILL.md +3 -3
  23. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +16 -9
  24. package/dist/skills/floless-app-steel-model/SKILL.md +11 -2
  25. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +95 -0
  26. package/dist/skills/floless-app-steel-takeoff/SKILL.md +142 -21
  27. package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +19 -0
  28. package/dist/skills/floless-app-tweak-contract/SKILL.md +42 -8
  29. package/dist/skills/floless-app-vectorize/SKILL.md +19 -6
  30. package/dist/skills/floless-app-workflows/SKILL.md +30 -3
  31. package/dist/skills/floless-app-workflows/references/workspace-data.md +77 -4
  32. package/dist/templates/floless-workspace-model-report.flo +77 -0
  33. package/dist/templates/revit-model.flo +111 -0
  34. package/dist/web/app.css +415 -177
  35. package/dist/web/app.js +302 -51
  36. package/dist/web/aware.js +1357 -1032
  37. package/dist/web/chat.css +692 -0
  38. package/dist/web/chat.js +2651 -0
  39. package/dist/web/commands-revit.js +42 -0
  40. package/dist/web/commands-shell.js +531 -70
  41. package/dist/web/commands-steel.js +344 -146
  42. package/dist/web/commands.js +1 -1
  43. package/dist/web/index.html +283 -77
  44. package/dist/web/instructor.js +217 -36
  45. package/dist/web/left-pane.js +636 -0
  46. package/dist/web/model-artifact-loader.js +75 -0
  47. package/dist/web/model-authoring-gestures.js +141 -0
  48. package/dist/web/model-cad-tools.js +20 -0
  49. package/dist/web/model-clip-gesture.js +148 -0
  50. package/dist/web/model-clip-list.js +156 -0
  51. package/dist/web/model-clip-session.js +274 -0
  52. package/dist/web/model-clip-three-overlay.js +295 -0
  53. package/dist/web/model-clip-three-preview.js +59 -0
  54. package/dist/web/model-editor-contract.js +519 -0
  55. package/dist/web/model-editor-revit-adapter.js +139 -0
  56. package/dist/web/model-editor-shell.js +271 -0
  57. package/dist/web/model-editor-state-recovery.js +44 -0
  58. package/dist/web/model-editor-steel-adapter.js +415 -0
  59. package/dist/web/model-editor.css +268 -0
  60. package/dist/web/model-frame.js +192 -0
  61. package/dist/web/model-inspector.js +128 -0
  62. package/dist/web/model-measure.js +390 -0
  63. package/dist/web/model-navigation-controls.js +246 -0
  64. package/dist/web/model-orientation-overlay.js +217 -0
  65. package/dist/web/model-panel-bridge.js +230 -0
  66. package/dist/web/model-pointer-dock.js +164 -0
  67. package/dist/web/model-revit-module.js +83 -0
  68. package/dist/web/model-selection-coordinator.js +151 -0
  69. package/dist/web/model-selection-tools.js +290 -0
  70. package/dist/web/model-snap-contract.js +267 -0
  71. package/dist/web/model-snapping.js +497 -0
  72. package/dist/web/model-spatial-panel.js +294 -0
  73. package/dist/web/model-spatial-tools.js +249 -0
  74. package/dist/web/model-tree.js +47 -0
  75. package/dist/web/model-viewport-lighting.js +166 -0
  76. package/dist/web/model-viewport-revit-adapter.js +1224 -0
  77. package/dist/web/model-viewport-state.js +505 -0
  78. package/dist/web/model-viewport-steel-adapter.js +150 -0
  79. package/dist/web/model-viewport-toolbar.js +516 -0
  80. package/dist/web/model-viewport.js +717 -0
  81. package/dist/web/panels.js +8 -15
  82. package/dist/web/renderers.js +3 -0
  83. package/dist/web/revit-editor.css +35 -0
  84. package/dist/web/revit-editor.html +74 -0
  85. package/dist/web/revit-editor.js +845 -0
  86. package/dist/web/steel-3d-core.js +16 -44
  87. package/dist/web/steel-3d-view.js +1384 -633
  88. package/dist/web/steel-canvas-guidance.js +3 -1
  89. package/dist/web/steel-editor.html +2145 -1255
  90. package/dist/web/steel-filter.html +5 -1
  91. package/dist/web/steel-model-v2-commands.js +80 -3
  92. package/dist/web/steel-split-view.js +5 -39
  93. package/dist/web/steel-view-generation.js +107 -17
  94. package/dist/web/vector-3d.html +12 -0
  95. package/dist/web/workspaces.js +2154 -283
  96. package/distribution-profile-active.mjs +2 -0
  97. package/distribution-profile-production.mjs +47 -0
  98. package/distribution-profile-shared.mjs +8 -0
  99. package/distribution-profile.mjs +18 -0
  100. package/distribution-resource-inventory.mjs +81 -0
  101. package/launch.mjs +18 -10
  102. package/log.mjs +2 -1
  103. package/managed-runtime-policy.mjs +104 -0
  104. package/model-reader-policy-active.mjs +7 -0
  105. package/network-policy-active.mjs +6 -0
  106. package/package.json +17 -2
  107. package/post-update-marker.mjs +3 -1
  108. package/rvt-production-uat-authority.mjs +60 -0
  109. package/teardown.mjs +4 -3
@@ -20,7 +20,12 @@
20
20
  code: 'response-unreadable',
21
21
  error: `FloLess received an unreadable response (HTTP ${res.status}).`,
22
22
  }));
23
- if (!res.ok || body.ok === false) { const e = new Error(body.error || `HTTP ${res.status}`); e.body = body; throw e; }
23
+ if (!res.ok || body.ok === false) {
24
+ const e = new Error(body.error || `HTTP ${res.status}`);
25
+ e.body = body;
26
+ e.status = res.status;
27
+ throw e;
28
+ }
24
29
  return body;
25
30
  });
26
31
  // Product-analytics seam (analytics.js, loaded first). A no-op until PostHog is configured;
@@ -280,6 +285,18 @@
280
285
  const $wsHistory = document.getElementById('ws-history');
281
286
  const $wsKnowledge = document.getElementById('ws-knowledge');
282
287
  const $wsKnowledgeFile = document.getElementById('ws-knowledge-file');
288
+ const $companyKnowledgeModal = document.getElementById('company-knowledge-modal');
289
+ const $companyKnowledgeDialog = $companyKnowledgeModal && $companyKnowledgeModal.querySelector('.company-knowledge-dialog');
290
+ const $companyKnowledgeFolder = document.getElementById('company-knowledge-folder');
291
+ const $companyKnowledgePromotion = document.getElementById('company-knowledge-promotion');
292
+ const $companyPromotionSource = document.getElementById('company-promotion-source');
293
+ const $companyPromotionLineage = document.getElementById('company-promotion-lineage');
294
+ const $companyKnowledgeList = document.getElementById('company-knowledge-list');
295
+ const $companyKnowledgeConfirm = document.getElementById('company-knowledge-confirm');
296
+ const $companyKnowledgeError = document.getElementById('company-knowledge-error');
297
+ const $companyKnowledgeClose = document.getElementById('company-knowledge-close');
298
+ const $companyKnowledgeCancel = document.getElementById('company-knowledge-cancel');
299
+ const $companyKnowledgeAction = document.getElementById('company-knowledge-action');
283
300
  const $approveBtn = document.getElementById('ws-approve');
284
301
  const $approvalModal = document.getElementById('approval-review-modal');
285
302
  const $approvalDialog = $approvalModal && $approvalModal.querySelector('.approval-review');
@@ -287,16 +304,45 @@
287
304
  const $approvalImpact = document.getElementById('approval-review-impact');
288
305
  const $approvalBody = document.getElementById('approval-review-body');
289
306
  const $approvalCounts = document.getElementById('approval-review-counts');
307
+ const $approvalLive = document.getElementById('approval-review-live');
290
308
  const $approvalCancel = document.getElementById('approval-review-cancel');
309
+ const $approvalRetry = document.getElementById('approval-review-retry');
310
+ const $approvalReload = document.getElementById('approval-review-reload');
311
+ const $approvalClose = document.getElementById('approval-review-close');
291
312
  const $approvalConfirm = document.getElementById('approval-review-confirm');
292
313
  const frames = {
293
314
  model: document.getElementById('ws-frame-model'),
294
315
  drawings: document.getElementById('ws-frame-drawings'),
295
316
  };
296
- const $attachRevision = document.getElementById('ws-attach-revision');
317
+ let lastModelDisposeReceipt = null;
318
+ function disposeModelEditorFrame(reason) {
319
+ // The left Model section drops the departing editor's tree now, not at the next load event, so a
320
+ // project switch that stays on the Model step never leaves the old project's rows clickable.
321
+ window.flolessLeftPane?.resetWorkspaceModel?.();
322
+ const frame = frames.model;
323
+ const child = frame && frame.contentWindow;
324
+ if (!child) return null;
325
+ try {
326
+ // Reading location.href is the same-origin proof. A cross-origin or already-torn-down child is
327
+ // allowed to fall through to navigation; pagehide remains its fallback.
328
+ void child.location.href;
329
+ if (typeof child.disposeEditor !== 'function') return null;
330
+ const receipt = child.disposeEditor(reason);
331
+ lastModelDisposeReceipt = receipt && receipt.acknowledged === true ? receipt : null;
332
+ return lastModelDisposeReceipt;
333
+ } catch (_) { return null; }
334
+ }
335
+ window.__modelEditorDisposeReceipt = () => lastModelDisposeReceipt;
297
336
  const $revisionCard = document.getElementById('ws-revision-card');
298
337
  const $revisionFile = document.getElementById('ws-revision-file');
299
338
  const $sourcePlaceholder = document.getElementById('ws-source-placeholder'); // shown for a filter-less Source step
339
+ const $revitSourceActions = document.getElementById('ws-source-actions');
340
+ const $revitReplace = document.getElementById('ws-revit-replace');
341
+ const $revitRetry = document.getElementById('ws-revit-retry');
342
+ const $revitCancel = document.getElementById('ws-revit-cancel');
343
+ const $revitReassure = document.getElementById('ws-source-reassure');
344
+ let revitSourceState = null;
345
+ let revitActiveOperation = null;
300
346
  let currentStep = 'model';
301
347
 
302
348
  // Shared drawing-file picker for both the new-project seed tile and the in-project
@@ -363,6 +409,27 @@
363
409
  });
364
410
  }
365
411
 
412
+ const RVT_FILE_TYPES = [{ description: 'Revit model (.rvt)', accept: { 'application/x-rvt': ['.rvt'] } }];
413
+ async function pickRvtFile(fallbackInput) {
414
+ if (window.showOpenFilePicker) {
415
+ try {
416
+ const [handle] = await window.showOpenFilePicker({ multiple: false, types: RVT_FILE_TYPES });
417
+ return handle ? handle.getFile() : null;
418
+ } catch (err) {
419
+ if (err && err.name === 'AbortError') return null;
420
+ throw err;
421
+ }
422
+ }
423
+ return new Promise((resolve) => {
424
+ const cleanup = () => { fallbackInput.removeEventListener('change', onChange); fallbackInput.removeEventListener('cancel', onCancel); };
425
+ const onChange = () => { cleanup(); const file = (fallbackInput.files || [])[0] || null; fallbackInput.value = ''; resolve(file); };
426
+ const onCancel = () => { cleanup(); resolve(null); };
427
+ fallbackInput.addEventListener('change', onChange);
428
+ fallbackInput.addEventListener('cancel', onCancel);
429
+ fallbackInput.click();
430
+ });
431
+ }
432
+
366
433
  // Single-image picker for Add/Replace thumbnail — same File System Access preference + hidden-input
367
434
  // fallback as the two above. Returns null on cancel; never throws.
368
435
  const THUMB_FILE_TYPES = [{
@@ -414,7 +481,7 @@
414
481
  // only after `createImageBitmap` has expanded the whole source in memory — a decompression bomb (or
415
482
  // an honest 200 MP panorama) can take the tab down there, and an OOM kills the page before any
416
483
  // catch can toast about it. 64 MB is far above any camera file and far below that cliff.
417
- if (file.size > MAX_THUMB_SOURCE_BYTES) throw new Error('too-large');
484
+ if (file.size > MAX_THUMB_SOURCE_BYTES) throw Object.assign(new Error('thumbnail source is too large'), { code: 'too-large' });
418
485
  let bitmap;
419
486
  try { bitmap = await createImageBitmap(file); }
420
487
  catch { throw new Error('decode'); }
@@ -591,6 +658,31 @@
591
658
  { kind: 'svg', ico: '▨', name: 'Traced drawing', fmt: 'SVG', verb: 'Export SVG', file: true, open: true },
592
659
  ],
593
660
  },
661
+ 'revit-model': {
662
+ // Commercial descriptors are presentation only. Unlike the two core apps, this one never
663
+ // participates in first-paint fallback: /api/apps must positively report the canonical
664
+ // installer-owned workflow plus its coarse access state before this card appears.
665
+ serverAuthorizedOnly: true,
666
+ displayName: 'Revit model',
667
+ projectCapability: 'reviewable 3D model',
668
+ createActions: [{
669
+ kind: 'rvt',
670
+ headline: 'Revit model',
671
+ capability: 'RVT → reviewable 3D model',
672
+ sub: 'Open an RVT without Revit. Inspect its hierarchy and properties, then approve a revision for workflows.',
673
+ label: 'Choose RVT',
674
+ }],
675
+ editor: '/revit-editor.html',
676
+ filter: null,
677
+ steps: [
678
+ { key: 'knowledge', label: 'Knowledge' },
679
+ { key: 'drawings', label: 'Source' },
680
+ { key: 'model', label: 'Model' },
681
+ { key: 'history', label: 'History' },
682
+ ],
683
+ diff: false,
684
+ exports: [],
685
+ },
594
686
  };
595
687
  // A project names its app by the LIVE id, which a rename or a duplicate moves off the descriptor
596
688
  // keys above — so resolve through the lineage ROOT the server ships beside it (`templateId`, derived
@@ -644,8 +736,10 @@
644
736
  // client's paint timing can mint an orphan project, and the click surfaces an honest error toast.
645
737
  // The pre-/api/apps default (and the failure fallback): assume each descriptor's canonical app is
646
738
  // the installed one. Unambiguous by construction — one entry per descriptor, appId === templateId.
647
- const wsDefaultAppEntries = () => Object.keys(WORKSPACE_APPS).map((id) => ({ appId: id, templateId: id, ambiguous: false }));
648
- function installedWorkspaceAppEntries(apps) {
739
+ const wsDefaultAppEntries = () => Object.entries(WORKSPACE_APPS)
740
+ .filter(([, descriptor]) => descriptor.serverAuthorizedOnly !== true)
741
+ .map(([id]) => ({ appId: id, templateId: id, ambiguous: false }));
742
+ function installedWorkspaceAppEntries(apps, capabilities) {
649
743
  // Group every installed app whose lineage root the client can render. A known descriptor plus a
650
744
  // live installed source is sufficient authority for today's first-party create cards; requiring
651
745
  // the lagging source flag as a third vote breaks partial updates (#362). Still call out a FLAGGED
@@ -663,12 +757,27 @@
663
757
  if (!byRoot.has(root)) byRoot.set(root, []);
664
758
  byRoot.get(root).push(a.id);
665
759
  }
760
+ const capabilityByRoot = new Map();
761
+ for (const capability of capabilities || []) {
762
+ if (!capability || capability.appId !== 'revit-model' || capability.templateId !== 'revit-model') continue;
763
+ const known = ['ready', 'access-required', 'account-selection-required', 'setup-unavailable', 'check-unavailable'];
764
+ capabilityByRoot.set('revit-model', known.includes(capability.status) ? capability.status : 'check-unavailable');
765
+ // A capability row exists only after the server positively found canonical revit-model. Add
766
+ // its presentation entry even when authorization intentionally filtered it out of `apps`.
767
+ if (!byRoot.has('revit-model')) byRoot.set('revit-model', ['revit-model']);
768
+ }
666
769
  return Object.keys(WORKSPACE_APPS).filter((root) => byRoot.has(root)).map((root) => {
667
770
  // Sorted, so which app a card targets is stable across loads rather than dependent on the
668
771
  // order `aware app list` happened to return. The canonical install wins when present: it is
669
772
  // the one the user has not deliberately made a variant of.
670
773
  const ids = byRoot.get(root).slice().sort();
671
- return { appId: ids.indexOf(root) >= 0 ? root : ids[0], templateId: root, ambiguous: ids.length > 1 };
774
+ const capabilityStatus = capabilityByRoot.get(root);
775
+ return {
776
+ appId: root === 'revit-model' ? 'revit-model' : ids.indexOf(root) >= 0 ? root : ids[0],
777
+ templateId: root,
778
+ ambiguous: root === 'revit-model' ? false : ids.length > 1,
779
+ ...(capabilityStatus ? { capabilityStatus } : {}),
780
+ };
672
781
  });
673
782
  }
674
783
  let wsAppEntries = wsDefaultAppEntries();
@@ -678,7 +787,7 @@
678
787
  // approvedAt remains compatibility metadata only and is never used to invent pending/clean state.
679
788
  let approvalState = { status: 'unavailable', review: null, pendingCount: 0, headVersion: null, error: '' };
680
789
  let approvalStateGen = 0;
681
- let approvalDialogState = null; // { projectId, review, decisions, returnFocus, stale }
790
+ let approvalDialogState = null; // { projectId, review, decisions, returnFocus, stale, phase }
682
791
  let exportSourcesState = { status: 'unavailable', data: null, selected: null, open: false };
683
792
 
684
793
  /**
@@ -962,6 +1071,7 @@
962
1071
  const ws = mode === 'workspaces';
963
1072
  $app.classList.toggle('mode-workspaces', ws);
964
1073
  document.body.classList.toggle('mode-workspaces', ws);
1074
+ document.documentElement.classList.remove('mode-workspaces-boot');
965
1075
  // The provenance strip is workflow-level data. Workspaces replaces that surface (including its
966
1076
  // landing), so cancel any late workflow-pin paint before the project UI starts loading.
967
1077
  if (ws && bridge.clearKbInformed) bridge.clearKbInformed();
@@ -997,6 +1107,11 @@
997
1107
  // workflow beacon; in a Workspaces project it points at that project's lifecycle.
998
1108
  if (!ws || !current) { if (bridge.clearWorkspaceGuide) bridge.clearWorkspaceGuide(); }
999
1109
  else syncWorkspaceGuide();
1110
+ if (window.flolessLeftPane) {
1111
+ // Any Model step may offer the left Model section; it appears only once that editor sends a snapshot.
1112
+ const modelPanelVisible = ws && !!current && currentStep === 'model';
1113
+ window.flolessLeftPane.setWorkspaceModelVisible(modelPanelVisible);
1114
+ }
1000
1115
  syncWorkspaceReporter();
1001
1116
  }
1002
1117
  let modeChangeSequence = 0;
@@ -1033,7 +1148,7 @@
1033
1148
  await bridge.refreshCurrentWorkflow();
1034
1149
  } catch (error) {
1035
1150
  if (sequence === modeChangeSequence) {
1036
- showToast('Couldn’t refresh the workflow: ' + (error && error.message ? error.message : String(error)), 'warn');
1151
+ showToast('We couldn’t refresh this workflow because FloLess could not reach it. Try again.', 'warn');
1037
1152
  }
1038
1153
  return;
1039
1154
  } finally {
@@ -1069,15 +1184,8 @@
1069
1184
  });
1070
1185
 
1071
1186
  // ── landing ─────────────────────────────────────────────────────────────────
1072
- const relAgo = (iso) => {
1073
- const ms = Date.now() - new Date(iso).getTime();
1074
- if (isNaN(ms) || ms < 0) return '';
1075
- const min = Math.round(ms / 60000);
1076
- if (min < 1) return 'just now';
1077
- if (min < 60) return `${min} min ago`;
1078
- const h = Math.round(min / 60);
1079
- return h < 48 ? `${h} h ago` : `${Math.round(h / 24)} d ago`;
1080
- };
1187
+ // `relAgo` is app.js's, like `escapeHtml` and `escapeAttr` this file already reuses — the copy
1188
+ // that used to live here and panels.js's were the same ladder, spelled twice.
1081
1189
 
1082
1190
  // Monotonic id per load. applyMode() fires loadProjects() fire-and-forget and re-runs on any mode
1083
1191
  // set (even a no-op one), and several actions trail a refresh, so two loads can overlap. Without
@@ -1106,7 +1214,7 @@
1106
1214
  // identical from `projects` alone). Cleared on the next success, so a recovered load drops
1107
1215
  // straight back to the normal empty state.
1108
1216
  projectsLoadError = (err && err.message) || String(err);
1109
- if (!(opts && opts.quiet)) showToast('Couldn’t load projects: ' + projectsLoadError, 'warn');
1217
+ if (!(opts && opts.quiet)) showToast('Couldn’t load projects. Check the Workspace directory and try again.', 'warn');
1110
1218
  }
1111
1219
  // Paint the moment the LIST is in hand — before the archived call, not after it. That call is a
1112
1220
  // secondary concern (a collapsed Trash disclosure) but it was measured at 0.31-0.83 s normally
@@ -1141,12 +1249,12 @@
1141
1249
  // Keep descriptor order for a stable card order. A load failure RE-WIDENS the entries to the
1142
1250
  // descriptor keys (the catch assigns them): still usable, and a card for something uninstalled is
1143
1251
  // refused by the server on click.
1144
- const cardsSig = (entries) => entries.map((e) => `${e.appId}>${e.templateId}${e.ambiguous ? '?' : ''}`).join(',');
1252
+ const cardsSig = (entries) => entries.map((e) => `${e.appId}>${e.templateId}${e.ambiguous ? '?' : ''}:${e.capabilityStatus || ''}`).join(',');
1145
1253
  const cardsBefore = cardsSig(wsAppEntries);
1146
1254
  try {
1147
- const { apps } = await api('/api/apps');
1255
+ const { apps, workspaceCapabilities } = await api('/api/apps');
1148
1256
  if (stale()) return;
1149
- wsAppEntries = installedWorkspaceAppEntries(apps);
1257
+ wsAppEntries = installedWorkspaceAppEntries(apps, workspaceCapabilities);
1150
1258
  // Hardening: /api/apps loaded but reported NONE of our known installed workspace apps (a
1151
1259
  // transient empty/read blip). Rather than render zero create cards, fall back to the descriptor
1152
1260
  // keys — the same usable default a full /api/apps failure lands on.
@@ -1232,17 +1340,19 @@
1232
1340
  clearTimeout(appsChangedTimer);
1233
1341
  appsChangedTimer = setTimeout(appsChangedRefresh, 250);
1234
1342
  });
1343
+ window.addEventListener('floless:revit-capability-changed', () => {
1344
+ if (mode !== 'workspaces' || current) return;
1345
+ clearTimeout(appsChangedTimer);
1346
+ appsChangedTimer = setTimeout(appsChangedRefresh, 250);
1347
+ });
1235
1348
 
1236
1349
  // The same reconciliation for the OPEN project. The listener above keeps the LANDING honest; a
1237
1350
  // project open in THIS tab was never reconciled at all when another tab (or the terminal AI)
1238
1351
  // renamed or archived it — `current` is assigned only in openProject and cleared only in
1239
1352
  // closeProject, and no cross-tab path reached either. So every surface derived from it went stale
1240
- // together: the breadcrumb, the header name, the header project picker (its rows come from
1241
- // `projects` and mark the open one by id) — and the step frames, which is the part that actually
1242
- // breaks. They carry `?project=<id>`, a rename mints a NEW id, and the next contract read or
1243
- // autosave from this tab then 404s. Relabelling would leave exactly that defect in place, so the
1244
- // answer is to re-open (openProject re-points both frames — blanking them now, re-srcing each on
1245
- // first show) or to close.
1353
+ // together: the breadcrumb, the header name, the project picker and the Instructor scope. Project
1354
+ // ids and selected working directories now stay fixed across display-name changes, so the open
1355
+ // frames remain valid; reconciliation adopts fresh metadata in place. Archiving still closes it.
1246
1356
  //
1247
1357
  // The toasts below say "elsewhere" and mean it: a project action is LANDING-ONLY (`openProjMenu`
1248
1358
  // is wired to the landing grid alone, and the landing is hidden whenever `current` is set), so a
@@ -1250,11 +1360,9 @@
1250
1360
  // origin and this listener has no self-echo suppression, so surfacing rename/archive from the
1251
1361
  // open-project chrome — which `openProjMenu`'s own comment contemplates — would break that, and
1252
1362
  // the copy with it. Named here so it is a dependency, not a coincidence. (Found by review.)
1253
- // WHICH PROJECT THIS IS, across a rename: `uuid`. A rename mints a new id (the folder moves) but
1254
- // PRESERVES the record's uuid, and archive preserves it too — while duplicate and import mint a
1255
- // fresh one, so a copy can never be mistaken for the original. That makes the live list
1256
- // self-describing: the row still carrying our uuid IS this project under whatever name and id it
1257
- // now has, and its absence means the project was retired.
1363
+ // WHICH PROJECT THIS IS: `uuid`. Duplicate and import mint a fresh one, so a copy can never be
1364
+ // mistaken for the original. Stable ids make rename simple, while uuid still distinguishes copies
1365
+ // and makes the live list self-describing when external or legacy state is encountered.
1258
1366
  //
1259
1367
  // THIS REPLACED AN EVENT-MAPPING MACHINE, and the deletion is the point. An earlier cut rebuilt the
1260
1368
  // old→new id link from the rename event, on the reasoning that "nothing in the live list records
@@ -1353,6 +1461,12 @@
1353
1461
  reconcileNow();
1354
1462
  });
1355
1463
 
1464
+ // app.js owns the app-wide root selector; repaint only the neutral landing when its remembered
1465
+ // availability/path changes. An open project is reconciled through projects-changed instead.
1466
+ window.addEventListener('floless:workspace-root-state', () => {
1467
+ if (mode === 'workspaces' && !current) renderLanding();
1468
+ });
1469
+
1356
1470
  /**
1357
1471
  * The one way to start a reconcile. NOTHING INSIDE it catches, and `openProject`/`closeProject` are
1358
1472
  * not throw-free (renderStepTabs maps over the descriptor's steps; the teardown chain is a dozen
@@ -1457,6 +1571,14 @@
1457
1571
  // `!==` test true on every `projects-changed`, discarding the server's `exportUnits` and
1458
1572
  // repainting for nothing. (Review round 5.)
1459
1573
  const freshUnits = mine.displayUnits === 'mm' ? 'mm' : 'ft-in';
1574
+ const freshName = typeof mine.name === 'string' ? mine.name : current.name;
1575
+ if (current && current.id === id && current.name !== freshName) {
1576
+ current.name = freshName;
1577
+ $projName.textContent = freshName;
1578
+ buildProjList();
1579
+ applyMode();
1580
+ showToast(`This project was renamed to “${freshName}” elsewhere.`, 'warn');
1581
+ }
1460
1582
  if (current && current.id === id && current.displayUnits !== freshUnits) {
1461
1583
  current.displayUnits = freshUnits;
1462
1584
  // The cached row too, for the reason the listener above spells out: `projects` is only
@@ -1630,17 +1752,56 @@
1630
1752
  }
1631
1753
 
1632
1754
  function workspaceCreateCardHtml(entry, action) {
1633
- const isDrawing = action.kind === 'drawing';
1755
+ if (entry.templateId === 'revit-model' && entry.capabilityStatus && entry.capabilityStatus !== 'ready') {
1756
+ const states = {
1757
+ 'access-required': {
1758
+ status: 'Access required',
1759
+ body: 'Revit model access is not included for this account.',
1760
+ action: 'View access',
1761
+ aria: 'Revit model access required — view access',
1762
+ },
1763
+ 'account-selection-required': {
1764
+ status: 'Choose an account',
1765
+ body: 'Choose which FloLess account you want to use for Revit model access.',
1766
+ action: 'Choose account',
1767
+ aria: 'Choose a FloLess account for Revit model access',
1768
+ },
1769
+ 'setup-unavailable': {
1770
+ status: 'Needs setup',
1771
+ body: 'Revit projects can’t be opened until xeoRVT setup finishes.',
1772
+ action: 'View setup',
1773
+ aria: 'Revit model needs setup — view setup',
1774
+ },
1775
+ 'check-unavailable': {
1776
+ status: 'Couldn’t check access',
1777
+ body: 'FloLess couldn’t check Revit model access. Your existing projects were not changed.',
1778
+ action: 'Try again',
1779
+ aria: 'Revit model access check unavailable — try again',
1780
+ },
1781
+ };
1782
+ const state = states[entry.capabilityStatus] || states['check-unavailable'];
1783
+ const descriptionId = `ws-revit-${entry.capabilityStatus || 'check-unavailable'}`;
1784
+ return `<button type="button" class="ws-seed ws-seed-remedy" ` +
1785
+ `aria-label="${escapeAttr(state.aria)}" aria-describedby="${escapeAttr(descriptionId)}" ` +
1786
+ `data-revit-remedy="${escapeAttr(entry.capabilityStatus || 'check-unavailable')}">` +
1787
+ `<span class="plus" aria-hidden="true">R</span>` +
1788
+ `<span class="ws-seed-headline">Revit model</span>` +
1789
+ `<span class="ws-seed-capability ws-seed-state">${escapeHtml(state.status)}</span>` +
1790
+ `<span class="ws-seed-sub" id="${escapeAttr(descriptionId)}">${escapeHtml(state.body)}</span>` +
1791
+ `<span class="ws-seed-action">${escapeHtml(state.action)} →</span>` +
1792
+ `</button>`;
1793
+ }
1794
+ const acceptsDrop = action.kind === 'drawing' || action.kind === 'rvt';
1634
1795
  // Name the target workflow ONLY when the root has more than one live app behind it, so the
1635
1796
  // ordinary card stays clean and the extra line means something wherever it does appear. It
1636
1797
  // must also go on the aria-label: the button's own aria-label REPLACES the accessible name
1637
1798
  // computed from its children, so a descendant span alone is silent to a screen reader.
1638
1799
  const target = entry.ambiguous ? entry.appId : '';
1639
- return `<button type="button" class="ws-seed${isDrawing ? ' ws-seed-drop' : ''}" ` +
1800
+ return `<button type="button" class="ws-seed${acceptsDrop ? ' ws-seed-drop' : ''}" ` +
1640
1801
  `aria-label="${escapeAttr((action.label || action.headline) + (target ? ` (on the ${target} workflow)` : ''))}" ` +
1641
1802
  (action.tip ? `data-tip="${escapeAttr(action.tip)}" ` : '') +
1642
1803
  `data-seed-app="${escapeAttr(entry.appId)}" data-seed-template="${escapeAttr(entry.templateId)}" data-seed-action="${escapeAttr(action.kind)}"` +
1643
- (isDrawing ? ` data-seed-drop="${escapeAttr(entry.appId)}"` : '') +
1804
+ (acceptsDrop ? ` data-seed-drop="${escapeAttr(entry.appId)}" data-seed-drop-kind="${escapeAttr(action.kind)}"` : '') +
1644
1805
  `>` +
1645
1806
  `<span class="plus">+</span>` +
1646
1807
  `<span class="ws-seed-headline">${escapeHtml(action.headline)}</span>` +
@@ -1715,9 +1876,20 @@
1715
1876
  }
1716
1877
 
1717
1878
  function renderLanding() {
1879
+ const rootState = window.flolessWorkspaceRoot && window.flolessWorkspaceRoot.current();
1880
+ const rootPath = rootState && rootState.root && rootState.root.path;
1881
+ const rootUnavailable = !!rootState && rootState.available === false;
1882
+ const folderName = window.flolessWorkspaceRoot ? window.flolessWorkspaceRoot.name() : 'Workspace directory';
1718
1883
  let html = `<div class="ws-head"><div class="ws-head-text"><h2>Workspaces</h2>` +
1719
- `<div class="ws-sub">Live projects — open a document to keep working. No Run here.</div></div>` +
1720
- `<button type="button" class="ws-import-btn" id="ws-import-project" data-command-id="shell.project-import" data-tip="Restore a project from an exported .zip file">↓ Import project…</button></div>`;
1884
+ `<div class="ws-sub">${rootUnavailable ? 'Workspace directory unavailable. Choose another folder to continue.' : 'Open a project to view its drawings, model, Knowledge and history.'}</div></div>` +
1885
+ `<div class="ws-head-actions"><button type="button" class="ws-import-btn ws-folder-btn${rootUnavailable ? ' is-unavailable' : ''}" id="ws-workspace-folder" data-command-id="menu.workspace-folder" data-tip="${escapeAttr(rootPath || 'Choose the Workspace directory FloLess reads for projects and workflows')}">Workspace directory · ${escapeHtml(rootUnavailable ? 'unavailable' : folderName)}</button>` +
1886
+ `${rootUnavailable ? '' : '<button type="button" class="ws-import-btn" id="ws-import-project" data-command-id="shell.project-import" data-tip="Restore a project from an exported .zip file">↓ Import project…</button>'}</div></div>`;
1887
+ if (rootUnavailable) {
1888
+ html += `<div class="ws-empty-note ws-root-unavailable" role="status" aria-live="polite"><b>Workspace directory unavailable.</b> ` +
1889
+ `Choose another folder to continue. ` +
1890
+ `<span class="ws-root-unavailable-path">${escapeHtml(rootPath || '')}</span></div>`;
1891
+ }
1892
+ if (!rootUnavailable) {
1721
1893
  const createEntries = workspaceCreateEntries(wsAppEntries);
1722
1894
  if (createEntries.length) {
1723
1895
  html += `<div class="ws-create-grid">`;
@@ -1766,8 +1938,7 @@
1766
1938
  const guess = projectsErrorHint(projectsLoadError);
1767
1939
  html += `<div class="ws-empty-note ws-load-error" role="status" aria-live="polite">`
1768
1940
  + `<b>Couldn’t load your projects.</b> `
1769
- + (guess ? `${escapeHtml(guess)} ` : '')
1770
- + `<span class="ws-load-error-detail">${escapeHtml(projectsLoadError)}</span>`
1941
+ + (guess ? `${escapeHtml(guess)} ` : 'FloLess could not read the Workspace directory. ')
1771
1942
  + ` <button type="button" id="ws-retry-projects">↻ Try again</button></div>`;
1772
1943
  } else {
1773
1944
  // First-run onboarding (#598). Workflows mode greets a newcomer with a real card and a route
@@ -1823,6 +1994,7 @@
1823
1994
  `<div class="ws-archived-list">${rows}</div>` +
1824
1995
  `</details>`;
1825
1996
  }
1997
+ }
1826
1998
  // Carry the user's place across the rebuild below, which replaces the landing wholesale: that
1827
1999
  // drops focus to <body>, collapses the Archived disclosure, and can leave a scrolled grid showing
1828
2000
  // a different slice. Every caller used to be a click or keypress in this tab, so the user's
@@ -1889,7 +2061,7 @@
1889
2061
  // element is ACTED on by, never by DOM position: a rebuild reorders the grid (a rename re-fronts its
1890
2062
  // card), so an index would hand focus to a different project — worse than losing it. Returns null
1891
2063
  // for anything unrecognised or outside the landing, which simply means "don't restore".
1892
- const FOCUS_KEY_ATTRS = ['data-open', 'data-kebab', 'data-thumb', 'data-restore', 'data-delete-archived'];
2064
+ const FOCUS_KEY_ATTRS = ['data-open', 'data-kebab', 'data-thumb', 'data-restore', 'data-delete-archived', 'data-revit-remedy'];
1893
2065
  function landingFocusKey(el) {
1894
2066
  if (!el || !$landing.contains(el)) return null;
1895
2067
  if (el.id) return `#${el.id}`; // #ws-import-project / #ws-retry-projects
@@ -1920,7 +2092,19 @@
1920
2092
  const del = e.target.closest('[data-delete-archived]');
1921
2093
  if (del) { e.stopPropagation(); deleteArchivedProject(del.dataset.deleteArchived); return; }
1922
2094
  if (e.target.closest('#ws-retry-projects')) { e.stopPropagation(); retryProjects(); return; }
2095
+ if (e.target.closest('#ws-workspace-folder')) {
2096
+ e.stopPropagation();
2097
+ if (window.flolessWorkspaceRoot) window.flolessWorkspaceRoot.open();
2098
+ return;
2099
+ }
1923
2100
  if (e.target.closest('#ws-import-project')) { importProject(); return; }
2101
+ const revitRemedy = e.target.closest('[data-revit-remedy]');
2102
+ if (revitRemedy) {
2103
+ window.dispatchEvent(new CustomEvent('floless:open-revit-access', {
2104
+ detail: { state: revitRemedy.dataset.revitRemedy },
2105
+ }));
2106
+ return;
2107
+ }
1924
2108
  const card = e.target.closest('[data-open]');
1925
2109
  if (card) { openProject(card.dataset.open); return; }
1926
2110
  const seed = e.target.closest('[data-seed-app]');
@@ -1937,6 +2121,9 @@
1937
2121
  if (seed.dataset.seedAction === 'drawing') {
1938
2122
  const files = await pickDrawingFiles($seedFile); // drop-a-drawing: open the picker
1939
2123
  if (files.length) createFromDrawing(appId, templateId, files);
2124
+ } else if (seed.dataset.seedAction === 'rvt') {
2125
+ const file = await pickRvtFile($seedRvt);
2126
+ if (file) createFromRvt(appId, templateId, file);
1940
2127
  } else {
1941
2128
  // Unreachable today, and it must not be SILENT the day it isn't: an unhandled kind still
1942
2129
  // renders a full dashed, focusable card, so without this the first person to add one gets a
@@ -1968,6 +2155,58 @@
1968
2155
  const $seedFile = document.createElement('input');
1969
2156
  $seedFile.type = 'file'; $seedFile.accept = '.pdf,image/*'; $seedFile.multiple = true; $seedFile.hidden = true;
1970
2157
  document.body.appendChild($seedFile);
2158
+ const $seedRvt = document.createElement('input');
2159
+ $seedRvt.type = 'file'; $seedRvt.accept = '.rvt,application/x-rvt'; $seedRvt.hidden = true;
2160
+ document.body.appendChild($seedRvt);
2161
+ $revitReplace?.addEventListener('click', async () => {
2162
+ const project = current;
2163
+ if (!project) return;
2164
+ const file = await pickRvtFile($seedRvt);
2165
+ if (!file || !current || current.id !== project.id) return;
2166
+ try {
2167
+ const state = await refreshRevitSourceState(project.id);
2168
+ if (!state?.canReplace) throw new Error('Revit replacement access is unavailable.');
2169
+ const operation = await uploadRvtForProject(project, file, state.generation);
2170
+ pollRevitImport(operation.operationId, project.id);
2171
+ } catch (error) {
2172
+ paintRevitSourceState('Couldn’t replace the RVT', `${error && error.message || error} The existing model was not changed.`);
2173
+ paintRevitSourceActions('failed', revitSourceState?.canReplace === true, revitActiveOperation?.failure?.retryable !== false);
2174
+ }
2175
+ });
2176
+ $revitRetry?.addEventListener('click', async () => {
2177
+ const project = current;
2178
+ const failedOperationId = revitActiveOperation?.operationId;
2179
+ if (!project || !failedOperationId) return;
2180
+ try {
2181
+ const started = await api(`/api/model-imports/${encodeURIComponent(failedOperationId)}/retry`, { method: 'POST', body: '{}' });
2182
+ revitActiveOperation = started.operation;
2183
+ paintRevitSourceState('Replacing source RVT…', 'Reading the already stored RVT again…');
2184
+ paintRevitSourceActions('active', true);
2185
+ pollRevitImport(started.operation.operationId, project.id);
2186
+ } catch (error) {
2187
+ paintRevitSourceState('Couldn’t retry the RVT', `${error && error.message || error} The existing model was not changed.`);
2188
+ paintRevitSourceActions('failed', revitSourceState?.canReplace === true, revitActiveOperation?.failure?.retryable !== false);
2189
+ }
2190
+ });
2191
+ $revitCancel?.addEventListener('click', async () => {
2192
+ const projectId = current?.id;
2193
+ const operationId = revitActiveOperation?.operationId;
2194
+ if (!projectId || !operationId) return;
2195
+ try {
2196
+ await api(`/api/model-imports/${encodeURIComponent(operationId)}/cancel`, { method: 'POST', body: '{}' });
2197
+ revitActiveOperation = null;
2198
+ paintRevitSourceState('Replacement cancelled', 'The existing model was not changed.');
2199
+ paintRevitSourceActions('ready', true);
2200
+ $revitReplace?.focus();
2201
+ } catch (error) {
2202
+ const status = error && error.status;
2203
+ showToast(status === 403
2204
+ ? 'We couldn’t cancel this import because Revit access is not available for this account. Check your account access, then try again.'
2205
+ : status === 409
2206
+ ? 'We couldn’t cancel this import because it is already finishing. Refresh the project to see the result.'
2207
+ : 'We couldn’t cancel this import because FloLess could not save the request. Try again.', 'warn');
2208
+ }
2209
+ });
1971
2210
  // Fallback picker for Import project (used when the File System Access API is absent). Outside
1972
2211
  // $landing so an innerHTML re-render can't wipe it — same as $seedFile.
1973
2212
  const $importZip = document.createElement('input');
@@ -1994,7 +2233,10 @@
1994
2233
  zone.classList.remove('drag-over');
1995
2234
  const files = Array.from((e.dataTransfer && e.dataTransfer.files) || []);
1996
2235
  // Same two ids as the click path — the dropzone IS the seed button, so it carries both.
1997
- if (files.length) createFromDrawing(zone.dataset.seedDrop, zone.dataset.seedTemplate || zone.dataset.seedDrop, files);
2236
+ if (zone.dataset.seedDropKind === 'rvt') {
2237
+ if (files.length === 1 && /\.rvt$/i.test(files[0].name)) createFromRvt(zone.dataset.seedDrop, zone.dataset.seedTemplate || zone.dataset.seedDrop, files[0]);
2238
+ else showToast('Choose one Revit .rvt file.', 'warn');
2239
+ } else if (files.length) createFromDrawing(zone.dataset.seedDrop, zone.dataset.seedTemplate || zone.dataset.seedDrop, files);
1998
2240
  });
1999
2241
 
2000
2242
  async function promptName(title, label, value) {
@@ -2035,140 +2277,535 @@
2035
2277
  return standardLabelsPromise;
2036
2278
  }
2037
2279
 
2280
+ // Project-only setup does not publish attachment bytes yet, so probing one byte is enough to
2281
+ // catch a revoked/unreadable browser handle without loading up to 20 complete drawings into RAM.
2282
+ const assertProjectSourceReadable = (file) => file.slice(0, Math.min(file.size, 1)).arrayBuffer();
2283
+
2284
+ const $projectSetup = document.getElementById('project-setup-modal');
2285
+ const $projectSetupDialog = $projectSetup && $projectSetup.querySelector('.project-setup-dialog');
2286
+ const $projectSetupTitle = document.getElementById('project-setup-title');
2287
+ const $projectSetupSourceName = document.getElementById('project-setup-source-name');
2288
+ const $projectSetupSourceCount = document.getElementById('project-setup-source-count');
2289
+ const $projectSetupFolder = document.getElementById('project-setup-folder');
2290
+ const $projectSetupFolderNote = document.getElementById('project-setup-folder-note');
2291
+ const $projectSetupFolderChoose = document.getElementById('project-setup-folder-choose');
2292
+ const $projectSetupName = document.getElementById('project-setup-name');
2293
+ const $projectSetupStandard = document.getElementById('project-setup-standard');
2294
+ const $projectSetupError = document.getElementById('project-setup-error');
2295
+ const $projectSetupChatMeta = document.getElementById('project-setup-chat-meta');
2296
+ const $projectSetupCancel = document.getElementById('project-setup-cancel');
2297
+ const $projectSetupCreateOnly = document.getElementById('project-setup-create-only');
2298
+ const $projectSetupCreate = document.getElementById('project-setup-create');
2299
+ const PROJECT_CHAT_INTAKE_KEY = 'floless.pending-project-chat-intake';
2300
+ let projectSetupState = null;
2301
+ let projectChatIntakeRecoveryStarted = false;
2302
+ function pendingProjectChatIntakes() {
2303
+ try {
2304
+ const value = JSON.parse(localStorage.getItem(PROJECT_CHAT_INTAKE_KEY) || '[]');
2305
+ return Array.isArray(value) ? value.filter((id) => typeof id === 'string') : [];
2306
+ } catch { return []; }
2307
+ }
2308
+ function rememberProjectChatIntake(id) {
2309
+ localStorage.setItem(PROJECT_CHAT_INTAKE_KEY, JSON.stringify([...new Set([...pendingProjectChatIntakes(), id])]));
2310
+ }
2311
+ function forgetProjectChatIntake(id) {
2312
+ const remaining = pendingProjectChatIntakes().filter((value) => value !== id);
2313
+ if (remaining.length) localStorage.setItem(PROJECT_CHAT_INTAKE_KEY, JSON.stringify(remaining));
2314
+ else localStorage.removeItem(PROJECT_CHAT_INTAKE_KEY);
2315
+ }
2316
+
2317
+ function setProjectSetupError(message, { workspaceAction = false } = {}) {
2318
+ $projectSetupError.hidden = !message;
2319
+ $projectSetupError.textContent = message || '';
2320
+ if (message && workspaceAction) {
2321
+ const action = document.createElement('button');
2322
+ action.type = 'button';
2323
+ action.className = 'project-setup-error-action';
2324
+ action.textContent = 'Change Workspace directory';
2325
+ action.addEventListener('click', () => {
2326
+ closeProjectSetup();
2327
+ window.flolessWorkspaceRoot?.open?.();
2328
+ });
2329
+ $projectSetupError.append(' ', action);
2330
+ }
2331
+ }
2332
+
2333
+ function projectSetupErrorMessage(error) {
2334
+ const raw = String(error && error.body?.error || error && error.message || error || '');
2335
+ const code = String(error && (error.code || error.body?.code) || '');
2336
+ if (code === 'chat-provider-unavailable' || /sign in|provider .* unavailable|chat providers are not configured/i.test(raw)) {
2337
+ return 'Sign in to Claude or Codex before starting this project in AI Chat. You can still create the project only.';
2338
+ }
2339
+ if (/workspace root|working directory changed|stale.*folder/i.test(raw)) {
2340
+ return 'The Workspace directory changed while this dialog was open. Choose the project folder again.';
2341
+ }
2342
+ if (/request chat|chat intake|chat session|ownership|generation|identity|binding|reconciliation|internal/i.test(raw)) {
2343
+ return 'FloLess could not start the project conversation. Check your AI sign-in and try again.';
2344
+ }
2345
+ // A server error that is not one of the known, user-safe messages is still an
2346
+ // implementation detail. Keep it out of the dialog and give the person a
2347
+ // clear recovery step instead.
2348
+ if (!raw || /[:{}()[\]\\/]|\b(?:error|failed|invalid|unknown|request|route|http|status|code|stack|errno|e[A-Z]+)\b/i.test(raw)) {
2349
+ return 'FloLess could not create this project. Check the folder and try again.';
2350
+ }
2351
+ return 'FloLess could not create this project. Check the folder and try again.';
2352
+ }
2353
+
2354
+ function projectSetupReady(state = projectSetupState) {
2355
+ return !!state && state.sourceReady && !!state.directory && !!state.name.trim()
2356
+ && (!state.askCatalogue || state.environment === 'US' || state.environment === 'UK');
2357
+ }
2358
+
2359
+ function setProjectSetupBusy(busy, label) {
2360
+ if (!projectSetupState) return;
2361
+ projectSetupState.busy = !!busy;
2362
+ $projectSetup.setAttribute('aria-busy', String(!!busy));
2363
+ for (const control of $projectSetup.querySelectorAll('button, input')) control.disabled = !!busy;
2364
+ $projectSetupCreate.textContent = label || 'Create project & start chat';
2365
+ $projectSetupCreateOnly.textContent = busy ? 'Creating…' : (projectSetupState.kind === 'rvt' ? 'Create project' : 'Create project only');
2366
+ if (!busy) {
2367
+ $projectSetupCreate.disabled = !projectSetupReady();
2368
+ $projectSetupCreateOnly.disabled = !projectSetupReady();
2369
+ }
2370
+ }
2371
+
2372
+ function renderProjectSetup() {
2373
+ const state = projectSetupState;
2374
+ if (!state) return;
2375
+ const provider = state.kind === 'rvt' ? null : (bridge.preferredChatProvider?.() || null);
2376
+ if ($projectSetupChatMeta) {
2377
+ $projectSetupChatMeta.hidden = !provider;
2378
+ $projectSetupChatMeta.textContent = provider
2379
+ ? `Starts with ${provider === 'claude' ? 'Claude Code' : provider === 'codex' ? 'Codex' : provider} · can edit this project folder`
2380
+ : '';
2381
+ }
2382
+ $projectSetupCreate.hidden = !provider;
2383
+ $projectSetupCreateOnly.classList.toggle('primary', !provider);
2384
+ $projectSetupTitle.textContent = `New ${descDisplayName(state.templateId)} project`;
2385
+ $projectSetupSourceName.textContent = state.files[0]?.name || (state.kind === 'rvt' ? 'Revit model' : 'Drawing set');
2386
+ $projectSetupCreateOnly.textContent = state.busy ? 'Creating…' : (state.kind === 'rvt' ? 'Create project' : 'Create project only');
2387
+ $projectSetupSourceCount.textContent = state.files.length > 1 ? `+ ${state.files.length - 1} more` : '';
2388
+ $projectSetupFolder.textContent = state.directory
2389
+ ? state.directory.path
2390
+ : 'Choose a project folder inside the Workspace directory';
2391
+ $projectSetupFolder.classList.toggle('has-folder', !!state.directory);
2392
+ if (state.directory) $projectSetupFolder.setAttribute('data-tip', state.directory.path);
2393
+ else $projectSetupFolder.removeAttribute('data-tip');
2394
+ $projectSetupFolderNote.textContent = state.directory
2395
+ ? (state.directory.existingItems
2396
+ ? `Contains ${state.directory.existingItems} existing item${state.directory.existingItems === 1 ? '' : 's'} · they will be kept`
2397
+ : 'Empty folder · ready for this project')
2398
+ : 'FloLess stores this project here, and AI starts in this folder.';
2399
+ if ($projectSetupName.value !== state.name) $projectSetupName.value = state.name;
2400
+ $projectSetupStandard.hidden = !state.askCatalogue;
2401
+ $projectSetupStandard.querySelectorAll('[data-environment]').forEach((button) => {
2402
+ button.setAttribute('aria-pressed', String(button.dataset.environment === state.environment));
2403
+ });
2404
+ $projectSetupCreate.disabled = !provider || state.busy || !projectSetupReady(state);
2405
+ $projectSetupCreateOnly.disabled = state.busy || !projectSetupReady(state);
2406
+ $projectSetupCancel.textContent = state.project ? 'Close' : 'Cancel';
2407
+ }
2408
+
2409
+ function closeProjectSetup({ restoreFocus = true } = {}) {
2410
+ const state = projectSetupState;
2411
+ if (!state || state.busy) return;
2412
+ projectSetupState = null;
2413
+ $projectSetup.classList.remove('show');
2414
+ $projectSetup.removeAttribute('aria-busy');
2415
+ setProjectSetupError('');
2416
+ if (restoreFocus && state.returnFocus && state.returnFocus.isConnected) state.returnFocus.focus();
2417
+ }
2418
+
2419
+ async function chooseProjectSetupFolder() {
2420
+ const state = projectSetupState;
2421
+ if (!state || state.busy) return;
2422
+ setProjectSetupError('');
2423
+ setProjectSetupBusy(true, 'Create project');
2424
+ $projectSetupFolderChoose.textContent = 'Choosing…';
2425
+ try {
2426
+ const choice = await api('/api/project-directories/choose', { method: 'POST', body: '{}' });
2427
+ if (!projectSetupState || projectSetupState !== state || choice.cancelled) return;
2428
+ state.directory = {
2429
+ selectionId: choice.selectionId,
2430
+ path: choice.path,
2431
+ locator: choice.locator,
2432
+ existingItems: Number(choice.existingItems) || 0,
2433
+ rootId: choice.rootId,
2434
+ generation: choice.generation,
2435
+ };
2436
+ if (!state.nameDirty) state.name = choice.locator;
2437
+ } catch (error) {
2438
+ if (projectSetupState === state) {
2439
+ const code = error && (error.code || error.body && error.body.code);
2440
+ setProjectSetupError(projectSetupErrorMessage(error), {
2441
+ workspaceAction: code === 'project-directory-outside-root',
2442
+ });
2443
+ }
2444
+ } finally {
2445
+ if (projectSetupState === state) {
2446
+ setProjectSetupBusy(false);
2447
+ $projectSetupFolderChoose.textContent = state.directory ? 'Change…' : 'Choose…';
2448
+ renderProjectSetup();
2449
+ }
2450
+ }
2451
+ }
2452
+
2453
+ async function createProjectFromSetup(startChat = true) {
2454
+ const state = projectSetupState;
2455
+ if (!projectSetupReady(state) || state.busy) return;
2456
+ if (startChat && !bridge.preferredChatProvider?.()) {
2457
+ setProjectSetupError('Sign in to Claude or Codex before starting this project in AI Chat. You can still create the project only.');
2458
+ return;
2459
+ }
2460
+ setProjectSetupError('');
2461
+ setProjectSetupBusy(true, startChat ? 'Preparing chat…' : 'Creating…');
2462
+ try {
2463
+ if (!startChat) {
2464
+ const payload = {
2465
+ name: state.name.trim(),
2466
+ app: state.appId,
2467
+ ...(state.askCatalogue ? { environment: state.environment } : {}),
2468
+ directorySelectionId: state.directory.selectionId,
2469
+ ...(state.kind === 'rvt' ? {} : { initialTask: { kind: 'drawing-intake', sourceNames: state.files.map((file) => file.name) } }),
2470
+ };
2471
+ const { project } = await api('/api/projects', { method: 'POST', body: JSON.stringify(payload) });
2472
+ if (state.kind === 'rvt') {
2473
+ setProjectSetupBusy(false);
2474
+ closeProjectSetup({ restoreFocus: false });
2475
+ await importRvtIntoProject(project, state.files[0], state.appId);
2476
+ return;
2477
+ }
2478
+ projects.unshift(project);
2479
+ track('workspace_project_created', { app: state.appId });
2480
+ setProjectSetupBusy(false);
2481
+ closeProjectSetup({ restoreFocus: false });
2482
+ await openProject(project.id, 'drawings');
2483
+ showToast('Project created. Attach the drawings on the Drawings step when you’re ready to read them.', 'ok');
2484
+ return;
2485
+ }
2486
+ let snapshots = state.snapshots || null;
2487
+ if (!snapshots) snapshots = await Promise.all(state.files.map(readFileAsSnapshot));
2488
+ state.snapshots = snapshots;
2489
+ const submissionId = state.submissionId || crypto.randomUUID();
2490
+ state.submissionId = submissionId;
2491
+ rememberProjectChatIntake(submissionId);
2492
+ const result = await bridge.startProjectChatIntake(submissionId, {
2493
+ name: state.name.trim(),
2494
+ app: state.appId,
2495
+ ...(state.askCatalogue ? { environment: state.environment } : {}),
2496
+ directorySelectionId: state.directory.selectionId,
2497
+ snapshots,
2498
+ provider: bridge.preferredChatProvider(),
2499
+ });
2500
+ const project = result.project;
2501
+ state.project = project;
2502
+ state.request = result.request;
2503
+ if (!projects.some((item) => item.id === project.id)) {
2504
+ projects.unshift(project);
2505
+ track('workspace_project_created', { app: state.appId });
2506
+ }
2507
+ if (!state.opened) {
2508
+ await openProject(project.id, 'drawings');
2509
+ state.opened = true;
2510
+ }
2511
+ await bridge.openChatConversation(result.chat.chatId);
2512
+ forgetProjectChatIntake(submissionId);
2513
+ } catch (error) {
2514
+ if (projectSetupState !== state) return;
2515
+ const code = error && (error.code || error.body && error.body.code);
2516
+ if (code && code.startsWith('project-directory-')) {
2517
+ state.directory = null;
2518
+ $projectSetupFolderChoose.textContent = 'Choose…';
2519
+ }
2520
+ const outsideWorkspace = code === 'project-directory-outside-root';
2521
+ setProjectSetupError(projectSetupErrorMessage(error), { workspaceAction: outsideWorkspace });
2522
+ setProjectSetupBusy(false);
2523
+ renderProjectSetup();
2524
+ return;
2525
+ }
2526
+ setProjectSetupBusy(false);
2527
+ closeProjectSetup({ restoreFocus: false });
2528
+ showToast('Project created — the drawing task is running in AI Chat.', 'ok');
2529
+ }
2530
+
2531
+ async function resumeInterruptedProjectChatIntake() {
2532
+ if (projectChatIntakeRecoveryStarted) return;
2533
+ const submissionIds = pendingProjectChatIntakes();
2534
+ if (!submissionIds.length) return;
2535
+ projectChatIntakeRecoveryStarted = true;
2536
+ for (const submissionId of submissionIds) {
2537
+ try {
2538
+ const result = await bridge.resumeProjectChatIntake(submissionId);
2539
+ if (!result) continue;
2540
+ if (!projects.some((item) => item.id === result.project.id)) projects.unshift(result.project);
2541
+ await openProject(result.project.id, 'drawings');
2542
+ await bridge.openChatConversation(result.chat.chatId);
2543
+ forgetProjectChatIntake(submissionId);
2544
+ showToast('Recovered the project and its AI Chat.', 'ok');
2545
+ } catch (error) {
2546
+ const code = error && (error.code || error.body && error.body.code);
2547
+ if (code === 'project-intake-not-found' || code === 'project-intake-damaged') {
2548
+ forgetProjectChatIntake(submissionId);
2549
+ } else {
2550
+ console.warn('project Chat intake recovery is still pending', error);
2551
+ }
2552
+ }
2553
+ }
2554
+ }
2555
+ window.addEventListener('floless:chat-ready', resumeInterruptedProjectChatIntake);
2556
+
2038
2557
  /**
2039
- * The NEW-PROJECT prompt: a name and the steel standard this job is built to.
2040
- *
2041
- * Separate from `promptName` deliberately — that one is shared with Rename, and a rename dialog has
2042
- * no business asking which standard a finished job uses.
2043
- *
2044
- * THE STANDARD IS ASKED HERE BECAUSE HERE IS THE ONLY PLACE IT CAN BE ASKED. It is fixed for the
2045
- * life of the project: the two section catalogues behind it are mutually exclusive, so moving a
2046
- * modelled job between them does not re-price it, it un-resolves every member — profile, thickness,
2047
- * weight and default grade at once, and the profile string handed to IFC and Tekla with them.
2048
- * Display units stay switchable at any time precisely because they are the opposite: harmless
2049
- * either way.
2050
- *
2051
- * NO COUNTRY, NO REGION, NO FLAG. §4.6 of the UK epic settled the user-facing noun as "Standard",
2052
- * with the standards body as the value — and this screen, the only one of the three where the choice
2053
- * is actually MADE, was the last one still offering countries (`United States` / `United Kingdom`).
2054
- * It is not stylistic: the reference job is British-standards work in Abu Dhabi, so a country list
2055
- * asks that user to pick a place they are not building in. "Standard" is what varies; where the job
2056
- * is does not appear, because it is not one of the two axes.
2057
- *
2058
- * NO PRESELECTED VALUE. A job is US or UK and neither is "the norm", so neither is offered as the
2059
- * one the user gets by not looking — the same rule display units follow. Since this choice cannot be
2060
- * revisited, a quietly-defaulted one would be the expensive kind of unnoticed.
2061
- */
2062
- /**
2063
- * Name a new project, and — ONLY for a steel one — the standard it resolves against forever.
2064
- *
2065
- * `askCatalogue` exists because this prompt is shared: `createFromDrawing` serves vectorize's Trace
2066
- * projects too, and asking those for a steel standard makes a user answer an irrelevant question
2067
- * with a permanent answer that nothing will ever read or be able to change. The option keeps the
2068
- * mechanism's word: what a Trace project is spared is the SECTION CATALOGUE the answer selects, and
2069
- * the stored field is `environment` on both sides of the wire.
2558
+ * A new project begins with one explicit boundary: the selected immediate child of the active
2559
+ * working directory. Nothing is written while the dialog is open. Creation atomically publishes
2560
+ * project.json and an unsent initial-task draft; the headless provider is not contacted here.
2070
2561
  */
2071
- async function promptNewProject(title, { askCatalogue = true } = {}) {
2072
- if (!bridge.formModal) return null;
2073
- // REFUSE rather than respell. If the one label table cannot be read, a hard-coded fallback here
2074
- // would be exactly the second spelling this field was pinned to that table to end — and it would
2075
- // be baked into a choice that cannot be corrected once the project exists. The user is told, and
2076
- // `loadStandardLabels` leaves itself retryable.
2077
- let standards = null;
2078
- if (askCatalogue) {
2079
- try {
2080
- standards = await loadStandardLabels();
2081
- // An INCOMPLETE table is the same failure arriving quietly: `Map.get` answers a missing key
2082
- // with `undefined`, which the modal would render as the literal string "undefined" and store
2083
- // the value behind it forever. Checked here rather than trusted, because a browser holding a
2084
- // stale copy of the module is the one way this survives the tests.
2562
+ async function createFromDrawing(appId, templateId, files, { kind = 'drawings' } = {}) {
2563
+ if (!$projectSetup || projectSetupState) return;
2564
+ if (!Array.isArray(files) || !files.length) return;
2565
+ if (files.length > 20) {
2566
+ showToast('Choose up to 20 drawings for a new project.', 'warn');
2567
+ return;
2568
+ }
2569
+ const state = {
2570
+ appId,
2571
+ templateId,
2572
+ files,
2573
+ kind,
2574
+ askCatalogue: kind === 'drawings' && templateId === 'steel-model',
2575
+ environment: null,
2576
+ directory: null,
2577
+ name: '',
2578
+ nameDirty: false,
2579
+ sourceReady: false,
2580
+ busy: false,
2581
+ returnFocus: document.activeElement instanceof HTMLElement ? document.activeElement : null,
2582
+ };
2583
+ projectSetupState = state;
2584
+ setProjectSetupError('');
2585
+ $projectSetupFolderChoose.textContent = 'Choose…';
2586
+ renderProjectSetup();
2587
+ $projectSetup.classList.add('show');
2588
+ $projectSetupFolderChoose.focus();
2589
+ try {
2590
+ await Promise.all(files.map(assertProjectSourceReadable));
2591
+ if (projectSetupState !== state) return;
2592
+ state.sourceReady = true;
2593
+ if (state.askCatalogue) {
2594
+ const standards = await loadStandardLabels();
2595
+ if (projectSetupState !== state) return;
2085
2596
  for (const env of ['US', 'UK']) {
2086
- if (!standards.get(env)) throw new Error(`the shared label table names no standard for ${env}`);
2597
+ const label = standards.get(env);
2598
+ if (!label) throw new Error(`the shared label table names no standard for ${env}`);
2599
+ $projectSetupStandard.querySelector(`[data-standard-label="${env}"]`).textContent = label;
2087
2600
  }
2088
- } catch (err) {
2089
- console.warn('promptNewProject: could not read the steel standard labels', err);
2090
- showToast('Couldn’t read the steel standards — reload the page and try again', 'warn');
2091
- return null;
2092
2601
  }
2602
+ renderProjectSetup();
2603
+ } catch (error) {
2604
+ if (projectSetupState !== state) return;
2605
+ console.warn('createFromDrawing: could not prepare project setup', error);
2606
+ setProjectSetupError(state.askCatalogue
2607
+ ? 'Couldn’t read the drawings or steel standards — choose the files again.'
2608
+ : 'Couldn’t read the drawings — choose the files again.');
2609
+ renderProjectSetup();
2093
2610
  }
2094
- const res = await bridge.formModal({
2095
- title,
2096
- fields: [
2097
- { name: 'name', label: 'Name this project', value: '', placeholder: 'e.g. Westfield Retail — Ph2' },
2098
- ...(askCatalogue ? [{
2099
- name: 'environment', type: 'select', label: 'Standard',
2100
- placeholder: 'Choose a standard…',
2101
- options: [
2102
- // The label is the standards body; `meta` is the mechanism it selects — the section family
2103
- // and the default grade — which is the detail a detailer actually recognises a standard by.
2104
- { value: 'US', label: standards.get('US'), meta: 'AISC sections · A992 / A36' },
2105
- { value: 'UK', label: standards.get('UK'), meta: 'BS EN sections · S355' },
2106
- ],
2107
- }] : []),
2108
- ],
2109
- okLabel: 'Create',
2110
- // `footnote`, not a `note` FIELD: that field type renders a <pre> for preformatted text, which
2111
- // sets a sentence of prose in a monospace block. The footnote slot is what this modal already
2112
- // has for exactly this.
2113
- ...(askCatalogue ? { footnote: 'The standard is fixed for the life of the project — every member resolves against its section catalogue. Display units can be changed at any time.' } : {}),
2114
- });
2115
- if (!res) return null;
2116
- const name = typeof res.name === 'string' ? res.name.trim() : '';
2117
- if (!name) return null;
2118
- // A project that was never asked carries NO environment — absent, not defaulted, so a vector
2119
- // project's metadata never claims a steel choice its owner did not make.
2120
- if (!askCatalogue) return { name, environment: undefined };
2121
- // An unchosen standard is REFUSED rather than defaulted: it cannot be corrected afterwards.
2122
- if (res.environment !== 'US' && res.environment !== 'UK') {
2123
- showToast('Choose a standard — it cannot be changed once the project exists', 'warn');
2124
- return null;
2611
+ }
2612
+
2613
+ $projectSetupFolderChoose.addEventListener('click', chooseProjectSetupFolder);
2614
+ $projectSetupName.addEventListener('input', () => {
2615
+ if (!projectSetupState) return;
2616
+ projectSetupState.name = $projectSetupName.value;
2617
+ projectSetupState.nameDirty = true;
2618
+ renderProjectSetup();
2619
+ });
2620
+ $projectSetupStandard.addEventListener('click', (event) => {
2621
+ const button = event.target.closest('[data-environment]');
2622
+ if (!button || !projectSetupState || projectSetupState.busy) return;
2623
+ projectSetupState.environment = button.dataset.environment;
2624
+ renderProjectSetup();
2625
+ });
2626
+ $projectSetupCancel.addEventListener('click', () => closeProjectSetup());
2627
+ $projectSetupCreate.addEventListener('click', () => createProjectFromSetup(true));
2628
+ $projectSetupCreateOnly.addEventListener('click', () => createProjectFromSetup(false));
2629
+ onBackdropDismiss($projectSetup, () => closeProjectSetup(), () => !!projectSetupState && !projectSetupState.busy);
2630
+ $projectSetup.addEventListener('keydown', (event) => {
2631
+ if (!projectSetupState) return;
2632
+ if (event.key === 'Escape' && !projectSetupState.busy) {
2633
+ event.preventDefault();
2634
+ closeProjectSetup();
2635
+ return;
2636
+ }
2637
+ if (event.key !== 'Tab') return;
2638
+ const focusable = Array.from($projectSetup.querySelectorAll('button:not([disabled]):not([hidden]), input:not([disabled])'))
2639
+ .filter((element) => !element.closest('[hidden]') && element.getClientRects().length);
2640
+ if (!focusable.length) { event.preventDefault(); return; }
2641
+ const first = focusable[0]; const last = focusable[focusable.length - 1];
2642
+ if (event.shiftKey && (document.activeElement === first || !$projectSetup.contains(document.activeElement))) {
2643
+ event.preventDefault(); last.focus();
2644
+ } else if (!event.shiftKey && (document.activeElement === last || !$projectSetup.contains(document.activeElement))) {
2645
+ event.preventDefault(); first.focus();
2125
2646
  }
2126
- return { name, environment: res.environment };
2127
- }
2128
-
2129
- // Drop-a-drawing create. No new server verb: create an EMPTY project, then fire the
2130
- // existing revision pipeline (attachRevision) with the dropped file so the terminal AI reads it into
2131
- // the native model. ROLLBACK on cancel/error — if the user cancels the name prompt, or the file can't be read,
2132
- // AFTER the row is created, archive the empty project so no dead, openable project is left
2133
- // behind (the row is created before the source exists — spec §4.1).
2134
- async function createFromDrawing(appId, templateId, files) {
2135
- // Ask for the name FIRST (before creating a row) so the common "cancel the prompt" path never
2136
- // creates anything to roll back.
2137
- // A STEEL STANDARD IS ASKED FOR ONLY ON A STEEL PROJECT. `createFromDrawing` is shared — vectorize
2138
- // creates its Trace projects through this same path — so prompting unconditionally made every
2139
- // vector drawing pick an immutable steel standard and stored that unrelated choice in its
2140
- // metadata, where nothing would ever read it and nothing could ever change it.
2141
- const created = await promptNewProject(`New ${descDisplayName(templateId)} project`,
2142
- { askCatalogue: appId === 'steel-model' });
2143
- if (!created) return;
2144
- const { name, environment } = created;
2145
- let project;
2647
+ });
2648
+ window.addEventListener('floless:workspace-root-state', (event) => {
2649
+ const state = projectSetupState;
2650
+ if (!state || !state.directory) return;
2651
+ const root = event.detail && event.detail.root;
2652
+ if (root && root.rootId === state.directory.rootId && root.generation === state.directory.generation) return;
2653
+ state.directory = null;
2654
+ $projectSetupFolderChoose.textContent = 'Choose…';
2655
+ setProjectSetupError('The Workspace directory changed. Choose this project’s folder again.');
2656
+ renderProjectSetup();
2657
+ });
2658
+
2659
+ function paintRevitSourceState(title, detail) {
2660
+ if (!$sourcePlaceholder) return;
2661
+ const titleNode = $sourcePlaceholder.querySelector('.ws-source-title');
2662
+ const detailNode = $sourcePlaceholder.querySelector('.ws-source-sub');
2663
+ if (titleNode) titleNode.textContent = title;
2664
+ if (detailNode) detailNode.textContent = detail;
2665
+ }
2666
+
2667
+ function paintRevitSourceActions(mode, canReplace = true, canRetry = true) {
2668
+ if (!$revitSourceActions) return;
2669
+ $revitSourceActions.hidden = !canReplace && mode !== 'active' && !(mode === 'failed' && canRetry);
2670
+ $revitReplace.hidden = mode === 'active' || !canReplace;
2671
+ $revitRetry.hidden = mode !== 'failed' || !canRetry;
2672
+ $revitCancel.hidden = mode !== 'active';
2673
+ $revitReassure.hidden = mode !== 'active';
2674
+ $sourcePlaceholder?.toggleAttribute('aria-busy', mode === 'active');
2675
+ $sourcePlaceholder?.setAttribute('role', mode === 'failed' ? 'alert' : 'status');
2676
+ $sourcePlaceholder?.setAttribute('aria-live', mode === 'failed' ? 'assertive' : 'polite');
2677
+ $sourcePlaceholder?.setAttribute('aria-atomic', 'true');
2678
+ }
2679
+
2680
+ async function refreshRevitSourceState(projectId = current?.id) {
2681
+ if (!projectId || !current || current.id !== projectId || wsDescOf(current)?.serverAuthorizedOnly !== true) return null;
2146
2682
  try {
2147
- ({ project } = await api('/api/projects', { method: 'POST', body: JSON.stringify({ name, app: appId, environment }) }));
2148
- } catch (err) {
2149
- showToast('Couldn’t create the project: ' + (err && err.message || err), 'warn');
2683
+ const response = await api(`/api/revit-projects/${encodeURIComponent(projectId)}/source-state`);
2684
+ if (!current || current.id !== projectId) return null;
2685
+ revitSourceState = response.state;
2686
+ revitActiveOperation = response.state.activeImport;
2687
+ if (revitActiveOperation) {
2688
+ paintRevitSourceState('Replacing source RVT…', 'The current model remains unchanged until this import finishes.');
2689
+ paintRevitSourceActions('active', true);
2690
+ pollRevitImport(revitActiveOperation.operationId, projectId);
2691
+ } else {
2692
+ const source = response.state.source;
2693
+ paintRevitSourceState('Source RVT', source ? `${source.filename} · ${(source.bytes / (1024 * 1024)).toFixed(1)} MB` : 'Choose an RVT to read into this project.');
2694
+ paintRevitSourceActions('ready', response.state.canReplace === true);
2695
+ }
2696
+ return response.state;
2697
+ } catch (error) {
2698
+ paintRevitSourceState('Revit source unavailable', error && error.message || 'Could not read source status.');
2699
+ paintRevitSourceActions('ready', false);
2700
+ return null;
2701
+ }
2702
+ }
2703
+
2704
+ async function uploadRvtForProject(project, file, generation) {
2705
+ const session = await fetch('/api/editor/session', { method: 'POST', credentials: 'same-origin' });
2706
+ if (!session.ok) throw new Error('could not start the secure editor session');
2707
+ paintRevitSourceState('Uploading RVT', `Storing ${file.name} locally…`);
2708
+ paintRevitSourceActions('active', true);
2709
+ const upload = await fetch('/api/model-sources', {
2710
+ method: 'POST', credentials: 'same-origin', body: file,
2711
+ headers: {
2712
+ 'content-type': 'application/x-rvt', 'x-floless-project-uuid': project.uuid,
2713
+ 'x-floless-generation': String(generation), 'x-floless-filename-uri': encodeURIComponent(file.name),
2714
+ },
2715
+ });
2716
+ const uploaded = await upload.json().catch(() => ({}));
2717
+ if (!upload.ok || uploaded.ok === false) throw new Error(uploaded.message || uploaded.error || `upload failed (${upload.status})`);
2718
+ const receipt = uploaded.receipt;
2719
+ const started = await api('/api/model-imports', { method: 'POST', body: JSON.stringify({
2720
+ projectUuid: project.uuid, generation: receipt.generation, sourceSha256: receipt.sourceSha256,
2721
+ }) });
2722
+ revitSourceState = { ...(revitSourceState || {}), generation: receipt.generation, pendingSource: receipt };
2723
+ revitActiveOperation = started.operation;
2724
+ return started.operation;
2725
+ }
2726
+
2727
+ async function pollRevitImport(operationId, projectId, retryAttempt = 0) {
2728
+ const isCurrentImport = () => current?.id === projectId && revitActiveOperation?.operationId === operationId;
2729
+ for (;;) {
2730
+ await new Promise((resolve) => setTimeout(resolve, 800));
2731
+ if (!isCurrentImport()) return;
2732
+ let operation;
2733
+ try { ({ operation } = await api(`/api/model-imports/${encodeURIComponent(operationId)}`)); }
2734
+ catch (err) {
2735
+ // A routine auth/lock response does not prove the operation disappeared. Only the two
2736
+ // explicit absence responses may clear it; every other outage retains the live import.
2737
+ if (!isCurrentImport()) return;
2738
+ paintRevitSourceState('Import status unavailable', err?.status === 403
2739
+ ? 'Revit access is not available for this account right now. FloLess will keep checking.'
2740
+ : 'FloLess couldn’t check this import. It will try again shortly.');
2741
+ if (err?.status === 404 || err?.status === 410) {
2742
+ revitActiveOperation = null;
2743
+ await refreshRevitSourceState(projectId);
2744
+ return;
2745
+ }
2746
+ // Status polling is advisory. Back off boundedly after transient server/network failures
2747
+ // so the viewer recovers without hammering a degraded local server.
2748
+ const retryDelay = Math.min(30_000, 2_000 * (2 ** Math.min(retryAttempt, 4)));
2749
+ if (isCurrentImport()) {
2750
+ setTimeout(() => { void pollRevitImport(operationId, projectId, retryAttempt + 1); }, retryDelay);
2751
+ }
2752
+ return;
2753
+ }
2754
+ if (!isCurrentImport()) return;
2755
+ const copy = {
2756
+ 'waiting-for-aware': ['Waiting for AWARE', 'Your RVT is stored locally and waiting for the trusted reader.'],
2757
+ converting: ['Reading model', 'Reading model geometry and properties…'],
2758
+ validating: ['Checking model integrity', 'Verifying the signed source and display packages…'],
2759
+ publishing: ['Publishing draft', 'Saving the verified read-only model snapshot…'],
2760
+ }[operation.state];
2761
+ if (copy) { paintRevitSourceState(copy[0], copy[1]); continue; }
2762
+ if (operation.state === 'ready') {
2763
+ revitActiveOperation = null;
2764
+ paintRevitSourceState('Model ready to review', 'The model is available on the Model tab. It is not approved yet.');
2765
+ paintRevitSourceActions('ready', true);
2766
+ // A Model tab opened during conversion has already loaded its temporary "unavailable" state.
2767
+ // Invalidate that frame now: reload immediately when visible, or on the next tab activation.
2768
+ reloadModelFromServerTruth();
2769
+ showToast('Revit model is ready to review.', 'ok');
2770
+ return;
2771
+ }
2772
+ if (operation.state === 'cancelled') {
2773
+ revitActiveOperation = null;
2774
+ paintRevitSourceState('Replacement cancelled', 'The existing model was not changed.');
2775
+ paintRevitSourceActions('ready', true);
2776
+ return;
2777
+ }
2778
+ revitActiveOperation = operation;
2779
+ const failure = operation.failure;
2780
+ paintRevitSourceState(failure?.title || 'Revit import failed',
2781
+ failure?.message || 'FloLess could not import this model. Try again or contact support if the problem continues.');
2782
+ paintRevitSourceActions('failed', revitSourceState?.canReplace === true, failure?.retryable !== false);
2783
+ if (failure?.retryable !== false) queueMicrotask(() => $revitRetry?.focus());
2150
2784
  return;
2151
2785
  }
2152
- // Validate the files are actually readable BEFORE queuing — a read failure here (after the row
2153
- // exists) must roll the empty project back rather than leave a dead one openable. attachRevision
2154
- // re-reads the files for the real pipeline; a tiny second read of the same files is harmless.
2155
- try { await readFileAsSnapshot(files[0]); }
2156
- catch {
2157
- // Tailor the toast to what actually happened server-side: only claim the empty project was
2158
- // removed if the archive POST succeeded — otherwise it's still there and we must say so.
2786
+ }
2787
+
2788
+ // An RVT project is created like a drawing project: the setup dialog asks for the project folder
2789
+ // and name (every project lives in a chosen working directory), then the RVT is uploaded and imported.
2790
+ function createFromRvt(appId, templateId, file) {
2791
+ if (!file || !/\.rvt$/i.test(file.name)) { showToast('Choose one Revit .rvt file.', 'warn'); return; }
2792
+ return createFromDrawing(appId, templateId, [file], { kind: 'rvt' });
2793
+ }
2794
+
2795
+ async function importRvtIntoProject(project, file, appId) {
2796
+ try {
2797
+ const operation = await uploadRvtForProject(project, file, 0);
2798
+ track('workspace_project_created', { app: appId });
2799
+ projects.unshift(project);
2800
+ await openProject(project.id, 'drawings');
2801
+ paintRevitSourceState('Waiting for AWARE', 'Your RVT is stored locally and waiting for the trusted reader.');
2802
+ if (!revitActiveOperation) { revitActiveOperation = operation; pollRevitImport(operation.operationId, project.id); }
2803
+ } catch (err) {
2159
2804
  const removed = await archiveEmptyProject(project.id);
2160
- showToast(
2161
- removed
2162
- ? 'Couldn’t read the dropped drawing — the empty project was removed.'
2163
- : 'Couldn’t read the dropped drawing — an empty project was left behind; archive it from the ⋯ menu.',
2164
- 'warn',
2165
- );
2166
- return;
2805
+ showToast(removed
2806
+ ? `Couldn’t import the RVT — the empty project was removed. ${err && err.message || err}`
2807
+ : `Couldn’t import the RVT. An empty project was left behind; archive it from the ⋯ menu. ${err && err.message || err}`, 'warn');
2167
2808
  }
2168
- track('workspace_project_created', { app: appId }); // drop-a-drawing create path (only once the row is kept, not rolled back)
2169
- projects.unshift(project);
2170
- openProject(project.id, 'drawings'); // show the queued drawing read before a model contract exists
2171
- attachRevision(files); // reads the file → POSTs the revision-read Request for THIS project (self-toasting)
2172
2809
  }
2173
2810
 
2174
2811
  // Best-effort rollback of a just-created empty project (the existing archive path — recoverable).
@@ -2226,6 +2863,19 @@
2226
2863
  // the 'model' frame loads the app's editor; the 'drawings' frame loads its filter (steel) OR is
2227
2864
  // left empty when the app has no filter step (vectorize — its Source step shows a placeholder).
2228
2865
  const d = wsDescOf(p); // guaranteed present — the guard above bailed on an unknown app
2866
+ if (d.serverAuthorizedOnly === true) {
2867
+ try {
2868
+ const session = await fetch('/api/editor/session', { method: 'POST', credentials: 'same-origin' });
2869
+ if (!session.ok) throw new Error(`HTTP ${session.status}`);
2870
+ } catch (error) {
2871
+ showToast('Couldn’t start the secure Revit editor session.', 'warn');
2872
+ current = null;
2873
+ return;
2874
+ }
2875
+ paintRevitSourceState('Revit source', 'Checking the current RVT and import state…');
2876
+ paintRevitSourceActions('ready', false);
2877
+ void refreshRevitSourceState(p.id);
2878
+ }
2229
2879
  if (d.filter && ['model', 'exports', 'history'].includes(initialStep)) {
2230
2880
  pendingPresenceStep = { projectId: p.id, step: initialStep };
2231
2881
  }
@@ -2235,6 +2885,7 @@
2235
2885
  frames.model.dataset.want = `${d.editor}${qs}`;
2236
2886
  frames.drawings.dataset.want = d.filter ? `${d.filter}${qs}` : '';
2237
2887
  renderStepTabs(); // paint the tab labels for THIS app before the first step shows
2888
+ disposeModelEditorFrame('project-open');
2238
2889
  frames.model.src = 'about:blank'; frames.drawings.src = 'about:blank'; // reset any previous project
2239
2890
  frames.model.dataset.loaded = ''; frames.drawings.dataset.loaded = '';
2240
2891
  // Start the small lifecycle envelope BEFORE the heavier approval review request. Both hit the
@@ -2321,6 +2972,33 @@
2321
2972
  exportsHasModel = present === 'model';
2322
2973
  renderApprovalHeader();
2323
2974
  applyStageGating();
2975
+ // A lifecycle probe may resolve after the saved-filter card already painted under `unknown`.
2976
+ // Retire it in the same turn that reveals the replacement strip; waiting for the request poll
2977
+ // would briefly recreate the two competing status bands this hand-off exists to remove.
2978
+ if (currentStep === 'drawings' && lastRevState === 'pending') retireRevisionCardForStrip(revCardReq);
2979
+ }
2980
+
2981
+ /**
2982
+ * Hand the saved-checkpoint status to the stage strip, which owns Done / Now / Next for it, and
2983
+ * report whether the hand-off happened.
2984
+ *
2985
+ * Retirement is conditional on the replacement being ON SCREEN, not on the contract lifecycle.
2986
+ * Two points matter. Drawing-first creation opens the project before its read is queued, so the
2987
+ * lifecycle probe commonly caches `absent`; gating on `filter-checkpoint` left the two competing
2988
+ * status bands standing in the most ordinary path there is. But an unresolved (`unknown`)
2989
+ * lifecycle un-gates every tab, so the strip paints nothing — and retiring against that would
2990
+ * leave the user with no status at all. Asking the strip itself settles both without a second
2991
+ * predicate that has to be kept in agreement with `stageGateFor`.
2992
+ */
2993
+ function retireRevisionCardForStrip(req) {
2994
+ if (!stageGuidanceOwnsSavedCheckpoint(req)) return false;
2995
+ applyStageGating();
2996
+ if (!$stageGuidance || $stageGuidance.hidden) return false;
2997
+ $revisionCard.hidden = true;
2998
+ $revisionCard.replaceChildren();
2999
+ $revisionCard._renderKey = '';
3000
+ $revisionCard.className = 'ws-revision-card';
3001
+ return true;
2324
3002
  }
2325
3003
  function closeProject() {
2326
3004
  current = null;
@@ -2332,7 +3010,7 @@
2332
3010
  exportUnits = null; // a new project's units arrive with its export listing; never inherit the last one's
2333
3011
  renderReadinessState = null;
2334
3012
  resetRevisionState();
2335
- stopKnowledgePoll(); kbCloseConfirm(); kbResetViewer(); knowledgeState = null; // the KB pane is per-project — never carry it across
3013
+ stopKnowledgePoll(); kbCloseConfirm(); closeCompanyKnowledge(false); kbResetViewer(); knowledgeState = null; companyKnowledgeState = null; // project-scoped — never carry it across
2336
3014
  // A STAGED REVIEW IS PER-PROJECT TOO, and the line above is the precedent. Without this the modal
2337
3015
  // survived leaving the project: it kept rendering the old project's proposals over the landing, and
2338
3016
  // `revReviewState.projectId` still named the project the user had just left — so confirming would
@@ -2364,6 +3042,8 @@
2364
3042
  const byKey = new Map(d.steps.map((st) => [st.key, st.label]));
2365
3043
  $stepTabs.querySelectorAll('button[data-step]').forEach((b) => {
2366
3044
  const label = byKey.get(b.dataset.step);
3045
+ b.hidden = !label;
3046
+ b.setAttribute('aria-hidden', label ? 'false' : 'true');
2367
3047
  if (label) {
2368
3048
  b.textContent = label;
2369
3049
  b.setAttribute('data-command-id', `shell.workspace-step#${label}`);
@@ -2371,6 +3051,316 @@
2371
3051
  });
2372
3052
  }
2373
3053
 
3054
+ // Everything the server refuses on write is refused again on read. A progress record is replayed
3055
+ // from the request store on every three-second poll, so a record written by a NEWER FloLess, or
3056
+ // edited on disk, must never be able to paint a confident status this build cannot stand behind.
3057
+ const PROGRESS_STATUSES = new Set(['active', 'waiting', 'blocked', 'complete', 'cancelled']);
3058
+ const PROGRESS_ITEM_STATES = new Set(['pending', 'done', 'now', 'blocked', 'waiting', 'provisional']);
3059
+ const PROGRESS_STALE_MS = 8 * 60_000;
3060
+ // `updatedAt` is stamped from the SERVER's clock and compared against this machine's. On the
3061
+ // remote-dev path the two are not synchronised, so an ordinary lead is absorbed rather than
3062
+ // refused: staleness simply cannot fire for that record, which is a far smaller harm than
3063
+ // blanking the strip. Only a lead no clock drift explains is treated as a corrupt record.
3064
+ const PROGRESS_MAX_CLOCK_LEAD_MS = 24 * 60 * 60_000;
3065
+
3066
+ function progressText(value) {
3067
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
3068
+ }
3069
+
3070
+ /**
3071
+ * Turn the provider-neutral drawing checklist into the small, honest view this surface needs.
3072
+ * Returns null when the record cannot be shown truthfully — the caller then says so out loud
3073
+ * rather than quietly falling back to a sentence claiming nothing has started.
3074
+ *
3075
+ * `contactLost` is true while the request poll itself is failing: the cached record may be
3076
+ * arbitrarily old, so no arm of this projection may keep asserting live work from it.
3077
+ */
3078
+ function drawingProgressView(req, currentTime = Date.now(), contactLost = false) {
3079
+ const progress = req && req.steelProgress;
3080
+ const exactKeys = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key));
3081
+ const plainText = (value, max, nullable = false) => (nullable && value === null)
3082
+ || (typeof value === 'string' && !!value.trim() && value.length <= max
3083
+ && !/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(value));
3084
+ const internalVisible = /\b(?:schema|api|manifest|ledger|registration|binding|disposition|audit|reconcile|attestation|evidence|candidate|json|etag|floless-app-[a-z0-9-]+|reading-structural-drawings|steel-drawing-abbreviations|[a-z][a-z0-9.-]*\/v\d+)\b/i;
3085
+ const sourceSkills = new Set([
3086
+ 'floless-app-steel-model', 'reading-structural-drawings', 'floless-app-steel-takeoff',
3087
+ 'floless-app-approval', 'steel-drawing-abbreviations',
3088
+ ]);
3089
+ const ids = new Set();
3090
+ if (!progress || progress.version !== 1 || !PROGRESS_STATUSES.has(progress.status)
3091
+ || !exactKeys(progress, ['version', 'requestId', 'status', 'items', 'done', 'now', 'next', 'revision', 'updatedAt'])
3092
+ || !Array.isArray(progress.items) || !progress.items.length || progress.items.length > 200
3093
+ || !progress.items.every((item) => item && typeof item === 'object' && !Array.isArray(item)
3094
+ && exactKeys(item, ['id', 'text', 'state', 'sources', 'verification', 'note'])
3095
+ && plainText(item.id, 100) && /^[a-z0-9][a-z0-9-]*$/.test(item.id)
3096
+ && !ids.has(item.id) && !!ids.add(item.id)
3097
+ && plainText(item.text, 500) && !internalVisible.test(item.text)
3098
+ && PROGRESS_ITEM_STATES.has(item.state)
3099
+ && Array.isArray(item.sources) && item.sources.length >= 1 && item.sources.length <= 10
3100
+ && item.sources.every((source) => source && typeof source === 'object' && !Array.isArray(source)
3101
+ && exactKeys(source, ['skill', 'section']) && sourceSkills.has(source.skill)
3102
+ && plainText(source.section, 200))
3103
+ && (item.verification === undefined || plainText(item.verification, 1_000))
3104
+ && (item.note === undefined || (plainText(item.note, 1_000) && !internalVisible.test(item.note)))
3105
+ && (item.state !== 'done' || !!progressText(item.verification))
3106
+ && (!['blocked', 'waiting', 'provisional'].includes(item.state) || !!progressText(item.note)))
3107
+ || !Number.isSafeInteger(progress.revision) || progress.revision < 1
3108
+ || !plainText(progress.updatedAt, 50)
3109
+ || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(progress.updatedAt)
3110
+ || !plainText(progress.done, 1_000) || internalVisible.test(progress.done)
3111
+ || !plainText(progress.now, 1_000, true) || (progress.now && internalVisible.test(progress.now))
3112
+ || !plainText(progress.next, 1_000, true) || (progress.next && internalVisible.test(progress.next))) return null;
3113
+ // The checklist shape the server guarantees per status. A record that breaks it is corrupt or
3114
+ // from a future contract; either way its heading would be a claim about work nobody verified.
3115
+ const nowItems = progress.items.filter((item) => item.state === 'now').length;
3116
+ const waitingItems = progress.items.filter((item) => item.state === 'waiting').length;
3117
+ if (progress.status === 'active' ? nowItems !== 1 : nowItems !== 0) return null;
3118
+ if (progress.status === 'waiting' ? waitingItems !== 1 : waitingItems > 0) return null;
3119
+ if (progress.status === 'complete' && progress.items.some((item) => item.state !== 'done')) return null;
3120
+ if (progress.status === 'active' && (!progressText(progress.now) || !progressText(progress.next))) return null;
3121
+ if (progress.status !== 'active' && progress.now !== null && progress.now !== undefined) return null;
3122
+ if (req.id && progress.requestId !== req.id) return null;
3123
+ const updatedAt = Date.parse(progress.updatedAt);
3124
+ if (!Number.isFinite(updatedAt)) return null;
3125
+ const age = currentTime - updatedAt;
3126
+ if (age < -PROGRESS_MAX_CLOCK_LEAD_MS) return null;
3127
+ const stale = age >= PROGRESS_STALE_MS;
3128
+ // Count only completed checklist items. Their evidence is present, but this surface has not
3129
+ // independently audited it, so the UI must not promote "complete" into "verified".
3130
+ const doneCount = progress.items.filter((item) => item.state === 'done').length;
3131
+ // An `active` record may legitimately carry a caveated or blocked CHECK while the read as a
3132
+ // whole continues. The server demands a plain-English note on each; rendering the checklist as
3133
+ // unqualified live work would bury exactly the sentence the user needs.
3134
+ // Under `blocked` the first blocked note is already shown as the Now row, so it is not
3135
+ // repeated here; every other caveated check still has to reach the user somewhere.
3136
+ const shownAsNow = progress.status === 'blocked'
3137
+ ? progress.items.find((item) => item.state === 'blocked')
3138
+ : progress.status === 'waiting'
3139
+ ? progress.items.find((item) => item.state === 'waiting')
3140
+ : null;
3141
+ const cautions = progress.items
3142
+ .filter((item) => (item.state === 'blocked' || item.state === 'provisional') && item !== shownAsNow)
3143
+ .map((item) => progressText(item.note))
3144
+ .filter(Boolean);
3145
+ const caution = cautions.length ? cautions.join(' · ') : null;
3146
+ let state = progress.status;
3147
+ let heading = 'Creating the first steel model';
3148
+ let nowLabel = 'Now';
3149
+ let now = progressText(progress.now);
3150
+ let next = progressText(progress.next);
3151
+ if (progress.status === 'waiting') {
3152
+ heading = 'Model creation needs your input';
3153
+ nowLabel = 'Needs you';
3154
+ now = progressText(progress.items.find((item) => item.state === 'waiting')?.note);
3155
+ } else if (progress.status === 'blocked') {
3156
+ heading = 'Model creation is blocked';
3157
+ nowLabel = 'Blocked';
3158
+ now = progressText(progress.items.find((item) => item.state === 'blocked')?.note)
3159
+ || 'Return to the same terminal AI for the blocking details.';
3160
+ } else if (progress.status === 'complete') {
3161
+ // A finished checklist is NOT a verified model: this request is still pending, nothing has
3162
+ // been submitted, and no audit has run. Only a signed post-audit surface may say the model
3163
+ // checks are complete, so this one reports exactly what it knows.
3164
+ heading = 'Drawing read finished';
3165
+ nowLabel = 'Done';
3166
+ now = null;
3167
+ next = 'Return to the same terminal AI session that prepared it and let it submit the read.';
3168
+ } else if (progress.status === 'cancelled') {
3169
+ heading = 'Model creation stopped';
3170
+ nowLabel = 'Stopped';
3171
+ now = 'Return to the same terminal AI for next steps.';
3172
+ next = null;
3173
+ }
3174
+ // A heartbeat nobody can refresh is not a heartbeat. Both arms below replace the forward-looking
3175
+ // plan with a recovery route, because carrying "Next: check every connection" into a stalled or
3176
+ // unreachable state presents work that is not happening as though it were queued.
3177
+ if (contactLost && progress.status === 'active') {
3178
+ state = 'waiting';
3179
+ heading = 'Progress updates have stopped arriving';
3180
+ nowLabel = 'Last reported';
3181
+ now = progressText(progress.now) || now;
3182
+ next = 'FloLess could not reach its own server. This refreshes by itself when the connection returns.';
3183
+ } else if (stale && progress.status === 'active') {
3184
+ state = 'waiting';
3185
+ heading = 'No progress update in the last 8 minutes';
3186
+ nowLabel = 'Last reported';
3187
+ next = 'Return to the same terminal AI session that prepared this read and ask it to continue.';
3188
+ } else if (stale && progress.status === 'complete') {
3189
+ state = 'waiting';
3190
+ heading = 'The drawing read finished but has not been submitted';
3191
+ nowLabel = 'Done';
3192
+ next = 'Return to the same terminal AI session that prepared it and tell it to submit the read.';
3193
+ }
3194
+ return {
3195
+ state,
3196
+ heading,
3197
+ doneCount,
3198
+ done: progress.done.trim(),
3199
+ nowLabel,
3200
+ now,
3201
+ caution,
3202
+ next,
3203
+ requestId: progress.requestId,
3204
+ revision: progress.revision,
3205
+ updatedAt: progress.updatedAt,
3206
+ };
3207
+ }
3208
+
3209
+ /** Revised drawing reads keep their own card; the strip owns every initial-read handoff it paints. */
3210
+ function stageGuidanceOwnsSavedCheckpoint(req) {
3211
+ return !!(req && isInitialRevisionRead(req) && (
3212
+ req?.preparationState === 'manifest-published' || req?.prepassReady
3213
+ ));
3214
+ }
3215
+
3216
+ function appendStageGuidanceFilterAction() {
3217
+ if (!$stageGuidance || $stageGuidance.querySelector('[data-revfilter]')) return;
3218
+ const actions = document.createElement('div');
3219
+ actions.className = 'wsg-actions';
3220
+ const review = document.createElement('button');
3221
+ review.type = 'button';
3222
+ review.className = 'btn-mini';
3223
+ review.textContent = 'Open Drawing Filter';
3224
+ review.dataset.revfilter = '';
3225
+ review.dataset.commandId = 'shell.revision-filter-open';
3226
+ review.setAttribute('data-tip', 'Focus the Drawing Filter below');
3227
+ actions.appendChild(review);
3228
+ $stageGuidance.appendChild(actions);
3229
+ markScrollable($stageGuidance);
3230
+ }
3231
+
3232
+ function wireStageGuidanceFilterAction() {
3233
+ $stageGuidance?.addEventListener('click', (e) => {
3234
+ if (e.target.closest('[data-revfilter]')) focusDrawingFilterSave();
3235
+ });
3236
+ }
3237
+
3238
+ function stageGuidanceRow(label, text) {
3239
+ const row = document.createElement('div');
3240
+ row.className = 'wsg-row';
3241
+ const key = document.createElement('span');
3242
+ key.className = 'wsg-label';
3243
+ key.textContent = label;
3244
+ const value = document.createElement('span');
3245
+ value.className = 'wsg-value';
3246
+ value.textContent = text;
3247
+ row.append(key, value);
3248
+ return row;
3249
+ }
3250
+
3251
+ /** Clear guidance without unmounting the page-load live region used by assistive technology. */
3252
+ function clearStageGuidance() {
3253
+ if (!$stageGuidance) return;
3254
+ $stageGuidance.hidden = true;
3255
+ let live = document.getElementById('ws-stage-guidance-live');
3256
+ if (!live) {
3257
+ live = document.createElement('span');
3258
+ live.id = 'ws-stage-guidance-live';
3259
+ live.className = 'sr-only wsg-live';
3260
+ live.setAttribute('role', 'status');
3261
+ live.setAttribute('aria-live', 'polite');
3262
+ live.setAttribute('aria-atomic', 'true');
3263
+ $stageGuidance.before(live);
3264
+ }
3265
+ if (live) live.textContent = '';
3266
+ $stageGuidance.replaceChildren();
3267
+ markScrollable($stageGuidance);
3268
+ $stageGuidance._renderKey = '';
3269
+ $stageGuidance._invalidProgressKey = '';
3270
+ }
3271
+
3272
+ /**
3273
+ * Avoid re-announcing unchanged progress every time the three-second request poll repaints.
3274
+ *
3275
+ * The bounded visible region is named and becomes keyboard-scrollable when needed. Its prose is
3276
+ * mirrored into the one established live region so progress changes are announced only once.
3277
+ */
3278
+ function paintStageGuidance(content, state = 'info') {
3279
+ if (!$stageGuidance) return;
3280
+ // Only a real projection may take the progress path. Any other object would render `undefined`
3281
+ // into the heading with no throw and no log, which is the failure this surface exists to remove.
3282
+ const progress = content && typeof content === 'object' && !Array.isArray(content)
3283
+ && typeof content.heading === 'string' && typeof content.state === 'string'
3284
+ && Number.isSafeInteger(content.doneCount) ? content : null;
3285
+ const key = progress
3286
+ ? `progress:${progress.requestId}:${progress.state}:${progress.revision}:${progress.heading}`
3287
+ : `text:${state}:${typeof content === 'string' ? content : ''}`;
3288
+ $stageGuidance.hidden = false;
3289
+ if ($stageGuidance._renderKey === key) return;
3290
+ $stageGuidance._renderKey = key;
3291
+ $stageGuidance.className = `ws-stage-guidance state-${progress ? progress.state : state}`;
3292
+ let live = document.getElementById('ws-stage-guidance-live');
3293
+ if (!live) {
3294
+ live = document.createElement('span');
3295
+ live.id = 'ws-stage-guidance-live';
3296
+ live.className = 'sr-only wsg-live';
3297
+ live.setAttribute('role', 'status');
3298
+ live.setAttribute('aria-live', 'polite');
3299
+ live.setAttribute('aria-atomic', 'true');
3300
+ $stageGuidance.before(live);
3301
+ }
3302
+ if (!progress) {
3303
+ // Only a string is guidance. Coercing an object here would paint the literal `[object Object]`
3304
+ // into the strip with no throw and no log.
3305
+ const text = typeof content === 'string' ? content : '';
3306
+ if (live) live.textContent = text;
3307
+ const visible = document.createElement('span');
3308
+ visible.setAttribute('aria-hidden', 'true');
3309
+ visible.textContent = text;
3310
+ $stageGuidance.replaceChildren(visible);
3311
+ markScrollable($stageGuidance);
3312
+ return;
3313
+ }
3314
+
3315
+ const head = document.createElement('div');
3316
+ head.className = 'wsg-head';
3317
+ head.setAttribute('aria-hidden', 'true');
3318
+ const signal = document.createElement('span');
3319
+ signal.className = 'wsg-signal';
3320
+ signal.setAttribute('aria-hidden', 'true');
3321
+ const title = document.createElement('strong');
3322
+ title.textContent = progress.heading;
3323
+ const count = document.createElement('span');
3324
+ count.className = 'wsg-count';
3325
+ count.textContent = `${progress.doneCount} check${progress.doneCount === 1 ? '' : 's'} complete`;
3326
+ head.append(signal, title, count);
3327
+
3328
+ const activity = document.createElement('div');
3329
+ activity.className = 'wsg-activity';
3330
+ activity.setAttribute('aria-hidden', 'true');
3331
+ activity.appendChild(document.createElement('span'));
3332
+
3333
+ const details = document.createElement('div');
3334
+ details.className = 'wsg-details';
3335
+ details.setAttribute('aria-hidden', 'true');
3336
+ details.appendChild(stageGuidanceRow('Done', progress.done));
3337
+ if (progress.now) details.appendChild(stageGuidanceRow(progress.nowLabel, progress.now));
3338
+ if (progress.caution) details.appendChild(stageGuidanceRow('Heads up', progress.caution));
3339
+ if (progress.next) details.appendChild(stageGuidanceRow('Next', progress.next));
3340
+
3341
+ const instant = new Date(progress.updatedAt);
3342
+ const updatedText = `Updated ${instant.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
3343
+ if (live) live.textContent = [
3344
+ progress.heading,
3345
+ `${progress.doneCount} check${progress.doneCount === 1 ? '' : 's'} complete`,
3346
+ `Done: ${progress.done}`,
3347
+ progress.now ? `${progress.nowLabel}: ${progress.now}` : '',
3348
+ progress.caution ? `Heads up: ${progress.caution}` : '',
3349
+ progress.next ? `Next: ${progress.next}` : '',
3350
+ updatedText,
3351
+ ].filter(Boolean).map((part) => (/[.!?]$/.test(part) ? part : `${part}.`)).join(' ').trim();
3352
+
3353
+ // Server summaries are prose and usually end in a full stop already. Joining with another one
3354
+ // makes a screen reader read "confirmed dot dot", so only unpunctuated segments get a stop.
3355
+ const updated = document.createElement('time');
3356
+ updated.className = 'wsg-updated';
3357
+ updated.setAttribute('aria-hidden', 'true');
3358
+ updated.dateTime = progress.updatedAt;
3359
+ updated.textContent = updatedText;
3360
+ $stageGuidance.replaceChildren(head, activity, details, updated);
3361
+ markScrollable($stageGuidance);
3362
+ }
3363
+
2374
3364
  // Keep steel projects stage-by-stage while the first drawing read is in progress. The later tabs
2375
3365
  // stay visible so the user can see what comes next, but explain their prerequisite instead of
2376
3366
  // opening empty destinations during a potentially long terminal-AI read.
@@ -2393,7 +3383,7 @@
2393
3383
  // stages until this probe produces a real lifecycle answer.
2394
3384
  if (projectContractLifecycle === 'unknown') return '';
2395
3385
  if (step === 'model') {
2396
- if (waitingForInitial && revCardReq?.preparationState === 'blocked') return 'Steel drawing preparation needs operator repair. Restart FloLess, then open Requests and follow Technical details if it remains blocked.';
3386
+ if (waitingForInitial && revCardReq?.preparationState === 'blocked') return 'FloLess could not finish drawing preparation. Restart FloLess, then open Requests and follow the detailed instructions if it remains blocked.';
2397
3387
  if (waitingForInitial && revCardReq?.preparationState === 'manifest-published' && !revCardReq?.prepassReady) return 'Drawing preparation is complete and saved. Return to the same terminal AI session and tell it to continue creating the Drawing Filter.';
2398
3388
  if (waitingForInitial && revCardReq?.filterCheckpointCurrent) return 'The Drawing Filter is saved. Return to the same terminal AI session that prepared it and tell it to continue the drawing read.';
2399
3389
  if (waitingForInitial && revCardReq?.prepassReady) return 'Review the selected lines, then press Save filter. After Save, return to the terminal AI that prepared it and tell it to continue.';
@@ -2421,7 +3411,7 @@
2421
3411
  b.removeAttribute('data-blocked-reason');
2422
3412
  b.setAttribute('tabindex', '0');
2423
3413
  });
2424
- if ($stageGuidance) $stageGuidance.hidden = true;
3414
+ clearStageGuidance();
2425
3415
  return;
2426
3416
  }
2427
3417
  let locked = false;
@@ -2459,12 +3449,32 @@
2459
3449
  const failedInitial = initialRead && lastRevState === 'failed';
2460
3450
  const unavailableInitial = initialRead && lastRevState === 'unavailable';
2461
3451
  if (!locked) {
2462
- $stageGuidance.hidden = true;
2463
- $stageGuidance.textContent = '';
3452
+ clearStageGuidance();
2464
3453
  return;
2465
3454
  }
2466
- $stageGuidance.hidden = false;
2467
- $stageGuidance.textContent = stagedInitial
3455
+ const ownsProgress = waitingForInitial && stageGuidanceOwnsSavedCheckpoint(revCardReq);
3456
+ const liveProgress = ownsProgress ? drawingProgressView(revCardReq, Date.now(), revRequestsFailed) : null;
3457
+ if (ownsProgress && revCardReq?.steelProgress && !liveProgress) {
3458
+ const revision = Number.isSafeInteger(revCardReq.steelProgress.revision)
3459
+ ? String(revCardReq.steelProgress.revision) : `invalid:${String(revCardReq.steelProgress.revision)}`;
3460
+ const invalidKey = `${revCardReq.id || ''}:${revision}`;
3461
+ if ($stageGuidance._invalidProgressKey !== invalidKey) {
3462
+ $stageGuidance._invalidProgressKey = invalidKey;
3463
+ console.warn('Ignoring an unreadable steel progress record', invalidKey, revCardReq.steelProgress);
3464
+ }
3465
+ // The server is holding progress, so work HAS started. Saying "live progress will appear here
3466
+ // when work starts" would state the opposite of what this build can already see.
3467
+ paintStageGuidance('Progress updates are arriving in a form this version of FloLess cannot show'
3468
+ + ' · The drawing read itself is unaffected. Open Requests for details and update FloLess.',
3469
+ 'failed');
3470
+ return;
3471
+ }
3472
+ if (liveProgress) {
3473
+ $stageGuidance._invalidProgressKey = '';
3474
+ paintStageGuidance(liveProgress);
3475
+ return;
3476
+ }
3477
+ const guidance = stagedInitial
2468
3478
  ? 'The drawing read is complete · Open Drawing Filter and choose Review changes before moving to Model, Exports, or History.'
2469
3479
  : failedInitial
2470
3480
  ? (revCardReq?.canClear === true
@@ -2473,20 +3483,24 @@
2473
3483
  : unavailableInitial
2474
3484
  ? 'This drawing read uses a status this version of FloLess does not recognize · Open Requests for details and update FloLess before continuing.'
2475
3485
  : waitingForInitial && revCardReq?.preparationState === 'blocked'
2476
- ? 'Stage 1 of 4 · Steel drawing preparation needs operator repair. Restart FloLess, then open Requests and follow Technical details if it remains blocked. Your drawings are still attached.'
3486
+ ? 'FloLess could not finish drawing preparation · Restart FloLess, then open Requests and follow the detailed instructions if it remains blocked. Your drawings are still attached.'
2477
3487
  : waitingForInitial && revCardReq?.preparationState === 'manifest-published' && !revCardReq?.prepassReady
2478
- ? 'Stage 1 of 4 · Drawing preparation is complete and saved. Return to the same terminal AI session and tell it to continue creating the Drawing Filter. Do not start or copy this request again.'
3488
+ ? 'Drawing preparation is complete and saved · Return to the same terminal AI session and tell it to continue creating the Drawing Filter. Do not start or copy this request again.'
2479
3489
  : waitingForInitial && revCardReq?.filterCheckpointCurrent
2480
- ? 'Stage 1 of 4 complete · The Drawing Filter is saved. Return to the same terminal AI session that prepared it and tell it to continue the drawing read. Model, Exports, and History unlock when it finishes.'
3490
+ ? 'The Drawing Filter is saved · Return to the same terminal AI session that prepared it and tell it to continue the drawing read. Live progress appears here once it starts.'
2481
3491
  : waitingForInitial && revCardReq?.prepassReady
2482
- ? 'Stage 1 of 4 · Review the selected layers, line weights, and colours below. Then press Save filter in the top-right corner, return to the terminal AI that prepared it, and tell it to continue. Model, Exports, and History unlock when the read finishes.'
3492
+ ? 'Drawing Filter ready for review · Review the selected layers, line weights, and colours below. Then press Save filter in the top-right corner, return to the terminal AI that prepared it, and tell it to continue.'
2483
3493
  : waitingForInitial && revCardReq?.preparationRetryable
2484
- ? 'Stage 1 of 4 · Steel Filter preparation was interrupted. Your drawings are still attached. Return to the same terminal AI and retry preparation for this same request. Model, Exports, and History unlock afterward.'
3494
+ ? 'Steel Filter preparation was interrupted · Your drawings are still attached. Return to the same terminal AI and retry preparation for this same request.'
2485
3495
  : waitingForInitial
2486
- ? 'Stage 1 of 4 · Your initial drawing read is waiting for your terminal AI. Open Requests, copy it into Claude Code, Codex, or OpenCode, then return to review and save the Drawing Filter. Model, Exports, and History unlock afterward.'
3496
+ ? 'Drawing read not started · Open Requests, copy it into Claude Code, Codex, or OpenCode, then return to review and save the Drawing Filter.'
2487
3497
  : projectContractLifecycle === 'filter-checkpoint'
2488
- ? 'Stage 1 of 4 · The earlier drawing request is no longer available. Attach the drawing set again in Drawing Filter to restart the read. Model, Exports, and History unlock after it finishes.'
3498
+ ? 'Drawing read needs restarting · The earlier drawing request is no longer available. Attach the drawing set again in Drawing Filter to restart the read.'
2489
3499
  : 'Start in Drawing Filter by attaching a PDF or image. The Model, Exports, and History stages unlock after the first steel model is created.';
3500
+ paintStageGuidance(guidance, failedInitial || unavailableInitial ? 'failed' : 'info');
3501
+ if (waitingForInitial && revCardReq?.prepassReady && !revCardReq?.filterCheckpointCurrent) {
3502
+ appendStageGuidanceFilterAction();
3503
+ }
2490
3504
  }
2491
3505
 
2492
3506
  function deferStageUntilLifecycle(s) {
@@ -2549,12 +3563,15 @@
2549
3563
  f.hidden = !show;
2550
3564
  if (show && !f.dataset.loaded && f.dataset.want) { f.src = f.dataset.want; f.dataset.loaded = '1'; }
2551
3565
  }
3566
+ if (window.flolessLeftPane) {
3567
+ window.flolessLeftPane.setWorkspaceModelVisible(s === 'model');
3568
+ }
2552
3569
  if ($sourcePlaceholder) $sourcePlaceholder.hidden = !(s === 'drawings' && !drawingsHasFrame);
2553
3570
  // Queried here rather than through the module const, the way master's own call sites do: setStep is
2554
3571
  // extracted and evaluated on its own by workspace-instructor-handoff.test.ts, and a closure
2555
3572
  // variable it cannot see is a ReferenceError there. It sits at the end of the step-tabs row now
2556
3573
  // (the breadcrumb row that used to hold it is gone), and is a Drawings-step control either way.
2557
- { const a = document.getElementById('ws-attach-revision'); if (a) a.hidden = s !== 'drawings'; }
3574
+ { const a = document.getElementById('ws-attach-revision'); if (a) a.hidden = s !== 'drawings' || d?.serverAuthorizedOnly === true; }
2558
3575
  renderRevisionCard(); // reflect any pending/failed revision read (card shows only on the Drawings step)
2559
3576
  // The conversion offer is Model-step scoped, and re-derived on every entry rather than cached:
2560
3577
  // the project's contract can change under this shell (a revision read, another tab, the editor's
@@ -2606,6 +3623,59 @@
2606
3623
  // (paintExports), and it never reads approvedAt: that field is compatibility metadata only, as
2607
3624
  // the approvalState declaration above says.
2608
3625
  const approvalDecisionLabel = (decision) => decision === 'approve' ? 'Approve this change' : 'Leave pending';
3626
+ let modelContractSaveState = null;
3627
+ window.addEventListener('message', (event) => {
3628
+ const message = event.data;
3629
+ if (event.origin !== location.origin || event.source !== frames.model?.contentWindow
3630
+ || !message || message.type !== 'floless:contract-save-state' || !current
3631
+ || message.projectId !== current.id || message.appId !== current.app
3632
+ || !['clean', 'dirty', 'saving', 'error', 'conflict'].includes(message.state)) return;
3633
+ modelContractSaveState = { projectId: current.id, appId: current.app, state: message.state, generation: message.generation };
3634
+ });
3635
+ const approvalPhaseText = {
3636
+ saving: 'Saving model edits…', comparing: 'Comparing changes…', approving: 'Approving and compiling…',
3637
+ reconciling: 'Reconciling approval…', approved: 'Approved', failed: 'Nothing was approved.', stale: 'The review changed.',
3638
+ abandoned: 'Nothing was approved. The previous approval attempt ended safely.',
3639
+ };
3640
+ const approvalDismissible = (phase) => ['saving', 'comparing', 'ready', 'failed', 'stale', 'approved', 'abandoned', 'recovery-close'].includes(phase);
3641
+
3642
+ function setApprovalPhase(phase, message) {
3643
+ const st = approvalDialogState;
3644
+ if (!st) return;
3645
+ const changed = st.phase !== phase;
3646
+ st.phase = phase;
3647
+ // Recovery may be dismissed, but it must never unlock a second mutation while the durable
3648
+ // outcome is pending or unreadable. Dismissibility and mutation safety are separate concerns.
3649
+ const locked = !approvalDismissible(phase) || ['abandoned', 'recovery-close'].includes(phase);
3650
+ const cancelVisible = ['saving', 'comparing', 'ready', 'failed', 'stale'].includes(phase);
3651
+ const active = document.activeElement;
3652
+ const activeControlWillHide = (active === $approvalCancel && !cancelVisible)
3653
+ || (active === $approvalRetry && phase !== 'failed')
3654
+ || (active === $approvalReload && phase !== 'stale')
3655
+ || (active === $approvalClose && !['approved', 'abandoned', 'recovery-close'].includes(phase))
3656
+ || (active === $approvalConfirm && !['ready', 'abandoned'].includes(phase));
3657
+ if (activeControlWillHide || (locked && active && $approvalBody.contains(active))) $approvalDialog.focus();
3658
+ if (changed && $approvalLive) $approvalLive.textContent = message || approvalPhaseText[phase] || '';
3659
+ $approvalBody?.setAttribute('aria-busy', String(['saving', 'comparing', 'approving', 'reconciling'].includes(phase)));
3660
+ $approvalCancel.hidden = !cancelVisible;
3661
+ $approvalRetry.hidden = phase !== 'failed';
3662
+ $approvalReload.hidden = phase !== 'stale';
3663
+ $approvalClose.hidden = !['approved', 'abandoned', 'recovery-close'].includes(phase);
3664
+ $approvalConfirm.hidden = !['ready', 'abandoned'].includes(phase);
3665
+ $approvalBody.querySelectorAll('[data-approval-decision],[data-approval-conflict],[data-approval-discard]').forEach((node) => { node.disabled = locked; });
3666
+ if (phase === 'saving' || phase === 'comparing') {
3667
+ const text = message || approvalPhaseText[phase];
3668
+ $approvalBody.innerHTML = `<div class="approval-loading"><span class="rtn-spinner" aria-hidden="true"></span><span aria-hidden="true">${escapeHtml(text)}</span></div>`;
3669
+ $approvalSub.textContent = phase === 'saving' ? 'Finishing the model edits already on screen…' : 'Loading the server comparison…';
3670
+ } else if (phase === 'approving' || phase === 'reconciling') {
3671
+ $approvalSub.textContent = message || approvalPhaseText[phase];
3672
+ } else if (['approved', 'failed', 'stale', 'abandoned', 'recovery-close'].includes(phase)) {
3673
+ // A terminal/recovery outcome replaces the in-flight phase visibly as well as in the live region.
3674
+ // Leaving "Approving and compiling…" above an Approved/failed body makes a finished command look
3675
+ // stuck — the exact ambiguity this state machine exists to remove.
3676
+ $approvalSub.textContent = message || approvalPhaseText[phase] || '';
3677
+ }
3678
+ }
2609
3679
 
2610
3680
  function renderApprovalReview() {
2611
3681
  if (!approvalDialogState) return;
@@ -2653,6 +3723,7 @@
2653
3723
  : remainingConflicts > 0 ? `${remainingConflicts} overlap${remainingConflicts === 1 ? '' : 's'} still need a decision`
2654
3724
  : approved ? `${approved} change${approved === 1 ? '' : 's'} will be approved · ${groups.length - approved} left pending`
2655
3725
  : groups.length ? 'All changes will remain pending' : 'Nothing needs approval';
3726
+ $approvalConfirm.setAttribute('data-command-id', 'shell.approval-confirm');
2656
3727
  $approvalConfirm.textContent = approved ? `Approve ${approved} change${approved === 1 ? '' : 's'}` : 'Approve selected changes';
2657
3728
  $approvalConfirm.disabled = remaining !== 0 || remainingConflicts !== 0 || approved === 0 || groups.length === 0 || approvalDialogState.stale;
2658
3729
  }
@@ -2660,12 +3731,150 @@
2660
3731
  function closeApprovalReview() {
2661
3732
  if (!$approvalModal) return;
2662
3733
  const st = approvalDialogState;
3734
+ if (st && !approvalDismissible(st.phase)) return;
2663
3735
  approvalDialogState = null;
2664
3736
  $approvalModal.classList.remove('show');
2665
3737
  $approvalModal.removeAttribute('aria-busy');
2666
3738
  if (st && st.returnFocus && st.returnFocus.isConnected) st.returnFocus.focus();
2667
3739
  }
2668
3740
 
3741
+ const approvalOperationStoragePrefix = 'floless:approval-operation:v1';
3742
+ const approvalOperationIdPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
3743
+ const approvalOperationStorageKey = (project) => `${approvalOperationStoragePrefix}:${encodeURIComponent(project.app)}|${encodeURIComponent(project.id)}`;
3744
+ const approvalDecisionRecord = (value, allowed) => value && typeof value === 'object' && !Array.isArray(value)
3745
+ && Object.entries(value).every(([key, decision]) => key.length > 0 && allowed.includes(decision));
3746
+ function validRememberedApprovalOperation(value, project) {
3747
+ return !!value && typeof value === 'object' && !Array.isArray(value)
3748
+ && value.projectId === project.id && value.appId === project.app
3749
+ && typeof value.operationId === 'string' && approvalOperationIdPattern.test(value.operationId)
3750
+ && typeof value.operationToken === 'string' && approvalOperationIdPattern.test(value.operationToken)
3751
+ && value.operationToken !== value.operationId
3752
+ && typeof value.reviewId === 'string' && value.reviewId.length > 0
3753
+ && approvalDecisionRecord(value.decisions, ['approve', 'leave-pending'])
3754
+ && approvalDecisionRecord(value.conflicts, ['use-draft', 'keep-latest-pending']);
3755
+ }
3756
+ function rememberedApprovalOperationMatchesReview(value, review) {
3757
+ if (!value || value.reviewId !== review.reviewId) return false;
3758
+ const groupIds = (Array.isArray(review.groups) ? review.groups : []).map((group) => group.id);
3759
+ const conflictIds = (review.moveForward && Array.isArray(review.moveForward.conflicts) ? review.moveForward.conflicts : [])
3760
+ .map((conflict) => conflict.id);
3761
+ return Object.keys(value.decisions).length === groupIds.length
3762
+ && groupIds.every((id) => Object.hasOwn(value.decisions, id))
3763
+ && Object.keys(value.conflicts).length === conflictIds.length
3764
+ && conflictIds.every((id) => Object.hasOwn(value.conflicts, id));
3765
+ }
3766
+ function rememberApprovalOperation(project, value) {
3767
+ try {
3768
+ const key = approvalOperationStorageKey(project);
3769
+ if (value) localStorage.setItem(key, JSON.stringify(value));
3770
+ else localStorage.removeItem(key);
3771
+ } catch { /* the server receipt remains authoritative when browser storage is unavailable */ }
3772
+ }
3773
+ function rememberedApprovalOperation(project) {
3774
+ try {
3775
+ const key = approvalOperationStorageKey(project);
3776
+ const value = JSON.parse(localStorage.getItem(key) || 'null');
3777
+ if (validRememberedApprovalOperation(value, project)) return value;
3778
+ if (value !== null) localStorage.removeItem(key);
3779
+ return null;
3780
+ } catch {
3781
+ try { localStorage.removeItem(approvalOperationStorageKey(project)); } catch { /* blocked storage */ }
3782
+ return null;
3783
+ }
3784
+ }
3785
+
3786
+ function ensureApprovalOperationPair(state) {
3787
+ if (approvalOperationIdPattern.test(state.operationId || '')
3788
+ && approvalOperationIdPattern.test(state.operationToken || '')
3789
+ && state.operationToken !== state.operationId) {
3790
+ return { operationId: state.operationId, operationToken: state.operationToken };
3791
+ }
3792
+ state.operationId = crypto.randomUUID();
3793
+ state.operationToken = crypto.randomUUID();
3794
+ return { operationId: state.operationId, operationToken: state.operationToken };
3795
+ }
3796
+
3797
+ async function finishApprovalSuccess(res, project) {
3798
+ rememberApprovalOperation(project, null);
3799
+ if (res && res.approvedAt) project.approvedAt = res.approvedAt;
3800
+ const n = res && res.version && Number(res.version.n);
3801
+ if (Number.isInteger(n)) expandDiffOnce = { projectId: project.id, n };
3802
+ reloadModelFromServerTruth();
3803
+ await refreshApprovalState(project.id);
3804
+ const pending = Number.isInteger(Number(res && res.pendingCount)) ? Number(res.pendingCount) : approvalState.pendingCount;
3805
+ const saved = res && res.savedWorkCheckpoint;
3806
+ showToast(`Approved${Number.isInteger(n) ? ` as v${n}` : ''}. ${pending ? `${pending} change${pending === 1 ? '' : 's'} remain pending${saved ? ' in Saved work' : ''}; approved exports omit them unless you explicitly choose DRAFT.` : 'No changes remain pending.'}`, 'ok');
3807
+ track('workspace_project_approved', { app: project.app });
3808
+ if (bridge.markWorkspaceApproved && wsDescOf(project)?.docGuide) bridge.markWorkspaceApproved(project.app);
3809
+ if (!$wsExports.hidden) safeRenderExports('after approving this version');
3810
+ if (!$wsHistory.hidden) await renderHistory();
3811
+ if (!approvalDialogState) return;
3812
+ $approvalImpact.textContent = pending
3813
+ ? `${pending} change${pending === 1 ? '' : 's'} remain pending${saved ? ' in Saved work' : ''}.`
3814
+ : 'No changes remain pending.';
3815
+ $approvalBody.innerHTML = `<div class="approval-notice approval-notice-success"><b>Approved${Number.isInteger(n) ? ` as v${n}` : ''}.</b> The approved model and compiled workflow are ready.</div>`;
3816
+ setApprovalPhase('approved', `Approved${Number.isInteger(n) ? ` as v${n}` : ''}`);
3817
+ $approvalClose.focus();
3818
+ }
3819
+
3820
+ async function reconcileApprovalOperation(project, operationId, operationToken) {
3821
+ setApprovalPhase('reconciling');
3822
+ try {
3823
+ const response = await fetch(`/api/projects/${encodeURIComponent(project.id)}/approval-operations/${encodeURIComponent(operationId)}?token=${encodeURIComponent(operationToken)}`, {
3824
+ signal: AbortSignal.timeout(4000),
3825
+ });
3826
+ if (response.status === 404) return { status: 'not-found' };
3827
+ if (!response.ok) return { status: 'unknown' };
3828
+ const receipt = await response.json();
3829
+ return receipt && ['complete', 'pending', 'abandoned'].includes(receipt.status) ? receipt : { status: 'unknown' };
3830
+ } catch { return { status: 'unknown' }; }
3831
+ }
3832
+
3833
+ const approvalRecoveryDisposition = (receipt) => receipt?.status === 'complete' ? 'complete'
3834
+ : receipt?.status === 'abandoned' ? 'abandoned'
3835
+ : receipt?.status === 'not-found' ? 'continue' : 'locked';
3836
+
3837
+ function showLockedApprovalRecovery(receipt) {
3838
+ const pending = receipt?.status === 'pending';
3839
+ $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>`;
3840
+ setApprovalPhase('recovery-close', pending ? 'Approval recovery is still in progress.' : 'The approval result is not available yet.');
3841
+ $approvalClose.focus();
3842
+ }
3843
+
3844
+ function showAbandonedApprovalRecovery(project) {
3845
+ const st = approvalDialogState;
3846
+ if (!st) return;
3847
+ rememberApprovalOperation(project, null);
3848
+ st.operationId = null;
3849
+ st.operationToken = null;
3850
+ st.decisions = {};
3851
+ st.conflicts = {};
3852
+ st.retryAction = null;
3853
+ $approvalSub.textContent = 'The previous approval attempt ended safely.';
3854
+ $approvalImpact.textContent = '';
3855
+ $approvalCounts.textContent = '';
3856
+ $approvalBody.innerHTML = '<div class="approval-notice"><b>Nothing was approved.</b> FloLess restored your working copy. That approval attempt is finished and cannot be retried.</div>';
3857
+ $approvalConfirm.setAttribute('data-command-id', 'shell.approval-start-new-review');
3858
+ $approvalConfirm.textContent = 'Start a new review';
3859
+ $approvalConfirm.disabled = false;
3860
+ setApprovalPhase('abandoned');
3861
+ $approvalConfirm.focus();
3862
+ }
3863
+
3864
+ async function startNewApprovalReview() {
3865
+ const st = approvalDialogState;
3866
+ if (!st || st.phase !== 'abandoned' || !current || current.id !== st.projectId) return;
3867
+ const returnFocus = st.returnFocus;
3868
+ rememberApprovalOperation(current, null);
3869
+ const preparing = approveProject();
3870
+ if (approvalDialogState) approvalDialogState.returnFocus = returnFocus;
3871
+ $approvalDialog.focus();
3872
+ await preparing;
3873
+ }
3874
+
3875
+ const approvalPreparationStillCurrent = (dialogState, project) => approvalDialogState === dialogState
3876
+ && current && current.id === project.id;
3877
+
2669
3878
  async function approveProject() {
2670
3879
  if (!current || !$approvalModal || !$approvalDialog) return;
2671
3880
  if (!exportsHasModel) {
@@ -2674,22 +3883,52 @@
2674
3883
  }
2675
3884
  const project = current;
2676
3885
  $approvalModal.classList.add('show');
2677
- $approvalModal.setAttribute('aria-busy', 'true');
2678
- $approvalSub.textContent = 'Loading the server comparison…';
2679
3886
  $approvalImpact.textContent = '';
2680
- $approvalBody.innerHTML = '<div class="approval-loading"><span class="rtn-spinner" aria-hidden="true"></span> Comparing changes…</div>';
2681
3887
  $approvalCounts.textContent = '';
2682
3888
  $approvalConfirm.disabled = true;
2683
- approvalDialogState = { projectId: project.id, review: { groups: [] }, decisions: {}, conflicts: {}, returnFocus: document.activeElement, stale: false };
3889
+ approvalDialogState = { projectId: project.id, review: { groups: [] }, decisions: {}, conflicts: {}, returnFocus: document.activeElement, stale: false, phase: 'comparing' };
3890
+ const dialogState = approvalDialogState;
3891
+ setApprovalPhase('comparing');
2684
3892
  $approvalDialog.focus();
2685
3893
  try {
3894
+ const remembered = rememberedApprovalOperation(project);
3895
+ if (remembered) {
3896
+ approvalDialogState.operationId = remembered.operationId;
3897
+ approvalDialogState.operationToken = remembered.operationToken;
3898
+ let receipt = await reconcileApprovalOperation(project, remembered.operationId, remembered.operationToken);
3899
+ for (let attempt = 0; approvalRecoveryDisposition(receipt) === 'locked' && attempt < 20; attempt += 1) {
3900
+ await new Promise((resolve) => setTimeout(resolve, 500));
3901
+ receipt = await reconcileApprovalOperation(project, remembered.operationId, remembered.operationToken);
3902
+ }
3903
+ if (approvalRecoveryDisposition(receipt) === 'complete') {
3904
+ await finishApprovalSuccess(receipt, project);
3905
+ return;
3906
+ }
3907
+ if (approvalRecoveryDisposition(receipt) === 'abandoned') {
3908
+ showAbandonedApprovalRecovery(project);
3909
+ return;
3910
+ }
3911
+ if (approvalRecoveryDisposition(receipt) === 'locked') {
3912
+ showLockedApprovalRecovery(receipt);
3913
+ return;
3914
+ }
3915
+ }
2686
3916
  const win = frames.model && frames.model.contentWindow;
2687
3917
  // History is server-owned after partial approval and may hide an editor whose in-memory draft
2688
3918
  // predates that partition. Other tabs can be reached immediately after an edit, before the
2689
3919
  // debounce saves, so they must still flush even though the iframe is hidden.
2690
- if (currentStep !== 'history' && win && typeof win.flushContract === 'function') await win.flushContract();
3920
+ const saveState = win && typeof win.contractSaveState === 'function'
3921
+ ? win.contractSaveState()
3922
+ : modelContractSaveState?.projectId === project.id && modelContractSaveState?.appId === project.app
3923
+ ? modelContractSaveState.state : null;
3924
+ if (win && typeof win.flushContract === 'function' && saveState !== 'clean') {
3925
+ setApprovalPhase('saving');
3926
+ await win.flushContract();
3927
+ }
3928
+ if (!approvalPreparationStillCurrent(dialogState, project)) return;
3929
+ setApprovalPhase('comparing');
2691
3930
  const review = await api(`/api/projects/${encodeURIComponent(project.id)}/approval-review`);
2692
- if (!current || current.id !== project.id || !approvalDialogState) return;
3931
+ if (!approvalPreparationStillCurrent(dialogState, project)) return;
2693
3932
  // THE SECOND CONSUMER of this route, and it needs the same guard `refreshApprovalState` has —
2694
3933
  // found by review, having shipped without it. The quiet answer is a 200, so `api()` no longer
2695
3934
  // throws and the catch below no longer sees it; the success path would then read a body with no
@@ -2704,53 +3943,114 @@
2704
3943
  approvalState = { status: 'unreviewable', reason: review.reason, review: null, pendingCount: 0,
2705
3944
  headVersion: null, error: review.message || 'This project cannot be approved.' };
2706
3945
  renderApprovalHeader();
2707
- showToast(review.message || 'This project cannot be approved.', 'warn');
3946
+ showToast('This project cannot be approved because FloLess found changes it cannot confirm. Review the project changes, then try again.', 'warn');
2708
3947
  return;
2709
3948
  }
2710
3949
  approvalDialogState.review = review;
3950
+ const storedAttempt = rememberedApprovalOperation(project);
3951
+ const canRestore = rememberedApprovalOperationMatchesReview(storedAttempt, review);
3952
+ approvalDialogState.decisions = canRestore ? storedAttempt.decisions || {} : {};
3953
+ approvalDialogState.conflicts = canRestore ? storedAttempt.conflicts || {} : {};
3954
+ if (!canRestore) { approvalDialogState.operationId = null; approvalDialogState.operationToken = null; rememberApprovalOperation(project, null); }
3955
+ approvalDialogState.stale = false;
2711
3956
  approvalState = { status: 'ready', review, pendingCount: Array.isArray(review.groups) ? review.groups.length : 0,
2712
3957
  headVersion: approvalHeadVersion(review), error: '' };
2713
3958
  renderApprovalHeader();
2714
3959
  renderApprovalReview();
3960
+ if (canRestore) {
3961
+ approvalDialogState.retryAction = 'approve';
3962
+ $approvalBody.insertAdjacentHTML('afterbegin', '<div class="approval-notice approval-notice-error"><b>Nothing was approved.</b> Try again with the same decisions.</div>');
3963
+ setApprovalPhase('failed', 'Nothing was approved. Try again.');
3964
+ $approvalRetry.focus();
3965
+ } else {
3966
+ setApprovalPhase('ready');
3967
+ ($approvalBody.querySelector('[data-approval-decision]') || $approvalConfirm).focus();
3968
+ }
2715
3969
  } catch (error) {
2716
- if (!approvalDialogState) return;
2717
- approvalDialogState.stale = true;
3970
+ if (approvalDialogState !== dialogState) return;
3971
+ approvalDialogState.stale = false;
3972
+ approvalDialogState.retryAction = 'prepare';
2718
3973
  $approvalSub.textContent = 'Approval status unavailable';
2719
3974
  $approvalImpact.textContent = (error && error.message) || 'Could not load the comparison.';
2720
- $approvalBody.innerHTML = '<div class="approval-empty">Close this review and try again. Nothing was approved.</div>';
2721
- } finally { $approvalModal.removeAttribute('aria-busy'); }
3975
+ $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>';
3976
+ setApprovalPhase('failed', 'Nothing was approved. Try again.');
3977
+ $approvalRetry.focus();
3978
+ }
2722
3979
  }
2723
3980
 
2724
3981
  async function confirmApprovalReview() {
2725
3982
  const st = approvalDialogState;
2726
3983
  if (!st || $approvalConfirm.disabled || !current || current.id !== st.projectId) return;
2727
3984
  const project = current;
2728
- $approvalModal.setAttribute('aria-busy', 'true');
3985
+ const decisionSnapshot = { decisions: { ...st.decisions }, conflicts: { ...st.conflicts } };
3986
+ const { operationId, operationToken } = ensureApprovalOperationPair(st);
3987
+ rememberApprovalOperation(project, { projectId: project.id, appId: project.app, operationId, operationToken,
3988
+ reviewId: st.review.reviewId, decisions: decisionSnapshot.decisions, conflicts: decisionSnapshot.conflicts });
3989
+ setApprovalPhase('approving');
2729
3990
  $approvalConfirm.disabled = true;
2730
3991
  try {
2731
3992
  const res = await api(`/api/contract/${encodeURIComponent(project.app)}/approve?project=${encodeURIComponent(project.id)}`, {
2732
- method: 'POST', body: JSON.stringify({ mode: st.review.mode || 'head', reviewId: st.review.reviewId, decisions: st.decisions, conflicts: st.conflicts, claimedChannel: 'browser' }),
3993
+ method: 'POST', body: JSON.stringify({ mode: st.review.mode || 'head', reviewId: st.review.reviewId, decisions: st.decisions, conflicts: st.conflicts, claimedChannel: 'browser', operationId, operationToken }),
2733
3994
  });
2734
- if (res && res.approvedAt) project.approvedAt = res.approvedAt;
2735
- const n = res && res.version && Number(res.version.n);
2736
- if (Number.isInteger(n)) expandDiffOnce = { projectId: project.id, n };
2737
- reloadModelFromServerTruth();
2738
- closeApprovalReview();
2739
- await refreshApprovalState(project.id);
2740
- const pending = Number.isInteger(Number(res && res.pendingCount)) ? Number(res.pendingCount) : approvalState.pendingCount;
2741
- const saved = res && res.savedWorkCheckpoint;
2742
- showToast(`Approved${Number.isInteger(n) ? ` as v${n}` : ''}. ${pending ? `${pending} change${pending === 1 ? '' : 's'} remain pending${saved ? ' in Saved work' : ''}; approved exports omit them unless you explicitly choose DRAFT.` : 'No changes remain pending.'}`, 'ok');
2743
- track('workspace_project_approved', { app: project.app });
2744
- if (bridge.markWorkspaceApproved && wsDescOf(project)?.docGuide) bridge.markWorkspaceApproved(project.app);
2745
- if (!$wsExports.hidden) safeRenderExports('after approving this version');
2746
- if (!$wsHistory.hidden) await renderHistory();
3995
+ await finishApprovalSuccess(res, project);
2747
3996
  } catch (error) {
2748
3997
  if (approvalDialogState && error && error.body && error.body.code === 'approval-review-stale') {
3998
+ rememberApprovalOperation(project, null);
3999
+ st.operationId = null;
4000
+ st.operationToken = null;
2749
4001
  approvalDialogState.stale = true;
2750
- $approvalImpact.textContent = 'The working copy changed. Your decisions were not applied. Close and reopen to reload the comparison.';
4002
+ $approvalImpact.textContent = 'The working copy changed. Your decisions were not applied. Reload the current review; earlier decisions will be cleared.';
4003
+ renderApprovalReview();
4004
+ setApprovalPhase('stale', 'The review changed. Reload current review.');
4005
+ $approvalReload.focus();
4006
+ } else if (approvalDialogState) {
4007
+ const recovered = await reconcileApprovalOperation(project, operationId, operationToken);
4008
+ if (approvalRecoveryDisposition(recovered) === 'complete') {
4009
+ await finishApprovalSuccess(recovered, project);
4010
+ return;
4011
+ }
4012
+ if (approvalRecoveryDisposition(recovered) === 'abandoned') {
4013
+ showAbandonedApprovalRecovery(project);
4014
+ return;
4015
+ }
4016
+ if (approvalRecoveryDisposition(recovered) === 'locked') {
4017
+ showLockedApprovalRecovery(recovered);
4018
+ return;
4019
+ }
4020
+ approvalDialogState.decisions = decisionSnapshot.decisions;
4021
+ approvalDialogState.conflicts = decisionSnapshot.conflicts;
4022
+ approvalDialogState.retryAction = 'approve';
2751
4023
  renderApprovalReview();
2752
- } else showToast('Approve failed: ' + ((error && error.message) || error), 'warn');
2753
- } finally { if (approvalDialogState) $approvalModal.removeAttribute('aria-busy'); }
4024
+ $approvalImpact.textContent = (error && error.message) || 'Approval failed before a version was committed.';
4025
+ $approvalBody.insertAdjacentHTML('afterbegin', '<div class="approval-notice approval-notice-error"><b>Nothing was approved.</b> Try again with the same decisions.</div>');
4026
+ setApprovalPhase('failed', 'Nothing was approved. Try again.');
4027
+ $approvalRetry.focus();
4028
+ }
4029
+ }
4030
+
4031
+ }
4032
+
4033
+ async function reloadApprovalReview() {
4034
+ const st = approvalDialogState;
4035
+ if (!st || !current || current.id !== st.projectId) return;
4036
+ const project = current;
4037
+ setApprovalPhase('comparing');
4038
+ try {
4039
+ const review = await api(`/api/projects/${encodeURIComponent(st.projectId)}/approval-review`);
4040
+ if (!approvalDialogState || approvalDialogState !== st) return;
4041
+ st.review = review; st.decisions = {}; st.conflicts = {}; st.stale = false;
4042
+ st.operationId = null;
4043
+ st.operationToken = null;
4044
+ rememberApprovalOperation(project, null);
4045
+ $approvalImpact.textContent = '';
4046
+ renderApprovalReview();
4047
+ setApprovalPhase('ready');
4048
+ ($approvalBody.querySelector('[data-approval-decision]') || $approvalConfirm).focus();
4049
+ } catch (error) {
4050
+ $approvalImpact.textContent = (error && error.message) || 'Could not reload the current review.';
4051
+ setApprovalPhase('stale', 'The current review could not be loaded.');
4052
+ $approvalReload.focus();
4053
+ }
2754
4054
  }
2755
4055
 
2756
4056
  async function discardApprovalChange(groupId) {
@@ -2771,7 +4071,19 @@
2771
4071
  renderApprovalReview();
2772
4072
  await refreshApprovalState(st.projectId);
2773
4073
  showToast('Discarded the selected working-copy change. Nothing was approved.', 'ok');
2774
- } catch (error) { showToast('Discard failed: ' + ((error && error.message) || error), 'warn'); }
4074
+ } catch (error) { showToast('We couldn’t discard these changes because FloLess could not save the update. Try again.', 'warn'); }
4075
+ }
4076
+
4077
+ async function retryApprovalReview() {
4078
+ const st = approvalDialogState;
4079
+ if (!st || st.phase !== 'failed') return;
4080
+ if (st.retryAction === 'prepare') {
4081
+ await approveProject();
4082
+ return;
4083
+ }
4084
+ setApprovalPhase('ready');
4085
+ renderApprovalReview();
4086
+ await confirmApprovalReview();
2775
4087
  }
2776
4088
 
2777
4089
  $approvalBody?.addEventListener('click', (event) => {
@@ -2798,10 +4110,16 @@
2798
4110
  if (discard) discardApprovalChange(discard.dataset.approvalDiscard);
2799
4111
  });
2800
4112
  $approvalCancel?.addEventListener('click', closeApprovalReview);
2801
- $approvalConfirm?.addEventListener('click', confirmApprovalReview);
2802
- $approvalModal?.addEventListener('mousedown', (event) => { if (event.target === $approvalModal) closeApprovalReview(); });
4113
+ $approvalClose?.addEventListener('click', closeApprovalReview);
4114
+ $approvalRetry?.addEventListener('click', () => { retryApprovalReview(); });
4115
+ $approvalReload?.addEventListener('click', reloadApprovalReview);
4116
+ $approvalConfirm?.addEventListener('click', () => {
4117
+ if (approvalDialogState?.phase === 'abandoned') startNewApprovalReview();
4118
+ else confirmApprovalReview();
4119
+ });
4120
+ $approvalModal?.addEventListener('mousedown', (event) => { if (event.target === $approvalModal && approvalDialogState && approvalDismissible(approvalDialogState.phase)) closeApprovalReview(); });
2803
4121
  $approvalModal?.addEventListener('keydown', (event) => {
2804
- if (event.key === 'Escape') { event.preventDefault(); closeApprovalReview(); return; }
4122
+ if (event.key === 'Escape') { event.preventDefault(); if (approvalDialogState && approvalDismissible(approvalDialogState.phase)) closeApprovalReview(); return; }
2805
4123
  if (event.key !== 'Tab') return;
2806
4124
  const focusable = Array.from($approvalModal.querySelectorAll('button:not([disabled]), summary, [tabindex="0"]')).filter((node) => !node.hidden);
2807
4125
  if (!focusable.length) return;
@@ -2809,6 +4127,27 @@
2809
4127
  if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
2810
4128
  else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
2811
4129
  });
4130
+ function keepApprovalFocusInside() {
4131
+ if (!approvalDialogState || !$approvalModal?.classList.contains('show') || document.activeElement !== frames.model) return;
4132
+ // Reloading the visible model after approval can focus its iframe after the modal has already moved
4133
+ // focus to Close. Restrict this to that exact iframe escape: the form modal used by Discard change
4134
+ // deliberately layers over approval and must keep its own focus. Choose the action that matches the
4135
+ // current recovery phase and restore the approval dialog boundary only from the editor.
4136
+ const phase = approvalDialogState.phase;
4137
+ const target = phase === 'abandoned' && !$approvalConfirm.hidden ? $approvalConfirm
4138
+ : !$approvalClose.hidden ? $approvalClose
4139
+ : !$approvalRetry.hidden ? $approvalRetry
4140
+ : !$approvalReload.hidden ? $approvalReload
4141
+ : !$approvalCancel.hidden ? $approvalCancel : $approvalDialog;
4142
+ target?.focus();
4143
+ }
4144
+ function retainApprovalModalFocus() {
4145
+ requestAnimationFrame(() => requestAnimationFrame(keepApprovalFocusInside));
4146
+ }
4147
+ document.addEventListener('focusin', (event) => {
4148
+ if (event.target !== frames.model) return;
4149
+ keepApprovalFocusInside();
4150
+ });
2812
4151
  $approveBtn?.addEventListener('click', () => {
2813
4152
  if ($approveBtn.getAttribute('aria-disabled') === 'true') {
2814
4153
  // Re-ask only where the answer can differ. A failed probe can; so can `no-contract`, which stops
@@ -2875,6 +4214,10 @@
2875
4214
  }
2876
4215
  });
2877
4216
  } catch { /* not-yet-loaded / cross-origin */ }
4217
+ // Chromium can make the iframe the parent's active element during navigation without a reliable
4218
+ // parent focusin event. Run after the load task so any editor autofocus has settled, then enforce
4219
+ // the approval modal boundary while it is open.
4220
+ retainApprovalModalFocus();
2878
4221
  syncWorkspaceReporter();
2879
4222
  retainTerminalRevisionReviewFocus();
2880
4223
  });
@@ -2883,6 +4226,7 @@
2883
4226
  // document's active element. Recover only that exact escape from the terminal result; focus in any
2884
4227
  // parent-document overlay is untouched.
2885
4228
  window.addEventListener('blur', () => {
4229
+ retainApprovalModalFocus();
2886
4230
  restoreTerminalRevisionReviewFocusFromModel(revReviewState?.stageId);
2887
4231
  }, true);
2888
4232
  // (find methods are exposed on the canonical window.flolessWorkspaces export below — a separate
@@ -2905,6 +4249,11 @@
2905
4249
  const KB_MB = (n) => Math.round(n / (1024 * 1024));
2906
4250
  let knowledgePoll = null;
2907
4251
  let knowledgeState = null;
4252
+ let companyKnowledgeState = null;
4253
+ let companyKnowledgePromotion = null; // { sourceId, filename }
4254
+ let companyKnowledgePending = null; // { kind:'accept'|'remove', ... }
4255
+ let companyKnowledgeReturnFocus = null;
4256
+ let companyKnowledgeBusy = false;
2908
4257
 
2909
4258
  // ── Stage B2: the content-switched viewer ────────────────────────────────────
2910
4259
  // The pane right of References holds exactly one of: 'graph' (today the Stage-C placeholder),
@@ -3002,9 +4351,11 @@
3002
4351
  // (the store writes organize.json at `start`), so "pending" must be the UNION of both reads — never
3003
4352
  // /status alone. The request queue is advisory: a blip there must not blank the sources column.
3004
4353
  async function loadKnowledgeState(proj) {
3005
- const [status, reqs] = await Promise.all([
4354
+ const [status, reqs, company] = await Promise.all([
3006
4355
  api(kbUrl(proj.id, '/status')),
3007
4356
  api('/api/requests').catch(() => []),
4357
+ api(`/api/company-knowledge?projectId=${encodeURIComponent(proj.id)}`)
4358
+ .catch((error) => ({ configured: false, loadError: String((error && error.message) || error) })),
3008
4359
  ]);
3009
4360
  const list = Array.isArray(reqs) ? reqs : (reqs.requests || []);
3010
4361
  const manifest = status.manifest || { revision: 0, currentGeneration: null, sources: [] };
@@ -3014,6 +4365,7 @@
3014
4365
  currentGeneration: status.currentGeneration || null,
3015
4366
  organize: status.organize || null,
3016
4367
  queued: list.filter((r) => r && r.type === 'knowledge-organize' && r.project === proj.id),
4368
+ company,
3017
4369
  };
3018
4370
  }
3019
4371
 
@@ -3052,7 +4404,31 @@
3052
4404
 
3053
4405
  // SECURITY: every value below is server/AI/user-derived — escapeHtml for text, escapeAttr for
3054
4406
  // attributes. Nothing reaches innerHTML raw (design §6: never raw LLM HTML).
3055
- function kbSourceRow(s) {
4407
+ function kbCompanyChip(s, st) {
4408
+ const snapshot = s.companySnapshot;
4409
+ if (!snapshot) return '';
4410
+ const company = st && st.company;
4411
+ const entry = company && company.available && Array.isArray(company.sources)
4412
+ ? company.sources.find((row) => row.librarySourceId === snapshot.librarySourceId)
4413
+ : null;
4414
+ const accepted = entry ? entry.versions.findIndex((version) => version.versionId === snapshot.versionId) : -1;
4415
+ const versionLabel = accepted >= 0 ? `v${accepted + 1}` : 'snapshot';
4416
+ let state = `company ${versionLabel}`;
4417
+ let cls = 'company';
4418
+ const projectAccepted = entry ? companyAcceptedVersion(entry, company.projectSnapshots) : null;
4419
+ if (projectAccepted && accepted >= 0 && projectAccepted.number > accepted + 1) {
4420
+ state += ` · retained after v${projectAccepted.number}`;
4421
+ } else if (entry && !entry.removedAt && accepted >= 0 && accepted < entry.versions.length - 1) {
4422
+ state += ` · v${entry.versions.length} available`;
4423
+ cls += ' update';
4424
+ } else if ((company && company.available && !entry) || (entry && entry.removedAt)) {
4425
+ state += ' · shared entry removed';
4426
+ cls += ' removed';
4427
+ }
4428
+ return `<span class="kb-chip ${cls}">${escapeHtml(state)}</span>`;
4429
+ }
4430
+
4431
+ function kbSourceRow(s, st) {
3056
4432
  const on = !!s.useAsKb;
3057
4433
  const ico = kbIcon(s.mime);
3058
4434
  const chip = KB_CHIP[s.state] || ['new', escapeHtml(String(s.state || 'new'))];
@@ -3073,7 +4449,7 @@
3073
4449
  `<div class="kb-fbody">` +
3074
4450
  `<button type="button" class="kb-fname" data-kb-open="${escapeAttr(s.sourceId)}" ` +
3075
4451
  `data-tip="Preview “${escapeAttr(name)}”">${escapeHtml(name)}</button>` +
3076
- `<div class="kb-fmeta">${escapeHtml(meta)}<span class="kb-chip ${chip[0]}">${chip[1]}</span>${imported}</div>` +
4452
+ `<div class="kb-fmeta">${escapeHtml(meta)}<span class="kb-chip ${chip[0]}">${chip[1]}</span>${imported}${kbCompanyChip(s, st)}</div>` +
3077
4453
  err +
3078
4454
  `</div>` +
3079
4455
  `<button type="button" class="kb-toggle" role="switch" aria-checked="${on ? 'true' : 'false'}" data-kb-toggle ` +
@@ -3326,6 +4702,11 @@
3326
4702
  return '<section class="kb-col kb-viewer">' +
3327
4703
  '<div class="kb-view-head">' +
3328
4704
  `<span class="kb-view-name" data-tip="${escapeAttr(name)}">${escapeHtml(name)}</span>` +
4705
+ (row.kind === 'file'
4706
+ ? `<button type="button" class="kb-promote" data-company-promote="${escapeAttr(row.sourceId)}" ` +
4707
+ `data-command-id="shell.company-promote-source" data-command-instance="${escapeAttr(row.sourceId)}" ` +
4708
+ `data-command-instance-label="${escapeAttr(name)}" data-tip="Share a copy of this file with company knowledge">Promote to company…</button>`
4709
+ : '') +
3329
4710
  '<button type="button" class="kb-view-x" data-kb-close aria-label="Close preview" data-tip="Close the preview">✕</button>' +
3330
4711
  '</div>' +
3331
4712
  `<div class="kb-view-body">${bodyHtml}</div>` +
@@ -3472,6 +4853,7 @@
3472
4853
  * polling would then never start. */
3473
4854
  function kbCommitState(st) {
3474
4855
  knowledgeState = st;
4856
+ companyKnowledgeState = st.company || null;
3475
4857
  paintKnowledge(st);
3476
4858
  if (kbPending(st)) startKnowledgePoll(); else stopKnowledgePoll();
3477
4859
  }
@@ -3588,7 +4970,7 @@
3588
4970
  function kbColumn(st) {
3589
4971
  const n = st.sources.length;
3590
4972
  const body = n
3591
- ? st.sources.map(kbSourceRow).join('')
4973
+ ? st.sources.map((source) => kbSourceRow(source, st)).join('')
3592
4974
  : '<div class="kb-empty">No references yet — drop files above, or ask your terminal AI to add them.</div>';
3593
4975
  return '<section class="kb-col">' +
3594
4976
  '<div class="kb-refs-body">' +
@@ -3621,7 +5003,17 @@
3621
5003
  const ov = kbGraphIndex
3622
5004
  ? `<button type="button" class="kb-g-overview" data-kb-node="${escapeAttr(kbGraphIndex.slug)}" data-tip="Open the overview">✦ Overview</button>`
3623
5005
  : '';
3624
- return `<div class="step-head" id="kb-step-head"><span>Knowledge</span>${count}${ov}</div>`;
5006
+ const company = st && st.company;
5007
+ const updates = company && company.available && Array.isArray(company.projectSnapshots)
5008
+ ? company.sources.filter((entry) => {
5009
+ if (entry.removedAt) return false;
5010
+ const accepted = companyAcceptedVersion(entry, company.projectSnapshots);
5011
+ return accepted && entry.versions.at(-1)?.versionId !== accepted.snapshot.versionId;
5012
+ }).length : 0;
5013
+ const companyButton = '<button type="button" class="kb-company-open" data-company-open ' +
5014
+ 'data-command-id="shell.company-knowledge" data-tip="Open company references shared across FloLess projects">' +
5015
+ `Company knowledge${updates ? `<span class="kb-company-count" aria-label="${updates} update${updates === 1 ? '' : 's'} available">${updates}</span>` : ''}</button>`;
5016
+ return `<div class="step-head" id="kb-step-head"><span>Knowledge</span>${count}${companyButton}${ov}</div>`;
3625
5017
  }
3626
5018
 
3627
5019
  /* Repaint the band iff its rendered output changed — the same contract the refs column keeps, and
@@ -3879,6 +5271,271 @@
3879
5271
  kbCommitState(st);
3880
5272
  }
3881
5273
 
5274
+ // ── Company knowledge ───────────────────────────────────────────────────────
5275
+ // One modal extends the existing Knowledge surface. Shared entries are immutable versions;
5276
+ // nothing reaches this project's source list until the user explicitly accepts one.
5277
+ let companyKnowledgeProjectId = null;
5278
+
5279
+ function companyVersionNumber(entry, versionId) {
5280
+ const at = entry && Array.isArray(entry.versions)
5281
+ ? entry.versions.findIndex((version) => version.versionId === versionId) : -1;
5282
+ return at < 0 ? null : at + 1;
5283
+ }
5284
+
5285
+ function companyAcceptedVersion(entry, snapshots) {
5286
+ let accepted = null;
5287
+ for (const snapshot of snapshots || []) {
5288
+ if (snapshot.librarySourceId !== entry.librarySourceId) continue;
5289
+ const number = companyVersionNumber(entry, snapshot.versionId);
5290
+ if (number && (!accepted || number > accepted.number)) accepted = { number, snapshot };
5291
+ }
5292
+ return accepted;
5293
+ }
5294
+
5295
+ function companySetError(message) {
5296
+ $companyKnowledgeError.hidden = !message;
5297
+ $companyKnowledgeError.textContent = message || '';
5298
+ }
5299
+
5300
+ function companyErrorMessage(error, fallback = 'FloLess could not update the company library. Try again.') {
5301
+ const raw = String(error && error.body?.error || error && error.message || error || '');
5302
+ if (/EPERM|EACCES|operation not permitted|permission denied/i.test(raw)) {
5303
+ return 'Windows denied FloLess access to the company folder. Choose a folder you can open and edit, then try again.';
5304
+ }
5305
+ if (/ENOENT|not found|no such file|unavailable|cannot be reached/i.test(raw)) {
5306
+ return 'FloLess cannot find the company folder right now. Reconnect the drive or choose another folder, then try again.';
5307
+ }
5308
+ if (/outside|inside|contain one another|project folder|workspace/i.test(raw)) {
5309
+ return 'Choose a separate folder for shared company references. It cannot be inside a FloLess project or Workspace directory.';
5310
+ }
5311
+ if (/invalid|identity|registry|marker|generation|ownership|internal|error|failed|errno|stack|code|status|http|operation/i.test(raw)) return fallback;
5312
+ return fallback;
5313
+ }
5314
+
5315
+ function companyFolderHtml(state) {
5316
+ if (state && state.loadError) {
5317
+ return '<div><div class="company-folder-title">Company folder</div>' +
5318
+ `<div class="company-folder-note">Couldn’t read the company library. ${escapeHtml(companyErrorMessage(state.loadError, 'Check the company folder and try again.'))}</div></div>` +
5319
+ '<button type="button" data-company-folder-choose data-command-id="shell.company-folder-choose">Choose folder…</button>';
5320
+ }
5321
+ if (!state || !state.configured) {
5322
+ return '<div><div class="company-folder-title">No company folder yet</div>' +
5323
+ '<div class="company-folder-note">Choose one independent folder for references shared across projects and modules.</div></div>' +
5324
+ '<button type="button" data-company-folder-choose data-command-id="shell.company-folder-choose">Choose folder…</button>';
5325
+ }
5326
+ const unavailable = !state.available;
5327
+ return '<div class="company-folder-copy"><div class="company-folder-title">Company folder' +
5328
+ (unavailable ? ' <span class="company-state-chip warn">unavailable</span>' : ' <span class="company-state-chip">connected</span>') +
5329
+ '</div><code class="company-folder-path"></code>' +
5330
+ (unavailable ? `<div class="company-folder-note">${escapeHtml(companyErrorMessage(state.reason, 'FloLess cannot reach the company folder right now. Choose another folder and try again.'))}</div>` : '') +
5331
+ '</div><button type="button" data-company-folder-choose data-command-id="shell.company-folder-choose">' +
5332
+ (unavailable ? 'Choose another…' : 'Change…') + '</button>';
5333
+ }
5334
+
5335
+ function companyEntryHtml(entry, state) {
5336
+ const latest = entry.versions[entry.versions.length - 1];
5337
+ const accepted = companyAcceptedVersion(entry, state.projectSnapshots);
5338
+ const latestNumber = entry.versions.length;
5339
+ const current = accepted && accepted.snapshot.versionId === latest.versionId;
5340
+ const status = current ? `<span class="company-state-chip">Added · up to date</span>`
5341
+ : accepted ? `<span class="company-state-chip warn">Update available · project uses v${accepted.number}</span>`
5342
+ : `<span class="company-state-chip">${latestNumber} version${latestNumber === 1 ? '' : 's'}</span>`;
5343
+ const action = current
5344
+ ? '<span class="company-entry-current">Added · up to date</span>'
5345
+ : `<button type="button" data-company-stage-accept="${escapeAttr(entry.librarySourceId)}" ` +
5346
+ `data-command-id="shell.company-accept" data-command-instance="${escapeAttr(entry.librarySourceId)}" ` +
5347
+ `data-command-instance-label="${escapeAttr(entry.displayName)}">${accepted ? `Review update to v${latestNumber}…` : 'Add to project…'}</button>`;
5348
+ return `<article class="company-entry" data-company-source-id="${escapeAttr(entry.librarySourceId)}">` +
5349
+ '<div class="company-entry-main"><div class="company-entry-heading">' +
5350
+ `<span>${escapeHtml(entry.displayName)}</span>${status}</div>` +
5351
+ `<div class="company-entry-meta">Latest v${latestNumber} · ${escapeHtml(latest.filename)} · ${escapeHtml(kbBytes(latest.bytes))}` +
5352
+ (latest.provenance && latest.provenance.projectName
5353
+ ? ` · from ${escapeHtml(latest.provenance.projectName)}` : '') + '</div></div>' +
5354
+ `<div class="company-entry-actions">${action}<button type="button" class="company-remove" ` +
5355
+ `data-company-stage-remove="${escapeAttr(entry.librarySourceId)}" data-command-id="shell.company-remove" ` +
5356
+ `data-command-instance="${escapeAttr(entry.librarySourceId)}" data-command-instance-label="${escapeAttr(entry.displayName)}" ` +
5357
+ 'data-tip="Remove this entry from company knowledge">Remove…</button></div></article>';
5358
+ }
5359
+
5360
+ function renderCompanyKnowledge() {
5361
+ const state = companyKnowledgeState;
5362
+ $companyKnowledgeFolder.innerHTML = companyFolderHtml(state);
5363
+ const path = $companyKnowledgeFolder.querySelector('.company-folder-path');
5364
+ if (path && state && state.configured) path.textContent = state.path;
5365
+
5366
+ const available = !!(state && state.configured && state.available);
5367
+ $companyKnowledgePromotion.hidden = !companyKnowledgePromotion;
5368
+ if (companyKnowledgePromotion) {
5369
+ $companyPromotionSource.textContent = companyKnowledgePromotion.filename;
5370
+ const prior = $companyPromotionLineage.value;
5371
+ const entries = available ? state.sources.filter((entry) => !entry.removedAt) : [];
5372
+ $companyPromotionLineage.innerHTML = '<option value="">New company entry</option>' + entries.map((entry) =>
5373
+ `<option value="${escapeAttr(entry.librarySourceId)}">New version of ${escapeHtml(entry.displayName)}</option>`).join('');
5374
+ $companyPromotionLineage.value = entries.some((entry) => entry.librarySourceId === prior) ? prior : '';
5375
+ $companyPromotionLineage.disabled = !available || companyKnowledgeBusy;
5376
+ $companyPromotionLineage.dataset.tip = available
5377
+ ? 'Choose whether this is a separate company reference or a version of an existing one'
5378
+ : 'Choose an available company folder first';
5379
+ }
5380
+
5381
+ if (!available) {
5382
+ $companyKnowledgeList.innerHTML = '<div class="company-empty">' +
5383
+ (state && state.configured ? 'Shared references will appear when this folder is available.'
5384
+ : 'After choosing a folder, shared references from every module appear here.') + '</div>';
5385
+ } else {
5386
+ const entries = state.sources.filter((entry) => !entry.removedAt);
5387
+ $companyKnowledgeList.innerHTML = entries.length
5388
+ ? '<div class="company-section-label">Shared references</div>' + entries.map((entry) => companyEntryHtml(entry, state)).join('')
5389
+ : '<div class="company-empty">No company references yet. Preview a project file and choose “Promote to company…”.</div>';
5390
+ }
5391
+
5392
+ $companyKnowledgeConfirm.hidden = !companyKnowledgePending;
5393
+ if (companyKnowledgePending) {
5394
+ const entry = available && state.sources.find((row) => row.librarySourceId === companyKnowledgePending.librarySourceId);
5395
+ const latest = entry && entry.versions[entry.versions.length - 1];
5396
+ $companyKnowledgeConfirm.innerHTML = companyKnowledgePending.kind === 'accept'
5397
+ ? `<strong>Add ${escapeHtml(entry ? entry.displayName : 'this reference')} v${entry ? entry.versions.length : ''} to this project?</strong>` +
5398
+ '<span>FloLess copies this exact version into the project. The previous version remains available for earlier references but will not be used the next time you organize Knowledge.</span>'
5399
+ : `<strong>Remove ${escapeHtml(entry ? entry.displayName : 'this company entry')}?</strong>` +
5400
+ '<span>Projects that already added a version keep their copies and earlier references. Other projects can no longer add this company reference.</span>';
5401
+ if (!latest && companyKnowledgePending.kind === 'accept') companySetError('That company version is no longer available.');
5402
+ }
5403
+
5404
+ $companyKnowledgeCancel.textContent = companyKnowledgePending ? 'Back' : 'Close';
5405
+ $companyKnowledgeAction.hidden = !(companyKnowledgePromotion || companyKnowledgePending);
5406
+ $companyKnowledgeAction.classList.toggle('danger', companyKnowledgePending?.kind === 'remove');
5407
+ $companyKnowledgeAction.classList.toggle('primary', companyKnowledgePending?.kind !== 'remove');
5408
+ if (companyKnowledgePending) {
5409
+ const entry = available && state.sources.find((row) => row.librarySourceId === companyKnowledgePending.librarySourceId);
5410
+ $companyKnowledgeAction.textContent = companyKnowledgePending.kind === 'accept'
5411
+ ? `${companyKnowledgePending.kind === 'accept' && entry && companyAcceptedVersion(entry, state.projectSnapshots) ? 'Update to' : 'Add'} v${entry ? entry.versions.length : ''}` : 'Remove entry';
5412
+ $companyKnowledgeAction.dataset.commandId = companyKnowledgePending.kind === 'accept'
5413
+ ? 'shell.company-accept-confirm' : 'shell.company-remove-confirm';
5414
+ } else if (companyKnowledgePromotion) {
5415
+ $companyKnowledgeAction.textContent = 'Publish';
5416
+ $companyKnowledgeAction.dataset.commandId = 'shell.company-publish';
5417
+ }
5418
+ $companyKnowledgeAction.disabled = companyKnowledgeBusy || !available;
5419
+ if (!available) $companyKnowledgeAction.dataset.blockedReason = 'Choose an available company folder first';
5420
+ else delete $companyKnowledgeAction.dataset.blockedReason;
5421
+ $companyKnowledgeDialog.setAttribute('aria-busy', String(companyKnowledgeBusy));
5422
+ }
5423
+
5424
+ async function loadCompanyKnowledge(projectId) {
5425
+ companyKnowledgeState = await api(`/api/company-knowledge?projectId=${encodeURIComponent(projectId)}`);
5426
+ return companyKnowledgeState;
5427
+ }
5428
+
5429
+ async function openCompanyKnowledge(promotion, returnFocus) {
5430
+ if (!current || !$companyKnowledgeModal) return;
5431
+ companyKnowledgeProjectId = current.id;
5432
+ companyKnowledgePromotion = promotion || null;
5433
+ companyKnowledgePending = null;
5434
+ companyKnowledgeReturnFocus = returnFocus || document.activeElement;
5435
+ companySetError('');
5436
+ $companyKnowledgeModal.classList.add('show');
5437
+ $companyKnowledgeFolder.innerHTML = '<div class="company-empty">Loading company knowledge…</div>';
5438
+ $companyKnowledgeList.innerHTML = '';
5439
+ $companyKnowledgeClose.focus({ preventScroll: true });
5440
+ try { await loadCompanyKnowledge(companyKnowledgeProjectId); }
5441
+ catch (error) { companyKnowledgeState = { configured: false, loadError: companyErrorMessage(error, 'FloLess could not load company references. Check the company folder and try again.') }; }
5442
+ if ($companyKnowledgeModal.classList.contains('show')) renderCompanyKnowledge();
5443
+ }
5444
+
5445
+ function closeCompanyKnowledge(restoreFocus = true) {
5446
+ if (!$companyKnowledgeModal || !$companyKnowledgeModal.classList.contains('show')) return;
5447
+ $companyKnowledgeModal.classList.remove('show');
5448
+ const back = companyKnowledgeReturnFocus;
5449
+ companyKnowledgeReturnFocus = null;
5450
+ companyKnowledgePromotion = null;
5451
+ companyKnowledgePending = null;
5452
+ companyKnowledgeProjectId = null;
5453
+ companySetError('');
5454
+ if (restoreFocus && back && back.isConnected) back.focus({ preventScroll: true });
5455
+ }
5456
+
5457
+ async function chooseCompanyFolder() {
5458
+ if (companyKnowledgeBusy) return;
5459
+ companyKnowledgeBusy = true; companySetError(''); renderCompanyKnowledge();
5460
+ try {
5461
+ const choice = await api('/api/company-knowledge/folder/choose', { method: 'POST', body: '{}' });
5462
+ if (!choice.cancelled) {
5463
+ await api('/api/company-knowledge/folder/select', {
5464
+ method: 'POST', body: JSON.stringify({ selectionId: choice.selectionId }),
5465
+ });
5466
+ await loadCompanyKnowledge(companyKnowledgeProjectId);
5467
+ showToast('Company knowledge folder connected', 'ok');
5468
+ }
5469
+ } catch (error) { companySetError(companyErrorMessage(error, 'FloLess could not use that company folder. Choose another folder and try again.')); }
5470
+ finally { companyKnowledgeBusy = false; renderCompanyKnowledge(); }
5471
+ }
5472
+
5473
+ async function performCompanyKnowledgeAction() {
5474
+ if (companyKnowledgeBusy || !companyKnowledgeProjectId) return;
5475
+ const state = companyKnowledgeState;
5476
+ if (!state || !state.available) return;
5477
+ companyKnowledgeBusy = true; companySetError(''); renderCompanyKnowledge();
5478
+ try {
5479
+ if (companyKnowledgePending?.kind === 'accept') {
5480
+ const entry = state.sources.find((row) => row.librarySourceId === companyKnowledgePending.librarySourceId && !row.removedAt);
5481
+ const latest = entry && entry.versions[entry.versions.length - 1];
5482
+ if (!entry || !latest) throw new Error('That company version is no longer available.');
5483
+ await api(`/api/company-knowledge/sources/${encodeURIComponent(entry.librarySourceId)}/versions/${encodeURIComponent(latest.versionId)}/accept`, {
5484
+ method: 'POST', body: JSON.stringify({ projectId: companyKnowledgeProjectId }),
5485
+ });
5486
+ companyKnowledgePending = null;
5487
+ showToast(`Added ${entry.displayName} v${entry.versions.length} to this project`, 'ok');
5488
+ } else if (companyKnowledgePending?.kind === 'remove') {
5489
+ const entry = state.sources.find((row) => row.librarySourceId === companyKnowledgePending.librarySourceId);
5490
+ await api(`/api/company-knowledge/sources/${encodeURIComponent(companyKnowledgePending.librarySourceId)}`, { method: 'DELETE' });
5491
+ companyKnowledgePending = null;
5492
+ showToast(`${entry ? entry.displayName : 'Company reference'} removed`, 'ok');
5493
+ } else if (companyKnowledgePromotion) {
5494
+ await api('/api/company-knowledge/promote', {
5495
+ method: 'POST', body: JSON.stringify({
5496
+ projectId: companyKnowledgeProjectId,
5497
+ sourceId: companyKnowledgePromotion.sourceId,
5498
+ librarySourceId: $companyPromotionLineage.value || null,
5499
+ }),
5500
+ });
5501
+ showToast('Company reference published.', 'ok');
5502
+ companyKnowledgePromotion = null;
5503
+ }
5504
+ await loadCompanyKnowledge(companyKnowledgeProjectId);
5505
+ if (current && current.id === companyKnowledgeProjectId) await renderKnowledge();
5506
+ } catch (error) { companySetError(companyErrorMessage(error)); }
5507
+ finally { companyKnowledgeBusy = false; renderCompanyKnowledge(); }
5508
+ }
5509
+
5510
+ if ($companyKnowledgeModal) {
5511
+ $companyKnowledgeModal.addEventListener('click', (event) => {
5512
+ const folder = event.target.closest('[data-company-folder-choose]');
5513
+ if (folder) { chooseCompanyFolder(); return; }
5514
+ const accept = event.target.closest('[data-company-stage-accept]');
5515
+ if (accept) { companyKnowledgePending = { kind: 'accept', librarySourceId: accept.dataset.companyStageAccept }; renderCompanyKnowledge(); $companyKnowledgeAction.focus(); return; }
5516
+ const remove = event.target.closest('[data-company-stage-remove]');
5517
+ if (remove) { companyKnowledgePending = { kind: 'remove', librarySourceId: remove.dataset.companyStageRemove }; renderCompanyKnowledge(); $companyKnowledgeAction.focus(); }
5518
+ });
5519
+ $companyKnowledgeClose.addEventListener('click', () => closeCompanyKnowledge());
5520
+ $companyKnowledgeCancel.addEventListener('click', () => {
5521
+ if (companyKnowledgePending) { companyKnowledgePending = null; companySetError(''); renderCompanyKnowledge(); }
5522
+ else closeCompanyKnowledge();
5523
+ });
5524
+ $companyKnowledgeAction.addEventListener('click', performCompanyKnowledgeAction);
5525
+ onBackdropDismiss($companyKnowledgeModal, () => closeCompanyKnowledge());
5526
+ document.addEventListener('keydown', (event) => {
5527
+ if (!$companyKnowledgeModal.classList.contains('show')) return;
5528
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeCompanyKnowledge(); return; }
5529
+ if (event.key !== 'Tab') return;
5530
+ const focusable = [...$companyKnowledgeModal.querySelectorAll('button:not([hidden]):not(:disabled), input:not([hidden]):not(:disabled), [tabindex="0"]')]
5531
+ .filter((node) => node.offsetParent !== null);
5532
+ if (!focusable.length) return;
5533
+ const first = focusable[0], last = focusable[focusable.length - 1];
5534
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
5535
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
5536
+ }, true);
5537
+ }
5538
+
3882
5539
  // ── Knowledge verbs (each captures `proj` — the user may switch projects mid-await) ──
3883
5540
  async function kbUpload(fileList) {
3884
5541
  const proj = current;
@@ -3901,9 +5558,8 @@
3901
5558
  const n = (res.sources || []).length;
3902
5559
  showToast(`Added ${n} reference${n === 1 ? '' : 's'}`, 'ok');
3903
5560
  track('kb_sources_added', { app: proj.app, n });
3904
- } catch (err) {
3905
- // The server rejects archives (xlsx/docx are zips), oversize and unknown types — say so, never swallow.
3906
- showToast('Couldn’t add: ' + ((err && err.message) || err), 'warn');
5561
+ } catch {
5562
+ showToast('Couldn’t add these references. Check the files and try again.', 'warn');
3907
5563
  }
3908
5564
  if (current === proj) renderKnowledge();
3909
5565
  }
@@ -3912,7 +5568,7 @@
3912
5568
  const proj = current;
3913
5569
  if (!proj) return;
3914
5570
  try { await api(kbUrl(proj.id, `/sources/${encodeURIComponent(sourceId)}`), { method: 'PATCH', body: JSON.stringify({ useAsKb: next }) }); }
3915
- catch (err) { showToast('Couldn’t update: ' + ((err && err.message) || err), 'warn'); }
5571
+ catch { showToast('Couldn’t update this reference. Try again.', 'warn'); }
3916
5572
  if (current === proj) renderKnowledge(); // re-render reconciles the optimistic flip either way
3917
5573
  }
3918
5574
 
@@ -3923,7 +5579,7 @@
3923
5579
  try {
3924
5580
  await api(kbUrl(proj.id, `/sources/${encodeURIComponent(sourceId)}`), { method: 'DELETE' });
3925
5581
  showToast('Reference removed', 'ok');
3926
- } catch (err) { showToast('Couldn’t remove: ' + ((err && err.message) || err), 'warn'); }
5582
+ } catch { showToast('Couldn’t remove this reference. Try again.', 'warn'); }
3927
5583
  if (current === proj) renderKnowledge();
3928
5584
  }
3929
5585
 
@@ -3937,7 +5593,7 @@
3937
5593
  if (bridge.loadRequests) await bridge.loadRequests();
3938
5594
  showToast('Organize queued for your terminal AI', 'ok');
3939
5595
  track('kb_organize_queued', { app: proj.app });
3940
- } catch (err) { showToast('Couldn’t queue organize: ' + ((err && err.message) || err), 'warn'); }
5596
+ } catch { showToast('Couldn’t queue Knowledge organization. Try again.', 'warn'); }
3941
5597
  if (current === proj) renderKnowledge();
3942
5598
  }
3943
5599
 
@@ -3960,8 +5616,8 @@
3960
5616
  const code = err && err.body && err.body.code;
3961
5617
  // already-started: the terminal AI won a fair race — not a failure; the repaint shows "Organizing…".
3962
5618
  // not-found: already gone (drained/cancelled elsewhere) — silent; the repaint shows it's cleared.
3963
- if (code === 'already-started') showToast('Organize already started — it’ll finish in your terminal', 'warn');
3964
- else if (code !== 'not-found') showToast('Couldn’t cancel: ' + ((err && err.message) || err), 'warn');
5619
+ if (code === 'already-started') showToast('Knowledge organization has already started, so it will finish in your AI app.', 'warn');
5620
+ else if (code !== 'not-found') showToast('Couldn’t cancel Knowledge organization. Try again.', 'warn');
3965
5621
  } finally {
3966
5622
  kbCancelBusy = false;
3967
5623
  // Refresh the footer Requests counter now for immediate feedback. (The guarded DELETE also
@@ -4028,7 +5684,7 @@
4028
5684
  ta.disabled = false; ta.focus(); // preserve the text + caret, return focus for a retry
4029
5685
  btn.disabled = false; btn.textContent = '✎ Adjust';
4030
5686
  kbSyncAdjustSubmit();
4031
- showToast('Couldn’t queue the adjustment: ' + msg, 'warn');
5687
+ showToast('We couldn’t save that adjustment because FloLess could not finish the request. Try again.', 'warn');
4032
5688
  }
4033
5689
  kbInvalidateRefs(); // the box stays active (focus) → next inactive tick settles the footer
4034
5690
  }
@@ -4069,6 +5725,14 @@
4069
5725
  // One delegated listener for the whole pane — the column is re-rendered wholesale on every state
4070
5726
  // change, so per-render wiring would leak handlers.
4071
5727
  $wsKnowledge.addEventListener('click', (e) => {
5728
+ const promote = e.target.closest('[data-company-promote]');
5729
+ if (promote) {
5730
+ const row = knowledgeState && knowledgeState.sources.find((source) => source.sourceId === promote.dataset.companyPromote);
5731
+ if (row) openCompanyKnowledge({ sourceId: row.sourceId, filename: row.filename || 'untitled' }, promote);
5732
+ return;
5733
+ }
5734
+ const company = e.target.closest('[data-company-open]');
5735
+ if (company) { openCompanyKnowledge(null, company); return; }
4072
5736
  const go = e.target.closest('[data-kb-remove-go]');
4073
5737
  if (go) { kbRemove(go.dataset.kbRemoveGo); return; }
4074
5738
  if (e.target.closest('.hc-cancel')) { kbCloseConfirm(); return; }
@@ -4737,14 +6401,8 @@
4737
6401
 
4738
6402
  const receiptKey = (kind) => `${current ? current.id : ''}:${kind}`;
4739
6403
 
4740
- function receiptItemText(prefix, value) {
4741
- if (typeof value === 'string') return `${prefix}: ${value}`;
4742
- if (!value || typeof value !== 'object') return `${prefix}: ${String(value)}`;
4743
- const parts = [value.id, value.code, value.message].filter((part) => typeof part === 'string' && part.trim());
4744
- if (parts.length) return `${prefix}: ${parts.join(' · ')}`;
4745
- try { return `${prefix}: ${JSON.stringify(value)}`; }
4746
- catch { return `${prefix}: detail unavailable`; }
4747
- }
6404
+ // `receiptItemText` is app.js's. The Workflows receipt popover (aware.js) and this card render
6405
+ // the SAME server receipt, and each used to carry its own identical copy of this line renderer.
4748
6406
 
4749
6407
  function receiptSummary(receipt, kind) {
4750
6408
  if (!receipt || !receipt.counts) return null;
@@ -5261,7 +6919,7 @@
5261
6919
  for (let attempt = 0; attempt < 2; attempt++) {
5262
6920
  let sources;
5263
6921
  try { sources = await captureSelectedExportSources(projectId, remainingHosts.length, sourceSelector); }
5264
- catch (error) { showToast((error && error.message) || 'Couldn’t freeze the export source.', 'warn'); return; }
6922
+ catch (error) { showToast('We couldn’t prepare this export because FloLess could not save its source. Try again.', 'warn'); return; }
5265
6923
  const handles = sources.map((source) => source.handleId);
5266
6924
  let reviews;
5267
6925
  try {
@@ -5294,7 +6952,7 @@
5294
6952
  return;
5295
6953
  }
5296
6954
  if (attempt === 0 && error && error.body && ['host-bake-confirmation-stale', 'host-bake-preflight-required', 'stale-selection'].includes(error.body.code)) continue;
5297
- showToast((error && error.message) || 'Couldn’t review the CAD send.', 'warn');
6955
+ showToast('We couldn’t review this CAD send because FloLess could not load it. Try again.', 'warn');
5298
6956
  return;
5299
6957
  }
5300
6958
  // A stale first continuation refreshes the open project's approval state before this retry.
@@ -5975,10 +7633,16 @@
5975
7633
  */
5976
7634
  function markScrollable(el) {
5977
7635
  if (!el) return;
5978
- if (el.scrollHeight > el.clientHeight) el.setAttribute('tabindex', '0');
7636
+ if (el.scrollHeight - el.clientHeight > 1) el.setAttribute('tabindex', '0');
5979
7637
  else el.removeAttribute('tabindex');
5980
7638
  }
5981
7639
 
7640
+ function wireStageGuidanceScrollability() {
7641
+ if (!$stageGuidance || typeof ResizeObserver !== 'function') return;
7642
+ const observer = new ResizeObserver(() => markScrollable($stageGuidance));
7643
+ observer.observe($stageGuidance);
7644
+ }
7645
+
5982
7646
  // A resize is not a repaint, but it is the other thing that decides whether these lists overflow:
5983
7647
  // narrow the window and a receipt's counts wrap onto another line. Without this, a list that
5984
7648
  // started to scroll because the window changed would keep the answer it was given at paint time.
@@ -5988,6 +7652,7 @@
5988
7652
  clearTimeout(scrollMarkTimer);
5989
7653
  scrollMarkTimer = setTimeout(() => {
5990
7654
  if (!$wsExports.hidden) $wsExports.querySelectorAll('.e-renders').forEach(markScrollable);
7655
+ markScrollable($stageGuidance);
5991
7656
  }, 150);
5992
7657
  });
5993
7658
 
@@ -6283,7 +7948,7 @@
6283
7948
  } else {
6284
7949
  const err = exportResult.reason;
6285
7950
  // Surface the load failure — don't let it read as "nothing exported yet" (a lie).
6286
- showToast('Couldn’t load export status: ' + (err && err.message || err), 'warn');
7951
+ showToast('We couldn’t load the export status because FloLess could not reach it. Try again.', 'warn');
6287
7952
  state = null;
6288
7953
  }
6289
7954
  /*
@@ -6353,7 +8018,7 @@
6353
8018
  // the user as a failed export that had in fact just succeeded. The wrapper never rejects.
6354
8019
  if (current && current.id === projectId) await safeRenderExports('after exporting the raw package');
6355
8020
  } catch (error) {
6356
- showToast('Raw export failed: ' + ((error && error.message) || error), 'warn');
8021
+ showToast('We couldn’t export this file because FloLess could not finish preparing it. Try again.', 'warn');
6357
8022
  }
6358
8023
  }
6359
8024
 
@@ -6401,7 +8066,7 @@
6401
8066
 
6402
8067
  let capturedSource;
6403
8068
  try { capturedSource = await captureSelectedExportSource(projectId); }
6404
- catch (error) { showToast((error && error.message) || 'Couldn’t freeze the export source.', 'warn'); return; }
8069
+ catch (error) { showToast('We couldn’t prepare this export because FloLess could not save its source. Try again.', 'warn'); return; }
6405
8070
  exportBusy.add(busyKey);
6406
8071
  // The delegated click can report BODY as active by the time this synchronous repaint runs.
6407
8072
  // Carry the activated kind through the first replacement explicitly; later repaints infer
@@ -6580,7 +8245,7 @@
6580
8245
  // the copy has to know which it is — "that send" about an IFC export is a sentence about
6581
8246
  // something that never happened.
6582
8247
  if (projectId && !summary) {
6583
- showToast(String(kind).startsWith('send:')
8248
+ showToast(kind.startsWith('send:')
6584
8249
  ? 'That send described an earlier version of this project — approve again to send it.'
6585
8250
  : 'That export described an earlier version of this project — approve again to export it.',
6586
8251
  'info');
@@ -6634,7 +8299,7 @@
6634
8299
  (res.readiness && res.readiness.message) || 'the agent did not become usable.'}`,
6635
8300
  res.readiness && res.readiness.ok ? 'ok' : 'warn');
6636
8301
  } catch (err) {
6637
- showToast(err && err.message ? err.message : String(err), 'warn');
8302
+ showToast('We couldn’t finish that because FloLess could not save the change. Try again.', 'warn');
6638
8303
  // Leaving `checking` in place would strand the card disabled as "Checking…" with no
6639
8304
  // recovery button until the tab is reopened — a failed install that hides its own retry.
6640
8305
  renderReadinessState = {
@@ -6803,6 +8468,9 @@
6803
8468
  let revCardReq = null;
6804
8469
  let revisionPoll = null;
6805
8470
  let revisionGen = 0; // newest-wins epoch for overlapping card renders — see renderRevisionCard
8471
+ // Newest request-list SUCCESS by start generation. A later success proves contact after an older
8472
+ // failure began; a slow success still clears an outage when it eventually settles.
8473
+ let revisionRequestsSuccessGen = 0;
6806
8474
  let revisionOwnerGen = 0; // bumped only when navigation retires actions owned by the current project
6807
8475
  let revisionAttachGen = 0; // newest Attach owns its delayed copy/modal completion within that project
6808
8476
  let revRequestsFailed = false; // one log per outage, not one per 3-second poll tick
@@ -6842,6 +8510,7 @@
6842
8510
  revCardReq = null;
6843
8511
  $revisionCard._renderKey = '';
6844
8512
  revisionGen++; // voids any render still in flight for the project being left
8513
+ revisionRequestsSuccessGen = revisionGen; // old same-id failures cannot cross a close/re-open boundary
6845
8514
  revisionOwnerGen++; // voids Attach/Copy work, without letting a routine poll do so
6846
8515
  stopRevisionPoll();
6847
8516
  $revisionCard.hidden = true;
@@ -6909,8 +8578,16 @@
6909
8578
  res = await api(`/api/projects/${encodeURIComponent(proj.id)}/revision-requests`, {
6910
8579
  method: 'POST', body: JSON.stringify({ appId: proj.app, snapshots }),
6911
8580
  });
6912
- } catch (err) { if (ownsAttach()) showToast('Attach failed: ' + ((err && err.message) || err), 'warn'); return; }
8581
+ } catch (err) { if (ownsAttach()) showToast('We couldn’t attach that file because FloLess could not save it. Try again.', 'warn'); return; }
6913
8582
  const req = res && res.request;
8583
+ if (!ownsAttach()) {
8584
+ if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
8585
+ return;
8586
+ }
8587
+ // The POST created a new authoritative request. Fence every request-list snapshot that began before
8588
+ // it, including one that settles while the best-effort clipboard copy below is still pending.
8589
+ revisionGen += 1;
8590
+ revisionRequestsSuccessGen = revisionGen;
6914
8591
  // Copy the paste-ready instruction so the user can hand it to their terminal AI (best-effort).
6915
8592
  const copied = await copyAttachedRevision(req, ownsAttach);
6916
8593
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {}); // refresh the footer Requests popover
@@ -6936,10 +8613,11 @@
6936
8613
  if (req.preparationState === 'blocked') {
6937
8614
  const dot = revEl('span', 'wrc-warn-ico', '⚠'); dot.setAttribute('aria-hidden', 'true');
6938
8615
  const txt = revEl('span', 'wrc-text');
6939
- txt.appendChild(revEl('b', null, 'Steel drawing preparation needs operator repair.'));
6940
- txt.appendChild(document.createTextNode(' FloLess could not verify that the earlier extractor stopped. Your drawings are still attached. Restart FloLess; if this remains blocked, open Requests and follow the operator repair in Technical details.'));
8616
+ txt.appendChild(revEl('b', null, 'FloLess could not finish drawing preparation.'));
8617
+ txt.appendChild(document.createTextNode(' FloLess could not confirm that an earlier drawing reader stopped. Your drawings are still attached. Restart FloLess; if this remains blocked, open Requests and follow the detailed instructions.'));
6941
8618
  return [dot, txt];
6942
8619
  }
8620
+ // Defensive fallback: initial reads retire this card only after the replacement strip paints.
6943
8621
  if (req.preparationState === 'manifest-published' && !req.prepassReady) {
6944
8622
  const dot = revEl('span', 'wrc-dot'); dot.setAttribute('aria-hidden', 'true');
6945
8623
  const txt = revEl('span', 'wrc-text');
@@ -6954,10 +8632,9 @@
6954
8632
  txt.appendChild(document.createTextNode(' Return to the same terminal AI session that prepared this Drawing Filter and tell it to continue the drawing read.'));
6955
8633
  return [dot, txt];
6956
8634
  }
8635
+ // Defensive fallback for a strip that could not paint; ordinary initial reads put this action in
8636
+ // the single surviving guidance band, while revised reads continue to use their own card.
6957
8637
  if (req.prepassReady) {
6958
- // The terminal AI has completed the deterministic pre-read; it is now waiting on the real Filter
6959
- // Save checkpoint below, not on another pasted instruction. A static dot avoids claiming work is
6960
- // still running, and the real action only focuses the existing Filter iframe — it never fakes Save.
6961
8638
  const dot = revEl('span', 'wrc-dot'); dot.setAttribute('aria-hidden', 'true');
6962
8639
  const txt = revEl('span', 'wrc-text');
6963
8640
  txt.appendChild(revEl('b', null, 'Drawing Filter is ready.'));
@@ -7096,15 +8773,22 @@
7096
8773
  }
7097
8774
 
7098
8775
  async function dismissFailedRevision(req) {
8776
+ const proj = current;
8777
+ const projectGeneration = revisionOwnerGen;
8778
+ const ownsDismiss = () => !!proj && current?.id === proj.id && revisionOwnerGen === projectGeneration;
7099
8779
  try { await api(`/api/requests/${encodeURIComponent(req.id)}`, { method: 'DELETE' }); }
7100
8780
  catch (error) {
7101
- showToast((error && error.message) || 'FloLess could not dismiss this drawing read.', 'warn');
8781
+ if (!ownsDismiss()) return;
8782
+ showToast('We couldn’t dismiss this drawing because FloLess could not save the change. Try again.', 'warn');
7102
8783
  if (bridge.loadRequests) await bridge.loadRequests().catch(() => {});
7103
8784
  await renderRevisionCard();
7104
8785
  return;
7105
8786
  }
7106
- lastRevState = 'none';
7107
8787
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
8788
+ if (!ownsDismiss()) return;
8789
+ revisionGen += 1;
8790
+ revisionRequestsSuccessGen = revisionGen;
8791
+ lastRevState = 'none';
7108
8792
  await renderRevisionCard();
7109
8793
  }
7110
8794
 
@@ -7116,12 +8800,15 @@
7116
8800
  // check passes and the stale render carries on. Bumping per render also settles two renders racing
7117
8801
  // for one project (the 3s poll can start a second while the first is still out): newest wins.
7118
8802
  const gen = ++revisionGen;
8803
+ const ownerGen = revisionOwnerGen;
7119
8804
  const proj = current;
7120
8805
  if (!proj) { $revisionCard.hidden = true; return; }
8806
+ if (wsDescOf(proj)?.serverAuthorizedOnly === true) { $revisionCard.hidden = true; return; }
7121
8807
  // Keep the last known card painted while the request list is reloading. Switching to another
7122
8808
  // stage and back must not turn a long-running terminal read into a blank strip for the few
7123
8809
  // seconds before /api/requests answers again.
7124
- if (currentStep === 'drawings' && revCardReq && lastRevState !== 'none') $revisionCard.hidden = false;
8810
+ if (currentStep === 'drawings' && revCardReq && lastRevState !== 'none'
8811
+ && $revisionCard.firstChild) $revisionCard.hidden = false;
7125
8812
  let reqs = [];
7126
8813
  // ONCE PER OUTAGE, not once per tick. This runs on a 3-second poll, so an unguarded log turns a
7127
8814
  // server restart into a wall of red — the same "every open logs an error" noise #600 was written
@@ -7130,17 +8817,34 @@
7130
8817
  try {
7131
8818
  const b = await api('/api/requests');
7132
8819
  reqs = Array.isArray(b) ? b : (b.requests || []);
8820
+ // Every owned success is fresh evidence of server contact, even if a later-started poll is in
8821
+ // flight or has failed. The route can legitimately outlast the 3-second polling interval.
8822
+ if (!current || current.id !== proj.id || ownerGen !== revisionOwnerGen) return;
8823
+ const recoveredFromOutage = revRequestsFailed;
7133
8824
  revRequestsFailed = false;
8825
+ // A delayed older success proves connectivity, but its request snapshot must not overwrite data
8826
+ // from a later-started success. Re-project the cached snapshot only when connectivity changed.
8827
+ if (gen < revisionRequestsSuccessGen) {
8828
+ if (recoveredFromOutage) applyStageGating();
8829
+ return;
8830
+ }
8831
+ revisionRequestsSuccessGen = Math.max(revisionRequestsSuccessGen, gen);
7134
8832
  } catch (e) {
8833
+ // The request that failed may belong to a project the user has already left. Do not let its
8834
+ // late failure mark the newly opened project's server state as disconnected. For the same
8835
+ // project, however, a newer in-flight poll has not disproved the outage: accept the failure
8836
+ // unless a later-started request-list fetch has already succeeded. Ownership also fences the
8837
+ // same project being closed and reopened while this fetch was in flight.
8838
+ if (!current || current.id !== proj.id || ownerGen !== revisionOwnerGen
8839
+ || gen < revisionRequestsSuccessGen) return;
7135
8840
  if (workspacePageUnloading) return;
7136
8841
  if (!revRequestsFailed) console.error('[workspaces] could not load requests for the revision card', e);
7137
8842
  revRequestsFailed = true;
8843
+ // Re-project the last server-owned progress so an outage can age an active heartbeat into the
8844
+ // truthful waiting state instead of leaving motion running indefinitely.
8845
+ applyStageGating();
7138
8846
  return;
7139
8847
  }
7140
- // Superseded while the requests were in flight. Everything past here reads the project and paints
7141
- // the ONE shared card, so resuming would either throw on a null `current` (the back-to-projects
7142
- // button, mid-poll) or paint the old project's revision state over the newly opened one.
7143
- if (gen !== revisionGen || !current || current.id !== proj.id) return;
7144
8848
  const mine = reqs.filter((r) => r && r.type === 'revision-read' && r.project === proj.id);
7145
8849
  // One project can retain an old failed request after the user follows its recovery instruction and
7146
8850
  // attaches the set again. The request list is durable oldest-first; the newest lifecycle is the one
@@ -7169,14 +8873,25 @@
7169
8873
  if (lastRevState === 'pending' && state === 'none') {
7170
8874
  let vr;
7171
8875
  try { vr = await api(`/api/projects/${encodeURIComponent(proj.id)}/versions`); }
7172
- catch (e) { console.error('[workspaces] could not read versions to confirm the revision read', e); return; }
8876
+ catch (e) {
8877
+ // A retired completion probe is not a live failure: a newer successful request snapshot or a
8878
+ // project-lifetime change already owns the UI. Page teardown aborts fetches by design.
8879
+ if (!current || current.id !== proj.id || ownerGen !== revisionOwnerGen
8880
+ || gen < revisionRequestsSuccessGen
8881
+ || (workspacePageUnloading && e instanceof TypeError && e.message === 'Failed to fetch')) return;
8882
+ console.error('[workspaces] could not read versions to confirm the revision read', e);
8883
+ return;
8884
+ }
7173
8885
  // ^ transient — leave lastRevState 'pending'; the poll retries next tick.
7174
8886
  // THIS one is not transient and does not retry: `openProject`/`closeProject` have already reset
7175
8887
  // `lastRevState` and stopped the poll, so the pending→none EDGE below is gone for good and the
7176
8888
  // completion toast for `proj` is DROPPED, not deferred. That is the deliberate trade — the
7177
8889
  // alternative, which is what shipped before, was to fire "Revision read complete" while another
7178
8890
  // project is on screen and clear ITS `approvedAt`, attributing one project's read to another.
7179
- if (gen !== revisionGen || !current || current.id !== proj.id) return;
8891
+ // The request-list snapshot above was authoritative when accepted. A later-started FAILURE does
8892
+ // not revoke that success; only navigation or a later-started SUCCESS may supersede its completion.
8893
+ if (!current || current.id !== proj.id || ownerGen !== revisionOwnerGen
8894
+ || gen < revisionRequestsSuccessGen) return;
7180
8895
  const tip = (vr.versions || [])[0];
7181
8896
  // A baseline captured in ANOTHER project says nothing about this one's ledger, and reading it as
7182
8897
  // though it did suppressed real completions (attach at head 12 there, a read commits at 4 here —
@@ -7216,7 +8931,8 @@
7216
8931
  if (state === 'none') {
7217
8932
  revCardReq = null;
7218
8933
  syncDrawingRevisionRequest('');
7219
- stopRevisionPoll(); $revisionCard.hidden = true; $revisionCard.replaceChildren(); applyStageGating(); return;
8934
+ stopRevisionPoll(); $revisionCard.hidden = true; $revisionCard.replaceChildren();
8935
+ $revisionCard.className = 'ws-revision-card'; applyStageGating(); return;
7220
8936
  }
7221
8937
  // Every durable lifecycle keeps polling until its request disappears. Failed and staged cards can
7222
8938
  // both change from another tab (Attach again, Clear, or a review action); stopping either interval
@@ -7238,10 +8954,19 @@
7238
8954
  // under it, the modal's own confirm learns that from the server and closes; the next tick then
7239
8955
  // paints the truth.
7240
8956
  if (revReviewState || revDiscardState) return;
8957
+ // Once the Filter is saved, the stage strip above owns Done / Now / Next. Keeping this static
8958
+ // card too produced the two contradictory-looking status bands in the reported UI.
8959
+ if (retireRevisionCardForStrip(pending)) return;
7241
8960
  const cardKey = `${state}:${revCardReq ? revCardReq.id : ''}:${pending && pending.filterCheckpointCurrent ? 'filter-saved' : pending && pending.prepassReady ? 'filter-ready' : 'read-pending'}:${pending && pending.run ? pending.run.state || '' : ''}`
7242
8961
  + (pending ? `:${pending.preparationState || ''}:${pending.preparationRetryable === true}:${pending.canRun === true}:${pending.canCopy === true}:${pending.canClear === true}:${pending.clearWhy || ''}` : '')
7243
8962
  + (staged ? `:${staged.baseVersion}:${staged.headVersion}:${staged.stageId || ''}:${staged.canDiscardRevision === true}:${staged.discardState || ''}:${staged.discardWhy || ''}:${staged.canClear === true}:${staged.clearWhy || ''}:${unavailableRevisionReviewStages.has(staged.stageId)}` : '');
7244
- if ($revisionCard._renderKey === cardKey && !$revisionCard.hidden) return; // preserve focus across the 3 s poll
8963
+ // The key below exists to preserve focus in the card across the three-second poll. It says
8964
+ // nothing about the strip, whose progress record advances on its own revision, so the strip is
8965
+ // repainted before returning — letting this short-circuit reach it froze live progress entirely.
8966
+ if ($revisionCard._renderKey === cardKey && !$revisionCard.hidden) {
8967
+ applyStageGating();
8968
+ return; // preserve focus across the 3 s poll
8969
+ }
7245
8970
  const restoreFocus = typeof document !== 'undefined' && $revisionCard.contains(document.activeElement);
7246
8971
  $revisionCard._renderKey = cardKey;
7247
8972
  $revisionCard.className = 'ws-revision-card state-' + state
@@ -7303,6 +9028,9 @@
7303
9028
  const savedEtag = String(notice?.savedEtag || '');
7304
9029
  if (!current || current.id !== projectId || !requestId || !savedEtag) return false;
7305
9030
  revisionGen += 1;
9031
+ // A request-list success that began before this exact Save may still settle afterwards. Let it
9032
+ // prove connectivity, but fence its older checkpoint snapshot from undoing the adopted receipt.
9033
+ revisionRequestsSuccessGen = revisionGen;
7306
9034
  syncDrawingRevisionRequest(requestId, savedEtag);
7307
9035
  void renderRevisionCard();
7308
9036
  return true;
@@ -7382,11 +9110,30 @@
7382
9110
  && !!copyButton?.isConnected;
7383
9111
  // "no instruction body" must not be reported as "copy blocked": that sends the user to the
7384
9112
  // Requests panel, where the ⧉ gives the real reason and contradicts this toast.
7385
- const res = await bridge.copyRequest(req, ownsCopy);
7386
- if (res === 'stale' || !ownsCopy()) return;
7387
- if (res === 'ok') showToast('Instruction copied', 'ok');
7388
- else if (res === 'empty') showToast('Nothing to copy — this request has no instruction', 'err');
7389
- else showToast('Copy blocked — use the Requests panel', 'warn');
9113
+ const previousTip = copyButton?.dataset.tip || '';
9114
+ const previousLabel = copyButton?.getAttribute('aria-label') || '';
9115
+ if (copyButton) {
9116
+ copyButton.disabled = true;
9117
+ copyButton.setAttribute('aria-busy', 'true');
9118
+ copyButton.dataset.tip = 'Copying the instruction…';
9119
+ copyButton.setAttribute('aria-label', 'Copying the instruction');
9120
+ }
9121
+ try {
9122
+ const res = await bridge.copyRequest(req, ownsCopy);
9123
+ if (res === 'stale' || !ownsCopy()) return;
9124
+ if (res === 'ok') showToast('Instruction copied', 'ok');
9125
+ else if (res === 'empty') showToast('Nothing to copy — this request has no instruction', 'err');
9126
+ else showToast('Copy blocked — use the Requests panel', 'warn');
9127
+ } finally {
9128
+ if (copyButton) {
9129
+ copyButton.disabled = false;
9130
+ copyButton.removeAttribute('aria-busy');
9131
+ if (previousTip) copyButton.dataset.tip = previousTip;
9132
+ else delete copyButton.dataset.tip;
9133
+ if (previousLabel) copyButton.setAttribute('aria-label', previousLabel);
9134
+ else copyButton.removeAttribute('aria-label');
9135
+ }
9136
+ }
7390
9137
  }
7391
9138
 
7392
9139
  $revisionCard.addEventListener('click', async (e) => {
@@ -7405,6 +9152,8 @@
7405
9152
  await dismissFailedRevision(req);
7406
9153
  }
7407
9154
  });
9155
+ wireStageGuidanceFilterAction();
9156
+ wireStageGuidanceScrollability();
7408
9157
 
7409
9158
  // ── Revision review (unit 5, P6e) ───────────────────────────────────────────────
7410
9159
  // The human decides what a re-read may change. The server has already taken the half that cannot
@@ -7548,11 +9297,11 @@
7548
9297
 
7549
9298
  const KIND_LABEL = {
7550
9299
  'member-added': 'Member added', 'provisional-member-added': 'Source-view member', 'provisional-group-refreshed': 'Placement evidence refreshed', 'member-removed': 'Member removed', 'member-changed': 'Member changed',
7551
- 'plan-added': 'Sheet added', 'plan-changed': 'Sheet changed',
9300
+ 'plan-added': 'Sheet added', 'plan-changed': 'Sheet changed', 'registration-completed': 'View registered',
7552
9301
  };
7553
9302
  const KIND_CLASS = {
7554
9303
  'member-added': 'k-added', 'provisional-member-added': 'k-changed', 'provisional-group-refreshed': 'k-changed', 'member-removed': 'k-removed', 'member-changed': 'k-changed',
7555
- 'plan-added': 'k-added', 'plan-changed': 'k-changed', 'model-changed': 'k-changed',
9304
+ 'plan-added': 'k-added', 'plan-changed': 'k-changed', 'model-changed': 'k-changed', 'registration-completed': 'k-changed',
7556
9305
  };
7557
9306
  /**
7558
9307
  * ROOT fields a revision read may propose, and how to name one (P7c-2).
@@ -7635,7 +9384,16 @@
7635
9384
  const label = revEl('label', 'rev-check');
7636
9385
  const box = document.createElement('input');
7637
9386
  box.type = 'checkbox'; box.dataset.revbucket = bucket; box.dataset.revidx = String(idx);
7638
- box.setAttribute('aria-labelledby', `${id}-title`);
9387
+ if (p.kind === 'registration-completed') {
9388
+ const affected = Number.isInteger(p.affectedCount) ? p.affectedCount : 0;
9389
+ const view = p.viewLabel || p.viewId || p.sheet || 'this view';
9390
+ box.checked = true;
9391
+ box.dataset.commandId = `shell.revision-registration-complete#${view}`;
9392
+ box.dataset.commandInstanceLabel = view;
9393
+ box.setAttribute('aria-label', `Register ${view} and promote ${affected} affected ${affected === 1 ? 'member' : 'members'}`);
9394
+ } else {
9395
+ box.setAttribute('aria-labelledby', `${id}-title`);
9396
+ }
7639
9397
  label.appendChild(box);
7640
9398
  const main = revEl('div', 'rev-row-main');
7641
9399
  const head = revEl('div', 'rev-row-head');
@@ -7707,6 +9465,15 @@
7707
9465
  note.appendChild(document.createTextNode(' is positioned against this grid. Accepting replaces the whole grid, not only the lines shown above.'));
7708
9466
  desc.push(note);
7709
9467
  }
9468
+ } else if (p.kind === 'registration-completed') {
9469
+ const affected = Number.isInteger(p.affectedCount) ? p.affectedCount : 0;
9470
+ const view = p.viewLabel || p.viewId || p.sheet || 'this view';
9471
+ const note = revEl('div', 'rev-row-note');
9472
+ note.appendChild(document.createTextNode('Accepting registers '));
9473
+ note.appendChild(revEl('b', null, view));
9474
+ note.appendChild(document.createTextNode(` and moves ${affected} source-view ${affected === 1 ? 'member' : 'members'} into the physical model in one step.`));
9475
+ desc.push(note);
9476
+ desc.push(revEl('div', 'rev-row-sub', 'The exact drawing observations, endpoint lineage, and member references stay attached to the same member ids.'));
7710
9477
  } else if ((p.kind === 'provisional-member-added' || p.kind === 'provisional-group-refreshed') && p.member) {
7711
9478
  const sub = memberHeadline(p.member);
7712
9479
  if (sub) desc.push(revEl('div', 'rev-row-sub', sub));
@@ -8026,6 +9793,39 @@
8026
9793
  $revReviewConfirm.hidden = true;
8027
9794
  }
8028
9795
 
9796
+ function renderRevisionForwardConflicts(st, conflicts) {
9797
+ st.forwardConflicts = conflicts;
9798
+ st.forwardConflictChoices = st.forwardConflictChoices || {};
9799
+ $revReviewChanged.replaceChildren();
9800
+ $revReviewChanged.appendChild(revEl('b', null, 'Newer approved work overlaps this drawing read.'));
9801
+ $revReviewChanged.appendChild(document.createTextNode(' Choose which value wins at every path. Nothing is applied until all overlaps are decided and you press Apply again.'));
9802
+ for (const conflict of conflicts) {
9803
+ const row = revEl('div', 'rev-forward-conflict');
9804
+ row.appendChild(revEl('span', 'rev-forward-path', conflict.path));
9805
+ const actions = revEl('span', 'rev-forward-actions');
9806
+ for (const [choice, label] of [['draft', 'Use drawing read'], ['latest', 'Keep approved value']]) {
9807
+ const button = revEl('button', `btn-mini${st.forwardConflictChoices[conflict.path] === choice ? ' selected' : ''}`, label);
9808
+ button.type = 'button';
9809
+ button.dataset.revForwardPath = conflict.path;
9810
+ button.dataset.revForwardChoice = choice;
9811
+ button.dataset.commandId = choice === 'draft' ? 'shell.revision-forward-draft' : 'shell.revision-forward-latest';
9812
+ button.setAttribute('aria-pressed', String(st.forwardConflictChoices[conflict.path] === choice));
9813
+ actions.appendChild(button);
9814
+ }
9815
+ row.appendChild(actions);
9816
+ $revReviewChanged.appendChild(row);
9817
+ }
9818
+ $revReviewChanged.dataset.kind = 'forward-conflicts';
9819
+ $revReviewChanged.hidden = false;
9820
+ $revReviewConfirm.disabled = conflicts.some((conflict) => !st.forwardConflictChoices[conflict.path]);
9821
+ }
9822
+
9823
+ function revisionForwardConflictsForUi(readOnly, summary, moveForward) {
9824
+ if (readOnly || summary?.rfiSelection?.decision === 'required'
9825
+ || !Array.isArray(moveForward?.conflicts) || moveForward.conflicts.length === 0) return null;
9826
+ return moveForward.conflicts;
9827
+ }
9828
+
8029
9829
  function renderRevisionRfiResult(result) {
8030
9830
  const outcomes = Array.isArray(result.rfis) ? result.rfis : [];
8031
9831
  const unasked = Array.isArray(result.unaskedRfis) ? result.unaskedRfis : [];
@@ -8159,7 +9959,7 @@
8159
9959
  // card token. Temporary read/recovery errors use a different code and remain retryable.
8160
9960
  unavailableRevisionReviewStages.add(err.body.stageId);
8161
9961
  }
8162
- showToast('Could not load the review: ' + ((err && err.message) || err), 'warn');
9962
+ showToast('We couldn’t load this review because FloLess could not reach it. Try again.', 'warn');
8163
9963
  renderRevisionCard();
8164
9964
  return;
8165
9965
  } finally {
@@ -8192,16 +9992,23 @@
8192
9992
  // the arm that still had it backwards. `revReviewState` is what makes `renderRevisionCard` skip its
8193
9993
  // repaint, so setting it first and then throwing inside `renderReview` left the guard latched with
8194
9994
  // no modal on screen: the card would never repaint again for the life of the page.
8195
- $revReviewTitle.textContent = readOnly ? 'This read is out of date' : 'Review this read';
9995
+ const moveForward = body.moveForward && Number.isInteger(body.moveForward.toVersion) ? body.moveForward : null;
9996
+ $revReviewTitle.textContent = readOnly ? 'This read is out of date' : moveForward ? 'Review this read on the latest model' : 'Review this read';
8196
9997
  $revReviewSub.textContent = readOnly
8197
9998
  ? `This read started from v${reviewRequest.baseVersion}, but the project is now at v${reviewRequest.headVersion}. It can’t be applied to the current model. The proposal below is for reference only.`
8198
- : 'Nothing is applied until you confirm. Everything starts unticked — tick what this read may change.';
9999
+ : moveForward
10000
+ ? `This read started from v${moveForward.fromVersion}. Its non-overlapping changes can be applied on top of approved v${moveForward.toVersion}; decide every overlap before applying.`
10001
+ : 'Nothing is applied until you confirm. Registration rows start selected; tick any other changes you want, and clear any registration this read may not change.';
8199
10002
  $revReviewChanged.hidden = true;
8200
10003
  delete $revReviewChanged.dataset.kind;
8201
10004
  renderReview(summary, { readOnly });
8202
10005
  revReviewState = { projectId, requestId: req.id, stageId: summary.stageId, summary, request: reviewRequest, stale: readOnly, returnFocus };
8203
10006
  $revReviewConfirm.hidden = readOnly;
8204
10007
  if (!readOnly && summary.rfiSelection?.decision === 'required') showRequiredRfiSelection(summary);
10008
+ else {
10009
+ const forwardConflicts = revisionForwardConflictsForUi(readOnly, summary, moveForward);
10010
+ if (forwardConflicts) renderRevisionForwardConflicts(revReviewState, forwardConflicts);
10011
+ }
8205
10012
  $revReviewDiscard.hidden = !canDiscardRevision(reviewRequest);
8206
10013
  $revReview.classList.add('show');
8207
10014
  const first = $revReviewBody.querySelector('input[type="checkbox"]');
@@ -8275,6 +10082,7 @@
8275
10082
  async function confirmRevisionDiscard() {
8276
10083
  const st = revDiscardState;
8277
10084
  if (!st || st.terminal) return;
10085
+ const projectGeneration = revisionOwnerGen;
8278
10086
  $revDiscardError.hidden = true;
8279
10087
  $revDiscardDialog.setAttribute('aria-busy', 'true');
8280
10088
  $revDiscardConfirm.disabled = true;
@@ -8312,6 +10120,13 @@
8312
10120
  }
8313
10121
  return;
8314
10122
  }
10123
+ if (!current || current.id !== st.projectId || revisionOwnerGen !== projectGeneration) {
10124
+ if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
10125
+ return;
10126
+ }
10127
+ // The server removed the staged request. Retire every snapshot that began before that mutation.
10128
+ revisionGen += 1;
10129
+ revisionRequestsSuccessGen = revisionGen;
8315
10130
  const reviewWasOpen = st.reviewWasOpen;
8316
10131
  lastRevState = 'none';
8317
10132
  closeRevisionDiscard(false, false);
@@ -8327,6 +10142,7 @@
8327
10142
  async function confirmRevisionReview() {
8328
10143
  const st = revReviewState;
8329
10144
  if (!st || st.stale || $revReview.hasAttribute('aria-busy')) return;
10145
+ const projectGeneration = revisionOwnerGen;
8330
10146
  const accept = { proposals: [], bindingProposals: [] };
8331
10147
  for (const box of $revReviewBody.querySelectorAll('input[type="checkbox"]:checked')) {
8332
10148
  const bucket = box.dataset.revbucket;
@@ -8357,7 +10173,7 @@
8357
10173
  let res;
8358
10174
  try {
8359
10175
  res = await api(`/api/projects/${encodeURIComponent(st.projectId)}/revision-read/confirm`, {
8360
- method: 'POST', body: JSON.stringify({ requestId: st.requestId, stageId: st.stageId, accept }),
10176
+ method: 'POST', body: JSON.stringify({ requestId: st.requestId, stageId: st.stageId, accept, conflicts: st.forwardConflictChoices || {} }),
8361
10177
  });
8362
10178
  } catch (err) {
8363
10179
  // THE MODEL MOVED WHILE THE USER WAS READING. The server has already re-staged and handed back the
@@ -8394,6 +10210,10 @@
8394
10210
  focusCloseAfterBusy = true;
8395
10211
  return;
8396
10212
  }
10213
+ if (err && err.body && err.body.code === 'revision-forward-conflicts' && Array.isArray(err.body.conflicts)) {
10214
+ renderRevisionForwardConflicts(st, err.body.conflicts);
10215
+ return;
10216
+ }
8397
10217
  const fresh = err && err.body && err.body.staged;
8398
10218
  if (fresh) {
8399
10219
  // RENDER FIRST, THEN adopt the new stage. The order matters on the failure path review found:
@@ -8413,10 +10233,18 @@
8413
10233
  }
8414
10234
  return;
8415
10235
  }
8416
- showToast('Could not apply: ' + ((err && err.message) || err), 'warn');
10236
+ showToast('We couldn’t apply that change because FloLess could not save it. Try again.', 'warn');
8417
10237
  closeRevReview(); // repaints the card itself
8418
10238
  return;
8419
10239
  }
10240
+ if (!current || current.id !== st.projectId || revisionOwnerGen !== projectGeneration) {
10241
+ if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
10242
+ return;
10243
+ }
10244
+ // Confirm committed the read and retired its request. Older request-list snapshots cannot own
10245
+ // the card after this boundary, even while the result modal remains open.
10246
+ revisionGen += 1;
10247
+ revisionRequestsSuccessGen = revisionGen;
8420
10248
  // Settle the surrounding state BEFORE closing, because closing is what repaints the card now —
8421
10249
  // `lastRevState` in particular, or the repaint would read the old value and re-run the
8422
10250
  // completion check against a request confirm has already deleted.
@@ -8442,13 +10270,14 @@
8442
10270
  renderRevisionRfiResult(res);
8443
10271
  revReviewState = { ...st, terminal: true };
8444
10272
  $revReviewCancel.dataset.commandId = 'shell.dialog-close#the revision result';
8445
- // Publish the terminal dialog identity before refreshing any surrounding client state. The
8446
- // refresh can reload the model iframe, whose load boundary settles focus below.
8447
10273
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
8448
10274
  focusCloseAfterBusy = true;
8449
10275
  } finally {
8450
10276
  // Always, on every path including a throw from the re-render above.
8451
10277
  setRevisionReviewBusy(false);
10278
+ if (revReviewState?.forwardConflicts) {
10279
+ $revReviewConfirm.disabled = revReviewState.forwardConflicts.some((conflict) => !revReviewState.forwardConflictChoices?.[conflict.path]);
10280
+ }
8452
10281
  $revReviewConfirm.removeAttribute('aria-busy');
8453
10282
  $revReviewConfirm.textContent = confirmLabel;
8454
10283
  if (focusCloseAfterBusy) {
@@ -8489,6 +10318,18 @@
8489
10318
  // the one where a stale explanation misleads most.
8490
10319
  clearBlockedBanner();
8491
10320
  });
10321
+ $revReviewChanged.addEventListener('click', (e) => {
10322
+ if ($revReview.hasAttribute('aria-busy')) return;
10323
+ const button = e.target.closest('[data-rev-forward-path]');
10324
+ if (!button || !revReviewState?.forwardConflicts) return;
10325
+ const path = button.dataset.revForwardPath;
10326
+ const choice = button.dataset.revForwardChoice;
10327
+ revReviewState.forwardConflictChoices = revReviewState.forwardConflictChoices || {};
10328
+ revReviewState.forwardConflictChoices[path] = choice;
10329
+ renderRevisionForwardConflicts(revReviewState, revReviewState.forwardConflicts);
10330
+ Array.from($revReviewChanged.querySelectorAll('[data-rev-forward-path]'))
10331
+ .find((control) => control.dataset.revForwardPath === path && control.dataset.revForwardChoice === choice)?.focus();
10332
+ });
8492
10333
  $revReviewDiscard.addEventListener('click', (e) => {
8493
10334
  if ($revReview.hasAttribute('aria-busy')) return;
8494
10335
  const st = revReviewState;
@@ -8721,7 +10562,7 @@
8721
10562
  'data-tip="Show the complete member-by-member comparison">' +
8722
10563
  '<span class="hd-caret">▸</span><span class="hd-toggle-label">View detailed changes</span></button>'
8723
10564
  : '';
8724
- const detailWarning = `${detailReconciliationWarningHtml(v)}${shellAuthoredNoteHtml(v)}`;
10565
+ const detailWarning = `${readinessHtml(v)}${detailReconciliationWarningHtml(v)}${shellAuthoredNoteHtml(v)}`;
8725
10566
  if (!s || !Array.isArray(s.bullets)) {
8726
10567
  return `<div class="hist-event">${escapeHtml(v.message)}</div>${detailWarning}${toggle}`;
8727
10568
  }
@@ -8736,6 +10577,24 @@
8736
10577
  `<ul class="hist-change-list">${bullets}</ul>${cautions}${detailWarning}${toggle}`;
8737
10578
  }
8738
10579
 
10580
+ function readinessHtml(v) {
10581
+ const ready = v && v.readiness;
10582
+ if (!ready || typeof ready.state !== 'string') return '';
10583
+ const physical = Number.isInteger(ready.physicalMemberCount) ? ready.physicalMemberCount : null;
10584
+ const provisional = Number.isInteger(ready.provisionalMemberCount) ? ready.provisionalMemberCount : null;
10585
+ const views = Number.isInteger(ready.relevantViewCount) ? ready.relevantViewCount : null;
10586
+ if (ready.state === 'host-ready') {
10587
+ return `<div class="hist-change-note" role="note"><strong>Ready for host send.</strong> ${escapeHtml(`${physical} physical ${physical === 1 ? 'member' : 'members'} across ${views} relevant ${views === 1 ? 'view' : 'views'} passed the model checks.`)}</div>`;
10588
+ }
10589
+ if (ready.state === 'provisional-only') {
10590
+ return `<div class="hist-change-caution" role="note"><strong>Provisional model — view registration needed.</strong> ${escapeHtml(`${provisional} source-local ${provisional === 1 ? 'member stays' : 'members stay'} provisional. Approval does not convert provisional steel or unlock host send or export.`)}</div>`;
10591
+ }
10592
+ if (ready.state === 'mixed-review') {
10593
+ return `<div class="hist-change-caution" role="note"><strong>Review required before host send.</strong> ${escapeHtml(`${physical} physical and ${provisional} provisional ${physical + provisional === 1 ? 'member is' : 'members are'} recorded. Approval does not convert the provisional rows or unlock host send or export.`)}</div>`;
10594
+ }
10595
+ return '<div class="hist-change-note" role="note"><strong>Model readiness unavailable.</strong> FloLess could not prove the model is ready for host send from the admitted History evidence.</div>';
10596
+ }
10597
+
8739
10598
  function versionRowHtml(v) {
8740
10599
  // Rolling back to the version you're already on is a no-op — omit the button (blank cell), never disable it.
8741
10600
  const action = v.current || v.canStartApprovedRevision !== true
@@ -8799,6 +10658,7 @@
8799
10658
  async function renderHistory() {
8800
10659
  if (!current) return;
8801
10660
  const id = current.id;
10661
+ const previousHistory = $wsHistory.dataset.historyProjectId === id ? $wsHistory.innerHTML : '';
8802
10662
  closeBaseMenu(); // this re-render replaces the History HTML — drop any open base-picker's listener first
8803
10663
  $wsHistory.innerHTML = HIST_HEAD + '<div class="hist-note">Loading history…</div>';
8804
10664
  await awaitApprovalVerdict();
@@ -8807,6 +10667,7 @@
8807
10667
  let approvedAt;
8808
10668
  let nextDiffSupported = false;
8809
10669
  let nextDiffEligibleVersions = null;
10670
+ let strictHistoryUnavailable = false;
8810
10671
  // The rejection handler is attached HERE, at creation, not at the `await` further down.
8811
10672
  //
8812
10673
  // The two requests are deliberately concurrent, but the handler used to go on only after
@@ -8830,6 +10691,7 @@
8830
10691
  let checkpointsUnavailable = false;
8831
10692
  try {
8832
10693
  const r = await api(`/api/projects/${encodeURIComponent(id)}/versions`);
10694
+ strictHistoryUnavailable = r.historyAvailable === false;
8833
10695
  rows = Array.isArray(r.versions) ? r.versions : [];
8834
10696
  // Absent on an older server → fall back to the descriptor, which is the pre-change behaviour.
8835
10697
  nextDiffSupported = typeof r.diffSupported === 'boolean' ? r.diffSupported : !!(wsApp() && wsApp().diff);
@@ -8849,7 +10711,7 @@
8849
10711
  // `defaultUnavailable`, and reaches here through this throw. A bare network failure has no
8850
10712
  // body, so it still gets the retry line it deserves.
8851
10713
  const served = err && err.body && typeof err.body.error === 'string' ? err.body.error.trim() : '';
8852
- showToast('Couldn’t load history: ' + ((err && err.message) || err), 'warn');
10714
+ showToast('We couldn’t load this history because FloLess could not reach it. Try again.', 'warn');
8853
10715
  if (current && current.id === id && !$wsHistory.hidden) {
8854
10716
  // The header comes too. A step that keeps its band while loading and while listing but drops
8855
10717
  // it the moment it refuses looks like a different pane rather than the same one with bad news.
@@ -8863,6 +10725,12 @@
8863
10725
  if (saved === null) checkpointsUnavailable = true;
8864
10726
  else checkpoints = Array.isArray(saved.checkpoints) ? saved.checkpoints : [];
8865
10727
  if (!current || current.id !== id || $wsHistory.hidden) return; // switched away mid-await
10728
+ if (strictHistoryUnavailable) {
10729
+ if (previousHistory) $wsHistory.innerHTML = previousHistory;
10730
+ else $wsHistory.innerHTML = HIST_HEAD + '<div class="hist-empty">Model readiness unavailable — History could not be verified within its safety limits.</div>';
10731
+ showToast('History could not be verified; the last confirmed view was kept.', 'warn');
10732
+ return;
10733
+ }
8866
10734
  histDiffSupported = nextDiffSupported;
8867
10735
  histDiffEligibleVersions = nextDiffEligibleVersions;
8868
10736
  current.approvedAt = approvedAt; // re-sync — an in-editor autosave clears the sign-off server-side
@@ -8912,6 +10780,7 @@
8912
10780
  empty.append('Nothing here yet — ', btn, ' to get started.');
8913
10781
  }
8914
10782
  $wsHistory.replaceChildren(empty);
10783
+ $wsHistory.dataset.historyProjectId = id;
8915
10784
  $wsHistory.insertAdjacentHTML('beforeend', savedWorkHtml(checkpoints, checkpointsUnavailable));
8916
10785
  return;
8917
10786
  }
@@ -8944,6 +10813,7 @@
8944
10813
  '<th style="width:80px">Gate</th><th style="width:99%">Change</th><th style="width:92px"></th>' +
8945
10814
  '</tr></thead><tbody>' + rows.map(versionRowHtml).join('') + '</tbody></table>'
8946
10815
  + savedWorkHtml(checkpoints, checkpointsUnavailable);
10816
+ $wsHistory.dataset.historyProjectId = id;
8947
10817
  if (expandDiffOnce && expandDiffOnce.projectId === id) {
8948
10818
  const toggle = $wsHistory.querySelector(`.hd-toggle[data-diff="${CSS.escape(String(expandDiffOnce.n))}"]`);
8949
10819
  expandDiffOnce = null;
@@ -8982,6 +10852,7 @@
8982
10852
  // hidden it must not be able to PUT pre-partition bytes later; when visible it reloads the exact
8983
10853
  // server result now so the canvas and the next review begin from the same revision.
8984
10854
  function reloadModelFromServerTruth() {
10855
+ disposeModelEditorFrame('server-truth-reload');
8985
10856
  frames.model.dataset.loaded = '';
8986
10857
  frames.model.src = 'about:blank';
8987
10858
  if (!frames.model.hidden && frames.model.dataset.want) {
@@ -9027,7 +10898,7 @@
9027
10898
  await refreshApprovalState(proj.id);
9028
10899
  renderHistory();
9029
10900
  } catch (err) {
9030
- showToast('Rollback failed: ' + ((err && err.message) || err), 'warn');
10901
+ showToast('We couldn’t restore that version because FloLess could not save the change. Try again.', 'warn');
9031
10902
  }
9032
10903
  }
9033
10904
 
@@ -9055,7 +10926,7 @@
9055
10926
  await refreshApprovalState(proj.id);
9056
10927
  renderHistory();
9057
10928
  } catch (err) {
9058
- showToast('Couldn’t resume saved work: ' + ((err && err.message) || err), 'warn');
10929
+ showToast('We couldn’t resume this saved work because FloLess could not reach it. Try again.', 'warn');
9059
10930
  }
9060
10931
  }
9061
10932
 
@@ -9720,7 +11591,7 @@
9720
11591
  let blob;
9721
11592
  try { blob = await encodeThumbnail(file); }
9722
11593
  catch (err) {
9723
- showToast(err && err.message === 'too-large'
11594
+ showToast(err && err.code === 'too-large'
9724
11595
  ? 'That image file is too large to use as a thumbnail — pick one under 64 MB.'
9725
11596
  : 'Couldn’t read that image — try a PNG, JPG or WebP.', 'warn');
9726
11597
  return;
@@ -9739,7 +11610,7 @@
9739
11610
  showToast(replacing ? 'Thumbnail replaced ✓' : 'Thumbnail added ✓', 'ok');
9740
11611
  track('workspace_project_thumbnail_set', { app: project.app, replaced: replacing });
9741
11612
  } catch (err) {
9742
- showToast('Couldn’t save that thumbnail: ' + ((err && err.message) || err), 'warn');
11613
+ showToast('We couldn’t save that thumbnail because FloLess could not save the change. Try again.', 'warn');
9743
11614
  } finally { projActionBusy = false; }
9744
11615
  loadProjects(); // background reconcile, mirroring rename/duplicate/archive
9745
11616
  }
@@ -9925,7 +11796,7 @@
9925
11796
  }
9926
11797
  }
9927
11798
  finishProgress();
9928
- showToast(`Couldn’t export “${label}”: ${err && err.message || err}`, 'warn');
11799
+ showToast(`We couldn’t export “${label}” because FloLess could not finish preparing it. Try again.`, 'warn');
9929
11800
  } finally {
9930
11801
  finishProgress();
9931
11802
  projectExportBusy.delete(id);
@@ -9960,7 +11831,7 @@
9960
11831
  loadProjects(); // background reconcile against the server truth (mirrors duplicate/rename/archive)
9961
11832
  } catch (err) {
9962
11833
  finishProgress();
9963
- showToast('Import failed: ' + (err && err.message || err), 'warn');
11834
+ showToast('We couldn’t import that file because FloLess could not read it. Check the file, then try again.', 'warn');
9964
11835
  } finally { finishProgress(); }
9965
11836
  }
9966
11837
 
@@ -9971,7 +11842,7 @@
9971
11842
  try {
9972
11843
  await api(`/api/projects/${encodeURIComponent(id)}/unarchive`, { method: 'POST', body: '{}' });
9973
11844
  showToast(`Restored${p ? ` “${p.name}”` : ''}`, 'ok');
9974
- } catch (err) { showToast('Restore failed: ' + (err && err.message || err), 'warn'); }
11845
+ } catch (err) { showToast('We couldn’t restore that item because FloLess could not save the change. Try again.', 'warn'); }
9975
11846
  loadProjects();
9976
11847
  }
9977
11848
 
@@ -9992,7 +11863,7 @@
9992
11863
  try {
9993
11864
  await api(`/api/projects/${encodeURIComponent(id)}/archived`, { method: 'DELETE' });
9994
11865
  showToast(`Deleted “${name}”`, 'ok');
9995
- } catch (err) { showToast('Delete failed: ' + (err && err.message || err), 'warn'); }
11866
+ } catch (err) { showToast('We couldn’t delete that item because FloLess could not save the change. Try again.', 'warn'); }
9996
11867
  loadProjects();
9997
11868
  }
9998
11869