@floless/app 0.142.0 → 0.144.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/floless-server.cjs +218260 -189290
  2. package/dist/schemas/steel.model.v2.schema.json +50 -2
  3. package/dist/schemas/tekla.model.v1.schema.json +66 -0
  4. package/dist/schemas/tekla.model.v2.schema.json +69 -0
  5. package/dist/schemas/tekla.source-package.v1.schema.json +37 -0
  6. package/dist/skills/floless-app-steel-takeoff/SKILL.md +24 -1
  7. package/dist/skills/floless-app-workflows/SKILL.md +8 -2
  8. package/dist/skills/floless-app-workflows/references/workspace-data.md +25 -4
  9. package/dist/templates/floless-workspace-model-report.flo +27 -23
  10. package/dist/templates/revit-model.flo +6 -2
  11. package/dist/templates/tekla-model-report.flo +60 -0
  12. package/dist/templates/tekla-parser.flo +61 -0
  13. package/dist/web/app.css +89 -2
  14. package/dist/web/app.js +5 -4
  15. package/dist/web/aware.js +441 -47
  16. package/dist/web/chat.css +2 -0
  17. package/dist/web/chat.js +37 -3
  18. package/dist/web/commands-revit.js +4 -0
  19. package/dist/web/commands-shell.js +136 -3
  20. package/dist/web/commands-steel.js +8 -2
  21. package/dist/web/commands-tekla-parser.js +48 -0
  22. package/dist/web/commands.js +1 -1
  23. package/dist/web/filter-ai-context.js +35 -6
  24. package/dist/web/filter-ai-proposal.js +40 -4
  25. package/dist/web/grid-core.js +15 -0
  26. package/dist/web/index.html +40 -2
  27. package/dist/web/instructor.js +26 -14
  28. package/dist/web/left-pane.js +160 -10
  29. package/dist/web/model-artifact-loader.js +15 -0
  30. package/dist/web/model-display-units.js +89 -0
  31. package/dist/web/model-editor-revit-adapter.js +21 -4
  32. package/dist/web/model-editor.css +4 -2
  33. package/dist/web/model-measure.js +10 -6
  34. package/dist/web/model-panel-bridge.js +46 -3
  35. package/dist/web/model-pointer-dock.js +21 -1
  36. package/dist/web/model-property-display.js +91 -0
  37. package/dist/web/model-revit-module.js +9 -0
  38. package/dist/web/model-selection-tools.js +11 -0
  39. package/dist/web/model-spatial-panel.js +52 -21
  40. package/dist/web/model-structural-grid-view.js +334 -0
  41. package/dist/web/model-tekla-selection.js +32 -0
  42. package/dist/web/model-viewport-revit-adapter.js +119 -32
  43. package/dist/web/revit-editor.css +11 -1
  44. package/dist/web/revit-editor.html +4 -3
  45. package/dist/web/revit-editor.js +589 -111
  46. package/dist/web/steel-3d-view.js +58 -372
  47. package/dist/web/steel-editor.html +258 -17
  48. package/dist/web/steel-filter.html +17 -3
  49. package/dist/web/tekla-editor.html +71 -0
  50. package/dist/web/tekla-structural-grid-adapter.js +56 -0
  51. package/dist/web/workspaces.js +872 -97
  52. package/distribution-profile-production.mjs +4 -0
  53. package/distribution-resource-inventory.mjs +4 -2
  54. package/package.json +5 -2
@@ -355,6 +355,10 @@
355
355
  const $revitReassure = document.getElementById('ws-source-reassure');
356
356
  let revitSourceState = null;
357
357
  let revitActiveOperation = null;
358
+ const activeImportPolls = new Set();
359
+ let teklaUploadAbort = null;
360
+ let teklaUploadProjectId = null;
361
+ const teklaAdmissionFailures = new Map();
358
362
  let currentStep = 'model';
359
363
 
360
364
  // Shared drawing-file picker for both the new-project seed tile and the in-project
@@ -442,6 +446,76 @@
442
446
  });
443
447
  }
444
448
 
449
+ const TEKLA_PICK_LIMITS = Object.freeze({ files: 10_000, fileBytes: 512 * 1024 * 1024, totalBytes: 1.5 * 1024 * 1024 * 1024, depth: 32, pathBytes: 512 });
450
+ function validateTeklaPickedEntries(entries) {
451
+ if (!entries.length) throw new Error('The selected folder is empty.');
452
+ if (entries.length > TEKLA_PICK_LIMITS.files) throw new Error('The selected folder contains more than 10,000 files.');
453
+ let total = 0;
454
+ for (const entry of entries) {
455
+ const path = String(entry.path || '').replaceAll('\\', '/').replace(/^\/+/, '');
456
+ const parts = path.split('/');
457
+ if (!path || path.includes(':') || parts.length > TEKLA_PICK_LIMITS.depth || parts.some((part) => !part || part === '.' || part === '..')) {
458
+ throw new Error('The selected folder contains an unsafe file path.');
459
+ }
460
+ if (new TextEncoder().encode(path).byteLength > TEKLA_PICK_LIMITS.pathBytes) {
461
+ throw new Error('The selected folder contains a file path longer than 512 bytes.');
462
+ }
463
+ if (entry.file.size > TEKLA_PICK_LIMITS.fileBytes) throw new Error(`${entry.file.name} is larger than 512 MB.`);
464
+ total += entry.file.size;
465
+ if (!Number.isSafeInteger(total) || total > TEKLA_PICK_LIMITS.totalBytes) throw new Error('The selected folder is larger than 1.5 GB.');
466
+ entry.path = path;
467
+ }
468
+ entries.sort((left, right) => left.path.localeCompare(right.path));
469
+ return entries;
470
+ }
471
+
472
+ async function filesFromDirectoryHandle(root) {
473
+ const entries = [];
474
+ async function visit(directory, prefix, depth) {
475
+ if (depth > TEKLA_PICK_LIMITS.depth) throw new Error('The selected folder is nested too deeply.');
476
+ const children = [];
477
+ for await (const pair of directory.entries()) children.push(pair);
478
+ children.sort(([left], [right]) => left.localeCompare(right));
479
+ for (const [name, handle] of children) {
480
+ const logicalPath = prefix ? `${prefix}/${name}` : name;
481
+ if (handle.kind === 'file') entries.push({ path: logicalPath, file: await handle.getFile() });
482
+ else if (handle.kind === 'directory') await visit(handle, logicalPath, depth + 1);
483
+ if (entries.length > TEKLA_PICK_LIMITS.files) throw new Error('The selected folder contains more than 10,000 files.');
484
+ }
485
+ }
486
+ await visit(root, '', 1);
487
+ return { label: root.name, kind: 'folder', entries: validateTeklaPickedEntries(entries) };
488
+ }
489
+
490
+ async function pickTeklaFolder(fallbackInput) {
491
+ if (window.showDirectoryPicker) {
492
+ try { return await filesFromDirectoryHandle(await window.showDirectoryPicker({ mode: 'read' })); }
493
+ catch (error) { if (error?.name === 'AbortError') return null; throw error; }
494
+ }
495
+ return new Promise((resolve, reject) => {
496
+ const cleanup = () => { fallbackInput.removeEventListener('change', onChange); fallbackInput.removeEventListener('cancel', onCancel); };
497
+ const onChange = () => {
498
+ cleanup();
499
+ try {
500
+ const files = Array.from(fallbackInput.files || []);
501
+ const first = files[0]?.webkitRelativePath?.split('/')[0] || 'Tekla model';
502
+ const entries = files.map((file) => ({ path: file.webkitRelativePath?.split('/').slice(1).join('/') || file.name, file }));
503
+ fallbackInput.value = '';
504
+ resolve({ label: first, kind: 'folder', entries: validateTeklaPickedEntries(entries) });
505
+ } catch (error) { reject(error); }
506
+ };
507
+ const onCancel = () => { cleanup(); resolve(null); };
508
+ fallbackInput.addEventListener('change', onChange); fallbackInput.addEventListener('cancel', onCancel); fallbackInput.click();
509
+ });
510
+ }
511
+
512
+ async function pickTeklaZip(fallbackInput) {
513
+ const file = await pickZipFile(fallbackInput);
514
+ if (!file) return null;
515
+ if (!/\.zip$/i.test(file.name) || file.size > 1024 * 1024 * 1024) throw new Error('Choose one Tekla model ZIP up to 1 GB.');
516
+ return { label: file.name, kind: 'zip', entries: [{ path: file.name, file }] };
517
+ }
518
+
445
519
  // Single-image picker for Add/Replace thumbnail — same File System Access preference + hidden-input
446
520
  // fallback as the two above. Returns null on cancel; never throws.
447
521
  const THUMB_FILE_TYPES = [{
@@ -675,14 +749,16 @@
675
749
  // participates in first-paint fallback: /api/apps must positively report the canonical
676
750
  // installer-owned workflow plus its coarse access state before this card appears.
677
751
  serverAuthorizedOnly: true,
678
- displayName: 'Revit model',
679
- projectCapability: 'reviewable 3D model',
752
+ cardIcon: 'R',
753
+ displayName: 'Revit Parser',
754
+ projectCapability: 'read-only 3D model',
755
+ readOnlyLabel: 'Read-only',
680
756
  createActions: [{
681
757
  kind: 'rvt',
682
- headline: 'Revit model',
683
- capability: 'RVT → reviewable 3D model',
684
- sub: 'Open an RVT without Revit. Inspect its hierarchy and properties, then approve a revision for workflows.',
685
- label: 'Choose RVT',
758
+ headline: 'Revit Parser',
759
+ capability: 'Read-only 3D model',
760
+ sub: 'Open an RVT without Revit. Inspect its hierarchy and properties—the source RVT is never changed.',
761
+ label: 'Choose RVT for Revit Parser',
686
762
  }],
687
763
  editor: '/revit-editor.html',
688
764
  filter: null,
@@ -695,6 +771,59 @@
695
771
  diff: false,
696
772
  exports: [],
697
773
  },
774
+ 'tekla-parser': {
775
+ // Tekla is a family entitlement; this descriptor names only the read-only parser module so
776
+ // future Tekla modules can have their own workflows and product language.
777
+ serverAuthorizedOnly: true,
778
+ cardIcon: 'T',
779
+ displayName: 'Tekla Parser',
780
+ projectCapability: 'read-only 3D model',
781
+ readOnlyLabel: 'Read-only',
782
+ createActions: [{
783
+ kind: 'tekla-source',
784
+ headline: 'Tekla Parser',
785
+ capability: 'Read-only 3D model',
786
+ sub: 'Open a Tekla model folder or ZIP as a reviewable 3D model. Inspect its hierarchy and properties—the source model is never changed.',
787
+ label: 'Choose Tekla model…',
788
+ }],
789
+ editor: '/tekla-editor.html',
790
+ filter: null,
791
+ steps: [
792
+ { key: 'knowledge', label: 'Knowledge' },
793
+ { key: 'drawings', label: 'Source' },
794
+ { key: 'model', label: 'Model' },
795
+ { key: 'history', label: 'History' },
796
+ ],
797
+ diff: false,
798
+ exports: [],
799
+ accessCopy: {
800
+ 'access-required': {
801
+ status: 'Access required', body: 'Tekla Parser is not included for this account. Ask your FloLess account owner to enable it.',
802
+ action: '', aria: 'Tekla Parser access required',
803
+ },
804
+ 'account-selection-required': {
805
+ status: 'Choose an account', body: 'Choose which FloLess account to use for Tekla Parser.',
806
+ action: 'Choose account', aria: 'Choose a FloLess account for Tekla Parser',
807
+ },
808
+ 'setup-unavailable': {
809
+ status: 'Needs setup', body: 'Tekla Parser setup didn’t finish. Try setup again.',
810
+ action: 'Try setup again', aria: 'Tekla Parser needs setup — try setup again',
811
+ },
812
+ 'setup-provisioning': {
813
+ status: 'Setting up', body: 'FloLess is preparing the read-only Tekla Parser.',
814
+ action: '', aria: 'Tekla Parser setup in progress',
815
+ },
816
+ 'setup-integrity-failure': {
817
+ status: 'Setup could not be verified',
818
+ body: 'FloLess could not verify the security of this Tekla Parser setup, so it was not used. No model files were changed.',
819
+ action: 'Report issue', aria: 'Tekla Parser setup could not be verified — report issue',
820
+ },
821
+ 'check-unavailable': {
822
+ status: 'Couldn’t check access', body: 'FloLess couldn’t verify Tekla Parser access. Existing projects were not changed.',
823
+ action: 'Check again', aria: 'Tekla Parser access check unavailable — check again',
824
+ },
825
+ },
826
+ },
698
827
  };
