@floless/app 0.112.1 → 0.113.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -532,7 +532,57 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
532
532
  text.numtx{fill:#fff;font:bold 12px system-ui;text-anchor:middle;dominant-baseline:central;pointer-events:none}
533
533
  #dupStat.has b{color:#fca5a5} #dupB.alert{background:#7f1d1d;border-color:#991b1b} #dupB.alert:hover{background:#991b1b}
534
534
  #dupB.ok,#revB.ok{background:#166534;border-color:#16a34a;color:#dcfce7}
535
- header select#planSel{width:auto;min-width:210px;padding:5px 8px;font-weight:600}
535
+ /* Plan switcher — a themed combobox, NOT a native <select>.
536
+ A <select>'s CLOSED state takes styling fine; its arrow and its option list do not. Those are drawn
537
+ by the OS, so they come up as a light panel against this dark theme no matter what the rule says —
538
+ the browser default the "style every control" rule exists to stop. Same defect, same fix, as
539
+ web/steel-filter.html's sheet switcher; the control's vocabulary (trigger + popover + option rows)
540
+ is the app-wide .wf-combo's (web/index.html + web/app.css).
541
+ Re-expressed in THIS page's dropdown idiom rather than copied from the sibling page, because the
542
+ editor already HAS a header-dropdown family (#moreMenu, .cmmenu, .m3dmenu, #comboPop) and a fifth
543
+ dropdown that read differently from the other four would be the drift this comment exists to stop:
544
+ #475569 border (not --line), top:calc(100% + 6px), z-index:30, 240px of list. Deliberately with NO
545
+ entry animation — the sibling page fades its panel in; this page's four dropdowns appear instantly
546
+ and it carries exactly one @keyframes (a spinner), so a fade here would be a new micro-aesthetic
547
+ rather than fidelity to the locked baseline. */
548
+ .plan-combo{position:relative;display:inline-flex;flex:none}
549
+ /* min-width is the OLD select's 210px floor, kept so the header's spacing does not move. The 320px cap
550
+ is new: `width:auto` let the native control grow without limit, and a long "S-202 · Second Floor
551
+ Framing At El 118'-6"" pushed the stat readouts along the dense header. What the cap clips, the
552
+ data-tip below restores on hover.
553
+ appearance:none is inert on a <button> — the background/border rules here already de-nativize it —
554
+ but it is stated rather than assumed: `appearance: auto` on this control is the exact signature the
555
+ QA pass matched on when it caught the <select>, and leaving it reading `auto` would have the next
556
+ such pass re-raise a defect that is gone. */
557
+ .plan-trigger{display:inline-flex;align-items:center;gap:6px;min-width:210px;max-width:320px;-webkit-appearance:none;appearance:none;background:var(--bg);border:1px solid #475569;border-radius:6px;padding:5px 8px;font:600 13px system-ui}
558
+ /* Load-bearing, not decorative: the page's generic `button:hover{background:#475569}` would otherwise
559
+ win on hover and flash the grey ACTION-button chrome onto a control that is a field you pick from.
560
+ (Class beats tag, so this rule wins wherever it is declared.) */
561
+ .plan-trigger:hover,.plan-trigger.open{background:var(--bg);border-color:var(--brand)}
562
+ .plan-trigger-label{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left}
563
+ .plan-caret{color:var(--mut);flex:none;transition:transform .15s}
564
+ .plan-trigger.open .plan-caret{transform:rotate(180deg)}
565
+ /* Panel matched to #moreMenu/.cmmenu — the other dropdowns hanging off this same header row. */
566
+ .plan-popover{position:absolute;top:calc(100% + 6px);left:0;min-width:100%;width:max-content;max-width:400px;background:var(--panel);border:1px solid #475569;border-radius:8px;box-shadow:0 8px 24px rgba(0,0,0,.5);padding:4px 0;z-index:30}
567
+ /* This page has no global [hidden] rule, so an author `display` on a hidden element wins by ORIGIN over
568
+ the UA's own [hidden] and `planPopover.hidden = true` would quietly do nothing. .plan-popover declares
569
+ no `display` TODAY, so this is redundant right now — it stays as insurance, because the moment anyone
570
+ gives this panel a `display` its absence becomes exactly that silent-inert-`hidden` bug. */
571
+ .plan-popover[hidden]{display:none}
572
+ .plan-list{overflow-y:auto;max-height:240px} /* a scroll container — themed by the global * scrollbar rules at the top of this file */
573
+ /* A <div role=option>, NOT a <button>: focus must stay on the trigger for aria-activedescendant to mean
574
+ anything, and a focusable row also leaves focus on <body> when the row is clicked and then hidden. So
575
+ it needs its own cursor/font rather than inheriting the page's button rules. The transparent
576
+ border-left is what stops the selected row's accent shifting its text by 2px. */
577
+ .plan-option{display:block;width:100%;cursor:pointer;background:transparent;border:none;border-left:2px solid transparent;padding:7px 12px;text-align:left;font:13px system-ui;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
578
+ .plan-option:hover,.plan-option.active{background:#334155} /* .active = the keyboard highlight, the name #comboPop already uses for it on this page */
579
+ /* Left-border accent for the current plan — the shared .wf-option.selected convention, not a tick glyph:
580
+ this page already spends ✓ on .m3dmenu's mode toggles, and blurring "pick one value" with "toggle a
581
+ mode" is worse than keeping the two apart. */
582
+ .plan-option.selected{border-left-color:var(--brand);color:var(--brand)}
583
+ /* Mirrors app.css's .sr-only. Needed because this page does not load app.css, and the plan switcher has
584
+ no visible label beside it the way the workflow/project pickers do. */
585
+ .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
536
586
  /* 2D|3D view toggle — segmented, far-left; active segment filled (--panel) with a --brand underline */
537
587
  #viewToggle{display:inline-flex;border:1px solid var(--line);border-radius:6px;overflow:hidden;flex:none}
538
588
  #viewToggle .seg{padding:5px 11px;margin:0;border:0;border-radius:0;background:transparent;color:var(--mut);font:600 12px system-ui;cursor:pointer}
@@ -819,7 +869,35 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
819
869
  <header>
820
870
  <b>Steel Model</b>
821
871
  <div id=viewToggle role=group aria-label="Canvas view"><button id=vt2d class="seg on" aria-pressed=true data-tip="Plan view (2D overlay)">2D</button><button id=vt3d class=seg aria-pressed=false data-tip="3D model view">3D</button></div>
822
- <select id=planSel data-tip="Switch plan view"></select>
872
+ <!-- Plan switcher. See the .plan-* rules for why this is not a <select>. Unlike the sibling page's sheet
873
+ switcher it is NOT hidden for a single plan: this control is the ONLY place the current sheet name
874
+ appears in this editor, so hiding it for a one-plan model would delete information rather than a
875
+ dead control. (An earlier version of this comment justified that by claiming the sibling can hide
876
+ because the sheet is also named on its #src readout. That is false — #src renders `C.source.name`,
877
+ the source FILE's name — and the sibling really does leave a lone sheet unnamed on screen. The
878
+ decision here stands on its own; it does not need a claim about the other page.) -->
879
+ <div class="plan-combo" id=planCombo>
880
+ <!-- aria-labelledby (label + VALUE), never aria-label: aria-label would OVERRIDE the button's own text,
881
+ so a screen reader would announce the control's purpose and never say which plan is open — a
882
+ regression against the <select>, which announced its selected option for free. data-tip is a
883
+ tooltip, not an accessible name, so it cannot carry this on its own. The label span is visually
884
+ hidden only because this header has no room for a visible one. -->
885
+ <span id=planComboLabel class=sr-only>Plan view</span>
886
+ <button id=planTrigger class=plan-trigger type=button role=combobox aria-haspopup=listbox aria-expanded=false aria-controls=planPopover aria-labelledby="planComboLabel planTriggerLabel" data-tip="Switch plan view">
887
+ <span class=plan-trigger-label id=planTriggerLabel></span>
888
+ <svg class=plan-caret width=10 height=6 viewBox="0 0 10 6" aria-hidden=true><path fill=currentColor d="M0 0l5 6 5-6z"/></svg>
889
+ </button>
890
+ <!-- role=listbox sits on the element aria-controls POINTS AT. With the role on the inner scroller
891
+ instead, the trigger would carry aria-activedescendant naming an option inside a listbox it never
892
+ declared it controlled — the APG relationship, broken. -->
893
+ <div id=planPopover class=plan-popover role=listbox aria-labelledby=planComboLabel hidden>
894
+ <!-- role=none on the scroller: it exists only to carry overflow, and without this the listbox owns no
895
+ options directly — every role=option would sit one generic group below it, which is not the
896
+ listbox→option relationship aria-activedescendant is read against. (Code review; the sibling page
897
+ has the same gap, so this is a fix, not a divergence to copy back blindly.) -->
898
+ <div class=plan-list id=planList role=none></div>
899
+ </div>
900
+ </div>
823
901
  <!-- These four are per-SHEET counts (see stats()). A model in the canonical format has no per-sheet
824
902
  members, so for it they are HIDDEN rather than dimmed — a readout that is wrong is worse than one
825
903
  that is absent, and "Members 0" beside a populated 3D scene is wrong (unit 5, P7d §8.5). -->
@@ -1078,6 +1156,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1078
1156
  <div id=selFly role=menu aria-label="Selectable types"></div>
1079
1157
  </div>
1080
1158
  <div id=panelResizer role=separator aria-orientation=vertical aria-label="Resize properties panel" tabindex=0 data-tip="Drag to resize · double-click to reset"></div>
1159
+ <span id=connectionTruthStatus class=sr-only role=status aria-live=polite aria-atomic=true></span>
1081
1160
  <aside id=panel></aside>
1082
1161
  </main>
1083
1162
  <datalist id=conntypes><option>moment</option><option>drag</option><option>shear</option><option>braced</option><option>pinned</option><option>fixed</option></datalist>
@@ -1322,6 +1401,23 @@ function restampDraftBase(prev, next) {
1322
1401
  localStorage.setItem(draftKey(), JSON.stringify(d));
1323
1402
  } catch (_) { /* the draft stays on its old base — a false "changed elsewhere" prompt, not a loss */ }
1324
1403
  }
1404
+ /**
1405
+ * Write a PENDING in-memory edit into this browser's draft row, right now. Assigned by main().
1406
+ *
1407
+ * WHY IT IS A SEAM AND NOT A CALL. `persist()` and the debounce handle `saveT` live inside main()'s
1408
+ * closure; the SSE handler below lives in boot()'s. Two scopes, one document — the same reason
1409
+ * `serverEtag` is declared out here rather than in there.
1410
+ *
1411
+ * WHY IT EXISTS AT ALL. `scheduleSave` debounces 500 ms, and it is the only AUTOSAVE caller of
1412
+ * `persist()` — Ctrl+S, connModifyRequest and detailRequest call it too, from explicit user actions, and
1413
+ * an earlier version of this comment wrongly called scheduleSave the only caller at all. For
1414
+ * that window an edit exists ONLY in memory: the pill already says "Saving…", the SSE handler already
1415
+ * counts it as unsaved and correctly banners instead of reloading — but the Reload it then offers would
1416
+ * destroy the very edit the banner is protecting, because there is nothing in storage to park or offer
1417
+ * back. Null until main() runs, and called defensively, so an event arriving mid-boot cannot throw the
1418
+ * handler (an exception there means the tab goes deaf to external writes entirely).
1419
+ */
1420
+ let flushLocalDraft = null;
1325
1421
  // ── Own-write identity, replacing the 2.5 s SSE echo clock (unit 5, P1c-3) ──
1326
1422
  // Every PUT names itself; the server echoes that name in the contract-changed broadcast. A clock could not
1327
1423
  // tell "my echo" from "someone else's write inside the window", so a genuine external write landing in
@@ -1461,6 +1557,32 @@ function armEarlyViewToggle() {
1461
1557
  arm(t2, false); arm(t3, true);
1462
1558
  }
1463
1559
 
1560
+ /**
1561
+ * The `code` on an error response, or null when there isn't one to be had.
1562
+ *
1563
+ * GUARDED, because this reads a body that is not guaranteed to be ours. A 404 can come from a proxy,
1564
+ * a dev-server error page, or any body-less error response — `res.json()` rejects on every one of
1565
+ * those, and an unhandled rejection here would replace a styled empty state with a raw `boot().catch`
1566
+ * message. Any failure means "no code", which lands the caller on the generic copy that was correct
1567
+ * before this field existed.
1568
+ *
1569
+ * The FALLBACK is silent-by-design; the DIAGNOSIS is not. Returning null for an unparseable body and
1570
+ * returning null for our own ordinary "no contract yet" body are the same value and very different
1571
+ * events, and without a line here the first leaves no trace anywhere. So the unparseable case warns
1572
+ * and the ordinary one does not — `body.code` simply being absent is the normal `none` answer.
1573
+ */
1574
+ async function errorCodeOf(res) {
1575
+ try {
1576
+ const body = await res.json();
1577
+ return body && typeof body.code === 'string' ? body.code : null;
1578
+ } catch (_) {
1579
+ // Not JSON, empty, or already consumed. The generic state is the safe answer, but this is a
1580
+ // response that did not come from us at all — say so rather than letting it look ordinary.
1581
+ console.warn('errorCodeOf: ' + res.status + ' body was not readable JSON — falling back to the generic empty state');
1582
+ return null;
1583
+ }
1584
+ }
1585
+
1464
1586
  async function boot() {
1465
1587
  if (!APP_ID) { showEmpty('⊞', 'No workflow selected', 'Open a workflow in the FloLess canvas, then open the contract editor from that workflow’s node.'); return; }
1466
1588
  armEarlyViewToggle(); // BEFORE the first await — that is the whole point; see above
@@ -1468,7 +1590,39 @@ async function boot() {
1468
1590
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS);
1469
1591
  if (!res.ok) {
1470
1592
  if (res.status === 404) {
1471
- showEmpty('⊞', 'No model for', 'Read a structural drawing first — ask your terminal AI to run the workflow, then open this editor again.', APP_ID);
1593
+ // TWO different 404s, and telling them apart is the whole point of this branch.
1594
+ //
1595
+ // Approving a migrated project publishes that project's model into the WORKFLOW's shared .flo, so
1596
+ // an app-keyed read then finds a document that is real but is not this workflow's own — the server
1597
+ // answers `project-publication` for it. Until that code existed both cases said "No model for …
1598
+ // read a structural drawing first", which for a migrated project is false twice over: the model
1599
+ // exists, and reading another drawing is not what gets the user to it.
1600
+ //
1601
+ // The CODE, never the sentence — the sentence is copy and copy gets edited.
1602
+ const code = await errorCodeOf(res);
1603
+ if (code === 'project-publication') {
1604
+ // NO `appIdText` HERE, and that is the fix for a real defect rather than a style choice.
1605
+ //
1606
+ // `showEmpty` BOLDS its 4th argument and appends it after the headline, so the sibling states
1607
+ // read "No model for **steel-model**" — true, because the id is the grammatical object of the
1608
+ // claim. This headline's only true claim is about the PROJECT, which we are barred from naming
1609
+ // (the baked bytes carry no owner marker — see contract-gateway.ts). Passing APP_ID here put a
1610
+ // bolded **steel-model** immediately after an em dash, where it reads as an appositive naming
1611
+ // the owning project — so the one screen that exists BECAUSE the old copy was untrue shipped a
1612
+ // headline that appeared to name the project and named the workflow instead.
1613
+ //
1614
+ // The workflow id is low-information here anyway: the user opened this editor from that very
1615
+ // workflow. The body says what is true about it in prose instead.
1616
+ showEmpty('⊞', 'This model belongs to a project',
1617
+ 'It was approved inside that project, and this workflow doesn’t hold its own copy of it. Open Workspaces and look for the project it came from to see the model there.',
1618
+ null);
1619
+ } else {
1620
+ // A code this build has never heard of falls here on purpose — inventing copy for it would be
1621
+ // worse than the generic state. But an UNRECOGNISED code and NO code are different events
1622
+ // landing on the same sentence, and only the second is ordinary, so name the first.
1623
+ if (code != null) console.warn('boot: unrecognised contract 404 code "' + code + '" — using the generic empty state');
1624
+ showEmpty('⊞', 'No model for', 'Read a structural drawing first — ask your terminal AI to run the workflow, then open this editor again.', APP_ID);
1625
+ }
1472
1626
  } else {
1473
1627
  showEmpty('⚠', 'Couldn’t load the contract', 'The server returned an error. Check that the FloLess server is running, then reopen the editor.');
1474
1628
  }
@@ -1592,6 +1746,20 @@ async function boot() {
1592
1746
  const hasUnsaved = !!sv && (sv.classList.contains('dirty') || sv.classList.contains('err')
1593
1747
  || sv.classList.contains('conflict'));
1594
1748
  if (hasUnsaved) {
1749
+ // GET THE EDIT ONTO DISK FIRST. 'dirty' also covers the 500 ms debounce window, where
1750
+ // `persist()` has not run yet and the edit lives only in `C` — so the Reload this banner is
1751
+ // about to offer would discard it, with no draft to park and nothing to offer back. That is
1752
+ // the same loss the stale-draft flow exists to prevent, arriving 500 ms earlier.
1753
+ //
1754
+ // The LOCAL half only. The server write stays on its debounce: the store has just moved, so a
1755
+ // PUT fired from here would be refused anyway, and racing one against the write we are
1756
+ // reacting to buys nothing. `persist()` is idempotent and does not disarm the timer, so the
1757
+ // pending tick rewriting the same row a moment later changes nothing.
1758
+ // The RESULT matters: quota exceeded, private mode, storage disabled by policy — persist()
1759
+ // swallows each into a red pill, and offering "↻ Reload" over an edit that reached no storage
1760
+ // is offering the very loss this flush exists to prevent, with a button on it.
1761
+ const parked = flushLocalDraft ? flushLocalDraft() : false;
1762
+ if (!parked) console.warn('steel-editor: the pending edit could not be written to this browser — a reload would lose it');
1595
1763
  // WHAT happened, not a guess at who. Absent or unrecognised → today's wording byte for byte.
1596
1764
  // The contract PUT — the one writer that usually IS the terminal AI — deliberately sends no
1597
1765
  // reason, so the generic sentence stays correct for it; and a tab left open across an
@@ -1604,7 +1772,12 @@ async function boot() {
1604
1772
  // to external writes with the error swallowed by the event loop. The reload path must not be
1605
1773
  // able to fail for a reason that only the banner path cares about.
1606
1774
  const lead = (typeof m.reason === 'string' && CHANGE_LEAD[m.reason]) || 'The AI updated this model';
1607
- showAiUpdateBanner(lead + ' — reload to see it (you have unsaved edits).');
1775
+ showAiUpdateBanner(parked
1776
+ ? lead + ' — reload to see it (you have unsaved edits).'
1777
+ // No Reload offered here, deliberately: with nothing in storage it is a button that destroys
1778
+ // their work, and there is no second copy to offer back afterwards.
1779
+ : lead + ' — but this browser could not save your unsaved edits, so reloading would lose them. Copy them out first.',
1780
+ parked ? undefined : { noReload: true });
1608
1781
  } else location.reload();
1609
1782
  };
1610
1783
  es.onerror = () => {
@@ -1640,11 +1813,16 @@ async function boot() {
1640
1813
  * already describes a re-read as "The AI read a revised drawing set". Copy that drifts from the control
1641
1814
  * it describes sends the user looking for a second, non-existent event.
1642
1815
  *
1643
- * Only `revision-read` names an actor, and that asymmetry is deliberate rather than sloppy: a re-read
1644
- * genuinely IS AI-authored (`author: 'AI'`, the History badge reads "AI read"), while a rollback and a
1645
- * conversion are the user's own doing — saying "the AI" there is the untruth this table exists to fix.
1646
- * Neither says "you", because this frame does not carry WHO, and a sentence that asserts the reader did
1647
- * it would be guessing at the one fact the wire withheld.
1816
+ * The two READ tokens name an actor — `revision-read` and `pre-read`, the two phases of one attach —
1817
+ * and that asymmetry is deliberate rather than sloppy: a read genuinely IS AI-authored (`author: 'AI'`,
1818
+ * the History badge reads "AI read"), while a rollback and a conversion are the user's own doing, so
1819
+ * saying "the AI" there is the untruth this table exists to fix. None of them says "you", because this
1820
+ * frame does not carry WHO, and a sentence asserting the reader did it would be guessing at the one
1821
+ * fact the wire withheld.
1822
+ *
1823
+ * (This paragraph said "only `revision-read`" until `pre-read` joined it, which is the kind of sentence
1824
+ * that goes quietly false when a fourth token lands. `verify-change-reasons.mjs` pins that every token
1825
+ * HAS a sentence; nothing can pin that the prose about them still counts them correctly.)
1648
1826
  *
1649
1827
  * The staged confirm (`revision-routes.ts`, the second site) shares `revision-read` even though a human
1650
1828
  * picked which proposals to apply. Deliberate: the AI still authored the read, and the ledger records
@@ -1659,11 +1837,34 @@ async function boot() {
1659
1837
  */
1660
1838
  const CHANGE_LEAD = Object.assign(Object.create(null), {
1661
1839
  'rollback': 'This model was rolled back',
1840
+ // A DELIBERATE VISIBLE PAIR with the row below it, two words apart, and they must be edited together.
1841
+ // These are phase one and phase two of a single user action (attach a revised set / re-read & re-bake):
1842
+ // the pre-read writes the filter and registration and STOPS for the user to review and Save, then the
1843
+ // committed read brings in the members. This bar is a single slot — `showAiUpdateBanner` removes any
1844
+ // existing `#aiUpdateBanner` before appending — so the second sentence REPLACES the first in the same
1845
+ // pixels. "started reading" → "read" therefore reads as progress; two differently-worded sentences
1846
+ // would read as a contradiction. `verify-change-reasons.mjs` pins that both tokens have sentences, but
1847
+ // nothing can check that they still rhyme, so: reword one, reword the other.
1848
+ //
1849
+ // It claims no CONTENT, on purpose. The pre-read writes a different set per schema version — on v2 a
1850
+ // `grid` or root `datum` write is refused by name — so a lead naming the grid would be false on a v2
1851
+ // model. "started reading" is true on both.
1852
+ //
1853
+ // AND IT DOES NOT SAY "REVISED", which is where it parts company with the row below. That row's
1854
+ // comment calls "a revised" a default and an initial read merely reachable "in principle"; for the
1855
+ // PRE-READ it is not in principle at all — `web/aware.js` has a first-class `isInitialRead` branch
1856
+ // that sends the AI through this same two-phase gate, and on a seeded project (which holds a contract
1857
+ // before it holds a v1) that initial pass writes through the verb. So the phase-one sentence would be
1858
+ // wrong on a documented path, not a rare one. Two words apart from phase two instead of one; still
1859
+ // "started reading" → "read", which is what carries the progress.
1860
+ 'pre-read': 'The AI started reading a drawing set into this model',
1662
1861
  // "a revised" is a DEFAULT, not a proof. An initial read can reach this in principle — "initial" is
1663
1862
  // decided by the version ledger, not by the contract, and a seeded project has a contract before it
1664
1863
  // has a v1 (`workspaces.js` renders exactly that empty state). It is rare, and the frame carries no
1665
1864
  // base version to tell the two apart, so the common case wins. `workspaces.js` distinguishes them
1666
1865
  // ("the initial" vs "a revised") only because it has the ledger to hand; here we do not.
1866
+ //
1867
+ // The row above inherits this trade rather than re-deciding it: same phrase, one decision.
1667
1868
  'revision-read': 'The AI read a revised drawing set into this model',
1668
1869
  'migration': 'This project was converted to the 3D model',
1669
1870
  });
@@ -1683,6 +1884,12 @@ function showAiUpdateBanner(message, opts) {
1683
1884
 
1684
1885
  const bar = document.createElement('div');
1685
1886
  bar.id = 'aiUpdateBanner';
1887
+ // A POLITE live region, matching #gZwarn's role=status rather than inventing a pattern. This bar appears
1888
+ // without the user doing anything and is the only notice that the model moved underneath them, so a
1889
+ // sighted user sees it and a screen-reader user previously got nothing at all. Deliberately `status`,
1890
+ // not `alert`: it is non-blocking, it can land mid-drag, and interrupting for it would be wrong.
1891
+ // Focus is NOT moved here for the same reason — see confirmDanger for the case where that IS right.
1892
+ bar.setAttribute('role', 'status');
1686
1893
  // Which cause raised this bar. Only the stale-draft caller sets it, so that one can be auto-dismissed
1687
1894
  // when it stops being true (see edit()) without touching the AI-update and conflict banners, which must
1688
1895
  // survive edits — persisting through them is the whole point of the conflict banner.
@@ -1702,25 +1909,41 @@ function showAiUpdateBanner(message, opts) {
1702
1909
  // today — but it was the last place in the file still asserting "the AI" about a change nobody has
1703
1910
  // established the AI made, which is the claim this bar stopped making. A caller that forgets its
1704
1911
  // message should say nothing it cannot support.
1705
- msg.textContent = message || 'This model changed — reload to see the latest version.';
1912
+ //
1913
+ // The text is written AFTER the bar is in the document (see the end of this function), not here.
1914
+ // A live region that is inserted ALREADY POPULATED is announced inconsistently across screen
1915
+ // readers — the announcement hangs off a mutation INSIDE an existing region — so setting it up
1916
+ // front made role=status decorative. Review caught that; `sentence` carries it to the append.
1917
+ const sentence = message || 'This model changed — reload to see the latest version.';
1706
1918
 
1707
- const reloadBtn = document.createElement('button');
1708
- reloadBtn.style.cssText = 'background:#3b82f6;color:#fff;border:1px solid #60a5fa;border-radius:6px;padding:5px 12px;cursor:pointer;font:13px system-ui';
1709
- // The LABEL is overridable as well as the handler. The two existing callers pass neither and render
1710
- // byte-identically; the stale-draft caller does not reload at all, so a button reading "↻ Reload"
1711
- // would have named an action it does not perform.
1712
- reloadBtn.textContent = (opts && opts.reloadLabel) || '↻ Reload';
1713
- if (opts && opts.reloadTip) reloadBtn.dataset.tip = opts.reloadTip; // data-tip, never title= — the themed tooltip is CI-enforced
1714
- reloadBtn.onclick = (opts && opts.onReload) ? opts.onReload : () => location.reload();
1919
+ // `noReload` — the one caller that must NOT offer it: an unsaved edit that reached no storage.
1920
+ // Suppressing the button beats disabling it; a dead control invites a hunt for why.
1921
+ const reloadBtn = (opts && opts.noReload) ? null : document.createElement('button');
1922
+ if (reloadBtn) {
1923
+ reloadBtn.style.cssText = 'background:#3b82f6;color:#fff;border:1px solid #60a5fa;border-radius:6px;padding:5px 12px;cursor:pointer;font:13px system-ui';
1924
+ // The LABEL is overridable as well as the handler. The two existing callers pass neither and render
1925
+ // byte-identically; the stale-draft caller does not reload at all, so a button reading "↻ Reload"
1926
+ // would have named an action it does not perform.
1927
+ reloadBtn.textContent = (opts && opts.reloadLabel) || '↻ Reload';
1928
+ if (opts && opts.reloadTip) reloadBtn.dataset.tip = opts.reloadTip; // data-tip, never title= — the themed tooltip is CI-enforced
1929
+ reloadBtn.onclick = (opts && opts.onReload) ? opts.onReload : () => location.reload();
1930
+ }
1715
1931
 
1716
1932
  const dismissBtn = document.createElement('button');
1717
1933
  dismissBtn.style.cssText = 'background:transparent;color:#93c5fd;border:1px solid #3b82f6;border-radius:6px;padding:5px 10px;cursor:pointer;font:13px system-ui';
1718
1934
  dismissBtn.textContent = '✕';
1719
1935
  dismissBtn.dataset.tip = 'Dismiss';
1936
+ // The glyph is the button's only content, and data-tip is hover-driven — it reaches neither a keyboard
1937
+ // nor a screen-reader user (the same argument this file makes for aria-describedby on the disabled grid
1938
+ // controls). An earlier version of this comment claimed every other icon-only control here already has
1939
+ // one — review measured that as false (several panel ✕ buttons lack it). It is still the right thing to
1940
+ // add HERE, because this bar appears unbidden and is the only notice that the model moved; the others
1941
+ // are a separate sweep, not a claim to make in passing.
1942
+ dismissBtn.setAttribute('aria-label', 'Dismiss');
1720
1943
  dismissBtn.onclick = () => bar.remove();
1721
1944
 
1722
1945
  bar.appendChild(msg);
1723
- bar.appendChild(reloadBtn);
1946
+ if (reloadBtn) bar.appendChild(reloadBtn);
1724
1947
  if (opts && opts.onOverwrite) {
1725
1948
  // Visually subordinate to Reload — it is the destructive option, and it still has to pass a confirm.
1726
1949
  const over = document.createElement('button');
@@ -1732,6 +1955,10 @@ function showAiUpdateBanner(message, opts) {
1732
1955
  }
1733
1956
  bar.appendChild(dismissBtn);
1734
1957
  document.body.appendChild(bar);
1958
+ // NOW fill the live region, with the bar already in the document — that mutation is what a screen
1959
+ // reader announces. Synchronous, so nothing can see an empty bar paint: the browser has not yielded
1960
+ // between the append and this line, and every DOM probe in the tests reads the sentence as before.
1961
+ msg.textContent = sentence;
1735
1962
  }
1736
1963
 
1737
1964
  function main() {
@@ -2043,7 +2270,14 @@ function snapshot(){return JSON.stringify(Object.assign(MODEL_RO?{modelGrid:C.gr
2043
2270
  function snapshotLike(){return snapshot();}
2044
2271
  function refreshDims3d(){if(window.Steel3DView&&window.Steel3DView.refreshDims)window.Steel3DView.refreshDims();} // repaint the 3D dim lines/labels from C.dims3d
2045
2272
  function refreshOverlayDims3d(){if(window.Steel3DView&&window.Steel3DView.refreshOverlayDims)window.Steel3DView.refreshOverlayDims();} // re-derive the legend DIMENSIONS overlays from C.dim_overlays
2046
- function pushUndo(prev){undo.push(prev);if(undo.length>200)undo.shift();redo.length=0;scheduleSave();}
2273
+ // updUR() here, at the one place that GROWS the undo stack, because not every pusher ends in a render().
2274
+ // The 3D clip / work-area manipulations are the live example: beginClipEdit is literally
2275
+ // `()=>pushUndo(snapshot())`, and the callbacks that follow it (onClipsChange, onWorkAreaChange) rebuild
2276
+ // the legend and the work-area button, never the header — so the entry existed while Undo still looked
2277
+ // dead until some later, unrelated repaint happened to fix it. That was already true on v1; it became
2278
+ // visible on v2 once the read-only branch started syncing these buttons at all, since render() is then
2279
+ // the ONLY other caller. Syncing at the writer covers both formats and every future pusher.
2280
+ function pushUndo(prev){undo.push(prev);if(undo.length>200)undo.shift();redo.length=0;scheduleSave();updUR();}
2047
2281
  function apply(json){
2048
2282
  // The undo stack's restore is the third write primitive (unit 5, P7d). Nothing pushes onto that stack while
2049
2283
  // the document is read-only — edit() refuses before pushUndo — so this is unreachable rather than merely
@@ -2100,7 +2334,7 @@ function apply(json){
2100
2334
  if(window.Steel3DView&&window.Steel3DView.setClipState&&'clips' in d)window.Steel3DView.setClipState(d.clips); // restore clips + work area alongside the contract
2101
2335
  if('member_types' in d)C.member_types=sanitizeMemberTypes(d.member_types);
2102
2336
  if('member_styles' in d)C.member_styles=(d.member_styles&&typeof d.member_styles==='object'&&!Array.isArray(d.member_styles))?d.member_styles:{}; // F5: model-global per-type line styles ride the undo stack (like dim_style) so a setMemberLineStyle() edit() is undoable
2103
- scheduleSave();render();sync3D();}
2337
+ scheduleSave();render();sync3D();}
2104
2338
  function doUndo(){if(!undo.length)return;redo.push(snapshotLike());apply(undo.pop());}
2105
2339
  function doRedo(){if(!redo.length)return;undo.push(snapshotLike());apply(redo.pop());}
2106
2340
  /**
@@ -2180,9 +2414,18 @@ function sanitizeViews(arr){return ViewGen.sanitizeViews(arr);}
2180
2414
  // AI revision changes members, not segments) compared EQUAL, and restoreSaved silently overlaid a stale
2181
2415
  // draft on top of it, masking the other write. See restampDraftBase() for why reading the CURRENT
2182
2416
  // serverEtag here is right, and why it must be re-stamped when a write lands.
2417
+ // `grid` — the ROOT one, which is v2's (v1's grid is per-plan and rides in `plans` below). P7d made it writable on a
2418
+ // read-only document (editGrid), and leaving it out meant a v2 grid edit was never stored at all. NOT
2419
+ // "the only field a v2 document can have unsaved edits in", which is what this said first and what review
2420
+ // disproved: `dim_overlays`, `target_confidence` and `profile_colors` are ungated too (see
2421
+ // RO_DRAFT_KEYS). The narrower true statement is that the grid was the only such field persist() was not
2422
+ // ALREADY storing — and a reload
2423
+ // after an external write discarded it with no offer and no warning. See applyDraftReadOnlyFields for
2424
+ // restore half. Undefined on v1, where JSON.stringify simply drops it.
2183
2425
  function persist(){try{localStorage.setItem(LSKEY,JSON.stringify({sig:dataSig(),baseEtag:serverEtag,ts:Date.now(),active:C.active,
2426
+ grid:C.grid,
2184
2427
  custom_details:C.custom_details, profile_colors:C.profile_colors, member_styles:C.member_styles, member_types:C.member_types, target_confidence:C.target_confidence, dims3d:C.dims3d, dim_overlays:C.dim_overlays, dim_style:C.dim_style, prop_labels:C.prop_labels, joints:C.joints, connections:C.connections, detail_placements:C.detail_placements, views:C.views,
2185
- plans:C.plans.map(p=>({sheet:p.sheet,members:p.members,default_tos:p.default_tos,details:p.details,callouts:p.callouts,dims:p.dims,frame:p.frame||null,grid:p.grid||null}))}));}catch(e){setSaved('err');console.error('local autosave failed',e);}}
2428
+ plans:C.plans.map(p=>({sheet:p.sheet,members:p.members,default_tos:p.default_tos,details:p.details,callouts:p.callouts,dims:p.dims,frame:p.frame||null,grid:p.grid||null}))}));return true;}catch(e){setSaved('err');console.error('local autosave failed',e);return false;}}
2186
2429
  // --- server-side draft save: PUT the FULL contract C — this is the copy Approve bakes.
2187
2430
  // localStorage (persist) stays the instant per-browser draft cache; this is the durable one.
2188
2431
  // fetch does NOT reject on HTTP 400 (schema rejection), so treat !res.ok as 'err' (not a false 'Saved ✓'). ---
@@ -2353,6 +2596,18 @@ async function persistServer(force){const seq=saveSeq;
2353
2596
  }catch(e){releaseMutation(mid);if(seq===saveSeq)setSaved('err');console.error('server save failed',e);}
2354
2597
  });}
2355
2598
  function scheduleSave(){setSaved('dirty');++saveSeq;clearTimeout(saveT);saveT=setTimeout(()=>{saveT=null;persist();persistServer();},500);} // clear the handle as it fires: `saveT !== null` is read as "a write is still pending" (the project send refuses on it), and a spent timer id would read as pending forever // ++saveSeq: a fresh edit is a new save intent — it invalidates any still-in-flight PUT so that PUT's late response can't flip the pill to a stale 'Saved ✓' while this edit is still unsaved (persistServer below captures this same intent id)
2599
+ // The boot-scope SSE handler's seam into that debounce — see `flushLocalDraft` for why the handler
2600
+ // cannot reach `persist()` itself.
2601
+ //
2602
+ // UNCONDITIONAL, and the first cut of this was not. It guarded on `saveT !== null` ("only write when a
2603
+ // save is actually pending"), described as hygiene — and Codex's review found the state that makes that
2604
+ // guard the bug rather than the tidiness: `flushContract()` CANCELS the debounce (`saveT = null`)
2605
+ // without persisting first, and on a refused flush leaves the pill 'err'/'conflict'. So a grid edit
2606
+ // followed inside 500 ms by Ask AI Send, the History revert or the shell's Approve reaches this handler
2607
+ // with the pill unsaved, no timer pending, and nothing on disk — precisely the case the flush exists
2608
+ // for, skipped. There is no state where writing is wrong: `persist()` records `C` as it stands against
2609
+ // the tag this tab believes it is editing, which is what a reload needs to park and offer back.
2610
+ flushLocalDraft = () => persist(); // the RESULT is load-bearing at the call site — a block body returns undefined, i.e. "it failed", and the banner would drop its Reload on every event
2356
2611
  // Flush: cancel the pending debounce and PUT the current in-memory contract to the
2357
2612
  // server right now. The parent (aware.js #contract-editor-approve) awaits this before
2358
2613
  // POSTing approve, so Approve always bakes the latest edits — not a stale debounce
@@ -2409,15 +2664,27 @@ window.flushContract = async () => {
2409
2664
  * Extracted from restoreSaved() (unit 5, P1c-3) so the AUTOMATIC restore and the user-initiated "View my
2410
2665
  * edits instead" apply exactly the same fields. Two copies of this list would drift, and the failure would
2411
2666
  * be silent: a field the button forgot would simply not come back, looking like it was never saved.
2667
+ *
2668
+ * RETURNS whether anything was applied, so the save pill cannot say "Restored ✓" over a document with no
2669
+ * restored edits in it. Be exact about how much that does today: the automatic caller has already passed
2670
+ * `draftFits`, which on a read-only document IS `v2DraftFits`, so the refusal arm is unreachable from
2671
+ * there. It IS reachable from showStaleDraftBanner's handler, where the user can move the document to
2672
+ * match the draft while the bar is up (the three model-global writers are ungated) — and beyond that it
2673
+ * is defence-in-depth against a future caller that skips the gate.
2412
2674
  */
2413
2675
  function applyDraftFields(d){
2414
- // The draft is V1-SHAPED, and overlaying it onto a read-only v2 document is one of the three leaks §8.4
2415
- // names: the per-plan pass below writes `members`, `default_tos` and `grid`, all three of which v2's
2416
- // plan schema forbids. Refused at the primitive rather than at each caller, so the automatic restore and
2417
- // the "View my edits instead" button are covered by one guard. (When the model grid becomes writable it
2418
- // needs a v2-shaped draft of its own — a ROOT `grid`, not a per-plan one; there is nothing to restore
2419
- // until then, because every write is refused.)
2420
- if(!canWriteModel()){console.warn('steel-editor: a local draft was not applied — this document is open read-only');return;}
2676
+ // The per-plan pass below is V1-SHAPED, and overlaying it onto a read-only v2 document is one of the
2677
+ // three leaks §8.4 names: it writes `members`, `default_tos` and `grid`, all three of which v2's plan
2678
+ // schema forbids. Refused at the primitive rather than at each caller, so the automatic restore and the
2679
+ // "View my edits instead" button are covered by one guard.
2680
+ //
2681
+ // CORRECTING WHAT THIS USED TO SAY. It read "there is nothing to restore until then, because every write
2682
+ // is refused" — true when P7d was written, false the moment P7d shipped: that same unit made the MODEL
2683
+ // grid writable on a v2 document (`editGrid` / `GRID_EDIT`, the one exemption `edit()`'s gate carries).
2684
+ // So a v2 document CAN hold an unsaved edit, and it is exactly the one this refusal covered — which made
2685
+ // the sentence not merely stale but load-bearing in the wrong direction. The v2-shaped draft it predicted
2686
+ // is now real (a ROOT `grid`, see persist), and this is where it lands.
2687
+ if(!canWriteModel())return applyDraftReadOnlyFields(d);
2421
2688
  const by={};(d.plans||[]).forEach(p=>by[p.sheet]=p);
2422
2689
  if(d.custom_details)C.custom_details=d.custom_details;
2423
2690
  if(d.profile_colors)C.profile_colors=d.profile_colors;
@@ -2436,7 +2703,179 @@ function applyDraftFields(d){
2436
2703
  if('prop_labels' in d)C.prop_labels=sanitizePropLabels(d.prop_labels); // restore canvas property-label display state (sanitised to known keys/placement)
2437
2704
  if(Array.isArray(d.joints))C.joints=d.joints; // restore model-global connection joints (base plates) from the local draft
2438
2705
  if(Array.isArray(d.views))C.views=sanitizeViews(d.views); // restore the unlimited saved-view library from the local draft; malformed generated provenance is dropped
2439
- if(d.active!=null)C.active=d.active;}
2706
+ if(d.active!=null)C.active=d.active;
2707
+ return true;}
2708
+ /**
2709
+ * Does a draft's grid describe the SAME grid lines as the document now holds?
2710
+ *
2711
+ * The v2 counterpart of dataSig(), and needed for the same reason: `labels_z` is positional against the
2712
+ * authored Z entries and `hidden_z` names elevations, so overlaying either onto a re-spaced grid relabels
2713
+ * or re-hides the wrong levels. Axes are compared as a NORMALISED PROJECTION rather than by stringifying
2714
+ * the objects: `JSON.stringify` is key-order sensitive, so a producer emitting `{dir,id,label}` instead of
2715
+ * `{id,dir,label}` would make an unchanged grid read as re-spaced and refuse the draft with a warning
2716
+ * that names the wrong cause (review).
2717
+ */
2718
+ function gridTopoSig(g){return (g&&typeof g==='object'&&!Array.isArray(g))?JSON.stringify({x:g.x||'',y:g.y||'',z:g.z||'',axes:(Array.isArray(g.axes)?g.axes:[]).map(a=>[(a&&a.id)||'',(a&&a.dir)||'',(a&&a.label)||''])}):'';}
2719
+ /**
2720
+ * WILL the draft's grid land? Topology must match (gridTopoSig), and there must be something to land.
2721
+ *
2722
+ * The second half is not pedantry — though the reason an earlier draft of this comment gave was wrong.
2723
+ * It claimed `boot()` writes a grid into every document; it does not (v2 declares `grid` nullable, and
2724
+ * boot defaults nine other keys but never this one). The real reason survives the correction: a draft is
2725
+ * a snapshot of `C`, so a document that HAS a grid produces a draft with a grid whether or not the user
2726
+ * touched it. "It has a grid" is not "the user changed one". Callers that need "is this worth offering" must ask this, not `d.grid`.
2727
+ */
2728
+ function v2GridFits(d){
2729
+ const dg=d&&d.grid,live=C&&C.grid;
2730
+ if(!dg||typeof dg!=='object'||Array.isArray(dg)||!live)return false;
2731
+ return gridTopoSig(dg)===gridTopoSig(live)&&JSON.stringify(dg)!==JSON.stringify(live);
2732
+ }
2733
+ /**
2734
+ * Is there anything in this draft that a READ-ONLY document can put back?
2735
+ *
2736
+ * Asked before the draft is offered, not only when it is applied: `showStaleDraftBanner` promises the
2737
+ * user their edits are still here and can be switched to, and offering a draft the overlay would then
2738
+ * refuse turns that promise into a button that does nothing.
2739
+ *
2740
+ * TWO WAYS TO QUALIFY — a grid that will land, or a model-global key whose value DIFFERS from the
2741
+ * document's. Both halves have now been wrong once, in opposite directions, and both errors produced
2742
+ * the same symptom:
2743
+ * - grid only: a draft whose one edit was a confidence target was dropped with no offer;
2744
+ * - `k in d`: `boot()` defaults `profile_colors` and `dim_overlays` onto EVERY contract before
2745
+ * `persist()` ever runs, so key presence is universally true. That made this function a constant
2746
+ * `true`, retired the topology gate entirely, and offered a re-spaced draft back under a promise
2747
+ * about a grid that the overlay would then silently skip. Both reviewers reproduced it.
2748
+ * So the test is a DELTA against the live document, which is the only thing "worth offering" can mean.
2749
+ */
2750
+ function v2DraftFits(d){
2751
+ if(!d||typeof d!=='object')return false;
2752
+ if(v2GridFits(d))return true;
2753
+ // JSON compare: both sides descend from the same object graph (C → persist → JSON.parse), so key
2754
+ // order matches whenever the values do. A false "differs" would only cost a no-op offer; a false
2755
+ // "same" would drop the user's edit, so the comparison errs in the safe direction by construction.
2756
+ return RO_DRAFT_KEYS.some(k=>k in d&&JSON.stringify(d[k])!==JSON.stringify(C&&C[k]));
2757
+ }
2758
+ /**
2759
+ * The MODEL-GLOBAL keys a read-only v2 document can still hold unsaved edits in, besides the grid.
2760
+ *
2761
+ * NOT a design statement — an OBSERVATION, and review is what turned it up. `edit()` refuses every
2762
+ * model write on a read-only document, but these three writers never went through `edit()`: the 3D
2763
+ * legend's dimension-overlay swatches (`C.dim_overlays[cat] = …`), the confidence target
2764
+ * (`C.target_confidence = …`) and the palette (`C.profile_colors`). Each ends in `scheduleSave()`,
2765
+ * each key is legal at a v2 root, so each reaches the server today and each lands in the draft.
2766
+ *
2767
+ * Which means they had exactly the same data-loss path this change exists to close, and an earlier cut
2768
+ * of it made them WORSE: the pill said "Grid restored ✓" and the bar promised "your grid changes" over
2769
+ * a draft whose real content was a confidence target that nothing put back. Restoring them is the
2770
+ * conservative reading — the edit already persists to the server, so bringing it back from the draft is
2771
+ * consistency, not new behaviour.
2772
+ *
2773
+ * Whether those three SHOULD be writable on a read-only document is a separate question (a P7d gate
2774
+ * gap) and deliberately not answered here — answering it by dropping the user's edit would be the
2775
+ * wrong way round.
2776
+ */
2777
+ const RO_DRAFT_KEYS=['dim_overlays','target_confidence','profile_colors'];
2778
+ /**
2779
+ * Overlay the parts of a stored draft that a READ-ONLY (v2) document can take back.
2780
+ *
2781
+ * THE GRID, plus RO_DRAFT_KEYS above. The grid's half is the one renderGridPanel leaves enabled: the
2782
+ * visibility switch, the typed origin, the X/Y label overrides, the per-level labels, which levels show,
2783
+ * and the extension. Its complement — the spacings, the levels and the axis ids they mint — belongs to
2784
+ * editGridTopology and is refused for the human as well as the AI, so a restore keeps the DOCUMENT's
2785
+ * topology: no draft, however old or hand-edited, can rebind an axis id or re-space a grid that
2786
+ * dimensions and generated views are anchored to. Keys outside both sets (`axes`, `ends`, `lines`) stay
2787
+ * the document's, which is also what keeps the result schema-valid — v2's `modelGrid` is
2788
+ * `additionalProperties:false`, so a stray key would mean "Save failed" for edits the user never made.
2789
+ * The prose above names those seven, and the single `patchGrid` literal below is what executes — read the
2790
+ * literal as the authority if the two ever disagree. (`x`, `y`, `z` and `axes` are the topology half and
2791
+ * stay the document's; `ends` and `lines` sit outside both sets and stay the document's too.)
2792
+ *
2793
+ * SANITISED FIELD BY FIELD, because localStorage is unvalidated input (the same treatment `member_styles`,
2794
+ * `dims3d`, `views` and `connections` get on the v1 arm) and because this document is bound for a
2795
+ * schema-checked PUT. The draft is AUTHORITATIVE for those keys: one it does not carry comes out as
2796
+ * `undefined`, which `patchGrid` DELETES rather than leaving standing — so "I unhid every level" restores
2797
+ * as an absent `hidden_z` instead of silently keeping the levels hidden.
2798
+ *
2799
+ * TWO EXCEPTIONS, for one reason: `origin` and `ext` are POSITIONS, not flags, so dropping them does not
2800
+ * reset something — it moves or resizes the drawn grid. A missing or unusable value there falls back to
2801
+ * the document's, never to a guess (a [0,0] origin fallback would relocate the whole grid, silently, on a
2802
+ * document bound for an IFC/Tekla bake). `Number.isFinite`, NOT the global `isFinite`, because the global
2803
+ * COERCES: `isFinite(null)` and `isFinite('')` are both true, so `origin:[null,null]` used to sail through
2804
+ * this guard and land as `[0,0]` — the exact outcome the paragraph above says cannot happen (review).
2805
+ *
2806
+ * THROUGH `ModelCmd.patchGrid`, and not by assigning `C.grid` — which the model-boundary guard
2807
+ * (`server/build/verify-model-boundary.mjs`) tracks and refuses. (The undo `apply` path does assign it
2808
+ * directly; that is an explicit, named entry in the guard's allowlist, not a precedent to follow.) The
2809
+ * guard was right to refuse the first cut of this: a restore is a model edit like any other, and
2810
+ * routing it means the ONE place that mutates a grid stays the one place. It also lands the edit in the
2811
+ * live object rather than swapping in a new one, so nothing holding a reference to `C.grid` goes stale.
2812
+ */
2813
+ function applyDraftReadOnlyFields(d){
2814
+ if(!v2DraftFits(d)){
2815
+ // NAMED PRECISELY, because review found this line claiming a re-space for any refused draft that
2816
+ // merely had a grid on both sides — including one with nothing to restore at all, where no re-space
2817
+ // happened. A grid that DIFFERS but does not fit is the re-space; a grid that matches is a draft
2818
+ // with nothing in it.
2819
+ const dg0=d&&d.grid,live0=C&&C.grid;
2820
+ if(dg0&&live0&&JSON.stringify(dg0)!==JSON.stringify(live0))
2821
+ console.warn('steel-editor: a stored grid edit was not applied — the grid was re-spaced elsewhere since those edits were made');
2822
+ else console.warn('steel-editor: a stored draft held nothing this read-only document could put back');
2823
+ return false;}
2824
+ const num=v=>typeof v==='number'&&Number.isFinite(v);
2825
+ const dg=d.grid,live=C&&C.grid,gc=GC();
2826
+ // THE MIXED CASE, and it is the one review called the remaining silent loss: this draft qualified on
2827
+ // one of the model-global keys, so the refusal above did not fire, and the grid is about to be skipped
2828
+ // because it no longer fits. Saying nothing here means a toast that claims the user's edits are on
2829
+ // screen over a grid edit that is not — and the next `persist()` then overwrites the stored grid with
2830
+ // the document's, so the copy goes too. Both channels: the console for the triage, the toast for the
2831
+ // person who lost the work.
2832
+ if(dg&&live&&!v2GridFits(d)&&JSON.stringify(dg)!==JSON.stringify(live)){
2833
+ console.warn('steel-editor: a stored grid edit was not applied — the grid was re-spaced elsewhere since those edits were made');
2834
+ toast('Your earlier grid changes could not be put back — the grid was re-spaced since you made them.');}
2835
+ // The SAME predicate the offer was made on — two spellings of "will the grid land" is exactly how the
2836
+ // banner came to promise a grid the overlay then skipped.
2837
+ if(v2GridFits(d)){
2838
+ const o=dg.origin,originV=(Array.isArray(o)&&o.length>=2&&num(o[0])&&num(o[1]))?[o[0],o[1]]:(Array.isArray(live.origin)?live.origin:undefined);
2839
+ const extV=(num(dg.ext)&&dg.ext>=0)?dg.ext:(num(live.ext)?live.ext:undefined);
2840
+ const zLabels=('labels_z' in dg)?(Array.isArray(dg.labels_z)?dg.labels_z.map(gridLabelText):[]):undefined; // gridLabelText clamps to the schema's 40 chars, exactly as sanitizeGridLines does for v1
2841
+ let hiddenV;
2842
+ if('hidden_z' in dg){
2843
+ const parsed=(gc&&gc.parseLevels)?gc.parseLevels(live.z,zLabels||live.labels_z):null; // against the DOCUMENT's levels (topology is the document's), with the draft's labels — the pair the panel itself renders
2844
+ const hidden=(gc&&gc.normalizeHiddenLevels&&parsed&&!parsed.err)?gc.normalizeHiddenLevels(dg.hidden_z,parsed.levels)
2845
+ :[...new Set((Array.isArray(dg.hidden_z)?dg.hidden_z:[]).filter(num))].sort((a,b)=>a-b);
2846
+ hiddenV=hidden.length?hidden:undefined;}
2847
+ ModelCmd.patchGrid(live,{
2848
+ on:('on' in dg)?!!dg.on:undefined,
2849
+ origin:originV,
2850
+ labels_x:('labels_x' in dg)?String(dg.labels_x==null?'':dg.labels_x):undefined,
2851
+ labels_y:('labels_y' in dg)?String(dg.labels_y==null?'':dg.labels_y):undefined,
2852
+ labels_z:zLabels,
2853
+ hidden_z:hiddenV,
2854
+ ext:extV,
2855
+ });
2856
+ // Mirror the undo path (`apply`, the `modelGrid` branch): the 3D grid is rebuilt from C.grid rather
2857
+ // than re-read on render, and the header toggle's on/off state comes from the same object.
2858
+ refresh3DGrid();updGridToggle();
2859
+ }
2860
+ // The ungated model-global three. `dim_overlays` is sanitised exactly as the v1 arm sanitises it — one
2861
+ // treatment, not two that can drift. The other two are deliberately STRICTER than v1, which takes any
2862
+ // non-null value and any object; see the clamp note below for why a read-only document cannot afford
2863
+ // that laxity.
2864
+ if(d.dim_overlays&&typeof d.dim_overlays==='object'&&!Array.isArray(d.dim_overlays)){const o=d.dim_overlays;C.dim_overlays={bolt_pitch:o.bolt_pitch!==false,edge_clearance:o.edge_clearance!==false,cope_size:o.cope_size!==false,base_plate:o.base_plate!==false,anchor_depth:o.anchor_depth!==false};}
2865
+ // CLAMPED to what v2 declares, not merely type-checked. Review reproduced both escapes from a
2866
+ // hand-edited row: `target_confidence: 999` (the schema caps it at 100) and a `profile_colors` value
2867
+ // that is not a string (the schema's additionalProperties is `{type:'string'}`) each produced a
2868
+ // document the server refuses — "Save failed" on edits the user never made, from a restore.
2869
+ if(num(d.target_confidence))C.target_confidence=Math.max(0,Math.min(100,d.target_confidence));
2870
+ if(d.profile_colors&&typeof d.profile_colors==='object'&&!Array.isArray(d.profile_colors)){
2871
+ const out={};for(const [k,v] of Object.entries(d.profile_colors))if(typeof v==='string')out[k]=v;
2872
+ C.profile_colors=out;}
2873
+ // TRUE means "the draft is the live document again", which is what the caller needs to know — not
2874
+ // "every byte of it landed". Those differ reachably: a grid delta confined to `lines` or `ends` passes
2875
+ // v2GridFits and is then skipped by the patch literal, which takes neither. The v1 arm above answers
2876
+ // the same question the same way. (A draft IDENTICAL to the document cannot reach here at all —
2877
+ // v2DraftFits requires a delta — so it is not the example to reason from.)
2878
+ return true;}
2440
2879
  /**
2441
2880
  * The bar for "your unsaved edits are older than what the server now holds".
2442
2881
  *
@@ -2447,14 +2886,35 @@ function applyDraftFields(d){
2447
2886
  *
2448
2887
  * One click, no confirm: nothing server-side changes when they look. What DOES need care is what happens
2449
2888
  * on the next autosave — see the handler.
2889
+ *
2890
+ * ONE SENTENCE FOR BOTH MODES, and an earlier cut of this had two. The read-only variant said "This
2891
+ * model's GRID has changed … you're viewing the current grid", on the reasoning that a v2 draft can only
2892
+ * hold a grid edit. Review killed it, correctly, on two counts. The trigger is a base-etag mismatch —
2893
+ * ANY external write, most often members or a rollback. Where the draft qualified on its GRID, the gate
2894
+ * has just established that the grid's topology is IDENTICAL, so the sentence asserted the one thing
2895
+ * ruled out immediately above it; where it qualified on a RO_DRAFT_KEYS delta instead, the grid may well
2896
+ * have moved, but then it is not what is coming back. Either way the first half cannot name a cause, and
2897
+ * it sent the user hunting for a grid change that did not happen. The premise was wrong besides:
2898
+ * RO_DRAFT_KEYS are not the grid. What the offer can honestly narrow is the second half — what is being
2899
+ * offered BACK — so only that half names the grid, and only when a grid is what came back.
2450
2900
  */
2451
2901
  function showStaleDraftBanner(d){
2452
- showAiUpdateBanner('This model has changed since you last edited it here — you’re viewing the current version. Your edits from before are still saved on this computer.',{
2902
+ // v2GridFits, NOT `d.grid`: every v2 draft HAS a grid (boot writes one), and a draft whose grid no
2903
+ // longer fits is still offerable for its other keys — so keying on presence promised grid changes
2904
+ // the overlay would then skip. Both reviewers reproduced exactly that.
2905
+ const mine=(!canWriteModel()&&v2GridFits(d))?'Your grid changes':'Your edits';
2906
+ showAiUpdateBanner('This model has changed since you last edited it here — you’re viewing the current version. '+mine+' from before are still saved on this computer.',{
2453
2907
  kind:'staleBase',
2454
2908
  reloadLabel:'View my edits instead',
2455
2909
  reloadTip:'Switch to the changes you made before. The version on the server won’t change unless you edit and save again.',
2456
2910
  onReload:()=>{
2457
- applyDraftFields(d);
2911
+ // The RETURN VALUE, which this caller used to drop on the floor. The three model-global writers are
2912
+ // ungated, so the user can move the document to match the draft while the bar is still up — and
2913
+ // rewinding `serverEtag` then arms a 412 for a restore that put nothing back.
2914
+ if(!applyDraftFields(d)){
2915
+ toast('Those earlier edits no longer apply to this model — nothing was changed.');
2916
+ const b0=document.getElementById('aiUpdateBanner'); if(b0)b0.remove();
2917
+ return;}
2458
2918
  // REWIND the tag to the one those edits were built on. Without this the next autosave would carry
2459
2919
  // the CURRENT server tag, satisfy the precondition, and silently replace the newer version with
2460
2920
  // these older edits — no 412, no banner, no warning. With it, the next save is correctly refused
@@ -2497,8 +2957,11 @@ function restoreSaved(){
2497
2957
  // The SAME structural gate the live row gets, which review found this path had skipped.
2498
2958
  // applyDraftFields overlays per SHEET, so offering a draft built against a different dataset
2499
2959
  // would let the user apply edits that cannot fit — the very masking the live gate prevents,
2500
- // reachable through the parked copy instead.
2501
- if(od&&typeof od==='object'&&od.sig===dataSig())showStaleDraftBanner(od);
2960
+ // reachable through the parked copy instead. (On a read-only v2 document `draftFits` asks the
2961
+ // v2 question as well — is there anything in here such a document can take back, and does a
2962
+ // grid in it still fit this grid — since dataSig alone would wave through a row with nothing
2963
+ // offerable in it.)
2964
+ if(draftFits(od))showStaleDraftBanner(od);
2502
2965
  // Deliberately NOT deleted when it does not fit. dataSig() is derived from the server document,
2503
2966
  // and a rollback can restore the dataset these edits were built against — at which point they
2504
2967
  // become offerable again. An unofferable row is one small row per store; discarding the user's
@@ -2513,14 +2976,42 @@ function restoreSaved(){
2513
2976
  }
2514
2977
  return applied;
2515
2978
  }
2979
+ /**
2980
+ * Can this draft be put back onto the document as it now stands?
2981
+ *
2982
+ * v1: the overlay is per-SHEET, so it is meaningless if the sheets moved — dataSig() is that check.
2983
+ *
2984
+ * v2: dataSig() still has to hold, but it is no longer sufficient, and on its own it is barely relevant —
2985
+ * what a read-only document's draft can carry (the MODEL grid, and the ungated keys in RO_DRAFT_KEYS) is
2986
+ * model-global, and dataSig knows only sheet names and segment counts. So the v2 arm asks `v2DraftFits`:
2987
+ * is there a grid edit that will actually land, or a model-global value that differs? Asked in ONE place
2988
+ * because both the live row and the parked offer must answer it identically — the parked path having
2989
+ * skipped the live path's gate is a bug review already found here once.
2990
+ *
2991
+ * KNOWN SHARP EDGE, logged rather than silently widened (see restoreSavedInner): dataSig is per-SHEET,
2992
+ * so an AI read that adds or drops a sheet refuses a model-global draft that would have applied.
2993
+ */
2994
+ function draftFits(d){return !!(d&&typeof d==='object'&&d.sig===dataSig()&&(canWriteModel()||v2DraftFits(d)));}
2516
2995
  function restoreSavedInner(){
2517
- // Nothing to restore onto a read-only document, and applyDraftFields would refuse anyway — but returning
2518
- // early keeps the SAVE PILL honest. Falling through would reach `return true` having applied nothing, and
2519
- // the pill would say "Restored ✓" over a document with no restored edits in it.
2520
- if(!canWriteModel())return false;
2996
+ // A read-only v2 document is NOT excluded here any more. It was, on the reasoning that "every write is
2997
+ // refused so there is nothing to restore" — which stopped being true when P7d made the model grid
2998
+ // writable in this very mode, and the exclusion then guaranteed the loss it was written to prevent:
2999
+ // the one edit a v2 document can hold was the one edit that could never come back. draftFits() below
3000
+ // asks the v2 question instead of refusing the whole format, and applyDraftFields' return value keeps
3001
+ // the SAVE PILL honest — a refused draft must not leave it saying "Restored ✓" over a document with no
3002
+ // restored edits in it, which is what the early return was really protecting.
2521
3003
  try{const raw=localStorage.getItem(LSKEY);if(!raw)return false;const d=JSON.parse(raw);
2522
- // Structural first: the overlay below is per-sheet, so it is meaningless if the sheets moved.
2523
- if(d.sig!==dataSig())return false;
3004
+ // Structural first: the overlay is per-sheet on v1 and per-grid-topology on v2, so it is meaningless if
3005
+ // either moved.
3006
+ if(!draftFits(d)){
3007
+ // NOT SILENT any more (review). Two different refusals reach here and a triage needs to tell them
3008
+ // apart — and the second is a known sharp edge: `dataSig()` is per-SHEET, while a v2 draft's grid is
3009
+ // model-global, so an AI read that adds or drops a sheet refuses a grid draft that would have
3010
+ // applied perfectly. Logged rather than quietly widened: relaxing the gate for v2 changes what "the
3011
+ // same drawing set" means, which is not this fix's call to make.
3012
+ if(d&&d.sig!==dataSig())console.warn('steel-editor: stored edits were not restored — the drawing set changed (sheets added or removed) since they were made');
3013
+ else console.warn('steel-editor: stored edits were not restored — nothing in them fits this document as it now stands');
3014
+ return false;}
2524
3015
  // Then the real base check. `serverEtag` is the tag boot() just read — main() is called synchronously
2525
3016
  // from boot() and nothing writes before this point, so it has not been advanced by a save yet. (If a
2526
3017
  // future change schedules a write earlier, this comparison silently starts meaning something else.)
@@ -2545,7 +3036,7 @@ function restoreSavedInner(){
2545
3036
  showStaleDraftBanner(d);
2546
3037
  return false;
2547
3038
  }
2548
- applyDraftFields(d);return true;}catch(e){console.warn('discarding corrupt local draft',e);return false;}}
3039
+ return applyDraftFields(d);}catch(e){console.warn('steel-editor: a stored draft could not be read or applied — leaving it in place',e);return false;}}
2549
3040
  function updUR(){document.getElementById('undoB').disabled=!undo.length;document.getElementById('redoB').disabled=!redo.length;}
2550
3041
  // Canonical, model-global palette rank (B2): EVERY plan's non-blank member profiles ∪ weight-table keys,
2551
3042
  // uppercased + sorted — the SAME basis contract-to-scene.ts uses, so a profile gets ONE hue in the 2D legend
@@ -3501,7 +3992,29 @@ function render(){
3501
3992
  // never persisted — the adapter's own sheetFrame() refuses to fabricate one. So the canvas stays empty
3502
3993
  // rather than drawing a plausible plan in the wrong place, which is the worst defect class this epic has.
3503
3994
  // The inspector still repaints: the read-only panel is what the user actually has here.
3504
- if(MODEL_RO){svg.replaceChildren();stats();panel();return;} // stats() here only RETIRES the per-sheet readouts — see its v2 branch
3995
+ // …and the header state, which this return used to skip entirely. The ⋯ → Display rows are the one
3996
+ // group of STATE-REPORTING rows read-only leaves usable (RO_LOCKED_SECS locks detailing/checks/snap;
3997
+ // coords and session are left live too, but carry actions rather than state). Their sync sits in
3998
+ // render()'s trailing upd*() batch, which this return never reaches — so every one of them showed its
3999
+ // static markup instead, and the static markup carries NO `on` class at all, so the slider switch
4000
+ // painted OFF on all six however their flags actually stood. Grid lines lied loudest: OFF over a grid
4001
+ // that is on and drawn in 3D, and enabled on a document with no grid. (Grid lines alone could recover,
4002
+ // since gridSetVisible and the undo restore call its updater directly; the other five could not.)
4003
+ // syncDisplayRows() is deliberately a NAMED function called from both exits rather than a second list
4004
+ // spelled out here — a hand-maintained copy of "the Display rows" is how these came to be skipped, and
4005
+ // verify:display-sync fails the build if the two ever disagree.
4006
+ // updUR joins them: apply() does not sync the buttons either, so on a v2 document Undo/Redo NEVER track
4007
+ // the stack — enabled from boot, still enabled after the one grid edit this mode allows has been undone
4008
+ // and there is nothing left to undo. An earlier revision of this repair left it out on the grounds that
4009
+ // an empty stack at boot is harmless; that was wrong, because the desync is permanent, not initial.
4010
+ // The REST of the batch is deliberately NOT called here; each was checked rather than assumed:
4011
+ // updDup THROWS on v2 (redundantDups reads P.members, which a v2 plan does not have — measured, and on
4012
+ // its own reason enough not to call the batch wholesale; pinned by a characterisation test);
4013
+ // updConnBtn/updBpBtn/updSpBtn label rows inside the Detailing section, which read-only disables AND
4014
+ // force-closes, so they are unreachable; updConf yields an empty report that leaves #confStat at the
4015
+ // display:none its markup already carries; and updCS is already called from every path that can change
4016
+ // the axes on a v2 document (csArm3dB, onFrame3dChange, the view switch), so it would add nothing.
4017
+ if(MODEL_RO){svg.replaceChildren();stats();panel();updUR();syncDisplayRows();return;} // stats() here only RETIRES the per-sheet readouts — see its v2 branch
3505
4018
  document.body.classList.remove('snapping'); // a wholesale svg rebuild drops any #snapMark → clear the cursor-hide flag too (the next pointermove re-adds it if still snapping)
3506
4019
  buildColorRank(); // refresh the model-global colour rank before any colorFor() call below (B2 — keeps 2D hues stable across plans + matched to 3D)
3507
4020
  reanchorAllPlans(); // F9: glue magnetic dims to their members BEFORE anything reads P.dims — covers every mutation path that ends in a render()
@@ -3556,7 +4069,7 @@ function render(){
3556
4069
  if(P.frame)s+=axisGlyphSvg(P.frame.o,P.frame.u,false); // local-axes glyph at the origin (only when a frame is set; removed on reset)
3557
4070
  // the detail datalist shows the SAME list as the combobox and the Details modal (#397), built as DOM
3558
4071
  // nodes rather than markup so a detail name coming off the drawing is never parsed as HTML
3559
- svg.innerHTML=s; document.getElementById('profiles').innerHTML=profs.map(p=>`<option value="${esc(p)}">`).join(''); {const dl=document.getElementById('details');dl.replaceChildren(...detTexts().map(t=>{const o=document.createElement('option');o.value=t;return o;}));} stats(); panel(); updUR(); updDup(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); updGridToggle(); updLenToggle(); updDimToggle(); updCalloutToggle(); updPlToggle(); updRefToggle();
4072
+ svg.innerHTML=s; document.getElementById('profiles').innerHTML=profs.map(p=>`<option value="${esc(p)}">`).join(''); {const dl=document.getElementById('details');dl.replaceChildren(...detTexts().map(t=>{const o=document.createElement('option');o.value=t;return o;}));} stats(); panel(); updUR(); updDup(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncDisplayRows();
3560
4073
  if(selFilterReady)reflectSelFilter(); // keep the Select-bar Members/Connections buttons in sync with the model — a new/removed connection kind (e.g. the first auto-detailed base plate) flips their on/off without a manual toggle. Gated on selFilterReady so it doesn't run until the deferred first reflect has armed it (that reflect needs BASE_MEMBER_TYPES, initialised later in main()).
3561
4074
  if(view3d&&window.Steel3DView){window.Steel3DView.setSelection(selIds);if(window.Steel3DView.setGridSelection)window.Steel3DView.setGridSelection(selGridIds);updateIsolateBtn();if((selIds.size||selGridIds.size)&&window.Steel3DView.selectedClips&&window.Steel3DView.selectedClips().length)window.Steel3DView.setSelectedClips([]);refreshLegendSel();} // keep the 3D member + grid highlight in sync; selecting geometry clears any clip selection (exclusive)
3562
4075
  try{updateConnCrumb();}catch(_){} // Connection Component breadcrumb follows the selection (3D-only; hidden at root)
@@ -4108,11 +4621,28 @@ function panel(){
4108
4621
  // about, so an un-annotated end gains no clutter. A refusal is never a dead end: it says what is missing
4109
4622
  // and offers the action that fixes it, because "Apply is greyed out and I don't know why" is the failure
4110
4623
  // this whole surface exists to avoid.
4111
- const dStat=(id,o,which)=>{
4112
- if(!o.detail&&!o.conn)return '';
4113
- const r=resolveDetail(m,which), cap=captureEligible(m,which);
4114
- const capBtn=cap?`<button id=${id}_cap class=ghost data-tip="Remember what this connection means, so every end with the same callout can be built from it">Remember as ${esc(o.detail)}</button>`:'';
4115
- if(r.ok){
4624
+ const dStat=(id,o,which)=>{
4625
+ const r=resolveDetail(m,which), cap=captureEligible(m,which);
4626
+ const capBtn=cap?`<button id=${id}_cap class=ghost data-tip="Remember what this connection means, so every end with the same callout can be built from it">Remember as ${esc(o.detail)}</button>`:'';
4627
+ const joint=jointAtEnd(m.id,which), truthId=(joint&&joint.id)||connectionPreviewJointByEnd.get(o), diag=truthId&&connectionDiagnostics.find(d=>d&&d.jointId===truthId);
4628
+ if(truthId&&connectionDiagnosticsStatus!=='ready'){
4629
+ const unavailable=connectionDiagnosticsStatus==='unavailable';
4630
+ return `<div class=drow aria-busy="${unavailable?'false':'true'}"><div style="flex:1 1 100%;min-width:0"><div class="dmsg warn">${unavailable?'Build status unavailable':'Checking connection build status…'}</div><div class=hint role=note style="margin-top:3px">${unavailable?'The connection engine could not verify this detail. No build action is offered until verification succeeds.':'The connection engine is checking the current model before offering a build action.'}</div></div>${unavailable?`<button id=${id}_retry class=ghostw data-tip="Check this connection against the current model again">Check again</button>`:''}</div>`;
4631
+ }
4632
+ if(diag&&diag.severity==='error'){
4633
+ const truth=connectionRefusalCopy(diag,m);
4634
+ return `<div class=drow><div style="flex:1 1 100%;min-width:0"><div class="dmsg warn">${esc(truth.head)}</div><div class=hint role=note style="margin-top:3px">${esc(truth.detail)}</div></div></div>`;
4635
+ }
4636
+ if(diag&&diag.code==='bolt-gauge-adjusted'){
4637
+ const authored=fmtFtIn(Number(diag.authored)/25.4),built=fmtFtIn(Number(diag.built)/25.4);
4638
+ const preview=!joint;
4639
+ return `<div class=drow><div style="flex:1 1 100%;min-width:0"><div class="dmsg warn">${preview?'Would build':'Built'} with adjusted bolt gauge</div>`
4640
+ +`<div class=hint role=note style="margin-top:3px"><div>Authored bolt gauge <b>${esc(authored)}</b></div><div>Bolt gauge (${preview?'after build / in exports':'built / exported'}) <b>${esc(built)}</b></div>`
4641
+ +`<div style="margin-top:3px">The bolted region cannot fit the authored gauge. ${preview?'Building this detail would make':'The 3D model, IFC, and Tekla export use'} ${esc(built)}${preview?' the gauge used by the 3D model, IFC, and Tekla export.':'.'}</div></div></div>`
4642
+ +(r.ok?`<button id=${id}_ap class=ghostw data-tip="${preview?'Build this connection from the detail':'Build it again from the detail, replacing what is here'}">${preview?'Build it':'Rebuild it'}</button>`:'')+`${capBtn}</div>`;
4643
+ }
4644
+ if(!o.detail&&!o.conn)return '';
4645
+ if(r.ok){
4116
4646
  // `built` also requires the joint to CITE this row: an identical-looking connection that came from a
4117
4647
  // different detail is not this detail's work, and saying "Built" for it would misreport provenance.
4118
4648
  const j=jointAtEnd(m.id,which), built=!!j&&j.kind===r.kind&&j.conn===r.rowId&&!recipeParamsDiffer(j.params,r.params);
@@ -4152,17 +4682,19 @@ function panel(){
4152
4682
  const spAllAuto=spjs.length>0&&spjs.every(x=>x.j.source==='auto');
4153
4683
  // DOM ids key on the END INDEX (0/1), NEVER the joint id (a free-string schema field) — so a crafted
4154
4684
  // joints[].id can't inject into an attribute position; the handlers below close over the real joint.
4155
- const spF=(e,j,key,label,ph,unit)=>{const raw=j&&j.params&&j.params[key]!=null?j.params[key]:null;const val=raw==null?'':(unit==='mm'?esc(fmtFtIn(Number(raw)/25.4)):esc(String(raw)));
4156
- return `<div class=elab>${label}</div><input id="spf_e${e}_${key}" inputmode=decimal placeholder="${esc(ph)}" value="${val}" autocomplete=off>${unit&&unit!=='mm'?`<span class=edec>${unit}</span>`:''}`;}; // mm params shown/entered in ft-in
4157
- const spBlock=({e,j})=>{const dot=e===1?dotE:dotS,lbl=e===1?'End':'Start',st=!!(j.params&&j.params.stiffener);const gus=j.kind==='brace-gusset';
4158
- return `<div class=divrow><hr><span class=sect style="margin:0">${dot}${lbl} · ${gus?'Gusset plate':'Shear plate'}</span><hr></div>
4685
+ const spF=(e,j,key,label,ph,unit)=>{const raw=j&&j.params&&j.params[key]!=null?j.params[key]:null;const val=raw==null?'':(unit==='mm'?esc(fmtFtIn(Number(raw)/25.4)):esc(String(raw)));
4686
+ return `<div class=elab>${label}</div><input id="spf_e${e}_${key}" inputmode=decimal placeholder="${esc(ph)}" value="${val}" autocomplete=off>${unit&&unit!=='mm'?`<span class=edec>${unit}</span>`:''}`;}; // mm params shown/entered in ft-in
4687
+ const spBlock=({e,j})=>{const dot=e===1?dotE:dotS,lbl=e===1?'End':'Start',st=!!(j.params&&j.params.stiffener);const gus=j.kind==='brace-gusset';
4688
+ const gaugeDiag=connectionDiagnostics.find(d=>d&&d.jointId===j.id&&d.code==='bolt-gauge-adjusted');
4689
+ const builtGauge=gaugeDiag?`<div style="display:flex;justify-content:space-between;gap:8px;font-size:12px;margin:3px 0" role=note><span style="color:var(--mut)">Bolt gauge (built / exported)</span><span style="font-variant-numeric:tabular-nums">${esc(fmtFtIn(Number(gaugeDiag.built)/25.4))}</span></div>`:'';
4690
+ return `<div class=divrow><hr><span class=sect style="margin:0">${dot}${lbl} · ${gus?'Gusset plate':'Shear plate'}</span><hr></div>
4159
4691
  ${spF(e,j,'plateWidth','Plate width','auto','mm')}${spF(e,j,'plateHeight','Plate height','auto','mm')}${spF(e,j,'plateThickness','Thickness','3/8"','mm')}${spF(e,j,'weldLeg','Weld leg','1/4"','mm')}${gus?spF(e,j,'plateCount','Plates (1 or 2)','2',''):spF(e,j,'clearance','Clearance (beam gap)','1/2"','mm')}
4160
4692
  <div class=elabrow><span class=elab>${gus?'Lapped side':'Web side'}</span></div>
4161
4693
  <div class=seg2 style="margin-top:0"><button id="spside_e${e}_n" class="${(j.params&&j.params.webSide<0)?'':'on'}">Near</button><button id="spside_e${e}_f" class="${(j.params&&j.params.webSide<0)?'on':''}">Far</button></div>
4162
4694
  ${gus?'':`<div class=elabrow><span class=elab>Weld sides</span></div>
4163
4695
  <div class=seg2 style="margin-top:0"><button id="spw_e${e}_n" class="${(j.params&&j.params.weldSide==='near')?'on':''}">Near</button><button id="spw_e${e}_f" class="${(j.params&&j.params.weldSide==='far')?'on':''}">Far</button><button id="spw_e${e}_b" class="${(!j.params||!j.params.weldSide||j.params.weldSide==='both')?'on':''}">Both</button></div>`}
4164
4696
  <div class=elab style="margin-top:7px;opacity:.7">Bolts</div>
4165
- ${spF(e,j,'boltCols','Bolt columns','1','')}${spF(e,j,'boltRows','Bolt rows','3','')}${spF(e,j,'boltDia','Bolt ⌀','3/4"','mm')}${spF(e,j,'boltPitch','Row spacing','2 3/4"','mm')}${(Number(j.params&&j.params.boltCols)>1)?spF(e,j,'boltColPitch','Column spacing',(j.params&&j.params.boltPitch!=null?fmtFtIn(Number(j.params.boltPitch)/25.4):'2 3/4"'),'mm'):''}
4697
+ ${spF(e,j,'boltCols','Bolt columns','1','')}${spF(e,j,'boltRows','Bolt rows','3','')}${spF(e,j,'boltDia','Bolt ⌀','3/4"','mm')}${spF(e,j,'boltPitch','Row spacing','2 3/4"','mm')}${(Number(j.params&&j.params.boltCols)>1)?spF(e,j,'boltColPitch','Authored bolt gauge',(j.params&&j.params.boltPitch!=null?fmtFtIn(Number(j.params.boltPitch)/25.4):'2 3/4"'),'mm'):''}${builtGauge}
4166
4698
  <div class=elabrow><span class=elab>Bolt grade</span></div>
4167
4699
  <div class=seg2 style="margin-top:0"><button id="spg_e${e}_325" class="${(j.params&&j.params.boltGrade==='A490')?'':'on'}">A325</button><button id="spg_e${e}_490" class="${(j.params&&j.params.boltGrade==='A490')?'on':''}">A490</button></div>
4168
4700
  <div class=hint style="margin:4px 0 0">Bolt length auto-sizes from the grip (AISC) → shown on the bolt callout.</div>
@@ -4329,6 +4861,8 @@ function panel(){
4329
4861
  if(cap)cap.onclick=()=>openCaptureModal(m,which);
4330
4862
  const fx=document.getElementById(id+'_fx');
4331
4863
  if(fx)fx.onclick=()=>openDetailPick(m,which);
4864
+ const retry=document.getElementById(id+'_retry');
4865
+ if(retry)retry.onclick=()=>{invalidateConnectionDiagnostics(true);panel();};
4332
4866
  };
4333
4867
  const wireConn=(id,o)=>{const i=document.getElementById(id);if(!i)return;i.onchange=e=>edit(()=>{const v=(e.target.value||'').trim();o.conn=(!v||v==='— none —')?'':v.split(' · ')[0];});};
4334
4868
  if(col){
@@ -5395,7 +5929,7 @@ function openLevelModal(tool){ // works from 2D and 3D — the commit is plan-
5395
5929
  let pick=-1;const rows=[];
5396
5930
  const go=document.createElement('button');go.className='primary';go.disabled=true;go.textContent=tool==='move'?'Move here':'Copy here';
5397
5931
  C.plans.forEach((pl,i)=>{const row=document.createElement('div');row.className='lvrow'+(pl===P?' cur':'');
5398
- const nm=document.createElement('span');nm.textContent=pl.sheet+(pl.title?' · '+pl.title:'')+(pl===P?' (current)':'');
5932
+ const nm=document.createElement('span');nm.textContent=planLabel(pl,i)+(pl===P?' (current)':''); // the page's ONE plan-label rule — this modal and the header switcher must not disagree about what a plan is called
5399
5933
  const ts=document.createElement('span');ts.className='lvtos';const nM=(pl.members||[]).length;ts.textContent=nM+' member'+(nM===1?'':'s')+' · TOS '+fmtFtIn(pl.default_tos!=null?pl.default_tos:198);
5400
5934
  row.append(nm,ts);
5401
5935
  if(pl!==P){row.onclick=()=>{pick=i;rows.forEach(r=>r.classList.remove('pick'));row.classList.add('pick');go.disabled=false;};
@@ -5483,6 +6017,7 @@ function updCS(){const s=document.getElementById('csStat');const r=document.getE
5483
6017
  // (the Tekla send takes seconds); the next plain toast() replaces the text and re-arms the timer.
5484
6018
  function toast(msg,sticky){let t=document.getElementById('toast');
5485
6019
  if(!t){t=document.createElement('div');t.id='toast';t.style.cssText='position:fixed;left:50%;bottom:18px;transform:translateX(-50%);background:var(--panel);color:var(--text);border:1px solid var(--line);border-radius:8px;padding:8px 14px;box-shadow:0 6px 20px rgba(0,0,0,.5);z-index:60;font:13px system-ui;opacity:0;transition:opacity .2s;pointer-events:none';document.body.appendChild(t);}
6020
+ t.setAttribute('role','status');t.setAttribute('aria-live','polite');t.setAttribute('aria-atomic','true');
5486
6021
  t.textContent=msg;t.style.opacity='1';clearTimeout(t._h);if(!sticky)t._h=setTimeout(()=>{t.style.opacity='0';},2600);}
5487
6022
  // --- pointer: select(+ctrl toggle / box) + group-move + endpoint (Shift = ortho) ---
5488
6023
  svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
@@ -5772,16 +6307,66 @@ document.getElementById('csArm3dB').onclick=()=>{const d3=window.Steel3DView;if(
5772
6307
  const fi=d3.frameInfo(),o=fi.origin?[...fi.origin]:[0,0,0],x=parseFloat(document.getElementById('csF3dX').value)*FT,y=parseFloat(document.getElementById('csF3dY').value)*FT,z=parseFloat(document.getElementById('csF3dZ').value)*FT;
5773
6308
  d3.setFrameOrigin([isNaN(x)?o[0]:x,isNaN(y)?o[1]:y,isNaN(z)?o[2]:z]);
5774
6309
  updCS();});});
5775
- function updDimToggle(){const b=document.getElementById('dimToggleB');if(b){b.classList.toggle('on',dimsVisible);b.setAttribute('aria-checked',String(dimsVisible));}}
5776
- document.getElementById('dimToggleB').onclick=e=>{e.stopPropagation();dimsVisible=!dimsVisible;updDimToggle();render();};
5777
- function updLenToggle(){const b=document.getElementById('lenToggleB');if(b){b.classList.toggle('on',showSelLen);b.setAttribute('aria-checked',String(showSelLen));}}
5778
- document.getElementById('lenToggleB').onclick=e=>{e.stopPropagation();showSelLen=!showSelLen;try{localStorage.setItem('steel:selLen:v1',showSelLen?'1':'0');}catch(_){}updLenToggle();render();}; // render() repaints the 2D chips + pushes labels to 3D
5779
- function updCalloutToggle(){const b=document.getElementById('calloutToggleB');if(b){b.classList.toggle('on',calloutsVisible);b.setAttribute('aria-checked',String(calloutsVisible));}}
5780
- document.getElementById('calloutToggleB').onclick=e=>{e.stopPropagation();calloutsVisible=!calloutsVisible;updCalloutToggle();render();};
6310
+ /**
6311
+ * The ⋯ → Display TOGGLE ROWS — the `.dtog` buttons, synced in ONE place.
6312
+ *
6313
+ * Named once and called from both of render()'s exits (the MODEL_RO branch and the trailing sync), so
6314
+ * "the Display rows" cannot mean two different lists. Adding a seventh `.dtog` row means adding its
6315
+ * updater here and nowhere else; `npm run verify:display-sync` fails the build if a `.dtog` id in the
6316
+ * markup has no updater in this function, because a hand-maintained second copy is exactly how the v2
6317
+ * rows came to be skipped in the first place.
6318
+ *
6319
+ * WHAT A ROW ON A READ-ONLY DOCUMENT REPORTS. Each of these paints one surface and one only: Dimensions
6320
+ * and Callouts draw onto the 2D plan, Reference sheet draws the traced sheet under it, Member length
6321
+ * needs a length v2 cannot yet produce (below). A v2 document has no 2D plan — render() returns before
6322
+ * drawing one and the 2D tab is permanently the #ro2d empty state — so on v2 all four are OFF, and they
6323
+ * say so: `!MODEL_RO && flag` rather than the raw flag. Reporting the raw flag is what the first version
6324
+ * of this repair did, and it shipped `aria-checked=true` on a DISABLED row — "on, and you cannot turn it
6325
+ * off", which is the very defect this repair exists to remove, just moved to different rows.
6326
+ *
6327
+ * (The equivalent v1 case — Reference sheet checked-and-disabled on a plan with no traced sheet — is
6328
+ * pre-existing and deliberately untouched here; this change is scoped to the read-only regression.)
6329
+ *
6330
+ * DISABLED BARE, with no aria-describedby: the self-disable updGridToggle (no grid) and updRefToggle (no
6331
+ * reference sheet) already use. #roRibbon would state the wrong reason — its copy is about REFUSED
6332
+ * EDITS, and these are not refused writes. `dimsVisible` flips perfectly well; there is no canvas for it
6333
+ * to reach. (Known gap: a disabled button fires no pointer events, so its data-tip cannot explain the
6334
+ * greying either. Shared with the two pre-existing self-disabling rows — see the follow-up.)
6335
+ */
6336
+ function syncDisplayRows(){updGridToggle();updLenToggle();updDimToggle();updCalloutToggle();updPlToggle();updRefToggle();}
6337
+ function updDimToggle(){const b=document.getElementById('dimToggleB');if(!b)return;const on=!MODEL_RO&&dimsVisible;b.disabled=MODEL_RO;b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));}
6338
+ document.getElementById('dimToggleB').onclick=e=>{e.stopPropagation();if(MODEL_RO)return;dimsVisible=!dimsVisible;updDimToggle();render();}; // the guard is the enforcement, the disable is only the UX — same split canWriteViews makes
6339
+ // Member length is OFF on v2 for a DIFFERENT reason than its plan-only neighbours, and the difference
6340
+ // matters to whoever re-enables it. This one is not conceptually 2D — it pushes labels to 3D too
6341
+ // (refreshSelLen3d), and 3D is the view a v2 document opens in, so it OUGHT to apply here. It cannot
6342
+ // produce a label at all today, twice over: refreshSelLen3d is reached only via
6343
+ // syncPropLabelsAfterRender(), whose two callers (render()'s trailing sync and reflect2dGridSelection)
6344
+ // are both skipped or unreachable on v2; and _len3dFt measures `m.wp`, which a v2 member does not have
6345
+ // (it carries from/to), so every length comes back 0 and is dropped as degenerate. Wiring the call alone
6346
+ // would therefore NOT fix it. Delete this disable when v2 gets a real length — it describes a gap, it
6347
+ // does not declare the row inapplicable.
6348
+ function updLenToggle(){const b=document.getElementById('lenToggleB');if(!b)return;const on=!MODEL_RO&&showSelLen;b.disabled=MODEL_RO;b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));}
6349
+ document.getElementById('lenToggleB').onclick=e=>{e.stopPropagation();if(MODEL_RO)return;showSelLen=!showSelLen;try{localStorage.setItem('steel:selLen:v1',showSelLen?'1':'0');}catch(_){}updLenToggle();render();}; // render() repaints the 2D chips + pushes labels to 3D
6350
+ function updCalloutToggle(){const b=document.getElementById('calloutToggleB');if(!b)return;const on=!MODEL_RO&&calloutsVisible;b.disabled=MODEL_RO;b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));} // plan-only, like Dimensions
6351
+ document.getElementById('calloutToggleB').onclick=e=>{e.stopPropagation();if(MODEL_RO)return;calloutsVisible=!calloutsVisible;updCalloutToggle();render();};
6352
+ // NOTE FOR THE NEXT EDITOR: do NOT add `b.disabled=MODEL_RO` here to match the five rows around it.
6353
+ // This row's disable is owned by roDisablePropLabelToggles(), which runs ONCE at boot and also sets the
6354
+ // aria-describedby; updPlToggle runs on EVERY render, so an assignment here would clobber both on the
6355
+ // first repaint after boot — the row would silently go live and lose its screen-reader reason. A
6356
+ // mutation run proved the shape passes the suite unless it is asserted after an op, which is why
6357
+ // steel-editor-v2.test.ts re-asserts this row's whole state following a render.
6358
+ // Its OFF-on-v2 reading needs no MODEL_RO term: plVis() already short-circuits to false under it — and
6359
+ // that short-circuit is also what keeps this line safe, because C.prop_labels is left UNNORMALISED on a
6360
+ // read-only document (sanitizePropLabels runs inside a canWriteModel() guard).
5781
6361
  function updPlToggle(){const b=document.getElementById('plToggleB');if(b){const on=!!(C.prop_labels&&plVis(false));b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));}} // B1: 2D property-label visibility (independent of 3D)
5782
6362
  document.getElementById('plToggleB').onclick=e=>{e.stopPropagation();if(!canWritePropLabelVis())return;C.prop_labels.vis2d=!C.prop_labels.vis2d;updPlToggle();refreshPropLabels();}; // refreshPropLabels → scheduleSave()+render(): repaints the 2D chips (gated by vis2d) and persists the choice
5783
- function updRefToggle(){const b=document.getElementById('refToggleB');if(!b)return;b.disabled=!hasOverlay();b.classList.toggle('on',refSheetOn);b.setAttribute('aria-checked',String(refSheetOn));} // F13: grey the row out on a plan with no reference sheet (mirrors updGridToggle's no-grid disable)
5784
- document.getElementById('refToggleB').onclick=e=>{e.stopPropagation();refSheetOn=!refSheetOn;try{localStorage.setItem('steel:refSheet:v1',refSheetOn?'1':'0');}catch(_){}updRefToggle();render();}; // render() rebuilds the SVG (overlaySvg gone/back) and buildSnap re-reads overlaySnapGeom (snap candidates gone/back)
6363
+ // MODEL_RO is a term here in its own right, NOT covered by !hasOverlay(): `filter` is a legal v2 root key
6364
+ // and the migration copies it verbatim, so a project migrated from drawings arrives WITH one and
6365
+ // hasOverlay() answers true — leaving this row live over a canvas that draws nothing. Worse than inert:
6366
+ // the handler persists to `steel:refSheet:v1`, which is not project-scoped, so a click here would follow
6367
+ // the user into their next v1 project and hide the traced sheet there.
6368
+ function updRefToggle(){const b=document.getElementById('refToggleB');if(!b)return;const on=!MODEL_RO&&refSheetOn;b.disabled=MODEL_RO||!hasOverlay();b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));} // F13: grey the row out on a plan with no reference sheet (mirrors updGridToggle's no-grid disable)
6369
+ document.getElementById('refToggleB').onclick=e=>{e.stopPropagation();if(MODEL_RO)return;refSheetOn=!refSheetOn;try{localStorage.setItem('steel:refSheet:v1',refSheetOn?'1':'0');}catch(_){}updRefToggle();render();}; // render() rebuilds the SVG (overlaySvg gone/back) and buildSnap re-reads overlaySnapGeom (snap candidates gone/back)
5785
6370
  document.getElementById('gridEditB').onclick=()=>{setGridMode(!gridMode);render();};
5786
6371
  {const ghb=document.getElementById('gridHdrB');if(ghb)ghb.onclick=()=>{setGridMode(!gridMode);render();};} // the header twin (read-only mode only) — same one action, not a second implementation
5787
6372
  /**
@@ -5903,7 +6488,14 @@ document.getElementById('redoB').onclick=doRedo;
5903
6488
  document.getElementById('dragMoveB').onclick=()=>{setDragMove(!dragMoveOn);toast(dragMoveOn?'Drag to move/copy: ON — drag moves, Ctrl+drag copies':'Drag to move/copy: OFF — a click only selects');};
5904
6489
  setDragMove(dragMoveOn); // reflect the persisted state on load (body class + pill)
5905
6490
  addEventListener('keydown',e=>{
5906
- const inForm=/^(INPUT|SELECT|TEXTAREA)$/.test((document.activeElement||{}).tagName);
6491
+ // #planTrigger is named explicitly because it USED to be covered for free: the plan switcher was a
6492
+ // <select>, so focusing it matched the tag test and suppressed every !inForm shortcut below. It is now a
6493
+ // themed combobox on a <button> (see the .plan-* CSS for why), and without this line focusing it would
6494
+ // start letting Delete, Alt+Z and the rest fire against the canvas underneath — a regression the theming
6495
+ // fix would otherwise have smuggled in. The keys the combobox itself handles never reach here at all;
6496
+ // its own keydown stops them.
6497
+ const _ae=document.activeElement||{};
6498
+ const inForm=/^(INPUT|SELECT|TEXTAREA)$/.test(_ae.tagName)||_ae.id==='planTrigger';
5907
6499
  if(dimEdit){if(e.key==='Escape'){e.preventDefault();closeDimEdit();}return;} // F8 popup is modal — suppress every editor/tool shortcut (incl. Ctrl+Z under the popup). Its own input/buttons handle their keys and stopPropagation, so they never reach here (Codex R2 #8).
5908
6500
  // A live drag-out to Tekla owns Escape: the 3D view cancels the gesture on its own handler (this one
5909
6501
  // runs first). Without this, Escape would fall through to the deselect below and clear the very
@@ -6149,7 +6741,100 @@ document.getElementById('cpLevelB').onclick=()=>openLevelModal('copy');
6149
6741
  // fetches the SAME scene the bake uses (/api/contract/:id/scene) so 2D and 3D show one contract. ---
6150
6742
  // Coped beams (auto, clash-driven) — cache the cut labels per member as the scene is fetched so the
6151
6743
  // member Inspector can show a read-only "Cope (auto)" note (a coped beam otherwise looks like an error).
6152
- let copesByMember={}, partsById={};
6744
+ let copesByMember={}, partsById={}, connectionDiagnostics=[], connectionDiagnosticsStatus='pending', connectionDiagnosticsSeq=0, connectionDiagnosticsTimer=null, connectionPreviewJointByEnd=new WeakMap(), shownConnectionDiagnosticSignatures=new Set();
6745
+ const connectionDiagnosticSignature=d=>[d.jointId,d.code,d.severity,d.field||'',d.authored==null?'':d.authored,d.built==null?'':d.built,d.supportId||''].join('|');
6746
+ function announceConnectionTruth(message,busy){
6747
+ const p=document.getElementById('panel'),s=document.getElementById('connectionTruthStatus');
6748
+ if(p){if(busy)p.setAttribute('aria-busy','true');else p.removeAttribute('aria-busy');}
6749
+ if(s){s.setAttribute('role','status');s.setAttribute('aria-live','polite');s.setAttribute('aria-atomic','true');s.textContent=message||'';}
6750
+ }
6751
+ function connectionRefusalCopy(d,m){
6752
+ const support=d.supportId||'the named support',main=d.mainId||m.id,profile=d.profile||m.profile||'This profile';
6753
+ if(d.code==='closed-section-unsupported'){
6754
+ return d.kind==='brace-gusset'
6755
+ ? {head:'Not built · This gusset does not support closed sections',detail:profile+' needs a slotted-tube or other welded detail; this through-bolted detail created no geometry.'}
6756
+ : {head:'Not built · This shear plate does not support closed sections',detail:profile+' needs a compatible welded detail; this through-bolted detail created no geometry.'};
6757
+ }
6758
+ const byCode={
6759
+ 'named-support-out-of-reach':{head:'Not built · Named support is out of reach',detail:main+' does not meet '+support+'. No gusset or brace trim was created.'},
6760
+ 'main-axis-unusable':{head:'Not built · Member direction cannot be resolved',detail:main+' has no usable plan run for this connection. No geometry was created.'},
6761
+ 'main-not-brace':{head:'Not built · This detail requires a brace',detail:main+' is not classified as a brace. No gusset or member trim was created.'},
6762
+ 'main-geometry-unusable':{head:'Not built · Brace geometry is incomplete',detail:main+' has no usable body for this connection. No gusset or member trim was created.'},
6763
+ 'named-support-missing':{head:'Not built · Named support is missing',detail:main+' names '+support+', but that member is not in the model. No gusset or brace trim was created.'},
6764
+ 'named-support-is-brace':{head:'Not built · Named support is another brace',detail:support+' cannot support this gusset. No gusset or brace trim was created.'},
6765
+ 'named-support-unusable':{head:'Not built · Named support has no usable body',detail:support+' cannot support this gusset. No gusset or brace trim was created.'},
6766
+ 'brace-axis-unusable':{head:'Not built · Brace direction cannot be resolved',detail:main+' has no usable plan run for a vertical gusset. No geometry or trim was created.'},
6767
+ 'brace-slope-unsupported':{head:'Not built · This gusset requires a level brace',detail:main+' needs a connection aligned to its slope; this vertical detail created no geometry or trim.'},
6768
+ 'support-not-found':{head:'Not built · No support meets this brace end',detail:'No support face could be proved for '+main+'. No gusset or brace trim was created.'},
6769
+ 'setback-unprovable':{head:'Not built · Brace setback cannot be proved',detail:'The support face and '+main+' do not define a safe setback. No gusset or brace trim was created.'},
6770
+ 'trim-exceeds-member':{head:'Not built · The required trim is too long',detail:main+' cannot safely give up enough length for this gusset. No geometry or trim was created.'},
6771
+ 'bearing-face-unresolved':{head:'Not built · Bearing face cannot be resolved',detail:profile+' has no provable face for this through-bolted detail. No geometry or trim was created.'},
6772
+ 'bolt-region-too-small':{head:'Not built · The bolt group does not fit',detail:'The authored plate cannot hold the required bolt group and edge distances. No geometry or trim was created.'}
6773
+ };
6774
+ return byCode[d.code]||{head:'Not built · Connection was refused',detail:'The connection engine refused '+(d.jointId||'this joint')+' ('+(d.code||'unknown reason')+'). No geometry or member trim was created.'};
6775
+ }
6776
+ function updateConnectionDiagnostics(raw,announce=true){
6777
+ const unique=[],seen=new Set();
6778
+ for(const d of (Array.isArray(raw)?raw:[])){if(!d||typeof d!=='object'||!d.jointId||!d.code)continue;const sig=connectionDiagnosticSignature(d);if(seen.has(sig))continue;seen.add(sig);unique.push(d);}
6779
+ for(const sig of [...shownConnectionDiagnosticSignatures])if(!seen.has(sig))shownConnectionDiagnosticSignatures.delete(sig);
6780
+ const fresh=unique.filter(d=>!shownConnectionDiagnosticSignatures.has(connectionDiagnosticSignature(d)));
6781
+ connectionDiagnostics=unique;connectionDiagnosticsStatus='ready';announceConnectionTruth('Connection build status checked.',false);
6782
+ for(const d of fresh)shownConnectionDiagnosticSignatures.add(connectionDiagnosticSignature(d));
6783
+ if(announce&&fresh.length){
6784
+ const refused=fresh.filter(d=>d.severity==='error').length,adjusted=fresh.filter(d=>d.code==='bolt-gauge-adjusted').length;
6785
+ const bits=[];if(refused)bits.push(refused+' connection'+(refused>1?'s':'')+' not built');if(adjusted)bits.push(adjusted+' built with an adjusted bolt gauge');
6786
+ toast(bits.join(' · ')+' — see the member inspector.');
6787
+ }
6788
+ return {count:fresh.length,refused:fresh.filter(d=>d.severity==='error').length,adjusted:fresh.filter(d=>d.code==='bolt-gauge-adjusted').length};
6789
+ }
6790
+ function applyConnectionBakeTruth(j,announce=true){
6791
+ const fresh=updateConnectionDiagnostics(j&&j.diagnostics,false),sk=Array.isArray(j&&j.skipped)?j.skipped:[];
6792
+ const diagnosed=new Set(connectionDiagnostics.map(d=>d.jointId));
6793
+ const legacy=sk.filter(s=>String(s).startsWith('joint:')&&!diagnosed.has(String(s).slice(6))).length;
6794
+ if(sk.length)console.warn('3D bake skipped '+sk.length+' item(s):',sk);
6795
+ if(announce&&(fresh.count||legacy)){
6796
+ const bits=[];
6797
+ if(fresh.refused)bits.push(fresh.refused+' connection'+(fresh.refused>1?'s':'')+' not built');
6798
+ if(fresh.adjusted)bits.push(fresh.adjusted+' built with an adjusted bolt gauge');
6799
+ if(legacy)bits.push(legacy+' connection'+(legacy>1?'s':'')+' not shown in 3D');
6800
+ toast(bits.join(' · ')+' — '+(legacy?'see the member inspector and console.':'see the member inspector.'));
6801
+ }
6802
+ }
6803
+ async function fetchScenePayload(contract=C){
6804
+ const r=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+'/scene'+PROJECT_QS,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({contract})});
6805
+ const j=await r.json();if(!j.ok)throw new Error(j.error||'scene render failed');return j;
6806
+ }
6807
+ function connectionTruthRequest(){
6808
+ const contract=JSON.parse(JSON.stringify(C)),previewByEnd=new WeakMap();
6809
+ if(!Array.isArray(contract.joints))contract.joints=[];
6810
+ const ids=new Set(contract.joints.map(j=>j&&j.id).filter(Boolean));let n=0;
6811
+ for(const m of allMembers()){
6812
+ if(!m)continue;
6813
+ const ends=m&&m.role==='column'?[{o:m.col,which:'col'}]:[{o:m&&m.ends&&m.ends[0],which:0},{o:m&&m.ends&&m.ends[1],which:1}];
6814
+ for(const t of ends){
6815
+ if(!t.o||(!t.o.detail&&!t.o.conn)||jointAtEnd(m.id,t.which))continue;
6816
+ const r=resolveDetail(m,t.which);if(!r.ok)continue;
6817
+ let id;do{id='preview-connection-'+(++n);}while(ids.has(id));ids.add(id);
6818
+ const joint={id,kind:r.kind,main:m.id,at:jointAtFor(t.which),params:Object.assign({},r.params),source:'preview',conn:r.rowId};
6819
+ if(r.kind==='shear-plate'&&t.which!=='col'){const sup=spInferSupport(m,t.which);joint.secondaries=sup?[sup.id]:[];}
6820
+ contract.joints.push(joint);previewByEnd.set(t.o,id);
6821
+ }
6822
+ }
6823
+ return {contract,previewByEnd,count:n};
6824
+ }
6825
+ function invalidateConnectionDiagnostics(immediate=false){
6826
+ const seq=++connectionDiagnosticsSeq,truth=connectionTruthRequest();
6827
+ if(connectionDiagnosticsTimer){clearTimeout(connectionDiagnosticsTimer);connectionDiagnosticsTimer=null;}
6828
+ connectionPreviewJointByEnd=truth.previewByEnd;
6829
+ if((!Array.isArray(C&&C.joints)||!C.joints.length)&&!truth.count){connectionDiagnostics=[];connectionDiagnosticsStatus='ready';announceConnectionTruth('',false);return;}
6830
+ connectionDiagnostics=[];connectionDiagnosticsStatus='pending';
6831
+ announceConnectionTruth('Checking connection build status.',true);
6832
+ connectionDiagnosticsTimer=setTimeout(async()=>{
6833
+ connectionDiagnosticsTimer=null;
6834
+ try{const j=await fetchScenePayload(truth.contract);if(seq!==connectionDiagnosticsSeq)return;applyConnectionBakeTruth(j,true);panel();}
6835
+ catch(e){if(seq!==connectionDiagnosticsSeq)return;connectionDiagnostics=[];connectionDiagnosticsStatus='unavailable';announceConnectionTruth('Connection build status unavailable. Use Check again to retry.',false);panel();console.warn('Connection build status unavailable:',(e&&e.message)||e);}
6836
+ },immediate?0:150);
6837
+ }
6153
6838
 
6154
6839
  // --- Send the selection to Tekla (Ctrl+Shift-drag it out of the 3D view, or ⋯ → Session). The
6155
6840
  // server bakes just these members as native parts in the OPEN model, at their real model
@@ -6371,19 +7056,21 @@ const view3dApi={
6371
7056
  // PROJECT_QS is threaded so the server can resolve this project's activation grant — without it a
6372
7057
  // steel.model/v2 draft posts app-scoped, no grant resolves, and the render is refused as "not
6373
7058
  // activated" for a project that IS activated (P7d). Harmless for v1, which needs no grant.
6374
- fetchScene:async()=>{const r=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+'/scene'+PROJECT_QS,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({contract:C})});const j=await r.json();if(!j.ok)throw new Error(j.error||'scene render failed');
7059
+ fetchScene:async()=>{const j=await fetchScenePayload();
6375
7060
  // The bake reports everything it could NOT emit in `skipped[]`, and we used to discard it entirely — so a
6376
7061
  // connection the engine refused (e.g. a shear plate whose main became a brace) vanished from 3D silently.
6377
7062
  // Always log the full list. TOAST only for `joint:<id>` entries: a refused connection is unambiguous and
6378
- // always surprising. Member skips are NOT toasted — the bake legitimately drops RFI members (no size) and
6379
- // zero-height foundation columns, so the count is dominated by expected drops and a toast would nag on
6380
- // every 3D open. Telling a degenerate brace apart from those needs skip REASONS from the server; until
6381
- // contract-to-scene returns them, the console is the honest channel. (silent-failure review)
6382
- {const sk=Array.isArray(j.skipped)?j.skipped:[];
6383
- if(sk.length){
6384
- const jn=sk.filter(s=>String(s).startsWith('joint:')).length;
6385
- console.warn('3D bake skipped '+sk.length+' item(s):',sk);
6386
- if(jn)toast(jn+' connection'+(jn>1?'s':'')+' not shown in 3D — see the console');}}const cm={},pb={};const sc=j.scene||{};sc.elements=Array.isArray(sc.elements)?sc.elements:[];for(const el of sc.elements){if(!el)continue;if(el.id)pb[el.id]=el;if(el.kind==='cut'&&el.member){(cm[el.member]||(cm[el.member]=[])).push((el.meta&&el.meta.label)||'Cope');}}
7063
+ // always surprising. Member skips are NOT toasted — the bake legitimately drops RFI members (no size),
7064
+ // so the count is dominated by expected drops and a toast would nag on every 3D open. Telling a
7065
+ // degenerate member apart from those needs skip REASONS from the server; until contract-to-scene
7066
+ // returns them, the console is the honest channel. (silent-failure review)
7067
+ //
7068
+ // "and zero-height foundation columns" USED TO BE IN THAT LIST and no longer belongs: on v2 migration
7069
+ // keeps every footprint marker out of `members[]` entirely, and the bake's height-only rule is gone, so
7070
+ // v2 drops no foundation columns at all. What remains on v2 is (a) no resolvable section and (b) a
7071
+ // genuinely zero-LENGTH member — and (b) is never expected, so the "would nag" argument no longer
7072
+ // covers it. Widening `skipped` to carry reasons is the fix; it is not this change.
7073
+ const cm={},pb={};const sc=j.scene||{};sc.elements=Array.isArray(sc.elements)?sc.elements:[];for(const el of sc.elements){if(!el)continue;if(el.id)pb[el.id]=el;if(el.kind==='cut'&&el.member){(cm[el.member]||(cm[el.member]=[])).push((el.meta&&el.meta.label)||'Cope');}}
6387
7074
  // Slice 4: append placed detail images as CLIENT-SIDE scene elements (kind:'image'), resolving each
6388
7075
  // placement's detailName → custom_details base64 in the browser. The server's contract-to-scene never
6389
7076
  // emits these, so they stay out of the reconstructed scene / IFC / Tekla export and the baked lock.
@@ -6646,7 +7333,7 @@ const view3dApi={
6646
7333
  // Re-extrude the 3D model after a structural edit (keeps the camera where it is). Selection-only
6647
7334
  // changes go through render()'s setSelection — only geometry mutations need a rebuild.
6648
7335
  let pendingConnSel=null; // a just-baked connection whose parts exist only AFTER the next rebuild → select the whole thing there (a recognized base-plate import, whose part ids aren't known ahead of expansion)
6649
- function sync3D(){if(view3d&&view3dReady&&window.Steel3DView){window.Steel3DView.rebuild(false).then(()=>{
7336
+ function sync3D(){invalidateConnectionDiagnostics();panel();if(view3d&&view3dReady&&window.Steel3DView){window.Steel3DView.rebuild(false).then(()=>{
6650
7337
  if(pendingConnSel&&window.Steel3DView.selectWholeConn){const c=pendingConnSel;pendingConnSel=null;window.Steel3DView.selectWholeConn(c);} // whole-connection select (envelope + "Parametric — editable" inspector), same as a 3D click
6651
7338
  else window.Steel3DView.setSelection(selIds);
6652
7339
  build3DLegend();panel();}).catch(()=>{pendingConnSel=null;});}} // rebuild also refreshes the legend (an edit may add/remove a profile) + re-renders the inspector so a selection of just-created parts (e.g. a placed custom connection) resolves against the freshly-fetched partsById, not the pre-rebuild stale copy
@@ -7818,7 +8505,12 @@ function applyViewState(on){ // flip the toggle + swap the canvases (
7818
8505
  document.getElementById('stage').style.display=on?'none':'';
7819
8506
  document.getElementById('stage3d').style.display=on?'block':'none';
7820
8507
  document.getElementById('zoombar').style.display=on?'none':''; // zoom slider is 2D-only
7821
- document.getElementById('planSel').style.display=on?'none':''; // plan selector is 2D-only (3D shows the whole model)
8508
+ // Plan switcher is 2D-only (3D shows the whole model). Hidden by `display`, not the `hidden` attribute:
8509
+ // .plan-combo carries an author `display:inline-flex`, which beats the UA's [hidden] rule by ORIGIN, so
8510
+ // `hidden = true` would quietly do nothing here. closePlans() first — a popover left open across the
8511
+ // switch is hidden with its wrapper, but would strand `aria-expanded=true` and the .open caret behind it.
8512
+ if(on)closePlans(false);
8513
+ document.getElementById('planCombo').style.display=on?'none':'';
7822
8514
  document.getElementById('m3dBar').style.display=on?'flex':'none';
7823
8515
  document.body.classList.toggle('v3d',on); // 3D-only chrome (e.g. ⋯ → Detailing → Insert detail) keys off this
7824
8516
  document.getElementById('dimB').style.display=on?'none':''; // 2D Dimension button — 2D only
@@ -8983,7 +9675,7 @@ function setPlanV2(i){
8983
9675
  dimStyleMode=false;csaxisMode=false;setCsMode();snapOnlyClear2d();closeSnapMenu();disarmCm();
8984
9676
  render();fitToWindow();
8985
9677
  refresh3DGrid();
8986
- const ps=document.getElementById('planSel');if(ps)ps.value=String(i);}
9678
+ syncPlanSwitcher(i);}
8987
9679
  // --- multi-plan: switch between all steel plan views ---
8988
9680
  function setPlan(i){C.active=i;P=C.plans[i];
8989
9681
  if(MODEL_RO){setPlanV2(i);return;} // v2: no 2D setup at all — see setPlanV2 for why that is the whole branch
@@ -9027,11 +9719,264 @@ function setPlan(i){C.active=i;P=C.plans[i];
9027
9719
  if(!P.autofilled){autofillTOS();P.autofilled=true;}
9028
9720
  document.getElementById('detailsBtn').textContent='Details ('+detTexts().length+')'; // counts what the modal LISTS — openDetails() sets the same label from the same list, and the two disagreed on a callouts-only sheet (#397)
9029
9721
  setMode();render();fitToWindow();
9030
- refresh3DGrid(); // the grid is PER-PLAN, so a plan switch must re-render it in 3D too. The plan <select> is 2D-only, but the Confidence report's Locate buttons switch sheets from 3D — without this the 3D view keeps drawing the OLD sheet's grid while snapping reads the NEW sheet's (found by Codex on the grid-level review)
9031
- const ps=document.getElementById('planSel');if(ps)ps.value=String(i);}
9032
- const planSel=document.getElementById('planSel');
9033
- planSel.innerHTML=C.plans.map((p,i)=>`<option value="${i}">${esc(p.sheet)} · ${esc(p.title)}</option>`).join('');
9034
- planSel.onchange=e=>setPlan(+e.target.value);
9722
+ refresh3DGrid(); // the grid is PER-PLAN, so a plan switch must re-render it in 3D too. The plan switcher is 2D-only, but the Confidence report's Locate buttons switch sheets from 3D — without this the 3D view keeps drawing the OLD sheet's grid while snapping reads the NEW sheet's (found by Codex on the grid-level review)
9723
+ syncPlanSwitcher(i);}
9724
+ // ── plan switcher ───────────────────────────────────────────────────────────────────────────────
9725
+ //
9726
+ // A themed combobox rather than a <select>: see the .plan-* CSS for why the native control cannot be made
9727
+ // to obey the dark baseline. Same control, and the same reasoning, as web/steel-filter.html's sheet
9728
+ // switcher; both descend from the app-wide .wf-combo (web/index.html + web/aware.js).
9729
+ //
9730
+ // Not ported from that shared control (a closed list, so the divergences are worth naming):
9731
+ // · no SEARCH field — the workflow and project pickers face dozens of rows, a plan set faces a handful,
9732
+ // and an input that grabs focus on open would put a control with nothing to do between the user and
9733
+ // the list. With no input to host them, focus stays on the trigger and the TRIGGER carries
9734
+ // aria-activedescendant — the WAI-ARIA select-only shape, hence role=combobox on a <button>.
9735
+ // · no per-row action or dirty-dot chrome — a plan is a place to look, not an entity you own.
9736
+ // · opens ON the current row, where the shared control opens with no highlight and merely scrolls the
9737
+ // selection into view. A short list has somewhere obvious to start.
9738
+ const planCombo=document.getElementById('planCombo');
9739
+ const planTrigger=document.getElementById('planTrigger');
9740
+ const planTriggerLabel=document.getElementById('planTriggerLabel');
9741
+ const planPopover=document.getElementById('planPopover');
9742
+ // planListEl, not planList: `planList` is already taken further up (modelReadsV1's per-plan DATA getter,
9743
+ // which returns members/scale/TOS). Two same-named consts meaning entirely different things in one file is
9744
+ // a trap even though the scopes don't collide today. (Code review.)
9745
+ const planListEl=document.getElementById('planList');
9746
+ let planHi=-1; // index of the keyboard-highlighted row while open; -1 = none
9747
+ let planType=''; // typeahead buffer, reset on open and after a pause
9748
+ let planTypeAt=0; // …and when the last key of it arrived
9749
+
9750
+ /** One plan's one-line label — "S-201 · Second Floor Framing".
9751
+ *
9752
+ * ONE rule, because the page needs this string in three places now (the closed trigger, the open option
9753
+ * row, the Move/Copy level modal) and it already held two that DISAGREED: the modal has always written
9754
+ * `sheet + (title ? ' · ' + title : '')`, while the <select> this replaced wrote an unconditional
9755
+ * `sheet · title` — so a plan with no title read "S-201 · undefined" in the header and "S-201" in the
9756
+ * modal. Both now call here.
9757
+ *
9758
+ * Deliberately NOT steel-filter-core.js's sheetLabel(), which is the same rule for the sibling page: the
9759
+ * editor does not otherwise depend on the filter pre-stage, and importing its pure core for one string
9760
+ * would couple the model editor to that pipeline while STILL leaving this page holding two rules unless
9761
+ * the modal changed too. Converging in-page is the win; the two are siblings, and a change to what a
9762
+ * sheet is called belongs in both.
9763
+ *
9764
+ * Every part of a plan's identity is drawing-derived, so nothing here may assume a string: an object
9765
+ * reaching String() paints the literal "[object Object]" into the header, which is why null/undefined
9766
+ * and anything typeof 'object' drop to the "Plan N" fallback rather than being coerced. */
9767
+ function planLabel(pl,i){
9768
+ const p=(pl&&typeof pl==='object')?pl:{};
9769
+ const text=v=>(v==null||typeof v==='object')?'':String(v).trim();
9770
+ const n=Number.isFinite(Number(i))?Math.max(0,Math.trunc(Number(i))):0; // 1-based for humans; the floor keeps "Plan 0" out
9771
+ const name=text(p.sheet)||('Plan '+(n+1));
9772
+ const title=text(p.title);
9773
+ return title?(name+' · '+title):name;
9774
+ }
9775
+
9776
+ const planOptions=()=>[...planListEl.children];
9777
+
9778
+ function buildPlanSwitcher(){
9779
+ // Rebuilding under an open popover would strand planHi and aria-activedescendant on rows that no longer
9780
+ // exist. Unreachable today (this runs once, from main()) — but it is one call, and it stops the trap the
9781
+ // day the plan list re-renders in place.
9782
+ closePlans(false);
9783
+ planListEl.replaceChildren();
9784
+ (C.plans||[]).forEach((pl,i)=>{
9785
+ // A <div role=option>, NOT a <button> — see the .plan-option rule for why focus has to stay on the trigger.
9786
+ const o=document.createElement('div');
9787
+ o.className='plan-option';
9788
+ o.id='plan-opt-'+i; // the target aria-activedescendant points at
9789
+ o.setAttribute('role','option');
9790
+ o.setAttribute('aria-selected','false');
9791
+ o.dataset.i=String(i);
9792
+ o.textContent=planLabel(pl,i); // textContent, never innerHTML: a sheet name and title are read off the drawing, so they are data
9793
+ // The tooltip is attached at OPEN time, not here — see tipClippedRows().
9794
+ o.addEventListener('click',()=>pickPlan(i));
9795
+ planListEl.appendChild(o);
9796
+ });
9797
+ }
9798
+
9799
+ /** Point the control at whatever plan is now active — called from BOTH setPlan and setPlanV2, so a
9800
+ * programmatic switch (the Confidence report's Locate buttons, a restored C.active) moves the label and
9801
+ * the selected-row accent exactly as a click does. Replaces the two `planSel.value = String(i)` writebacks. */
9802
+ function syncPlanSwitcher(i){
9803
+ // An ABSENT plan gets an empty label, not planLabel's fallback. The fallback exists for a plan that is
9804
+ // THERE but whose sheet/title is junk — "Plan 3" is the honest name for it. With no plan at all it would
9805
+ // instead assert a plan that does not exist: a v2 document may legitimately carry `plans: []` (boot only
9806
+ // checks Array.isArray), and the header would then read "Plan 1" over a switcher holding zero rows. The
9807
+ // <select> rendered blank there — uninformative, but it did not invent an identity.
9808
+ const pl=(C.plans||[])[i];
9809
+ const label=pl?planLabel(pl,i):'';
9810
+ planTriggerLabel.textContent=label;
9811
+ // The trigger ellipsizes at 320px too, so the closed state needs the same escape hatch as the rows. This
9812
+ // REPLACES the static "Switch plan view" tip: the caret and the listbox already say what the control
9813
+ // does, and the accessible name (aria-labelledby) still carries the purpose — so the one thing the
9814
+ // tooltip can add that nothing else does is the part that got clipped.
9815
+ if(label)planTrigger.setAttribute('data-tip',label);
9816
+ for(const o of planOptions()){
9817
+ // Number(i), not a bare `i`: the index is not guaranteed to be a number here. C.active is copied
9818
+ // straight out of a localStorage draft (applyDraftFields, `d.active != null` and nothing else), so a
9819
+ // hand-edited or corrupt row can carry the STRING "1". Everything else tolerates that — P=C.plans["1"]
9820
+ // resolves, the label is right — but a strict === against a number would then match no row at all,
9821
+ // leaving every option aria-selected=false and no accent: a listbox that announces no selection while
9822
+ // the header shows a plan. (Found by the silent-failure review.)
9823
+ const on=Number(o.dataset.i)===Number(i);
9824
+ o.classList.toggle('selected',on);
9825
+ o.setAttribute('aria-selected',on?'true':'false');
9826
+ }
9827
+ // A switch that lands while the popover is OPEN must move the highlight with it, or the highlight and
9828
+ // aria-activedescendant stay on the previously-active row and the next Enter re-picks the row the user
9829
+ // just navigated away from.
9830
+ if(!planPopover.hidden)highlightPlan(i);
9831
+ }
9832
+
9833
+ function highlightPlan(i){
9834
+ const opts=planOptions();if(!opts.length)return;
9835
+ planHi=Math.max(0,Math.min(opts.length-1,i)); // clamp, so Up on the first row parks rather than wrapping
9836
+ opts.forEach((o,n)=>o.classList.toggle('active',n===planHi));
9837
+ const hi=opts[planHi];
9838
+ hi.scrollIntoView({block:'nearest'});
9839
+ planTrigger.setAttribute('aria-activedescendant',hi.id); // DOM focus never leaves the trigger, so the highlighted row is announced through it
9840
+ }
9841
+
9842
+ /** Commit a pick. The ORDER is the whole point and was measured, not assumed: setPlan() reaches
9843
+ * setMode() → cmHudClose(), which calls stage.focus(). So closing with focusTrigger=true and THEN
9844
+ * switching plans lands the user on the canvas — focus silently leaves the control they were operating.
9845
+ * Harmless-looking on a mouse click; on the keyboard it strands them, since the <select> this replaced
9846
+ * kept focus after a pick for free. Close quietly, switch, then take focus back last. */
9847
+ function pickPlan(i){
9848
+ closePlans(false);
9849
+ setPlan(i);
9850
+ planTrigger.focus();
9851
+ }
9852
+
9853
+ /** Give a row a tooltip ONLY when its label is actually clipped.
9854
+ *
9855
+ * A row ellipsizes inside the 400px panel, so a long "S-202 · Second Floor Framing At El 118'-6"" loses
9856
+ * its tail with no way to read the rest — the <select> this replaced had no such problem, since its OS
9857
+ * panel auto-sized to its content, so leaving that unaddressed would regress what a user can read.
9858
+ *
9859
+ * But setting it unconditionally (as the sibling page does, calling it "harmlessly redundant when the
9860
+ * label fits") is NOT harmless here: the shared tooltip renders at z-index 80, above this z-30 popover,
9861
+ * and positions itself just under the hovered element — so scanning a list of short names pops a panel
9862
+ * repeating text the user can already read, on top of the next row and a half. (Code review.)
9863
+ *
9864
+ * Measured at open rather than at build, because scrollWidth/clientWidth are both 0 while the popover is
9865
+ * `hidden` — computing it in buildPlanSwitcher would mark every row as clipped. */
9866
+ function tipClippedRows(){
9867
+ for(const o of planOptions()){
9868
+ if(o.scrollWidth>o.clientWidth)o.setAttribute('data-tip',o.textContent);
9869
+ else o.removeAttribute('data-tip');
9870
+ }
9871
+ }
9872
+
9873
+ function plansOpen(){return !planPopover.hidden;}
9874
+ function openPlans(){
9875
+ if(plansOpen())return;
9876
+ planPopover.hidden=false;
9877
+ planTrigger.classList.add('open');
9878
+ planTrigger.setAttribute('aria-expanded','true');
9879
+ tipClippedRows(); // now that the rows have layout, tooltip only the ones that actually lost their tail
9880
+ // Open ON the current plan, so ↓ steps to the next one rather than to the top — and take "current" from
9881
+ // the row the control is SHOWING, not from C.active. The two can disagree: "View my edits instead"
9882
+ // (showStaleDraftBanner) calls applyDraftFields, which writes C.active and then only render()s — it never
9883
+ // reaches setPlan, so P, the canvas and this control all stay on the old plan while C.active moves. That
9884
+ // desync predates this control and is not ours to fix here, but reading C.active would make this the
9885
+ // first thing to RENDER the contradiction: one row accented as selected, a different row highlighted,
9886
+ // and Enter committing the one the header never named. Opening on the selected row keeps the control
9887
+ // self-consistent whatever C.active says. (Found by the silent-failure review.)
9888
+ const cur=planOptions().findIndex(o=>o.classList.contains('selected'));
9889
+ highlightPlan(cur>=0?cur:0);
9890
+ planType=''; // a fresh open starts a fresh typeahead
9891
+ }
9892
+ function closePlans(focusTrigger){
9893
+ if(!plansOpen())return;
9894
+ planPopover.hidden=true;
9895
+ planTrigger.classList.remove('open');
9896
+ planTrigger.setAttribute('aria-expanded','false');
9897
+ planTrigger.removeAttribute('aria-activedescendant'); // must not survive the close — it would name a row nothing is showing
9898
+ planOptions().forEach(o=>o.classList.remove('active'));
9899
+ planHi=-1;
9900
+ if(focusTrigger)planTrigger.focus();
9901
+ }
9902
+
9903
+ planTrigger.addEventListener('click',()=>{plansOpen()?closePlans(false):openPlans();});
9904
+ planTrigger.addEventListener('keydown',e=>{
9905
+ // stopPropagation on every key this control handles, so none of them ALSO reaches the global editor
9906
+ // shortcuts below — the idle Space/Enter "repeat the last command" handler would otherwise fire while
9907
+ // the user is opening the list. The page's own convention for a control that owns its keys: the F12 RFI
9908
+ // pill and the F8 dimension-edit popup both stopPropagation for exactly this reason. The keys this does
9909
+ // NOT handle are covered instead by naming the trigger in that handler's `inForm` guard, which the old
9910
+ // <select> satisfied for free by being a SELECT.
9911
+ // (Deliberately no line numbers here. The three this comment first carried were all wrong — they were
9912
+ // written against pre-insertion positions and drifted further as the file grew — and a reference that
9913
+ // lands on unrelated code is worse than none, because it invites a reader to trust it. Name the thing.)
9914
+ if(!plansOpen()){
9915
+ if(e.key==='ArrowDown'||e.key==='ArrowUp'||e.key==='Enter'||e.key===' '){e.preventDefault();e.stopPropagation();openPlans();}
9916
+ return;
9917
+ }
9918
+ if(e.key==='ArrowDown'){e.preventDefault();e.stopPropagation();highlightPlan(planHi+1);}
9919
+ else if(e.key==='ArrowUp'){e.preventDefault();e.stopPropagation();highlightPlan(planHi-1);}
9920
+ else if(e.key==='Home'){e.preventDefault();e.stopPropagation();highlightPlan(0);}
9921
+ else if(e.key==='End'){e.preventDefault();e.stopPropagation();highlightPlan(planOptions().length-1);}
9922
+ else if(e.key==='Enter'||e.key===' '){e.preventDefault();e.stopPropagation();const i=planHi;if(i>=0)pickPlan(i);else closePlans(true);}
9923
+ else if(e.key==='Escape'){e.preventDefault();e.stopPropagation();closePlans(true);}
9924
+ // Tab must still MOVE — close on the way out rather than swallowing it, or the popover is left orphaned
9925
+ // over a control the user has already left.
9926
+ else if(e.key==='Tab'){closePlans(false);}
9927
+ // TYPEAHEAD — type "S-2" or "sec" to jump to a row. The <select> this replaced had it natively, and all
9928
+ // three reviewers flagged its loss independently; WAI-ARIA's select-only combobox lists it as expected
9929
+ // behaviour. It also failed as a pure SILENT no-op: an unhandled printable key fell through to the global
9930
+ // handler, where the new #planTrigger `inForm` clause suppressed it — swallowed at both ends, with
9931
+ // nothing happening and nothing logged.
9932
+ // Deliberately open-state only. A closed native <select> also types to CHANGE the value outright; doing
9933
+ // that here would commit a plan switch (a full re-render) per keystroke, which is a much larger surface
9934
+ // than the key was worth. Closed, the trigger still opens on Enter/Space/arrows.
9935
+ else if(e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey){
9936
+ e.preventDefault();e.stopPropagation();
9937
+ const now=Date.now();
9938
+ if(now-planTypeAt>500)planType=''; // a pause starts a new search rather than extending a stale one
9939
+ planTypeAt=now;planType+=e.key.toLowerCase();
9940
+ const opts=planOptions();
9941
+ // Search from the row AFTER the highlight when the same single char is repeated, so pressing "s" walks
9942
+ // the S-sheets instead of pinning the first one — the native behaviour this restores.
9943
+ const rot=(planType.length===1&&planHi>=0)?planHi+1:0;
9944
+ const hit=opts.map((o,n)=>opts[(rot+n)%opts.length]).find(o=>o.textContent.toLowerCase().startsWith(planType));
9945
+ if(hit)highlightPlan(opts.indexOf(hit));
9946
+ }
9947
+ });
9948
+ // An open popover closes on a press anywhere outside it.
9949
+ //
9950
+ // pointerdown, not click, so the popover goes at the START of a press: this canvas begins a pan, a
9951
+ // marquee, a dimension placement or an add-member click on pointerdown, and a click-based listener would
9952
+ // leave the panel hanging over the drawing for the whole gesture.
9953
+ //
9954
+ // Capture phase is declared defence rather than a fact about today's code — nothing on the canvas path
9955
+ // calls stopPropagation() — but it costs nothing and means a future one can never strand this open.
9956
+ document.addEventListener('pointerdown',e=>{
9957
+ if(!plansOpen()||planCombo.contains(e.target))return;
9958
+ closePlans(false);
9959
+ // …and the dismissing press does ONLY that. Without this it closes the popover and then continues into
9960
+ // the canvas, which acts on pointerdown: the press that dismissed the list would also start a pan or a
9961
+ // marquee, place a dimension point, or drop an add-member click onto the drawing. The <select> this
9962
+ // replaced could not do that — its OS popup owned the pointer, so the dismissing press never reached the
9963
+ // page at all. (Codex review.)
9964
+ // stopPropagation, NOT stopImmediatePropagation: other document-capture listeners are unrelated and must
9965
+ // still run. And deliberately not preventDefault — the canvas commands are pointerdown-driven and are
9966
+ // already stopped here, while buttons act on `click`, which this does not touch. So a press on another
9967
+ // header control dismisses the list AND works, instead of costing the user a dead first click. That is a
9968
+ // considered divergence from the native popup, which swallowed both.
9969
+ e.stopPropagation();
9970
+ },true);
9971
+ // An open popover also closes when focus leaves the DOCUMENT, which the press listener above cannot see.
9972
+ // This editor runs INSIDE AN IFRAME in the workspaces shell (see wsShell() below), so a click anywhere in
9973
+ // the shell around it — the chat, the project rail, History — never enters this document; nor does
9974
+ // Alt+Tab, nor opening devtools. Without this the panel hangs over the canvas with aria-expanded=true and
9975
+ // the caret still flipped until the user happens to press inside the editor again. The <select> got this
9976
+ // for free: an OS popup closes on window blur. (Found by the silent-failure review.)
9977
+ addEventListener('blur',()=>closePlans(false));
9978
+ document.addEventListener('visibilitychange',()=>{if(document.hidden)closePlans(false);});
9979
+ buildPlanSwitcher();
9035
9980
  // "Revert to an earlier version…" — a POINTER into the workspaces shell's History step, never a
9036
9981
  // revert of its own. The project version ledger already restores any version as a NEW version
9037
9982
  // (audited, itself undoable, and it re-locks exports); this item only makes it reachable from
@@ -9074,7 +10019,12 @@ if(canWriteModel()){
9074
10019
  for(const _p of (C.plans||[]))sanitizePlanGrid(_p);
9075
10020
  }
9076
10021
  setPlan(C.active==null?0:C.active);
10022
+ invalidateConnectionDiagnostics(); // 2D asks the same server bake as 3D before it promises a connection will build
9077
10023
  applyReadOnlyChrome(); // …after setPlan, so the controls it touches are the ones the render just wired
10024
+ // ONE WORD FOR BOTH MODES. This said "Grid restored ✓" on a read-only document, on the premise that the
10025
+ // grid is the only thing such a draft can hold — which review disproved (see RO_DRAFT_KEYS: the overlay
10026
+ // swatches, the confidence target and the palette are ungated too). A chip that names the grid over a
10027
+ // restored confidence target is a smaller lie than the banner's was, but it is the same lie.
9078
10028
  setSaved(_restored?'ok':'idle', _restored?'Restored ✓':'Auto-save on');
9079
10029
  try{stage.focus({preventScroll:true});}catch(_){} // grab keyboard focus on open so shortcuts work before the first click
9080
10030
  // --- ?selftest=1 — cheap regression guard for the only non-trivial new math (local frame). Logs PASS/FAIL