@floless/app 0.113.7 → 0.115.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.
@@ -113,7 +113,15 @@
113
113
  }
114
114
 
115
115
  let exportState = null; // kind → { path, exportedAt } after a successful list; null = unknown/failed
116
- let teklaReadinessState = null; // latest machine-readable readiness result; {state:'checking'} while probing
116
+ // Readiness per CAD destination: host id → the server's readiness object, or {state:'checking'}
117
+ // while probing. Tekla answers from /api/tekla-readiness (a richer probe that can tell "open but
118
+ // no model loaded"); the other three from /api/host-readiness/:host. Same shape either way, which
119
+ // is what lets one row template serve all four.
120
+ let hostReadinessStates = {};
121
+ // The destinations picked last time, per project. A convenience only — re-validated against live
122
+ // readiness every time the chooser opens, so a remembered host that has since gone down cannot
123
+ // come back pre-ticked.
124
+ const hostChoices = new Map();
117
125
  // Same shape for the Render card. Rendering needs AWARE >= 0.103.0 AND Blender on the machine,
118
126
  // neither of which floless can assume, so the card reports which one to fix rather than offering
119
127
  // a button that fails. The server re-checks on POST — this badge can be minutes stale.
@@ -198,10 +206,19 @@
198
206
  ],
199
207
  diff: true, // steel semantic diff expander
200
208
  exports: [
201
- { kind: 'bom-csv', ico: '▤', name: 'Bill of materials', fmt: 'CSV', verb: 'Export CSV', file: true, open: true },
202
- { kind: 'bom-xlsx', ico: '▦', name: 'Bill of materials', fmt: 'XLSX', verb: 'Export Excel', file: true, open: true },
209
+ // ONE card, THREE export kinds (bom-csv / bom-xlsx / bom-html). It was a card per file format
210
+ // while there were two; the report made three, and three tiles of the same bill is a grid that
211
+ // says "pick a card" when the real question is "which columns, and in what". `file:false`
212
+ // because a card fronting several kinds cannot state its status through the single-kind
213
+ // exportState path — bomCardState lists one row per file actually produced, like Render.
214
+ { kind: 'bom', ico: '▤', name: 'Bill of materials', fmt: 'CSV · XLSX · Report', verb: 'Export BOM', file: false },
203
215
  { kind: 'ifc', ico: '◈', name: 'Model', fmt: 'IFC4', verb: 'Export IFC', file: true, open: false },
204
- { kind: 'tekla', ico: '◧', name: 'Tekla', fmt: 'Native parts', verb: 'Send to Tekla', file: false },
216
+ // ONE card for every CAD destination, not one per application. It was Tekla-only while
217
+ // Tekla was the only host that could receive a model; Revit, SketchUp and Rhino now can
218
+ // too, and four cards would mean three permanently "not ready" tiles for tools a given
219
+ // firm may never open — plus four bridge probes on every tab open. The card names the
220
+ // destination it is ready to send to; its button opens the chooser for the rest.
221
+ { kind: 'send-host', ico: '◧', name: 'CAD model', fmt: 'Native objects', verb: 'Send to a CAD app', file: false },
205
222
  // Yields a URL, not a file, so none of the exportState/receipt plumbing applies — its status
206
223
  // comes from shareCardState and its result is a link with a Copy button (see cardHtml).
207
224
  { kind: 'share-3d', ico: '↗', name: 'Model', fmt: 'Shareable web link', verb: 'Create share link', file: false },
@@ -1007,7 +1024,7 @@
1007
1024
  }
1008
1025
  current = p;
1009
1026
  exportState = null;
1010
- teklaReadinessState = null;
1027
+ hostReadinessStates = {};
1011
1028
  renderReadinessState = null;
1012
1029
  track('workspace_project_opened', { app: p.app }); // a real open (card click or post-create landing)
1013
1030
  lastRevState = 'none'; stopRevisionPoll(); closeRevReview(); // fresh project — drop any prior revision-poll state and any open review
@@ -1045,7 +1062,7 @@
1045
1062
  function closeProject() {
1046
1063
  current = null;
1047
1064
  exportState = null;
1048
- teklaReadinessState = null;
1065
+ hostReadinessStates = {};
1049
1066
  renderReadinessState = null;
1050
1067
  stopRevisionPoll();
1051
1068
  stopKnowledgePoll(); kbCloseConfirm(); kbResetViewer(); knowledgeState = null; // the KB pane is per-project — never carry it across
@@ -2364,12 +2381,19 @@
2364
2381
  function exportUrl(kind, projectId, appId) {
2365
2382
  const qs = `?project=${encodeURIComponent(projectId)}`;
2366
2383
  const base = `/api/contract/${encodeURIComponent(appId)}`;
2384
+ // The BATCH route: one request, one project lock, every picked format. Three separate requests
2385
+ // would release the lock between formats — long enough for a render to take it and leave this
2386
+ // card waiting minutes — and would let the workbook see a different approved version than the CSV.
2387
+ if (kind === 'bom') return `${base}/export-bom${qs}`;
2367
2388
  if (kind === 'bom-csv') return `${base}/export-bom/csv${qs}`;
2368
2389
  if (kind === 'bom-xlsx') return `${base}/export-bom/xlsx${qs}`;
2369
2390
  if (kind === 'ifc') return `${base}/export-ifc${qs}`;
2370
2391
  if (kind === 'svg') return `${base}/export-svg${qs}`;
2371
2392
  if (kind === 'render') return `${base}/render${qs}`;
2372
- return `${base}/export-tekla${qs}`; // tekla
2393
+ // Sends to a live CAD application do NOT come through here — they are per-destination and go
2394
+ // via hostSendUrl(). Anything reaching this line is a kind nobody wired up; refusing beats
2395
+ // silently POSTing it at whichever route used to be the fallback.
2396
+ throw new Error(`no export route for "${kind}"`);
2373
2397
  }
2374
2398
 
2375
2399
  // Every existing card is one button with no options, and the grid's rhythm depends on that — so
@@ -2454,11 +2478,16 @@
2454
2478
  : null),
2455
2479
  fields: [
2456
2480
  {
2457
- // Multi-select: a drawing pack usually wants several angles, and rendering them one at
2458
- // a time meant reopening this dialog per angle. Each picked viewpoint becomes its own
2459
- // artifact — they no longer overwrite one another.
2460
- name: 'viewpoint', label: 'Viewpoints', type: 'select', multiple: true,
2461
- placeholder: 'Pick one or more',
2481
+ // Several angles at once: a drawing pack usually wants more than one, and rendering them
2482
+ // one at a time meant reopening this dialog per angle. Each picked viewpoint becomes its
2483
+ // own artifact — they no longer overwrite one another.
2484
+ //
2485
+ // A CHECKLIST, not a multi-select combo — and that is the app-wide rule now: a field that
2486
+ // takes SEVERAL answers shows tick-boxes, a combo picks exactly one. The two patterns had
2487
+ // drifted apart (viewpoints hidden in a popover, CAD destinations as tick-boxes) and read
2488
+ // as two different products. Seven short angles also fit on screen at once, so the
2489
+ // popover was hiding the whole choice behind a click and buying nothing for it.
2490
+ name: 'viewpoint', label: 'Viewpoints', type: 'checklist', compact: true,
2462
2491
  value: (last.viewpoints && last.viewpoints.join(',')) || 'hero',
2463
2492
  options: RENDER_VIEWPOINTS,
2464
2493
  },
@@ -2515,6 +2544,193 @@
2515
2544
  return options;
2516
2545
  }
2517
2546
 