699
828
  // A project names its app by the LIVE id, which a rename or a duplicate moves off the descriptor
700
829
  // keys above — so resolve through the lineage ROOT the server ships beside it (`templateId`, derived
@@ -771,12 +900,14 @@
771
900
  }
772
901
  const capabilityByRoot = new Map();
773
902
  for (const capability of capabilities || []) {
774
- if (!capability || capability.appId !== 'revit-model' || capability.templateId !== 'revit-model') continue;
775
- const known = ['ready', 'access-required', 'account-selection-required', 'setup-unavailable', 'check-unavailable'];
776
- capabilityByRoot.set('revit-model', known.includes(capability.status) ? capability.status : 'check-unavailable');
777
- // A capability row exists only after the server positively found canonical revit-model. Add
903
+ if (!capability || typeof capability.templateId !== 'string'
904
+ || capability.appId !== capability.templateId
905
+ || WORKSPACE_APPS[capability.templateId]?.serverAuthorizedOnly !== true) continue;
906
+ const known = ['ready', 'access-required', 'account-selection-required', 'setup-provisioning', 'setup-unavailable', 'setup-integrity-failure', 'check-unavailable'];
907
+ capabilityByRoot.set(capability.templateId, known.includes(capability.status) ? capability.status : 'check-unavailable');
908
+ // A capability row exists only after the server positively found the canonical module. Add
778
909
  // its presentation entry even when authorization intentionally filtered it out of `apps`.
779
- if (!byRoot.has('revit-model')) byRoot.set('revit-model', ['revit-model']);
910
+ if (!byRoot.has(capability.templateId)) byRoot.set(capability.templateId, [capability.templateId]);
780
911
  }
781
912
  // Keep the two built-in drawing actions visible when only one workflow is installed.
782
913
  // /api/apps is authoritative about which canonical workflow is missing, so the card's
@@ -797,9 +928,9 @@
797
928
  const ids = byRoot.get(root).slice().sort();
798
929
  const capabilityStatus = capabilityByRoot.get(root);
799
930
  return {
800
- appId: root === 'revit-model' ? 'revit-model' : ids.indexOf(root) >= 0 ? root : ids[0],
931
+ appId: WORKSPACE_APPS[root]?.serverAuthorizedOnly === true ? root : ids.indexOf(root) >= 0 ? root : ids[0],
801
932
  templateId: root,
802
- ambiguous: root === 'revit-model' ? false : ids.length > 1,
933
+ ambiguous: WORKSPACE_APPS[root]?.serverAuthorizedOnly === true ? false : ids.length > 1,
803
934
  ...(capabilityStatus ? { capabilityStatus } : {}),
804
935
  ...(missingCoreRoots.has(root) ? { missing: true } : {}),
805
936
  };
@@ -864,7 +995,14 @@
864
995
  let label = 'Review & approve';
865
996
  let tip = APPROVE_TIP;
866
997
  let unavailable = false;
867
- if (projectContractLifecycle === 'filter-checkpoint') {
998
+ if (s.status === 'waiting-for-model-read') {
999
+ const tekla = isTeklaParserProject();
1000
+ label = tekla ? 'Review after read' : 'Review after import';
1001
+ tip = tekla
1002
+ ? 'Review will be available when the read-only snapshot is ready.'
1003
+ : 'Review will be available when the read-only model is ready.';
1004
+ unavailable = true;
1005
+ } else if (projectContractLifecycle === 'filter-checkpoint') {
868
1006
  label = 'Read members first';
869
1007
  tip = 'The Drawing Filter is saved. Read the selected drawing content before approval.';
870
1008
  unavailable = true;
@@ -978,7 +1116,7 @@
978
1116
  }
979
1117
  }
980
1118
 