2547
+ // ── The Bill of Materials card ────────────────────────────────────────────────────────────────
2548
+ // Formats cheap-first, which is also the order the server writes them in: a report that fails still
2549
+ // leaves the CSV and the workbook on disk. `meta` carries the extension AND the cost, the same shape
2550
+ // the render dialog's own options use.
2551
+ // The extension is IN the label because a checklist row has no neutral slot beside it — its status
2552
+ // slot is coloured (ready / checking / blocked) and none of those tones means "here is a hint".
2553
+ // The cost asymmetry is not repeated here; it belongs in the live footnote, which is the only place
2554
+ // that can state it for the combination actually picked.
2555
+ const BOM_FORMATS = [
2556
+ { value: 'csv', label: 'CSV' },
2557
+ { value: 'xlsx', label: 'Excel workbook (.xlsx)' },
2558
+ { value: 'html', label: 'Report (.html)' },
2559
+ ];
2560
+
2561
+ // One row per format on the card, in this fixed order — deliberately NOT newest-first like the
2562
+ // render card. All three come out of ONE click, so their timestamps are equal to the minute and
2563
+ // sorting by time only makes the order look arbitrary from one repaint to the next.
2564
+ const BOM_ROWS = [
2565
+ { kind: 'bom-csv', format: 'csv', label: 'CSV' },
2566
+ { kind: 'bom-xlsx', format: 'xlsx', label: 'Excel workbook' },
2567
+ { kind: 'bom-html', format: 'html', label: 'Report' },
2568
+ ];
2569
+
2570
+ // Mirrors the server's registry (bom-format.ts). Canonical order, never pick order: a bill is a
2571
+ // standard deliverable, and the same columns arriving in a different sequence week to week is
2572
+ // exactly what breaks an estimator's comparison. `meta` teaches the two that are new.
2573
+ // Each label is EXACTLY the header the file will carry, so the picker is a preview of the bill
2574
+ // rather than a glossary of it. What Grade and Type mean for the ROWS — that picking them
2575
+ // subdivides the bill — is the dialog's `sub`, because that is the part a label cannot say.
2576
+ const BOM_COLUMNS = [
2577
+ { value: 'profile', label: 'Profile' },
2578
+ { value: 'grade', label: 'Grade' },
2579
+ { value: 'type', label: 'Type' },
2580
+ { value: 'qty', label: 'Qty' },
2581
+ { value: 'length', label: 'Length (ft)' },
2582
+ { value: 'lbft', label: 'lb/ft' },
2583
+ { value: 'weight', label: 'Weight (lb)' },
2584
+ ];
2585
+ const BOM_DESCRIPTIVE = ['profile', 'grade', 'type'];
2586
+ const DEFAULT_BOM_FORMATS = ['csv', 'xlsx'];
2587
+ const DEFAULT_BOM_COLUMNS = ['profile', 'qty', 'length', 'lbft', 'weight'];
2588
+
2589
+ // Picks made this session, per project — the same in-memory treatment renderChoices gets, so a
2590
+ // detailer exporting a second project does not inherit the first one's columns.
2591
+ const bomChoices = new Map();
2592
+
2593
+ const splitPicks = (v) => String(v || '').split(',').map((s) => s.trim()).filter(Boolean);
2594
+
2595
+ /**
2596
+ * The refusals, in one place so the live footnote and the OK handler cannot disagree about what is
2597
+ * allowed. Each exists because the alternative is a file that looks like a bill and is not — the
2598
+ * server enforces the same three (bomColumnRefusal), because a browser is not a gate.
2599
+ */
2600
+ function bomRefusal(formats, columns) {
2601
+ if (!formats.length) return 'Pick at least one format to export.';
2602
+ if (!columns.length) return 'Pick at least one column to export.';
2603
+ // Same ORDER as the server's bomColumnRefusal, deliberately: unticking Profile breaks both this
2604
+ // and the descriptive rule, and only this message names the real conflict and both ways out —
2605
+ // and adding Profile satisfies the other rule too, where adding Grade would earn a second refusal.
2606
+ if (columns.includes('lbft') && !columns.includes('profile')) {
2607
+ return 'lb/ft is a property of the profile — pick Profile too, or drop lb/ft.';
2608
+ }
2609
+ if (!columns.some((c) => BOM_DESCRIPTIVE.includes(c))) {
2610
+ return 'Pick at least one of Profile, Grade or Type — a bill has to say what the material is.';
2611
+ }
2612
+ return null;
2613
+ }
2614
+
2615
+ /**
2616
+ * The live footnote: what this click will cost, and the one consequence the dialog cannot otherwise
2617
+ * show. Not a restatement of the picks — the trigger buttons already summarise those, and
2618
+ * renderEstimate's whole justification is saying something no static label could.
2619
+ *
2620
+ * The cost line leads because the formats are not alike: two are instant and the report compiles and
2621
+ * runs an AWARE app. No invented number — "a few seconds" is what has actually been measured until
2622
+ * someone measures it properly, and an under-promise is what makes a working export read as hung.
2623
+ */
2624
+ function bomPreview(values) {
2625
+ const formats = splitPicks(values.formats);
2626
+ const columns = splitPicks(values.columns);
2627
+ const refusal = bomRefusal(formats, columns);
2628
+ if (refusal) return refusal;
2629
+
2630
+ const instant = formats.filter((f) => f !== 'html');
2631
+ const n = formats.length;
2632
+ const files = `${n} file${n === 1 ? '' : 's'}`;
2633
+ let text;
2634
+ if (!formats.includes('html')) text = `${files}, written straight away.`;
2635
+ else if (!instant.length) text = 'One file — the report takes a few seconds to render.';
2636
+ else {
2637
+ const names = instant.map((f) => (f === 'csv' ? 'CSV' : 'Excel workbook'));
2638
+ text = `${files}. The ${names.join(' and ')} ${names.length === 1 ? 'is' : 'are'} written straight away; the report takes a few seconds.`;
2639
+ }
2640
+ // Said ONLY when it can bite. The bill this button writes is the one you picked; the bill a Run
2641
+ // writes is baked into the approved lock and is always the full one, because what a locked run
2642
+ // produces must not depend on a preference living in a browser. Someone who has not narrowed
2643
+ // anything has no contradiction to be warned about, so they are not.
2644
+ const narrowed = columns.length !== DEFAULT_BOM_COLUMNS.length
2645
+ || DEFAULT_BOM_COLUMNS.some((c) => !columns.includes(c));
2646
+ return narrowed ? `${text} Running the workflow still writes the full bill.` : text;
2647
+ }
2648
+
2649
+ async function askBomOptions(projectId) {
2650
+ if (!bridge.formModal) return { formats: [...DEFAULT_BOM_FORMATS], columns: [...DEFAULT_BOM_COLUMNS] };
2651
+ const last = bomChoices.get(projectId) || {};
2652
+ const chosen = await bridge.formModal({
2653
+ title: 'Export Bill of Materials',
2654
+ // The one mechanic that is not obvious from the controls, and the reason Grade is worth picking:
2655
+ // the columns are the grouping, not just the headings.
2656
+ sub: 'Rows are grouped by the columns you pick — adding Grade or Type can split one line into several.',
2657
+ okLabel: 'Export',
2658
+ onChange: bomPreview,
2659
+ // The card repaints on the way in, which moves focus off the button, so naming it explicitly is
2660
+ // what keeps Cancel from dropping focus behind the dialog — same reasoning as the render dialog.
2661
+ returnFocusTo: $wsExports.querySelector('[data-export="bom"]'),
2662
+ returnFocusFallback: () => (current && current.id === projectId
2663
+ ? $wsExports.querySelector('[data-export="bom"]')
2664
+ : null),
2665
+ fields: [
2666
+ // `checklist compact` — the same control the CAD-destination card and the render dialog's
2667
+ // viewpoints use for a multi-pick, so the two consolidated export cards in this grid ask
2668
+ // their question the same way. Every row is visible and ticked or not, which is what a
2669
+ // column picker wants: a collapsed "5 selected" hides the very thing being chosen.
2670
+ {
2671
+ name: 'formats', label: 'Formats', type: 'checklist', compact: true,
2672
+ // Defaults to the two cards this one replaced. A consolidated card must not quietly give a
2673
+ // plain click FEWER files than before, nor surprise anyone with the slower opt-in format.
2674
+ value: (last.formats || DEFAULT_BOM_FORMATS).join(','),
2675
+ options: BOM_FORMATS,
2676
+ },
2677
+ {
2678
+ name: 'columns', label: 'Columns', type: 'checklist', compact: true,
2679
+ value: (last.columns || DEFAULT_BOM_COLUMNS).join(','),
2680
+ options: BOM_COLUMNS,
2681
+ },
2682
+ ],
2683
+ });
2684
+ if (!chosen) return null;
2685
+ const formats = splitPicks(chosen.formats);
2686
+ const columns = splitPicks(chosen.columns);
2687
+ // Refuse and say which rule — never disable OK (formModal gates only checkbox/files anyway), and
2688
+ // never silently repair the selection. Dropping lb/ft or adding Profile behind someone's back
2689
+ // changes the deliverable's shape without telling them, which is worse than asking again.
2690
+ const refusal = bomRefusal(formats, columns);
2691
+ if (refusal) { showToast(refusal, 'warn'); return null; }
2692
+ const options = { formats, columns };
2693
+ bomChoices.set(projectId, options);
2694
+ return options;
2695
+ }
2696
+
2697
+ /**
2698
+ * The BOM card's state — the same {meta, disabled, tip} shape as renderCardState, and for the same
2699
+ * reason: it fronts several export kinds, so `exportState[c.kind]` cannot describe it.
2700
+ */
2701
+ function bomCardState(approved) {
2702
+ if (!approved) return {
2703
+ meta: '<span class="e-status">Available after approval</span>',
2704
+ disabled: true,
2705
+ tip: 'Approve this version first',
2706
+ };
2707
+ // `exportState == null` means the LISTING failed, not that nothing was exported. Printing "not
2708
+ // exported yet" would be a definite negative the server never confirmed.
2709
+ if (exportState == null) {
2710
+ return { meta: '<span class="e-status">Status unavailable</span>', disabled: false, tip: '' };
2711
+ }
2712
+ const done = BOM_ROWS
2713
+ .filter((row) => exportState[row.kind] && exportState[row.kind].exportedAt)
2714
+ .map((row) => ({ ...row, exportedAt: exportState[row.kind].exportedAt }));
2715
+ if (!done.length) {
2716
+ return { meta: '<span class="e-status">not exported yet</span>', disabled: false, tip: '' };
2717
+ }
2718
+ const rows = done.map((row) =>
2719
+ `<div class="e-render-row">` +
2720
+ `<span class="e-done"><span class="chk">✓</span> ${escapeHtml(row.label)} <span class="t">${escapeHtml(hhmm(row.exportedAt))}</span></span>` +
2721
+ `<span class="e-links">` +
2722
+ `<button type="button" class="e-link" data-openfile="${escapeAttr(row.kind)}" data-tip="Open in its default app">⧉ Open</button>` +
2723
+ `<button type="button" class="e-link" data-reveal="${escapeAttr(row.kind)}" data-tip="Show the file in its folder">▤ Reveal</button>` +
2724
+ `</span>` +
2725
+ `</div>`).join('');
2726
+ // At most three rows, so this never scrolls — but it reuses the render card's themed scroller
2727
+ // verbatim rather than inventing a second way to list produced files.
2728
+ return {
2729
+ meta: `<div class="e-renders" role="group" aria-label="Exported files">${rows}</div>`,
2730
+ disabled: false, tip: '', rendered: true,
2731
+ };
2732
+ }
2733
+
2518
2734
  const receiptKey = (kind) => `${current ? current.id : ''}:${kind}`;
2519
2735
 
2520
2736
  function receiptItemText(prefix, value) {
@@ -2530,7 +2746,10 @@
2530
2746
  if (!receipt || !receipt.counts) return null;
2531
2747
  const c = receipt.counts;
2532
2748
  const parts = [`${Number(c.emitted) || 0} emitted`];
2533
- if (kind === 'tekla' && Number.isFinite(Number(c.native))) parts.push(`${Number(c.native)} native`);
2749
+ // "N native" is meaningful for a host bake — it separates real native parts from fallback
2750
+ // geometry — and meaningless for a file export, which has no such split. Keyed on the send
2751
+ // kinds (`send:tekla`, `send:revit`, …), so a new destination inherits it without a new branch.
2752
+ if (String(kind).startsWith('send:') && Number.isFinite(Number(c.native))) parts.push(`${Number(c.native)} native`);
2534
2753
  if (Number(c.unsupported)) parts.push(`${Number(c.unsupported)} unsupported`);
2535
2754
  if (Number(c.warnings)) parts.push(`${Number(c.warnings)} warning${Number(c.warnings) === 1 ? '' : 's'}`);
2536
2755
  return {
@@ -2543,9 +2762,22 @@
2543
2762
  };
2544
2763
  }
2545
2764
 
2546
- function receiptHtml(kind, approved) {
2765
+ /**
2766
+ * The receipt for `kind` under the CURRENTLY approved version, or null.
2767
+ *
2768
+ * Every consumer — the summary line, the button that offers the details, and the dialog that
2769
+ * shows them — resolves the receipt through here, so they cannot ask subtly different questions
2770
+ * and disagree. A receipt from an older approval describes a model that no longer exists.
2771
+ */
2772
+ function currentReceipt(kind) {
2773
+ if (!current) return null;
2547
2774
  const receipt = exportReceipts.get(receiptKey(kind));
2548
- if (!approved || !receipt || receipt.approvedAt !== current.approvedAt) return '';
2775
+ return receipt && receipt.approvedAt === current.approvedAt ? receipt : null;
2776
+ }
2777
+
2778
+ function receiptHtml(kind, approved) {
2779
+ const receipt = approved ? currentReceipt(kind) : null;
2780
+ if (!receipt) return '';
2549
2781
  const summary = receiptSummary(receipt, kind);
2550
2782
  if (!summary) return '';
2551
2783
  return `<div class="e-receipt${summary.partial ? ' partial' : ''}">` +
@@ -2554,6 +2786,264 @@
2554
2786
  `</div>`;
2555
2787
  }
2556
2788
 
2789
+ // ── The destination chooser ───────────────────────────────────────────────────────────────────
2790
+ const hostSendUrl = (host, projectId, appId) => {
2791
+ const qs = `?project=${encodeURIComponent(projectId)}`;
2792
+ const base = `/api/contract/${encodeURIComponent(appId)}`;
2793
+ // Tekla keeps its original route (its readiness probe can tell "open but no model loaded",
2794
+ // which the generic one cannot); the other three share the newer one.
2795
+ return host === 'tekla'
2796
+ ? `${base}/export-tekla${qs}`
2797
+ : `${base}/export-host/${encodeURIComponent(host)}${qs}`;
2798
+ };
2799
+
2800
+ /** One chooser row, derived from that host's live readiness. */
2801
+ function hostRowOption(host) {
2802
+ const label = hostLabel(host);
2803
+ const st = hostState(host);
2804
+ if (!st || st.state === 'checking') {
2805
+ return { value: host, label, pickable: false, status: { tone: 'checking', text: 'Checking…' } };
2806
+ }
2807
+ if (st.ok && st.state === 'ready') {
2808
+ const v = hostVersion(st);
2809
+ return { value: host, label, pickable: true, status: { tone: 'ready', text: `Ready${v ? ` · ${label} ${v}` : ''}` } };
2810
+ }
2811
+ const recovery = st.recovery || { action: 'retry', label: 'Check again' };
2812
+ // Only offer to DO something we can actually do. Opening an application, loading a model or
2813
+ // closing a duplicate window are the user's to perform — the button that helps there is the one
2814
+ // that re-checks once they have. A bridge install we can genuinely run, so that one keeps its
2815
+ // real label. Labelling a re-check "Open Revit" would be a button that lies about its effect.
2816
+ const installs = recovery.action === 'install-bridge' || recovery.action === 'install-addin';
2817
+ return {
2818
+ value: host,
2819
+ label,
2820
+ pickable: false,
2821
+ status: { tone: 'blocked', text: st.message || `${label} can’t receive this model right now.` },
2822
+ action: { label: installs ? recovery.label : 'Check again' },
2823
+ };
2824
+ }
2825
+
2826
+ const hostRowOptions = () => SEND_HOSTS.map((h) => hostRowOption(h.host));
2827
+
2828
+ /** "Tekla Structures, then Rhino" — the destinations in the order they will actually be sent. */
2829
+ function sequenceText(picked) {
2830
+ const names = picked.map(hostLabel);
2831
+ if (names.length === 1) return names[0];
2832
+ return `${names.slice(0, -1).join(', ')}, then ${names[names.length - 1]}`;
2833
+ }
2834
+
2835
+ /**
2836
+ * Ask which applications should receive this model. Resolves to an array of host ids, or null.
2837
+ *
2838
+ * Every destination is listed, including the ones that cannot take it — a user who has never
2839
+ * installed the Revit bridge would otherwise never learn FloLess can drive Revit at all. The
2840
+ * rows that cannot be ticked carry the reason and, where we can actually perform it, the fix.
2841
+ */
2842
+ async function askSendDestinations(projectId) {
2843
+ if (!bridge.formModal) {
2844
+ const ready = SEND_HOSTS.map((h) => h.host).filter(hostIsReady);
2845
+ return ready.length === 1 ? ready : null;
2846
+ }
2847
+ const remembered = hostChoices.get(projectId) || [];
2848
+ // Pre-tick the remembered picks that are STILL ready, else the single ready host. This is what
2849
+ // keeps the ordinary one-application case a single click through the dialog.
2850
+ const readyHosts = SEND_HOSTS.map((h) => h.host).filter(hostIsReady);
2851
+ const preTicked = remembered.filter(hostIsReady);
2852
+ const initial = (preTicked.length ? preTicked : readyHosts.slice(0, 1)).join(',');
2853
+ const chosen = await bridge.formModal({
2854
+ title: 'Send to a CAD application',
2855
+ // The deliberate opposite of the Render dialog's "nothing in your model changes". This one
2856
+ // writes into a live document somebody may be looking at, and saying so is the honest half of
2857
+ // sitting next to a button that only reads.
2858
+ sub: 'Creates or replaces these members as native objects in the app you choose — this changes the model open there.',
2859
+ okLabel: 'Send',
2860
+ onChange: (values) => {
2861
+ const picked = String(values.destinations || '').split(',').map((v) => v.trim()).filter(Boolean);
2862
+ if (!picked.length) return 'Pick at least one destination.';
2863
+ // Never "at the same time": the project's lifecycle lock serializes these, so a batch is
2864
+ // several sends in a row. Promising simultaneity we do not have would be a lie about the
2865
+ // one thing the user is waiting on.
2866
+ return picked.length === 1
2867
+ ? `Sends to ${sequenceText(picked)} now. This project’s other exports wait until it finishes.`
2868
+ : `Sends to ${sequenceText(picked)} — one at a time. This project’s other exports wait until they all finish.`;
2869
+ },
2870
+ returnFocusTo: $wsExports.querySelector('[data-export="send-host"]'),
2871
+ returnFocusFallback: () => (current && current.id === projectId
2872
+ ? $wsExports.querySelector('[data-export="send-host"]')
2873
+ : null),
2874
+ fields: [{
2875
+ name: 'destinations',
2876
+ label: 'Destinations',
2877
+ type: 'checklist',
2878
+ value: initial,
2879
+ options: hostRowOptions(),
2880
+ onAction: async (host) => {
2881
+ const st = hostState(host);
2882
+ const action = st && st.recovery ? st.recovery.action : 'retry';
2883
+ if (action === 'install-bridge' || action === 'install-addin') {
2884
+ try {
2885
+ await api(host === 'tekla'
2886
+ ? '/api/tekla-readiness/setup'
2887
+ : `/api/host-readiness/${encodeURIComponent(host)}/setup`, { method: 'POST' });
2888
+ } catch (err) {
2889
+ // Report it and still re-probe: the install may have partly succeeded, and the fresh
2890
+ // readiness is a truer answer than either the old row or this error alone.
2891
+ showToast(err && err.message ? err.message : `Couldn’t install the ${hostLabel(host)} bridge.`, 'warn');
2892
+ }
2893
+ }
2894
+ hostReadinessStates = { ...hostReadinessStates, [host]: { ok: false, state: 'checking' } };
2895
+ const fresh = await probeHost(host);
2896
+ hostReadinessStates = { ...hostReadinessStates, [host]: fresh };
2897
+ // Deliberately does NOT repaint the card behind the dialog. That repaint restores focus to
2898
+ // the card's own button (restoreExportFocus), which yanks it out of the open modal — the
2899
+ // user pressed a button INSIDE the dialog and focus landed behind it. The card is brought
2900
+ // up to date once the dialog closes instead; see chooseAndSend.
2901
+ return hostRowOptions();
2902
+ },
2903
+ }],
2904
+ });
2905
+ if (!chosen) return null;
2906
+ const picked = String(chosen.destinations || '').split(',').map((v) => v.trim()).filter(Boolean);
2907
+ if (!picked.length) {
2908
+ showToast('Pick at least one destination to send to.', 'warn');
2909
+ return null;
2910
+ }
2911
+ return picked;
2912
+ }
2913
+
2914
+ /**
2915
+ * Send to each destination IN TURN.
2916
+ *
2917
+ * Sequential is not a simplification — the project's lifecycle lock already serializes these, so
2918
+ * firing them together would only queue them invisibly. Doing it in the open means the card can
2919
+ * say which one is in flight, and a host that failed can be named.
2920
+ *
2921
+ * Every destination is re-validated immediately before its own send: the chooser's snapshot can
2922
+ * be minutes old by the time a third host's turn comes round, and an application closed since
2923
+ * then must be reported rather than sent into.
2924
+ */
2925
+ async function sendToHosts(hosts, projectId, app, approvedAt) {
2926
+ const busyKey = `${projectId}:send-host`;
2927
+ if (exportBusy.has(busyKey)) return;
2928
+ exportBusy.add(busyKey);
2929
+ const done = [];
2930
+ const failed = [];
2931
+ const aborted = [];
2932
+ /** Has the sign-off this batch was aimed at moved on? Only answerable while it is still open. */
2933
+ const approvalMoved = () => !!current && current.id === projectId && current.approvedAt !== approvedAt;
2934
+ try {
2935
+ for (let i = 0; i < hosts.length; i++) {
2936
+ const host = hosts[i];
2937
+ // Every destination must receive the SAME approved version. A batch runs for minutes and
2938
+ // each POST picks up whatever is approved when it acquires the project lock, so a sign-off
2939
+ // that lands mid-batch would put version A in Tekla and version B in Revit while both
2940
+ // receipts claimed A. Stop instead: half a model in two versions is worse than none.
2941
+ // (It narrows the window the user can create from this app; it is NOT a compare-and-swap —
2942
+ // the routes take no expected-approval token, so a change landing between the last check
2943
+ // and the POST is still possible. Closing that needs a server-side check under the project
2944
+ // lifecycle lock; see the PR.)
2945
+ //
2946
+ // Asked ONLY while the captured project is still the open one: `current` IS whatever the
2947
+ // user is looking at, so switching projects mid-batch says nothing about this batch's
2948
+ // approval. Treating navigation as a version change aborted perfectly good sends and told
2949
+ // the user their version had changed when it had not.
2950
+ if (approvalMoved()) { aborted.push(...hosts.slice(i)); break; }
2951
+ sendProgress = { host, index: i + 1, total: hosts.length };
2952
+ if (current && current.id === projectId && !$wsExports.hidden) paintExports(approvedAt);
2953
+ const fresh = await probeHost(host);
2954
+ hostReadinessStates = { ...hostReadinessStates, [host]: fresh };
2955
+ if (!fresh.ok) {
2956
+ failed.push({ host, error: fresh.message || `${hostLabel(host)} isn’t ready.` });
2957
+ continue;
2958
+ }
2959
+ // Again, immediately before dispatch: the probe above can take seconds against a cold
2960
+ // bridge, and that is the longest gap in this loop.
2961
+ if (approvalMoved()) { aborted.push(...hosts.slice(i)); break; }
2962
+ try {
2963
+ const res = await api(hostSendUrl(host, projectId, app), { method: 'POST' });
2964
+ track('workspace_export', { app, kind: `send:${host}` });
2965
+ let summary = null;
2966
+ if (res.counts) {
2967
+ exportReceipts.set(`${projectId}:send:${host}`, {
2968
+ counts: res.counts,
2969
+ warnings: res.warnings || [],
2970
+ unsupported: res.receipt && Array.isArray(res.receipt.unsupported) ? res.receipt.unsupported : [],
2971
+ approvedAt,
2972
+ });
2973
+ summary = receiptSummary(exportReceipts.get(`${projectId}:send:${host}`), `send:${host}`);
2974
+ }
2975
+ hostSends.set(`${projectId}:${host}`, { at: new Date().toISOString(), approvedAt });
2976
+ done.push({ host, partial: !!(summary && summary.partial), text: summary && summary.text });
2977
+ } catch (err) {
2978
+ const detail = (err && err.body && err.body.error) || (err && err.message) || String(err);
2979
+ failed.push({ host, error: detail });
2980
+ }
2981
+ }
2982
+ } finally {
2983
+ sendProgress = null;
2984
+ exportBusy.delete(busyKey);
2985
+ }
2986
+
2987
+ // One toast for the whole run, naming what landed and what did not. A per-host toast storm
2988
+ // would bury the one line that matters when three destinations were picked.
2989
+ //
2990
+ // Built per DESTINATION rather than per outcome-bucket. Summarising by bucket lost the two
2991
+ // things a mixed run most needs to say: a destination that landed WITH GAPS read as a plain
2992
+ // "Sent to Revit" the moment any other destination failed, and with several partial runs only
2993
+ // the first one's counts appeared, attached to no host at all.
2994
+ const clean = done.filter((d) => !d.partial);
2995
+ const partial = done.filter((d) => d.partial);
2996
+ if (done.length || failed.length || aborted.length) {
2997
+ const sentence = [
2998
+ clean.length ? `Sent to ${sequenceText(clean.map((d) => d.host))}.` : '',
2999
+ ...partial.map((d) => `${hostLabel(d.host)} took it with gaps — ${d.text}.`),
3000
+ ...failed.map((f) => `${hostLabel(f.host)} didn’t — ${reasonFragment(humanSendError(f.error))}.`),
3001
+ // The abort rides in the SAME sentence rather than firing its own toast: two toasts about
3002
+ // one action is exactly the storm this single-line report replaced.
3003
+ aborted.length
3004
+ ? `This version changed, so ${sequenceText(aborted)} ${aborted.length === 1 ? 'wasn’t' : 'weren’t'} sent — approve again and re-send.`
3005
+ : '',
3006
+ ].filter(Boolean).join(' ');
3007
+ showToast(sentence, partial.length || failed.length || aborted.length ? 'warn' : 'ok');
3008
+ }
3009
+ if (current && current.id === projectId && !$wsExports.hidden) {
3010
+ // Re-reads the listing AND re-probes every host, so the card reflects the machine as it is
3011
+ // now — including a host that went down during the run.
3012
+ return renderExports('send-host').catch(() => paintExports(approvedAt, 'send-host'));
3013
+ }
3014
+ }
3015
+
3016
+ /** The Send card's whole action: ask, then send. */
3017
+ async function chooseAndSend() {
3018
+ if (!current) return;
3019
+ const projectId = current.id, app = current.app, approvedAt = current.approvedAt;
3020
+ // The busy button stays `aria-disabled` + `aria-busy` rather than natively disabled (so a
3021
+ // screen reader can still reach it and hear the progress), and the click delegate lets that
3022
+ // combination through on purpose. Without this it opened the whole destination dialog on top of
3023
+ // a running send, took the user's picks, and threw them away against the busy key below —
3024
+ // a complete decision discarded in silence.
3025
+ if (exportBusy.has(`${projectId}:send-host`)) { showToast(sendBusyText(), 'info'); return; }
3026
+ const picked = await askSendDestinations(projectId);
3027
+ // The dialog's per-row re-checks update readiness but deliberately leave the card alone while it
3028
+ // is open (focus). Bring it up to date now, on EVERY exit including cancel — otherwise a user
3029
+ // who re-checked, saw a host come up, then cancelled would be left looking at a stale card.
3030
+ //
3031
+ // A row's probe can still be in flight when the dialog is dismissed (Esc during "Checking…").
3032
+ // Its continuation is discarded — it would be writing into a dialog that no longer exists — so
3033
+ // painting the state as it stands leaves that host stuck on "Checking…" behind a natively
3034
+ // disabled button, with nothing left to move it. Re-probe in that case only: doing it on every
3035
+ // exit would cost four bridge round-trips on a plain Cancel, which this flow exists to avoid.
3036
+ if (current && current.id === projectId && !$wsExports.hidden) {
3037
+ if (SEND_HOSTS.some((h) => (hostState(h.host) || {}).state === 'checking')) renderExports();
3038
+ else paintExports(current.approvedAt);
3039
+ }
3040
+ if (!picked) return;
3041
+ hostChoices.set(projectId, picked);
3042
+ // The user may have switched projects while the dialog was open — the send must not land on
3043
+ // whatever is open NOW. Everything below is keyed to the captured project.
3044
+ return sendToHosts(picked, projectId, app, approvedAt);
3045
+ }
3046
+
2557
3047
  // Links created this session, per project: `${projectId}:share-3d` -> { url, approvedAt }. Held in
2558
3048
  // memory only — the server keeps no record of what a project has shared, and inventing a durable
2559
3049
  // one here would imply a revoke story that does not exist yet.
@@ -2605,7 +3095,7 @@
2605
3095
  }