981
- async function refreshApprovalState(projectId = current && current.id) {
1119
+ async function refreshApprovalState(projectId = current && current.id, sourceStateProbe = null) {
982
1120
  if (!projectId || !current || current.id !== projectId) return null;
983
1121
  const gen = ++approvalStateGen;
984
1122
  let settle;
@@ -986,6 +1124,18 @@
986
1124
  approvalState = { status: 'loading', review: null, pendingCount: 0, headVersion: null, error: '' };
987
1125
  renderApprovalHeader();
988
1126
  try {
1127
+ // A newly opened read-only project may still be publishing its model. Wait for its
1128
+ // source-state check before asking for a review: the server correctly refuses a
1129
+ // review while the import is active, but that refusal is not a lasting error.
1130
+ if (sourceStateProbe) await sourceStateProbe;
1131
+ if (gen !== approvalStateGen || !current || current.id !== projectId) return null;
1132
+ if (wsDescOf(current)?.serverAuthorizedOnly === true && revitActiveOperation
1133
+ && !['ready', 'failed', 'cancelled'].includes(revitActiveOperation.state)) {
1134
+ approvalState = { status: 'waiting-for-model-read', review: null, pendingCount: 0,
1135
+ headVersion: null, error: '' };
1136
+ renderApprovalHeader();
1137
+ return null;
1138
+ }
989
1139
  const review = await api(`/api/projects/${encodeURIComponent(projectId)}/approval-review`);
990
1140
  if (gen !== approvalStateGen || !current || current.id !== projectId) return null;
991
1141
  // NOT an error, and kept apart from one on purpose: the route answers this 200 for a project
@@ -1622,6 +1772,10 @@
1622
1772
  try {
1623
1773
  res = await api('/api/projects');
1624
1774
  } catch (err) {
1775
+ // Page teardown rejects in-flight fetches as "Failed to fetch" in Chromium. The page is
1776
+ // leaving, so there is no project state to verify or recovery action to show. An explicit
1777
+ // abort is cancellation too; live network/server failures still use the warning below.
1778
+ if (workspacePageUnloading || (err && err.name === 'AbortError')) return;
1625
1779
  // Never silent, and never only in the console: "we could not tell" leaves the user in the
1626
1780
  // exact unknown state this exists to resolve, and the event that would have asked again is
1627
1781
  // already consumed. Say so, and name the recovery. (Found by review — the first cut logged
@@ -1852,6 +2006,7 @@
1852
2006
  }
1853
2007
 
1854
2008
  function workspaceCreateCardHtml(entry, action) {
2009
+ const descriptor = WORKSPACE_APPS[entry.templateId];
1855
2010
  if (entry.missing === true) {
1856
2011
  const descriptionId = `ws-${entry.templateId}-missing`;
1857
2012
  const buttonStart = entry.templateId === 'vectorize'
@@ -1860,54 +2015,70 @@
1860
2015
  return buttonStart +
1861
2016
  `aria-label="${escapeAttr(`${action.headline} needs setup — why unavailable`)}" aria-describedby="${escapeAttr(descriptionId)}" ` +
1862
2017
  `data-seed-app="${escapeAttr(entry.appId)}" data-seed-template="${escapeAttr(entry.templateId)}" data-seed-action="${escapeAttr(action.kind)}">` +
1863
- `<span class="plus" aria-hidden="true">!</span>` +
2018
+ `<span class="ws-seed-icon" aria-hidden="true">!</span>` +
1864
2019
  `<span class="ws-seed-headline">${escapeHtml(action.headline)}</span>` +
1865
2020
  `<span class="ws-seed-capability ws-seed-state">Needs setup</span>` +
1866
2021
  `<span class="ws-seed-sub" id="${escapeAttr(descriptionId)}">${escapeHtml(missingWorkspaceWorkflowMessage(entry.templateId))}</span>` +
1867
2022
  `<span class="ws-seed-action">Why unavailable →</span>` +
1868
- `</button>`;
2023
+ `</button>`;
1869
2024
  }
1870
- if (entry.templateId === 'revit-model' && entry.capabilityStatus && entry.capabilityStatus !== 'ready') {
1871
- const states = {
2025
+ if (descriptor?.serverAuthorizedOnly === true && entry.capabilityStatus && entry.capabilityStatus !== 'ready') {
2026
+ const revitStates = {
1872
2027
  'access-required': {
1873
2028
  status: 'Access required',
1874
- body: 'Revit model access is not included for this account.',
2029
+ body: 'Revit Parser is not included for this account. Ask your FloLess account owner to enable it.',
1875
2030
  action: 'View access',
1876
- aria: 'Revit model access required — view access',
2031
+ aria: 'Revit Parser access required — view access',
1877
2032
  },
1878
2033
  'account-selection-required': {
1879
2034
  status: 'Choose an account',
1880
- body: 'Choose which FloLess account you want to use for Revit model access.',
2035
+ body: 'Choose which FloLess account to use for Revit Parser.',
1881
2036
  action: 'Choose account',
1882
- aria: 'Choose a FloLess account for Revit model access',
2037
+ aria: 'Choose a FloLess account for Revit Parser',
1883
2038
  },
1884
2039
  'setup-unavailable': {
1885
2040
  status: 'Needs setup',
1886
- body: 'Revit projects can’t be opened until xeoRVT setup finishes.',
1887
- action: 'View setup',
1888
- aria: 'Revit model needs setup — view setup',
2041
+ body: 'Revit Parser setup didn’t finish. Try setup again.',
2042
+ action: 'Try setup again',
2043
+ aria: 'Revit Parser needs setup — try setup again',
1889
2044
  },
1890
2045
  'check-unavailable': {
1891
2046
  status: 'Couldn’t check access',
1892
- body: 'FloLess couldn’t check Revit model access. Your existing projects were not changed.',
1893
- action: 'Try again',
1894
- aria: 'Revit model access check unavailable — try again',
2047
+ body: 'FloLess couldn’t check Revit Parser access. Existing projects were not changed.',
2048
+ action: 'Check again',
2049
+ aria: 'Revit Parser access check unavailable — check again',
1895
2050
  },
1896
2051
  };
2052
+ const states = descriptor.accessCopy || revitStates;
1897
2053
  const state = states[entry.capabilityStatus] || states['check-unavailable'];
1898
- const descriptionId = `ws-revit-${entry.capabilityStatus || 'check-unavailable'}`;
1899
- return `<button type="button" class="ws-seed ws-seed-remedy" ` +
2054
+ const descriptionId = `ws-${entry.templateId}-${entry.capabilityStatus || 'check-unavailable'}`;
2055
+ const actionable = !!state.action;
2056
+ const provisioning = entry.capabilityStatus === 'setup-provisioning';
2057
+ const teklaCommand = entry.capabilityStatus === 'setup-unavailable'
2058
+ ? 'data-command-id="shell.tekla-retry-setup"'
2059
+ : entry.capabilityStatus === 'setup-integrity-failure'
2060
+ ? 'data-command-id="shell.tekla-report-setup-issue"'
2061
+ : 'data-command-id="shell.tekla-view-access"';
2062
+ const revitCommand = entry.capabilityStatus === 'setup-unavailable'
2063
+ ? 'data-command-id="shell.revit-retry-setup"'
2064
+ : 'data-command-id="shell.revit-view-access"';
2065
+ return `<${actionable ? 'button type="button"' : 'div'} class="ws-seed ws-seed-remedy" ` +
1900
2066
  `aria-label="${escapeAttr(state.aria)}" aria-describedby="${escapeAttr(descriptionId)}" ` +
1901
- `data-command-id="shell.revit-view-access" data-revit-remedy="${escapeAttr(entry.capabilityStatus || 'check-unavailable')}">` +
1902
- `<span class="plus" aria-hidden="true">R</span>` +
1903
- `<span class="ws-seed-headline">Revit model</span>` +
2067
+ (provisioning ? 'aria-busy="true" ' : '') +
2068
+ (actionable ? entry.templateId === 'revit-model'
2069
+ ? `${revitCommand} data-revit-remedy="${escapeAttr(entry.capabilityStatus || 'check-unavailable')}"`
2070
+ : `${teklaCommand} data-module-remedy="tekla-parser" data-module-remedy-state="${escapeAttr(entry.capabilityStatus || 'check-unavailable')}"` : '') + `>` +
2071
+ `<span class="ws-seed-icon" aria-hidden="true">${escapeHtml(descriptor.cardIcon || '!')}</span>` +
2072
+ `<span class="ws-seed-headline">${escapeHtml(descriptor.displayName)}</span>` +
2073
+ (descriptor.readOnlyLabel ? `<span class="ws-seed-readonly">${escapeHtml(descriptor.readOnlyLabel)}</span>` : '') +
1904
2074
  `<span class="ws-seed-capability ws-seed-state">${escapeHtml(state.status)}</span>` +
1905
2075
  `<span class="ws-seed-sub" id="${escapeAttr(descriptionId)}">${escapeHtml(state.body)}</span>` +
1906
- `<span class="ws-seed-action">${escapeHtml(state.action)} →</span>` +
1907
- `</button>`;
2076
+ (state.action ? `<span class="ws-seed-action">${escapeHtml(state.action)} →</span>` : '') +
2077
+ `</${actionable ? 'button' : 'div'}>`;
1908
2078
  }
1909
2079
  const acceptsDrop = action.kind === 'drawing' || action.kind === 'rvt';
1910
- const createCommand = action.kind !== 'drawing' ? ''
2080
+ const createCommand = action.kind === 'tekla-source' ? 'data-command-id="shell.project-create-tekla-read" '
2081
+ : action.kind !== 'drawing' ? ''
1911
2082
  : entry.templateId === 'steel-model' ? 'data-command-id="shell.project-create-steel-from-drawings" '
1912
2083
  : entry.templateId === 'vectorize' ? 'data-command-id="shell.project-create-trace-from-drawing" '
1913
2084
  : '';
@@ -1923,8 +2094,9 @@
1923
2094
  `data-seed-app="${escapeAttr(entry.appId)}" data-seed-template="${escapeAttr(entry.templateId)}" data-seed-action="${escapeAttr(action.kind)}"` +
1924
2095
  (acceptsDrop ? ` data-seed-drop="${escapeAttr(entry.appId)}" data-seed-drop-kind="${escapeAttr(action.kind)}"` : '') +
1925
2096
  `>` +
1926
- `<span class="plus">+</span>` +
2097
+ `<span class="ws-seed-icon" aria-hidden="true">${escapeHtml(descriptor?.cardIcon || '+')}</span>` +
1927
2098
  `<span class="ws-seed-headline">${escapeHtml(action.headline)}</span>` +
2099
+ (descriptor?.readOnlyLabel ? `<span class="ws-seed-readonly">${escapeHtml(descriptor.readOnlyLabel)}</span>` : '') +
1928
2100
  (action.capability ? `<span class="ws-seed-capability">${escapeHtml(action.capability)}</span>` : '') +
1929
2101
  `<span class="ws-seed-sub">${escapeHtml(action.sub)}</span>` +
1930
2102
  (target
@@ -2181,7 +2353,7 @@
2181
2353
  // element is ACTED on by, never by DOM position: a rebuild reorders the grid (a rename re-fronts its
2182
2354
  // card), so an index would hand focus to a different project — worse than losing it. Returns null
2183
2355
  // for anything unrecognised or outside the landing, which simply means "don't restore".
2184
- const FOCUS_KEY_ATTRS = ['data-open', 'data-kebab', 'data-thumb', 'data-restore', 'data-delete-archived', 'data-revit-remedy'];
2356
+ const FOCUS_KEY_ATTRS = ['data-open', 'data-kebab', 'data-thumb', 'data-restore', 'data-delete-archived', 'data-revit-remedy', 'data-module-remedy'];
2185
2357
  function landingFocusKey(el) {
2186
2358
  if (!el || !$landing.contains(el)) return null;
2187
2359
  if (el.id) return `#${el.id}`; // #ws-import-project / #ws-retry-projects
@@ -2220,11 +2392,153 @@
2220
2392
  if (e.target.closest('#ws-import-project')) { importProject(); return; }
2221
2393
  const revitRemedy = e.target.closest('[data-revit-remedy]');
2222
2394
  if (revitRemedy) {
2395
+ if (revitRemedy.dataset.revitRemedy === 'report-issue') {
2396
+ window.dispatchEvent(new CustomEvent('floless:report-revit-setup-issue', {
2397
+ detail: { returnFocus: revitRemedy },
2398
+ }));
2399
+ return;
2400
+ }
2401
+ if (revitRemedy.dataset.revitRemedy === 'setup-unavailable') {
2402
+ const originalLabel = revitRemedy.getAttribute('aria-label');
2403
+ const originalBlockedReason = revitRemedy.getAttribute('data-blocked-reason');
2404
+ const action = revitRemedy.querySelector('.ws-seed-action');
2405
+ const originalAction = action?.textContent;
2406
+ revitRemedy.disabled = true;
2407
+ revitRemedy.setAttribute('aria-busy', 'true');
2408
+ revitRemedy.setAttribute('aria-label', 'Revit Parser setup retry in progress');
2409
+ revitRemedy.setAttribute('data-blocked-reason', 'Revit Parser setup retry is already in progress.');
2410
+ if (action) action.textContent = 'Trying…';
2411
+ window.Instructor?.refreshCarrier(revitRemedy);
2412
+ let ready = false;
2413
+ let setup = null;
2414
+ try {
2415
+ setup = await api('/api/rvt-defaults/retry', { method: 'POST' });
2416
+ ready = setup?.status === 'ready';
2417
+ } catch (error) {
2418
+ setup = error?.body || null;
2419
+ }
2420
+ if (ready) {
2421
+ if (revitRemedy.isConnected) {
2422
+ revitRemedy.disabled = false;
2423
+ revitRemedy.removeAttribute('aria-busy');
2424
+ if (originalLabel === null) revitRemedy.removeAttribute('aria-label');
2425
+ else revitRemedy.setAttribute('aria-label', originalLabel);
2426
+ if (originalBlockedReason === null) revitRemedy.removeAttribute('data-blocked-reason');
2427
+ else revitRemedy.setAttribute('data-blocked-reason', originalBlockedReason);
2428
+ if (action) action.textContent = originalAction;
2429
+ }
2430
+ window.Instructor?.clear();
2431
+ showToast('Revit Parser setup is ready.', 'ok');
2432
+ window.dispatchEvent(new CustomEvent('floless:revit-capability-changed'));
2433
+ return;
2434
+ }
2435
+
2436
+ const details = {
2437
+ 'aware-unavailable': 'FloLess couldn’t start the service used by Revit Parser. Try setup again.',
2438
+ 'core-workflow-provisioning': 'FloLess couldn’t prepare the built-in Workspace workflows. Try setup again.',
2439
+ 'reader-verification': 'FloLess couldn’t verify the installed Revit reader. Try setup again.',
2440
+ 'workspace-bootstrap': 'FloLess couldn’t prepare the Workspace connection used by Revit Parser. Try setup again.',
2441
+ 'revit-workflow-provisioning': 'FloLess couldn’t prepare the Revit project workflows. Try setup again.',
2442
+ 'reader-release-unavailable': 'The required Revit reader version is unavailable. Report this issue.',
2443
+ };
2444
+ const category = setup?.category;
2445
+ const explanation = details[category] || 'Revit Parser setup still needs attention. Try setup again.';
2446
+ // Provisioning broadcasts can repaint the landing before this request settles. Apply the
2447
+ // safe result to the live replacement instead of leaving its card and Instructor narration stale.
2448
+ const settledRemedy = revitRemedy.isConnected
2449
+ ? revitRemedy
2450
+ : document.querySelector('[data-revit-remedy="setup-unavailable"]');
2451
+ if (!settledRemedy) {
2452
+ window.Instructor?.clear();
2453
+ showToast(explanation, 'warn');
2454
+ return;
2455
+ }
2456
+ const settledAction = settledRemedy.querySelector('.ws-seed-action');
2457
+ const settledBody = settledRemedy.querySelector('.ws-seed-sub');
2458
+ if (settledBody) settledBody.textContent = explanation;
2459
+ if (category === 'reader-release-unavailable') {
2460
+ settledRemedy.dataset.revitRemedy = 'report-issue';
2461
+ settledRemedy.dataset.commandId = 'shell.revit-report-setup-issue';
2462
+ settledRemedy.setAttribute('aria-label', 'Revit Parser reader unavailable — report issue');
2463
+ if (settledAction) settledAction.textContent = 'Report issue →';
2464
+ } else {
2465
+ if (originalLabel === null) settledRemedy.removeAttribute('aria-label');
2466
+ else settledRemedy.setAttribute('aria-label', originalLabel);
2467
+ if (settledAction) settledAction.textContent = originalAction;
2468
+ }
2469
+ settledRemedy.disabled = false;
2470
+ settledRemedy.removeAttribute('aria-busy');
2471
+ if (originalBlockedReason === null) settledRemedy.removeAttribute('data-blocked-reason');
2472
+ else settledRemedy.setAttribute('data-blocked-reason', originalBlockedReason);
2473
+ window.Instructor?.refreshCarrier(settledRemedy);
2474
+ showToast(explanation, 'warn');
2475
+ return;
2476
+ }
2223
2477
  window.dispatchEvent(new CustomEvent('floless:open-revit-access', {
2224
2478
  detail: { state: revitRemedy.dataset.revitRemedy },
2225
2479
  }));
2226
2480
  return;
2227
2481
  }
2482
+ const moduleRemedy = e.target.closest('[data-module-remedy]');
2483
+ if (moduleRemedy) {
2484
+ if (moduleRemedy.dataset.moduleRemedyState === 'setup-provisioning') return;
2485
+ if (moduleRemedy.dataset.moduleRemedyState === 'setup-integrity-failure') {
2486
+ window.dispatchEvent(new CustomEvent('floless:report-tekla-setup-issue', {
2487
+ detail: { returnFocus: moduleRemedy },
2488
+ }));
2489
+ return;
2490
+ }
2491
+ if (moduleRemedy.dataset.moduleRemedyState === 'setup-unavailable') {
2492
+ const originalLabel = moduleRemedy.getAttribute('aria-label');
2493
+ const action = moduleRemedy.querySelector('.ws-seed-action');
2494
+ const originalAction = action?.textContent || '';
2495
+ moduleRemedy.disabled = true;
2496
+ moduleRemedy.setAttribute('aria-busy', 'true');
2497
+ moduleRemedy.setAttribute('aria-label', 'Tekla Parser setup retry in progress');
2498
+ moduleRemedy.setAttribute('data-blocked-reason', 'Tekla Parser setup retry is already in progress.');
2499
+ if (action) action.textContent = 'Trying…';
2500
+ window.Instructor?.refreshCarrier(moduleRemedy);
2501
+ let status = null;
2502
+ try {
2503
+ const setup = await api('/api/tekla-defaults/retry', { method: 'POST' });
2504
+ status = setup?.status || null;
2505
+ } catch {
2506
+ // The server may have accepted the retry even when this response was lost. Reconcile from
2507
+ // its authoritative catalogue; never turn a transport loss into a false setup failure.
2508
+ try {
2509
+ const catalogue = await api('/api/apps');
2510
+ status = catalogue.workspaceCapabilities?.find((entry) => entry.templateId === 'tekla-parser')?.status || null;
2511
+ } catch { /* the next health/SSE refresh will reconcile */ }
2512
+ }
2513
+ moduleRemedy.disabled = false;
2514
+ moduleRemedy.removeAttribute('aria-busy');
2515
+ moduleRemedy.removeAttribute('data-blocked-reason');
2516
+ if (originalLabel === null) moduleRemedy.removeAttribute('aria-label');
2517
+ else moduleRemedy.setAttribute('aria-label', originalLabel);
2518
+ if (action) action.textContent = originalAction;
2519
+ window.Instructor?.refreshCarrier(moduleRemedy);
2520
+ await loadProjects({ quiet: true });
2521
+ if (status === 'ready') {
2522
+ window.Instructor?.clear();
2523
+ showToast('Tekla Parser setup is ready.', 'ok');
2524
+ return;
2525
+ }
2526
+ if (status === 'setup-provisioning') {
2527
+ showToast('Tekla Parser setup is still running.', 'info');
2528
+ return;
2529
+ }
2530
+ const liveRemedy = document.querySelector('[data-module-remedy="tekla-parser"]');
2531
+ if (liveRemedy) window.Instructor?.refreshCarrier(liveRemedy);
2532
+ showToast(status
2533
+ ? 'Tekla Parser setup still needs attention. Try setup again.'
2534
+ : 'FloLess couldn’t confirm whether Tekla Parser setup finished. Check again.', 'warn');
2535
+ return;
2536
+ }
2537
+ window.dispatchEvent(new CustomEvent('floless:open-tekla-access', {
2538
+ detail: { state: moduleRemedy.dataset.moduleRemedyState },
2539
+ }));
2540
+ return;
2541
+ }
2228
2542
  const card = e.target.closest('[data-open]');
2229
2543
  if (card) { openProject(card.dataset.open); return; }
2230
2544
  const seed = e.target.closest('[data-seed-app]');
@@ -2255,6 +2569,8 @@
2255
2569
  } else if (seed.dataset.seedAction === 'rvt') {
2256
2570
  const file = await pickRvtFile($seedRvt);
2257
2571
  if (file) createFromRvt(appId, templateId, file);
2572
+ } else if (seed.dataset.seedAction === 'tekla-source') {
2573
+ openTeklaSourceChoice(appId, templateId, seed);
2258
2574
  } else {
2259
2575
  // Unreachable today, and it must not be SILENT the day it isn't: an unhandled kind still
2260
2576
  // renders a full dashed, focusable card, so without this the first person to add one gets a
@@ -2290,13 +2606,115 @@
2290
2606
  $seedRvt.type = 'file'; $seedRvt.accept = '.rvt,application/x-rvt'; $seedRvt.hidden = true;
2291
2607
  document.body.appendChild($seedRvt);
2292
2608
  $revitOpenModel?.addEventListener('click', () => setStep('model'));
2609
+ const $seedTeklaFolder = document.createElement('input');
2610
+ $seedTeklaFolder.type = 'file'; $seedTeklaFolder.multiple = true; $seedTeklaFolder.hidden = true;
2611
+ $seedTeklaFolder.setAttribute('webkitdirectory', '');
2612
+ document.body.appendChild($seedTeklaFolder);
2613
+ const $seedTeklaZip = document.createElement('input');
2614
+ $seedTeklaZip.type = 'file'; $seedTeklaZip.accept = '.zip,application/zip'; $seedTeklaZip.hidden = true;
2615
+ document.body.appendChild($seedTeklaZip);
2616
+ const $teklaSourceModal = document.getElementById('tekla-source-modal');
2617
+ const $teklaSourceDialog = $teklaSourceModal?.querySelector('.tekla-source-dialog');
2618
+ const $teklaSourceFolder = document.getElementById('tekla-source-folder');
2619
+ const $teklaSourceZip = document.getElementById('tekla-source-zip');
2620
+ const $teklaSourceCancel = document.getElementById('tekla-source-cancel');
2621
+ const $teklaSourceStatus = document.getElementById('tekla-source-status');
2622
+ let teklaSourceChoice = null;
2623
+ let teklaSourcePicking = false;
2624
+ function setTeklaSourcePicking(busy, message = '') {
2625
+ teklaSourcePicking = busy;
2626
+ $teklaSourceModal?.setAttribute('aria-busy', String(busy));
2627
+ if ($teklaSourceFolder) $teklaSourceFolder.disabled = busy;
2628
+ if ($teklaSourceZip) $teklaSourceZip.disabled = busy;
2629
+ if ($teklaSourceCancel) $teklaSourceCancel.disabled = busy;
2630
+ if ($teklaSourceStatus) {
2631
+ $teklaSourceStatus.textContent = message;
2632
+ $teklaSourceStatus.hidden = !message;
2633
+ }
2634
+ }
2635
+ function openTeklaSourceChoice(appId, templateId, returnFocus, onPicked = null) {
2636
+ if (!$teklaSourceModal || teklaSourceChoice) return;
2637
+ teklaSourceChoice = { appId, templateId, returnFocus, onPicked };
2638
+ setTeklaSourcePicking(false);
2639
+ $teklaSourceModal.classList.add('show');
2640
+ $teklaSourceDialog?.focus();
2641
+ }
2642
+ function closeTeklaSourceChoice(restoreFocus = true) {
2643
+ const state = teklaSourceChoice;
2644
+ teklaSourceChoice = null;
2645
+ $teklaSourceModal?.classList.remove('show');
2646
+ if (restoreFocus && state?.returnFocus?.isConnected) state.returnFocus.focus();
2647
+ }
2648
+ async function chooseTeklaSource(kind) {
2649
+ const choice = teklaSourceChoice;
2650
+ if (!choice || teklaSourcePicking) return;
2651
+ const trigger = kind === 'folder' ? $teklaSourceFolder : $teklaSourceZip;
2652
+ setTeklaSourcePicking(true, kind === 'folder' ? 'Choosing folder…' : 'Choosing ZIP…');
2653
+ try {
2654
+ const source = kind === 'folder' ? await pickTeklaFolder($seedTeklaFolder) : await pickTeklaZip($seedTeklaZip);
2655
+ if (teklaSourceChoice !== choice) return;
2656
+ if (!source) { setTeklaSourcePicking(false); trigger?.focus(); return; }
2657
+ if (choice.onPicked) {
2658
+ closeTeklaSourceChoice(false);
2659
+ $sourcePlaceholder?.focus();
2660
+ await choice.onPicked(source);
2661
+ return;
2662
+ }
2663
+ const opened = await createFromTeklaSource(choice.appId, choice.templateId, source, choice.returnFocus);
2664
+ if (opened && teklaSourceChoice === choice) closeTeklaSourceChoice(false);
2665
+ else if (teklaSourceChoice === choice) setTeklaSourcePicking(false,
2666
+ 'FloLess could not open project setup. Close any other setup window, then choose the source again.');
2667
+ } catch (error) {
2668
+ if (teklaSourceChoice === choice) setTeklaSourcePicking(false, error?.message || 'FloLess could not read that selection.');
2669
+ showToast(error?.message || 'Could not read that Tekla source.', 'warn');
2670
+ }
2671
+ }
2672
+ $teklaSourceFolder?.addEventListener('click', () => { void chooseTeklaSource('folder'); });
2673
+ $teklaSourceZip?.addEventListener('click', () => { void chooseTeklaSource('zip'); });
2674
+ $teklaSourceCancel?.addEventListener('click', () => closeTeklaSourceChoice());
2675
+ $teklaSourceModal?.addEventListener('click', (event) => { if (event.target === $teklaSourceModal) closeTeklaSourceChoice(); });
2676
+ $teklaSourceModal?.addEventListener('keydown', (event) => {
2677
+ if (event.key === 'Escape') { event.preventDefault(); closeTeklaSourceChoice(); return; }
2678
+ if (event.key !== 'Tab') return;
2679
+ const controls = [...$teklaSourceModal.querySelectorAll('button:not([disabled])')];
2680
+ if (!controls.length) return;
2681
+ const first = controls[0]; const last = controls.at(-1);
2682
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
2683
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
2684
+ });
2685
+ const isTeklaParserProject = (project = current) => wsDescOf(project) === WORKSPACE_APPS['tekla-parser'];
2293
2686
  $revitReplace?.addEventListener('click', async () => {
2294
2687
  const project = current;
2295
2688
  if (!project) return;
2689
+ if (isTeklaParserProject(project)) {
2690
+ openTeklaSourceChoice(project.app, 'tekla-parser', $revitReplace, async (source) => {
2691
+ try {
2692
+ const state = await readReplacementSourceState(project);
2693
+ if (current?.id !== project.id) return;
2694
+ if (!state?.canReplace) throw new Error('Tekla Parser replacement access is unavailable.');
2695
+ const operation = await uploadTeklaForProject(project, source, state.generation);
2696
+ if (current?.id === project.id) pollRevitImport(operation.operationId, project.id);
2697
+ } catch (error) {
2698
+ if (current?.id !== project.id) return;
2699
+ if (error?.name === 'AbortError') {
2700
+ paintRevitSourceState('Read cancelled', 'The existing read-only snapshot was not changed.');
2701
+ paintRevitSourceActions('ready', revitSourceState?.canReplace === true);
2702
+ return;
2703
+ }
2704
+ const reason = teklaAdmissionMessage(error);
2705
+ const title = teklaAdmissionTitle(error);
2706
+ const message = `${reason} The existing read-only snapshot was not changed.`;
2707
+ teklaAdmissionFailures.set(project.id, { title, message });
2708
+ paintRevitSourceState(title, message);
2709
+ paintRevitSourceActions('failed', revitSourceState?.canReplace === true, false);
2710
+ }
2711
+ });
2712
+ return;
2713
+ }
2296
2714
  const file = await pickRvtFile($seedRvt);
2297
2715
  if (!file || !current || current.id !== project.id) return;
2298
2716
  try {
2299
- const state = await refreshRevitSourceState(project.id);
2717
+ const state = await readReplacementSourceState(project);
2300
2718
  if (!state?.canReplace) throw new Error('Revit replacement access is unavailable.');
2301
2719
  const operation = await uploadRvtForProject(project, file, state.generation);
2302
2720
  pollRevitImport(operation.operationId, project.id);
@@ -2308,7 +2726,7 @@
2308
2726
  $revitRetry?.addEventListener('click', async () => {
2309
2727
  const project = current;
2310
2728
  const failedOperationId = revitActiveOperation?.operationId;
2311
- if (!project || !failedOperationId) return;
2729
+ if (!project || !failedOperationId || isTeklaParserProject(project)) return;
2312
2730
  try {
2313
2731
  const started = await api(`/api/model-imports/${encodeURIComponent(failedOperationId)}/retry`, { method: 'POST', body: '{}' });
2314
2732
  revitActiveOperation = started.operation;
@@ -2321,11 +2739,19 @@
2321
2739
  }
2322
2740
  });
2323
2741
  $revitCancel?.addEventListener('click', async () => {
2742
+ if (isTeklaParserProject() && teklaUploadAbort && teklaUploadProjectId === current?.id) {
2743
+ teklaUploadAbort.abort();
2744
+ paintRevitSourceState('Cancelling read…', 'Stopping the copy. The source model and any existing snapshot remain unchanged.');
2745
+ return;
2746
+ }
2324
2747
  const projectId = current?.id;
2325
2748
  const operationId = revitActiveOperation?.operationId;
2326
2749
  if (!projectId || !operationId) return;
2327
2750
  try {
2328
- await api(`/api/model-imports/${encodeURIComponent(operationId)}/cancel`, { method: 'POST', body: '{}' });
2751
+ const cancelPath = isTeklaParserProject()
2752
+ ? `/api/tekla-imports/${encodeURIComponent(operationId)}/cancel`
2753
+ : `/api/model-imports/${encodeURIComponent(operationId)}/cancel`;
2754
+ await api(cancelPath, { method: 'POST', body: '{}' });
2329
2755
  revitActiveOperation = null;
2330
2756
  paintRevitSourceState('Replacement cancelled', 'The existing model was not changed.');
2331
2757
  paintRevitSourceActions('ready', true);
@@ -2333,7 +2759,7 @@
2333
2759
  } catch (error) {
2334
2760
  const status = error && error.status;
2335
2761
  showToast(status === 403
2336
- ? 'We couldn’t cancel this import because Revit access is not available for this account. Check your account access, then try again.'
2762
+ ? `We couldn’t cancel this import because ${isTeklaParserProject() ? 'Tekla Parser' : 'Revit'} access is not available for this account. Check your account access, then try again.`
2337
2763
  : status === 409
2338
2764
  ? 'We couldn’t cancel this import because it is already finishing. Refresh the project to see the result.'
2339
2765
  : 'We couldn’t cancel this import because FloLess could not save the request. Try again.', 'warn');
@@ -2501,7 +2927,9 @@
2501
2927
  // Waiting for FloLess to set an AI up creates nothing yet, so Cancel stays usable (#1607).
2502
2928
  if (busy && projectSetupState.settingUp) $projectSetupCancel.disabled = false;
2503
2929
  $projectSetupCreate.textContent = label || 'Create project & start chat';
2504
- $projectSetupCreateOnly.textContent = busy && !projectSetupState.settingUp ? 'Creating…' : (projectSetupState.kind === 'rvt' ? 'Create project' : 'Create project only');
2930
+ $projectSetupCreateOnly.textContent = busy && !projectSetupState.settingUp
2931
+ ? 'Creating…'
2932
+ : (['rvt', 'tekla-source'].includes(projectSetupState.kind) ? 'Create project' : 'Create project only');
2505
2933
  if (!busy) {
2506
2934
  $projectSetupCreate.disabled = !projectSetupReady();
2507
2935
  $projectSetupCreateOnly.disabled = !projectSetupReady();
@@ -2524,7 +2952,7 @@
2524
2952
  // conversation's AI, which may since have been uninstalled, and a choice that cannot start must
2525
2953
  // never be the one shown as chosen and sent.
2526
2954
  function projectSetupProvider(state) {
2527
- if (!state || state.kind === 'rvt') return null;
2955
+ if (!state || ['rvt', 'tekla-source'].includes(state.kind)) return null;
2528
2956
  const runtimes = bridge.chatProviderRuntimes?.() || [];
2529
2957
  const readiness = (id) => (id ? projectSetupProviderReadiness(runtimes.find((runtime) => runtime.id === id)) : 'unavailable');
2530
2958
  const canStart = (id) => readiness(id) !== 'unavailable';
@@ -2647,8 +3075,8 @@
2647
3075
  $projectSetupCreate.hidden = !provider;
2648
3076
  $projectSetupCreateOnly.classList.toggle('primary', !provider);
2649
3077
  $projectSetupTitle.textContent = `New ${descDisplayName(state.templateId)} project`;
2650
- $projectSetupSourceName.textContent = state.files[0]?.name || (state.kind === 'rvt' ? 'Revit model' : 'Drawing set');
2651
- $projectSetupCreateOnly.textContent = state.busy ? 'Creating…' : (state.kind === 'rvt' ? 'Create project' : 'Create project only');
3078
+ $projectSetupSourceName.textContent = state.sourceLabel || state.files[0]?.name || (state.kind === 'rvt' ? 'Revit model' : 'Drawing set');
3079
+ $projectSetupCreateOnly.textContent = state.busy ? 'Creating…' : (['rvt', 'tekla-source'].includes(state.kind) ? 'Create project' : 'Create project only');
2652
3080
  $projectSetupSourceCount.textContent = state.files.length > 1 ? `+ ${state.files.length - 1} more` : '';
2653
3081
  $projectSetupFolder.textContent = state.directory
2654
3082
  ? state.directory.path
@@ -2765,7 +3193,7 @@
2765
3193
  app: state.appId,
2766
3194
  ...(state.askCatalogue ? { environment: state.environment } : {}),
2767
3195
  directorySelectionId: state.directory.selectionId,
2768
- ...(state.kind === 'rvt' ? {} : { initialTask: { kind: 'drawing-intake', sourceNames: state.files.map((file) => file.name) } }),
3196
+ ...(['rvt', 'tekla-source'].includes(state.kind) ? {} : { initialTask: { kind: 'drawing-intake', sourceNames: state.files.map((file) => file.name) } }),
2769
3197
  };
2770
3198
  const { project } = await api('/api/projects', { method: 'POST', body: JSON.stringify(payload) });
2771
3199
  if (state.kind === 'rvt') {
@@ -2774,6 +3202,12 @@
2774
3202
  await importRvtIntoProject(project, state.files[0], state.appId);
2775
3203
  return;
2776
3204
  }
3205
+ if (state.kind === 'tekla-source') {
3206
+ setProjectSetupBusy(false);
3207
+ closeProjectSetup({ restoreFocus: false });
3208
+ await importTeklaIntoProject(project, state.teklaSource, state.appId);
3209
+ return;
3210
+ }
2777
3211
  projects.unshift(project);
2778
3212
  track('workspace_project_created', { app: state.appId });
2779
3213
  setProjectSetupBusy(false);
@@ -2858,12 +3292,12 @@
2858
3292
  * working directory. Nothing is written while the dialog is open. Creation atomically publishes
2859
3293
  * project.json and an unsent initial-task draft; the headless provider is not contacted here.
2860
3294
  */
2861
- async function createFromDrawing(appId, templateId, files, { kind = 'drawings' } = {}) {
2862
- if (!$projectSetup || projectSetupState) return;
2863
- if (!Array.isArray(files) || !files.length) return;
2864
- if (files.length > 20) {
3295
+ async function createFromDrawing(appId, templateId, files, { kind = 'drawings', sourceLabel = '', teklaSource = null, returnFocus = null } = {}) {
3296
+ if (!$projectSetup || projectSetupState) return false;
3297
+ if (!Array.isArray(files) || !files.length) return false;
3298
+ if (kind === 'drawings' && files.length > 20) {
2865
3299
  showToast('Choose up to 20 drawings for a new project.', 'warn');
2866
- return;
3300
+ return false;
2867
3301
  }
2868
3302
  const state = {
2869
3303
  appId,
@@ -2872,6 +3306,8 @@
2872
3306
  kind,
2873
3307
  chatProvider: null,
2874
3308
  providersRead: false,
3309
+ sourceLabel,
3310
+ teklaSource,
2875
3311
  askCatalogue: kind === 'drawings' && templateId === 'steel-model',
2876
3312
  environment: null,
2877
3313
  directory: null,
@@ -2879,7 +3315,7 @@
2879
3315
  nameDirty: false,
2880
3316
  sourceReady: false,
2881
3317
  busy: false,
2882
- returnFocus: document.activeElement instanceof HTMLElement ? document.activeElement : null,
3318
+ returnFocus: returnFocus || (document.activeElement instanceof HTMLElement ? document.activeElement : null),
2883
3319
  };
2884
3320
  projectSetupState = state;
2885
3321
  setProjectSetupError('');
@@ -2887,9 +3323,11 @@
2887
3323
  renderProjectSetup();
2888
3324
  $projectSetup.classList.add('show');
2889
3325
  $projectSetupFolderChoose.focus();
2890
- if (kind !== 'rvt') void refreshProjectSetupProviders(state);
3326
+ if (kind !== 'rvt' && kind !== 'tekla-source') void refreshProjectSetupProviders(state);
2891
3327
  try {
2892
- await Promise.all(files.map(assertProjectSourceReadable));
3328
+ if (kind !== 'tekla-source') {
3329
+ await Promise.all(files.map(assertProjectSourceReadable));
3330
+ }
2893
3331
  if (projectSetupState !== state) return;
2894
3332
  state.sourceReady = true;
2895
3333
  if (state.askCatalogue) {
@@ -2902,13 +3340,16 @@
2902
3340
  }
2903
3341
  }
2904
3342
  renderProjectSetup();
3343
+ return true;
2905
3344
  } catch (error) {
2906
3345
  if (projectSetupState !== state) return;
2907
3346
  console.warn('createFromDrawing: could not prepare project setup', error);
2908
- setProjectSetupError(state.askCatalogue
2909
- ? 'Couldn’t read the drawings or steel standards — choose the files again.'
2910
- : 'Couldn’t read the drawings — choose the files again.');
3347
+ setProjectSetupError(kind === 'tekla-source'
3348
+ ? 'Couldn’t read one or more files in this Tekla folder. Check access to the folder, then choose it again.'
3349
+ : state.askCatalogue ? 'Couldn’t read the drawings or steel standards — choose the files again.'
3350
+ : 'Couldn’t read the drawings — choose the files again.');
2911
3351
  renderProjectSetup();
3352
+ return true;
2912
3353
  }
2913
3354
  }
2914
3355
 
@@ -2969,45 +3410,129 @@
2969
3410
  if (detailNode) detailNode.textContent = detail;
2970
3411
  }
2971
3412
 
2972
- // mode: 'active' (import running) | 'imported' (this import just landed — offer to open it) |
2973
- // 'ready' (steady state / cancelled) | 'failed'.
3413
+ function teklaAdmissionMessage(error) {
3414
+ const message = error?.message || String(error || '');
3415
+ if (/No upload progress was detected for 30 seconds/i.test(message)) return 'No upload progress was detected for 30 seconds, so FloLess stopped this copy. No partial snapshot was saved, and the source ZIP was not changed.';
3416
+ if (/upload made no progress for 2 minutes/i.test(message)) return 'The Tekla ZIP upload made no progress for 2 minutes, so FloLess stopped this copy. No partial snapshot was saved, and the source ZIP was not changed.';
3417
+ if (/413|too large|payload too large/i.test(message)) return 'This Tekla ZIP is too large to copy in one read. Choose the model folder instead, or make a smaller ZIP and try again.';
3418
+ if (/401|403|sign.?in|unauthori[sz]ed|forbidden|access/i.test(message)) return 'FloLess could not confirm access for this read. Sign in again, then choose the Tekla source once more.';
3419
+ if (/failed to fetch|network|browser could not copy|source copy failed/i.test(message)) return 'FloLess could not finish copying this Tekla source. Check the connection, then choose the source again.';
3420
+ if (/layout|format|framing|integrity|verif|manifest|database/i.test(message)) return 'FloLess could not verify this Tekla source. Choose the model folder or ZIP again. The source model was not changed.';
3421
+ return 'FloLess could not read this Tekla source. Choose the model folder or ZIP again. The source model was not changed.';
3422
+ }
3423
+ function teklaAdmissionTitle(error) {
3424
+ const message = error?.message || String(error || '');
3425
+ return /No upload progress was detected for 30 seconds/i.test(message) ? 'Tekla ZIP copy stopped'
3426
+ : /layout|format|framing/i.test(message)
3427
+ ? 'We can’t safely read this model yet' : 'Tekla source needs attention';
3428
+ }
3429
+
3430
+ function configureReadOnlySourceChrome(project = current) {
3431
+ const tekla = isTeklaParserProject(project);
3432
+ const hasTeklaSource = tekla && !!revitSourceState?.source;
3433
+ if (!$revitOpenModel || !$revitReplace || !$revitRetry || !$revitCancel || !$revitReassure) return;
3434
+ $revitOpenModel.dataset.commandId = tekla ? 'tekla-parser.open-model' : 'revit.open-model';
3435
+ $revitOpenModel.dataset.tip = tekla
3436
+ ? 'Show the read-only snapshot on the Model tab. It stays a draft until approved.'
3437
+ : 'Show the imported model on the Model tab. It stays a draft until approved.';
3438
+ $revitReplace.textContent = tekla
3439
+ ? hasTeklaSource ? 'Replace Tekla source…' : 'Choose Tekla source…'
3440
+ : 'Replace RVT…';
3441
+ $revitReplace.dataset.commandId = tekla ? 'tekla-parser.replace-source' : 'revit.replace-import';
3442
+ $revitReplace.dataset.tip = tekla
3443
+ ? hasTeklaSource
3444
+ ? 'Choose a new Tekla model folder or ZIP. The current read-only snapshot remains available until the replacement is ready.'
3445
+ : 'Choose a Tekla model folder or ZIP to create a read-only snapshot.'
3446
+ : 'Choose a new RVT. The current model remains available until the replacement is ready.';
3447
+ $revitRetry.textContent = tekla ? '' : 'Try import again';
3448
+ if (tekla) {
3449
+ delete $revitRetry.dataset.commandId;
3450
+ delete $revitRetry.dataset.tip;
3451
+ } else {
3452
+ $revitRetry.dataset.commandId = 'revit.retry-import';
3453
+ $revitRetry.dataset.tip = 'Try importing the already stored RVT again.';
3454
+ }
3455
+ $revitCancel.textContent = tekla ? 'Cancel read' : 'Cancel import';
3456
+ $revitCancel.dataset.commandId = tekla ? 'tekla-parser.cancel-import' : 'revit.cancel-import';
3457
+ $revitCancel.dataset.tip = tekla
3458
+ ? 'Cancel this read. The existing read-only snapshot remains unchanged.'
3459
+ : 'Cancel this import. The existing model remains unchanged.';
3460
+ $revitReassure.textContent = tekla
3461
+ ? 'The current read-only snapshot remains unchanged until this read finishes.'
3462
+ : 'The current model remains unchanged until this import finishes.';
3463
+ window.__instructor?.notifyChanged();
3464
+ }
3465
+
2974
3466
  function paintRevitSourceActions(mode, canReplace = true, canRetry = true) {
2975
3467
  if (!$revitSourceActions) return;
3468
+ if (isTeklaParserProject()) canRetry = false;
3469
+ const busy = mode === 'active' || mode === 'uploading';
2976
3470
  $revitOpenModel.hidden = mode !== 'imported';
2977
- $revitReplace.hidden = mode === 'active' || !canReplace;
3471
+ $revitSourceActions.hidden = !canReplace && !busy && !(mode === 'failed' && canRetry) && mode !== 'imported';
3472
+ $revitReplace.hidden = busy || !canReplace;
2978
3473
  $revitRetry.hidden = mode !== 'failed' || !canRetry;
2979
3474
  $revitCancel.hidden = mode !== 'active';
2980
- $revitSourceActions.hidden = [$revitOpenModel, $revitReplace, $revitRetry, $revitCancel].every((b) => b.hidden);
2981
- $revitReassure.hidden = mode !== 'active';
2982
- // The spinner's hook is deliberately NOT aria-busy. This element IS the live region below, and
2983
- // pollRevitImport narrates the import through it by rewriting the title and detail; marking a
2984
- // live region busy tells assistive tech to withhold exactly those updates, so the change that
2985
- // gives sighted users a spinner would have taken the running commentary away from everyone else.
2986
- $sourcePlaceholder?.setAttribute('data-importing', String(mode === 'active'));
3475
+ $revitReassure.hidden = !busy;
3476
+ // This is also the live region: aria-busy would suppress spoken progress.
3477
+ $sourcePlaceholder?.setAttribute('data-importing', String(busy));
2987
3478
  $sourcePlaceholder?.setAttribute('role', mode === 'failed' ? 'alert' : 'status');
2988
3479
  $sourcePlaceholder?.setAttribute('aria-live', mode === 'failed' ? 'assertive' : 'polite');
2989
3480
  $sourcePlaceholder?.setAttribute('aria-atomic', 'true');
2990
3481
  }
2991
3482
 
3483
+ // Replacement admission needs a fresh generation, but it must not share the painter's
3484
+ // stale-response guard. A simultaneous project-open refresh can legitimately change the
3485
+ // displayed operation while this request is in flight; that must not silently discard the
3486
+ // user's already-selected source before its upload session is created.
3487
+ async function readReplacementSourceState(project) {
3488
+ if (!project || current?.id !== project.id) return null;
3489
+ const tekla = wsDescOf(project) === WORKSPACE_APPS['tekla-parser'];
3490
+ const response = await api(`/api/${tekla ? 'tekla' : 'revit'}-projects/${encodeURIComponent(project.id)}/source-state`);
3491
+ return current?.id === project.id ? response.state : null;
3492
+ }
3493
+
2992
3494
  async function refreshRevitSourceState(projectId = current?.id) {
2993
3495
  if (!projectId || !current || current.id !== projectId || wsDescOf(current)?.serverAuthorizedOnly !== true) return null;
3496
+ const operationAtRequest = revitActiveOperation;
2994
3497
  try {
2995
- const response = await api(`/api/revit-projects/${encodeURIComponent(projectId)}/source-state`);
3498
+ const tekla = isTeklaParserProject(current);
3499
+ const response = await api(`/api/${tekla ? 'tekla' : 'revit'}-projects/${encodeURIComponent(projectId)}/source-state`);
2996
3500
  if (!current || current.id !== projectId) return null;
3501
+ // A project-open status request may finish after a new upload has been admitted.
3502
+ // Never replace the newer operation with the older source-state response.
3503
+ if (revitActiveOperation !== operationAtRequest) return null;
2997
3504
  revitSourceState = response.state;
3505
+ configureReadOnlySourceChrome(current);
2998
3506
  revitActiveOperation = response.state.activeImport;
2999
- if (revitActiveOperation) {
3000
- paintRevitSourceState('Replacing source RVT…', 'The current model remains unchanged until this import finishes.');
3507
+ if (revitActiveOperation && !['ready', 'failed', 'cancelled'].includes(revitActiveOperation.state)) {
3508
+ paintRevitSourceState(tekla ? 'Reading Tekla source…' : 'Replacing source RVT…',
3509
+ `The current ${tekla ? 'read-only snapshot' : 'model'} remains unchanged until this ${tekla ? 'read' : 'import'} finishes.`);
3001
3510
  paintRevitSourceActions('active', true);
3002
3511
  pollRevitImport(revitActiveOperation.operationId, projectId);
3512
+ } else if (revitActiveOperation?.state === 'failed') {
3513
+ const failure = revitActiveOperation.failure;
3514
+ paintRevitSourceState(failure?.title || (tekla ? 'Tekla read failed' : 'Revit import failed'),
3515
+ failure?.message || (tekla
3516
+ ? 'Choose the Tekla model folder or ZIP again to start a new read.'
3517
+ : 'FloLess could not import this model. Try again or contact support if the problem continues.'));
3518
+ paintRevitSourceActions('failed', response.state.canReplace === true, failure?.retryable !== false);
3003
3519
  } else {
3004
3520
  const source = response.state.source;
3005
- paintRevitSourceState('Source RVT', source ? `${source.filename} · ${(source.bytes / (1024 * 1024)).toFixed(1)} MB` : 'Choose an RVT to read into this project.');
3006
- paintRevitSourceActions('ready', response.state.canReplace === true);
3521
+ const admissionFailure = tekla ? teklaAdmissionFailures.get(projectId) : null;
3522
+ if (admissionFailure) {
3523
+ paintRevitSourceState(admissionFailure.title, admissionFailure.message);
3524
+ paintRevitSourceActions('failed', response.state.canReplace === true, false);
3525
+ } else {
3526
+ paintRevitSourceState(tekla ? 'Tekla source · Read-only' : 'Source RVT', source
3527
+ ? `${source.filename} · ${(source.bytes / (1024 * 1024)).toFixed(1)} MB`
3528
+ : tekla ? 'Choose a Tekla model folder or ZIP to create a read-only snapshot.' : 'Choose an RVT to read into this project.');
3529
+ paintRevitSourceActions('ready', response.state.canReplace === true);
3530
+ }
3007
3531
  }
3008
3532
  return response.state;
3009
3533
  } catch (error) {
3010
- paintRevitSourceState('Revit source unavailable', error && error.message || 'Could not read source status.');
3534
+ if (!current || current.id !== projectId || revitActiveOperation !== operationAtRequest) return null;
3535
+ paintRevitSourceState(isTeklaParserProject() ? 'Tekla source unavailable' : 'Revit source unavailable', error && error.message || 'Could not read source status.');
3011
3536
  paintRevitSourceActions('ready', false);
3012
3537
  return null;
3013
3538
  }
@@ -3036,19 +3561,209 @@
3036
3561
  return started.operation;
3037
3562
  }
3038
3563
 
3564
+ const TEKLA_COPY_STALL_MS = 30_000;
3565
+ const TEKLA_COPY_ACTIVE_STALL_MS = 2 * 60_000;
3566
+ const TEKLA_ZIP_CHUNK_BYTES = 8 * 1024 * 1024;
3567
+ async function copyTeklaSourceBytes(url, file, { signal, relativePath = '', onProgress = () => {} } = {}) {
3568
+ const chunked = !relativePath && file.size > TEKLA_ZIP_CHUNK_BYTES;
3569
+ const sendChunk = async (blob, offset) => {
3570
+ const controller = new AbortController();
3571
+ let stalled = false;
3572
+ const abort = () => controller.abort();
3573
+ const timer = setTimeout(() => { stalled = true; controller.abort(); }, TEKLA_COPY_STALL_MS);
3574
+ signal?.addEventListener('abort', abort, { once: true });
3575
+ try {
3576
+ const response = await fetch(url, { method: 'PUT', credentials: 'same-origin', body: blob, signal: controller.signal,
3577
+ headers: { 'content-type': 'application/octet-stream', 'x-floless-upload-offset': String(offset),
3578
+ 'x-floless-upload-total': String(file.size) } });
3579
+ const body = await response.json().catch(() => ({}));
3580
+ if (!response.ok || body.ok === false) throw new Error(body.message || body.error || `source copy failed (${response.status})`);
3581
+ onProgress(Math.min(file.size, offset + blob.size), file.size);
3582
+ return body;
3583
+ } catch (error) {
3584
+ if (stalled) throw new Error('No upload progress was detected for 30 seconds, so FloLess stopped this copy. No partial snapshot was saved, and the source ZIP was not changed.');
3585
+ if (signal?.aborted) throw new DOMException('Read cancelled', 'AbortError');
3586
+ throw error;
3587
+ } finally {
3588
+ clearTimeout(timer);
3589
+ signal?.removeEventListener('abort', abort);
3590
+ }
3591
+ };
3592
+ const send = (blob, offset) => new Promise((resolve, reject) => {
3593
+ const xhr = new XMLHttpRequest();
3594
+ let settled = false;
3595
+ let stallTimer = null;
3596
+ let lastLoaded = 0;
3597
+ let stalledError = null;
3598
+ const cleanup = () => {
3599
+ if (stallTimer !== null) clearTimeout(stallTimer);
3600
+ signal?.removeEventListener('abort', abortFromSignal);
3601
+ };
3602
+ const finish = (error, value) => {
3603
+ if (settled) return;
3604
+ settled = true;
3605
+ cleanup();
3606
+ if (error) reject(error); else resolve(value);
3607
+ };
3608
+ const armStall = (timeoutMs = TEKLA_COPY_STALL_MS) => {
3609
+ if (stallTimer !== null) clearTimeout(stallTimer);
3610
+ stallTimer = setTimeout(() => {
3611
+ stalledError = new Error(timeoutMs === TEKLA_COPY_STALL_MS
3612
+ ? 'No upload progress was detected for 30 seconds, so FloLess stopped this copy. No partial snapshot was saved, and the source ZIP was not changed.'
3613
+ : 'The Tekla ZIP upload made no progress for 2 minutes, so FloLess stopped this copy. No partial snapshot was saved, and the source ZIP was not changed.');
3614
+ xhr.abort();
3615
+ }, timeoutMs);
3616
+ };
3617
+ const abortFromSignal = () => xhr.abort();
3618
+ xhr.open('PUT', url, true);
3619
+ xhr.withCredentials = true;
3620
+ xhr.responseType = 'json';
3621
+ xhr.setRequestHeader('content-type', 'application/octet-stream');
3622
+ if (relativePath) xhr.setRequestHeader('x-floless-relative-path', encodeURIComponent(relativePath));
3623
+ xhr.upload.addEventListener('progress', (event) => {
3624
+ if (event.loaded <= lastLoaded) return;
3625
+ lastLoaded = event.loaded;
3626
+ armStall(TEKLA_COPY_ACTIVE_STALL_MS);
3627
+ onProgress(offset + event.loaded, file.size);
3628
+ });
3629
+ xhr.addEventListener('load', () => {
3630
+ const body = xhr.response && typeof xhr.response === 'object' ? xhr.response : (() => {
3631
+ try { return JSON.parse(xhr.responseText || '{}'); } catch { return {}; }
3632
+ })();
3633
+ if (xhr.status < 200 || xhr.status >= 300 || body.ok === false) {
3634
+ finish(new Error(body.message || body.error || `source copy failed (${xhr.status})`));
3635
+ return;
3636
+ }
3637
+ finish(null, body);
3638
+ });
3639
+ xhr.addEventListener('error', () => finish(new Error('The browser could not copy the Tekla source to FloLess. Choose the source again.')));
3640
+ xhr.addEventListener('abort', () => finish(stalledError || new DOMException('Read cancelled', 'AbortError')));
3641
+ if (signal?.aborted) { finish(new DOMException('Read cancelled', 'AbortError')); return; }
3642
+ signal?.addEventListener('abort', abortFromSignal, { once: true });
3643
+ xhr.send(blob);
3644
+ armStall();
3645
+ });
3646
+ if (!chunked) return send(file, 0);
3647
+ let response = null;
3648
+ for (let offset = 0; offset < file.size; offset += TEKLA_ZIP_CHUNK_BYTES) {
3649
+ response = await sendChunk(file.slice(offset, Math.min(file.size, offset + TEKLA_ZIP_CHUNK_BYTES)), offset);
3650
+ }
3651
+ return response;
3652
+ }
3653
+
3654
+ async function uploadTeklaForProject(project, source, generation) {
3655
+ if (!source || !['folder', 'zip'].includes(source.kind) || !Array.isArray(source.entries)) throw new Error('Choose a Tekla model folder or ZIP.');
3656
+ const controller = new AbortController();
3657
+ teklaUploadAbort = controller;
3658
+ teklaUploadProjectId = project.id;
3659
+ const isCurrentProject = () => current?.id === project.id;
3660
+ const declaredFiles = source.kind === 'folder'
3661
+ ? source.entries.map((entry) => ({ path: entry.path, bytes: entry.file.size })) : undefined;
3662
+ let sessionId = null;
3663
+ let finishAttempted = false;
3664
+ try {
3665
+ if (isCurrentProject()) {
3666
+ paintRevitSourceState('Checking Tekla files…', 'Preparing a read-only copy. The source model remains unchanged.');
3667
+ paintRevitSourceActions('active', true);
3668
+ }
3669
+ const created = await api(`/api/tekla-projects/${encodeURIComponent(project.id)}/source-sessions`, {
3670
+ method: 'POST', signal: controller.signal,
3671
+ body: JSON.stringify({ generation, kind: source.kind, ...(declaredFiles ? { files: declaredFiles } : {}) }),
3672
+ });
3673
+ sessionId = created.session?.id;
3674
+ if (!sessionId) throw new Error('FloLess could not start the secure Tekla source upload.');
3675
+ const entries = source.entries;
3676
+ const totalBytes = entries.reduce((sum, entry) => sum + entry.file.size, 0);
3677
+ let copiedBytes = 0;
3678
+ let copiedFiles = 0;
3679
+ let nextIndex = 0;
3680
+ let uploadError = null;
3681
+ let lastPaintedPercent = -1;
3682
+ const copyOne = async () => {
3683
+ while (nextIndex < entries.length && !controller.signal.aborted) {
3684
+ const entry = entries[nextIndex++];
3685
+ const endpoint = source.kind === 'zip' ? 'archive' : 'files';
3686
+ try {
3687
+ await copyTeklaSourceBytes(`/api/tekla-source-sessions/${encodeURIComponent(sessionId)}/${endpoint}`, entry.file, {
3688
+ signal: controller.signal,
3689
+ relativePath: source.kind === 'folder' ? entry.path : '',
3690
+ onProgress: (loaded) => {
3691
+ if (!isCurrentProject()) return;
3692
+ const currentBytes = copiedBytes + loaded;
3693
+ const percent = Math.min(99, Math.floor((currentBytes / totalBytes) * 100));
3694
+ if (percent === lastPaintedPercent && loaded < entry.file.size) return;
3695
+ lastPaintedPercent = percent;
3696
+ paintRevitSourceState(`${source.kind === 'zip' ? 'Copying Tekla ZIP' : 'Copying Tekla model'} · ${percent}%`,
3697
+ loaded >= entry.file.size ? 'Finishing the secure copy…'
3698
+ : `${(currentBytes / 1048576).toFixed(1)} of ${(totalBytes / 1048576).toFixed(1)} MB copied to FloLess…`);
3699
+ },
3700
+ });
3701
+ copiedBytes += entry.file.size;
3702
+ copiedFiles++;
3703
+ if (isCurrentProject()) paintRevitSourceState(source.kind === 'zip' ? 'Copying Tekla ZIP' : 'Copying Tekla model',
3704
+ source.kind === 'zip' ? `Copying ${entry.file.name} for this read…`
3705
+ : `Copied ${copiedFiles} of ${entries.length} files · ${(copiedBytes / 1048576).toFixed(1)} of ${(totalBytes / 1048576).toFixed(1)} MB…`);
3706
+ } catch (error) {
3707
+ if (!uploadError || uploadError.name === 'AbortError') uploadError = error;
3708
+ controller.abort();
3709
+ return;
3710
+ }
3711
+ }
3712
+ };
3713
+ if (isCurrentProject()) {
3714
+ paintRevitSourceState(source.kind === 'zip' ? 'Copying Tekla ZIP' : 'Copying Tekla model',
3715
+ source.kind === 'zip' ? `Copying ${entries[0].file.name} for this read…` : `Copied 0 of ${entries.length} files · 0.0 of ${(totalBytes / 1048576).toFixed(1)} MB…`);
3716
+ paintRevitSourceActions('active', true);
3717
+ }
3718
+ await Promise.all(Array.from({ length: Math.min(source.kind === 'folder' ? 8 : 1, entries.length) }, copyOne));
3719
+ if (uploadError) throw uploadError;
3720
+ if (controller.signal.aborted) throw new DOMException('Read cancelled', 'AbortError');
3721
+ // Finalize can admit a durable server operation even if its HTTP response is lost. The
3722
+ // browser may cancel only the copy phase; after this boundary, use the operation's real
3723
+ // cancel route once its ID is known. Never claim cancellation of an already admitted read.
3724
+ if (teklaUploadAbort === controller) { teklaUploadAbort = null; teklaUploadProjectId = null; }
3725
+ if (isCurrentProject()) {
3726
+ paintRevitSourceState('Checking Tekla model…', 'Checking the copied model before reading it. This check cannot be cancelled.');
3727
+ paintRevitSourceActions('uploading', true);
3728
+ }
3729
+ // A completed admission owns session cleanup. Retrying DELETE after its refusal only produces
3730
+ // a spurious browser error for a session it already removed; earlier upload failures still delete.
3731
+ finishAttempted = true;
3732
+ const started = await api(`/api/tekla-source-sessions/${encodeURIComponent(sessionId)}/finalize`, {
3733
+ method: 'POST', body: JSON.stringify({ projectId: project.id }),
3734
+ });
3735
+ teklaAdmissionFailures.delete(project.id);
3736
+ if (isCurrentProject()) {
3737
+ revitSourceState = { ...(revitSourceState || {}), generation: generation + 1 };
3738
+ revitActiveOperation = started.operation;
3739
+ }
3740
+ return started.operation;
3741
+ } finally {
3742
+ if (!finishAttempted && sessionId) {
3743
+ await fetch(`/api/tekla-source-sessions/${encodeURIComponent(sessionId)}`, { method: 'DELETE', credentials: 'same-origin' }).catch(() => {});
3744
+ }
3745
+ if (teklaUploadAbort === controller) { teklaUploadAbort = null; teklaUploadProjectId = null; }
3746
+ }
3747
+ }
3748
+
3039
3749
  async function pollRevitImport(operationId, projectId, retryAttempt = 0) {
3750
+ const pollKey = `${projectId}:${operationId}`;
3751
+ if (activeImportPolls.has(pollKey)) return;
3752
+ activeImportPolls.add(pollKey);
3040
3753
  const isCurrentImport = () => current?.id === projectId && revitActiveOperation?.operationId === operationId;
3754
+ try {
3041
3755
  for (;;) {
3042
3756
  await new Promise((resolve) => setTimeout(resolve, 800));
3043
3757
  if (!isCurrentImport()) return;
3044
3758
  let operation;
3045
- try { ({ operation } = await api(`/api/model-imports/${encodeURIComponent(operationId)}`)); }
3759
+ try { ({ operation } = await api(`/api/${isTeklaParserProject() ? 'tekla-imports' : 'model-imports'}/${encodeURIComponent(operationId)}`)); }
3046
3760
  catch (err) {
3047
3761
  // A routine auth/lock response does not prove the operation disappeared. Only the two
3048
3762
  // explicit absence responses may clear it; every other outage retains the live import.
3049
3763
  if (!isCurrentImport()) return;
3050
- paintRevitSourceState('Import status unavailable', err?.status === 403
3051
- ? 'Revit access is not available for this account right now. FloLess will keep checking.'
3764
+ const tekla = isTeklaParserProject();
3765
+ paintRevitSourceState(tekla ? 'Read status unavailable' : 'Import status unavailable', err?.status === 403
3766
+ ? `${tekla ? 'Tekla Parser' : 'Revit'} access is not available for this account right now. FloLess will keep checking.`
3052
3767
  : 'FloLess couldn’t check this import. It will try again shortly.');
3053
3768
  if (err?.status === 404 || err?.status === 410) {
3054
3769
  revitActiveOperation = null;
@@ -3058,47 +3773,70 @@
3058
3773
  // Status polling is advisory. Back off boundedly after transient server/network failures
3059
3774
  // so the viewer recovers without hammering a degraded local server.
3060
3775
  const retryDelay = Math.min(30_000, 2_000 * (2 ** Math.min(retryAttempt, 4)));
3061
- if (isCurrentImport()) {
3062
- setTimeout(() => { void pollRevitImport(operationId, projectId, retryAttempt + 1); }, retryDelay);
3063
- }
3064
- return;
3776
+ await new Promise((resolve) => setTimeout(resolve, retryDelay));
3777
+ if (!isCurrentImport()) return;
3778
+ retryAttempt++;
3779
+ continue;
3065
3780
  }
3066
3781
  if (!isCurrentImport()) return;
3782
+ const tekla = isTeklaParserProject();
3067
3783
  const copy = {
3068
- 'waiting-for-aware': ['Waiting for AWARE', 'Your RVT is stored locally and waiting for the trusted reader.'],
3069
- converting: ['Reading model', 'Reading model geometry and properties…'],
3784
+ 'waiting-for-aware': ['Waiting for AWARE', tekla ? 'Your copied Tekla source is waiting for the entitled read-only parser.' : 'Your RVT is stored locally and waiting for the trusted reader.'],
3785
+ converting: [tekla ? 'Reading source' : 'Reading model', 'Reading model geometry and properties…'],
3070
3786
  validating: ['Checking model integrity', 'Verifying the signed source and display packages…'],
3071
3787
  publishing: ['Publishing draft', 'Saving the verified read-only model snapshot…'],
3072
3788
  }[operation.state];
3073
3789
  if (copy) { paintRevitSourceState(copy[0], copy[1]); continue; }
3074
3790
  if (operation.state === 'ready') {
3075
3791
  revitActiveOperation = null;
3076
- paintRevitSourceState('Model ready to review', 'Imported as a draft — not approved yet.');
3792
+ paintRevitSourceState(tekla ? 'Read-only snapshot ready to review' : 'Model ready to review', 'The model is available on the Model tab. It is not approved yet.');
3077
3793
  paintRevitSourceActions('imported', true);
3078
3794
  // A Model tab opened during conversion has already loaded its temporary "unavailable" state.
3079
3795
  // Invalidate that frame now: reload immediately when visible, or on the next tab activation.
3080
3796
  reloadModelFromServerTruth();
3081
- showToast('Revit model is ready to review.', 'ok');
3797
+ // The initial approval check was intentionally held while the import was active.
3798
+ // Recheck both gates now, without requiring a tab switch or page reload.
3799
+ await refreshModelPresence(projectId, current.app, true);
3800
+ await refreshApprovalState(projectId);
3801
+ showToast(tekla ? 'Tekla Parser snapshot is ready to review.' : 'Revit model is ready to review.', 'ok');
3082
3802
  return;
3083
3803
  }
3084
3804
  if (operation.state === 'cancelled') {
3085
3805
  revitActiveOperation = null;
3086
- paintRevitSourceState('Replacement cancelled', 'The existing model was not changed.');
3806
+ paintRevitSourceState('Replacement cancelled', tekla ? 'The existing read-only snapshot was not changed.' : 'The existing model was not changed.');
3087
3807
  paintRevitSourceActions('ready', true);
3808
+ await refreshModelPresence(projectId, current.app, true);
3809
+ await refreshApprovalState(projectId);
3088
3810
  return;
3089
3811
  }
3090
3812
  revitActiveOperation = operation;
3091
3813
  const failure = operation.failure;
3092
- paintRevitSourceState(failure?.title || 'Revit import failed',
3093
- failure?.message || 'FloLess could not import this model. Try again or contact support if the problem continues.');
3094
- paintRevitSourceActions('failed', revitSourceState?.canReplace === true, failure?.retryable !== false);
3095
- if (failure?.retryable !== false) queueMicrotask(() => $revitRetry?.focus());
3814
+ paintRevitSourceState(failure?.title || (tekla ? 'Tekla read failed' : 'Revit import failed'),
3815
+ failure?.message || (tekla
3816
+ ? 'Choose the Tekla model folder or ZIP again to start a new read.'
3817
+ : 'FloLess could not import this model. Try again or contact support if the problem continues.'));
3818
+ paintRevitSourceActions('failed', revitSourceState?.canReplace === true, !tekla && failure?.retryable !== false);
3819
+ await refreshModelPresence(projectId, current.app, true);
3820
+ await refreshApprovalState(projectId);
3821
+ if (!tekla && failure?.retryable !== false && !$revitRetry?.hidden) queueMicrotask(() => $revitRetry?.focus());
3096
3822
  return;
3097
3823
  }
3824
+ } finally { activeImportPolls.delete(pollKey); }
3098
3825
  }
3099
3826
 
3100
3827
  // An RVT project is created like a drawing project: the setup dialog asks for the project folder
3101
3828
  // and name (every project lives in a chosen working directory), then the RVT is uploaded and imported.
3829
+ function createFromTeklaSource(appId, templateId, source, returnFocus = null) {
3830
+ if (!source || !['folder', 'zip'].includes(source.kind) || !Array.isArray(source.entries) || !source.entries.length) return false;
3831
+ if (source.kind === 'folder' && !source.entries.some((entry) => /\.db1$/i.test(entry.path) && !/(?:^|\/)xslib\.db1$/i.test(entry.path))) {
3832
+ showToast('That folder is not a Tekla model folder.', 'warn');
3833
+ return false;
3834
+ }
3835
+ return createFromDrawing(appId, templateId, source.entries.map((entry) => entry.file), {
3836
+ kind: 'tekla-source', sourceLabel: source.label, teklaSource: source, returnFocus,
3837
+ });
3838
+ }
3839
+
3102
3840
  function createFromRvt(appId, templateId, file) {
3103
3841
  if (!file || !/\.rvt$/i.test(file.name)) { showToast('Choose one Revit .rvt file.', 'warn'); return; }
3104
3842
  return createFromDrawing(appId, templateId, [file], { kind: 'rvt' });
@@ -3111,7 +3849,8 @@
3111
3849
  projects.unshift(project);
3112
3850
  await openProject(project.id, 'drawings');
3113
3851
  paintRevitSourceState('Waiting for AWARE', 'Your RVT is stored locally and waiting for the trusted reader.');
3114
- if (!revitActiveOperation) { revitActiveOperation = operation; pollRevitImport(operation.operationId, project.id); }
3852
+ if (revitActiveOperation?.operationId !== operation.operationId) revitActiveOperation = operation;
3853
+ pollRevitImport(operation.operationId, project.id);
3115
3854
  } catch (err) {
3116
3855
  const removed = await archiveEmptyProject(project.id);
3117
3856
  showToast(removed
@@ -3120,6 +3859,37 @@
3120
3859
  }
3121
3860
  }
3122
3861
 
3862
+ async function importTeklaIntoProject(project, source, appId) {
3863
+ try {
3864
+ track('workspace_project_created', { app: appId });
3865
+ if (!projects.some((entry) => entry.id === project.id)) projects.unshift(project);
3866
+ await openProject(project.id, 'drawings');
3867
+ const operation = await uploadTeklaForProject(project, source, 0);
3868
+ if (current?.id === project.id) {
3869
+ paintRevitSourceState('Waiting for AWARE', 'Your copied Tekla source is waiting for the entitled read-only parser.');
3870
+ if (revitActiveOperation?.operationId !== operation.operationId) revitActiveOperation = operation;
3871
+ pollRevitImport(operation.operationId, project.id);
3872
+ }
3873
+ } catch (error) {
3874
+ if (error?.name === 'AbortError') {
3875
+ if (current?.id === project.id) {
3876
+ paintRevitSourceState('Read cancelled', 'No read-only snapshot was created. The source Tekla model was not changed.');
3877
+ paintRevitSourceActions('ready', revitSourceState?.canReplace === true);
3878
+ }
3879
+ return;
3880
+ }
3881
+ const message = teklaAdmissionMessage(error);
3882
+ const title = teklaAdmissionTitle(error);
3883
+ teklaAdmissionFailures.set(project.id, { title, message });
3884
+ if (!projects.some((entry) => entry.id === project.id)) projects.unshift(project);
3885
+ if (current?.id === project.id) {
3886
+ paintRevitSourceState(title, message);
3887
+ paintRevitSourceActions('failed', revitSourceState?.canReplace === true, false);
3888
+ showToast('Tekla source needs attention. The reason and next step are shown on the Source pane.', 'warn');
3889
+ }
3890
+ }
3891
+ }
3892
+
3123
3893
  // Best-effort rollback of a just-created empty project (the existing archive path — recoverable).
3124
3894
  // Returns true if the archive POST succeeded (removed server-side), false if it failed (a dead
3125
3895
  // empty project was left behind) so the caller can tell the truth in its toast. Either way the
@@ -3150,6 +3920,8 @@
3150
3920
  return;
3151
3921
  }
3152
3922
  current = p;
3923
+ revitSourceState = null;
3924
+ revitActiveOperation = null;
3153
3925
  // Project lifecycle is project-scoped. Reset it before the first setStep so one project's model
3154
3926
  // cannot unlock another project's tabs (or one empty project redirect a modeled project forever).
3155
3927
  projectContractLifecycle = 'unknown';
@@ -3162,6 +3934,7 @@
3162
3934
  exportState = null;
3163
3935
  exportUnits = null; // a new project's units arrive with its export listing; never inherit the last one's
3164
3936
  renderReadinessState = null;
3937
+ let sourceStateProbe = null;
3165
3938
  track('workspace_project_opened', { app: p.app }); // a real open (card click or post-create landing)
3166
3939
  resetRevisionState(); closeRevisionDiscard(false, false); closeRevReview(); // fresh project — drop any prior revision state and any open review
3167
3940
  // Per-project, like everything above it: never let one project's answer describe another's. Not
@@ -3176,17 +3949,19 @@
3176
3949
  // left empty when the app has no filter step (vectorize — its Source step shows a placeholder).
3177
3950
  const d = wsDescOf(p); // guaranteed present — the guard above bailed on an unknown app
3178
3951
  if (d.serverAuthorizedOnly === true) {
3952
+ configureReadOnlySourceChrome(p);
3179
3953
  try {
3180
3954
  const session = await fetch('/api/editor/session', { method: 'POST', credentials: 'same-origin' });
3181
3955
  if (!session.ok) throw new Error(`HTTP ${session.status}`);
3182
3956
  } catch (error) {
3183
- showToast('Couldn’t start the secure Revit editor session.', 'warn');
3957
+ showToast(`Couldn’t start the secure ${isTeklaParserProject(p) ? 'Tekla Parser' : 'Revit'} editor session.`, 'warn');
3184
3958
  current = null;
3185
3959
  return;
3186
3960
  }
3187
- paintRevitSourceState('Revit source', 'Checking the current RVT and import state…');
3961
+ paintRevitSourceState(isTeklaParserProject(p) ? 'Tekla source · Read-only' : 'Revit source',
3962
+ isTeklaParserProject(p) ? 'Checking the copied source and read-only snapshot…' : 'Checking the current RVT and import state…');
3188
3963
  paintRevitSourceActions('ready', false);
3189
- void refreshRevitSourceState(p.id);
3964
+ sourceStateProbe = refreshRevitSourceState(p.id);
3190
3965
  } else {
3191
3966
  // This pane is shared with the apps that have no filter step (vectorize), and only the branch
3192
3967
  // above ever repaints it. Without this reset, opening one of those straight after a Revit
@@ -3194,7 +3969,7 @@
3194
3969
  // import that would act on the OTHER project's operation.
3195
3970
  paintRevitSourceActions('ready', false);
3196
3971
  }
3197
- if (d.filter && ['model', 'exports', 'history'].includes(initialStep)) {
3972
+ if ((d.filter || d.serverAuthorizedOnly === true) && ['model', 'exports', 'history'].includes(initialStep)) {
3198
3973
  pendingPresenceStep = { projectId: p.id, step: initialStep };
3199
3974
  }
3200
3975
  // The LIVE app id, deliberately: the frames address the server with it (contract reads, saves),
@@ -3225,7 +4000,7 @@
3225
4000
  // status and `approvalSettled` SYNCHRONOUSLY, before its first await, so any render that follows
3226
4001
  // this line sees a probe to park on. The waiter is deliberately NOT taught to block on a
3227
4002
  // not-yet-started probe — that would hang any surface rendered outside a project open.
3228
- refreshApprovalState(p.id).catch((e) => console.error('[workspaces] could not load approval state', e));
4003
+ refreshApprovalState(p.id, sourceStateProbe).catch((e) => console.error('[workspaces] could not load approval state', e));
3229
4004
  // A steel project's lifecycle answer arrives asynchronously. Do not briefly open (or falsely
3230
4005
  // refuse) a later stage while that answer is unknown: hold the requested destination, show the
3231
4006
  // first actionable stage, and restore the destination only after an explicit `model` answer.