2606
3096
 
2607
3097
  /**
2608
- * The Render card's state — same {meta, disabled, tip} shape as teklaCardState/shareCardState.
3098
+ * The Render card's state — same {meta, disabled, tip} shape as sendHostCardState/shareCardState.
2609
3099
  *
2610
3100
  * Two things make it unlike the others. It reads TWO export kinds (a still and a turntable are
2611
3101
  * different deliverables, and last-wins would claim "rendered 14:41" while a 14:32 still also sat
@@ -2638,9 +3128,12 @@
2638
3128
  if (readiness && !readiness.ok) {
2639
3129
  const recovery = readiness.recovery || { action: 'retry', label: 'Check again' };
2640
3130
  return {
2641
- meta: `<span class="e-readiness blocked" role="status" aria-live="polite">${escapeHtml(readiness.message || 'Rendering is not available on this computer.')}</span>` +
3131
+ meta: `<span class="e-readiness blocked" id="e-why-render" role="status" aria-live="polite">${escapeHtml(readiness.message || 'Rendering is not available on this computer.')}</span>` +
2642
3132
  `<button type="button" class="e-recovery" data-render-recovery="${escapeAttr(recovery.action)}">${escapeHtml(recovery.label)}</button>`,
2643
3133
  disabled: true,
3134
+ // Keeps the button reachable so the reason above is discoverable by keyboard — see the
3135
+ // `softBlock` branch in cardHtml.
3136
+ blockedBy: 'e-why-render',
2644
3137
  tip: readiness.message || 'Resolve the rendering requirements first',
2645
3138
  };
2646
3139
  }
@@ -2701,12 +3194,12 @@
2701
3194
  // whose content overflows also needs to be focusable for someone scrolling WITHOUT tabbing
2702
3195
  // through every link — hence tabindex + the group label.
2703
3196
  return {
2704
- meta: `<div class="e-renders" role="group" aria-label="Rendered files"${done.length > 4 ? ' tabindex="0"' : ''}>${rows}</div>`,
3197
+ meta: `<div class="e-renders" role="group" aria-label="Rendered files">${rows}</div>`,
2705
3198
  disabled: false, tip: '', rendered: true,
2706
3199
  };
2707
3200
  }
2708
3201
 
2709
- // The share card's state, same {meta, disabled, tip} shape as teklaCardState. It is the second
3202
+ // The share card's state, same {meta, disabled, tip} shape as sendHostCardState. It is the second
2710
3203
  // file:false export kind, and the first whose RESULT is a URL rather than a file.
2711
3204
  function shareCardState(approved) {
2712
3205
  if (!approved) return {
@@ -2735,35 +3228,278 @@
2735
3228
  return { meta: '<span class="e-status">not created yet</span>', disabled: false, tip: '' };
2736
3229
  }
2737
3230
 
2738
- function teklaCardState(approved) {
3231
+ // ── CAD destinations ──────────────────────────────────────────────────────────────────────────
3232
+ // Every application a model can be sent to, in the order the chooser lists them. Tekla leads: it
3233
+ // is the deepest integration and the one users arrive expecting. Adding a host is one row here
3234
+ // plus a server-side materializer — nothing in the card or the chooser is per-host.
3235
+ const SEND_HOSTS = [
3236
+ { host: 'tekla', label: 'Tekla Structures' },
3237
+ { host: 'revit', label: 'Revit' },
3238
+ { host: 'sketchup', label: 'SketchUp' },
3239
+ { host: 'rhino', label: 'Rhino' },
3240
+ ];
3241
+ const hostLabel = (host) => (SEND_HOSTS.find((h) => h.host === host) || {}).label || host;
3242
+ // Tekla keeps its own probe: it can distinguish "open but no model loaded", which the generic
3243
+ // `list-instances` cannot. Same envelope out, so the row template does not care which answered.
3244
+ const hostReadinessUrl = (host) => (host === 'tekla'
3245
+ ? '/api/tekla-readiness'
3246
+ : `/api/host-readiness/${encodeURIComponent(host)}`);
3247
+ // Sends completed this browser session: `${projectId}:${host}` → { at, approvedAt }. In memory
3248
+ // only, exactly like share links — the server keeps no record of which applications a project has
3249
+ // been pushed into, and inventing a durable one here would imply a history that does not exist.
3250
+ const hostSends = new Map();
3251
+ // Sequential send progress for the open project: { host, index, total } — a multi-destination
3252
+ // send is several minutes of silence otherwise, and "Sending…" alone cannot say which one.
3253
+ let sendProgress = null;
3254
+
3255
+ /** The readiness of a host, or null when it has not been asked about yet. */
3256
+ const hostState = (host) => hostReadinessStates[host] || null;
3257
+ const hostIsReady = (host) => {
3258
+ const st = hostState(host);
3259
+ return !!(st && st.ok && st.state === 'ready');
3260
+ };
3261
+ /** The version to show beside a ready host — Tekla nests it under `host`, the others under `session`. */
3262
+ function hostVersion(st) {
3263
+ if (!st) return '';
3264
+ const v = (st.session && st.session.version) || (st.host && typeof st.host === 'object' && st.host.version) || '';
3265
+ return v ? String(v) : '';
3266
+ }
3267
+
3268
+ /**
3269
+ * Probe ONE destination. A probe that fails is recorded as "couldn't check" WITH a retry — never
3270
+ * as "not open", which would be a definite negative the server never gave us.
3271
+ */
3272
+ async function probeHost(host) {
3273
+ try {
3274
+ return (await api(hostReadinessUrl(host))).readiness;
3275
+ } catch (err) {
3276
+ return {
3277
+ host,
3278
+ ok: false,
3279
+ state: 'error',
3280
+ message: err && err.message
3281
+ ? err.message
3282
+ : `Couldn’t check whether ${hostLabel(host)} is ready.`,
3283
+ recovery: { action: 'retry', label: 'Check again' },
3284
+ };
3285
+ }
3286
+ }
3287
+
3288
+ /**
3289
+ * Refresh every destination: the cheap process scan first, then the expensive per-host probe for
3290
+ * only those it found.
3291
+ *
3292
+ * This ordering is what lets the chooser list all four applications without the Exports tab
3293
+ * paying four bridge round-trips every time it opens. The shortcut is sound in ONE direction
3294
+ * only: a host the scan did not see is painted closed **solely when the scan actually ran**. If
3295
+ * the scan could not run (`scanned:false` — not Windows, PowerShell unavailable) we know nothing,
3296
+ * so every host is probed rather than four applications being declared shut on the strength of a
3297
+ * look that never happened.
3298
+ */
3299
+ async function refreshHostReadiness() {
3300
+ const hosts = SEND_HOSTS.map((h) => h.host);
3301
+ hostReadinessStates = Object.fromEntries(hosts.map((h) => [h, { ok: false, state: 'checking' }]));
3302
+ let scan = null;
3303
+ try {
3304
+ scan = await api('/api/hosts/running');
3305
+ } catch {
3306
+ scan = null; // unknown — fall through to probing everything
3307
+ }
3308
+ // Null is NOT "none running": it means the scan did not answer, and the difference decides
3309
+ // whether a row may claim an application is closed. Never assert a negative we did not observe.
3310
+ const runningHosts = scan && scan.scanned && Array.isArray(scan.hosts) ? scan.hosts : null;
3311
+ const probe = runningHosts ? hosts.filter((h) => runningHosts.includes(h)) : hosts;
3312
+ const closed = hosts.filter((h) => !probe.includes(h));
3313
+ const next = {};
3314
+ for (const host of closed) {
3315
+ next[host] = {
3316
+ host,
3317
+ ok: false,
3318
+ state: 'host-closed',
3319
+ // An OBSERVATION, not a verdict. The scan matches four exact process names, so an
3320
+ // application running under any other one is unseen rather than shut — and telling a user
3321
+ // with Tekla open on screen that Tekla is closed is precisely the failure this readiness
3322
+ // machinery exists to prevent. The chooser's own per-row "Check again" probes the bridge
3323
+ // directly, bypassing the scan, so the authoritative answer is always one click away.
3324
+ message: `We didn’t see ${hostLabel(host)} running. Start it, then check again.`,
3325
+ recovery: { action: 'retry', label: 'Check again' },
3326
+ };
3327
+ }
3328
+ const probed = await Promise.all(probe.map((host) => probeHost(host).then((r) => [host, r])));
3329
+ for (const [host, readiness] of probed) next[host] = readiness;
3330
+ return next;
3331
+ }
3332
+
3333
+ /**
3334
+ * A send failure in words a detailer can act on.
3335
+ *
3336
+ * The reconciliation refusal is the one that actually reaches people, and it arrives as
3337
+ * `receipt omitted 333 scene record(s): bp-S-202-colx20:plate-hole0, …` — a sentence about our
3338
+ * internal bookkeeping, listing ids nobody outside this codebase can read. It is restated as what
3339
+ * was OBSERVED (the application reported back on fewer parts than the model holds) and what
3340
+ * FOLLOWED (nothing was sent). Deliberately does NOT name a cause: the check knows only that
3341
+ * records went unaccounted for, and asserting "holes aren't supported there" would be inventing a
3342
+ * diagnosis the evidence does not carry. Anything else passes through unchanged — the server's
3343
+ * own words are usually the better ones.
3344
+ */
3345
+ /**
3346
+ * A readiness/error message reshaped to sit INSIDE a sentence.
3347
+ *
3348
+ * They arrive as complete sentences, often already opening "Couldn’t send — ", so dropping one
3349
+ * straight into "Revit didn’t — <reason>." produced "Revit didn’t — Couldn’t send — … again..".
3350
+ */
3351
+ function reasonFragment(text) {
3352
+ return String(text || '').trim()
3353
+ .replace(/^Couldn’t send\s*[—-]\s*/i, '')
3354
+ .replace(/[.!]+$/, '');
3355
+ }
3356
+
3357
+ function humanSendError(raw) {
3358
+ const text = String(raw || '').trim();
3359
+ const omitted = text.match(/^receipt omitted (\d+) scene record/);
3360
+ if (omitted) {
3361
+ return `it reported back on ${omitted[1]} fewer parts than this model contains, so nothing was sent — a half-built model is worse than none`;
3362
+ }
3363
+ return text || 'the send failed';
3364
+ }
3365
+
3366
+ /** What the last send to `host` under this approval reported, or null if it reported nothing. */
3367
+ function hostSendSummary(host) {
3368
+ return receiptSummary(currentReceipt(`send:${host}`), `send:${host}`);
3369
+ }
3370
+
3371
+ function sendBusyText() {
3372
+ if (!sendProgress) return 'Sending…';
3373
+ const where = hostLabel(sendProgress.host);
3374
+ return sendProgress.total > 1
3375
+ ? `Sending to ${where} (${sendProgress.index} of ${sendProgress.total})…`
3376
+ : `Sending to ${where}…`;
3377
+ }
3378
+
3379
+ /**
3380
+ * The CAD card's state — same {meta, disabled, tip} contract as renderCardState/shareCardState.
3381
+ *
3382
+ * Unlike the Tekla card it replaces, it is NOT disabled when nothing is ready. Its button opens
3383
+ * the chooser, and the chooser is precisely where a user learns why each application is out and
3384
+ * what would fix it. A dead button teaches nothing; this one always leads somewhere.
3385
+ */
3386
+ function sendHostCardState(approved) {
2739
3387
  if (!approved) return {
2740
3388
  meta: '<span class="e-status">Available after approval</span>',
2741
3389
  disabled: true,
2742
3390
  tip: 'Approve this version first',
2743
3391
  };
2744
- const readiness = teklaReadinessState;
2745
- if (!readiness || readiness.state === 'checking') return {
2746
- meta: '<span class="e-readiness checking" role="status" aria-live="polite"><span class="rtn-spinner" aria-hidden="true"></span> Checking Tekla readiness…</span>',
2747
- disabled: true,
2748
- tip: 'Checking AWARE, the Tekla bridge, and the open model',
2749
- };
2750
- if (readiness.ok && readiness.state === 'ready') {
2751
- const version = readiness.host && readiness.host.version ? ` · Tekla ${readiness.host.version}` : '';
3392
+ if (exportBusy.has(`${current.id}:send-host`)) {
2752
3393
  return {
2753
- meta: `<span class="e-readiness ready" role="status" aria-live="polite">Ready${escapeHtml(version)}</span>`,
2754
- disabled: false,
2755
- tip: 'Create native parts in the open Tekla model',
3394
+ meta: '<span class="e-readiness checking" role="status" aria-live="polite">' +
3395
+ `<span class="rtn-spinner" aria-hidden="true"></span>${escapeHtml(sendBusyText())}</span>`,
3396
+ disabled: true,
3397
+ tip: sendBusyText(),
2756
3398
  };
2757
3399
  }
2758
- const recovery = readiness.recovery || { action: 'retry', label: 'Check again' };
2759
- const label = recovery.action === 'open-tekla' || recovery.action === 'open-model' || recovery.action === 'retry'
2760
- ? 'Check again'
2761
- : recovery.label;
2762
- return {
2763
- meta: `<span class="e-readiness blocked" role="status" aria-live="polite">${escapeHtml(readiness.message || 'Tekla readiness could not be verified.')}</span>` +
2764
- `<button type="button" class="e-recovery" data-tekla-recovery="${escapeAttr(recovery.action)}">${escapeHtml(label)}</button>`,
3400
+ const states = SEND_HOSTS.map((h) => hostState(h.host));
3401
+ if (states.some((st) => !st || st.state === 'checking')) return {
3402
+ meta: '<span class="e-readiness checking" role="status" aria-live="polite">' +
3403
+ '<span class="rtn-spinner" aria-hidden="true"></span> Checking which CAD apps are open…</span>',
2765
3404
  disabled: true,
2766
- tip: readiness.message || 'Resolve the Tekla readiness check first',
3405
+ tip: 'Checking AWARE, the bridges, and the open applications',
3406
+ };
3407
+
3408
+ // What was sent from THIS approved version — one row per destination, like the render card's
3409
+ // per-artifact rows. A send under an older approval is not shown: it no longer describes what
3410
+ // is in that model.
3411
+ const sent = SEND_HOSTS
3412
+ .map((h) => ({ host: h.host, rec: hostSends.get(`${current.id}:${h.host}`) }))
3413
+ .filter((r) => r.rec && r.rec.approvedAt === current.approvedAt)
3414
+ .sort((a, b) => String(b.rec.at).localeCompare(String(a.rec.at)));
3415
+
3416
+ const ready = SEND_HOSTS.filter((h) => hostIsReady(h.host));
3417
+ let head;
3418
+ if (ready.length === 1) {
3419
+ const v = hostVersion(hostState(ready[0].host));
3420
+ head = `<span class="e-readiness ready" role="status" aria-live="polite">Ready · ${escapeHtml(hostLabel(ready[0].host))}${v ? ` ${escapeHtml(v)}` : ''}</span>`;
3421
+ } else if (ready.length > 1) {
3422
+ head = `<span class="e-readiness ready" role="status" aria-live="polite">${ready.length} apps ready</span>`;
3423
+ } else {
3424
+ // Deliberately NOT one arbitrary host's message: with four destinations out for four
3425
+ // different reasons, promoting one of them to the card would misrepresent the other three.
3426
+ // The count is honest and the chooser carries every reason, each with its own way out.
3427
+ //
3428
+ // One exception, because it is not one host's problem at all: an AWARE below the required
3429
+ // version blocks every destination for the SAME reason, and re-checking can never clear it.
3430
+ // That needs the updater, and the chooser cannot open it (it would stack a second modal over
3431
+ // itself), so the way out belongs here. Without it the user re-checks forever — which is what
3432
+ // the old Tekla card's `update-aware` route existed to prevent, and this card had lost.
3433
+ //
3434
+ // `some`, not `every`: only a host that was actually PROBED can report update-aware, and the
3435
+ // readiness refresh short-circuits any host the process scan did not see straight to "not
3436
+ // running" without asking the server. Requiring all four to say it meant the button appeared
3437
+ // only with all four applications open at once — never in the ordinary case of one. This
3438
+ // branch already knows nothing is ready, so one host reporting it is the whole story.
3439
+ const awareState = states.find((st) => st && st.recovery && st.recovery.action === 'update-aware');
3440
+ head = '<span class="e-readiness blocked" role="status" aria-live="polite">' +
3441
+ (awareState
3442
+ // That host's own words: the required floor differs per destination, so a message borrowed
3443
+ // from a different one would quote the wrong version.
3444
+ ? escapeHtml(awareState.message || 'AWARE needs updating before any CAD app can receive this model.')
3445
+ : 'No CAD app is ready to receive this model.') +
3446
+ '</span>' +
3447
+ (awareState
3448
+ ? '<button type="button" class="e-recovery" data-host-recovery="update-aware">Update AWARE</button>'
3449
+ : '<button type="button" class="e-recovery" data-host-recheck="1">Check again</button>');
3450
+ }
3451
+
3452
+ // No row-count guess at whether this list needs a tab stop — markScrollable measures it after
3453
+ // paint, because a destination reporting gaps is two or three lines depending on how its
3454
+ // counts wrap.
3455
+ const rows = sent.length
3456
+ ? `<div class="e-renders e-sent-list" role="group" aria-label="Sent to">` +
3457
+ sent.map((r) => {
3458
+ // Asked of the receipt HERE rather than remembered as a flag at send time. The two
3459
+ // drifted: a clean send stored "has details" and then opened an empty dialog, because
3460
+ // what the button offers and what the dialog can show must be the same question.
3461
+ const summary = hostSendSummary(r.host);
3462
+ // A ✓ with nothing under it reads as a perfect send. When the model went in with parts
3463
+ // the application could not represent, the row has to say so where the eye lands — the
3464
+ // toast that said it at send time is long gone, and this card is what the user comes back
3465
+ // to. Same wording and amber as the file exports' receipt line, so "gaps" means the same
3466
+ // thing everywhere in this tab.
3467
+ //
3468
+ // A CLEAN send stays one line. The file cards do print their counts unconditionally, but
3469
+ // they report ONE artifact; this card can hold four destinations at once, and a permanent
3470
+ // green counts line on each is completeness nobody needs when nothing went wrong. Here the
3471
+ // absence of a second line is what says "all of it landed".
3472
+ //
3473
+ // The line and the button are gated separately, exactly as receiptHtml gates them: a
3474
+ // receipt can be partial by its counts yet carry no itemisable rows, and that must still
3475
+ // show the warning — just without a button that would open an empty box.
3476
+ const receipt = summary && summary.partial
3477
+ ? `<div class="e-receipt partial">` +
3478
+ `<span>With gaps · ${escapeHtml(summary.text)}</span>` +
3479
+ (summary.details && summary.details.trim()
3480
+ ? `<button type="button" class="e-receipt-details" data-export-details="send:${escapeAttr(r.host)}" data-tip="What landed, and what didn’t">Details</button>`
3481
+ : '') +
3482
+ `</div>`
3483
+ : '';
3484
+ // One entry per destination. The wrapper's tighter internal gap is what ties a row to its
3485
+ // OWN receipt: spaced by the list's 6px like everything else, the gap above a receipt
3486
+ // would read exactly like the gap between two unrelated destinations.
3487
+ return `<div class="e-render-entry">` +
3488
+ `<div class="e-render-row">` +
3489
+ `<span class="e-done"><span class="chk">✓</span> sent to ${escapeHtml(hostLabel(r.host))} <span class="t">${escapeHtml(hhmm(r.rec.at))}</span></span>` +
3490
+ `</div>` + receipt +
3491
+ `</div>`;
3492
+ }).join('') +
3493
+ `</div>`
3494
+ : '';
3495
+
3496
+ return {
3497
+ meta: head + rows,
3498
+ disabled: false,
3499
+ tip: ready.length
3500
+ ? `Create native objects in the open ${ready.length === 1 ? hostLabel(ready[0].host) : 'CAD'} model`
3501
+ : 'See which applications can receive this model, and what to fix',
3502
+ sent: sent.length > 0,
2767
3503
  };
2768
3504
  }
2769
3505
 
@@ -2772,9 +3508,10 @@
2772
3508
  const busy = exportBusy.has(`${current.id}:${c.kind}`);
2773
3509
  // The two file:false kinds resolve their own status; everything else uses the file/receipt path
2774
3510
  // below. `special` keeps the branches from growing a third arm each time a kind is added.
2775
- const special = c.kind === 'tekla' ? teklaCardState(approved)
3511
+ const special = c.kind === 'send-host' ? sendHostCardState(approved)
2776
3512
  : c.kind === 'share-3d' ? shareCardState(approved)
2777
- : c.kind === 'render' ? renderCardState(approved) : null;
3513
+ : c.kind === 'render' ? renderCardState(approved)
3514
+ : c.kind === 'bom' ? bomCardState(approved) : null;
2778
3515
  if (special) {
2779
3516
  meta = special.meta;
2780
3517
  } else if (!approved) {
@@ -2798,10 +3535,20 @@
2798
3535
  // Re-labelled once a link exists, mirroring the file kinds' "Re-export" convention. Gated on the
2799
3536
  // in-memory record rather than exportState, which only ever tracks file exports.
2800
3537
  const shared = approved && c.kind === 'share-3d' && shareLinks.has(`${current.id}:share-3d`);
2801
- const rendered = approved && c.kind === 'render' && special && special.rendered;
2802
- const busyLabel = c.kind === 'tekla' ? 'Sending…' : c.kind === 'share-3d' ? 'Creating…'
3538
+ // `special.rendered` means "this card has already produced something", whatever card it is. It was
3539
+ // gated on `c.kind === 'render'` as well, which made the flag unreadable for any other multi-kind
3540
+ // card: the BOM card would have gone on saying "Export BOM" forever after a successful export.
3541
+ // Safe for the CAD card, which reports the same idea through its own `sent`.
3542
+ const rendered = approved && special && special.rendered;
3543
+ const sentSomewhere = approved && c.kind === 'send-host' && special && special.sent;
3544
+ const busyLabel = c.kind === 'send-host' ? sendBusyText() : c.kind === 'share-3d' ? 'Creating…'
2803
3545
  : c.kind === 'render' ? 'Rendering…' : 'Exporting…';
3546
+ // The CAD card's button NEVER names a destination, even when only one application is ready.
3547
+ // Choosing where a model goes is always a deliberate step: a button reading "Send to Tekla"
3548
+ // promises a direct send, and the next thing it does is open a dialog — and it would rename
3549
+ // itself as applications open and close, so the same control never reads the same twice.
2804
3550
  const label = busy ? busyLabel
3551
+ : c.kind === 'send-host' ? (sentSomewhere ? 'Send again' : c.verb)
2805
3552
  : (exported || shared || rendered
2806
3553
  ? (c.kind === 'share-3d' ? 'Create new link' : c.kind === 'render' ? 'Re-render' : 'Re-export')
2807
3554
  : c.verb);
@@ -2809,27 +3556,49 @@
2809
3556
  // and every other project-scoped export serializes on that same key. In-process those queue
2810
3557
  // with no timeout, so a sibling card clicked meanwhile would just sit on "Exporting…" with no
2811
3558
  // explanation. Say what is happening instead of letting it hang.
2812
- const renderHolding = c.kind !== 'render' && exportBusy.has(`${current.id}:render`);
2813
- const disabled = renderHolding || (special ? special.disabled : !approved);
2814
- const busyTip = c.kind === 'tekla' ? 'Sending the approved model to Tekla'
3559
+ //
3560
+ // A LIST rather than one kind, because `render` is no longer the only card shaped like this. The
3561
+ // BOM's Report format installs an agent if missing, then compiles and runs an AWARE app, all
3562
+ // inside the project lock; a CAD send takes that lock once per destination. Both reproduced the
3563
+ // exact hang this line exists to prevent — a sibling card clicked meanwhile sat silent.
3564
+ const HOLDS_PROJECT = ['render', 'bom', 'send-host'];
3565
+ const holder = HOLDS_PROJECT.find((k) => k !== c.kind && exportBusy.has(`${current.id}:${k}`));
3566
+ const disabled = !!holder || (special ? special.disabled : !approved);
3567
+ const busyTip = c.kind === 'send-host' ? sendBusyText()
2815
3568
  : c.kind === 'share-3d' ? 'Rendering the model and uploading the link'
2816
3569
  : c.kind === 'render' ? renderBusyText()
2817
3570
  : 'Export in progress';
2818
3571
  const tip = busy ? busyTip
2819
- : renderHolding ? 'Waiting for the render to finish — it holds this project while it runs'
3572
+ : holder === 'render' ? 'Waiting for the render to finish — it holds this project while it runs'
3573
+ : holder === 'bom' ? 'Waiting for the bill of materials to finish — it holds this project while it runs'
3574
+ : holder === 'send-host' ? 'Waiting for the CAD send to finish — it holds this project while it runs'
2820
3575
  : special ? special.tip : (approved ? '' : 'Approve this version first');
2821
- const dis = `${disabled && !busy ? ' disabled' : ''}${busy ? ' aria-disabled="true" aria-busy="true"' : ''}${tip ? ` data-tip="${escapeAttr(tip)}"` : ''}`;
3576
+ // A button blocked by a DURABLE, card-specific reason is `aria-disabled`, never `disabled`: a
3577
+ // natively disabled control leaves the tab order, so a keyboard or screen-reader user can
3578
+ // neither reach it nor discover why it is out — and `data-tip` is hover-only, so it never
3579
+ // reaches them either. `aria-describedby` points at the reason already printed on the card.
3580
+ // The click handler refuses the action and speaks the reason instead.
3581
+ // Not applied to the un-approved state: that is the whole pane's condition, and the gate banner
3582
+ // above the grid states it once with its own focusable Approve button (the #roRibbon pattern).
3583
+ const softBlock = disabled && !busy && special && special.blockedBy;
3584
+ const dis = `${softBlock ? ` aria-disabled="true" aria-describedby="${escapeAttr(special.blockedBy)}"` : ''}` +
3585
+ `${disabled && !busy && !softBlock ? ' disabled' : ''}` +
3586
+ `${busy ? ' aria-disabled="true" aria-busy="true"' : ''}${tip ? ` data-tip="${escapeAttr(tip)}"` : ''}`;
2822
3587
  return `<div class="ecard">` +
2823
3588
  `<div class="e-top"><div class="e-ico">${escapeHtml(c.ico)}</div>` +
2824
3589
  `<div><div class="e-name">${escapeHtml(c.name)}</div><div class="e-fmt">${escapeHtml(c.fmt)}</div></div></div>` +
2825
- `<div class="e-meta${special ? ' e-meta-tekla' : ''}">${meta}</div>` +
3590
+ `<div class="e-meta${special ? ' e-meta-stacked' : ''}">${meta}</div>` +
2826
3591
  // Only the still gets a preview: an MP4 has no frame to show without decoding one, and a
2827
3592
  // card is not a video player. Click opens it exactly like ⧉ Open — no lightbox.
2828
3593
  (c.kind === 'render' && approved && exportState && exportState['render-png']
2829
3594
  && exportState['render-png'].exportedAt
2830
3595
  ? `<button type="button" class="e-thumb" data-render-thumb data-openfile="render-png" data-tip="Open the rendered image"><img alt=""></button>`
2831
3596
  : '') +
2832
- receiptHtml(c.kind, approved) +
3597
+ // The CAD card is deliberately NOT here: its receipts are per destination
3598
+ // (`<project>:send:tekla`), so this card-kind lookup can only ever miss — and a call that
3599
+ // silently returns '' is exactly what hid a missing receipt line once already. Each
3600
+ // destination prints its own, in sendHostCardState.
3601
+ (c.kind === 'send-host' ? '' : receiptHtml(c.kind, approved)) +
2833
3602
  `<div class="e-act"><button type="button" data-export="${escapeAttr(c.kind)}"${dis}>↗ ${escapeHtml(label)}</button></div>` +
2834
3603
  `</div>`;
2835
3604
  }
@@ -2839,7 +3608,8 @@
2839
3608
  'data-openfile',
2840
3609
  'data-reveal',
2841
3610
  'data-export-details',
2842
- 'data-tekla-recovery',
3611
+ 'data-host-recheck',
3612
+ 'data-host-recovery',
2843
3613
  'data-render-recovery',
2844
3614
  'data-open-exports-folder', // the note's `exports` button — survives the repaint an export triggers
2845
3615
  'data-copyshare', // the share-link Copy button — omitted here, a repaint mid-render steals its focus
@@ -2871,7 +3641,13 @@
2871
3641
  }
2872
3642
 
2873
3643
  function paintExports(approvedAt, requestedRestoreKind) {
2874
- const restoreIdentity = requestedRestoreKind
3644
+ // An explicit kind says "put them back on the button they pressed" — but only if they are still
3645
+ // here. A send runs for minutes and its refresh repaints at the END; honouring the request
3646
+ // unconditionally would reach across and yank focus out of whatever they had moved on to, which
3647
+ // is the opposite of restoring it. Body means focus was lost (the state this exists to repair);
3648
+ // inside this pane means they are still working here.
3649
+ const stillHere = document.activeElement === document.body || $wsExports.contains(document.activeElement);
3650
+ const restoreIdentity = requestedRestoreKind && stillHere
2875
3651
  ? { attr: 'data-export', value: requestedRestoreKind, cardKind: requestedRestoreKind }
2876
3652
  : exportFocusIdentity(document.activeElement);
2877
3653
  const approved = !!approvedAt;
@@ -2893,9 +3669,38 @@
2893
3669
  html += '<div class="export-grid">' + cards.map((c) => cardHtml(c, approved)).join('') + '</div>';
2894
3670
  $wsExports.innerHTML = html;
2895
3671
  paintRenderThumb();
3672
+ // Both capped lists, so two lists in the same pane cannot answer the same question differently.
3673
+ $wsExports.querySelectorAll('.e-renders').forEach(markScrollable);
2896
3674
  restoreExportFocus(restoreIdentity);
2897
3675
  }
2898
3676
 
3677
+ /**
3678
+ * Give a scroll container a tab stop only while it actually scrolls.
3679
+ *
3680
+ * Guessing from a row count is what this replaces, and the guess was wrong: a destination that
3681
+ * reports gaps is two or three lines depending on how its counts wrap, so "how many entries
3682
+ * before it overflows" is not a number that can be written down — it moves with the copy.
3683
+ * Measuring after paint is exact. Content scrolled out of reach with no way to scroll to it is
3684
+ * content a keyboard user cannot read; a tab stop on a container that fits is a dead one.
3685
+ */
3686
+ function markScrollable(el) {
3687
+ if (!el) return;
3688
+ if (el.scrollHeight > el.clientHeight) el.setAttribute('tabindex', '0');
3689
+ else el.removeAttribute('tabindex');
3690
+ }
3691
+
3692
+ // A resize is not a repaint, but it is the other thing that decides whether these lists overflow:
3693
+ // narrow the window and a receipt's counts wrap onto another line. Without this, a list that
3694
+ // started to scroll because the window changed would keep the answer it was given at paint time.
3695
+ // Debounced, so dragging a window edge does not re-measure on every frame.
3696
+ let scrollMarkTimer = null;
3697
+ window.addEventListener('resize', () => {
3698
+ clearTimeout(scrollMarkTimer);
3699
+ scrollMarkTimer = setTimeout(() => {
3700
+ if (!$wsExports.hidden) $wsExports.querySelectorAll('.e-renders').forEach(markScrollable);
3701
+ }, 150);
3702
+ });
3703
+
2899
3704
  /**
2900
3705
  * Wire up the render card's preview after the card markup lands.
2901
3706
  *
@@ -2921,19 +3726,30 @@
2921
3726
  + `?project=${encodeURIComponent(current.id)}&v=${encodeURIComponent(stamp)}`;
2922
3727
  }
2923
3728
 
2924
- async function renderExports() {
3729
+ /**
3730
+ * `restoreKind` names the card whose button the user just pressed.
3731
+ *
3732
+ * Without it a refresh loses their place: the first paint here puts every host back to
3733
+ * "Checking…", which renders the send button natively disabled, so focus cannot be restored to
3734
+ * it — and by the time the authoritative paint runs, `document.activeElement` is the body and
3735
+ * there is no identity left to restore. Carrying the kind through both paints means pressing
3736
+ * Send leaves you on Send.
3737
+ */
3738
+ async function renderExports(restoreKind) {
2925
3739
  if (!current) return;
2926
3740
  const id = current.id, app = current.app;
2927
3741
  const cards = (wsApp() && wsApp().exports) || [];
2928
- const hasTekla = cards.some((card) => card.kind === 'tekla');
3742
+ const hasHosts = cards.some((card) => card.kind === 'send-host');
2929
3743
  const hasRender = cards.some((card) => card.kind === 'render');
2930
- teklaReadinessState = hasTekla ? { ok: false, state: 'checking' } : null;
3744
+ hostReadinessStates = hasHosts
3745
+ ? Object.fromEntries(SEND_HOSTS.map((h) => [h.host, { ok: false, state: 'checking' }]))
3746
+ : {};
2931
3747
  renderReadinessState = hasRender ? { ok: false, state: 'checking' } : null;
2932
- paintExports(current.approvedAt);
3748
+ paintExports(current.approvedAt, restoreKind);
2933
3749
  let state = null;
2934
3750
  let approvedAt = current.approvedAt; // fallback if the fetch fails (best-known)
2935
3751
  const exportPromise = api(`/api/contract/${encodeURIComponent(app)}/exports?project=${encodeURIComponent(id)}`);
2936
- const readinessPromise = hasTekla ? api('/api/tekla-readiness') : Promise.resolve(null);
3752
+ const readinessPromise = hasHosts ? refreshHostReadiness() : Promise.resolve(null);
2937
3753
  const renderReadyPromise = hasRender ? api('/api/render/readiness') : Promise.resolve(null);
2938
3754
  const [exportResult, readinessResult, renderReadyResult] = await Promise.allSettled([
2939
3755
  exportPromise, readinessPromise, renderReadyPromise,
@@ -2968,27 +3784,35 @@
2968
3784
  showToast('Couldn’t load export status: ' + (err && err.message || err), 'warn');
2969
3785
  state = null;
2970
3786
  }
2971
- if (hasTekla) {
2972
- teklaReadinessState = readinessResult.status === 'fulfilled'
2973
- ? readinessResult.value.readiness
2974
- : {
3787
+ if (hasHosts) {
3788
+ // refreshHostReadiness already converts a per-host probe failure into "couldn't check +
3789
+ // retry". This outer branch only covers it throwing outright, which would otherwise strand
3790
+ // every row on "Checking…" forever with no way to retry.
3791
+ hostReadinessStates = readinessResult.status === 'fulfilled' && readinessResult.value
3792
+ ? readinessResult.value
3793
+ : Object.fromEntries(SEND_HOSTS.map((h) => [h.host, {
3794
+ host: h.host,
2975
3795
  ok: false,
2976
3796
  state: 'error',
2977
3797
  message: readinessResult.reason && readinessResult.reason.message
2978
3798
  ? readinessResult.reason.message
2979
- : 'Could not verify Tekla readiness.',
3799
+ : `Couldn’t check whether ${h.label} is ready.`,
2980
3800
  recovery: { action: 'retry', label: 'Check again' },
2981
- };
3801
+ }]));
2982
3802
  }
2983
3803
  // The user may have switched project/step during the await — don't paint stale.
2984
3804
  if (!current || current.id !== id || $wsExports.hidden) return;
2985
3805
  exportState = state;
2986
3806
  syncWorkspaceGuide(); // fresh approve/export state → tick the Export (and re-sync Approve) guide rows
2987
- paintExports(approvedAt);
3807
+ paintExports(approvedAt, restoreKind);
2988
3808
  }
2989
3809
 
2990
3810
  async function doExport(kind) {
2991
3811
  if (!current) return;
3812
+ // Sending to a CAD application is its own flow end to end: it asks WHERE first, then performs
3813
+ // one lock-holding send per destination with its own re-validation and its own receipt. None of
3814
+ // the file/receipt machinery below applies to it.
3815
+ if (kind === 'send-host') return chooseAndSend();
2992
3816
  const app = current.app, projectId = current.id, approvedAt = current.approvedAt, projectName = current.name; // capture — the user may switch projects, or leave, during the await
2993
3817
  const busyKey = `${projectId}:${kind}`;
2994
3818
  if (exportBusy.has(busyKey)) return;
@@ -2996,6 +3820,15 @@
2996
3820
  // The Render card is the only one that asks anything before it runs, so the options are
2997
3821
  // collected BEFORE the busy state — marking the card "Rendering…" while a dialog is still open
2998
3822
  // would be a lie about what the machine is doing.
3823
+ let bomOptions = null;
3824
+ if (kind === 'bom') {
3825
+ bomOptions = await askBomOptions(projectId);
3826
+ if (!bomOptions) return; // cancelled or refused — nothing started, so nothing to unwind
3827
+ // The dialog is awaited, so the project can move under us; everything below keys off the
3828
+ // captured ids, and bailing here keeps the request from being aimed somewhere else.
3829
+ if (!current || current.id !== projectId) return;
3830
+ }
3831
+
2999
3832
  let renderOptions = null;
3000
3833
  if (kind === 'render') {
3001
3834
  renderOptions = await askRenderOptions(projectId);
@@ -3082,10 +3915,38 @@
3082
3915
  // paint a stale intermediate state over it.
3083
3916
  let refreshing = false;
3084
3917
  try {
3085
- // Render is the only export whose POST carries a body — the options the modal collected.
3086
- const res = await api(exportUrl(kind, projectId, app), renderOptions
3087
- ? { method: 'POST', body: JSON.stringify(renderOptions), headers: { 'content-type': 'application/json' } }
3918
+ // Render and the BOM are the exports whose POST carries a body — the options their modal collected.
3919
+ const body = renderOptions || bomOptions;
3920
+ const res = await api(exportUrl(kind, projectId, app), body
3921
+ ? { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }
3088
3922
  : { method: 'POST' });
3923
+ if (kind === 'bom') {
3924
+ // The batch answers per format. A 200 here means SOMETHING landed, not that everything did —
3925
+ // so the toast names what failed rather than letting a green tick stand for a partial run, and
3926
+ // the files that did land are already on the card.
3927
+ const results = Array.isArray(res.results) ? res.results : [];
3928
+ const ok = results.filter((r) => r && r.ok);
3929
+ const failed = results.filter((r) => r && !r.ok);
3930
+ const nameOf = (f) => (BOM_FORMATS.find((x) => x.value === f) || {}).label || f;
3931
+ if (failed.length) {
3932
+ showToast(
3933
+ `${ok.length} of ${results.length} exported — ${failed.map((r) => nameOf(r.format)).join(', ')} failed: `
3934
+ + (failed[0].error || 'no reason given'),
3935
+ 'warn');
3936
+ } else {
3937
+ showToast(`Exported — ${ok.map((r) => nameOf(r.format)).join(', ')}`, 'ok');
3938
+ }
3939
+ // Per FORMAT, so the analytics keep the granularity the two separate cards used to give.
3940
+ for (const r of ok) track('workspace_export', { app, kind: `bom-${r.format}` });
3941
+ // Set BEFORE handing off, exactly as the shared success path does: the `finally` below runs
3942
+ // while this refresh is still in flight and would otherwise paint the pre-refresh state over
3943
+ // it — the card reading "not exported yet" for a second after a successful export.
3944
+ refreshing = true;
3945
+ return renderExports().catch((refreshErr) => {
3946
+ console.warn('exports refresh failed after a BOM export', refreshErr);
3947
+ if (current && current.id === projectId) paintExports(current.approvedAt);
3948
+ });
3949
+ }
3089
3950
  track('workspace_export', { app, kind }); // a successful export/bake (e.g. { app:'vectorize', kind:'svg' })
3090
3951
  if (res.counts) exportReceipts.set(`${projectId}:${kind}`, {
3091
3952
  counts: res.counts,
@@ -3094,17 +3955,10 @@
3094
3955
  approvedAt,
3095
3956
  });
3096
3957
  const summary = receiptSummary(exportReceipts.get(`${projectId}:${kind}`), kind);
3097
- if (kind === 'tekla') {
3098
- showToast(summary && summary.partial
3099
- ? `Sent to Tekla with gaps — ${summary.text}`
3100
- : (res.message || 'Baked into the Tekla model.'),
3101
- summary && summary.partial ? 'warn' : 'ok');
3102
- } else {
3103
- showToast(summary && summary.partial
3104
- ? `Exported with gaps — ${summary.text}`
3105
- : `Exported — ${res.filename || kind}`,
3106
- summary && summary.partial ? 'warn' : 'ok');
3107
- }
3958
+ showToast(summary && summary.partial
3959
+ ? `Exported with gaps — ${summary.text}`
3960
+ : `Exported — ${res.filename || kind}`,
3961
+ summary && summary.partial ? 'warn' : 'ok');
3108
3962
  refreshing = true;
3109
3963
  // The catch is what makes the finally's skip safe: if the refresh itself throws, nothing else
3110
3964
  // would repaint and the card would sit in its busy state forever, with exportBusy already
@@ -3117,8 +3971,6 @@
3117
3971
  // The durable export listing may still show the previously published file, but its in-session
3118
3972
  // receipt must not masquerade as the result of this failed attempt.
3119
3973
  exportReceipts.delete(`${projectId}:${kind}`);
3120
- const needsTekla = err && err.body && err.body.needsTekla;
3121
- if (kind === 'tekla' && err && err.body && err.body.readiness) teklaReadinessState = err.body.readiness;
3122
3974
  // The render route ships machine-readable readiness on its 409 precisely so the card can
3123
3975
  // show WHICH dependency broke. Dropping it left the card looking ready with an enabled
3124
3976
  // button, and the only trace of the refusal was a toast that evaporates.
@@ -3134,8 +3986,7 @@
3134
3986
  got > 0
3135
3987
  ? `${err && err.message ? err.message : 'Rendering failed'} — ${got} viewpoint${got === 1 ? '' : 's'} did finish and ${got === 1 ? 'is' : 'are'} saved.`
3136
3988
  : (err && err.message ? err.message : String(err)),
3137
- needsTekla ? 'info' : 'warn');
3138
- if (kind === 'tekla' && current && current.id === projectId) paintExports(current.approvedAt);
3989
+ 'warn');
3139
3990
  } finally {
3140
3991
  exportBusy.delete(busyKey);
3141
3992
  if (kind === 'render') {
@@ -3153,12 +4004,34 @@
3153
4004
 
3154
4005
  function showExportReceiptDetails(kind, returnFocusTo) {
3155
4006
  const projectId = current && current.id;
3156
- const receipt = exportReceipts.get(receiptKey(kind));
3157
- const summary = receiptSummary(receipt, kind);
3158
- if (!summary || !summary.details || !bridge.formModal) return;
4007
+ const summary = receiptSummary(currentReceipt(kind), kind);
4008
+ // `.trim()`: a details string of nothing but whitespace still passed a truthiness test and
4009
+ // opened a dialog with an empty box in it.
4010
+ if (!summary || !summary.details || !summary.details.trim() || !bridge.formModal) {
4011
+ // The button and the dialog resolve the receipt the same way, so reaching here means the
4012
+ // receipt went away UNDER the button — the sign-off was cleared by an edit or a revision read
4013
+ // while this pane sat open. Never answer that with silence: say what happened and repaint,
4014
+ // which is what removes the row the click came from.
4015
+ // This function serves the file cards' receipts as well as the per-destination CAD ones, so
4016
+ // the copy has to know which it is — "that send" about an IFC export is a sentence about
4017
+ // something that never happened.
4018
+ if (projectId && !summary) {
4019
+ showToast(String(kind).startsWith('send:')
4020
+ ? 'That send described an earlier version of this project — approve again to send it.'
4021
+ : 'That export described an earlier version of this project — approve again to export it.',
4022
+ 'info');
4023
+ if (!$wsExports.hidden) renderExports();
4024
+ }
4025
+ return;
4026
+ }
4027
+ // A send names its destination ("Revit send details"); everything else that reaches here is the
4028
+ // IFC export. The old two-way branch predates a kind resolving to four different applications.
4029
+ const sentTo = String(kind).startsWith('send:') ? hostLabel(String(kind).slice(5)) : null;
3159
4030
  bridge.formModal({
3160
- title: `${kind === 'tekla' ? 'Tekla' : 'IFC'} export details`,
3161
- sub: 'Details from the last successful export for this approved version.',
4031
+ title: sentTo ? `${sentTo} send details` : 'IFC export details',
4032
+ sub: sentTo
4033
+ ? 'Details from the last send to this application for this approved version.'
4034
+ : 'Details from the last successful export for this approved version.',
3162
4035
  fields: [{ name: 'details', label: 'Receipt details', type: 'note', value: summary.details }],
3163
4036
  okLabel: 'Close',
3164
4037
  hideCancel: true,
@@ -3233,29 +4106,30 @@
3233
4106
  if (current) paintExports(current.approvedAt);
3234
4107
  }
3235
4108
 
3236
- async function recoverTekla(action) {
4109
+ /**
4110
+ * The CAD card's "Check again" — re-probe every destination.
4111
+ *
4112
+ * There is deliberately no per-ACTION branch here as the Tekla card had: with four destinations
4113
+ * out for four different reasons the card refuses to promote one of them, so the only thing it
4114
+ * can honestly offer is a re-check. The per-host fixes live on their own rows in the chooser,
4115
+ * where each sits beside the reason it addresses.
4116
+ */
4117
+ async function recheckHosts() {
3237
4118
  if (!current) return;
3238
- if (action === 'open-tekla' || action === 'open-model' || action === 'retry') {
3239
- return renderExports();
3240
- }
3241
- if (action === 'update-aware') {
3242
- if (bridge.openAwareUpdate) bridge.openAwareUpdate('', document.activeElement);
3243
- else showToast('Could not open the AWARE update dialog.', 'warn');
3244
- return;
3245
- }
3246
- teklaReadinessState = { ok: false, state: 'checking' };
4119
+ hostReadinessStates = Object.fromEntries(SEND_HOSTS.map((h) => [h.host, { ok: false, state: 'checking' }]));
3247
4120
  paintExports(current.approvedAt);
3248
- try {
3249
- if (action === 'install-bridge') {
3250
- await api('/api/tekla-readiness/setup', { method: 'POST' });
3251
- }
3252
- showToast('Tekla bridge installed.', 'ok');
3253
- } catch (err) {
3254
- showToast(err && err.message ? err.message : String(err), 'warn');
3255
- }
3256
4121
  return renderExports();
3257
4122
  }
3258
4123
 
4124
+ /** The card's own recovery — today only the AWARE updater, which no per-host row can open. */
4125
+ function recoverHosts(action) {
4126
+ if (action !== 'update-aware') return;
4127
+ // Workspaces opens the shared updater; it never starts an install itself. Same route the render
4128
+ // card and the old Tekla card use.
4129
+ if (bridge.openAwareUpdate) bridge.openAwareUpdate('', document.activeElement);
4130
+ else showToast('Could not open the AWARE update dialog.', 'warn');
4131
+ }
4132
+
3259
4133
  /**
3260
4134
  * `kind` may carry a variant as `kind:variant` (a render viewpoint), because a kind can now hold
3261
4135
  * several artifacts and Open/Reveal has to reach the one whose row was clicked — not merely the
@@ -3299,12 +4173,27 @@
3299
4173
  if (e.target.closest('[data-open-exports-folder]')) { openExportsFolder(); return; }
3300
4174
  const details = e.target.closest('[data-export-details]');
3301
4175
  if (details) { showExportReceiptDetails(details.dataset.exportDetails, details); return; }
3302
- const recovery = e.target.closest('[data-tekla-recovery]');
3303
- if (recovery) { recoverTekla(recovery.dataset.teklaRecovery); return; }
4176
+ const recheck = e.target.closest('[data-host-recheck]');
4177
+ if (recheck) { recheckHosts(); return; }
4178
+ const hostFix = e.target.closest('[data-host-recovery]');
4179
+ if (hostFix) { recoverHosts(hostFix.dataset.hostRecovery); return; }
3304
4180
  const renderFix = e.target.closest('[data-render-recovery]');
3305
4181
  if (renderFix) { recoverRender(renderFix.dataset.renderRecovery); return; }
3306
4182
  const exp = e.target.closest('[data-export]');
3307
- if (exp && !exp.disabled) { doExport(exp.dataset.export); return; }
4183
+ if (exp && !exp.disabled) {
4184
+ // `aria-disabled` does NOT stop a click the way the native attribute does — that is the whole
4185
+ // point of using it (the control stays reachable so its reason is discoverable). So the
4186
+ // refusal has to be made here, and it must SAY something: silently swallowing the click is
4187
+ // the dead-button behaviour this pattern replaced.
4188
+ if (exp.getAttribute('aria-disabled') === 'true' && !exp.hasAttribute('aria-busy')) {
4189
+ const card = exp.closest('.ecard');
4190
+ const why = card && card.querySelector('.e-readiness.blocked');
4191
+ showToast((why && why.textContent) || exp.getAttribute('data-tip') || 'Not available yet.', 'warn');
4192
+ return;
4193
+ }
4194
+ doExport(exp.dataset.export);
4195
+ return;
4196
+ }
3308
4197
  const open = e.target.closest('[data-openfile]');
3309
4198
  if (open) { fileAction('/api/open-file', open.dataset.openfile, 'Couldn’t open the file'); return; }
3310
4199
  const rev = e.target.closest('[data-reveal]');
@@ -3458,6 +4347,11 @@
3458
4347
  if (tip && tip.kind === 'revision-read' && tip.n > revBaseVersion) {
3459
4348
  current.approvedAt = vr.approvedAt || undefined; // the AI read cleared the sign-off (exports re-lock)
3460
4349
  if (!$wsHistory.hidden) renderHistory();
4350
+ // …and the Exports pane, if it is the one showing. "Exports re-lock" was the intent, but
4351
+ // nothing repainted them: the pane kept its live buttons and its per-destination Details
4352
+ // rows describing a version that had just been superseded. Clicking Details then resolved
4353
+ // no receipt and did nothing at all — a control that answers a click with silence.
4354
+ if (!$wsExports.hidden) renderExports();
3461
4355
  showToast('Revision read complete — a new version is on History', 'ok');
3462
4356
  }
3463
4357
  }