@floless/app 0.134.1 → 0.134.3

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.
@@ -41,7 +41,6 @@
41
41
  it into --shadow-lg would de-sync this one from them */
42
42
  --backdrop:rgba(2,8,23,.62);
43
43
  --brand-wash:rgba(59,130,246,.16); /* a selected row */
44
- --brand-wash-soft:rgba(59,130,246,.12); /* a "you just navigated here" flash */
45
44
  --brand-wash-faint:rgba(59,130,246,.08);/* an open accordion header */
46
45
  --brand-wash-strong:rgba(59,130,246,.28);/* the .mck switch track when on */
47
46
  --ink-max:#fff; /* the hover "brighten" one step past --text */
@@ -83,7 +82,7 @@
83
82
  --shadow-xl:0 24px 70px rgba(15,23,42,.20);
84
83
  --shadow-tip:0 8px 22px rgba(15,23,42,.14);
85
84
  --backdrop:rgba(15,23,42,.42);
86
- --brand-wash:rgba(37,99,235,.14);--brand-wash-soft:rgba(37,99,235,.10);
85
+ --brand-wash:rgba(37,99,235,.14);
87
86
  --brand-wash-faint:rgba(37,99,235,.07);--brand-wash-strong:rgba(37,99,235,.22);
88
87
  --ink-max:#0f172a;
89
88
  /* The ink/fill/edge swap named in :root, applied: ink is the -700/-800 stop (AA on --panel), the fill
@@ -148,7 +147,7 @@
148
147
  --shadow-sm:0 2px 8px rgba(0,0,0,.45);--shadow-float:0 4px 14px rgba(0,0,0,.45);
149
148
  --shadow-modal:0 20px 60px rgba(0,0,0,.6);--shadow-xl:0 24px 70px rgba(0,0,0,.7);
150
149
  --shadow-tip:0 8px 22px rgba(0,0,0,.5);--backdrop:rgba(2,8,23,.62);
151
- --brand-wash:rgba(59,130,246,.16);--brand-wash-soft:rgba(59,130,246,.12);
150
+ --brand-wash:rgba(59,130,246,.16);
152
151
  --brand-wash-faint:rgba(59,130,246,.08);--brand-wash-strong:rgba(59,130,246,.28);
153
152
  --ink-max:#fff;
154
153
  --warn:#fbbf24;--warn-soft:#fcd34d;--warn-bg:#713f12;--warn-edge:#713f12;
@@ -471,6 +470,7 @@
471
470
  .sw{width:12px;height:12px;border-radius:2px;display:inline-block}
472
471
  .swc{width:14px;height:14px;padding:0;border:1px solid var(--ctrl-border);border-radius:3px;cursor:pointer;background:none;flex:none;-webkit-appearance:none;appearance:none}
473
472
  .swc::-webkit-color-swatch-wrapper{padding:0} .swc::-webkit-color-swatch{border:none;border-radius:2px}
473
+ .swc::-moz-color-swatch{border:none;border-radius:2px}
474
474
  .hint{color:var(--mut);font-size:12px;line-height:1.5}
475
475
  .seg2{display:flex;border:1px solid var(--line);border-radius:6px;overflow:hidden;height:28px;margin-top:8px}
476
476
  .seg2 button{flex:1;border:0;border-radius:0;background:transparent;color:var(--mut)}
@@ -512,11 +512,13 @@
512
512
  input:disabled{opacity:.55;cursor:default}
513
513
  .badge{display:block;background:var(--brand);color:var(--brand-ink);text-align:center;font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:5px;border-radius:6px;margin-bottom:10px}
514
514
  .pick{color:var(--brand)!important}
515
- rect.lblhot{cursor:pointer;fill:rgba(251,191,36,.10);stroke:#fbbf24;stroke-width:1;stroke-dasharray:3 3;vector-effect:non-scaling-stroke}
516
- rect.lblhot:hover{fill:rgba(251,191,36,.28)}
515
+ rect.lblhot{cursor:pointer;fill:rgba(251,191,36,.10);stroke:#fbbf24;stroke-width:1;stroke-dasharray:3 3;vector-effect:non-scaling-stroke}
516
+ rect.lblhot:hover{fill:rgba(251,191,36,.28)}
517
+ rect.lblhot:focus-visible{outline:2px solid var(--brand);outline-offset:2px;stroke-width:2;fill:rgba(251,191,36,.28);filter:drop-shadow(0 0 4px var(--brand))}
517
518
  rect.dethot{cursor:pointer;fill:rgba(168,85,247,.16);stroke:#a855f7;stroke-width:1;stroke-dasharray:3 3;vector-effect:non-scaling-stroke}
518
519
  rect.dethot:hover{fill:rgba(168,85,247,.34)}
519
520
  text.dettx{fill:#ddd6fe;font:bold 11px system-ui;text-anchor:middle;pointer-events:none}
521
+ text.lbltx{fill:#fde68a;font:bold 11px system-ui;text-anchor:middle;pointer-events:none}
520
522
  /* clickable callout bubbles (Workstream B): section/elevation/detail-ref + plain details — navigable cross-references drawn on the plan in select mode. Existing palette only: purple #a855f7 (details), cyan #22d3ee (sections/elevations); solid vs dashed separates the kinds. */
521
523
  g.cohot{cursor:pointer}
522
524
  circle.cobub{stroke-width:1.5;vector-effect:non-scaling-stroke;opacity:.55}
@@ -525,9 +527,10 @@
525
527
  circle.cobub.k-detailref,circle.cobub.k-elev{stroke-dasharray:3 3}
526
528
  g.cohot:hover circle.cobub{opacity:1;stroke-width:2;filter:drop-shadow(0 0 4px currentColor)}
527
529
  text.cotx{fill:#e2e8f0;font:bold 11px system-ui;text-anchor:middle;dominant-baseline:central;pointer-events:none;opacity:.6}
528
- /* Vectorized PDF overlay — crisp, snappable drawing linework rendered from the filter vectors, NOT a
529
- blurry raster (only vector PDFs; scanned sheets still fall back to the raster image). */
530
+ /* Reviewed source-PDF context under crisp, snappable Filter vectors. The raster is deliberately quiet
531
+ and inert: it restores native printed callouts without becoming a second geometry authority. */
530
532
  rect.pdfsheet{fill:#f8fafc}
533
+ image.pdfref{opacity:.42;pointer-events:none}
531
534
  g.pdfvec{pointer-events:none}
532
535
  g.pdfvec path{fill:none;stroke:#334155;stroke-width:.7;vector-effect:non-scaling-stroke;opacity:.82;stroke-linecap:round;stroke-linejoin:round}
533
536
  g.pdfvec circle{fill:none;stroke:#334155;stroke-width:.7;vector-effect:non-scaling-stroke;opacity:.55}
@@ -710,6 +713,35 @@
710
713
  #moreMenu .mhint{color:var(--mut);font-size:11px;line-height:1.4;padding:4px 12px 6px;max-width:230px;white-space:normal}
711
714
  #rfiStat{cursor:pointer;text-decoration:underline dotted} #rfiStat:hover b{color:var(--ink-max)}
712
715
  #endsStat{color:var(--mut)} #endsStat.has{color:var(--warn)} #endsStat.has b{color:var(--warn)}
716
+ /* Connection review, in the header — the ONLY place the state is visible in Plan (2D), where the
717
+ inspector, the breadcrumb and the 3D scene all do not exist.
718
+ `#reviewStat` goes amber when non-zero, exactly like #endsStat. `#untrackedStat` has NO `.has` rule
719
+ and stays --mut at any count, deliberately: every pre-existing connection is untracked, and a legacy
720
+ model lighting up amber on open would teach people to ignore the colour. */
721
+ #reviewStat{color:var(--mut)} #reviewStat.has{color:var(--warn)} #reviewStat.has b{color:var(--warn)}
722
+ #untrackedStat{color:var(--mut)}
723
+ #reviewUnavailStat{color:var(--cyan)}
724
+ /* These two are real buttons rather than the plain <span>s the older stats use, because they open a
725
+ list and must be reachable by keyboard. The reset keeps them visually identical to their siblings. */
726
+ button.stat{background:none;border:0;padding:0;font:inherit;color:inherit;cursor:pointer}
727
+ button.stat:focus-visible{outline:2px solid var(--brand);outline-offset:2px;border-radius:3px}
728
+ /* The list itself borrows #selFly's recipe wholesale — same popover, new id. A capped, scrollable
729
+ popover hanging off a stat is not the "full review list panel" the design ruled out. */
730
+ #reviewFly{position:fixed;z-index:46;min-width:250px;background:var(--panel);border:1px solid var(--line);border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,.55);padding:6px;display:none}
731
+ #reviewFly.open{display:block}
732
+ #reviewFly .fhdr{display:flex;align-items:baseline;justify-content:space-between;padding:4px 8px 6px}
733
+ #reviewFly .fhdr b{font-size:12px;font-weight:600;letter-spacing:.02em}
734
+ #reviewFly .fhdr .cnt{font-size:11px;color:var(--mut);font-variant-numeric:tabular-nums}
735
+ #reviewFly .frow{display:flex;align-items:center;gap:9px;width:100%;padding:6px 8px;border:0;border-radius:6px;background:transparent;color:var(--text);cursor:pointer;font:13px system-ui;text-align:left}
736
+ #reviewFly .frow:hover{background:rgba(148,163,184,.12)}
737
+ #reviewFly .frow:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
738
+ #reviewFly .frow .nm{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
739
+ #reviewFly .frow .sub{font-size:11px;color:var(--mut);flex:none}
740
+ #reviewFly .fempty{padding:6px 8px;color:var(--mut);font-size:12px}
741
+ #reviewFly .flist{max-height:230px;overflow:auto;scrollbar-width:thin;scrollbar-color:var(--scroll) transparent}
742
+ #reviewFly .flist::-webkit-scrollbar{width:8px}
743
+ #reviewFly .flist::-webkit-scrollbar-thumb{background:var(--scroll);border-radius:4px}
744
+ #reviewFly .flist::-webkit-scrollbar-track{background:transparent}
713
745
  body.member-end-review #stage{cursor:default}
714
746
  #panel .mer-head{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:4px}
715
747
  #panel .mer-title{font-size:10px;font-weight:700;line-height:1.35;letter-spacing:.08em;text-transform:uppercase;color:var(--text)}
@@ -798,6 +830,15 @@
798
830
  input[type=number] rule near the top, which is what the three origin fields were missing. Leaving
799
831
  the per-id copy here would just be the template for the next field to be patched one at a time. */
800
832
  #confTarget{width:54px;text-align:right;padding:4px 6px;font:13px system-ui}
833
+ #confTargetState{font-size:11px;color:var(--mut);white-space:nowrap}
834
+ .read-diag{margin:12px 0 0;padding:8px 10px;border:1px solid var(--warn-edge);border-radius:6px;color:var(--warn);background:var(--warn-bg);font-size:12px}
835
+ .read-group{margin:8px 0;padding:8px 10px;border:1px solid var(--line);border-radius:6px;background:var(--bg)}
836
+ .read-group-head{display:flex;gap:7px;align-items:center;flex-wrap:wrap;margin-bottom:6px;color:var(--text);font-size:12px}
837
+ .read-field{display:grid;grid-template-columns:minmax(120px,1fr) minmax(150px,2fr) auto;gap:10px;padding:4px 0;border-top:1px solid var(--line);font-size:12px;align-items:baseline}
838
+ .read-field:first-of-type{border-top:0}.read-field .read-value{overflow-wrap:anywhere}.read-field .read-pct{font-variant-numeric:tabular-nums;white-space:nowrap}
839
+ .read-notes{margin:12px 0 0;padding:10px 12px;border:1px solid var(--line);border-radius:6px;background:var(--sunken)}
840
+ .read-notes h3{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);margin:0 0 5px}.read-notes ul{margin:0 0 10px;padding-left:18px}.read-notes ul:last-child{margin-bottom:0}.read-notes li{font-size:12px;line-height:1.45;overflow-wrap:anywhere}
841
+ #svg:focus-visible{outline:2px solid var(--brand);outline-offset:-2px}
801
842
  .mgrid{padding:14px;overflow:auto;display:grid;grid-template-columns:repeat(auto-fill,minmax(168px,1fr));gap:12px}
802
843
  .dcard{border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--bg)}
803
844
  .dcard .dprev{height:120px;display:flex;align-items:center;justify-content:center;background:var(--sunken);color:var(--mut);font-size:11px;text-align:center;padding:8px;line-height:1.4}
@@ -1785,9 +1826,15 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1785
1826
  <span class=stat id=rfiStat data-tip="Click to list members with an unresolved size (RFI — Request for Information)">RFI <b id=rc>0</b></span>
1786
1827
  <span class=stat id=dupStat data-tip="Overlapping/duplicate members (same geometry)">Dup <b id=dpc>0</b></span>
1787
1828
  <span class=stat id=endsStat data-tip="Member ends that may stop at a support face instead of its centerline.">Ends <b id=endsCount>—</b></span>
1829
+ <button data-command-id="steel.review-list" class=stat id=reviewStat data-tip="Imported connections whose steel has moved since they were placed — click to list them" aria-haspopup="true" aria-expanded="false" aria-controls="reviewFly" hidden>Review <b id=reviewCount>0</b></button>
1830
+ <button data-command-id="steel.untracked-list" class=stat id=untrackedStat data-tip="Imported connections that are not being watched for moved steel — click to list them" aria-haspopup="true" aria-expanded="false" aria-controls="reviewFly" hidden>Untracked <b id=untrackedCount>0</b></button>
1831
+ <!-- Hidden at zero rather than shown as "0", matching the readouts above: a readout that is wrong is
1832
+ worse than one that is absent. But BOTH hidden while the server could not derive the state would
1833
+ read as "all clear", so that one condition gets its own neutral marker instead of silence. -->
1834
+ <span class=stat id=reviewUnavailStat data-tip="The server could not check connections for moved steel this time" hidden>Review check unavailable</span>
1788
1835
  <span class=stat id=csStat data-tip="Coordinate system — Global by default. Set a local frame from the ⋯ menu for skewed framing.">Axes <b>Global</b></span>
1789
1836
  <span class=stat id=snapStat style="display:none" data-tip="Snap restricted for this operation — right-click the canvas to change; click here or press Esc to clear">Snap <b>—</b></span>
1790
- <span class=stat id=confStat data-tip="Confidence report — AI-read score vs. target. Click to review element evidence." style="display:none">Confidence <b id=confPct>—</b><span id=confTgt></span></span>
1837
+ <button data-command-id="steel.confidence-report" class=stat id=confStat data-tip="Confidence report — review recorded drawing evidence." style="display:none" aria-haspopup=dialog aria-controls=confModal><span id=confLabel>Confidence</span> <b id=confPct>—</b><span id=confTgt></span></button>
1791
1838
  <span class=stat id=saveStat data-tip="Edits auto-save in this browser (localStorage)">Saved</span>
1792
1839
  <span class=stat id=srcStat style="display:none"></span><span style="flex:1"></span>
1793
1840
  <button data-command-id="steel.undo" id=undoB data-tip="Undo (Ctrl+Z)">↶</button>
@@ -1845,9 +1892,9 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1845
1892
  to 16 — then jumped on the first drag. One authority on what a legal size is. -->
1846
1893
  <div class=mrow><span class=mlbl>Grid label size</span><input data-command-id="steel.grid-label-size" id=gridLabelSize type=range min=14 max=48 step=1 aria-label="Grid label size in pixels" data-tip="How big the grid bubbles are drawn, in both 2D and 3D. Like a CAD drawing they hold this size on screen however far you zoom in or out."><span id=gridLabelSizeV class=mval>26 px</span></div>
1847
1894
  <button data-command-id="steel.show-member-length" id=lenToggleB class=dtog role=menuitemcheckbox aria-checked=false data-tip="Show the length of each selected member in 2D and 3D"><span class=mck aria-hidden=true></span>Member length</button>
1848
- <button data-command-id="steel.position-gizmo" id=posGizmoToggleB class=dtog role=menuitemcheckbox aria-checked=false data-tip="Show a drag handle on the selected member for setting its Profile Position right in the 3D view"><span class=mck aria-hidden=true></span>Position handle</button>
1895
+ <button data-command-id="steel.position-gizmo" id=posGizmoToggleB class=dtog role=menuitemcheckbox aria-checked=false data-tip="Show a drag handle on the selected member for moving it and rolling its section right in the 3D view"><span class=mck aria-hidden=true></span>Position handle</button>
1849
1896
  <button data-command-id="steel.show-property-labels" id=plToggleB class=dtog role=menuitemcheckbox aria-checked=true data-tip="Show or hide property labels in the 2D plan (the property selection is shared with 3D — this hides them here only)"><span class=mck aria-hidden=true></span>Property labels</button>
1850
- <button data-command-id="steel.show-reference-sheet" id=refToggleB class=dtog role=menuitemcheckbox aria-checked=true data-tip="Show or hide the traced reference sheet (the PDF/SVG drawing under the model). Hidden, it also stops contributing snap points."><span class=mck aria-hidden=true></span>Reference sheet</button>
1897
+ <button data-command-id="steel.show-reference-sheet" id=refToggleB class=dtog role=menuitemcheckbox aria-checked=true data-tip="Show or hide the source drawing under the model. The source image is visual context; traced lines—not the raster—provide snap points."><span class=mck aria-hidden=true></span>Reference sheet</button>
1851
1898
  <button data-command-id="steel.grid" id=gridEditB data-tip="Grid lines — a plan reference with structural bay spacings (n*d repeats a bay). Shows in 2D and 3D; drawing and drags snap to its lines and intersections.">Grid lines…</button>
1852
1899
  <button data-command-id="steel.dimension-style" id=dimStyleB data-tip="Dimension style — end marks, label position and label background. Sets the defaults every dimension follows unless you give it its own style.">Dimension style…</button>
1853
1900
  </div>
@@ -1906,7 +1953,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
1906
1953
  ResizeObserver(canvas.parentElement) keep working untouched — they now measure #pane3d. -->
1907
1954
  <div id=stagewrap>
1908
1955
  <div id=pane2d>
1909
- <div id=stage><svg id=svg></svg></div>
1956
+ <div id=stage><svg id=svg tabindex=-1 aria-label="2D model plan"></svg></div>
1910
1957
  <div id=zoombar>
1911
1958
  <button data-command-id="steel.zoom" id=zOut data-tip="Zoom out">−</button>
1912
1959
  <input data-command-id="steel.zoom" aria-label="Zoom level" id=zRange type=range min=10 max=400 step=1 value=100>
@@ -2063,6 +2110,12 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2063
2110
  </div>
2064
2111
  </div>
2065
2112
  <div id=selFly role=menu aria-label="Selectable types"></div>
2113
+ <!-- The connection-review list. One popover serves BOTH stats; its header says which list is open. -->
2114
+ <div id=reviewFly role=menu aria-label="Connections needing attention">
2115
+ <div class=fhdr><b id=reviewFlyTitle>Needs review</b><span class=cnt id=reviewFlyCount></span></div>
2116
+ <div class=flist id=reviewFlyList></div>
2117
+ <div class=fempty id=reviewFlyMore hidden></div>
2118
+ </div>
2066
2119
  </div>
2067
2120
  <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>
2068
2121
  <span id=connectionTruthStatus class=sr-only role=status aria-live=polite aria-atomic=true></span>
@@ -2251,8 +2304,8 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2251
2304
  </div>
2252
2305
  </div>
2253
2306
  </div></div>
2254
- <div id=confModal><div class=mbackdrop id=confBackdrop></div>
2255
- <div class=mpanel><div class=mhead><b>Confidence report</b><label class=conf-tgt data-tip="Confidence target for this read (%). Overrides the workflow default; saved with the contract.">Target <input data-command-id="steel.confidence-target" id=confTarget type=number min=0 max=100 step=1> %</label><button data-command-id="steel.dialog-close#the confidence report" id=confClose>✕</button></div>
2307
+ <div id=confModal role=dialog aria-modal=true aria-labelledby=confTitle><div class=mbackdrop id=confBackdrop></div>
2308
+ <div class=mpanel><div class=mhead><b id=confTitle>Confidence report</b><label class=conf-tgt data-tip="Confidence target for this read (%). Overrides the workflow default; saved with the contract.">Target <input data-command-id="steel.confidence-target" id=confTarget type=number min=0 max=100 step=1 placeholder="—"> % <span id=confTargetState></span></label><button data-command-id="steel.dialog-close#the confidence report" id=confClose aria-label="Close confidence report">✕</button></div>
2256
2309
  <div id=confCats class=conf-cats></div>
2257
2310
  <div id=confFilter class=conf-filter></div>
2258
2311
  <div id=confBody class=conf-body></div></div></div>
@@ -2440,8 +2493,9 @@ let CatalogPicker = null; // steel-catalog-picker.js — provider-neutral Profil
2440
2493
  let SteelCore = null; // steel-3d-core.js module namespace — boot() awaits its dynamic import before main() so the classic script can call its pure helpers (sanitizeDims3d) at load
2441
2494
  let ViewGen = null; // steel-view-generation.js pure F11 helpers — loaded before saved views are sanitised
2442
2495
  let ModelCmd = null; // steel-model-commands.js — the model boundary's WRITE half (unit 5, P3a); the read half is steel-model-adapter.js
2443
- let V2Projection = null, V2Commands = null, V2Validation = null, FilterCore = null;
2496
+ let V2Projection = null, V2Commands = null, V2Validation = null, FilterCore = null, ProfileColours = null, ReferenceSheet = null, ReadConfidence = null;
2444
2497
  let PlanXf = null; // steel-plan-transform.js — the px↔world registration boundary. Already in the module graph (V2Projection imports it); named here so the classic script can read a sheet's registration angle and fit scale when it draws a rolled section footprint.
2498
+ let ReviewClient = null; // connection-review-client.js — how one observation of the connection review state is ordered against the one on screen, and when a refresh cycle may stop. A module because its totality has to be unit-testable; see its header.
2445
2499
  let V2_SCHEMA = null, V2_SESSION = null, V2_PROJECTION = null;
2446
2500
  let V2_PROJECTIONS = new Map();
2447
2501
  let DetailRefs = null; // steel-detail-refs.js — what detail callouts a plan carries (details[] ∪ callouts[]); the ⌖ pick tool, the Connection-detail combobox and the Details list must all read the SAME answer (#397)
@@ -2497,6 +2551,42 @@ const DEFAULT_PAL=['#60a5fa','#94a3b8','#f59e0b','#34d399','#f472b6','#a78bfa','
2497
2551
  // wasted traffic and makes the pill flicker in a way that reads as broken rather than informative.
2498
2552
  let serverEtag = null;
2499
2553
  let serverRevision = -1;
2554
+ /**
2555
+ * How many times the VISIBLE document has changed. Not a save counter — `saveSeq` already is one, and
2556
+ * that is exactly why it cannot serve here: `flushContract` bumps `saveSeq` as well as `scheduleSave`
2557
+ * does, so it counts save INTENTS, and a flush would invalidate its own capture.
2558
+ *
2559
+ * WHAT IT IS FOR. `If-Match` proves which generation the SERVER had, never which one the user LOOKED AT.
2560
+ * `flushContract` adopts its reply's tag unconditionally, so an edit landing mid-flight leaves
2561
+ * `serverEtag` naming generation A while the document on screen is B — the precondition passes and its
2562
+ * meaning is false, recording a human acceptance of a state nobody reviewed. That is the precise failure
2563
+ * the review feature exists to prevent, arriving through the one verb that grants authority.
2564
+ *
2565
+ * IT IS ONE OF THREE TRIPWIRES, DELIBERATELY, because a counter is only as total as the list of places
2566
+ * it is bumped from — and the first draft of that list was wrong. It had `scheduleSave` and
2567
+ * `installMemberEndContract` and argued a visible change that schedules no save is already a data-loss
2568
+ * bug. `applyRevalidation` falsifies it: it deletes joints from `C.joints`, calls `persist()` and
2569
+ * deliberately NOT `scheduleSave()` (the durable copy already holds the change), and it runs inside
2570
+ * `flushContract`'s own success branch — the very window being policed. So sign-off checks all three:
2571
+ *
2572
+ * serverEtag !== the flushed tag → some write LANDED after the flush
2573
+ * saveT !== null → an unsaved USER edit is pending (only scheduleSave sets it)
2574
+ * this counter moved → a server-applied IN-PLACE mutation neither of those can see
2575
+ *
2576
+ * Any one of them refuses. If a fourth in-place applier is ever added and nobody bumps this, the other
2577
+ * two still catch it, which is the property a bare counter could not offer.
2578
+ *
2579
+ * IT DELIBERATELY MOVES FOR EDITS THAT CANNOT AFFECT STEEL — a profile colour, a saved view, a label
2580
+ * toggle. Review raised that as over-refusal, and it is: recolouring a profile while a sign-off is in
2581
+ * flight refuses a physically valid review. Kept anyway, because the two errors are not symmetric. A
2582
+ * false refusal costs one more click and says why. A missed refusal records a human accepting steel
2583
+ * nobody looked at, silently, which is the single failure this feature exists to prevent. Narrowing it
2584
+ * would also mean maintaining a list of “geometry-relevant” edits — exactly the enumeration whose
2585
+ * incompleteness produced this three-tripwire design in the first place, and which would go stale with
2586
+ * nothing to notice. The window is one round trip wide.
2587
+ */
2588
+ let modelEditGeneration = 0;
2589
+ const bumpModelEditGeneration = () => { modelEditGeneration++; };
2500
2590
  let contractEventEpoch = 0;
2501
2591
  let contractEventReady = false;
2502
2592
  let contractEventWatermark = null;
@@ -2506,13 +2596,38 @@ const CONTRACT_EVENT_BOOTSTRAP_ATTEMPTS = 3;
2506
2596
  const CONTRACT_EVENT_BOOTSTRAP_RETRY_MS = 250;
2507
2597
 
2508
2598
  function contractEventMatches(m){return m&&typeof m==='object'&&m.type==='contract-changed'&&m.appId===APP_ID&&((m.project||'')===PROJECT);}
2599
+ /* ── The connection review watermark ───────────────────────────────────────────────────────────────
2600
+ A SECOND, independent watermark beside serverRevision, because a sign-off deliberately moves neither
2601
+ the contract ETag nor the store revision (design §6.3) — so every ordering rule above, which keys on
2602
+ storeRevision and suppresses anything that did not increase, would discard it as a duplicate.
2603
+
2604
+ What is ordered is the PAIR (storeRevision, reviewRevision). The revision alone cannot do it: it moves
2605
+ only when the sidecar rows change, while the summary is derived from live geometry, so an ordinary
2606
+ member move changes what the summary says without moving the revision at all. The comparison itself
2607
+ lives in connection-review-client.js so its totality can be unit-tested — five drafts of this rule had
2608
+ a case fall through during plan review.
2609
+
2610
+ A review frame is a SEPARATE type and takes a SEPARATE buffer slot: contractEventWatermark is keyed on
2611
+ a storeRevision that a review frame does not carry, so one slot would let the two evict each other. */
2612
+ let reviewAt = { storeRevision: -1, reviewRevision: -1 }; // the pair currently on screen
2613
+ let reviewSummary = null; // the last installed summary, or null before boot
2614
+ let reviewUnavailable = false; // the server could not derive it — a presentation, never silence
2615
+ let reviewEventWatermark = null; // a review frame that arrived before the tab was ready
2616
+ let reviewCycle = null; // the in-flight refresh: { bounds, attempts, late }
2617
+ function reviewEventMatches(m){return m&&typeof m==='object'&&m.type==='review-changed'&&m.appId===APP_ID&&((m.project||'')===PROJECT);}
2618
+ function reviewFrameOrderable(m){return Number.isSafeInteger(m.reviewRevision)&&m.reviewRevision>=0;}
2509
2619
  function editorHasUnsavedWork(){const sv=document.getElementById('saveStat');return !!sv&&(sv.classList.contains('dirty')||sv.classList.contains('err')||sv.classList.contains('conflict'));}
2510
2620
  function parkDraftForExternalChange(){const parked=flushLocalDraft?flushLocalDraft():false;if(!parked)console.warn('steel-editor: pending edits could not be parked before an external model update');return parked;}
2511
2621
  function handleContractChanged(m){
2512
2622
  if(!contractEventMatches(m))return;
2513
2623
  if(!Number.isSafeInteger(m.storeRevision)||m.storeRevision<0||typeof m.etag!=='string'){console.warn('steel-editor: ignored an unorderable contract event');return;}
2514
2624
  const own=m.mutationId?ownWrites.indexOf(m.mutationId):-1;
2515
- if(own>=0){const newest=own===ownWrites.length-1;ownWrites.splice(0,own+1);if(newest&&m.storeRevision>serverRevision){const prev=serverEtag;serverEtag=m.etag;serverRevision=m.storeRevision;restampDraftBase(prev,m.etag);}return;}
2625
+ /* THE TAB'S OWN WRITE. It is suppressed for contract purposes — but the review summary still has to be
2626
+ re-read, and this is the trigger that makes the feature work at all: an ordinary member move can flip
2627
+ a connection from clean to needs-review WITHOUT touching the sidecar, so no `review-changed` is
2628
+ emitted and reviewRevision does not move. Nothing else would ever ask. In Plan view, where the 3D
2629
+ scene does not exist, this is the only path that keeps the count honest. */
2630
+ if(own>=0){const newest=own===ownWrites.length-1;ownWrites.splice(0,own+1);if(newest&&m.storeRevision>serverRevision){const prev=serverEtag;serverEtag=m.etag;serverRevision=m.storeRevision;restampDraftBase(prev,m.etag);}reviewRefreshForOwnWrite();return;}
2516
2631
  if(m.storeRevision<=serverRevision)return;
2517
2632
  if(window.invalidateMemberEndReview)window.invalidateMemberEndReview('The model changed — check member ends again.');
2518
2633
  if(editorHasUnsavedWork()){
@@ -2526,6 +2641,120 @@ function bufferContractEvent(m){
2526
2641
  if(!contractEventWatermark||m.storeRevision>=contractEventWatermark.storeRevision)contractEventWatermark=m;
2527
2642
  }
2528
2643
  function drainContractEvents(epoch){if(epoch!==contractEventEpoch||!contractEventReady)return;const row=contractEventWatermark;contractEventWatermark=null;if(row)handleContractChanged(row);}
2644
+ /* The review buffer's own drain. A SIBLING of drainContractEvents rather than a line inside it: the two
2645
+ watermarks are independent all the way down, and keeping the drains separate means neither function
2646
+ carries the other's state — which is also what lets each be lifted and tested in isolation. */
2647
+ function drainReviewEvents(epoch){if(epoch!==contractEventEpoch||!contractEventReady)return;const row=reviewEventWatermark;reviewEventWatermark=null;if(row)handleReviewChanged(row);}
2648
+ /* Install one observation, or say why not. The ONLY place the watermark moves.
2649
+ Returns 'installed' | 'recovered' | 'noop' | 'unavailable' | 'rejected' | 'stale', or the shape name
2650
+ ('dominated' | 'incomparable') when the caller must reconcile. */
2651
+ function installReviewSummary(summary,storeRevision,epoch){
2652
+ if(epoch!==contractEventEpoch)return 'stale';
2653
+ /* `signedOff` is checked like its two siblings, and its absence is a REJECTION rather than a shrug.
2654
+ The server always sends it — the unavailable path sends an empty one deliberately — so a summary
2655
+ without it is a protocol violation. Accepting one looked harmless and was not: `reviewSignedOff`
2656
+ would answer false for everything, so every ✓ chip and every Reopen button would vanish model-wide,
2657
+ silently, and the user who had just signed off would be shown "Imported geometry" instead. Rejecting
2658
+ routes it to the reconciliation path, which says "unavailable" out loud. (Found by review.) */
2659
+ if(!ReviewClient||!summary||!Array.isArray(summary.needsReview)||!Array.isArray(summary.untracked)
2660
+ ||!Array.isArray(summary.signedOff)
2661
+ ||!Number.isSafeInteger(storeRevision)||!Number.isSafeInteger(summary.reviewRevision)){
2662
+ console.warn('steel-editor: ignored an unorderable review summary');return 'rejected';}
2663
+ /* -1 is the server saying it could not derive this AT ALL (§2.3). A presentation, never a generation:
2664
+ it must not become the watermark, and the last valid pair is retained so a later EQUAL snapshot —
2665
+ the only thing a transient failure can be followed by — can clear it again. */
2666
+ if(ReviewClient.isUnavailableRevision(summary.reviewRevision)){reviewUnavailable=true;repaintReviewSurface();return 'unavailable';}
2667
+ const incoming={storeRevision,reviewRevision:summary.reviewRevision};
2668
+ const shape=ReviewClient.classifyReviewPair(incoming,reviewAt);
2669
+ if(shape==='advancing'){reviewAt=incoming;reviewSummary=summary;reviewUnavailable=false;repaintReviewSurface();return 'installed';}
2670
+ if(shape==='equal'){
2671
+ // Nothing to do in normal state — and an ordinary reconnect returns exactly this, so treating it as a
2672
+ // failure would paint "unavailable" over a perfectly healthy tab. While unavailable it is the recovery.
2673
+ if(reviewUnavailable){reviewUnavailable=false;reviewSummary=summary;repaintReviewSurface();return 'recovered';}
2674
+ return 'noop';}
2675
+ return shape;}
2676
+ /* One named seam for "a snapshot arrived — take its review half", used by boot and by reconnect. It
2677
+ exists as its own function so the reconnect reader keeps ONE review dependency rather than three, and
2678
+ so the project-scoped guard lives in exactly one place. */
2679
+ function installReviewFromSnapshot(snap,epoch){if(PROJECT&&snap&&snap.review)installReviewSummary(snap.review,snap.storeRevision,epoch);}
2680
+ const reviewBoundsMax=(a,b)=>({storeRevision:Math.max(a.storeRevision,b.storeRevision),reviewRevision:Math.max(a.reviewRevision,b.reviewRevision)});
2681
+ /* Ask for a refresh. Coalesced, and the latch is COMPOSITE: a trigger is recorded as lower bounds on
2682
+ BOTH axes, because the review verbs move reviewRevision while leaving storeRevision alone — a
2683
+ store-only latch would drop a sign-off that arrived mid-fetch and never look again. */
2684
+ function markReviewDirty(bounds){
2685
+ if(!PROJECT||!ReviewClient)return;
2686
+ if(!reviewCycle){reviewCycle={bounds,attempts:0,finalStarted:false,late:null};runReviewCycle(contractEventEpoch);return;}
2687
+ /* A trigger that lands after the final attempt has ALREADY started reading belongs to nobody: this
2688
+ cycle cannot go back and look again, and clearing it with this cycle would lose the event outright.
2689
+ It is handed to a fresh cycle instead. Termination comes from the attempt counter; not losing an
2690
+ update comes from this hand-off. Neither mechanism is asked to do both. */
2691
+ if(reviewCycle.finalStarted){reviewCycle.late=reviewCycle.late?reviewBoundsMax(reviewCycle.late,bounds):bounds;return;}
2692
+ reviewCycle.bounds=reviewBoundsMax(reviewCycle.bounds,bounds);}
2693
+ /* The whole loop is wrapped, because a throw ANYWHERE in it would leave reviewCycle non-null forever —
2694
+ after which markReviewDirty only ever merges bounds into a cycle that will never run again, and the
2695
+ counts stop updating for the rest of the session with nothing on screen to say so. That silent freeze
2696
+ is exactly what the unavailable presentation exists to replace, so a throw ends in unavailable. */
2697
+ async function runReviewCycle(epoch){
2698
+ try{await runReviewCycleInner(epoch);}
2699
+ catch(e){
2700
+ /* Release FIRST and unconditionally: if this handler throws, a still-held reviewCycle would freeze the
2701
+ surface for the session, which is the exact failure the wrapper exists to prevent. */
2702
+ reviewCycle=null;
2703
+ reviewUnavailable=true;
2704
+ /* And repaint in its own try, because the painter is a plausible source of the original throw — calling
2705
+ it again here would rethrow out of the catch and undo everything above. */
2706
+ try{repaintReviewSurface();}catch(_){/* the state is set; the surface will catch up on the next paint */}
2707
+ try{console.warn('steel-editor: the review refresh cycle failed',e&&e.message?e.message:e);}catch(_){}
2708
+ }}
2709
+ async function runReviewCycleInner(epoch){
2710
+ const cycle=reviewCycle;
2711
+ /* Clear the slot ONLY if it is still ours. An obsolete run that nulls the global unconditionally
2712
+ would delete a newer cycle that had already replaced it — and that newer cycle's bounds go with it,
2713
+ which is the lost update the hand-off exists to prevent. */
2714
+ const release=()=>{if(reviewCycle===cycle)reviewCycle=null;};
2715
+ const finish=()=>{release();const late=cycle.late;if(late)markReviewDirty(late);};
2716
+ while(cycle===reviewCycle){
2717
+ cycle.attempts++;
2718
+ if(cycle.attempts>=ReviewClient.REVIEW_MAX_ATTEMPTS)cycle.finalStarted=true;
2719
+ let snap=null;
2720
+ try{const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+'/snapshot'+CONTRACT_QS);if(res.ok)snap=await res.json();}
2721
+ catch(e){console.warn('steel-editor: review snapshot failed',e&&e.message?e.message:e);}
2722
+ if(epoch!==contractEventEpoch){release();return;} // a reconnect owns the tab now; it will drain and start its own cycle
2723
+ const outcome=snap?installReviewSummary(snap.review,snap.storeRevision,epoch):'rejected';
2724
+ if(outcome==='stale'){release();return;}
2725
+ // Entering unavailable SETTLES the cycle. Without this the -1 sentinel (which deliberately retains the
2726
+ // watermark) and the bounds check spin against each other forever, hammering a server already failing.
2727
+ if(outcome==='unavailable'){finish();return;}
2728
+ if(outcome==='dominated'||outcome==='incomparable'||outcome==='rejected'){
2729
+ if(!cycle.finalStarted)continue; // exactly one reconciliation…
2730
+ reviewUnavailable=true;repaintReviewSurface();finish();return;} // …then stop, through either door
2731
+ const settle=ReviewClient.settleCycle({installed:reviewAt,bounds:cycle.bounds,attempts:cycle.attempts,arrivedAfterFinalAttempt:cycle.late});
2732
+ if(settle.retry)continue;
2733
+ // Advanced-but-not-far-enough is NOT a success: rendering its number as if it were leaves a confident
2734
+ // stale count that nothing marks and no further trigger is guaranteed to correct.
2735
+ if(settle.state==='unavailable'){reviewUnavailable=true;repaintReviewSurface();}
2736
+ finish();return;}}
2737
+ /* The transport lives out here; the SURFACE lives inside main(), because it needs esc/C/selIds/
2738
+ render()/viewMode — all of which are main()'s closure and are not visible from this scope. main()
2739
+ publishes the real one on window, exactly as it already does for flushContract and
2740
+ invalidateMemberEndReview. Before main() runs there is nothing on screen to repaint, so the
2741
+ no-op is correct rather than merely tolerable. */
2742
+ function repaintReviewSurface(){if(window.renderReviewSurface)window.renderReviewSurface();}
2743
+ /* The own-write trigger. The store advanced, so the DERIVED state may have changed even though the
2744
+ sidecar did not — ask for at least this store revision, and for no less review than already held. */
2745
+ /* NOT gated on reviewSummary. A boot snapshot carrying the -1 sentinel leaves it null, and gating on it
2746
+ there would disable the own-write trigger — the one thing that makes the feature work — for the rest of
2747
+ the session, with the header stuck on "unavailable" and no user action able to retry. The bounds come
2748
+ from serverRevision and reviewAt, both valid before any summary lands. */
2749
+ function reviewRefreshForOwnWrite(){if(PROJECT&&ReviewClient)markReviewDirty({storeRevision:serverRevision,reviewRevision:reviewAt.reviewRevision});}
2750
+ function handleReviewChanged(m){
2751
+ if(!reviewEventMatches(m))return;
2752
+ if(!reviewFrameOrderable(m)){console.warn('steel-editor: ignored an unorderable review event');return;}
2753
+ if(m.reviewRevision<=reviewAt.reviewRevision&&!reviewUnavailable)return; // already seen
2754
+ /* NEVER location.reload() here. That is handleContractChanged's answer to an external GEOMETRY change;
2755
+ applying it to a sign-off would throw away the user's unsaved edits because another tab clicked a
2756
+ button. A review generation moving is not a reason to lose work. */
2757
+ markReviewDirty({storeRevision:reviewAt.storeRevision,reviewRevision:m.reviewRevision});}
2529
2758
  async function rebootstrapContractEvents(epoch,attempt=0){
2530
2759
  if(epoch!==contractEventEpoch)return;contractEventReady=false;
2531
2760
  try{
@@ -2542,7 +2771,10 @@ async function rebootstrapContractEvents(epoch,attempt=0){
2542
2771
  showAiUpdateBanner(parked?'A newer model is available. Your edits are still here. Resolve the model update, then check member ends again.':'Live updates reconnected, but this browser could not save your edits. Copy them out before reloading.',parked?undefined:{noReload:true});
2543
2772
  }else{location.reload();return;}
2544
2773
  }
2545
- if(epoch!==contractEventEpoch)return;contractEventReady=true;drainContractEvents(epoch);
2774
+ // The reconnect snapshot carries the review summary too, and installing it here is what stops a
2775
+ // sign-off that landed while the tab was disconnected from being invisible until an unrelated edit.
2776
+ installReviewFromSnapshot(snap,epoch);
2777
+ if(epoch!==contractEventEpoch)return;contractEventReady=true;drainContractEvents(epoch);drainReviewEvents(epoch);
2546
2778
  }catch(e){
2547
2779
  if(epoch!==contractEventEpoch)return;
2548
2780
  contractEventReady=false;
@@ -2568,7 +2800,14 @@ function startContractEvents(){
2568
2800
  if(!contractBootSnapshotInstalled)return;
2569
2801
  contractEventEpoch++;contractEventReady=false;contractEventWatermark=null;rebootstrapContractEvents(contractEventEpoch);
2570
2802
  };
2571
- source.onmessage=e=>{if(source!==contractEventSource)return;let m;try{m=JSON.parse(e.data);}catch{return;}if(!contractEventMatches(m))return;if(!contractEventReady)bufferContractEvent(m);else handleContractChanged(m);};
2803
+ source.onmessage=e=>{if(source!==contractEventSource)return;let m;try{m=JSON.parse(e.data);}catch{return;}
2804
+ /* Two frame types, two paths, and they must not cross: a review frame carries no storeRevision, so
2805
+ handleContractChanged would reject it as unorderable, and a contract frame carries no
2806
+ reviewRevision. SSE is plain fan-out with no replay buffer, so anything arriving before the tab has
2807
+ installed its first snapshot is buffered — in its OWN slot, since contractEventWatermark is keyed
2808
+ on a storeRevision a review frame does not have. */
2809
+ if(reviewEventMatches(m)){if(!contractEventReady){if(reviewFrameOrderable(m)&&(!reviewEventWatermark||m.reviewRevision>=reviewEventWatermark.reviewRevision))reviewEventWatermark=m;}else handleReviewChanged(m);return;}
2810
+ if(!contractEventMatches(m))return;if(!contractEventReady)bufferContractEvent(m);else handleContractChanged(m);};
2572
2811
  source.onerror=()=>{if(source!==contractEventSource)return;contractEventReady=false;if(source.readyState===EventSource.CLOSED){ownWrites.length=0;console.warn('steel-editor: SSE channel closed — live updates paused');showAiUpdateBanner('Live updates disconnected — reload to resume change detection.');}};
2573
2812
  }catch(e){console.warn('steel-editor: could not open live updates',e&&e.message?e.message:e);}
2574
2813
  }
@@ -2579,7 +2818,55 @@ let conflicted = false;
2579
2818
  // themselves, potentially aborting Approve. `saveSeq` only decides which response owns the pill; it
2580
2819
  // never stopped the overlap. vector-editor already queues; this brings the steel editor in line.
2581
2820
  let writeQueue = Promise.resolve();
2582
- const queueWrite = (fn) => (writeQueue = writeQueue.then(fn, fn));
2821
+ /**
2822
+ * THE WRITE GATE — one transaction's exclusive hold on this tab's contract writes.
2823
+ *
2824
+ * "Place again" has to publish the OLD placement, mark the joint untracked, and only THEN move the
2825
+ * geometry. A debounced autosave scheduled by an earlier edit would otherwise fire in the middle of
2826
+ * that and publish the NEW geometry ahead of the command, which is the torn sequence the whole
2827
+ * transaction exists to prevent (it leaves a row reading CLEAN over the wrong steel — `failClosed`
2828
+ * never fires, because the tear happens before anything stages).
2829
+ *
2830
+ * IT NEEDS AN OWNER-ONLY BYPASS, OR IT DEADLOCKS AGAINST ITSELF. The drain and the fail-closed save are
2831
+ * both writes issued BY the transaction that closed the gate; a gate that simply blocked the queue would
2832
+ * leave each waiting on a gate only it can open. So the gate carries the owning transaction's token and
2833
+ * admits writes bearing it.
2834
+ *
2835
+ * A deferred non-owner write waits OUTSIDE the FIFO and joins it only once the gate opens. That ordering
2836
+ * is load-bearing rather than incidental: parking it IN the queue would put it ahead of the owner's own
2837
+ * drain, so the drain would queue behind the very writes it closed the gate to exclude.
2838
+ *
2839
+ * A LEAKED GATE DISABLES SAVING FOR THE SESSION — worse than the bug it fixes — so its release is
2840
+ * asserted on every path, including throw, and `openWriteGate` is token-checked so a settling
2841
+ * transaction can never clear a gate a newer one installed.
2842
+ */
2843
+ let writeGateToken = null, writeGateOpen = null, writeGateRelease = null;
2844
+ /**
2845
+ * REFUSES to close over a gate that is already held, and that refusal is the mechanism rather than a
2846
+ * caller's manners. Overwriting `writeGateRelease` would strand every write parked on the OLD gate's
2847
+ * promise — permanently, because nothing can resolve a release nobody holds any more. That is the same
2848
+ * "saving is dead for the session" failure the gate exists to avoid, arriving through the gate itself.
2849
+ * Callers read the answer instead of pre-checking `writeGateToken`, so there is one statement of the
2850
+ * rule and no window between the check and the act.
2851
+ */
2852
+ function closeWriteGate(token){
2853
+ if (writeGateToken) return false;
2854
+ writeGateToken = token; writeGateOpen = new Promise((resolve) => { writeGateRelease = resolve; });
2855
+ return true;
2856
+ }
2857
+ function openWriteGate(token){
2858
+ if (writeGateToken !== token) return false; // a newer transaction owns it; clearing here would strand that one
2859
+ writeGateToken = null;
2860
+ const release = writeGateRelease; writeGateRelease = null; writeGateOpen = null;
2861
+ if (release) release();
2862
+ return true;
2863
+ }
2864
+ const queueWrite = (fn, token) => {
2865
+ // Re-entrant on purpose: if a NEW gate closed while this write was parked, it parks again rather than
2866
+ // slipping through. Gates are bounded by one user transaction, so this terminates.
2867
+ if (writeGateToken && token !== writeGateToken) return writeGateOpen.then(() => queueWrite(fn, token));
2868
+ return (writeQueue = writeQueue.then(fn, fn));
2869
+ };
2583
2870
  /**
2584
2871
  * The full-screen "there is nothing to show" state.
2585
2872
  *
@@ -2733,12 +3020,13 @@ async function boot() {
2733
3020
  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; }
2734
3021
  armEarlyViewToggle(); // BEFORE the first await — that is the whole point; see above
2735
3022
  startContractEvents(); // subscribe first; contract events buffer until the atomic snapshot is installed
2736
- [SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf, CatalogPicker] = await Promise.all([
3023
+ [SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf, CatalogPicker, ReviewClient, ProfileColours, ReferenceSheet, ReadConfidence] = await Promise.all([
2737
3024
  import('./steel-3d-core.js'), import('./steel-view-generation.js'), import('./steel-model-commands.js'),
2738
3025
  import('./steel-detail-refs.js'), import('./steel-model-v2-projection.js'),
2739
3026
  import('./steel-model-v2-commands.js'), import('./steel-model-v2-client-validation.js'),
2740
3027
  import('./steel-split-view.js'), import('./steel-filter-core.js'), import('./steel-plan-transform.js'),
2741
- import('./steel-catalog-picker.js'),
3028
+ import('./steel-catalog-picker.js'), import('./connection-review-client.js'), import('./steel-profile-colours.js'),
3029
+ import('./steel-reference-sheet.js'), import('./steel-read-confidence.js'),
2742
3030
  ]);
2743
3031
  const res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + '/snapshot' + CONTRACT_QS);
2744
3032
  // 204 = the project-scoped "nothing stored yet", the quiet twin of the generic 404 below. It carries
@@ -2852,6 +3140,11 @@ async function boot() {
2852
3140
  // land on top of someone else's is refused instead of silently winning.
2853
3141
  serverEtag = snapshotPayload.etag || res.headers.get('ETag');
2854
3142
  serverRevision = Number.isSafeInteger(snapshotPayload.storeRevision) ? snapshotPayload.storeRevision : -1;
3143
+ /* The review summary rides the SAME envelope, read atomically with the contract under the project lock,
3144
+ and is installed INDEPENDENTLY of the contract revision — a sign-off leaves storeRevision exactly
3145
+ where it was, so gating this on `storeRevision > serverRevision` (as the reconnect path does for the
3146
+ contract) would discard every review update that mattered. */
3147
+ installReviewFromSnapshot(snapshotPayload, contractEventEpoch);
2855
3148
  // The confidence target is a workflow INPUT (target_confidence), not contract data. Read its declared
2856
3149
  // default only for an app-scoped editor: a project owns its contract independently of the installed
2857
3150
  // workflow, so asking /api/app/<id> there can only add a normal 404 to the console. A project-specific
@@ -2888,19 +3181,23 @@ async function boot() {
2888
3181
  // AISC catalogue weight for any tabulated designation the contract's weights map does not carry.
2889
3182
  C.custom_details = C.custom_details || {};
2890
3183
  C.profile_colors = C.profile_colors || {};
2891
- if(!C.member_styles||typeof C.member_styles!=='object'||Array.isArray(C.member_styles))C.member_styles={}; // F5: per member-type 2D line style {weight,dash} — model-global, draft-only (stripped at bake like prop_labels). boot() only object-guards; main() sanitizes the tokens/keys (sanitizeMemberStyles lives in main()'s scope)
3184
+ if(!C.member_styles||typeof C.member_styles!=='object'||Array.isArray(C.member_styles))C.member_styles={}; // F5: per member-type 2D line style {weight,dash} — model-global, draft-only (stripped at bake like prop_labels). boot() only object-guards; the token/key sanitise (sanitizeMemberStyles, which lives in main()'s scope) runs where the UNVALIDATED input arrives — the draft restore (#851). The contract itself reaches here schema-validated.
2892
3185
  if(!Array.isArray(C.member_types))C.member_types=[];
2893
3186
  if(!Array.isArray(C.dims3d))C.dims3d=[]; // model-global draft-only 3D dimensions
2894
3187
  if(!Array.isArray(C.detail_placements))C.detail_placements=[]; // model-global draft-only placed detail images (Slice 4)
2895
3188
  if(!C.dim_overlays||typeof C.dim_overlays!=='object'||Array.isArray(C.dim_overlays))C.dim_overlays={bolt_pitch:true,edge_clearance:true,cope_size:true,base_plate:true,anchor_depth:true}; // model-global legend DIMENSIONS toggles — all on by default
2896
- if(!C.dim_style||typeof C.dim_style!=='object'||Array.isArray(C.dim_style))C.dim_style={}; // model-global dimension-style defaults; the full sanitizeDimStyle() runs inside main() where DIM_ENDS/DIM_DEF live (mirrors prop_labels/views)
2897
- if(!Array.isArray(C.views))C.views=[]; // model-global saved views (Views Organizer): ensure an array in boot()'s OUTER scope (like dims3d/detail_placements above); the full sanitizeViews() runs inside main() where that helper lives (mirrors prop_labels)
3189
+ if(!C.dim_style||typeof C.dim_style!=='object'||Array.isArray(C.dim_style))C.dim_style={}; // model-global dimension-style defaults. This object-guard is the ONLY normalisation on the load path: `sanitizeDimStyle()` has no production call site (#851). Harmless as it stands — `dimStyle()` re-checks every key against DIM_DEF on each read, and the schema types dim_style `additionalProperties:true` with no enums, so junk here can neither reach the canvas nor refuse a save.
3190
+ if(!Array.isArray(C.views))C.views=[]; // model-global saved views (Views Organizer): ensure an array in boot()'s OUTER scope (like dims3d/detail_placements above). The array-guard is all this path needs — `C` here is the server-validated contract, so its views have already passed `$defs.view`. `sanitizeViews()` is for the path that has NOT been validated: the localStorage draft, via DRAFT_SANITIZERS in applyDraftFields (#854).
2898
3191
  // Reference models (#278) are always a model-level array in the native contract.
2899
3192
  if(!Array.isArray(C.reference_models))C.reference_models=[];
2900
3193
  main(); // (C.prop_labels is normalised inside main(), right after the PROP_DEFS/sanitizePropLabels registry is defined — see ~"normalise the contract's incoming value" — since that helper isn't in scope out here in boot())
2901
3194
  contractBootSnapshotInstalled=true;
2902
3195
  contractEventReady=true;
2903
3196
  drainContractEvents(contractEventEpoch);
3197
+ // …and the review buffer, which has its own slot. Missing this was a real lost update: a sign-off
3198
+ // landing between the snapshot read and the tab becoming ready would sit in reviewEventWatermark
3199
+ // forever, because SSE is plain fan-out with no replay. The reconnect path already drained both.
3200
+ drainReviewEvents(contractEventEpoch);
2904
3201
  }
2905
3202
 
2906
3203
  /**
@@ -3125,8 +3422,8 @@ function memberEndGroup(f){if(f.basis&&f.basis.kind==='drawing'){for(const p of
3125
3422
  function memberEndRole(f){return f.role==='horizontal-brace'?'Horizontal brace':f.role==='vertical-brace'?'Vertical brace':f.role==='brace-unknown'?'Brace':'Beam';}
3126
3423
  function memberEndClassification(f){return ({'aligned-auto':'Aligned automatically','aligned-manual':'Aligned after review','kept-short':'Kept intentionally short','needs-review':'Needs review','stale':'Decision needs review','not-checkable':'Not checkable'})[f.classification]||f.classification;}
3127
3424
  function memberEndReason(f){const words={
3128
- 'cross-view-conflict':'Source views disagree','brace-type-unknown':'Brace type is not recorded','multiple-targets':'Two possible work points','near-coincident-supports':'Nearby supports do not share one exact work point','candidate-overflow':'Too many nearby supports to prove one target','gap-too-large':'Gap larger than expected','crossing-angle-too-small':'Crossing angle is too small','target-out-of-reach':'Support does not span the work point','unresolved-profile':'Support footprint could not be proved','unsupported-placement':'Support placement could not be proved','existing-endpoint':'Existing endpoint requires review','unobserved-endpoint':'No drawing endpoint evidence','view-unregistered':'This view is not registered for geometry','stale-context':'The model changed since this decision'};
3129
- return (f.reasonCodes||[]).map(r=>words[r]||r).join(' · ');
3425
+ 'cross-view-conflict':'Source views disagree','brace-type-unknown':'Brace type is not recorded','multiple-targets':'Two possible work points','near-coincident-supports':'Nearby supports do not share one exact work point','candidate-overflow':'Too many nearby supports to prove one target','gap-too-large':'Gap larger than expected','crossing-angle-too-small':'Crossing angle is too small','target-out-of-reach':'Support does not span the work point','unresolved-profile':'Support footprint could not be proved','unsupported-placement':'Support placement could not be proved','existing-endpoint':'Existing endpoint requires review','unobserved-endpoint':'No drawing endpoint evidence','endpoint-elevation-missing':'Drawing endpoint elevation is missing.','view-scale-invalid':'This view has no usable drawing scale.','observation-scale-mismatch':'Drawing evidence uses a different scale than this view.','view-unregistered':'This view is not registered for geometry','view-policy-forbidden':'This endpoint cannot be checked in this view','subject-geometry-invalid':'Member geometry is incomplete','stale-context':'The model changed since this decision'};
3426
+ return (f.reasonCodes||[]).map(r=>words[r]||'Additional endpoint diagnostic').join(' · ');
3130
3427
  }
3131
3428
  function memberEndTargetName(t){return (t.memberIds||[]).join(' + ')+' centerline';}
3132
3429
  function memberEndTargetEqual(a,b){
@@ -3156,9 +3453,11 @@ function installMemberEndContract(doc,etag,revision){
3156
3453
  const activePlan=C.plans&&C.plans[C.active];
3157
3454
  if(activePlan&&activePlan.viewKind==='plan'){NO_PLAN_VIEW=false;V2_PROJECTION=v2ProjectionForSheet(activePlan.sheet);P=DEV_MODE?ModelCmd.deepFreezeProjection(V2_PROJECTION.plan):V2_PROJECTION.plan;}
3158
3455
  else{V2_PROJECTION=null;NO_PLAN_VIEW=true;if(!activePlan)C.active=0;P=activePlan?{...structuredClone(activePlan),members:[],segments:[],dims:[],details:[],callouts:[],tos_callouts:[],grid:null,default_tos:Number.isFinite(activePlan.elevation_in)?activePlan.elevation_in:0}:{sheet:'',members:[],segments:[],dims:[],details:[],callouts:[],tos_callouts:[],grid:null,default_tos:0};resetPlanViewState(C.active);}
3456
+ syncElevationContext();
3159
3457
  // A server command replaces the model underneath the editor's local history. Retaining those snapshots
3160
3458
  // would let Ctrl+Z resurrect pre-command geometry without the server-owned decision/audit metadata.
3161
3459
  undo.length=0;redo.length=0;updUR();
3460
+ bumpModelEditGeneration(); // the server replaced the document under the editor; nothing captured before this describes what is now on screen
3162
3461
  const prev=serverEtag;serverEtag=etag;serverRevision=revision;restampDraftBase(prev,etag);conflicted=false;render();sync3D();
3163
3462
  }
3164
3463
  async function memberEndRequest(path,body){
@@ -3439,8 +3738,16 @@ function memberPositionGizmoState(id){
3439
3738
  }
3440
3739
  const f=SteelCore.positionGizmoFrame(input.from,input.to,captured);
3441
3740
  if(!f)return{available:false,reason:m.id+' has no Profile Position frame in the current view'};
3741
+ const effRot=positionAuthoringRoll(m);
3442
3742
  return{available:true,id,anchor:[...input.from],xAxis:[...f.x],yAxis:[...f.y],zAxis:[...f.z],
3443
- positionOffset:+m.positionOffset||0,positionHOffset:+m.positionHOffset||0,rot:positionAuthoringRoll(m),degenerate:!!f.degenerate,
3743
+ // The member's PROFILE axes — the part frame turned by the authored roll. ONE source, computed here,
3744
+ // because the gizmo now DRAWS depth/width on them AND moves the work points along them: if the drawing
3745
+ // and the drag scalar ever re-derived this separately, the steel would travel somewhere the arrow does
3746
+ // not point. Every consumer (draw, pick, screen probe, drag math, leader, typed entry, live state)
3747
+ // reads st.profile. Slide and both swings deliberately stay on the UNROLLED frame above — an elevation
3748
+ // swing about a rolled y is not a tilt.
3749
+ profile:SteelCore.rolledProfileAxes(f,effRot),
3750
+ positionOffset:+m.positionOffset||0,positionHOffset:+m.positionHOffset||0,rot:effRot,degenerate:!!f.degenerate,
3444
3751
  // slice 3b.1 — the reference-line handles need the FAR work point and the basis UP vector as well, plus a
3445
3752
  // drag-start FINGERPRINT. The fingerprint has to be captured HERE, when the gesture starts, because that
3446
3753
  // is the state the drag's arithmetic is frozen against; taking it again at commit time would compare the
@@ -3483,7 +3790,12 @@ function refLineHandleAvailability(m,f,from,to,up){
3483
3790
  SteelCore.swingBarriers(from,to,f.y,up,SteelCore.POSITION_SWING_MARGIN_RAD),SteelCore.POSITION_ROT_SNAP_DEG*Math.PI/180)
3484
3791
  ?{available:false,reason:'This member is within a degree of plumb — set its elevations in the Inspect panel.'}
3485
3792
  :swing;
3486
- return{slide:{available:true},swingPlan:swing,swingElev:elev};}
3793
+ // depth/width are TRANSLATIONS of the whole line along the profile axes, so like the axial slide they
3794
+ // are representable for every member the gizmo shows at all — including a plumb column, where they move
3795
+ // it in plan. They are listed rather than left out so all five moving handles come from ONE map: the
3796
+ // typed-entry path asks `st.handles[axis]` for every handle it opens, and an axis missing from the map
3797
+ // would read as "not available" rather than as "always available".
3798
+ return{depth:{available:true},width:{available:true},slide:{available:true},swingPlan:swing,swingElev:elev};}
3487
3799
  /*
3488
3800
  * The gizmo's one write path: the 3D view hands back an absolute new offset (mm) or roll (deg) for a
3489
3801
  * single member; this routes it through `commitPositionEdit`, which rebases to the current frame,
@@ -3527,7 +3839,12 @@ function commitMemberEndpoints(id,spec,source){
3527
3839
  const after=SteelCore.positionGizmoFrame(from,to,captured);
3528
3840
  if(!after)return positionRefuse('That move leaves the member with no length.',source);
3529
3841
  const gesture=spec&&spec.gesture;
3530
- if(gesture==='slide'?(!!after.degenerate!==!!(before&&before.degenerate))
3842
+ // A gesture that moves the line RIGIDLY (the axial slide, and since the redesign the two lateral
3843
+ // translates) must merely KEEP partFrame's branch, in both directions; a swing re-aims the member and
3844
+ // has to land on the ordinary branch. This is a shared VALIDATION policy, not a claim that the two
3845
+ // translations are numerically identical: each endpoint quantises independently, so near the degeneracy
3846
+ // cone either one can cross the branch through rounding alone — which is exactly what this rejects.
3847
+ if(SteelCore.directionPreservingGesture(gesture)?(!!after.degenerate!==!!(before&&before.degenerate))
3531
3848
  :after.degenerate)return positionRefuse('That move would leave the section with no usable frame — try a smaller change.',source);
3532
3849
  const pin=SteelCore.requiredDepthPin(input.canonical,{from:input.from,to:input.to},{from,to}).pin;
3533
3850
  const current=positionAuthoringBasis();if(current.generation!==captured.generation)return positionRefuse('Frame changed — review the refreshed Profile Position and try again.',source);
@@ -3802,9 +4119,11 @@ function parseVec(s){s=String(s==null?'':s).trim();if(!s)return null;
3802
4119
  const d=parseLen(s);return d==null?null:{dist:d};}
3803
4120
  // To-level TOS mapping (spec §4.5): default-follow ends land on the target level automatically;
3804
4121
  // explicit overrides shift by Δ so relative offsets survive. Columns keep their height (bos shifts by Δ).
3805
- // best-effort: framing plans carry TOS at the level UNO — assume the L2 datum +16'-6" (198"); each end's
3806
- // 'default' checkbox links it to this value (auto-updates when changed); uncheck to override.
3807
- let defaultTOS=198, addProfile='', addMaterial='', addType='beam'; // addProfile/addMaterial/addType are independent defaults for newly drawn members
4122
+ // Legacy plans can still carry default-follow ends. Native v2 plans do not: this number is only their
4123
+ // read-only active-plan elevation context and is synchronized whenever the active projection changes.
4124
+ let defaultTOS=0, addProfile='', addMaterial='', addType='beam'; // addProfile/addMaterial/addType are independent defaults for newly drawn members
4125
+ function nativeElevationModel(){return C&&C.type===MODEL_V2_TYPE;}
4126
+ function syncElevationContext(){const value=Number(P&&P.default_tos);defaultTOS=Number.isFinite(value)?value:0;return defaultTOS;}
3808
4127
  const profileCatalog=window.__STEEL_PROFILE_CATALOG||{environment:'US',standard:'Profile catalog',families:[],rows:[]};
3809
4128
  const profileCatalogRows=CatalogPicker.buildProfileRows(profileCatalog,window.__AISC_SECTIONS||{},window.__AISC_WEIGHTS||{});
3810
4129
  const materialCatalog=CatalogPicker.materialCatalogDescriptorFor(profileCatalog.environment||'US',window.__STEEL_MATERIAL_CATALOG);
@@ -3890,6 +4209,7 @@ function apply(json){
3890
4209
  V2_SESSION.restoreSnapshot(d);
3891
4210
  V2_PROJECTION=v2ProjectionForSheet(C.plans[C.active].sheet);
3892
4211
  P=DEV_MODE?ModelCmd.deepFreezeProjection(V2_PROJECTION.plan):V2_PROJECTION.plan;
4212
+ syncElevationContext();
3893
4213
  updCS();
3894
4214
  selIds=new Set([...selIds].filter(id=>byId(id)||/^det:/.test(id))); // keep a selected placed-detail id (det:…) — it isn't a member
3895
4215
  selDimIds.forEach(id=>{if(!(P.dims||[]).some(x=>x.id===id))selDimIds.delete(id);}); // drop any dim selection the undo removed
@@ -4130,7 +4450,12 @@ function applyRevalidation(rv){
4130
4450
  const mk=id=>{const m=byId(id);return (m&&(m.mark||m.id))||id;};
4131
4451
  const KIND={'shear-plate':'Shear plate','brace-gusset':'Brace gusset'};
4132
4452
  const kindLabel=k=>KIND[k]||'Connection';
4133
- const rm=rv.removed||[],rp=rv.repointed||[],fl=rv.flagged||[],df=rv.deferred||[];
4453
+ const rm=rv.removed||[],rp=rv.repointed||[],df=rv.deferred||[];
4454
+ /* The connection whose members are being named right now is EXCLUDED from the flagged clause. The
4455
+ placement command is about to record the very relationship "may need review" would be asking
4456
+ about, so the warning is both noise and untrue at that moment — and it lands on the shared #toast,
4457
+ erasing the only complete statement of how to confirm or skip the pick. */
4458
+ const fl=(rv.flagged||[]).filter(f=>!(connMemberPick&&f&&f.id===connMemberPick.id));
4134
4459
  const clauses=[];
4135
4460
  if(rm.length)clauses.push(rm.length===1?(kindLabel(rm[0].kind)+' removed — no supporting member'):(rm.length+' connections removed — no supporting member'));
4136
4461
  if(rp.length){
@@ -4147,6 +4472,7 @@ function applyRevalidation(rv){
4147
4472
  if(removedIds.size||repoints.length){
4148
4473
  C.joints=(C.joints||[]).filter(j=>!removedIds.has(j.id));
4149
4474
  for(const r of repoints){const j=(C.joints||[]).find(x=>x.id===r.id);if(j)j.secondaries=[r.to];}
4475
+ bumpModelEditGeneration(); // the VISIBLE document just changed without scheduling a save — a sign-off captured before this must not pass its generation check
4150
4476
  persist();render();sync3D(); // persist() rewrites the localStorage draft; the durable copy already holds this
4151
4477
  }
4152
4478
  if(rm.length!==removedIds.size||rp.length!==repoints.length)console.warn('steel-editor: a malformed revalidation report entry was skipped',rv);
@@ -4168,7 +4494,7 @@ function applyRevalidation(rv){
4168
4494
  // This replaced a client-side merge (fingerprints, ownership rules, etag-generation heuristics) that four
4169
4495
  // adversarial review rounds kept finding concurrency bugs in: reconciling a server-authoritative transform
4170
4496
  // against a concurrently-edited local copy is a CRDT-class problem, and the way to win it was not to play.
4171
- async function persistServer(force){const seq=saveSeq;
4497
+ async function persistServer(force,token){const seq=saveSeq;
4172
4498
  // Once conflicted, stop firing doomed PUTs; re-surface the explanation instead of hammering the
4173
4499
  // network every debounce tick. Cleared only by a reload or a confirmed overwrite.
4174
4500
  if(conflicted&&!force){showConflictBanner();return;}
@@ -4226,8 +4552,8 @@ async function persistServer(force){const seq=saveSeq;
4226
4552
  // then still carry a joint the store removed, and the NEXT save re-introduces it, which is exactly the
4227
4553
  // shape the server always re-decides. So the removal simply happens again, authoritatively.
4228
4554
  }
4229
- });}
4230
- function scheduleSave(){if(memberEndStatus.known||memberEndReview)invalidateMemberEndReview();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)
4555
+ },token);}
4556
+ function scheduleSave(){if(memberEndStatus.known||memberEndReview)invalidateMemberEndReview();bumpModelEditGeneration();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)
4231
4557
  // The boot-scope SSE handler's seam into that debounce — see `flushLocalDraft` for why the handler
4232
4558
  // cannot reach `persist()` itself.
4233
4559
  //
@@ -4244,13 +4570,27 @@ flushLocalDraft = () => persist(); // the RESULT is load-bearing at the call s
4244
4570
  // server right now. The parent (aware.js #contract-editor-approve) awaits this before
4245
4571
  // POSTing approve, so Approve always bakes the latest edits — not a stale debounce
4246
4572
  // snapshot. Throws on a non-2xx response so the parent can abort and show the warn toast.
4247
- window.flushContract = async () => {
4573
+ /**
4574
+ * It RESOLVES TO `{ etag, generation }`, and both halves are the sign-off precondition (§5.2).
4575
+ *
4576
+ * `etag` is the tag this write produced — the one the sign-off must send as `If-Match`, rather than
4577
+ * re-reading `serverEtag`, which by dispatch time may already name a LATER write. `generation` is
4578
+ * `modelEditGeneration` captured synchronously beside `JSON.stringify(C)`, so it names the document
4579
+ * that was actually published rather than whatever is on screen a round trip later.
4580
+ *
4581
+ * `token` admits this flush past a closed write gate when the flush IS the gate's owner — see the gate.
4582
+ * Every pre-existing caller (Approve, memberEndRequest, placeConnection, detailRequest) only awaits the
4583
+ * promise, so widening the resolution value breaks nothing.
4584
+ */
4585
+ async function flushContractWith(token) {
4248
4586
  clearTimeout(saveT); saveT = null; // the debounced write is being taken over by this flush, so it is no longer pending
4249
4587
  // Behind the SAME queue as autosave — Approve awaits this, and a flush racing an in-flight autosave
4250
4588
  // was the self-conflict path that could abort Approve for no reason.
4251
4589
  return queueWrite(async () => {
4252
4590
  const mid = newMutationId(); claimMutation(mid); // same own-echo identity as persistServer — see there
4253
4591
  const seq = ++saveSeq;
4592
+ let adoptedTag = null; // the tag THIS write produced, reported back for the sign-off's precondition
4593
+ let publishedGeneration = modelEditGeneration;
4254
4594
  let res;
4255
4595
  try {
4256
4596
  // Conditional like every other write, and it MUST refresh the tag on success. Getting this wrong is
@@ -4260,6 +4600,9 @@ window.flushContract = async () => {
4260
4600
  const headers = { 'content-type': 'application/json', 'x-floless-mutation-id': mid };
4261
4601
  // Same total rule as persistServer — see the comment there for why "no tag" means If-None-Match: *.
4262
4602
  if (serverEtag) headers['if-match'] = serverEtag; else headers['if-none-match'] = '*';
4603
+ // Captured HERE, in the same synchronous expression that serialises the body, so it names the
4604
+ // document this PUT actually carried — not one an edit produced while the request was in flight.
4605
+ publishedGeneration = modelEditGeneration;
4263
4606
  res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS, { method: 'PUT', headers, body: JSON.stringify(C) });
4264
4607
  } catch (e) {
4265
4608
  releaseMutation(mid); // nothing was written, so no broadcast will ever carry this id
@@ -4284,7 +4627,7 @@ window.flushContract = async () => {
4284
4627
  showConflictBanner();
4285
4628
  throw new Error('save conflict');
4286
4629
  }
4287
- if (res.ok) { let d = {}, bodyReadable = true; try { d = await res.json(); } catch (_) { bodyReadable = false; } const t = d.etag || res.headers.get('ETag'); if (d.contract && t && Number.isSafeInteger(d.storeRevision)) installMemberEndContract(d.contract, t, d.storeRevision); else { if (t) { const pv = serverEtag; serverEtag = t; restampDraftBase(pv, t); } if (Number.isSafeInteger(d.storeRevision)) serverRevision = Math.max(serverRevision, d.storeRevision); } conflicted = false;
4630
+ if (res.ok) { let d = {}, bodyReadable = true; try { d = await res.json(); } catch (_) { bodyReadable = false; } const t = d.etag || res.headers.get('ETag'); adoptedTag = t || null; if (d.contract && t && Number.isSafeInteger(d.storeRevision)) installMemberEndContract(d.contract, t, d.storeRevision); else { if (t) { const pv = serverEtag; serverEtag = t; restampDraftBase(pv, t); } if (Number.isSafeInteger(d.storeRevision)) serverRevision = Math.max(serverRevision, d.storeRevision); } conflicted = false;
4288
4631
  // The flush committed. Same rule as persistServer: apply the report only when the body was readable and
4289
4632
  // `seq===saveSeq` (Approve awaits this flush, so the user CAN edit meanwhile and make it stale). Otherwise
4290
4633
  // do nothing — the next save re-introduces any joint whose removal we missed, and the server re-decides it.
@@ -4293,7 +4636,34 @@ window.flushContract = async () => {
4293
4636
  else releaseMutation(mid);
4294
4637
  if (seq === saveSeq) setSaved(res.ok ? 'ok' : 'err'); // only the latest save owns the pill
4295
4638
  if (!res.ok) throw new Error('save failed (' + res.status + ')');
4296
- });
4639
+ return { etag: adoptedTag, generation: publishedGeneration };
4640
+ }, token);
4641
+ }
4642
+ /**
4643
+ * A flush is a WHOLE-DOCUMENT publish, and it must never queue behind a human.
4644
+ *
4645
+ * Approve (`aware.js`) awaits this inside a `try/finally` that re-enables its button — so a flush that
4646
+ * parks on the re-placement gate leaves Approve stuck on "Baking…" for as long as the member pick stays
4647
+ * armed, which is indefinitely: naming members is a human action with no time limit and no other tab is
4648
+ * going to end it. `detailRequest` and `memberEndRequest` await it too and would silently do nothing.
4649
+ * (Found by review.)
4650
+ *
4651
+ * So an outside flush SETTLES the placement rather than waiting on it, in the direction this design
4652
+ * already prefers: abandoning lands the joint untracked, which is visible and correctable, where
4653
+ * waiting looks exactly like a hung server. The abandon resolves the transaction, whose `finally`
4654
+ * opens the gate, and this flush — parked for that one turn — then proceeds.
4655
+ *
4656
+ * Only for a NON-owner flush. The transaction's own flush carries the token and must go straight
4657
+ * through; abandoning there would have it settle itself halfway.
4658
+ */
4659
+ window.flushContract = () => {
4660
+ if (writeGateToken) {
4661
+ const v = window.Steel3DView;
4662
+ if (v && v.abandonConnMemberPick && v.connMemberPickJoint && v.connMemberPickJoint() !== null) {
4663
+ v.abandonConnMemberPick('flush-requested');
4664
+ }
4665
+ }
4666
+ return flushContractWith(null);
4297
4667
  };
4298
4668
  /**
4299
4669
  * The server's reference list, wearing the draft's display and placement wherever the ids still match.
@@ -4351,13 +4721,101 @@ function reconcileReferences(server,draft){
4351
4721
  function applyDraftFields(d){
4352
4722
  const candidate=structuredClone(C);
4353
4723
  const rootKeys=['members','grid','custom_details','profile_colors','member_styles','member_types','target_confidence','dims3d','dim_overlays','dim_style','prop_labels','joints','connections','detail_placements','views'];
4354
- for(const key of rootKeys)if(key in d)candidate[key]=structuredClone(d[key]);
4355
- // …EXCEPT `prop_labels`, WHICH IS SANITISED (#614). A draft is unvalidated
4356
- // localStorage, and this restore runs AFTER the boot-time sanitise — so a raw copy re-introduces
4357
- // exactly the shape that sanitise exists to prevent: `prop_labels` with no `props`, which
4358
- // `renderPropLabels` dereferences on the next repaint. Reachable today, not hypothetically: a
4359
- // and any draft written by a build that did not sanitise carries that shape forward.
4360
- if('prop_labels' in d)candidate.prop_labels=sanitizePropLabels(d.prop_labels);
4724
+ // A draft is unvalidated localStorage, and this restore runs AFTER the boot-time sanitise — so a raw
4725
+ // copy re-introduces exactly the shapes the sanitisers exist to prevent, one link past the guard.
4726
+ // `prop_labels` was wired for that reason (#614) and the others were not (#851): `sanitizeConnections`
4727
+ // had NO call site anywhere in the repo, and `sanitizeMemberStyles`/`sanitizeDims3d` only a self-test —
4728
+ // three sanitisers written for THIS site and never reached from it. The registry replaces the loop's
4729
+ // blanket clone so the wiring lives with the key list: a rootKey that grows a sanitiser can no longer
4730
+ // be added to one and silently skipped by the other, which is how all three came to be dead.
4731
+ //
4732
+ // WHAT IT ACTUALLY COSTS — measured, and not what #851 predicted. The issue expected an id-less
4733
+ // `connections` row to SAIL PAST the client and refuse every save server-side. It does not:
4734
+ // `checkModelReferences` really is blind to it (it indexes the row as `null` and flags only DUPLICATE
4735
+ // and UNRESOLVED ids, never a missing one), but `validationProblems()` in steel-model-v2-commands.js
4736
+ // runs the SCHEMA as well, and `connections[].id` is required — so the restore itself is refused,
4737
+ // atomically. The row was never what was at risk. THE USER'S WHOLE DRAFT WAS: one unusable row and
4738
+ // every edit in that session is discarded, with one console line as the only trace. Sanitising first
4739
+ // turns "throw all of it away" into "drop the row that was unreachable anyway" — an id-less row
4740
+ // resolves from nothing, since every `ends[].conn` / `joints[].conn` looks up BY id. `member_styles`
4741
+ // (bogus weight/dash token) and `dims3d` (degenerate `axisDir`, whose own doc says "run at every point
4742
+ // a dims3d array is assigned") are the same story with the same cost.
4743
+ //
4744
+ // `views` was held out of this registry until #854 for a reason worth keeping written down: its
4745
+ // sanitiser was itself unsaveable. `sanitizeViews` minted a root `projection` against a
4746
+ // `$defs.view` that is `additionalProperties:false`, and wrote `camera`/`clips`/`objects` as `null`
4747
+ // where the schema types each as an object — so wiring it would have CAUSED the refused save this
4748
+ // block exists to prevent. The sanitiser was corrected first, in the same change that wired it.
4749
+ // EACH ENTRY ENFORCES THE SCHEMA AND NOTHING ELSE. A guard here may reject what the schema cannot
4750
+ // hold — that is the whole job, since anything else refuses the restore or the next save — and may
4751
+ // never impose an opinion of its own, because the draft is the user's data and the loss is silent.
4752
+ // A guard returns `undefined` for a drafted value whose ROOT is the wrong type, and that key is then
4753
+ // LEFT ALONE — the document's own value stands. It is the only outcome that saves the rest of the
4754
+ // draft. Substituting an empty collection looks tidy and is not: with `connections:{}` in the draft,
4755
+ // an empty library orphans every `ends[].conn` / `joints[].conn` the document already holds, so the
4756
+ // whole restore is refused and every unrelated edit dies with it — the exact failure this block
4757
+ // exists to prevent. Passing the malformed value through refuses just as hard (the schema types these
4758
+ // roots), so neither substitute works and only skipping does. A wrong-typed root is corruption, never
4759
+ // a user state: emptying a collection is legitimately drafted as `[]`/`{}`, which is well-typed and
4760
+ // restores normally. (Codex, #853.)
4761
+ const unusableRoots=[];
4762
+ const arr=v=>Array.isArray(v)?v:undefined;
4763
+ const rec=v=>(v&&typeof v==='object'&&!Array.isArray(v))?v:undefined;
4764
+ // ASK THE SCHEMA, DO NOT RESTATE IT. Every regression in this block came from a guard holding an
4765
+ // opinion about the contract that the contract did not hold — narrower six times (a clamped id, a
4766
+ // trimmed id, a rebuilt recipe, a rebuilt note, a deleted style entry, a filtered props token) and,
4767
+ // once the search finally ran in the other direction, WIDER too: `sanitizeDims3d` only canonicalises
4768
+ // `axisDir`, so a dim with no `id`, a bogus `axis`, a missing `b` or an extra key sailed straight
4769
+ // through and refused the whole restore. Rather than write those four rules out here — the seventh
4770
+ // restatement of a rule the schema already owns — each row is put to `$defs.dim3` itself, through the
4771
+ // same subset interpreter the server validates with. `$defs` rides along so `#/$defs/point3` resolves.
4772
+ const rowSchema=name=>(V2_SCHEMA&&V2_SCHEMA.$defs&&V2_SCHEMA.$defs[name])?{...V2_SCHEMA.$defs[name],$defs:V2_SCHEMA.$defs}:null;
4773
+ const rowsOk=(list,name)=>{const node=rowSchema(name);
4774
+ return node?list.filter(r=>V2Validation.validateSchemaSubset(r,node).valid):list;}; // no schema yet → keep everything; a guard must never be the thing that loses data
4775
+ const DRAFT_SANITIZERS={
4776
+ prop_labels:v=>rec(v)&&sanitizePropLabels(v), // $defs.propLabels is CLOSED and this emits exactly its six keys
4777
+ connections:v=>arr(v)&&sanitizeConnections(v),
4778
+ // NOT `sanitizeMemberStyles`. `member_styles` is `additionalProperties:true` and otherwise
4779
+ // UNCONSTRAINED, so the only thing the schema can refuse is a non-object — which is all this guards.
4780
+ // #851 asked for the full sanitiser here and its premise does not survive contact with the schema:
4781
+ // a bogus weight/dash token and an un-normalised type key both validate FINE, so no corrupt style
4782
+ // can refuse a save and there is nothing for a clamp to save the user from. Wiring it cost instead
4783
+ // of gained — `{beam:{weight:'med',dash:'solid',vendor:'AceSteel'}}` is schema-valid and came back
4784
+ // as `{}` (an all-default entry is deleted), taking `vendor` with it, permanently on the next
4785
+ // autosave. The renderer already tolerates junk tokens (`memberLineStyle` falls back per token), so
4786
+ // nothing downstream needed the clamp either. (Codex, #853.)
4787
+ member_styles:rec,
4788
+ // canonicalise axisDir (SteelCore, resolved at call time — boot() awaits the module before main()),
4789
+ // then let $defs.dim3 itself reject the rows it cannot hold: id/a/b/axis are required, id is
4790
+ // minLength 1, axis is an enum and the row is additionalProperties:false, NONE of which
4791
+ // sanitizeDims3d checks — so any of them used to cost the entire draft.
4792
+ dims3d:v=>arr(v)&&rowsOk(SteelCore.sanitizeDims3d(v),'dim3'),
4793
+ // Canonicalise what the view module owns (id, name, display mode, provenance), then let `$defs.view`
4794
+ // itself refuse the rows it cannot hold — the same two-step as `dims3d`, and for the same reason:
4795
+ // `sanitizeViews` knows nothing of the schema, so an opaque `camera`/`clips`/`objects` snapshot from
4796
+ // an older editor carrying a key this schema closed off is caught HERE rather than being restated
4797
+ // there. A refused row costs that one saved view and is warned about below; passing it through would
4798
+ // cost the entire draft, since `views` is a root the schema types.
4799
+ views:v=>arr(v)&&rowsOk(sanitizeViews(v),'view'),
4800
+ };
4801
+ for(const key of rootKeys)if(key in d){
4802
+ const raw=structuredClone(d[key]),clean=DRAFT_SANITIZERS[key];
4803
+ if(clean){
4804
+ const val=clean(raw);
4805
+ if(val===undefined){unusableRoots.push(key);continue;} // wrong-typed root → keep the document's value
4806
+ candidate[key]=val;
4807
+ }else candidate[key]=raw;
4808
+ // Dropping a row silently is the half that makes this dangerous — the draft the user asked for came
4809
+ // back short and nothing said so. Warn per key, with the count, so a short restore has a local trail.
4810
+ // Only `connections` can shorten today (the others map 1:1 or are objects), but the guard is written
4811
+ // against the LENGTH rather than the key, so a sanitiser that starts dropping keeps its trail too.
4812
+ if(clean&&Array.isArray(raw)&&Array.isArray(candidate[key])&&candidate[key].length<raw.length)
4813
+ console.warn('steel-editor: dropped '+(raw.length-candidate[key].length)+' unusable '+key+' row(s) restoring the browser draft — the rest of the draft was kept');
4814
+ }
4815
+ // Louder than a dropped row, because a whole collection did not come back: whatever the user changed
4816
+ // under these keys is not on screen, and the document's version is showing in its place.
4817
+ if(unusableRoots.length)
4818
+ console.warn('steel-editor: the browser draft held a malformed '+unusableRoots.join(', ')+' — that key was NOT restored and the model’s own value is being shown; the rest of the draft was applied');
4361
4819
  // REFERENCES ARE RECONCILED, NEVER REPLACED — and this is not tidiness, it is a reference that
4362
4820
  // vanished in front of me. Which references EXIST is the server's answer: insert and remove are
4363
4821
  // routes that write the contract themselves, and `adoptReferenceWrite` then re-points this draft at
@@ -4513,14 +4971,10 @@ function updUR(){document.getElementById('undoB').disabled=!undo.length;document
4513
4971
  // index moved off it — a blank/RFI/other-plan profile must not shift a real profile's slot.) Rebuilt at
4514
4972
  // render() top so it tracks edits without touching every profs.push site.
4515
4973
  let colorRank=[];
4516
- // Canonical designation (MIRRORS server contract-to-scene canonProfile): upper, x/X/× → X, whitespace
4517
- // around X / after the prefix removed, mixed-fraction spaces kept. One identity for 2D / 3D / IFC / Tekla.
4518
- function canonProfile(s){return String(s||'').trim().toUpperCase().replace(/×/g,'X').replace(/\s*X\s*/g,'X').replace(/^([A-Z]+)\s+/,'$1');}
4519
- function buildColorRank(){colorRank=[...new Set([...(C.plans||[]).flatMap(pl=>(pl.members||[]).map(m=>canonProfile(m.profile))).filter(Boolean), ...Object.keys(WT||{}).map(canonProfile)])].sort();}
4520
- function colorFor(p){const k=canonProfile(p);
4521
- const ov=C.profile_colors[p]??(Object.entries(C.profile_colors).find(([kk])=>canonProfile(kk)===k)||[])[1]; // override: exact key, then canonical (case + x/X/× + separator whitespace) — mirrors contract-to-scene pickColor so an override resolves identically in 2D + 3D
4522
- if(ov)return ov;
4523
- const i=colorRank.indexOf(k);return PAL[((i%PAL.length)+PAL.length)%PAL.length];} // i<0 (blank/CUSTOM/unresolved) wraps to PAL[last], matching pickColor so those members agree in 2D + 3D too
4974
+ const canonProfile=s=>ProfileColours.canonicalProfile(s);
4975
+ function buildColorRank(){colorRank=ProfileColours.profileColourRank(C,WT);}
4976
+ function colorFor(p){return ProfileColours.profileColour(p,C.profile_colors,colorRank,PAL,message=>console.warn('steel-editor: '+message));}
4977
+ function setProfileColour(profile,colour){ProfileColours.setCanonicalProfileColour(C.profile_colors,profile,colour);}
4524
4978
  // F5: per member-type 2D line style. Tokens → px; dashes chosen to avoid the reserved semantic patterns
4525
4979
  // (RFI 10 6, brace 30 8 6 8, grid 12 4 2 4). med+solid (or absent) = today's default (line.member stroke-width:6).
4526
4980
  const MS_W={thin:3,med:6,thick:9},MS_D={solid:'',dashed:'14 8',dotted:'2 8',dashdot:'18 7 3 7'};
@@ -4532,9 +4986,16 @@ function memberLineStyle(m){const s=C.member_styles&&C.member_styles[memberTypeO
4532
4986
  function setMemberLineStyle(tk,prop,val){edit(()=>{const cur=(C.member_styles[tk]&&typeof C.member_styles[tk]==='object')?C.member_styles[tk]:{};
4533
4987
  const next={weight:cur.weight||'med',dash:cur.dash||'solid'};next[prop]=val;
4534
4988
  if(next.weight==='med'&&next.dash==='solid')delete C.member_styles[tk];else C.member_styles[tk]=next;});}
4535
- // F5: clamp a restored member_styles map to valid tokens + normalised type keys. The server schema validates
4536
- // on save, but the localStorage draft (and any hand-edited contract) is unvalidated — this keeps a bogus
4537
- // token/key from reaching the next save (which would fail validation) and drops all-default entries.
4989
+ // F5: canonicalise a member_styles map to valid tokens + normalised type keys, and drop all-default entries
4990
+ // — the same shape `setMemberLineStyle` writes, so this is the WRITE-side canonical form.
4991
+ //
4992
+ // IT IS NOT THE DRAFT-RESTORE GUARD, and the reason it reads like one is that its original rationale was
4993
+ // wrong: "a bogus token would fail validation on save" is false. `member_styles` is `additionalProperties:
4994
+ // true` and otherwise unconstrained, so `{beam:{weight:'bogus'}}` validates, and the only member_styles the
4995
+ // schema refuses is a non-object. Nothing here protects a save. Running it over a restored draft only
4996
+ // destroyed data — a schema-valid entry carrying an unknown key came back stripped, or, if its tokens were
4997
+ // the defaults, deleted outright — so `applyDraftFields` guards that key with a plain object-check instead
4998
+ // and this stays on the write path. See DRAFT_SANITIZERS (Codex, #853).
4538
4999
  function sanitizeMemberStyles(ms){if(!ms||typeof ms!=='object'||Array.isArray(ms))return {};
4539
5000
  const WOK={thin:1,med:1,thick:1},DOK={solid:1,dashed:1,dotted:1,dashdot:1},out={};
4540
5001
  const nk=k=>String(k||'').trim().toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-+|-+$/g,'').slice(0,48); // mirrors normMemberTypeKey (a const defined later → inlined so this stays callable at boot-time init)
@@ -4548,22 +5009,36 @@ function sanitizeMemberStyles(ms){if(!ms||typeof ms!=='object'||Array.isArray(ms
4548
5009
  // anyway and keeping it would only let a later save write a contract the schema rejects (id is required).
4549
5010
  // The recipe/notes/image keys carry each detail's meaning, so they are preserved but shape-checked —
4550
5011
  // detail-recipes.ts already refuses a malformed recipe, and this keeps junk from reaching it at all.
5012
+ //
5013
+ // THE ID IS NEITHER TRUNCATED NOR TRIMMED-AND-JUDGED, unlike every other string here — it is taken
5014
+ // verbatim or the row is dropped, and the ONLY rejections are "not a string" and "" (which the schema's
5015
+ // `minLength:1` forbids outright, so no valid document can hold one). An id is IDENTITY, matched by exact
5016
+ // string, and every narrowing of it is the same bug wearing a different hat: `ends[].conn` / `joints[].conn`
5017
+ // keep the ORIGINAL value, `checkModelReferences` then reports conn-unresolved, and the restore is refused
5018
+ // WHOLESALE — the precise atomic draft loss this sanitiser was wired up to prevent. Two such narrowings
5019
+ // have been caught here already (Codex, #853): a `slice(0,120)` clamp, which broke any id over 120 chars,
5020
+ // and a `.trim()` test, which dropped a whitespace-only id like " " that is schema-valid, reference-clean
5021
+ // and resolves perfectly well. Bound the text fields; never touch the key they are found by.
4551
5022
  function sanitizeConnections(rows){if(!Array.isArray(rows))return [];
4552
- const txt=(v,n)=>typeof v==='string'?v.slice(0,n):undefined;
4553
- const obj=v=>(v&&typeof v==='object'&&!Array.isArray(v))?v:undefined;
5023
+ // ROWS ARE DROPPED, NEVER RESHAPED. This function used to rebuild `recipe` from {kind,params,schedule}
5024
+ // and each note from {text,source}, clamping several of them — which quietly DELETED every other key.
5025
+ // `connections[].items` is `required:['id']` with `additionalProperties:true`, deliberately: a row carries
5026
+ // whatever a vendor's detail means, so `recipe.vendor`, `recipe.partNumber`, a note's `author` or `rfi`
5027
+ // are all valid data. Restoring a draft therefore stripped them, and — unlike a refused restore, which at
5028
+ // least leaves the server copy intact — the NEXT ordinary autosave wrote the stripped version back, making
5029
+ // the loss permanent and silent. Third narrowing caught in review here (Codex, #853), after the id clamp
5030
+ // and the id trim, and the same lesson each time: this guard may not hold an opinion the schema does not.
5031
+ //
5032
+ // What is left is only what is load-bearing — the two shapes the schema genuinely cannot hold, each of
5033
+ // which would refuse every save from the moment it lands. Shape-checking `recipe` was belt-and-braces on
5034
+ // top of detail-recipes.ts, which resolves a recipe to a NAMED refusal rather than trusting it.
5035
+ //
5036
+ // Rows are returned by reference; the DRAFT_SANITIZERS call site structuredClones its input first.
4554
5037
  const out=[];
4555
- for(const r of rows){if(!r||typeof r!=='object'||Array.isArray(r))continue;
4556
- const id=txt(r.id,120);if(!id||!id.trim())continue;
4557
- const row={...r,id};
4558
- const rec=obj(r.recipe);
4559
- if(rec){const kind=txt(rec.kind,64);
4560
- row.recipe={...(kind?{kind}:{}),...(obj(rec.params)?{params:obj(rec.params)}:{}),
4561
- ...(Array.isArray(rec.schedule)?{schedule:rec.schedule.filter(s=>s&&typeof s==='object'&&!Array.isArray(s)).slice(0,200)}:{})};
4562
- }else if('recipe' in row)delete row.recipe;
4563
- if(Array.isArray(r.notes))row.notes=r.notes.filter(n=>n&&typeof n==='object'&&typeof n.text==='string')
4564
- .slice(0,200).map(n=>({text:n.text.slice(0,2000),...(typeof n.source==='string'?{source:n.source.slice(0,32)}:{})}));
4565
- else if('notes' in row)delete row.notes;
4566
- out.push(row);}
5038
+ for(const r of rows){
5039
+ if(!r||typeof r!=='object'||Array.isArray(r))continue; // items: {type:'object'}
5040
+ if(typeof r.id!=='string'||r.id==='')continue; // id: required, minLength 1 — '' only
5041
+ out.push(r);}
4567
5042
  return out;}
4568
5043
  function len(a,b){return Math.hypot(a[0]-b[0],a[1]-b[1]);}
4569
5044
  // ── Column profile sections ─────────────────────────────────────────────────────────────────────
@@ -4916,11 +5391,14 @@ function columnSectionPoly(m){
4916
5391
  return Object.assign([[cx-r,cy-r],[cx+r,cy-r],[cx+r,cy+r],[cx-r,cy+r]],{placeholder:true});
4917
5392
  }
4918
5393
  const _polyStr=pts=>pts.map(p=>p[0].toFixed(1)+','+p[1].toFixed(1)).join(' ');
4919
- // Vector overlay: render THIS sheet's filter linework crisply (sharp, snappable, measurable) instead of
4920
- // the blurry raster JPEG. Vector PDFs expose filterElsForPlan(); a genuinely scanned sheet (no vectors)
4921
- // falls back to the RB64 raster. ponytail: all line d's are merged into ONE <path> so the browser parses
4922
- // one node, not thousands — fast to re-render on pan/zoom.
4923
- function hasOverlay(){const d=drawablePlan();return d?d.renders:!!RB64;} // F13: the active plan carries a reference sheet — vector linework or a scanned raster. Keyed on whether anything DRAWABLE actually paints, so a vector sheet whose every layer is hidden (or whose survivors are all text) greys the toggle out instead of offering to show a blank page; only a sheet with NO vectors falls through to the raster (#507)
5394
+ // Reference-sheet overlay: reuse THIS plan's reviewed Drawing Filter raster as inert source context,
5395
+ // then render the Filter linework crisply above it as the only snappable/measurable authority. The
5396
+ // resolver requires one unique sheet match and the same registered extent Drawing Filter uses; it never
5397
+ // copies the confidential bytes into plans[].raster_b64. A genuinely scanned legacy plan with no saved
5398
+ // Filter raster still falls back to RB64. ponytail: all line d's are merged into ONE <path> so the
5399
+ // browser parses one node, not thousands — fast to re-render on pan/zoom.
5400
+ function reviewedRaster(){return ReferenceSheet?ReferenceSheet.resolvePlanReferenceRaster(P,C&&C.filter):{ok:false,reason:'resolver-unavailable'};}
5401
+ function hasOverlay(){const r=reviewedRaster(),d=drawablePlan();return r.ok||(d?d.renders:!!RB64);} // F13: a reviewed raster is useful even when its vectors are absent/all non-drawable: the raster restores the source PDF's native printed context while remaining inert
4924
5402
  // #507: `filter.layers[].drawable === false` means "listed but not drawn (e.g. a text/title-block
4925
5403
  // layer)" — the schema's own words. Only the Steel Filter's row styling ever honoured it; the plan drew
4926
5404
  // every element regardless, so a reader that marked its noise non-drawable exactly as instructed still
@@ -4932,13 +5410,13 @@ function hasOverlay(){const d=drawablePlan();return d?d.renders:!!RB64;} // F1
4932
5410
  function nonDrawableLayers(){const f=C&&C.filter,out=new Set();
4933
5411
  for(const l of (f&&f.layers)||[]) if(l&&l.drawable===false&&typeof l.name==='string') out.add(l.name);
4934
5412
  return out;}
4935
- // The sheet's linework MINUS every non-drawable layer — the one set all three overlay consumers share
4936
- // (draw, snap, has-a-sheet), so what you can see, what you can snap to, and whether the toggle is even
4937
- // enabled can never disagree. null and [] mean DIFFERENT things and callers must keep them apart:
4938
- // null = this plan carries no vector overlay at all (a scanned sheet, so the raster IS the reference
4939
- // sheet); [] = it carries one but every layer of it is hidden, and the raster must NOT stand in for it
4940
- // — that bitmap is a picture of the whole sheet, so it would put the very text and title block the user
4941
- // suppressed straight back on screen.
5413
+ // The sheet's INTERACTIVE linework MINUS every non-drawable layer — the one set the vector draw and snap
5414
+ // consumers share, so a traced line that is excluded can never remain an invisible snap target. The
5415
+ // reviewed raster is a separate, inert source-image context and may still show that printed ink faintly.
5416
+ // null and [] mean DIFFERENT things and callers must keep them apart:
5417
+ // null = this plan carries no vector overlay at all; [] = it carries one but every vector layer is
5418
+ // excluded. Neither state authorizes a vector or a snap candidate. The reviewed source image, when
5419
+ // present, is resolved independently and never changes this set.
4942
5420
  // NOT folded into filterElsForPlan(): gridReadFromDrawing() reads the RAW set to detect the printed
4943
5421
  // grid, and the bubbles it hunts routinely sit on an annotation layer a reader would mark non-drawable.
4944
5422
  // Hiding them from the canvas must not blind the detector.
@@ -4967,17 +5445,20 @@ function drawablePlan(){
4967
5445
  return _draw;}
4968
5446
  function drawableElsForPlan(){const d=drawablePlan();return d?d.els:null;}
4969
5447
  function hiddenLayerCount(){const d=drawablePlan();return d?d.hidden:0;}
5448
+ function rasterImageSvg(r){const b=r.rect;return `<image class=pdfref aria-hidden=true href="data:image/jpeg;base64,${r.rasterB64}" x="${b.x}" y="${b.y}" width="${b.w}" height="${b.h}" preserveAspectRatio="none"/>`;}
4970
5449
  function overlaySvg(){
4971
5450
  if(!refSheetOn)return ''; // F13: reference sheet hidden → draw neither the raster/vector linework NOR the white pdfsheet backdrop
4972
- const d0=drawablePlan();
4973
- if(!d0)return RB64?`<image href="data:image/jpeg;base64,${RB64}" x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/>`:''; // no vectors at all: the scanned raster IS the reference sheet
4974
- if(!d0.renders)return ''; // vectors exist but nothing left will paint: draw NOTHING. Not the white backdrop (that reads as a failed read), and emphatically not RB64 — the raster pictures the WHOLE sheet, so it would put the suppressed text and title block straight back on screen
5451
+ const rr=reviewedRaster(),d0=drawablePlan();
5452
+ let out=rr.ok?`<rect class=pdfsheet x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/>${rasterImageSvg(rr)}`:'';
5453
+ if(!d0)return out||(RB64?`<image href="data:image/jpeg;base64,${RB64}" x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/>`:''); // legacy scanned plan: only when no reviewed Filter raster resolves
5454
+ if(!d0.renders)return out; // no drawable vectors means no path and no snap geometry; a reviewed raster may still provide inert printed context
4975
5455
  const els=d0.els;
4976
5456
  let d='',circ='';
4977
5457
  for(const e of els){if(!e)continue;
4978
5458
  if(e.kind==='line'){if(typeof e.d==='string'&&e.d)d+=e.d+' ';else if(e.x1!=null&&e.x2!=null)d+=`M${e.x1} ${e.y1}L${e.x2} ${e.y2}`;}
4979
5459
  else if(e.kind==='circle'&&e.r>0)circ+=`<circle cx="${e.cx}" cy="${e.cy}" r="${e.r}"/>`;}
4980
- return `<rect class=pdfsheet x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/><g class=pdfvec>${d?`<path d="${d}"/>`:''}${circ}</g>`;
5460
+ if(!out)out=`<rect class=pdfsheet x="${X0}" y="${Y0}" width="${X1-X0}" height="${Y1-Y0}"/>`;
5461
+ return `${out}<g class=pdfvec>${d?`<path d="${d}"/>`:''}${circ}</g>`;
4981
5462
  }
4982
5463
  // --- geometric edit: extend/trim (snap nearest end to a target line) + split at a point ---
4983
5464
  function lineX(p1,p2,p3,p4){const x1=p1[0],y1=p1[1],x2=p2[0],y2=p2[1],x3=p3[0],y3=p3[1],x4=p4[0],y4=p4[1];
@@ -5524,7 +6005,7 @@ function gridCancelLinePick(){if(gridLinePick&&gridLinePick.line)gridLinePick.li
5524
6005
  function planColumnCount(){let n=0;for(const m of ((P&&P.members)||[]))if(m.role==='column')n++;return n;}
5525
6006
  // The active plan's steel-filter elements (per-sheet linework the reader captured).
5526
6007
  function filterElsForPlan(){const f=C&&C.filter;if(!f)return null;
5527
- const sh=(f.sheets||[]).find(s=>s&&s.sheet&&P&&P.sheet&&s.sheet.toUpperCase()===P.sheet.toUpperCase());
6008
+ const match=ReferenceSheet&&ReferenceSheet.resolvePlanFilterSheet(P,f),sh=match&&match.ok?match.sheet:null;
5528
6009
  const els=sh&&sh.elements;
5529
6010
  return (Array.isArray(els)&&els.length)?els:null;}
5530
6011
  // Detect the printed grid in the sheet's linework (grid-core gridFromDrawing) and apply it. keep = an
@@ -5771,6 +6252,7 @@ function anyToolActive(){
5771
6252
  if(dimMode||dimChain||dimSplitMode||geoMode||csaxisMode||gridMode||gridPick||gridLinePick||dimStyleMode||mode==='add'||picking||cmTool||qdPick)return true; // 2D tools armed (cmTool = Move/Copy; qdPick = the F7 grid station pick)
5772
6253
  if(view3d&&window.Steel3DView){if(window.Steel3DView.clipMode&&window.Steel3DView.clipMode())return true;
5773
6254
  if(window.Steel3DView.refMeasureState&&window.Steel3DView.refMeasureState().armed)return true; // the reference measure owns the left-click too, so Space/Enter must not re-invoke the last command over it
6255
+ if(window.Steel3DView.connMemberPick&&window.Steel3DView.connMemberPick())return true; // the member pick owns ENTER (it confirms) — without this, Enter also fires repeatLast() and arms an unrelated tool behind the user
5774
6256
  const dm=document.getElementById('m3dDim');if(dm&&dm.classList.contains('on'))return true;} // 3D dim/clip armed
5775
6257
  return false;
5776
6258
  }
@@ -5980,8 +6462,14 @@ function stepSlotText(commandId){
5980
6462
  var typing=t&&(t.isContentEditable||t.tagName==='INPUT'||t.tagName==='TEXTAREA'||t.tagName==='SELECT');
5981
6463
  if(e.key==='?'&&typing)return; // F1 stays reachable while typing, by design
5982
6464
  try{
5983
- if(window.parent&&window.parent!==window&&typeof window.parent.__instructorKey==='function'){
5984
- if(window.parent.__instructorKey(e.key))e.preventDefault();
6465
+ if(window.parent&&window.parent!==window){
6466
+ /* The key came from THIS frame, so make it authoritative before the
6467
+ shell opens help. This repairs a missed startup-ready hand-off (or a
6468
+ hidden sibling frame becoming ready later) and gives the sheet the
6469
+ live carrier it needs to return focus to the exact control. */
6470
+ if(typeof window.parent.__instructorReady==='function')window.parent.__instructorReady(window);
6471
+ if(typeof window.parent.__instructorReport==='function')window.parent.__instructorReport(snapshot(),window);
6472
+ if(typeof window.parent.__instructorKey==='function'&&window.parent.__instructorKey(e.key))e.preventDefault();
5985
6473
  }
5986
6474
  }catch(err){/* cross-origin or torn-down parent */}
5987
6475
  },true);
@@ -6124,7 +6612,7 @@ function applyZoom(z,ax,ay){z=Math.max(ZMIN,Math.min(ZMAX,z));
6124
6612
  zoom=z;svg.setAttribute('width',EXTX*zoom);svg.setAttribute('height',EXTY*zoom);
6125
6613
  if(pt){const m=svg.getScreenCTM();stage.scrollLeft+=(m.a*pt.x+m.e)-ax;stage.scrollTop+=(m.d*pt.y+m.f)-ay;}
6126
6614
  document.getElementById('zRange').value=Math.round(zoom*100);
6127
- document.getElementById('zPct').textContent=Math.round(zoom*100)+'%';updateBadges();}
6615
+ document.getElementById('zPct').textContent=Math.round(zoom*100)+'%';updateBadges();refreshProfileLabelOverlay();}
6128
6616
  function zoomCentered(z){const r=stage.getBoundingClientRect();applyZoom(z,r.left+stage.clientWidth/2,r.top+stage.clientHeight/2);}
6129
6617
  function fitToWindow(){applyZoom(Math.min(stage.clientWidth/EXTX,stage.clientHeight/EXTY)*0.98);}
6130
6618
  // --- duplicate the selected member(s) in place (Ctrl+D) ---
@@ -6134,7 +6622,162 @@ function doDup(){const arr=sel2d();if(!arr.length)return;const o=12,pv=snapshot(
6134
6622
  mc.replaceEndpoints(c,[[s.wp[0][0]+o,s.wp[0][1]+o],[s.wp[1][0]+o,s.wp[1][1]+o]]); // replaces the wp array wholesale, as `c.wp=[[…],[…]]` did
6135
6623
  mc.addMembers(P,[c]);ns.add(c.id);}
6136
6624
  selIds=ns;selDimIds.clear();mode='sel';setMode();pushUndo(pv);render();}
6137
- function esc(s){return String(s).replace(/[<>&"]/g,c=>({'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'}[c]));}
6625
+ /* Matches REF_TREE_CAP / RC_CAP deliberately rather than minting a second cap number for the codebase.
6626
+ Past it the list says "Showing N of M" — a silent truncation would read as "that is all of them". */
6627
+ const REVIEW_LIST_CAP=300;
6628
+ let reviewFlyKind=null; // 'needs-review' | 'untracked' while the list is open
6629
+ function reviewCountsOf(){
6630
+ return {review:reviewSummary&&Array.isArray(reviewSummary.needsReview)?reviewSummary.needsReview.length:0,
6631
+ untracked:reviewSummary&&Array.isArray(reviewSummary.untracked)?reviewSummary.untracked.length:0};}
6632
+ /* Paint the two header counts. THE header surface, because in Plan (2D) the inspector, the breadcrumb and
6633
+ the 3D scene do not exist — this is the only place the state can appear there. */
6634
+ function renderReviewSurface(){
6635
+ const rs=document.getElementById('reviewStat'),us=document.getElementById('untrackedStat'),un=document.getElementById('reviewUnavailStat');
6636
+ if(!rs||!us||!un)return;
6637
+ // Unavailable hides both counts (a zero would be a claim the server did not make) and says so plainly,
6638
+ // because two hidden counts on their own are indistinguishable from a clean model.
6639
+ // The early return still has to carry the other surfaces: when the state becomes unavailable the amber
6640
+ // has to come OFF the 3D parts too, or the model keeps asserting a review state the server just
6641
+ // disclaimed. Returning before the sync was the same disagreement this whole function exists to avoid.
6642
+ if(reviewUnavailable||!reviewSummary){un.hidden=!reviewUnavailable;rs.hidden=true;us.hidden=true;closeReviewFly();syncReviewToScene();return;}
6643
+ un.hidden=true;
6644
+ const c=reviewCountsOf();
6645
+ rs.hidden=c.review===0;rs.classList.toggle('has',c.review>0);
6646
+ const rc=document.getElementById('reviewCount');if(rc)rc.textContent=String(c.review);
6647
+ us.hidden=c.untracked===0;
6648
+ const uc=document.getElementById('untrackedCount');if(uc)uc.textContent=String(c.untracked);
6649
+ // A list left open over a count that just went to zero would be a list of nothing.
6650
+ if(reviewFlyKind==='needs-review'&&!c.review)closeReviewFly();
6651
+ if(reviewFlyKind==='untracked'&&!c.untracked)closeReviewFly();
6652
+ if(reviewFlyKind)paintReviewFly(reviewFlyKind);
6653
+ syncReviewToScene();}
6654
+ /* The other two surfaces. The header is not the only place this state shows, and the review state can
6655
+ move without the geometry moving — so a repaint that updated only the counts would leave the 3D parts
6656
+ wearing their old colour and a selected connection's chip asserting the old state. Three surfaces
6657
+ derived from one summary must not be allowed to disagree. */
6658
+ function syncReviewToScene(){
6659
+ const v=window.Steel3DView;
6660
+ if(v&&v.setConnReview&&v.isReady&&v.isReady()){
6661
+ const map=new Map();
6662
+ if(reviewSummary&&!reviewUnavailable){
6663
+ for(const e of reviewSummary.needsReview||[])map.set(e.jointId,'needs-review');
6664
+ for(const e of reviewSummary.untracked||[])map.set(e.jointId,'untracked');
6665
+ }
6666
+ v.setConnReview(map);
6667
+ }
6668
+ /* Repaint the inspector ONLY when a whole custom connection is showing — that is the only view whose
6669
+ chip can go stale. Narrow on purpose: panel() rebuilds the inspector, and rebuilding it while the
6670
+ user is typing in one of its fields would discard the keystrokes. */
6671
+ const cs=(typeof connSelInfo==='function')?connSelInfo():null;
6672
+ if(cs&&cs.whole&&cs.joint&&cs.joint.kind==='custom')panel();}
6673
+ /* What the review record says about ONE joint, for the inspector. Reads the summary the transport
6674
+ installed — never the scene — so it is the same answer in Plan view, where no scene exists. */
6675
+ function reviewStateOf(jointId){
6676
+ if(reviewUnavailable)return 'unavailable';
6677
+ if(!reviewSummary)return 'clean';
6678
+ if((reviewSummary.needsReview||[]).some(r=>r.jointId===jointId))return 'needs-review';
6679
+ if((reviewSummary.untracked||[]).some(r=>r.jointId===jointId))return 'untracked';
6680
+ /* CLEAN-AND-ACCEPTED is its own state, not a decoration on clean. Reopen review is offered only here,
6681
+ and a chip that still read "Imported geometry" beside it would leave the user no on-screen evidence
6682
+ that anything was ever reviewed. Read from the SUMMARY, never from client history: a second tab, a
6683
+ reload and a reconnect would each get a remembered sign-off wrong. */
6684
+ if(reviewSignedOff(jointId))return 'signed-off';
6685
+ return 'clean';}
6686
+ /* The server reports which clean joints a human explicitly accepted, because only the store knows.
6687
+ Gated on the derived state being clean too (the server already does this) — a stale acceptance must
6688
+ never keep "Reopen review" on screen over a joint that is currently asking for review. */
6689
+ function reviewSignedOff(jointId){
6690
+ return !!(reviewSummary&&Array.isArray(reviewSummary.signedOff)&&reviewSummary.signedOff.indexOf(jointId)!==-1);}
6691
+ /* The custom-connection chip. It REPLACES the old neutral one rather than sitting beside it — this slot
6692
+ already was "what kind of connection is this", and a second chip would make the row say two things.
6693
+ Amber only for needs-review: untracked keeps the neutral colours and changes only its leading word, so
6694
+ it is distinguishable on read without ever suggesting a fault. */
6695
+ function reviewChipFor(jointId){
6696
+ const st=reviewStateOf(jointId);
6697
+ if(st==='needs-review')return '<span class=chip style="border-color:var(--warn-edge);color:var(--warn)" data-tip="The steel this connection is watching has moved since it was placed">Needs review — the steel it sits on moved</span>';
6698
+ if(st==='untracked')return '<span class=chip style="border-color:var(--line);color:var(--mut)" data-tip="Steel moving under this connection will not be flagged — place it again to start watching it">Untracked — move / replace only</span>';
6699
+ // Not grey: grey would be indistinguishable from clean and would claim a confidence the server did not
6700
+ // give. Cyan is this file's existing "informational, not an error" idiom.
6701
+ if(st==='unavailable')return '<span class=chip style="border-color:var(--cyan-edge);color:var(--cyan);background:var(--cyan-soft)" data-tip="The server could not check this connection for moved steel this time">Review status unavailable</span>';
6702
+ /* Green, through the EXISTING `.chip.verified` recipe whose token is already commented "human-confirmed"
6703
+ — the same idea, so it gets the same colour rather than a new one. */
6704
+ if(st==='signed-off')return '<span class="chip verified" data-tip="Someone confirmed this connection against the steel it sits on — it is still being watched">✓ Reviewed — checked against this steel</span>';
6705
+ // The clean state gets a tooltip too. Every other state explains itself on hover, and a chip that is
6706
+ // the only silent one reads as an oversight rather than a decision.
6707
+ return '<span class=chip style="border-color:var(--line);color:var(--mut)" data-tip="This connection is being watched — the steel it was placed against has not moved">Imported geometry — move / replace only</span>';}
6708
+ /* The DRILLED-PART chip. It names the connection explicitly, because the part's own kind (Bolt, Plate…)
6709
+ is the first thing on screen and a bare "Needs review" there would read as "this bolt needs review".
6710
+ Shown only for needs-review and unavailable: 3D selection out-ranks the amber lift, so without this the
6711
+ warning would disappear entirely while a part is selected. Untracked is omitted on purpose — it never
6712
+ had a lift to lose, and repeating it on every bolt of a legacy connection is noise. */
6713
+ function partReviewChipFor(jointId){
6714
+ const st=reviewStateOf(jointId);
6715
+ if(st==='needs-review')return '<div class=row style="margin:2px 0 4px"><span class=chip style="border-color:var(--warn-edge);color:var(--warn)" data-tip="The parent connection is flagged — step back to it to act">Connection needs review</span></div>';
6716
+ if(st==='unavailable')return '<div class=row style="margin:2px 0 4px"><span class=chip style="border-color:var(--cyan-edge);color:var(--cyan);background:var(--cyan-soft)">Connection review unavailable</span></div>';
6717
+ return '';}
6718
+ function closeReviewFly(){
6719
+ const fly=document.getElementById('reviewFly');if(fly)fly.classList.remove('open');
6720
+ for(const id of ['reviewStat','untrackedStat']){const b=document.getElementById(id);if(b)b.setAttribute('aria-expanded','false');}
6721
+ reviewFlyKind=null;}
6722
+ function paintReviewFly(kind){
6723
+ const list=document.getElementById('reviewFlyList'),title=document.getElementById('reviewFlyTitle'),
6724
+ cnt=document.getElementById('reviewFlyCount'),more=document.getElementById('reviewFlyMore');
6725
+ if(!list||!reviewSummary)return;
6726
+ const rows=kind==='needs-review'?(reviewSummary.needsReview||[]):(reviewSummary.untracked||[]);
6727
+ title.textContent=kind==='needs-review'?'Needs review':'Not watched';
6728
+ cnt.textContent=String(rows.length);
6729
+ const shown=rows.slice(0,REVIEW_LIST_CAP);
6730
+ list.innerHTML=shown.map(r=>{
6731
+ const j=(Array.isArray(C.joints)?C.joints:[]).find(x=>x&&x.id===r.jointId);
6732
+ const nm=esc((j&&j.name)||r.jointId);
6733
+ const sub=kind==='needs-review'?esc((r.memberIds||[]).length+' member'+((r.memberIds||[]).length===1?'':'s')):'not watched';
6734
+ // The instance key names what the row acts on, so the guidance band reads "Selects <that connection>"
6735
+ // rather than printing "{instance}" verbatim. Escaped — a connection is user-named.
6736
+ // The instance LABEL as well as the key: an unnamed joint would otherwise have `?` narrate its raw id.
6737
+ return '<button data-command-id="steel.review-select#'+esc((j&&j.name)||r.jointId)+'" data-command-instance-label="'+esc((j&&j.name)||('connection '+r.jointId))+'" class=frow data-joint="'+esc(r.jointId)+'"><span class=nm>'+nm+'</span><span class=sub>'+sub+'</span></button>';
6738
+ }).join('');
6739
+ more.hidden=rows.length<=REVIEW_LIST_CAP;
6740
+ if(!more.hidden)more.textContent='Showing '+shown.length+' of '+rows.length+'.';
6741
+ for(const b of list.querySelectorAll('.frow'))b.onclick=()=>selectReviewedJoint(b.getAttribute('data-joint'),kind);}
6742
+ function openReviewFly(kind,trigger){
6743
+ if(!reviewSummary||reviewUnavailable)return;
6744
+ if(reviewFlyKind===kind){closeReviewFly();return;} // the trigger toggles
6745
+ reviewFlyKind=kind;paintReviewFly(kind);
6746
+ const fly=document.getElementById('reviewFly');if(!fly||!trigger)return;
6747
+ const r=trigger.getBoundingClientRect();fly.style.left=Math.max(8,Math.min(r.left,window.innerWidth-266))+'px';fly.style.top=(r.bottom+6)+'px';
6748
+ fly.classList.add('open');
6749
+ for(const id of ['reviewStat','untrackedStat']){const b=document.getElementById(id);if(b)b.setAttribute('aria-expanded',String(id===(kind==='needs-review'?'reviewStat':'untrackedStat')));}
6750
+ const first=fly.querySelector('.frow');if(first)first.focus();}
6751
+ /* A needs-review row selects the MEMBERS the user named — they exist in the contract, so this works in
6752
+ Plan view where the joint itself has no representation. An untracked row has no members recorded, so
6753
+ the only thing it can point at is the joint, which is a 3D-only object. */
6754
+ async function selectReviewedJoint(jointId,kind){
6755
+ const entry=kind==='needs-review'?(reviewSummary.needsReview||[]).find(r=>r.jointId===jointId):null;
6756
+ closeReviewFly();
6757
+ if(entry&&(entry.memberIds||[]).length){selIds=new Set(entry.memberIds);selDimIds.clear();sel3dDimIds.clear();selGridIds.clear();render();return;}
6758
+ /* No members recorded, so the joint itself is the only thing to point at — and a custom connection is a
6759
+ 3D-only object, with no representation in the plan. Switch first, then select.
6760
+
6761
+ THROUGH setView, and NOT through applyViewState. applyViewState is the chrome half — it flips the
6762
+ toggle and swaps the panes. setView is the half that calls init(), show() and awaits rebuild(). Going
6763
+ round it left the pane blank and frozen (no meshes to select, no render loop), and stuck: viewMode was
6764
+ already '3d', so a later setView('3d') is a no-op and no edit repairs it, because sync3D gates on
6765
+ view3dShown && view3dReady. This is the COMMON path — every pre-existing connection is untracked. */
6766
+ if(viewMode==='2d')await setView('3d');
6767
+ /* And only select if we ACTUALLY got there. setView has its own refusal path — no renderer, or a newer
6768
+ view request superseding this one — after which it leaves the tab in 2D. Selecting anyway would put a
6769
+ selection somewhere the user cannot see and cannot clear. */
6770
+ if(viewMode!=='3d'){toast('Open the 3D view to see this connection');return;}
6771
+ if(window.Steel3DView&&window.Steel3DView.selectWholeConn)window.Steel3DView.selectWholeConn(jointId);}
6772
+ /* Publish the renderer for the boot-scope transport, and paint ONCE right now.
6773
+ The initial paint is not optional: boot() installs the snapshot's review summary BEFORE main() runs,
6774
+ so that first repaint finds no renderer on `window` and is a no-op. Without this line the counts stay
6775
+ hidden until something else happens to move the review state — which on a quiet model is never. */
6776
+ window.renderReviewSurface=renderReviewSurface;
6777
+ renderReviewSurface();
6778
+ // Keep this tiny helper regex-free: source-slice.mjs deliberately refuses to guess whether `/` begins
6779
+ // a regex, and security tests lift this exact production function to prove hostile connection names stay inert.
6780
+ function esc(s){const entities={'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;'};return String(s).split('').map(c=>entities[c]||c).join('');}
6138
6781
  function memberEndReviewSvg(){
6139
6782
  if(!memberEndReview||NO_PLAN_VIEW||!P||!P.members)return '';
6140
6783
  const f=memberEndReview.report.findings[memberEndReview.focus];if(!f)return '';
@@ -6148,7 +6791,57 @@ function memberEndReviewSvg(){
6148
6791
  const pt=projected[Math.max(0,chosenIndex)];if(pt)out+=`<text class=mer-label x="${(start[0]+pt[0])/2}" y="${(start[1]+pt[1])/2-8/zoom}" style="font-size:${11/zoom}px">${esc(fmtFtIn(memberEndDistance(f,targets[Math.max(0,chosenIndex)])/25.4))}</text>`;
6149
6792
  return out+'</g>';
6150
6793
  }
6794
+ let profileLabelState={labels:[],source:'none',hidden:0,message:null,diagnostic:null};
6795
+ function profilePickViewport(){
6796
+ try{
6797
+ const m=svg.getScreenCTM().inverse(),r=stage.getBoundingClientRect(),p=svg.createSVGPoint();
6798
+ p.x=r.left;p.y=r.top;const a=p.matrixTransform(m);p.x=r.right;p.y=r.bottom;const b=p.matrixTransform(m);
6799
+ return [Math.min(a.x,b.x),Math.min(a.y,b.y),Math.max(a.x,b.x),Math.max(a.y,b.y)];
6800
+ }catch(_){return [X0,Y0,X1,Y1];}
6801
+ }
6802
+ function profilePickProfiles(){return [...profileCatalogValues(),...Object.keys(WT||{}),...(C.members||[]).map(m=>m&&m.profile).filter(Boolean)];}
6803
+ function profileLabelQuery(allowFallback){
6804
+ return DetailRefs.planProfileLabelOverlay(P,allowFallback?C.filter:null,{profiles:profilePickProfiles(),viewport:profilePickViewport(),max:500});
6805
+ }
6806
+ function profilePickGuidance(){const armed=picking&&pickKind==='profile';return (armed&&profileLabelState.diagnostic)||profileLabelState.message||'Choose a highlighted profile label by click, Enter, or Space.';}
6807
+ function profileLabelFocusKey(lb){return lb.text+'@'+lb.disp[0]+','+lb.disp[1];}
6808
+ function profileLabelMarkup(labels){let out='';for(const lb of labels){const w=Math.max(40,lb.text.length*11);
6809
+ out+=`<rect class=lblhot data-command-id="steel.apply-profile-label#${esc(lb.text)}" data-command-instance-label="${esc(lb.text)}" data-prof="${esc(lb.text)}" data-pick-key="${esc(profileLabelFocusKey(lb))}" role="button" tabindex="0" x="${lb.disp[0]-w/2}" y="${lb.disp[1]-10}" width="${w}" height="20" rx="3" aria-label="Apply profile ${esc(lb.text)}"></rect><text class=lbltx x="${lb.disp[0]}" y="${lb.disp[1]+4}">${esc(lb.text)}</text>`;}return out;}
6810
+ function profilePickerFocusToken(){const active=document.activeElement;if(!active)return null;
6811
+ if(active.id==='addPick'||active.id==='pickProf')return {kind:'control',id:active.id};
6812
+ if(active.classList&&active.classList.contains('lblhot'))return {kind:'label',key:active.dataset.pickKey,ownerId:mode==='add'?'addPick':'pickProf'};
6813
+ return null;}
6814
+ function restoreProfilePickerFocus(token){if(!token)return false;let target=null;
6815
+ if(token.kind==='control')target=document.getElementById(token.id);
6816
+ else{const group=document.getElementById('profileLabelOverlay');if(group)for(const el of group.querySelectorAll('.lblhot'))if(el.dataset.pickKey===token.key){target=el;break;}if(!target&&token.ownerId)target=document.getElementById(token.ownerId);}
6817
+ if(!target||typeof target.focus!=='function')return false;target.focus({preventScroll:true});return true;}
6818
+ // Applying a keyboard-focused SVG hotspot rebuilds the SVG inside that same keydown dispatch. Chromium
6819
+ // finalises focus for the removed SVG node only after the handler returns, which can overwrite render()'s
6820
+ // synchronous focus restoration and leave focus on <body>. Re-home it on the next task, but only while
6821
+ // focus is still nowhere useful so an intervening user/script focus move is never stolen.
6822
+ function restoreProfilePickerOwnerAfterApply(id){const rehome=()=>{const active=document.activeElement;
6823
+ if(active&&active!==document.body&&active!==svg)return;const target=document.getElementById(id);
6824
+ if(target&&typeof target.focus==='function')target.focus({preventScroll:true});};
6825
+ // The immediate task covers removal of the SVG event target. sync3D can repaint the inspector after its
6826
+ // first async scene refresh, so repeat across that boundary; every attempt refuses to steal meaningful focus.
6827
+ setTimeout(rehome,0);setTimeout(rehome,100);setTimeout(rehome,250);}
6828
+ function reflectProfilePickGuidance(){
6829
+ for(const el of document.querySelectorAll('[data-profile-pick-status]'))el.textContent=profilePickGuidance();
6830
+ }
6831
+ function refreshProfileLabelOverlay(){
6832
+ const group=document.getElementById('profileLabelOverlay');if(!group)return;
6833
+ const focusToken=profilePickerFocusToken();
6834
+ const armed=picking&&pickKind==='profile';profileLabelState=profileLabelQuery(armed);
6835
+ group.replaceChildren();
6836
+ for(const lb of profileLabelState.labels){const w=Math.max(40,lb.text.length*11),rect=document.createElementNS('http://www.w3.org/2000/svg','rect'),label=document.createElementNS('http://www.w3.org/2000/svg','text');
6837
+ rect.setAttribute('class','lblhot');rect.dataset.commandId='steel.apply-profile-label#'+lb.text;rect.dataset.commandInstanceLabel=lb.text;rect.dataset.prof=lb.text;rect.dataset.pickKey=profileLabelFocusKey(lb);rect.setAttribute('role','button');rect.setAttribute('tabindex','0');rect.setAttribute('aria-label','Apply profile '+lb.text);rect.setAttribute('x',lb.disp[0]-w/2);rect.setAttribute('y',lb.disp[1]-10);rect.setAttribute('width',w);rect.setAttribute('height',20);rect.setAttribute('rx',3);
6838
+ label.setAttribute('class','lbltx');label.setAttribute('x',lb.disp[0]);label.setAttribute('y',lb.disp[1]+4);label.textContent=lb.text;group.append(rect,label);
6839
+ }
6840
+ reflectProfilePickGuidance();
6841
+ restoreProfilePickerFocus(focusToken);
6842
+ }
6151
6843
  function render(){
6844
+ const profileFocusToken=profilePickerFocusToken();
6152
6845
  /* The Instructor's second publish trigger, and the one that catches what input
6153
6846
  events cannot: an arm or disarm inside a PROMISE callback (an async contract
6154
6847
  load, an awaited edit) resolves long after the macrotask the originating
@@ -6166,7 +6859,7 @@ function render(){
6166
6859
  buildColorRank(); // refresh the model-global colour rank before any colorFor() call below (B2 — keeps 2D hues stable across plans + matched to 3D)
6167
6860
  reanchorAllPlans(); // F9: glue magnetic dims to their members BEFORE anything reads P.dims — covers every mutation path that ends in a render()
6168
6861
  if(geoMode&&(selIds.size<1||(geoMode==='split'&&selIds.size!==1))){geoMode=null;setGeo();} // Split needs exactly one member; Extend/Trim works on any selection. setGeo() clears BOTH geo + geoel (not a bare remove('geo')) so the grid affordance can't outlive the tool
6169
- let s=overlaySvg(); // crisp vector linework (snappable) when the sheet has vectors; raster only for scanned PDFs
6862
+ let s=overlaySvg(); // reviewed source image (inert) beneath crisp Filter vectors (the only snap authority)
6170
6863
  s+=gridSvg(); // structural grid under the linework (members/dims stay on top)
6171
6864
  for(const sg of P.segments) s+=`<line class=seg data-seg="${sg.id}" x1="${sg.a[0]}" y1="${sg.a[1]}" x2="${sg.b[0]}" y2="${sg.b[1]}"/>`;
6172
6865
  for(const m of P.members){const c=colorFor(m.profile);const sel=selIds.has(m.id);const fh=findHits.has(m.id);const on=sel||fh;const g=on?` style="filter:drop-shadow(0 0 3px ${c}) drop-shadow(0 0 8px ${c})"`:'';
@@ -6188,8 +6881,10 @@ function render(){
6188
6881
  const _sty=(_fx||_sw||_sd)?` style="${_fx}${_sw}${_sd}"`:'';
6189
6882
  s+=`<line class="member${rfi?' rfi':''}${sel?' sel':''}${fh?' find-hit':''}" data-id="${m.id}" x1="${m.wp[0][0]}" y1="${m.wp[0][1]}" x2="${m.wp[1][0]}" y2="${m.wp[1][1]}" stroke="${c}"${_sty}/>`;}
6190
6883
  {const hsel=sel2d();if(hsel.length>=1){const HR=epR();for(const sm of hsel)for(let i=0;i<2;i++) s+=`<circle class="handle ${i===0?'ep-start':'ep-end'}" data-mid="${sm.id}" data-h="${i}" cx="${sm.wp[i][0]}" cy="${sm.wp[i][1]}" r="${HR}"/>`;}} // end 1 (start) yellow, end 2 (end) magenta · shown for every selected member · radius grows with zoom (epR) so it stays visible against the thick line
6191
- if((mode==='add'||(picking&&pickKind==='profile'))&&P.labels) for(const lb of P.labels){const w=Math.max(40,lb.text.length*11);
6192
- s+=`<rect class=lblhot data-prof="${esc(lb.text)}" x="${lb.disp[0]-w/2}" y="${lb.disp[1]-10}" width="${w}" height="20" rx="3"><title>${esc(lb.text)}</title></rect>`;}
6884
+ if(mode==='add'||(picking&&pickKind==='profile')){
6885
+ const armed=picking&&pickKind==='profile';profileLabelState=profileLabelQuery(armed);
6886
+ s+=`<g id=profileLabelOverlay>${profileLabelMarkup(profileLabelState.labels)}</g>`;
6887
+ }
6193
6888
  // One hot-zone per PHYSICAL callout bubble — details[] AND callouts[], undeduplicated, because you pick
6194
6889
  // the bubble beside the end you are detailing. Reading details[] alone left nothing to click on a set
6195
6890
  // whose reader landed everything in callouts[] (#397), which made binding a detail — and so everything
@@ -6230,7 +6925,7 @@ function render(){
6230
6925
  // `profs` and `detTexts()` live — so the combobox offers the same list with no mirror to keep filled.
6231
6926
  // Deleting the elements while these two writes stayed made render() throw on null here, which also
6232
6927
  // killed every call after it on this line (stats/panel/upd*/syncDisplayRows). Measured in Chromium.
6233
- svg.innerHTML=s; stats(); panel(); updUR(); updDup(); updateMemberEndStatus(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncDisplayRows();
6928
+ svg.innerHTML=s; stats(); panel(); updUR(); updDup(); updateMemberEndStatus(); updConf(); updCS(); updConnBtn(); updBpBtn(); updSpBtn(); syncDisplayRows();restoreProfilePickerFocus(profileFocusToken);
6234
6929
  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()).
6235
6930
  if(view3dShown&&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)
6236
6931
  try{updateConnCrumb();}catch(_){} // Connection Component breadcrumb follows the selection (3D-only; hidden at root)
@@ -6467,12 +7162,12 @@ function refPanelPreempted(){
6467
7162
  }
6468
7163
  function renderMemberEndPanel(p){
6469
7164
  const state=memberEndReview,rows=state.report.findings,groups=new Map();rows.forEach((f,i)=>{const g=memberEndGroup(f);if(!groups.has(g))groups.set(g,[]);groups.get(g).push([f,i]);});
6470
- const actionable=rows.filter(f=>f.classification==='needs-review'&&state.chosen.has(memberEndKey(f))),selected=actionable.filter(f=>state.selected.has(memberEndKey(f))).length;
7165
+ const canChoose=rows.filter(f=>f.classification==='needs-review'&&(f.targets||[]).length>0),readyToSelect=canChoose.filter(f=>state.chosen.has(memberEndKey(f))),selected=readyToSelect.filter(f=>state.selected.has(memberEndKey(f))).length;
6471
7166
  const historyAction=memberEndHistoryAction(state.undoDirection);
6472
7167
  p.setAttribute('aria-busy',String(!!state.busy));p.setAttribute('aria-labelledby','memberEndReviewTitle');
6473
7168
  const disabled=state.busy?' disabled':'';
6474
7169
  let html=`<div class=mer-head><div><div class=mer-title id=memberEndReviewTitle>Member ends short of support centerlines</div><div class=hint>${memberEndUnresolved(state.report)} unresolved end${memberEndUnresolved(state.report)===1?'':'s'} on ${new Set(rows.map(f=>f.memberId)).size} member${new Set(rows.map(f=>f.memberId)).size===1?'':'s'}</div></div><button id=merDone data-command-id="steel.member-end-review-close" class=ghost data-tip="Close member-end review"${disabled}>Done</button></div>`;
6475
- const toolbar=[];if(actionable.length>selected)toolbar.push(`<button id=merAll data-command-id="steel.member-end-select-all" class=ghost${disabled}>Select all</button>`);if(selected)toolbar.push(`<button id=merClear data-command-id="steel.member-end-select-clear" class=ghost${disabled}>Clear</button>`);html+=`<div class=mer-toolbar>${toolbar.join('')}<span class=hint>${selected} selected</span></div>`;
7170
+ const toolbar=[];if(readyToSelect.length>selected)toolbar.push(`<button id=merAll data-command-id="steel.member-end-select-all" class=ghost${disabled}>Select all</button>`);if(selected)toolbar.push(`<button id=merClear data-command-id="steel.member-end-select-clear" class=ghost${disabled}>Clear</button>`);html+=`<div class=mer-toolbar>${toolbar.join('')}<span class=hint>${selected} selected</span></div>`;
6476
7171
  for(const [group,items] of groups){html+=`<section class=mer-group><div class=mer-group-title>${esc(group)}</div>`;for(const [f,i] of items){const key=memberEndKey(f),target=state.chosen.get(key),checked=state.selected.has(key),canCheck=f.classification==='needs-review'&&!!target;
6477
7172
  const evidence=target?memberEndTargetName(target)+' · Extend '+fmtFtIn(memberEndDistance(f,target)/25.4):memberEndReason(f)||memberEndClassification(f);
6478
7173
  html+=`<div class="mer-row${i===state.focus?' focused':''}" data-mer-row="${i}">${canCheck?`<input type=checkbox data-mer-check="${i}" data-command-id="steel.member-end-select#${esc(f.memberId+' end '+(f.end+1))}" aria-label="Include ${esc(f.memberId)} end ${f.end+1}" ${checked?'checked':''}${disabled}>`:'<span aria-hidden=true></span>'}<div><label${canCheck?` for="merCheck${i}"`:''}>${esc(memberEndRole(f)+' '+f.memberId+' · End '+(f.end+1))}</label><div class=mer-evidence>${esc(evidence)}</div><div class=mer-actions>`;
@@ -6484,10 +7179,10 @@ function renderMemberEndPanel(p){
6484
7179
  html+='</div></div></div>';}
6485
7180
  html+='</section>';}
6486
7181
  html+=`<div class=mer-nav><button id=merPrev data-command-id="steel.member-end-review-nav#previous" class=ghost${disabled}>Previous</button><button id=merNext data-command-id="steel.member-end-review-nav#next" class=ghost${disabled}>Next</button>${state.undoToken?`<button id=merUndo data-command-id="steel.member-end-history#${esc(historyAction.label)}" class=ghost data-tip="${historyAction.tip}"${disabled}>${historyAction.label}</button>`:''}</div><div class=mer-live role=status aria-live=polite aria-atomic=true>${esc(state.live||'')}</div>`;
6487
- if(selected)html+=`<button id=merApply data-command-id="steel.member-end-apply" class=mer-primary${disabled}>${state.busy?'Working…':'Extend '+selected+' end'+(selected===1?'':'s')+' to centerlines'}</button>`;else html+='<div class=hint style="margin-top:9px">No ends selected</div>';
7182
+ if(selected)html+=`<button id=merApply data-command-id="steel.member-end-apply" class=mer-primary${disabled}>${state.busy?'Working…':'Extend '+selected+' end'+(selected===1?'':'s')+' to centerlines'}</button>`;else html+=`<div class=hint style="margin-top:9px">${canChoose.length?'No ends selected':'No endpoints are available to extend'}</div>`;
6488
7183
  p.innerHTML=html;
6489
7184
  const done=document.getElementById('merDone');if(done)done.onclick=closeMemberEndReview;
6490
- const all=document.getElementById('merAll');if(all)all.onclick=()=>{for(const f of actionable)state.selected.add(memberEndKey(f));panel();};
7185
+ const all=document.getElementById('merAll');if(all)all.onclick=()=>{for(const f of readyToSelect)state.selected.add(memberEndKey(f));panel();};
6491
7186
  const clear=document.getElementById('merClear');if(clear)clear.onclick=()=>{state.selected.clear();panel();};
6492
7187
  p.querySelectorAll('[data-mer-row]').forEach(row=>row.addEventListener('click',e=>{if(e.target.closest('button,input'))return;focusMemberEnd(+row.dataset.merRow);}));
6493
7188
  p.querySelectorAll('[data-mer-check]').forEach(input=>{input.id='merCheck'+input.dataset.merCheck;input.onchange=()=>{const f=rows[+input.dataset.merCheck],key=memberEndKey(f);input.checked?state.selected.add(key):state.selected.delete(key);state.focus=+input.dataset.merCheck;panel();render();};input.onfocus=()=>{state.focus=+input.dataset.merCheck;selIds=new Set([rows[state.focus].memberId]);if(view3dShown&&window.Steel3DView)window.Steel3DView.setSelection(selIds);};});
@@ -6501,6 +7196,17 @@ function renderMemberEndScanPanel(p){
6501
7196
  p.innerHTML=`<div class=mer-head><div><div class=mer-title id=memberEndScanTitle>${state.error?'Member-end check needs attention':'Checking member ends'}</div><div class=hint>Drawing and model evidence</div></div></div><div class=mer-live role=status aria-live=polite aria-atomic=true>${esc(state.live)}</div>${state.error?'<button id=merRetry data-command-id="steel.member-end-retry" class=mer-primary>Check again</button>':''}`;
6502
7197
  const retry=document.getElementById('merRetry');if(retry)retry.onclick=()=>scanMemberEnds();
6503
7198
  }
7199
+ function nativeElevationContextHtml(){
7200
+ const plan=(C.plans||[])[C.active]||{},values=[];let unknown=0;
7201
+ for(const member of P.members||[])for(const end of member.ends||[]){const raw=end&&end.tos,value=raw==null?NaN:Number(raw);if(Number.isFinite(value))values.push(value);else unknown++;}
7202
+ const range=!values.length?'No finite visible endpoints':(Math.min(...values)===Math.max(...values)
7203
+ ?fmtFtIn(values[0]):fmtFtIn(Math.min(...values))+' to '+fmtFtIn(Math.max(...values)));
7204
+ const planElevation=Number.isFinite(plan.elevation_in)?fmtFtIn(plan.elevation_in):'Not recorded';
7205
+ return '<div style="border-top:1px solid var(--line);margin-top:12px;padding-top:12px"><div class=sect>Elevation context</div>'+
7206
+ '<div class=hint style="margin:0 0 5px;font-size:11px">Plan elevation <b>'+esc(planElevation)+'</b> ('+esc(P.sheet)+')</div>'+
7207
+ '<div class=hint style="margin:0 0 5px;font-size:11px">Visible member endpoints <b>'+esc(range)+'</b>'+ (unknown?' · '+unknown+' unknown':'') +'</div>'+
7208
+ '<div class=hint style="margin:0;font-size:11px">Member elevations are explicit in this model. Select a member to inspect or edit its endpoints.</div></div>';
7209
+ }
6504
7210
  function panel(){
6505
7211
  const p=document.getElementById('panel');
6506
7212
  p.removeAttribute('aria-busy');p.removeAttribute('aria-labelledby');
@@ -6609,8 +7315,8 @@ function panel(){
6609
7315
  p.innerHTML=`<span class=badge>Add member</span>
6610
7316
  ${memberTypeField('mTypeA',[{memberType:addType}])}
6611
7317
  <div class=sect style="margin-top:8px">Current profile</div>
6612
- <div style="display:flex;gap:6px"><input data-command-id="steel.add-profile" aria-label="Current profile" id=addProf class=combo data-src=profiles placeholder="type or pick (e.g. W16X26)" value="${esc(addProfile)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-profile-catalog" id=profileBrowseA class=ghost data-tip="Browse the active environment profile catalog">Browse</button><button data-command-id="steel.pick-profile" id=addPick class="ghost${pk?' on':''}" data-tip="Pick profile by clicking a label in the drawing">⌖ pick</button></div>
6613
- <div class=hint id=pickHint style="margin-top:4px;font-style:italic${pk?';color:var(--brand)':''}">${pk?'Click a profile label in the drawing…':'or click a label in the drawing'}</div>
7318
+ <div style="display:flex;gap:6px"><input data-command-id="steel.add-profile" aria-label="Current profile" id=addProf class=combo data-src=profiles placeholder="type or pick (e.g. W16X26)" value="${esc(addProfile)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-profile-catalog" id=profileBrowseA class=ghost data-tip="Browse the active environment profile catalog">Browse</button><button data-command-id="steel.pick-profile" id=addPick class="ghost${pk?' on':''}" aria-pressed="${pk?'true':'false'}" data-tip="Pick profile from drawing labels by click, Enter, or Space">⌖ pick</button></div>
7319
+ <div class=hint id=pickHint data-profile-pick-status role=status aria-live=polite style="margin-top:4px;font-style:italic${pk?';color:var(--brand)':''}">${esc(profilePickGuidance())}</div>
6614
7320
  <div class=elab style="margin-top:9px">Material grade</div>
6615
7321
  <div style="display:flex;gap:6px"><input data-command-id="steel.add-material" aria-label="Material grade" id=addMat class=combo data-src=materials placeholder="Profile default · ${esc(profileDefaultMaterial(addProfile))}" value="${esc(addMaterial)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-material-catalog" id=materialBrowseA class=ghost data-tip="Browse structural member grades">Browse</button></div>
6616
7322
  <div class=divrow><hr></div>
@@ -6674,10 +7380,27 @@ function panel(){
6674
7380
  if(j.kind==='custom'){
6675
7381
  const nm=j.name?esc(j.name):'Imported connection';
6676
7382
  const onLine=j.main?`On <button data-command-id="steel.connection-select-member" class=pilllink id=cmpMember data-tip="Select ${esc(j.main)}">${esc(j.main)}</button> · `:'';
7383
+ /* THE REVIEW ACTIONS GET THEIR OWN ROW, above the connection-management one. Not tidiness: the row
7384
+ below ends with a destructive Delete, and the review actions are the most-clicked thing on this
7385
+ pane while a connection is flagged — a single six-wide wrapping row would land them adjacent. The
7386
+ row break is what keeps Delete structurally isolated rather than incidentally distant.
7387
+
7388
+ HIDDEN, never disabled, when they do not apply — the house rule. Mark-as-reviewed and Reopen are
7389
+ mutually exclusive by construction (a joint cannot be both needs-review and clean-and-accepted),
7390
+ so this row is at most two buttons wide. Neither shows while the state is `unavailable`: letting
7391
+ someone assert an acceptance over a baseline the server could not even report would be a worse
7392
+ claim than showing nothing. */
7393
+ const rst=reviewStateOf(j.id);
7394
+ const reviewRow=[
7395
+ rst==='needs-review'?`<button data-command-id="steel.connection-sign-off" class=ghostw id=cmpSign data-tip="Confirms this connection still fits the steel it sits on now. This is a sign-off record, not a model edit — Ctrl+Z will not undo it.">✓ Mark as reviewed</button>`:'',
7396
+ rst==='signed-off'?`<button data-command-id="steel.connection-reopen" class=ghostw id=cmpReopen data-tip="Clears the sign-off, so this connection asks to be checked again. Also a record rather than a model edit — Ctrl+Z will not undo it.">Reopen review</button>`:'',
7397
+ `<button data-command-id="steel.connection-replace" class="ghostw${connReplaceArm===j.id?' on':''}" id=cmpAgain data-tip="Click where this connection sits, then name the members it joins — the only way to start watching an untracked one. It stops being watched until you finish.">⌖ Place again…</button>`,
7398
+ ].join('');
6677
7399
  p.innerHTML=`<span class=badge>Custom connection</span>
6678
- <div class=row style="margin:0 0 6px"><span class=chip style="border-color:var(--line);color:var(--mut)">Imported geometry — move / replace only</span></div>
7400
+ <div class=row style="margin:0 0 6px">${reviewChipFor(j.id)}</div>
6679
7401
  <div class="row hint" style="margin:0 0 2px">${onLine}${cs.childIds.length} parts · ${nm}</div>
6680
7402
  <div class="row hint" style="margin:0 0 6px;font-size:11px">Read from IFC — opaque tessellated geometry (no per-dimension edit). <b>Esc</b> steps back.</div>
7403
+ <div class="row f" style="gap:6px;flex-wrap:wrap;margin:0 0 8px">${reviewRow}</div>
6681
7404
  <div class=divrow><hr></div>
6682
7405
  <div class="row f" style="gap:6px;flex-wrap:wrap">
6683
7406
  <button data-command-id="steel.connection-modify-request" class=ghostw id=cmpAsk data-tip="Record a request for your terminal AI to move / replace this connection">Modify connection…</button>
@@ -6685,6 +7408,9 @@ function panel(){
6685
7408
  <button data-command-id="steel.connection-favourite" class=ghostw id=cmpFav data-tip="Save this imported geometry to your Favourites — drops in place, will not re-fit">★ Save to Favourites</button>
6686
7409
  </div>`;
6687
7410
  {const b=document.getElementById('cmpMember');if(b)b.onclick=()=>{if(window.Steel3DView&&window.Steel3DView.clearConnSel)window.Steel3DView.clearConnSel();selIds=new Set([j.main]);selDimIds.clear();sel3dDimIds.clear();selGridIds.clear();render();};}
7411
+ {const b=document.getElementById('cmpSign');if(b)b.onclick=()=>signOffConnection(j.id);}
7412
+ {const b=document.getElementById('cmpReopen');if(b)b.onclick=()=>reopenConnectionReview(j.id);}
7413
+ {const b=document.getElementById('cmpAgain');if(b)b.onclick=()=>armConnectionReplace(j.id);}
6688
7414
  {const b=document.getElementById('cmpAsk');if(b)b.onclick=()=>connModifyRequest(j);}
6689
7415
  {const b=document.getElementById('cmpDel');if(b)b.onclick=()=>edit(()=>{C.joints=(C.joints||[]).filter(x=>x!==j);selIds.clear();});}
6690
7416
  {const b=document.getElementById('cmpFav');if(b)b.onclick=()=>openFavModalFor(j);}
@@ -6777,6 +7503,7 @@ function panel(){
6777
7503
  else if(pk==='aplate')body=sec('Anchor plate')+kv('Width',dim(el&&el.width))+kv('Height',dim(el&&el.depth))+kv('Thickness',dim(el&&el.thickness));
6778
7504
  else body=sec(kindName+'')+kv('Width',dim(el&&el.width))+kv('Height',dim(el&&el.depth))+kv('Thickness',dim(el&&el.thickness));
6779
7505
  p.innerHTML=`<h3>${esc(head)} <span style="color:var(--mut);font-weight:400">· ${loc}</span></h3>
7506
+ ${partReviewChipFor(j.id)}
6780
7507
  <div class="row hint" style="margin-top:2px">Read-only — auto-detailed on <b>${esc(j.main)}</b>; edit its parameters on the member.</div>
6781
7508
  ${lbl?`<div class="row" style="margin:3px 0 0;font-size:12px;color:var(--brand);font-variant-numeric:tabular-nums">${esc(lbl)}</div>`:''}
6782
7509
  ${body}
@@ -6803,14 +7530,16 @@ function panel(){
6803
7530
  {const qb=document.getElementById('qdPlaceG');if(qb)qb.onclick=()=>quickDimSpacing(qdAnchorPt);}
6804
7531
  return;}
6805
7532
  const arr=selArr();
6806
- if(arr.length===0){p.innerHTML='<h3 style="display:flex;justify-content:space-between;align-items:center">Legend'+(Object.keys(C.profile_colors).length?'<button data-command-id="steel.profile-colours-reset" class=ghost id=resetCols style="font-size:10px;padding:1px 6px">reset colours</button>':'')+'</h3><div class=legend>'+profs.filter(pr=>P.members.some(mm=>mm.profile===pr)).map(pr=>`<span><input data-command-id="steel.profile-colour#${esc(pr)}" aria-label="Colour for ${esc(pr)}" type=color class=swc data-prof="${esc(pr)}" value="${colorFor(pr)}" data-tip="Click to recolour ${esc(pr)}">${esc(pr)}</span>`).join('')+'</div><div class=hint style="margin-top:12px">Click a member to edit; <b>Ctrl</b>/<b>Shift+click</b> to add/remove; drag an empty area to <b>box-select</b> — <b>left→right</b> grabs fully-enclosed, <b>right→left</b> grabs touched (Ctrl/Shift adds). Drag a selected line to move it (all selected move together) — it snaps onto nearby grid/endpoints; drag an end dot to adjust — also snaps (<b>Alt</b> off). Hold <b>Shift</b> to keep it straight (H/V). <b>Ctrl+D</b> duplicate, <b>Ctrl+Z/Y</b> undo/redo, <b>Del</b> delete, <b>Esc</b> deselect. <b>Scroll</b> zoom, <b>middle-drag</b> pan, <b>Home</b> fit. Short even dashes = RFI (size unresolved, e.g. MF). A line with <b>arrowheads</b> is a <b>brace</b> — solid = above the floor, long–short dashes = below; the double arrowhead marks its lower end.</div>'+
7533
+ if(arr.length===0){const elevationContext=nativeElevationModel()?nativeElevationContextHtml():
6807
7534
  '<div style="border-top:1px solid var(--line);margin-top:12px;padding-top:12px"><div class=sect>Project defaults</div>'+
6808
7535
  '<div class=hint style="margin:0 0 6px;font-size:11px">Level <b>'+esc(fmtFtIn(defaultTOS))+'</b> ('+esc(P.sheet)+'). '+((P.tos_callouts&&P.tos_callouts.length)?'Per-zone T.O. STEEL callouts from the drawing applied to each member; ':'')+'ends ticked <b>default</b> follow the level.</div>'+
6809
7536
  '<div class=elab>Default TOS</div><input data-command-id="steel.default-tos" aria-label="Default TOS" id=defTos inputmode=decimal placeholder="5 3/4&quot; · 1&#39;-0 1/4&quot;" value="'+esc(fmtFtIn(defaultTOS))+'"><span class=edec>'+esc(fmtDecIn(defaultTOS))+'</span>'+
6810
7537
  '<button data-command-id="steel.ends-reset-default" class="ghostw f" id=applyTos>Reset all ends to default</button></div>';
6811
- document.getElementById('defTos').onchange=e=>{defaultTOS=parseLen(e.target.value);ModelCmd.setPlanDefaultTos(P,defaultTOS);syncDefaults();scheduleSave();render();sync3D();}; // sync3D: this moves every unset-elevation member on THIS sheet, so the 3D meshes and the per-sheet scale cache both have to follow — without it the 3D kept drawing them at the old datum
6812
- document.getElementById('applyTos').onclick=()=>edit(()=>{for(const m of P.members)for(const o of ModelCmd.elevTargets(m))ModelCmd.setTosDefault(o,true,defaultTOS);}); // overwrites EVERY member, overrides included - unlike syncDefaults, which skips them
6813
- document.querySelectorAll('.swc').forEach(c=>c.onchange=e=>{C.profile_colors[c.dataset.prof]=e.target.value;scheduleSave();render();sync3D();}); // recolour a profile (applies everywhere it's drawn; sync3D repaints a live 3D scene, no-op in 2D)
7538
+ p.innerHTML='<h3 style="display:flex;justify-content:space-between;align-items:center">Legend'+(Object.keys(C.profile_colors).length?'<button data-command-id="steel.profile-colours-reset" class=ghost id=resetCols style="font-size:10px;padding:1px 6px">reset colours</button>':'')+'</h3><div class=legend>'+profs.filter(pr=>P.members.some(mm=>mm.profile===pr)).map(pr=>`<span><input data-command-id="steel.profile-colour#${esc(pr)}" aria-label="Colour for ${esc(pr)}" type=color class=swc data-prof="${esc(pr)}" value="${colorFor(pr)}" data-tip="Click to recolour ${esc(pr)}">${esc(pr)}</span>`).join('')+'</div><div class=hint style="margin-top:12px">Click a member to edit; <b>Ctrl</b>/<b>Shift+click</b> to add/remove; drag an empty area to <b>box-select</b> — <b>left→right</b> grabs fully-enclosed, <b>right→left</b> grabs touched (Ctrl/Shift adds). Drag a selected line to move it (all selected move together) — it snaps onto nearby grid/endpoints; drag an end dot to adjust — also snaps (<b>Alt</b> off). Hold <b>Shift</b> to keep it straight (H/V). <b>Ctrl+D</b> duplicate, <b>Ctrl+Z/Y</b> undo/redo, <b>Del</b> delete, <b>Esc</b> deselect. <b>Scroll</b> zoom, <b>middle-drag</b> pan, <b>Home</b> fit. Short even dashes = RFI (size unresolved, e.g. MF). A line with <b>arrowheads</b> is a <b>brace</b> — solid = above the floor, long–short dashes = below; the double arrowhead marks its lower end.</div>'+elevationContext;
7539
+ const defTos=document.getElementById('defTos'),applyTos=document.getElementById('applyTos');
7540
+ if(defTos)defTos.onchange=e=>{defaultTOS=parseLen(e.target.value);ModelCmd.setPlanDefaultTos(P,defaultTOS);syncDefaults();scheduleSave();render();sync3D();};
7541
+ if(applyTos)applyTos.onclick=()=>edit(()=>{for(const m of P.members)for(const o of ModelCmd.elevTargets(m))ModelCmd.setTosDefault(o,true,defaultTOS);});
7542
+ document.querySelectorAll('.swc').forEach(c=>c.onchange=e=>{setProfileColour(c.dataset.prof,e.target.value);scheduleSave();render();sync3D();}); // recolour a profile (applies everywhere it's drawn; sync3D repaints a live 3D scene, no-op in 2D)
6814
7543
  const _rc=document.getElementById('resetCols');if(_rc)_rc.onclick=()=>{C.profile_colors={};scheduleSave();render();};
6815
7544
  return;}
6816
7545
  if(arr.length>1){
@@ -6827,9 +7556,9 @@ function panel(){
6827
7556
  const exPH='5 3/4&quot; · 1&#39;-0 1/4&quot;';
6828
7557
  const endName=id=>({bos:'column bottom',tosC:'column top',ntC:'column top',dtC:'column top',cnC:'column top',tosA:'start end',ntA:'start end',dtA:'start end',cnA:'start end',tosB:'end end',ntB:'end end',dtB:'end end',cnB:'end end'})[id]||id;
6829
7558
  // multi-aware field renderers: show the shared value when all agree, else a "Varies" placeholder (typing applies to all).
6830
- const mTos=(id,label,os)=>{const defA=agg(os,o=>o.tosDef!==false),def=defA===true,vEff=def?defaultTOS:agg(os,o=>o.tosDef!==false?defaultTOS:o.tos);
6831
- return `<div class=elabrow><span class=elab>${label}</span><label class=defck><input data-command-id="steel.end-tos-default#${esc(endName(id))}" aria-label="Use default TOS for ${esc(endName(id))}" type=checkbox id=${id}_ck ${def?'checked':''}>default</label></div>`+
6832
- `<input data-command-id="steel.end-tos#${esc(endName(id))}" aria-label="TOS for ${esc(endName(id))}" id=${id} inputmode=decimal placeholder="${(!def&&VV(vEff))?'Varies':exPH}" value="${def?esc(fmtFtIn(defaultTOS)):valOf(vEff)}"${def?' disabled data-blocked-reason="Following the project default; clear default to enter a custom elevation"':''}><span class=edec>${def?esc(fmtDecIn(defaultTOS)):decOf(vEff)}</span>`;};
7559
+ const mTos=(id,label,os)=>{const native=nativeElevationModel(),defA=agg(os,o=>o.tosDef!==false),def=!native&&defA===true,vEff=native?agg(os,o=>o.tos):(def?defaultTOS:agg(os,o=>o.tosDef!==false?defaultTOS:o.tos));
7560
+ return (native?`<div class=elab>${label}</div>`:`<div class=elabrow><span class=elab>${label}</span><label class=defck><input data-command-id="steel.end-tos-default#${esc(endName(id))}" aria-label="Use default TOS for ${esc(endName(id))}" type=checkbox id=${id}_ck ${def?'checked':''}>default</label></div>`)+
7561
+ `<input data-command-id="steel.end-tos#${esc(endName(id))}" aria-label="${native?'Elevation':'TOS'} for ${esc(endName(id))}" id=${id} inputmode=decimal placeholder="${(!def&&VV(vEff))?'Varies':exPH}" value="${def?esc(fmtFtIn(defaultTOS)):valOf(vEff)}"${def?' disabled data-blocked-reason="Following the project default; clear default to enter a custom elevation"':''}><span class=edec>${def?esc(fmtDecIn(defaultTOS)):decOf(vEff)}</span>`;};
6833
7562
  const mFt=(id,label,os,get)=>{const a=agg(os,get);return `<div class=elab>${label}</div><input data-command-id="steel.end-elevation#${esc(endName(id))}" aria-label="Elevation for ${esc(endName(id))}" id=${id} inputmode=decimal placeholder="${VV(a)?'Varies':exPH}" value="${valOf(a)}"><span class=edec>${decOf(a)}</span>`;};
6834
7563
  const mNote=(id,os)=>{const a=agg(os,o=>o.note||'');return `<input data-command-id="steel.end-note#${esc(endName(id))}" aria-label="Connection or note for ${esc(endName(id))}" id=${id} class="f combo" data-src=conntypes placeholder="${VV(a)?'Varies':'connection / note'}" value="${VV(a)?'':esc(a||'')}" autocomplete=off>`;};
6835
7564
  const mDet=(id,os)=>{const a=agg(os,o=>o.detail||'');return `<div class=elab>Connection detail</div><input data-command-id="steel.end-detail#${esc(endName(id))}" aria-label="Connection detail for ${esc(endName(id))}" id=${id} class=combo data-src=details placeholder="${VV(a)?'Varies':'e.g. 5-S504'}" value="${VV(a)?'':esc(a||'')}" autocomplete=off>`;};
@@ -6837,11 +7566,11 @@ function panel(){
6837
7566
  let elev='';
6838
7567
  if(!allBeam&&!allCol) elev=`<div class="hint f" style="border:1px solid var(--line);border-radius:6px;padding:8px 10px">Mixed beam + column — select one type only to edit levels.</div>`;
6839
7568
  else if(allCol){const cs=cols.map(m=>m.col);
6840
- elev=`<div class="sect f">Elevation</div>${mFt('bos',dotS+'Bottom (BOS)',cs,o=>o.bos)}${mTos('tosC',dotE+'Top (TOS)',cs)}${mNote('ntC',cs)}${mDet('dtC',cs)}`;}
7569
+ elev=`<div class="sect f">Elevation</div>${mFt('bos',dotS+(nativeElevationModel()?'Bottom elevation':'Bottom (BOS)'),cs,o=>o.bos)}${mTos('tosC',dotE+(nativeElevationModel()?'Top elevation':'Top (TOS)'),cs)}${mNote('ntC',cs)}${mDet('dtC',cs)}`;}
6841
7570
  else{const s0=beams.map(m=>m.ends[0]),s1=beams.map(m=>m.ends[1]);
6842
- elev=`<div class="sect f">${dotS}Start</div>${mTos('tosA','TOS',s0)}${mNote('ntA',s0)}${mDet('dtA',s0)}`+
7571
+ elev=`<div class="sect f">${dotS}Start</div>${mTos('tosA',nativeElevationModel()?'Start elevation':'TOS',s0)}${mNote('ntA',s0)}${mDet('dtA',s0)}`+
6843
7572
  `<div class=divrow><hr><button data-command-id="steel.ends-match" class=ghost id=matchEnds>Match → both ends (each)</button><hr></div>`+
6844
- `<div class=sect>${dotE}End</div>${mTos('tosB','TOS',s1)}${mNote('ntB',s1)}${mDet('dtB',s1)}`;}
7573
+ `<div class=sect>${dotE}End</div>${mTos('tosB',nativeElevationModel()?'End elevation':'TOS',s1)}${mNote('ntB',s1)}${mDet('dtB',s1)}`;}
6845
7574
  // The placement aggregates over the ELIGIBLE subset only — a member whose profile resolves to no section
6846
7575
  // is skipped by the bake entirely, so folding it in would report a Varies (or a value) for a member
6847
7576
  // nothing applies to. ONE subset for both axes and both offsets, because the bake has one answer for all
@@ -6968,8 +7697,8 @@ function panel(){
6968
7697
  const mfSug=((m.mf||/^MF/i.test(m.profile))&&_lvl&&C.moment_frames)?[...new Set(C.moment_frames.flatMap(f=>f[_lvl]||[]))].filter(Boolean):[];
6969
7698
  const endName2=id=>({bos:'column bottom',tosC:'column top',ntC:'column top',dtC:'column top',cnC:'column top',tosA:'start end',ntA:'start end',dtA:'start end',cnA:'start end',tosB:'end end',ntB:'end end',dtB:'end end',cnB:'end end'})[id]||id;
6970
7699
  const ftFld=(id,label,v)=>`<div class=elab>${label}</div><input data-command-id="steel.end-elevation#${esc(endName2(id))}" aria-label="Elevation for ${esc(endName2(id))}" id=${id} inputmode=decimal placeholder="5 3/4&quot; · 1&#39;-0 1/4&quot;" value="${esc(fmtFtIn(v))}"><span class=edec>${esc(fmtDecIn(v))}</span>`;
6971
- const tosFld=(id,label,o)=>{const def=o.tosDef!==false,v=def?defaultTOS:o.tos;
6972
- return `<div class=elabrow><span class=elab>${label}</span><label class=defck><input data-command-id="steel.end-tos-default#${esc(endName2(id))}" aria-label="Use default TOS for ${esc(endName2(id))}" type=checkbox id=${id}_ck ${def?'checked':''}>default</label></div><input data-command-id="steel.end-tos#${esc(endName2(id))}" aria-label="TOS for ${esc(endName2(id))}" id=${id} inputmode=decimal placeholder="5 3/4&quot; · 1&#39;-0 1/4&quot;" value="${esc(fmtFtIn(v))}"${def?' disabled data-blocked-reason="Following the project default; clear default to enter a custom elevation"':''}><span class=edec>${esc(fmtDecIn(v))}</span>`;};
7700
+ const tosFld=(id,label,o)=>{const native=nativeElevationModel(),def=!native&&o.tosDef!==false,v=def?defaultTOS:o.tos;
7701
+ return (native?`<div class=elab>${label}</div>`:`<div class=elabrow><span class=elab>${label}</span><label class=defck><input data-command-id="steel.end-tos-default#${esc(endName2(id))}" aria-label="Use default TOS for ${esc(endName2(id))}" type=checkbox id=${id}_ck ${def?'checked':''}>default</label></div>`)+`<input data-command-id="steel.end-tos#${esc(endName2(id))}" aria-label="${native?'Elevation':'TOS'} for ${esc(endName2(id))}" id=${id} inputmode=decimal placeholder="5 3/4&quot; · 1&#39;-0 1/4&quot;" value="${esc(fmtFtIn(v))}"${def?' disabled data-blocked-reason="Following the project default; clear default to enter a custom elevation"':''}><span class=edec>${esc(fmtDecIn(v))}</span>`;};
6973
7702
  const nin=(id,v)=>`<input data-command-id="steel.end-note#${esc(endName2(id))}" aria-label="Connection or note for ${esc(endName2(id))}" id=${id} class="f combo" data-src=conntypes placeholder="connection / note" value="${esc(v||'')}" autocomplete=off>`;
6974
7703
  const dFld=(id,o)=>{const hasPrev=o.detail&&previewFor(o.detail);return `<div class=elab>Connection detail</div><div style="display:flex;gap:6px"><input data-command-id="steel.end-detail#${esc(endName2(id))}" aria-label="Connection detail for ${esc(endName2(id))}" id=${id} class=combo data-src=details placeholder="e.g. 5-S504" value="${esc(o.detail||'')}" style="flex:1" autocomplete=off>${hasPrev?`<button data-command-id="steel.detail-preview#${esc(endName2(id))}" aria-label="Open connection detail for ${esc(endName2(id))}" id=${id}_open class=ghost data-tip="Open detail ${esc(o.detail)}">⤢</button>`:''}<button data-command-id="steel.pick-detail" aria-label="Pick connection detail for ${esc(endName2(id))}" id=${id}_pk class="ghost${(picking&&pickKind==='detail'&&pickEnd===o)?' on':''}" data-tip="Pick a detail callout from the drawing">⌖</button></div>`;};
6975
7704
  // Per-end connection-library picker (sets o.conn = a connections[] row id). When set, the row's
@@ -7030,10 +7759,10 @@ function panel(){
7030
7759
  };
7031
7760
  const dotS='<span class=epdot style="background:#facc15"></span>',dotE='<span class=epdot style="background:#f472b6"></span>'; // start=yellow, end=magenta — matches the canvas end markers
7032
7761
  const elev = col
7033
- ? `<div class="sect f">Elevation</div>${ftFld('bos',dotS+'Bottom (BOS)',m.col.bos)}${tosFld('tosC',dotE+'Top (TOS)',m.col)}${cFld('cnC',m.col)}${fb(m.col,nin('ntC',m.col.note)+dFld('dtC',m.col))}${dStat('dtC',m.col,'col')}`
7034
- : `<div class="sect f">${dotS}Start</div>${tosFld('tosA','TOS',m.ends[0])}${cFld('cnA',m.ends[0])}${fb(m.ends[0],nin('ntA',m.ends[0].note)+dFld('dtA',m.ends[0]))}${dStat('dtA',m.ends[0],0)}
7762
+ ? `<div class="sect f">Elevation</div>${ftFld('bos',dotS+(nativeElevationModel()?'Bottom elevation':'Bottom (BOS)'),m.col.bos)}${tosFld('tosC',dotE+(nativeElevationModel()?'Top elevation':'Top (TOS)'),m.col)}${cFld('cnC',m.col)}${fb(m.col,nin('ntC',m.col.note)+dFld('dtC',m.col))}${dStat('dtC',m.col,'col')}`
7763
+ : `<div class="sect f">${dotS}Start</div>${tosFld('tosA',nativeElevationModel()?'Start elevation':'TOS',m.ends[0])}${cFld('cnA',m.ends[0])}${fb(m.ends[0],nin('ntA',m.ends[0].note)+dFld('dtA',m.ends[0]))}${dStat('dtA',m.ends[0],0)}
7035
7764
  ${isBrace(m)?'':`<div class=divrow><hr><button data-command-id="steel.ends-match" class=ghost id=matchEnds>Match → both ends</button><hr></div>`}
7036
- <div class=sect>${dotE}End</div>${tosFld('tosB','TOS',m.ends[1])}${cFld('cnB',m.ends[1])}${fb(m.ends[1],nin('ntB',m.ends[1].note)+dFld('dtB',m.ends[1]))}${dStat('dtB',m.ends[1],1)}`;
7765
+ <div class=sect>${dotE}End</div>${tosFld('tosB',nativeElevationModel()?'End elevation':'TOS',m.ends[1])}${cFld('cnB',m.ends[1])}${fb(m.ends[1],nin('ntB',m.ends[1].note)+dFld('dtB',m.ends[1]))}${dStat('dtB',m.ends[1],1)}`;
7037
7766
  const bpj=col?(C.joints||[]).find(j=>j&&j.kind==='base-plate'&&j.main===m.id):null; // this column's base-plate joint, if detailed
7038
7767
  const pFld=(key,label,ph,unit)=>{const raw=bpj&&bpj.params&&bpj.params[key]!=null?bpj.params[key]:null;const val=raw==null?'':(unit==='mm'?esc(fmtFtIn(Number(raw)/25.4)):esc(String(raw)));return `<div class=elab>${label}</div><input data-command-id="steel.connection-parameter#${esc('base plate '+label.toLowerCase())}" aria-label="${esc(label)}" id=bp_${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
7039
7768
  const bpSect=bpj?`<div class=divrow><hr><span class=sect style="margin:0">Base plate</span><hr></div>
@@ -7154,7 +7883,7 @@ function panel(){
7154
7883
  p.innerHTML=`<h3>Member ${esc(m.id)}</h3>
7155
7884
  ${typeFilterHTML()}
7156
7885
  ${memberTypeField('mTypeS',[m])}
7157
- <div class="f"><div class=elab>Profile</div><div style="display:flex;gap:6px"><input data-command-id="steel.member-profile" aria-label="Profile" id=pf class=combo data-src=profiles value="${esc(m.profile)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-profile-catalog" id=profileBrowseS class=ghost data-tip="Browse the active environment profile catalog">Browse</button><button data-command-id="steel.pick-profile" id=pickProf class="ghost${(picking&&pickKind==='profile')?' on':''}" data-tip="Pick profile by clicking a label in the drawing">⌖ pick</button></div>${(picking&&pickKind==='profile')?'<div class="hint" style="margin-top:4px;font-style:italic;color:var(--brand)">Click a profile label in the drawing…</div>':(picking&&pickKind==='detail')?'<div class="hint" style="margin-top:4px;font-style:italic;color:var(--purple)">Click a detail callout in the drawing…</div>':''}</div>
7886
+ <div class="f"><div class=elab>Profile</div><div style="display:flex;gap:6px"><input data-command-id="steel.member-profile" aria-label="Profile" id=pf class=combo data-src=profiles value="${esc(m.profile)}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-profile-catalog" id=profileBrowseS class=ghost data-tip="Browse the active environment profile catalog">Browse</button><button data-command-id="steel.pick-profile" id=pickProf class="ghost${(picking&&pickKind==='profile')?' on':''}" aria-pressed="${(picking&&pickKind==='profile')?'true':'false'}" data-tip="Pick profile from drawing labels by click, Enter, or Space">⌖ pick</button></div>${(picking&&pickKind==='profile')?'<div class="hint" data-profile-pick-status role=status aria-live=polite style="margin-top:4px;font-style:italic;color:var(--brand)">'+esc(profilePickGuidance())+'</div>':(picking&&pickKind==='detail')?'<div class="hint" style="margin-top:4px;font-style:italic;color:var(--purple)">Click a detail callout in the drawing…</div>':''}</div>
7158
7887
  <div class="f"><div class=elab>Material grade</div><div style="display:flex;gap:6px"><input data-command-id="steel.member-material" aria-label="Material grade" id=mat class=combo data-src=materials value="${esc(m.material||'')}" placeholder="Profile default · ${esc(profileDefaultMaterial(m.profile))}" style="flex:1" autocomplete=off><button data-command-id="steel.browse-material-catalog" id=materialBrowseS class=ghost data-tip="Browse structural member grades">Browse</button></div><div class=hint>${m.material?esc(m.material)+' · explicit':'Follows the selected profile automatically'}</div></div>
7159
7888
  ${appearanceSect}
7160
7889
  ${braceSect}
@@ -7191,7 +7920,7 @@ function panel(){
7191
7920
  {const rp=document.getElementById('rfiPill');if(rp){const go=()=>openRFI(m.id);rp.onclick=go;rp.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();e.stopPropagation();go();}};}} // F12: the RFI pill opens the list focused on THIS member (role=button span → keydown for Enter/Space). stopPropagation so idle Space/Enter doesn't ALSO hit the global repeat-last handler (:3804) — matches the editor's local-keydown convention (:1738,:4212)
7192
7921
  document.getElementById('pickProf').onclick=()=>{if(picking&&pickKind==='profile'){picking=false;}else{picking=true;pickKind='profile';pickEnd=null;}render();};
7193
7922
  document.getElementById('mTypeS').onchange=e=>{const v=e.target.value;if(!normMemberTypeKey(v)){e.target.value=memberTypeLabel(memberTypeOf(m));return;}edit(()=>{const k=memberTypeFromInput(v);if(k&&memberTypeOf(m)!==k)applyMemberType([m],k);});}; // retype → role + legend recategorize (edit() → sync3D → build3DLegend); undoable
7194
- {const _cc=document.getElementById('msColor');if(_cc)_cc.onchange=e=>{C.profile_colors[m.profile]=e.target.value;scheduleSave();render();sync3D();};} // F1: recolour this member's profile (same write as the legend swatch) — sync3D() repaints a live 3D scene (no-op in 2D) so colour is truly 2D+3D
7923
+ {const _cc=document.getElementById('msColor');if(_cc)_cc.onchange=e=>{setProfileColour(m.profile,e.target.value);scheduleSave();render();sync3D();};} // F1: recolour this member's profile (same write as the legend swatch) — sync3D() repaints a live 3D scene (no-op in 2D) so colour is truly 2D+3D
7195
7924
  document.querySelectorAll('.msW').forEach(b=>b.onclick=()=>setMemberLineStyle(memberTypeOf(m),'weight',b.dataset.w)); // F5: per member-type line weight
7196
7925
  document.querySelectorAll('.msD').forEach(b=>b.onclick=()=>setMemberLineStyle(memberTypeOf(m),'dash',b.dataset.d)); // F5: per member-type line dash
7197
7926
  document.querySelectorAll('.mfsug').forEach(b=>b.onclick=()=>edit(()=>{const profile=b.dataset.s;ModelCmd.patchMember(m,{profile,mf:true,rfi:_wt(profile)==null});if(!profs.includes(profile)){profs.push(profile);profs.sort();}})); // record the moment-frame provenance (drives the confidence "schedule-resolved" factor)
@@ -7678,13 +8407,26 @@ const PROP_DEFS=[
7678
8407
  {key:'col_detail',label:'Detail', get:m=>m.role==='column'?(m.col?(m.col.detail||''):undefined):undefined, fmt:v=>v==null?'':String(v)},
7679
8408
  ];
7680
8409
  const PROP_KEYS=new Set(PROP_DEFS.map(d=>d.key));
7681
- // normalise persisted/incoming prop_labels to known keys/placement so a corrupt draft can't desync the UI
7682
- function sanitizePropLabels(x){const o=(x&&typeof x==='object'&&!Array.isArray(x))?x:{};
7683
- return {props:Array.isArray(o.props)?o.props.filter(k=>PROP_KEYS.has(k)):[],
8410
+ // Normalise persisted/incoming prop_labels to what `$defs.propLabels` ACTUALLY permits — not to what this
8411
+ // build happens to understand. The distinction cost data twice here (Codex, #853):
8412
+ //
8413
+ // - `props` is `items:{type:'string'}`, so ANY string is valid. Filtering it to `PROP_KEYS` deleted a
8414
+ // token this build does not know — exactly what a NEWER build's draft carries — and the next autosave
8415
+ // persisted the loss, silently reaching back and unpicking a selection made elsewhere. Unknown tokens
8416
+ // are inert to every reader (`propLabelLinesFor` walks PROP_DEFS), so carrying them costs nothing.
8417
+ // - `ids` is `items:{minLength:1}`, and the old `typeof v==='string'` test let `''` through — the mirror
8418
+ // mistake, a guard under-enforcing, which refuses every save (`expected at least 1 characters`).
8419
+ //
8420
+ // `placement` (an enum) and the three booleans ARE schema-constrained, so clamping those is this
8421
+ // function's job rather than an opinion.
8422
+ function sanitizePropLabels(x){const hasState=!!(x&&typeof x==='object'&&!Array.isArray(x)),o=hasState?x:{};
8423
+ return {props:Array.isArray(o.props)?o.props.filter(k=>typeof k==='string'):(hasState?[]:['profile']),
7684
8424
  placement:['start','mid','end'].includes(o.placement)?o.placement:'mid',
7685
8425
  selected_only:o.selected_only===true,
7686
8426
  vis2d:o.vis2d!==false,vis3d:o.vis3d!==false, // per-view label VISIBILITY (B1): default ON; the property SELECTION (props) stays shared across 2D+3D — only show/hide is independent
7687
- ids:Array.isArray(o.ids)?o.ids.filter(v=>typeof v==='string'):[]};}
8427
+ ids:Array.isArray(o.ids)?o.ids.filter(v=>typeof v==='string'&&v!==''):[]};}
8428
+ /** How many selected props this build can actually draw — `props` may carry tokens minted by a newer one. */
8429
+ const knownPropCount=pl=>(pl&&Array.isArray(pl.props)?pl.props.filter(k=>PROP_KEYS.has(k)).length:0);
7688
8430
  // Normalise the optional property-label object before any renderer reads it. Every key written here is
7689
8431
  // part of the native schema, including the independent 2D/3D visibility flags.
7690
8432
  C.prop_labels=sanitizePropLabels(C.prop_labels);
@@ -7778,12 +8520,9 @@ function renderPropLabels(){const pl=C.prop_labels;propLabelsHidden=0;if(!pl||!p
7778
8520
  //
7779
8521
  // A SECOND MESSAGE WAS ADDED HERE AND REMOVED, and the reason is worth keeping. The UX review noted that
7780
8522
  // "visibility on, no properties ticked" leaves a toggle reading on over a canvas with no chips — true, and
7781
- // "Clear all" reaches it in one click. But `props: []` with visibility on is not an anomaly, it is the
7782
- // RESTING STATE OF EVERY DOCUMENT: `sanitizePropLabels` writes `props: []` and defaults both flags on, and
7783
- // the reader emits the same empty skeleton. So the predicate that was supposed to explain a rare state
7784
- // matched every project that had never used the feature, and parked a permanent pill telling the user to
7785
- // right-click a member. Measured by review, not reasoned about. The honest place for that explanation is
7786
- // the popup where "Clear all" lives, not the canvas.
8523
+ // "Clear all" reaches it in one click. A MISSING preference now starts with Profile, while an explicit
8524
+ // `props: []` remains the user's legitimate cleared state. Parking a permanent pill over that deliberate
8525
+ // state would still be noise; the Properties popup is where the selection and "Clear all" live.
7787
8526
  function updatePropHint(){let el=document.getElementById('plHint');
7788
8527
  const show=view2dShown&&propLabelsHidden>0; // a 2D-CANVAS hint: it belongs on screen whenever the plan is, not only when the plan holds the tools
7789
8528
  if(!show){if(el)el.style.display='none';return;}
@@ -7849,7 +8588,9 @@ function renderPropPop(){const el=document.getElementById('propPop');if(!el||!el
7849
8588
  if(propPopConn){renderConnTree(el);return;} // connection / mixed-selection tree view
7850
8589
  const arr=selArr(),pl=C.prop_labels,q=(el.querySelector('#ppSearch').value||'').trim().toLowerCase();
7851
8590
  el.querySelector('#ppTitle').textContent='Properties'; // short title so the header never clips it; the selection count moved to the roomy scope line below
7852
- el.querySelector('#ppLabeled').textContent=pl.props.length?pl.props.length+' labeled':'';
8591
+ // Counts what this build can DRAW, not what `props` holds — a token from a newer build is carried through
8592
+ // the restore now (see sanitizePropLabels) and would otherwise be counted as a label nobody can see.
8593
+ {const n=knownPropCount(pl);el.querySelector('#ppLabeled').textContent=n?n+' labeled':'';}
7853
8594
  el.querySelector('#ppScope').textContent=arr.length+(arr.length===1?' member · ':' members · ')+(pl.selected_only?'labels apply to the selected':'labels apply to all on this plan');
7854
8595
  el.querySelectorAll('#ppPlace button').forEach(b=>b.classList.toggle('on',b.dataset.pl===pl.placement));
7855
8596
  el.querySelector('#ppSel').checked=pl.selected_only;
@@ -8404,14 +9145,16 @@ function openPositionHud(id,axis,scr){
8404
9145
  if(!st||!st.available){ // a double-click on a VISIBLE handle that opens nothing is confusing — the view picked it from a cached snapshot, but a fresh read can disagree (a mid-flight external write, a roll that became unresolvable). Surface it instead of a silent return (mirrors currentPositionGizmoState's console.debug + the drag bail).
8405
9146
  console.debug('steel: position HUD not opened —',st&&st.reason);
8406
9147
  toast('Can’t edit this handle right now'+(st&&st.reason?' — '+st.reason:'')+'. Try the Inspect panel.');return;}
8407
- // The reference-line handles (3b.1) type a DELTA — how far to slide, how far to swing — so their "current
8408
- // value" hint is 0, unlike the three profile handles whose current absolute value is the hint. A handle the
8409
- // member cannot take never opens a HUD either, or the user would type a value into something that can only
8410
- // refuse it.
8411
- const refline=axis==='slide'||axis==='swingPlan'||axis==='swingElev';
9148
+ // Every handle that MOVES THE REFERENCE LINE types a DELTA — how far to translate, how far to swing — so
9149
+ // its “current value” hint is 0. Since the redesign that is all five of them: the depth and width arrows
9150
+ // moved from writing a profile offset to translating the line, and their hint moved with them. The roll arc
9151
+ // is the only handle whose current ABSOLUTE value is still the hint, because it is the only one that still
9152
+ // writes a stored member field. A handle the member cannot take never opens a HUD either, or the user would
9153
+ // type a value into something that can only refuse it.
9154
+ const refline=axis!=='rot';
8412
9155
  if(refline&&!(st.handles&&st.handles[axis]&&st.handles[axis].available)){
8413
9156
  toast((st.handles&&st.handles[axis]&&st.handles[axis].reason)||'That handle isn’t available on this member.');return;}
8414
- const cur=refline?0:axis==='depth'?st.positionOffset:axis==='width'?st.positionHOffset:st.rot;
9157
+ const cur=refline?0:st.rot;
8415
9158
  posHudTarget={id,axis,cur};
8416
9159
  if(view3d&&window.Steel3DView&&window.Steel3DView.setPositionTyping)window.Steel3DView.setPositionTyping(true);
8417
9160
  cmHudShow('',{consumer:'position',scr});
@@ -8426,13 +9169,17 @@ function cmHudSyncPill(){if(!cmHudEl)return;const pill=cmHudEl.querySelector('#c
8426
9169
  pill.classList.toggle('locked',cmHudLock); // Add 1st point → ABS only, REL hidden (not disabled)
8427
9170
  pill.querySelectorAll('.cmHudSeg').forEach(s=>{const on=((s.dataset.mode==='abs')===cmHudAbs);s.setAttribute('aria-checked',on?'true':'false');s.tabIndex=on?0:-1;s.classList.toggle('on',on);}); // roving tabindex: only the selected radio is Tab-reachable
8428
9171
  const abs=pill.querySelector('.cmHudSeg[data-mode="abs"]');if(abs)abs.setAttribute('data-tip',cmHudLock?'First point has no anchor to offset from — absolute only':'Absolute — X′,Y′,Z′ in the local frame (X,Y,Z if none)');}
9172
+ function posHudAngular(){return !!(cmHudConsumer==='position'&&posHudTarget&&(posHudTarget.axis==='rot'||posHudTarget.axis==='swingPlan'||posHudTarget.axis==='swingElev'));} // roll + the two swing arcs type DEGREES; every other handle types a length
8429
9173
  function cmHudPlaceholder(){if(!cmHudEl)return;const inp=cmHudEl.querySelector('input');if(!inp)return;
8430
- if(cmHudConsumer==='position'){const ang=posHudTarget&&(posHudTarget.axis==='rot'||posHudTarget.axis==='swingPlan'||posHudTarget.axis==='swingElev');
9174
+ if(cmHudConsumer==='position'){const ang=posHudAngular();
8431
9175
  inp.placeholder=posHudTarget?(ang?(String(+(+posHudTarget.cur||0).toFixed(2))+'°'):(posOffDisp(posHudTarget.cur)||'0"')):'';return;} // 3b.3: the current value is the hint (HUD opens empty). 3b.1: a reference-line handle types a DELTA, so its hint is 0.
8432
9176
  inp.placeholder=cmHudAbs?(cmHudPrimed?"X′,Y′ · or X′,Y′,Z′":"X,Y · or X,Y,Z"):(cmHudConsumer==='add'?"dx,dy · or dx,dy,dz":"12'-6 · or dx,dy");}
8433
9177
  function cmHudEcho(){const inp=cmHudEl.querySelector('input'),lbl=cmHudEl.querySelector('#cmHudLbl');
8434
9178
  const pv=parseVec(inp.value),n=(cmTool==='copy'&&!cmArrayMode&&cmCount>1)?(' ×'+cmCount):'';let txt='';
8435
- if(pv){if(pv.dist!=null){txt='= '+fmtFtIn(pv.dist);}
9179
+ // An ANGLE is not a length. Echoing it through fmtFtIn turned "45" into "= 3'-9"" on the roll and swing
9180
+ // handles — the placeholder already knew better, so the two halves of the same HUD contradicted each other.
9181
+ if(pv&&posHudAngular()){txt=pv.dist!=null?('= '+String(+(+pv.dist).toFixed(2))+'°'):'';}
9182
+ else if(pv){if(pv.dist!=null){txt='= '+fmtFtIn(pv.dist);}
8436
9183
  else{const ax=!view3d?['','','']:(cmHudAbs?(cmHudPrimed?['X′','Y′','Z′']:['X','Y','Z']):['Δx','Δy','Δz']); // 3D echo carries the ′ prime + axis so the space is never ambiguous; 2D stays plain (unchanged)
8437
9184
  txt='= '+pv.comp.map((c,i)=>pv.provided[i]?((ax[i]?ax[i]+' ':'')+fmtFtIn(c)):null).filter(Boolean).join(', ');}}
8438
9185
  lbl.textContent=(txt?txt+n:n.trim());
@@ -8477,21 +9224,30 @@ function cmHudCommit(str){
8477
9224
  if(cmHudConsumer==='position'){ // 3b.3: single scalar → commitMemberPosition (same path as a drag: absolute value, one undo entry). Typed values BYPASS the ¼"/5° snap.
8478
9225
  const t=String(str==null?'':str).trim();
8479
9226
  if(t===''||!posHudTarget){cmHudClose();return;} // empty = no-op close
8480
- if(posHudTarget.axis==='slide'||posHudTarget.axis==='swingPlan'||posHudTarget.axis==='swingElev'){ // 3b.1: a reference-line handle — the typed value is a DELTA, committed as absolute work points
9227
+ // Every handle that moves the reference LINE takes a typed DELTA and commits ABSOLUTE work points.
9228
+ // Since the redesign that is all of them but the roll: the depth and width arrows translate the line
9229
+ // along the member's rolled profile axes instead of writing a profile offset, so they type a distance
9230
+ // to move, exactly as the axial slide always has.
9231
+ if(posHudTarget.axis!=='rot'){
8481
9232
  const st=memberPositionGizmoState(posHudTarget.id);
8482
9233
  if(!st||!st.available){cmHudEl.classList.add('err');toast('Can’t move this member right now'+(st&&st.reason?' — '+st.reason:'')+'.');return;}
9234
+ const ax=posHudTarget.axis;
8483
9235
  let spec=null;
8484
- if(posHudTarget.axis==='slide'){
9236
+ if(ax==='slide'||ax==='depth'||ax==='width'){
8485
9237
  const inch=parseLen(t);if(inch==null||!isFinite(inch)){cmHudEl.classList.add('err');toast('Couldn’t read “'+t+'” as a length — try 3 1/2" or 1\'-3 1/2".');return;}
8486
9238
  if(Math.abs(inch)<1e-9){cmHudClose();return;} // typing 0 is "never mind", not an error — close quietly rather than toasting the command's inert-move refusal
8487
- const r=SteelCore.slideEndpoints(st.anchor,st.end,st.xAxis,inch*25.4);
8488
- if(!r){cmHudEl.classList.add('err');toast('That slide can’t be applied to this member.');return;}
8489
- spec={from:r.from,to:r.to,gesture:'slide'};
9239
+ // The axis is the ONLY difference between the three: the member axis for a slide, and st.profile —
9240
+ // the same rolled axes the arrows are drawn along — for depth and width, so a typed value travels
9241
+ // exactly where dragging that arrow would.
9242
+ const tax=ax==='slide'?st.xAxis:ax==='depth'?(st.profile&&st.profile.z):(st.profile&&st.profile.y);
9243
+ const r=SteelCore.translateEndpoints(st.anchor,st.end,tax,inch*25.4);
9244
+ if(!r){cmHudEl.classList.add('err');toast('That move can’t be applied to this member.');return;}
9245
+ spec={from:r.from,to:r.to,gesture:ax==='slide'?'slide':'translate'};
8490
9246
  }else{
8491
9247
  const deg=Number(t.replace(',','.'));if(!isFinite(deg)){cmHudEl.classList.add('err');toast('Enter an angle in degrees, e.g. 45 or -90.');return;}
8492
9248
  let theta=deg*Math.PI/180;
8493
- const swingAxis=posHudTarget.axis==='swingPlan'?st.up:st.yAxis;
8494
- if(posHudTarget.axis==='swingElev'){
9249
+ const swingAxis=ax==='swingPlan'?st.up:st.yAxis;
9250
+ if(ax==='swingElev'){
8495
9251
  // A typed value bypasses the SNAP — that is the shipped 3b.3 contract — but it does not bypass
8496
9252
  // geometry. 'typed' mode REFUSES rather than silently rewriting the number the user asked for; the
8497
9253
  // HUD stays open in its error state so they can see nothing was committed and pick another angle.
@@ -8502,17 +9258,20 @@ function cmHudCommit(str){
8502
9258
  }
8503
9259
  const to=SteelCore.swingEndpoint(st.anchor,st.end,swingAxis,theta);
8504
9260
  if(!to){cmHudEl.classList.add('err');toast('That swing can’t be applied to this member.');return;}
8505
- spec={to,gesture:posHudTarget.axis};
9261
+ spec={to,gesture:ax};
8506
9262
  }
8507
9263
  const okRef=commitMemberEndpoints(posHudTarget.id,spec,cmHudEl);
8508
9264
  if(!okRef){cmHudEl.classList.add('err');return;}
8509
9265
  cmHudClose();return;
8510
9266
  }
8511
- let val;
8512
- if(posHudTarget.axis==='rot'){val=Number(t.replace(',','.'));if(!isFinite(val)){cmHudEl.classList.add('err');toast('Enter an angle in degrees, e.g. 45 or -90.');return;}val=SteelCore.rollCommitNorm(val);}
8513
- else{const inch=parseLen(t);if(inch==null||!isFinite(inch)){cmHudEl.classList.add('err');toast('Couldn’t read “'+t+'” as a length — try 3 1/2" or 1\'-3 1/2".');return;}val=inch*25.4;}
8514
- const key=posHudTarget.axis==='depth'?'positionOffset':posHudTarget.axis==='width'?'positionHOffset':'rot';
8515
- const ok=commitMemberPosition(posHudTarget.id,{[key]:val},cmHudEl); // refused (frame drift) toasts its own reason; keep the HUD open + .err so the user can retry. Passing cmHudEl as `source` is safe ONLY because #cmHud is not focusable — positionRefuse calls source.focus(), a no-op on a plain <div>; giving #cmHud a tabindex/contenteditable would blur the input, fire the blur handler, and wrongly discard+toast.
9267
+ // ONLY the roll reaches here now. It is the last gizmo handle that writes a stored member field rather
9268
+ // than moving the work points, so it is the last caller of commitMemberPosition from the 3D view; the
9269
+ // depth and width arrows used to land here and set positionOffset / positionHOffset, and those two are
9270
+ // panel-only numbers from here on.
9271
+ let val=Number(t.replace(',','.'));
9272
+ if(!isFinite(val)){cmHudEl.classList.add('err');toast('Enter an angle in degrees, e.g. 45 or -90.');return;}
9273
+ val=SteelCore.rollCommitNorm(val);
9274
+ const ok=commitMemberPosition(posHudTarget.id,{rot:val},cmHudEl); // refused (frame drift) toasts its own reason; keep the HUD open + .err so the user can retry. Passing cmHudEl as `source` is safe ONLY because #cmHud is not focusable — positionRefuse calls source.focus(), a no-op on a plain <div>; giving #cmHud a tabindex/contenteditable would blur the input, fire the blur handler, and wrongly discard+toast.
8516
9275
  if(!ok){cmHudEl.classList.add('err');return;}
8517
9276
  cmHudClose();return;
8518
9277
  }
@@ -8556,7 +9315,8 @@ function openLevelModal(tool){ // works from 2D and 3D — the commit is plan-
8556
9315
  const go=document.createElement('button');go.className='primary';go.disabled=true;go.textContent=tool==='move'?'Move here':'Copy here';
8557
9316
  C.plans.forEach((pl,i)=>{const row=document.createElement('div');row.className='lvrow'+(pl===P?' cur':'');
8558
9317
  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
8559
- 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);
9318
+ const ts=document.createElement('span');ts.className='lvtos';const nM=(pl.members||[]).length;
9319
+ const elevation=nativeElevationModel()?Number(pl.elevation_in):Number(pl.default_tos);ts.textContent=nM+' member'+(nM===1?'':'s')+' · '+(nativeElevationModel()?'Elevation ':'TOS ')+fmtFtIn(Number.isFinite(elevation)?elevation:0);
8560
9320
  row.append(nm,ts);
8561
9321
  if(pl!==P){row.onclick=()=>{pick=i;rows.forEach(r=>r.classList.remove('pick'));row.classList.add('pick');go.disabled=false;};
8562
9322
  row.ondblclick=()=>{pick=i;toLevelCommit(tool,i);closeLevelModal();};}
@@ -8646,6 +9406,14 @@ function toast(msg,sticky,ms){let t=document.getElementById('toast');
8646
9406
  t.setAttribute('role','status');t.setAttribute('aria-live','polite');t.setAttribute('aria-atomic','true');
8647
9407
  t.textContent=msg;t.style.opacity='1';clearTimeout(t._h);if(!sticky)t._h=setTimeout(()=>{t.style.opacity='0';},ms>0?ms:TOAST_MS);}
8648
9408
  // --- pointer: select(+ctrl toggle / box) + group-move + endpoint (Shift = ortho) ---
9409
+ function applyProfileLabel(prof){
9410
+ if(mode!=='add'&&picking&&pickKind==='profile'&&selIds.size===1){const id=[...selIds][0];picking=false;edit(()=>{const m=byId(id);ModelCmd.patchMember(m,{profile:prof,rfi:_wt(prof)==null});if(!profs.includes(prof)){profs.push(prof);profs.sort();}});restoreProfilePickerOwnerAfterApply('pickProf');return true;}
9411
+ if(mode==='add'&&!drawDraft){addProfile=prof;if(picking&&pickKind==='profile'){picking=false;render();restoreProfilePickerOwnerAfterApply('addPick');return true;}
9412
+ const hi=document.getElementById('addProf');if(hi)hi.value=addProfile;const ph=document.getElementById('pickHint');if(ph){ph.classList.add('pick');setTimeout(()=>ph&&ph.classList.remove('pick'),450);}return true;}
9413
+ return false;
9414
+ }
9415
+ svg.addEventListener('keydown',e=>{const t=e.target;if(!t||!t.classList||!t.classList.contains('lblhot'))return;
9416
+ if(e.key!=='Enter'&&e.key!==' ')return;e.preventDefault();e.stopPropagation();applyProfileLabel(t.dataset.prof);});
8649
9417
  svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
8650
9418
  if(memberEndReview){const pick=t.closest&&t.closest('[data-mer-canvas-target]');if(pick&&!memberEndReview.busy){const f=memberEndReview.report.findings[memberEndReview.focus];chooseMemberEndTarget(memberEndKey(f),+pick.dataset.merCanvasTarget);}e.preventDefault();e.stopPropagation();return;}
8651
9419
  if(csaxisMode){csClick(e);e.preventDefault();return;} // set-local-axes armed → clicks define origin then X-direction
@@ -8708,11 +9476,7 @@ svg.addEventListener('pointerdown',e=>{if(e.button!==0)return;const t=e.target;
8708
9476
  return;}
8709
9477
  if(t.classList.contains('handle')){const id=t.dataset.mid||[...selIds][0],m=byId(id),h=+t.dataset.h;if(!m)return;buildSnap(id);
8710
9478
  drag={type:'end',h,id,anchor:m.wp[1-h].slice(),orig:m.wp[h].slice(),pre:snapshot()};svg.setPointerCapture(e.pointerId);e.preventDefault();return;} // anchor = the fixed end (length ref); orig = where this end started (moved ref)
8711
- if(t.classList.contains('lblhot')){const prof=t.dataset.prof;
8712
- if(mode!=='add'&&picking&&pickKind==='profile'&&selIds.size===1){const id=[...selIds][0];picking=false;edit(()=>{const m=byId(id);ModelCmd.patchMember(m,{profile:prof,rfi:_wt(prof)==null});if(!profs.includes(prof)){profs.push(prof);profs.sort();}});return;} // in Add mode a profile pick ALWAYS means "adopt as the current add profile" (a 3D draw can leave a member selected)
8713
- if(mode==='add'&&!drawDraft){addProfile=prof;if(picking&&pickKind==='profile'){picking=false;render();return;} // adopt a label's profile ONLY before the first click; mid-draw a label click falls through to drawClick → places the END on that label's point (mirrors the seg guard)
8714
- const hi=document.getElementById('addProf');if(hi)hi.value=addProfile;const ph=document.getElementById('pickHint');if(ph){ph.classList.add('pick');setTimeout(()=>ph&&ph.classList.remove('pick'),450);}return;}
8715
- return;}
9479
+ if(t.classList.contains('lblhot')){applyProfileLabel(t.dataset.prof);return;} // Add mode adopts it; an armed inspector applies it. Enter/Space call the same path above.
8716
9480
  if(t.classList.contains('dethot')){const det=t.dataset.det;
8717
9481
  if(picking&&pickKind==='detail'&&pickEnd){const o=pickEnd;picking=false;pickEnd=null;edit(()=>{ModelCmd.patchEnd(o,{detail:det});});}return;}
8718
9482
  {const cg=t.closest('g.cohot');if(cg){const sheet=cg.dataset.coSheet,prev=cg.dataset.coPrev; // Workstream B smart jump
@@ -8977,13 +9741,13 @@ function updCalloutToggle(){const b=document.getElementById('calloutToggleB');if
8977
9741
  document.getElementById('calloutToggleB').onclick=e=>{e.stopPropagation();calloutsVisible=!calloutsVisible;updCalloutToggle();render();};
8978
9742
  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)
8979
9743
  document.getElementById('plToggleB').onclick=e=>{e.stopPropagation();C.prop_labels.vis2d=!C.prop_labels.vis2d;updPlToggle();refreshPropLabels();};
8980
- const REF_TIP='Show or hide the traced reference sheet (the PDF/SVG drawing under the model). Hidden, it also stops contributing snap points.';
9744
+ const REF_TIP='Show or hide the source drawing under the model. The source image is visual context; traced lines—not the raster—provide snap points.';
8981
9745
  function updRefToggle(){const b=document.getElementById('refToggleB');if(!b)return;const on=refSheetOn;b.disabled=!hasOverlay();b.classList.toggle('on',on);b.setAttribute('aria-checked',String(on));
8982
- // #507: a non-drawable layer is excluded whatever this toggle says, and NOTHING in the editor sets
8983
- // that flag — the reader writes it and Steel Filter only dims the row. So say it here, on the one
8984
- // control a user consults to reason about the backdrop, instead of leaving the omission silent.
9746
+ // #507 + #875: a non-drawable layer remains absent from traced vectors and snaps, while the reviewed
9747
+ // source image may still show its printed ink faintly as context. Say both halves where the user
9748
+ // reasons about the backdrop instead of making "visible" sound equivalent to "snappable".
8985
9749
  const n=hiddenLayerCount();
8986
- b.setAttribute('data-tip',REF_TIP+(n?(' '+n+' layer'+(n===1?'':'s')+' marked “listed but not drawn” '+(n===1?'is':'are')+' always excluded — review them in Drawing Filter.'):''));}
9750
+ b.setAttribute('data-tip',REF_TIP+(n?(' '+n+' layer'+(n===1?'':'s')+' marked “listed but not drawn” '+(n===1?'is':'are')+' excluded from traced linework and snap points, though its printed ink may remain faintly visible in the source image.'):''));}
8987
9751
  document.getElementById('refToggleB').onclick=e=>{e.stopPropagation();refSheetOn=!refSheetOn;try{localStorage.setItem('steel:refSheet:v2',refSheetOn?'1':'0');}catch(_){}updRefToggle();render();};
8988
9752
  document.getElementById('gridEditB').onclick=()=>{setGridMode(!gridMode);render();};
8989
9753
  document.getElementById('dimStyleB').onclick=()=>{setDimStyleMode(!dimStyleMode);render();};
@@ -9371,6 +10135,27 @@ selFly.addEventListener('click',e=>{const row=e.target.closest('.frow');if(!row)
9371
10135
  const k=row.dataset.k;def.store[k]=!(def.store[k]!==false);
9372
10136
  saveSelFilter();reflectSelFilter();render();});
9373
10137
  document.addEventListener('click',e=>{if(selFly.classList.contains('open')&&!selFly.contains(e.target)&&!selBar.contains(e.target))closeSelFly();});
10138
+ /* The two review stats open the same popover. Wired here beside #selFly's own wiring because they are the
10139
+ same interaction — a stat that toggles a capped list — and a second, differently-behaving popover in the
10140
+ header is exactly the drift the baseline is meant to prevent. */
10141
+ {const rf=document.getElementById('reviewFly');
10142
+ for(const [id,kind] of [['reviewStat','needs-review'],['untrackedStat','untracked']]){
10143
+ const b=document.getElementById(id);if(b)b.onclick=(e)=>{e.stopPropagation();openReviewFly(kind,b);};}
10144
+ // Esc returns focus to the trigger it came from, so a keyboard user is not dropped at the top of the page.
10145
+ /* ONE Esc, ONE action. Without stopPropagation the global Escape ladder still runs to its terminal
10146
+ rung and clears the selection (and steps out of a drilled connection) — so dismissing this list would
10147
+ silently throw away what the user had selected. Every other capture-phase Esc in this file stops. */
10148
+ document.addEventListener('keydown',e=>{
10149
+ if(e.key!=='Escape'||!rf||!rf.classList.contains('open'))return;
10150
+ /* Consume it ONLY while the popover or its trigger owns focus. Swallowing every Escape just because the
10151
+ list happens to be open would steal it from whatever the user Tabbed to next. */
10152
+ const back=reviewFlyKind==='needs-review'?'reviewStat':'untrackedStat',t=document.getElementById(back);
10153
+ const mine=rf.contains(document.activeElement)||document.activeElement===t;
10154
+ closeReviewFly();
10155
+ if(!mine)return;
10156
+ e.stopPropagation();e.preventDefault();
10157
+ if(t)t.focus();},true);
10158
+ document.addEventListener('click',e=>{if(rf&&rf.classList.contains('open')&&!rf.contains(e.target))closeReviewFly();});}
9374
10159
  Promise.resolve().then(()=>{selFilterReady=true;reflectSelFilter();}).catch(e=>console.warn('selFilter: initial reflect failed',e)); // defer the first paint: memberTypeRecords() reads BASE_MEMBER_TYPES, a const declared later in main() — run once main() has fully initialized (microtask flushes before paint, so no flash). Arm selFilterReady BEFORE the first reflect so a throw here can't permanently disable render()'s per-edit sync (reflectSelFilter is idempotent — arm-then-run is safe). Log a throw rather than swallow it: a silent failure leaves the bar in its inert default HTML state while selFilter is still active.
9375
10160
  // --- Move/Copy split-button dropdowns: same open/close discipline as the ⋯ menu ---
9376
10161
  function wireCmMenu(caretId,menuId){const b=document.getElementById(caretId),m=document.getElementById(menuId);
@@ -9843,7 +10628,10 @@ const view3dApi={
9843
10628
  onClipsChange:()=>{const v=window.Steel3DView;if(v&&v.selectedClips&&v.selectedClips().length)clearWholeReferenceSelection();build3DLegend();}, // a clip added / removed / toggled → its renderer-side selection also takes the one action target, then rebuild the legend's Clip section
9844
10629
  beginClipEdit:()=>pushUndo(snapshot()), // a clip / work-area manipulation → push a pre-edit snapshot so Ctrl+Z/Y restores it
9845
10630
  onClipModeChange:(m)=>{const b=document.getElementById('m3dClip');if(b){b.classList.toggle('on',!!m);b.textContent=m?'Clip ✕':'Clip ▾';}}, // armed → button fills brand-blue + becomes a cancel target (✕ = cancel)
9846
- onInsertModeChange:(on)=>{const b=document.getElementById('m3dInsert');if(b){b.classList.toggle('on',!!on);b.textContent=on?'✕ Cancel insert':'Insert…';} if(!on)favDisarmed();}, // armed → cancel target; disarm also clears any armed favourite (the pinned bar + the .armed row)
10631
+ onInsertModeChange:(on)=>{const b=document.getElementById('m3dInsert');if(b){b.classList.toggle('on',!!on);b.textContent=on?'✕ Cancel insert':'Insert…';} if(!on)favDisarmed();
10632
+ /* Esc at the crosshair cancels a re-placement before ANY of it happened — nothing was untracked and
10633
+ nothing moved, so the only thing to undo is the button's armed look. */
10634
+ if(!on&&connReplaceArm){connReplaceArm=null;panel();}}, // armed → cancel target; disarm also clears any armed favourite (the pinned bar + the .armed row)
9847
10635
  // A canvas click selected (or deselected) a whole reference model. Without this the binding is
9848
10636
  // one-way — the panel drives the 3D view but a pick in the 3D view leaves the panel showing the
9849
10637
  // previous row, which is worse than no highlight because it is confidently wrong. Found by clicking
@@ -9887,6 +10675,24 @@ const view3dApi={
9887
10675
  pushReferences();if(legendTab==='refs')renderRefsTab();if(refSelectedObjIdx!==null)panel();
9888
10676
  toast('Could not draw the new geometry for “'+((refById(id)||{}).name||id)+'” — keeping the previous view');
9889
10677
  },
10678
+ onConnMemberPickChange:()=>{}, // the chosen set shows as the 3D selection + the chip's live count; nothing else to reflect
10679
+ onConnMemberPickAbandon:(jointId,reason)=>{ // left the pick without answering it (focus moved, left 3D, pane went inactive)
10680
+ const nm=(connMemberPick&&connMemberPick.id===jointId?connMemberPick.name:null)||'connection';
10681
+ connMemberPick=null; // MUST clear, or applyRevalidation goes on suppressing this joint's warning forever
10682
+ console.warn('steel-editor: connection member pick abandoned',{jointId,reason});
10683
+ /* A re-placement transaction is WAITING on this pick, and abandoning is one of its four settle paths —
10684
+ it fires on focus moves and pane switches, which the 3D view's own comment calls "all ordinary user
10685
+ actions". Handing it to the transaction is what releases the write gate; without this the gate leaks
10686
+ and saving is disabled for the rest of the session. It also owns the message on that path. */
10687
+ if(settleConnPick(jointId,{commit:false,reason}))return;
10688
+ toast('“'+nm+'” placed — no members named, so it is not being watched');
10689
+ },
10690
+ /* Enter AND Esc both arrive here (steel-3d-view.js) — Esc as `skipped` with an empty list, not as an
10691
+ abandon. So this is the transaction's ordinary settle path, and the plain placement path underneath. */
10692
+ onConnMemberPickCommit:(jointId,memberIds,skipped)=>{
10693
+ if(settleConnPick(jointId,{commit:true,memberIds,skipped}))return;
10694
+ placeConnection(jointId,memberIds,skipped);
10695
+ },
9890
10696
  onBasePickModeChange:()=>{}, // Mode B armed state shows via the 3D crosshair + elevation readout; nothing else to reflect
9891
10697
  onBasePick:(p)=>{ // Mode B: retarget the armed column's base to the picked elevation (world mm → inches), ONE undo entry
9892
10698
  const m=byId(basePickColId); if(!m||m.role!=='column'||!m.col){toast('No column to trim');return;}
@@ -9905,6 +10711,11 @@ const view3dApi={
9905
10711
  toast('Column '+m.id+' base '+dir+' to '+where+' — base plate re-seated');
9906
10712
  },
9907
10713
  onInsertPlace:(pick,pending)=>{
10714
+ /* FIRST, because it is the one branch that must not mint a new id: "Place again" re-commits the
10715
+ EXISTING joint through the transaction that untracks it before anything moves (§5.3). Not awaited —
10716
+ the 3D view disarms the crosshair the moment this returns, which is exactly what we want while the
10717
+ transaction runs. */
10718
+ if(pending&&pending.kind==='connection-replace'&&pending.jointId){connReplaceArm=null;replaceConnectionAt(pending.jointId,pick);return;}
9908
10719
  if(pending&&pending.kind==='favourite'&&pending.favourite){const f=pending.favourite;
9909
10720
  // Slice F1: apply a saved favourite. base-plate → a column; shear-plate → the nearest beam end; custom → drop the
9910
10721
  // mesh at the pick. Wrong target → a corrective toast + no-op (the sticky arm stays on for a retry). Reuses the
@@ -9947,7 +10758,7 @@ const view3dApi={
9947
10758
  const joint={id,kind:'custom',name:f.name||'Imported connection',place:pick.point,geometry:f.geometry,source:'user'};
9948
10759
  if(pick.anchorId)joint.main=pick.anchorId;
9949
10760
  edit(()=>{if(!Array.isArray(C.joints))C.joints=[];C.joints.push(joint);selIds=new Set(f.geometry.map((gg,i)=>id+':'+(gg.id||'m'+i)));});
9950
- toast('“'+f.name+'” placed'+(pick.anchorId?' on '+pick.anchorId:'')+' — click to place another, or Esc');return;
10761
+ armConnMemberPick(id,pick.anchorId,f.name||'Imported connection');return;
9951
10762
  }
9952
10763
  toast('That favourite has no geometry to place');return;
9953
10764
  }
@@ -9993,8 +10804,11 @@ const view3dApi={
9993
10804
  const joint={id,kind:'custom',name:conn.name||'Imported connection',place:pick.point,geometry:conn.geometry,source:'user'};
9994
10805
  if(pick.anchorId)joint.main=pick.anchorId; // snapped to a member face → record it for the inspector's "on member" line
9995
10806
  edit(()=>{if(!Array.isArray(C.joints))C.joints=[];C.joints.push(joint);selIds=new Set(conn.geometry.map((g,i)=>id+':'+(g.id||'m'+i)));});
9996
- toast(rc?('Imported “'+(conn.name||'connection')+'” as geometry — drop it on a '+(rc.kind==='shear-plate'?'beam end to apply it as an editable shear plate':'column to apply it as an editable base plate'))
9997
- :('Connection “'+(conn.name||'imported')+'” placed'+(pick.anchorId?' on '+pick.anchorId:'')+' — select it to move or replace'));
10807
+ // ONE toast: toast() sets textContent on a single shared element, so a recipe hint fired here would be
10808
+ // erased by the pick instruction in the same tick — and the hint is the actionable half (how to get an
10809
+ // editable connection instead of a frozen mesh). It rides the pick's own sentence instead.
10810
+ armConnMemberPick(id,pick.anchorId,conn.name||'Imported connection',
10811
+ rc?('It can be an editable '+(rc.kind==='shear-plate'?'shear plate — drop it on a beam end':'base plate — drop it on a column')):null);
9998
10812
  return;
9999
10813
  }
10000
10814
  toast('That connection has no geometry to place');return;
@@ -10035,6 +10849,416 @@ function armConnectionInsert(connection){if(!connection||!Array.isArray(connecti
10035
10849
  const recognized=connection.recipe&&connection.recipe.kind==='base-plate';
10036
10850
  toast(recognized?('Click a column to place “'+nm+'” as an editable base plate — Esc to cancel')
10037
10851
  :('Click in the model to place “'+nm+'” — Esc to cancel'));}
10852
+ let connMemberPick=null; // {id,name} of the connection whose members are being named, or null
10853
+ /* After a CUSTOM connection is placed, ask which members it joins (connection review, design §5.1).
10854
+ The geometry is already committed locally at this point — this step records the RELATIONSHIP, which
10855
+ cannot be recovered from the frozen mesh afterwards. The member the placement click snapped to is
10856
+ pre-picked, because that is the member the user already chose by snapping to its face.
10857
+ Outside a project there is nowhere to record it (the store is per-project), so the step is skipped
10858
+ entirely rather than asking a question whose answer would be dropped. */
10859
+ /* RETURNS whether it actually armed. The re-placement transaction awaits this pick's settlement, so an
10860
+ arm that refused would leave a promise nobody can ever resolve — and the write gate held behind it. */
10861
+ function armConnMemberPick(jointId,anchorId,name,hint){
10862
+ const nm=name||'connection';
10863
+ // Skipping the RECORDING outside a project is correct — the store is per-project. Skipping the
10864
+ // CONFIRMATION is not: the user would see geometry appear and be told nothing at all.
10865
+ if(!PROJECT){toast('“'+nm+'” placed — open this model from a project to have its steel watched');return false;}
10866
+ if(!(window.Steel3DView&&window.Steel3DView.setConnMemberPick)){
10867
+ console.warn('steel-editor: no 3D member pick — this connection will not be watched');
10868
+ toast('“'+nm+'” placed, but what it joins can’t be recorded here — it is not being watched');
10869
+ return false;
10870
+ }
10871
+ connMemberPick={id:jointId,name:name||'connection'};
10872
+ window.Steel3DView.setConnMemberPick({jointId,chosen:anchorId?[anchorId]:[]});
10873
+ toast('Click each member “'+connMemberPick.name+'” joins — Enter to confirm, Esc to skip'+(hint?' · '+hint:''));
10874
+ return true;
10875
+ }
10876
+ /* The awaited member pick, as ONE slot.
10877
+ Keyed on the joint id as well as its presence: a pick settling for a DIFFERENT joint than the one this
10878
+ transaction armed must fall through to the ordinary path, not resolve somebody else's await with an
10879
+ answer about the wrong connection. Returns whether it consumed the event, so the caller knows whether
10880
+ it still owns the message. */
10881
+ let connPickSettle=null; // {jointId, resolve} while a transaction is awaiting the pick
10882
+ function settleConnPick(jointId,outcome){
10883
+ const w=connPickSettle;
10884
+ if(!w||w.jointId!==jointId)return false;
10885
+ connPickSettle=null;
10886
+ w.resolve(outcome);
10887
+ return true;
10888
+ }
10889
+ /**
10890
+ * The awaited pick, plus a watchdog for the case where nobody ever answers it.
10891
+ *
10892
+ * THE ROOT CAUSE IS FIXED AT THE SOURCE — `dispose()` in steel-3d-view.js used to drop `connPick`
10893
+ * without firing either callback, so this promise never settled and the write gate stayed held for the
10894
+ * session. This is the belt to that fix's braces, and it earns its place rather than duplicating it:
10895
+ * the transaction is awaiting an event owned by ANOTHER module, and a leaked gate is severe enough
10896
+ * that "every teardown remembers to call the callback" is too fragile an invariant to rest it on. The
10897
+ * watchdog asks a question the editor can answer for itself — is that pick still armed? — so a future
10898
+ * teardown that forgets costs one polling interval instead of the session's saves.
10899
+ *
10900
+ * Deliberately NOT a plain timeout: naming the members is a human action with no time limit, and a
10901
+ * timer would settle a transaction the user is still working through.
10902
+ */
10903
+ function awaitConnPick(jointId){
10904
+ return new Promise(resolve=>{
10905
+ connPickSettle={jointId,resolve};
10906
+ /* THIS joint's pick, not "a" pick. `connMemberPick()` returns the chosen ids and never says whose
10907
+ they are, so a pick replaced by another joint's would read as still-armed and the watchdog would
10908
+ poll forever over a transaction nobody can settle — a hole in the very backstop that exists so a
10909
+ hole like it cannot be fatal. (Found by review.) */
10910
+ const armed=()=>{
10911
+ const v=window.Steel3DView;
10912
+ return !!(v&&v.connMemberPickJoint&&v.connMemberPickJoint()===jointId);
10913
+ };
10914
+ const tick=()=>{
10915
+ if(!connPickSettle||connPickSettle.jointId!==jointId)return; // settled normally; nothing to do
10916
+ if(armed()){setTimeout(tick,500);return;}
10917
+ console.warn('steel-editor: the member pick vanished without settling — releasing the re-placement',{jointId});
10918
+ settleConnPick(jointId,{commit:false,reason:'pick-lost'});
10919
+ };
10920
+ setTimeout(tick,500);
10921
+ });
10922
+ }
10923
+ /* Commit the placement through the command that establishes a baseline. Flush FIRST: an in-flight
10924
+ debounced autosave would otherwise race this write, and a later stale whole-contract PUT could
10925
+ overwrite its result. The flush's ETag is the precondition, so a genuinely concurrent write is
10926
+ refused rather than silently clobbered. */
10927
+ /* RE-COMMITTING AN EXISTING JOINT ID IS SAFE ONLY THROUGH `replaceConnectionAt`, AND THAT IS WHY IT
10928
+ EXISTS. This path on its own is not: the flush below publishes the geometry as an ordinary client
10929
+ write first, and if the joint's `self` is unchanged (only the named members differ) the previous
10930
+ baseline still corroborates — so a failure before the command stages leaves a stale row reading CLEAN
10931
+ over the wrong steel, with `failClosed` never firing because nothing staged. `replaceConnectionAt`
10932
+ closes that by marking the joint untracked BEFORE the geometry moves, so a torn re-placement degrades
10933
+ to "not being watched" instead of to a confident lie. Reaching a re-commit by any other route would
10934
+ re-open the hole.
10935
+
10936
+ RETURNS whether the command actually staged, so the transaction knows whether it still owes a
10937
+ fail-closed save. `token` admits its flush past the transaction's own write gate. */
10938
+ async function placeConnection(jointId,memberIds,skipped,token){
10939
+ const name=(connMemberPick&&connMemberPick.id===jointId?connMemberPick.name:null)||'connection';
10940
+ if(!PROJECT){connMemberPick=null;return false;}
10941
+ const joint=(Array.isArray(C.joints)?C.joints:[]).find(j=>j&&j.id===jointId);
10942
+ if(!joint){connMemberPick=null;toast('That connection is no longer in the model');return false;}
10943
+ let mid=null;
10944
+ try{
10945
+ await flushContractWith(token||null);
10946
+ mid=newMutationId();claimMutation(mid);
10947
+ const headers={'content-type':'application/json','x-floless-mutation-id':mid};
10948
+ if(serverEtag)headers['if-match']=serverEtag;
10949
+ const res=await fetch('/api/projects/'+encodeURIComponent(PROJECT)+'/connections/place',{method:'POST',headers,body:JSON.stringify({joint,memberIds})});
10950
+ const d=await res.json().catch(()=>({}));
10951
+ if(!res.ok){
10952
+ releaseMutation(mid);
10953
+ console.warn('steel-editor: placement command refused',{status:res.status,code:d.code,error:d.error});
10954
+ // 428 is the client failing to send a precondition, which is a FloLess bug, not something the user
10955
+ // can act on — never show its header vocabulary. "Place it again" IS now a real action (the
10956
+ // inspector's Place again…), so the sentence names the recovery instead of stopping at the fault.
10957
+ const why=(res.status===428||!d.error)?'what it joins could not be recorded':String(d.error);
10958
+ toast('“'+name+'” is placed — '+why+', so it is not being watched. Use Place again… to start watching it.');
10959
+ return false;
10960
+ }
10961
+ // Adopt the tag; do NOT re-install the contract. installMemberEndContract clears undo/redo, and design
10962
+ // §5.0 is explicit that undoing a placement must keep working ("one Ctrl+Z restores the joint") — the
10963
+ // same reason server/index.ts deliberately does not return the contract on an ordinary move. Nothing is
10964
+ // lost by skipping it: the client flushed this document a moment ago and the route only upserts the very
10965
+ // joint the client sent, so C already matches what was published. It also avoids shipping a
10966
+ // tens-of-megabyte contract back into the page on every placement.
10967
+ const hdrTag=d.etag||res.headers.get('ETag'),rev=Number.isSafeInteger(d.storeRevision)?d.storeRevision:null;
10968
+ /* Adopt the tag and the revision TOGETHER, and only when this reply is at least as new as what the tab
10969
+ already holds. This POST is outside the save queue, so an autosave can land while it is in flight;
10970
+ taking the tag unconditionally while keeping the newer revision would leave the pair torn and make
10971
+ the user's own next save a false 412. Older reply → keep both, the newer save already owns them. */
10972
+ if(hdrTag&&rev!==null&&rev>=serverRevision){const pv=serverEtag;serverEtag=hdrTag;restampDraftBase(pv,hdrTag);serverRevision=rev;}
10973
+ else console.warn('steel-editor: placement reply not adopted (a newer save owns the tab, or the reply was incomplete)',{etag:hdrTag,storeRevision:d.storeRevision,held:serverRevision});
10974
+ const n=(d.memberIds||memberIds||[]).length;
10975
+ // Never claim it is watched when it is not: skipping is legitimate, and saying so plainly is what
10976
+ // stops "placed ✓" being read as "this connection is being checked".
10977
+ toast(skipped||!n
10978
+ ? '“'+name+'” placed — no members named, so it is not being watched'
10979
+ : '“'+name+'” placed on '+n+' member'+(n===1?'':'s')+' — you will be told if that steel moves');
10980
+ return true; // the command STAGED, whatever it decided about members — the caller owes no fail-closed save
10981
+ }catch(e){
10982
+ if(mid)releaseMutation(mid);
10983
+ console.warn('steel-editor: placement command failed',e);
10984
+ toast('“'+name+'” is placed, but what it joins could not be recorded');
10985
+ return false;
10986
+ }finally{
10987
+ /* UNCONDITIONAL, and after the flush rather than before it. This handle suppresses the joint's
10988
+ "may need review" clause while it is being answered, so a path that leaves it set would silence
10989
+ that warning for the rest of the page's life — on the one connection that is provably not watched.
10990
+ Clearing it in `finally` is what stops a future early return re-introducing that. */
10991
+ connMemberPick=null;
10992
+ }
10993
+ }
10994
+ /* -- The review VERBS (design 5.1). One dispatcher, because they differ only in what they do to a
10995
+ single sidecar row and share their preconditions, their 409 and their reply shape. All three take
10996
+ `reviewRevision`; only sign-off takes `If-Match`, because only sign-off can manufacture an
10997
+ acceptance - reopen and untrack both move the state conservatively, and refusing them on a stale tag
10998
+ would make the safe action harder to take than the dangerous one. */
10999
+ async function reviewVerb(verb,jointId,opts){
11000
+ const o=opts||{};
11001
+ if(!PROJECT)throw new Error('this model is not open from a project');
11002
+ const rev=Number.isSafeInteger(o.reviewRevision)?o.reviewRevision:reviewAt.reviewRevision;
11003
+ if(!Number.isSafeInteger(rev)||rev<0)throw new Error('the review state has not loaded yet');
11004
+ const headers={'content-type':'application/json'};
11005
+ if(o.ifMatch)headers['if-match']=o.ifMatch;
11006
+ let res;
11007
+ /* A `fetch` rejection is not prose for a user — "Failed to fetch" and "NetworkError when attempting to
11008
+ fetch resource" are the browser talking to a developer. Marked so the caller can say something the
11009
+ user can act on instead. (Found by review.) */
11010
+ try{res=await fetch('/api/projects/'+encodeURIComponent(PROJECT)+'/connections/'+encodeURIComponent(jointId)+'/'+verb,
11011
+ {method:'POST',headers,body:JSON.stringify({reviewRevision:rev})});}
11012
+ catch(e){const err=new Error('the server could not be reached');err.transport=true;throw err;}
11013
+ const d=await res.json().catch(()=>{console.warn('steel-editor: a review reply was not readable JSON',{verb,status:res.status});return {};});
11014
+ if(!res.ok){
11015
+ const err=new Error(d.error||('the review action failed ('+res.status+')'));
11016
+ err.code=d.code;err.status=res.status;throw err;
11017
+ }
11018
+ return d;
11019
+ }
11020
+ /* Take a verb's reply. The verbs return the FULL summary with the contract tag UNCHANGED, so it is
11021
+ installable directly - but only while the document it describes is still the one on screen. When it
11022
+ is not, the reply is discarded and the refresh cycle fetches the post-save snapshot instead; the
11023
+ server's success is kept either way, because it happened. */
11024
+ function installVerbReply(d,describesVisible){
11025
+ if(describesVisible&&d&&d.review&&Number.isSafeInteger(d.storeRevision)){
11026
+ const outcome=installReviewSummary(d.review,d.storeRevision,contractEventEpoch);
11027
+ if(outcome==='installed'||outcome==='recovered'||outcome==='noop'||outcome==='unavailable')return true;
11028
+ }
11029
+ /* THE REPLY DID NOT DESCRIBE WHAT IS ON SCREEN — so asking the server again RIGHT NOW gets the same
11030
+ wrong answer, not a better one. The store still holds the pre-edit document, its summary satisfies
11031
+ the bounds, and the cycle would settle on it: sign-off's "✓ Reviewed" painted over steel the user
11032
+ has just moved and nobody has reviewed. That is the manufactured approval this whole feature exists
11033
+ to prevent, arriving through the guard meant to stop it.
11034
+
11035
+ So when a write is already pending, say nothing and let it answer. Its own-write refresh fires when
11036
+ it lands, with a summary derived from the document the user is actually looking at. And if that
11037
+ write FAILS, the surface keeps the pre-verb state — needs-review — which is the conservative
11038
+ direction and the right one to be stuck in. (Codex code review.) */
11039
+ if(!serverHasVisibleDocument())return false;
11040
+ markReviewDirty({storeRevision:serverRevision,
11041
+ reviewRevision:Number.isSafeInteger(d&&d.reviewRevision)?d.reviewRevision:reviewAt.reviewRevision});
11042
+ return false;
11043
+ }
11044
+ /* A refused verb, said in the user's terms. 409 is the ordinary two-tab outcome and gets its own
11045
+ sentence - it is not a fault, and the surface is about to correct itself. */
11046
+ function reviewVerbFailed(e,fallback){
11047
+ console.warn('steel-editor: review action refused',{code:e&&e.code,status:e&&e.status,message:e&&e.message});
11048
+ /* 409 deliberately keeps its unguarded re-read. The sidecar demonstrably moved, so the `+1` bound can
11049
+ only be satisfied by a genuinely newer generation — unlike the fall-through above, this cannot
11050
+ settle on the pre-edit snapshot. The asymmetry is the point, not an oversight. */
11051
+ if(e&&e.status===409){toast('Someone else already reviewed this connection — its status just updated');markReviewDirty({storeRevision:reviewAt.storeRevision,reviewRevision:reviewAt.reviewRevision+1});return;}
11052
+ /* The server's own 4xx prose is written FOR the user and names what to do; anything else — a transport
11053
+ failure, a 5xx behind an HTML error page — is not, so the caller's sentence wins, because it is the
11054
+ only one that names the connection. */
11055
+ const speakable=e&&!e.transport&&e.status>=400&&e.status<500&&e.message;
11056
+ toast(speakable?String(e.message)
11057
+ :(fallback+' — '+((e&&e.transport)?'the server could not be reached':'try again in a moment')));
11058
+ }
11059
+ /* Is the document on screen still the one that flush published? THREE tripwires, each answering a
11060
+ different question, because no one of them is total on its own - see `modelEditGeneration`. */
11061
+ function visibleDocumentIs(flushed){
11062
+ return serverEtag===flushed.etag && saveT===null && modelEditGeneration===flushed.generation;
11063
+ }
11064
+ /* MARK AS REVIEWED - the one verb that grants authority, so it is the one with the generation guard.
11065
+ 5.2: `If-Match` proves which generation the SERVER had, never which one the user LOOKED AT. The three
11066
+ tripwires above decide whether the flushed document is still the visible one; any one of them
11067
+ refuses, because recording an acceptance of a state nobody reviewed is the exact failure this feature
11068
+ exists to prevent. */
11069
+ async function signOffConnection(jointId){
11070
+ const j=(Array.isArray(C.joints)?C.joints:[]).find(x=>x&&x.id===jointId);
11071
+ const name=(j&&j.name)||'This connection';
11072
+ if(!PROJECT||!ReviewClient||reviewUnavailable||!reviewSummary){toast('The review state is not available right now — try again in a moment');return;}
11073
+ let flushed;
11074
+ try{flushed=await flushContractWith(null);}
11075
+ catch(e){console.warn('steel-editor: could not flush before sign-off',e);toast('Your latest edits could not be saved, so “'+name+'” was not marked reviewed');return;}
11076
+ // No tag means no precondition, and an unconditional sign-off would assert exactly the authority the
11077
+ // precondition exists to withhold. Refuse rather than send one.
11078
+ if(!flushed||!flushed.etag){toast('Could not confirm which version you are looking at — “'+name+'” was not marked reviewed');return;}
11079
+ if(!visibleDocumentIs(flushed)){toast('The model changed while that was saving — check “'+name+'” again, then mark it reviewed');return;}
11080
+ let d;
11081
+ try{d=await reviewVerb('sign-off',jointId,{ifMatch:flushed.etag,reviewRevision:reviewSummary.reviewRevision});}
11082
+ catch(e){reviewVerbFailed(e,'“'+name+'” could not be marked reviewed');return;}
11083
+ /* GUARD THE REPLY TOO, or the window is moved rather than closed: an edit that landed while the
11084
+ request was in flight makes the returned summary describe the OLDER contract. The sign-off itself
11085
+ stands - the server took it against the generation we proved - but its summary must not be painted
11086
+ over a document it does not describe. */
11087
+ /* THE TOAST HAS TO MATCH THE SURFACE. When the reply is declined the chip stays amber and the
11088
+ button stays on screen, so the flat sentence would have the two disagreeing — and the obvious
11089
+ response to that is to press the button again. (Found by review.) */
11090
+ const painted=installVerbReply(d,visibleDocumentIs(flushed));
11091
+ toast(painted
11092
+ ? '“'+name+'” marked reviewed — Ctrl+Z will not undo this'
11093
+ : '“'+name+'” marked reviewed — Ctrl+Z will not undo this, and the chip catches up once your latest edit saves');
11094
+ }
11095
+ /* Is a pending write going to re-ask this question for us? Only `scheduleSave` sets `saveT`, and the
11096
+ write it schedules ends in the own-write refresh — so when one is pending, asking NOW can only ever
11097
+ get the pre-edit answer back. */
11098
+ /**
11099
+ * Does the STORE hold the document that is on screen?
11100
+ *
11101
+ * The one question both verbs need, stated positively on purpose. An earlier spelling asked "is a
11102
+ * refresh already coming?", which named a DIFFERENT fact and was wrong in the `err`/`conflict` case —
11103
+ * there the document is unsaved and no refresh is coming at all, so the name promised something the
11104
+ * predicate could not deliver.
11105
+ *
11106
+ * `saveT` alone will not do: `scheduleSave` nulls it the moment the timer fires, so for the whole time
11107
+ * the PUT is actually on the wire it reads false — the middle of the very window this covers. The pill
11108
+ * spans all of it, because `setSaved('dirty')` goes up with the debounce and only the settling response
11109
+ * takes it down. (Both found by review.)
11110
+ *
11111
+ * WHERE THE ANSWER IS "no", NOTHING IS PROMISED. A pending write's refresh rides its own SSE echo, so
11112
+ * with the stream down nothing re-asks and the surface stays as it was — which is why neither verb
11113
+ * DEPENDS on a refresh arriving: reopen drops its acceptance locally, and sign-off's toast says the chip
11114
+ * will catch up. This decides only whether asking the server right now could tell us anything new.
11115
+ */
11116
+ function serverHasVisibleDocument(){
11117
+ return saveT===null&&!editorHasUnsavedWork();
11118
+ }
11119
+ /* REOPEN - the reversal of sign-off, and the reason it must exist: sign-off writes no `edit()` entry, so
11120
+ Ctrl+Z does not undo it. No flush and no `If-Match`: it moves the state back toward needing review,
11121
+ which is the conservative direction, so a slightly stale view of the steel cannot do harm. */
11122
+ async function reopenConnectionReview(jointId){
11123
+ const j=(Array.isArray(C.joints)?C.joints:[]).find(x=>x&&x.id===jointId);
11124
+ const name=(j&&j.name)||'This connection';
11125
+ if(!PROJECT||!ReviewClient||reviewUnavailable||!reviewSummary){toast('The review state is not available right now — try again in a moment');return;}
11126
+ /* Reopen publishes nothing, so it needs no flush and no `If-Match` — but the user can still edit while
11127
+ the request is in flight, and the reply would then describe the older document. The verb is safe to
11128
+ take on a stale view (it moves the state conservatively); PAINTING its summary is what is not. Same
11129
+ question as sign-off, so the same guard rather than a second rule. (Codex code review.) */
11130
+ const at={etag:serverEtag,generation:modelEditGeneration};
11131
+ let d;
11132
+ try{d=await reviewVerb('reopen',jointId,{reviewRevision:reviewSummary.reviewRevision});}
11133
+ catch(e){reviewVerbFailed(e,'“'+name+'” could not be reopened');return;}
11134
+ /* DROP THE ACCEPTANCE LOCALLY, FIRST, AND UNCONDITIONALLY.
11135
+ The first cut of this guard simply reused sign-off's rule — install the reply only while it still
11136
+ describes the visible document — and that inverted the safety argument. For sign-off, declining to
11137
+ paint leaves NEEDS-REVIEW on screen, which is the conservative direction. For reopen, the pre-verb
11138
+ state is "✓ Reviewed": declining to paint leaves the surface asserting a human acceptance the server
11139
+ has just erased, and it stands until the next save's echo — forever if that save fails or the live
11140
+ channel is down. That is the manufactured approval this feature exists to prevent, arriving through
11141
+ the guard written to stop it. (Found by review.)
11142
+ Applying it locally is safe in a way applying a sign-off never is: reopen only ever REMOVES an
11143
+ acceptance, so a local copy of it cannot overstate what the server holds. */
11144
+ if(reviewSummary&&Array.isArray(reviewSummary.signedOff)&&reviewSummary.signedOff.indexOf(jointId)!==-1){
11145
+ reviewSummary={...reviewSummary,signedOff:reviewSummary.signedOff.filter(id=>id!==jointId)};
11146
+ repaintReviewSurface();
11147
+ }
11148
+ toast('“'+name+'” reopened — it will ask to be checked again');
11149
+ /* BOTH halves, and the second is what a flush would otherwise have bought. Sign-off can settle for
11150
+ "unchanged since I published it", because its flush guarantees the store holds what the user saw.
11151
+ Reopen never publishes, so the store may have been behind before the request was even sent — and
11152
+ then "unchanged since dispatch" is true while the reply still describes an older document.
11153
+ Asserted by test: an in-flight save at dispatch passes `visibleDocumentIs` and must NOT install. */
11154
+ installVerbReply(d,serverHasVisibleDocument()&&visibleDocumentIs(at));
11155
+ }
11156
+ /* -- PLACE AGAIN - ONE TRANSACTION (design 5.3), and the riskiest thing in this feature.
11157
+
11158
+ The hazard it exists for: the placement command's flush publishes the geometry as an ORDINARY write
11159
+ before the command stages, and if the joint's `self` is unchanged the previous baseline still
11160
+ corroborates. So a tear anywhere between the flush and the staging leaves the row reading CLEAN over
11161
+ steel it was never checked against - and `failClosed` does NOT fire, because nothing staged.
11162
+
11163
+ The answer is to mark the joint untracked BEFORE the geometry moves. Then every torn outcome degrades
11164
+ to "not being watched", which is visible and correctable, instead of to a confident lie.
11165
+
11166
+ armed (crosshair) the joint stays TRACKED. Esc here cancels and nothing was untracked.
11167
+ point accepted gate the write queue FIRST; cancel the debounce; drain what was already queued
11168
+ against the OLD placement; flush it. THEN untrack. Failure => ABORT, C unmutated.
11169
+ untrack ok move the geometry; arm the member pick.
11170
+ settle commit | Esc | abandon | arming failure | throw - ALL through ONE finally that
11171
+ releases the gate and refreshes the summary.
11172
+
11173
+ SUPPRESSION BEGINS BEFORE THE UNTRACK, not after: a timer scheduled by an EARLIER edit would otherwise
11174
+ fire after the re-placement mutation and publish the new geometry ahead of the command, which is the
11175
+ very sequence being prevented.
11176
+
11177
+ NO ROLLBACK, and that is a consequence of the ordering rather than an omission. Because the untrack
11178
+ precedes the only mutation, the pre-untrack failures moved nothing, and every post-untrack failure
11179
+ lands in exactly one state - moved geometry, untracked, no members. The finally's persist() +
11180
+ scheduleSave() are what make that state reach the draft and the server rather than living only here. */
11181
+ let connReplaceArm=null; // the joint id whose re-placement crosshair is armed, for the button's live .on state
11182
+ function armConnectionReplace(jointId){
11183
+ const j=(Array.isArray(C.joints)?C.joints:[]).find(x=>x&&x.id===jointId);
11184
+ if(!j||j.kind!=='custom'){toast('That connection is no longer in the model');return;}
11185
+ const nm=j.name||'Imported connection';
11186
+ if(!PROJECT){toast('Open this model from a project to re-place “'+nm+'”');return;}
11187
+ if(!view3d){toast('Switch to the 3D view to place this connection again');return;}
11188
+ if(!(window.Steel3DView&&window.Steel3DView.setInsertMode)){toast('The 3D view is not ready yet');return;}
11189
+ /* SAY NO BEFORE THE USER COMMITS TO A POINT. The transaction needs a review generation to untrack
11190
+ against, and without this check it discovers that only AFTER closing the gate and PUTting the whole
11191
+ contract — a wasted write, and a refusal arriving once the user has already chosen where it goes.
11192
+ The other two verbs check their preconditions up front; this one now does too. (Found by review.) */
11193
+ if(!ReviewClient||reviewUnavailable||!Number.isSafeInteger(reviewAt.reviewRevision)||reviewAt.reviewRevision<0){
11194
+ toast('The review state is not available right now — “'+nm+'” cannot be re-placed until it loads');return;}
11195
+ if(writeGateToken){toast('A placement is still finishing — try again in a moment');return;}
11196
+ connReplaceArm=jointId;
11197
+ window.Steel3DView.setInsertMode(true,{kind:'connection-replace',jointId,name:nm});
11198
+ panel(); // the button it was pressed on now reads as armed
11199
+ toast('Click where “'+nm+'” should sit — Esc to cancel');
11200
+ }
11201
+ async function replaceConnectionAt(jointId,pick){
11202
+ const joint=(Array.isArray(C.joints)?C.joints:[]).find(j=>j&&j.id===jointId);
11203
+ const name=(joint&&joint.name)||'Imported connection';
11204
+ if(!joint||joint.kind!=='custom'){toast('That connection is no longer in the model');return;}
11205
+ if(!PROJECT){toast('Open this model from a project to re-place “'+name+'”');return;}
11206
+ const token={};
11207
+ let mutated=false,placed=false;
11208
+ /* Capture the queue tail and close the gate in the SAME synchronous block - an await between them
11209
+ would let a write slip in that is neither grandfathered nor blocked. */
11210
+ const grandfathered=writeQueue;
11211
+ if(!closeWriteGate(token)){toast('A placement is still finishing — try again in a moment');return;}
11212
+ try{
11213
+ clearTimeout(saveT);saveT=null; // the debounce is taken over by the flush below
11214
+ await grandfathered.catch(()=>{}); // drain what was already queued, against the OLD placement
11215
+ await flushContractWith(token); // ...and publish it, so nothing pending can publish the NEW one
11216
+ await reviewVerb('untrack',jointId,{reviewRevision:reviewAt.reviewRevision});
11217
+ /* RE-RESOLVE, because `joint` was read before two awaits. `flushContractWith` installs the server's
11218
+ contract when the reply carries one, and that REPLACES the document — after which the object
11219
+ captured above is detached, and mutating it would move nothing while the toast claimed it had.
11220
+ Cheap, and the alternative is a lie about geometry. (Codex code review.) */
11221
+ const live=(Array.isArray(C.joints)?C.joints:[]).find(j=>j&&j.id===jointId);
11222
+ if(!live||live.kind!=='custom')throw new Error('the connection is no longer in this model');
11223
+ mutated=true; // only now may C move
11224
+ /* `edit()` SOFT-FAILS: a V2CommandError is caught, toasted, and reported by a `false` RETURN rather
11225
+ than a throw. Discarding that return was the one hole in the no-rollback argument — the
11226
+ transaction would carry on arming the pick and committing a baseline over geometry that never
11227
+ moved, which is a state the argument says is unreachable. (Found by review.) */
11228
+ if(!edit(()=>{
11229
+ live.place=pick.point;
11230
+ if(pick.anchorId)live.main=pick.anchorId;else delete live.main;
11231
+ selIds=new Set((live.geometry||[]).map((g,i)=>jointId+':'+(g.id||'m'+i)));
11232
+ }))throw new Error('the connection could not be moved');
11233
+ if(!armConnMemberPick(jointId,pick.anchorId,name))throw new Error('the member pick could not be armed');
11234
+ const out=await awaitConnPick(jointId);
11235
+ if(out&&out.commit)placed=await placeConnection(jointId,out.memberIds,out.skipped,token);
11236
+ /* THE ABANDON PATH HAS TO SPEAK. Consuming the settlement takes the message away from
11237
+ `onConnMemberPickAbandon`, which is the only thing that would otherwise have said anything — so
11238
+ without this the user switches panes, the connection silently stops being watched, and the only
11239
+ words on screen are the now-false instruction to name its members. Found by the regression test
11240
+ for the vanished-pick case; it was equally true of an ordinary pane switch, and my own browser
11241
+ pass had walked straight past the stale toast. */
11242
+ else toast('“'+name+'” was moved but no members were named, so it is no longer being watched — use Place again… to start watching it');
11243
+ }catch(e){
11244
+ console.warn('steel-editor: re-placement failed',e);
11245
+ toast(mutated
11246
+ ? '“'+name+'” was moved but is no longer being watched — use Place again… to start watching it'
11247
+ : '“'+name+'” was not moved — '+((e&&e.message)?String(e.message):'the model could not be saved first'));
11248
+ }finally{
11249
+ /* THE SINGLE MOST IMPORTANT ASSERTION IN THIS FEATURE. A leaked gate disables saving for the rest of
11250
+ the session, which is worse than the bug the gate fixes - so it is released on every path,
11251
+ including throw, and token-checked so a settling transaction cannot clear a newer one's gate. */
11252
+ if(connPickSettle&&connPickSettle.jointId===jointId)connPickSettle=null;
11253
+ openWriteGate(token);
11254
+ try{persist();}catch(_){/* setSaved('err') already fired inside persist */}
11255
+ // An un-placed mutation still has to reach the server - untracked and honest - rather than living
11256
+ // only in this browser. A placed one already published through the command; saying it twice would
11257
+ // move the store revision for nothing.
11258
+ if(mutated&&!placed)scheduleSave();
11259
+ reviewRefreshForOwnWrite();
11260
+ }
11261
+ }
10038
11262
  async function detailRequest(intent,place,note){
10039
11263
  // flushContract PUTs C to the server so the terminal AI reads the latest contract — but it clears the
10040
11264
  // debounced autosave (saveT) WITHOUT writing localStorage, which would drop the just-placed detail from
@@ -10505,7 +11729,7 @@ function viewGenKey(s){return s.kind+':'+s.index;}
10505
11729
  function closeViewGenerator(){const modal=document.getElementById('viewGenModal');if(modal)modal.style.display='none';viewGenState=null;
10506
11730
  const target=viewGenLauncher&&viewGenLauncher.isConnected?viewGenLauncher:document.getElementById('vwSaveMore');viewGenLauncher=null;if(target)target.focus();}
10507
11731
  function openViewGenerator(launcher){const geo=gridGeo(),gc=GC();if(!geo||!gc){toast('This plan has no usable structural grid');return;}
10508
- const sources=ViewGen.sourcesFromGrid(geo,gc.mmPerPx(P.pt_per_ft),P.sheet);
11732
+ const sources=ViewGen.sourcesFromGrid(geo,gc.mmPerPx(P.pt_per_ft),P.sheet,P.modelGrid);
10509
11733
  const selected=ViewGen.preselectedSourceKeys(selGridIds,sources),ignoredFree=ViewGen.unsupportedFreeGridCount(selGridIds);
10510
11734
  viewGenLauncher=launcher||document.activeElement;viewGenState={tab:'grid',look:'positive',selected,lastAnchor:null,sources,ignoredFree,
10511
11735
  depths:{grid:{ahead:'2\'-0"',behind:'2\'-0"'},levels:{above:'2\'-0"',below:'2\'-0"'}},committedDepths:{grid:{ahead:'2\'-0"',behind:'2\'-0"'},levels:{above:'2\'-0"',below:'2\'-0"'}}};
@@ -15946,6 +17170,8 @@ stage.addEventListener('pointerdown',e=>{if(e.button!==1)return;e.preventDefault
15946
17170
  pan={x:e.clientX,y:e.clientY,sl:stage.scrollLeft,st:stage.scrollTop};stage.setPointerCapture(e.pointerId);stage.style.cursor='grabbing';});
15947
17171
  stage.addEventListener('pointermove',e=>{if(!pan)return;stage.scrollLeft=pan.sl-(e.clientX-pan.x);stage.scrollTop=pan.st-(e.clientY-pan.y);});
15948
17172
  stage.addEventListener('pointerup',()=>{if(pan){pan=null;stage.style.cursor='';}});
17173
+ let profileScrollFrame=0;
17174
+ stage.addEventListener('scroll',()=>{if(profileScrollFrame)return;const later=window.requestAnimationFrame||((fn)=>setTimeout(fn,16));profileScrollFrame=later(()=>{profileScrollFrame=0;refreshProfileLabelOverlay();});},{passive:true});
15949
17175
  document.getElementById('exp').onclick=()=>{const out={pt_per_ft:FT,elev_units:'inch',members:P.members.map(m=>{ensureMeta(m);return {profile:m.profile,workpoint:m.wp,role:m.role,rfi:_wt(m.profile)==null,
15950
17176
  length_ft:+_lenFt(m).toFixed(1),weight_plf:_wt(m.profile), // columns measure vertical height (TOS−BOS), not their ~0 plan-point distance
15951
17177
  ends:m.role==='column'?undefined:m.ends, column:m.role==='column'?m.col:undefined};})};
@@ -16415,8 +17641,66 @@ function bandColorForPct(p){return p==null?'var(--mut)':p>=95?BANDC.verified:p>=
16415
17641
  // target_confidence input default (read in boot()); else none. Editing the override never touches
16416
17642
  // the .flo, so it can't disarm the Run gate.
16417
17643
  function effectiveTarget(){const t=C&&C.target_confidence;return typeof t==='number'?t:(TARGET_CONF!=null?TARGET_CONF:null);}
16418
- function updConf(){const el=document.getElementById('confStat');if(!el)return;const s=scoreContractJS();
17644
+ function readConfidenceProjection(){return ReadConfidence?ReadConfidence.projectReadConfidence(C):{rows:[],diagnostics:[{code:'projector-unavailable'}]};}
17645
+ function readTargetControl(){const ct=document.getElementById('confTarget'),state=document.getElementById('confTargetState'),tgt=effectiveTarget();
17646
+ if(ct&&document.activeElement!==ct){ct.value=typeof C.target_confidence==='number'?C.target_confidence:'';ct.placeholder='—';}
17647
+ if(state)state.textContent=tgt==null?'No target set':(typeof C.target_confidence==='number'?'Saved target':('Workflow default '+tgt+'%'));}
17648
+ function readPlanIndex(row){const member=(C.members||[]).find(m=>m&&m.id===row.memberId);if(!member)return -1;
17649
+ for(const observation of row.observations||[]){const i=(C.plans||[]).findIndex(p=>p&&p.viewKind==='plan'&&p.sheet===observation.sheet);if(i>=0)return i;}
17650
+ const sheets=V2Projection&&V2Projection.memberSheets?V2Projection.memberSheets(C,row.memberId):[];
17651
+ return (C.plans||[]).findIndex(p=>p&&p.viewKind==='plan'&&sheets.includes(p.sheet));}
17652
+ function readValueText(field){if(field.kind!=='elevation')return String(field.value);
17653
+ const value=field.value||{};if(typeof value.known==='number'&&isFinite(value.known))return fmtFtIn(value.known/25.4)+' ('+String(value.known)+' mm)';
17654
+ return 'Unknown'+(typeof value.rfiRef==='string'&&value.rfiRef.trim()?(' · '+value.rfiRef.trim()):'');}
17655
+ function readNotesHtml(){const groups=[];const add=(label,notes)=>{const unique=[...new Set((Array.isArray(notes)?notes:[]).filter(n=>typeof n==='string'&&n.trim()).map(n=>n.trim()))];if(unique.length)groups.push({label,notes:unique});};
17656
+ add('Model notes',C.read_notes);for(const p of C.plans||[])add('Sheet '+String(p.sheet||'—'),p.read_notes);
17657
+ if(!groups.length)return '';return '<section class=read-notes aria-label="Sheet read notes">'+groups.map(g=>'<h3>'+esc(g.label)+'</h3><ul>'+g.notes.map(n=>'<li>'+esc(n)+'</li>').join('')+'</ul>').join('')+'</section>';}
17658
+ function readFieldsHtml(row,target){return (row.observations||[]).map(observation=>{
17659
+ const flags=[observation.provenanceLabel];if(observation.inherited)flags.push('Shared evidence — inherited after split');if(observation.verified)flags.push('✓ Human-confirmed observation');
17660
+ return '<div class=read-group><div class=read-group-head><b>'+esc(observation.sheet||'Unknown sheet')+'</b><span>'+flags.map(esc).join(' · ')+'</span></div>'+observation.fields.map(field=>{
17661
+ const below=target!=null&&field.confidence<target;return '<div class=read-field><b>'+esc(field.label)+'</b><span class=read-value>'+esc(readValueText(field))+'</span><span class=read-pct'+(below?' style="color:var(--warn)"':'')+'>'+field.confidence+'%'+(below?' · below target':'')+'</span></div>';}).join('')+'</div>';}).join('');}
17662
+ let confReadBand='all',confRestoreMember=null,confRestoreControl=null;
17663
+ function rememberConfControl(control,kind){confRestoreControl={kind,value:control.dataset[kind]};}
17664
+ function restoreConfControl(){if(!confRestoreControl)return false;const pending=confRestoreControl;confRestoreControl=null;
17665
+ const selectors={readBand:'#confFilter [data-read-band]',readCat:'#confFilter [data-read-cat]',band:'#confFilter [data-band]',fcat:'#confFilter [data-fcat]'};
17666
+ const selector=selectors[pending.kind];if(!selector)return false;const next=[...document.querySelectorAll(selector)].find(control=>control.dataset[pending.kind]===pending.value);if(!next)return false;next.focus();return true;}
17667
+ function renderReadConf(){const projection=readConfidenceProjection(),target=effectiveTarget(),summary=ReadConfidence.summarizeReadConfidence(projection,target);
17668
+ if(!['all','beams','columns'].includes(confCat))confCat='all';if(target==null)confReadBand='all';readTargetControl();
17669
+ const metric=(label,value,note)=>'<div class=ccard><div class=cc-label>'+label+'</div><div class=cc-score>'+value+'</div><div class=cc-counts><span>'+note+'</span></div></div>';
17670
+ document.getElementById('confCats').innerHTML=metric('Recorded fields',summary.totalFields,'immutable drawing values')+metric('Below target',target==null?'—':summary.belowFields,target==null?'No target set':('strictly below '+target+'%'))+metric('Members affected',target==null?'—':summary.affectedMembers,'review destinations')+metric('Not recorded',summary.notRecordedMembers,'members without field confidence');
17671
+ const disabled=target==null,blocked='Set a target above to filter uncertain reads.';
17672
+ document.getElementById('confFilter').innerHTML='<span class=glab>Read confidence</span><span class=grp><button data-command-id="steel.confidence-filter#all recorded reads" data-read-band=all class="'+(confReadBand==='all'?'on':'')+'" aria-pressed="'+(confReadBand==='all')+'">All</button><button data-command-id="steel.confidence-filter#reads below target" data-read-band=below class="'+(confReadBand==='below'?'on':'')+'" aria-pressed="'+(confReadBand==='below')+'"'+(disabled?' disabled aria-disabled=true data-blocked-reason="'+esc(blocked)+'"':'')+'>Below target</button></span><span class=glab>Category</span><span class=grp>'+[['all','All'],['beams','Beams'],['columns','Columns']].map(([key,label])=>'<button data-command-id="steel.confidence-filter#category '+key+'" data-read-cat="'+key+'" class="'+(confCat===key?'on':'')+'" aria-pressed="'+(confCat===key)+'">'+label+'</button>').join('')+'</span><span class=glab style="margin-left:auto">'+(target==null?'No target set':(summary.belowFields+' fields below '+target+'% · '+summary.affectedMembers+' members'))+'</span>';
17673
+ let rows=projection.rows.map((row,i)=>({row,i,member:(C.members||[]).find(m=>m&&m.id===row.memberId)}));
17674
+ if(confCat==='beams')rows=rows.filter(x=>(x.member&&x.member.role)!=='column');else if(confCat==='columns')rows=rows.filter(x=>x.member&&x.member.role==='column');
17675
+ if(confReadBand==='below')rows=rows.filter(x=>ReadConfidence.rowIsBelowTarget(x.row,target));
17676
+ let h=projection.diagnostics.length?'<div class=read-diag role=alert>'+projection.diagnostics.length+' drawing-confidence record'+(projection.diagnostics.length===1?' could':'s could')+' not be read. Review the source contract before treating this report as complete.</div>':'';
17677
+ if(!rows.length){const unread=projection.diagnostics.length>0,category=confCat==='beams'?'beam':confCat==='columns'?'column':null;
17678
+ const empty=unread?'No readable members match this filter. Unread drawing-confidence records remain and may affect the result.':
17679
+ confReadBand==='below'&&target!=null?(category?'No recorded '+category+' fields are below the '+target+'% target.':'No recorded fields are below the '+target+'% target.'):
17680
+ category?'No '+category+' members match this filter.':'No members in the model yet.';
17681
+ h+='<div class=hint style="padding:14px 0">'+empty+'</div>';}
17682
+ else{h+='<table class=ftab><thead><tr><th>Read</th><th>Member</th><th>Type</th><th>Source</th><th>Evidence</th><th></th></tr></thead><tbody>';
17683
+ rows.forEach(({row,i,member})=>{const below=ReadConfidence.rowIsBelowTarget(row,target),sources=[...new Set(row.observations.map(o=>o.sheet).filter(Boolean))];let evidence;
17684
+ if(row.state==='unobserved')evidence='No active drawing observation is linked to this member.';else if(row.state==='unrecorded')evidence='No per-field read confidence was recorded for this member.';else evidence='Lowest recorded field '+row.minimum+'%'+(below?' · below '+target+'% target':'');
17685
+ const exp=confExpand===row.memberId,region='confReadFields'+i;
17686
+ h+='<tr class=confrow data-mid="'+esc(row.memberId)+'"><td>'+(row.minimum==null?'—':(row.minimum+'%'))+'</td><td>'+esc((member&&member.profile)||row.memberId)+'</td><td>'+esc(member&&member.role==='column'?'Column':member&&member.memberType==='brace'?'Brace':'Beam')+'</td><td>'+esc(sources.join(', ')||'—')+'</td><td><span class="chip '+(below?'assumed':'')+'">'+esc(evidence)+'</span></td><td>'+(row.fieldCount?'<button data-command-id="steel.confidence-fields#'+esc(row.memberId)+'" class=ghost data-review="'+esc(row.memberId)+'" aria-expanded="'+exp+'" aria-controls="'+region+'">Review fields</button> ':'')+'<button data-command-id="steel.locate-member#'+esc(row.memberId)+'" class=ghost data-read-loc="'+esc(row.memberId)+'">Locate</button></td></tr>';
17687
+ if(exp)h+='<tr id="'+region+'"><td></td><td colspan=5 class=conf-expand>'+readFieldsHtml(row,target)+'</td></tr>';});h+='</tbody></table>';}
17688
+ h+=readNotesHtml();document.getElementById('confBody').innerHTML=h;wireReadConf(projection);
17689
+ if(!restoreConfControl()&&confRestoreMember){const id=confRestoreMember;confRestoreMember=null;const next=[...document.querySelectorAll('#confBody [data-review]')].find(b=>b.dataset.review===id);if(next)next.focus();}}
17690
+ function wireReadConf(projection){document.querySelectorAll('#confFilter [data-read-band]').forEach(b=>b.onclick=()=>{if(b.disabled)return;rememberConfControl(b,'readBand');confReadBand=b.dataset.readBand;renderConf();});
17691
+ document.querySelectorAll('#confFilter [data-read-cat]').forEach(b=>b.onclick=()=>{rememberConfControl(b,'readCat');confCat=b.dataset.readCat;renderConf();});
17692
+ document.querySelectorAll('#confBody [data-review]').forEach(b=>b.onclick=()=>{const id=b.dataset.review;confExpand=confExpand===id?null:id;confRestoreMember=id;renderConf();});
17693
+ document.querySelectorAll('#confBody [data-read-loc]').forEach(b=>b.onclick=()=>locateReadMember(b.dataset.readLoc,projection));}
17694
+ async function locateReadMember(id,projection){const row=projection.rows.find(r=>r.memberId===id),canonical=(C.members||[]).find(member=>member&&member.id===id);if(!row||!canonical)return;const pi=readPlanIndex(row);
17695
+ selDimIds.clear();selIds=new Set([id]);geoMode=null;setGeo();closeConf(false);
17696
+ if(pi>=0){if(pi!==C.active)setPlan(pi);const projected=byId(id);if(projected){render();zoomToMember(projected);if(view3d)document.getElementById('stage3d').focus();else svg.focus();toast('Selected '+id+' on '+String(C.plans[pi].sheet)+'.');return;}}
17697
+ render();await setView('3d');if(!view3d){svg.focus();toast('Selected '+id+', but it has no editable 2D plan view and 3D is unavailable.');return;}
17698
+ if(window.Steel3DView)window.Steel3DView.setSelection(selIds);document.getElementById('stage3d').focus();toast('Selected '+id+' in 3D — no editable 2D plan view is available.');}
17699
+ function updConf(){const el=document.getElementById('confStat');if(!el)return;
17700
+ if(nativeElevationModel()){const projection=readConfidenceProjection();if(!projection.rows.length){el.style.display='none';return;}el.style.display='';const target=effectiveTarget(),summary=ReadConfidence.summarizeReadConfidence(projection,target),unread=summary.diagnosticCount;document.getElementById('confLabel').textContent='Read confidence';document.getElementById('confPct').textContent=summary.totalFields+' field'+(summary.totalFields===1?'':'s');const tg=document.getElementById('confTgt');tg.textContent=(target==null?(summary.lowest==null?' · not recorded':(' · lowest '+summary.lowest+'%')):(' · '+summary.belowFields+' below '+target+'%'+(summary.notRecordedMembers?' · '+summary.notRecordedMembers+' members not recorded':'')))+(unread?' · '+unread+' unread':'');tg.style.color=(target!=null&&summary.belowFields)||unread?'var(--warn)':'';el.dataset.tip=(unread?unread+' drawing-confidence record'+(unread===1?' could':'s could')+' not be read; the result is incomplete. ':'')+(target==null?'No confidence target is set. Click to review recorded drawing fields.':summary.belowFields+' recorded drawing field'+(summary.belowFields===1?' is':'s are')+' below the '+target+'% target. Click to review them.');return;}
17701
+ const s=scoreContractJS();
16419
17702
  if(!s.byMember.length){el.style.display='none';return;}el.style.display='';
17703
+ document.getElementById('confLabel').textContent='Confidence';
16420
17704
  const sc=s.overall.score,col=bandColorForPct(sc),tgt=effectiveTarget();
16421
17705
  const b=document.getElementById('confPct');b.textContent=sc==null?'—':sc+'%';b.style.color=col;
16422
17706
  // Goal suffix: "· target N%" (muted, static) + "(−G%)" gap in the band color, shown only while below target.
@@ -16429,14 +17713,14 @@ function updConf(){const el=document.getElementById('confStat');if(!el)return;co
16429
17713
  el.dataset.tip='Confidence '+(sc==null?'—':sc+'%')+(tgt!=null?' vs target '+tgt+'%':'')+' — '+s.overall.tons.toFixed(1)+' t scored · '+s.overall.rfiCount+' RFI. Click for the report.';}
16430
17714
  // --- the report modal ---
16431
17715
  let confBand='all',confCat='all',confExpand=null;
16432
- function openConf(){confExpand=null;renderConf();document.getElementById('confModal').style.display='flex';}
16433
- function closeConf(){document.getElementById('confModal').style.display='none';}
17716
+ function openConf(){confExpand=null;renderConf();document.getElementById('confModal').style.display='flex';document.getElementById('confClose').focus();}
17717
+ function closeConf(restore=true){document.getElementById('confModal').style.display='none';if(restore)document.getElementById('confStat').focus();}
16434
17718
  function confOpen(){return document.getElementById('confModal').style.display==='flex';}
16435
17719
  function _bar(pct){return '<div class=cc-bar><div class=cc-fill style="width:'+(pct||0)+'%;background:'+bandColorForPct(pct)+';'+(pct==null?'opacity:0':'')+'"></div></div>';}
16436
17720
  function _countsHtml(c){const out=['verified','high','med','low','rfi'].filter(k=>c[k]>0).map(k=>'<span style="color:'+BANDC[k]+'">'+BANDLAB[k][0]+' <b>'+c[k]+'</b></span>').join('');return out||'<span>—</span>';}
16437
- function renderConf(){const s=scoreContractJS();const cat=s.byCategory;
17721
+ function renderConf(){if(nativeElevationModel()){renderReadConf();return;}const s=scoreContractJS();const cat=s.byCategory;
16438
17722
  const ct=document.getElementById('confTarget');if(ct&&document.activeElement!==ct){ // value = the per-read OVERRIDE only; the app default shows as a placeholder (empty = using default)
16439
- ct.value=typeof C.target_confidence==='number'?C.target_confidence:'';ct.placeholder=TARGET_CONF!=null?String(TARGET_CONF):'70';}
17723
+ ct.value=typeof C.target_confidence==='number'?C.target_confidence:'';ct.placeholder='—';}readTargetControl();
16440
17724
  const card=(key,label,cs,stub)=>'<div class="ccard'+(stub?' stub':' click')+(confCat===key?' on':'')+'" data-cat="'+key+'"'+(stub?' data-tip="not scored yet"':'')+'>'+
16441
17725
  '<div class=cc-label>'+label+'</div>'+
16442
17726
  '<div class=cc-score style="color:'+(stub?'var(--mut)':bandColorForPct(cs.score))+'">'+(stub||cs.score==null?'—':cs.score+'%')+'</div>'+
@@ -16449,7 +17733,7 @@ function renderConf(){const s=scoreContractJS();const cat=s.byCategory;
16449
17733
  '<span class=glab>Category</span><span class=grp>'+cats.map(c=>'<button data-command-id="steel.confidence-filter#category '+c+'" data-fcat="'+c+'" class="'+(confCat===c?'on':'')+'" aria-pressed="'+(confCat===c?'true':'false')+'">'+(c==='all'?'All':c[0].toUpperCase()+c.slice(1))+'</button>').join('')+'</span>'+
16450
17734
  '<span class=glab style="margin-left:auto">Coverage: '+s.coverage.members+' members · '+s.coverage.segments+' segments (approx.)</span>';
16451
17735
  document.getElementById('confBody').innerHTML=confBodyHtml(s);
16452
- wireConf();}
17736
+ wireConf();restoreConfControl();}
16453
17737
  function confBodyHtml(s){
16454
17738
  if(!s.byMember.length&&!s.byDetail.length)return '<div class=hint style="padding:14px 0">No members in the model yet.</div>';
16455
17739
  if(confCat==='connections'){
@@ -16484,18 +17768,22 @@ function confBodyHtml(s){
16484
17768
  h+='</tbody></table>';return h;}
16485
17769
  function wireConf(){
16486
17770
  document.querySelectorAll('#confCats .ccard.click').forEach(c=>c.onclick=()=>{confCat=(confCat===c.dataset.cat?'all':c.dataset.cat);renderConf();});
16487
- document.querySelectorAll('#confFilter [data-band]').forEach(b=>b.onclick=()=>{confBand=b.dataset.band;renderConf();});
16488
- document.querySelectorAll('#confFilter [data-fcat]').forEach(b=>b.onclick=()=>{confCat=b.dataset.fcat;renderConf();});
17771
+ document.querySelectorAll('#confFilter [data-band]').forEach(b=>b.onclick=()=>{rememberConfControl(b,'band');confBand=b.dataset.band;renderConf();});
17772
+ document.querySelectorAll('#confFilter [data-fcat]').forEach(b=>b.onclick=()=>{rememberConfControl(b,'fcat');confCat=b.dataset.fcat;renderConf();});
16489
17773
  document.querySelectorAll('#confBody tr.confrow').forEach(r=>r.onclick=e=>{if(e.target.closest('button'))return;const id=r.dataset.mid;confExpand=confExpand===id?null:id;renderConf();});
16490
17774
  document.querySelectorAll('#confBody button[data-loc]').forEach(b=>b.onclick=e=>{e.stopPropagation();const pi=+b.dataset.pi;if(pi!==C.active)setPlan(pi);const m=byId(b.dataset.loc);if(!m)return;selDimIds.clear();selIds=new Set([m.id]);geoMode=null;setGeo();closeConf();render();zoomToMember(m);});}
16491
17775
  document.getElementById('confStat').onclick=openConf;
16492
- document.getElementById('confTarget').onchange=e=>{ // per-read target override → contract.target_confidence (never the .flo)
16493
- const raw=String(e.target.value).trim();
16494
- if(raw===''){delete C.target_confidence;} // cleared → fall back to the app default
16495
- else{let v=Math.round(+raw);if(!isFinite(v))return;v=Math.max(0,Math.min(100,v));C.target_confidence=v;e.target.value=v;}
16496
- scheduleSave();updConf();};
17776
+ function commitConfTarget(el){ // per-read target override → contract.target_confidence (never the .flo)
17777
+ const raw=String(el.value).trim(),had=typeof C.target_confidence==='number',before=had?C.target_confidence:null;let after=null;
17778
+ if(raw===''){if(had)delete C.target_confidence;} // cleared → fall back to the app default
17779
+ else{let v=Math.round(+raw);if(!isFinite(v))return;v=Math.max(0,Math.min(100,v));after=v;C.target_confidence=v;el.value=v;}
17780
+ if(before!==after)scheduleSave(); // Enter then blur/change is one mutation, not two
17781
+ updConf();if(confOpen())renderConf();}
17782
+ document.getElementById('confTarget').onchange=e=>commitConfTarget(e.target);
17783
+ document.getElementById('confTarget').onkeydown=e=>{if(e.key!=='Enter')return;e.preventDefault();commitConfTarget(e.target);e.target.blur();};
16497
17784
  document.getElementById('confClose').onclick=closeConf;
16498
17785
  document.getElementById('confBackdrop').onclick=closeConf;
17786
+ document.getElementById('confModal').addEventListener('keydown',e=>{e.stopPropagation();if(e.key==='Escape'){e.preventDefault();closeConf();return;}if(e.key!=='Tab')return;const f=[...document.querySelectorAll('#confModal button,#confModal input,#confModal [tabindex]')].filter(n=>!n.disabled&&n.offsetParent!==null);if(!f.length)return;const first=f[0],last=f[f.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus();}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus();}});
16499
17787
  // --- detail preview lightbox (click a card / an end's ⤢ to enlarge) ---
16500
17788
  const SHEET_PREV=C.sheet_previews||{}, DBUB=C.detail_bubbles||{};
16501
17789
  // Both halves of a detail reference are parsed in steel-detail-refs.js, where they are covered by tests;
@@ -16997,7 +18285,7 @@ document.addEventListener('keydown',e=>{if(!comboInput||comboPop.style.display==
16997
18285
  function resetPlanViewState(i){
16998
18286
  // The 2D viewport still needs FINITE numbers even though nothing is drawn into it: fitToWindow() divides by
16999
18287
  // EXTX/EXTY, and a NaN zoom propagates into the viewBox and into every snap tolerance derived from it.
17000
- X0=0;Y0=0;X1=1000;Y1=1000;FT=(P&&P.pt_per_ft>0)?P.pt_per_ft:12;RB64='';EXTX=1000;EXTY=1000;
18288
+ X0=0;Y0=0;X1=1000;Y1=1000;FT=(P&&P.pt_per_ft>0)?P.pt_per_ft:12;RB64='';EXTX=1000;EXTY=1000;syncElevationContext();
17001
18289
  svg.setAttribute('viewBox',`${X0} ${Y0} ${X1-X0} ${Y1-Y0}`);
17002
18290
  // The profile list, read from the native document root. Deriving it from
17003
18291
  // `P.members` would be the silent-empty this design refuses; deriving it from `weights` alone would be a
@@ -17035,6 +18323,7 @@ function setPlan(i){
17035
18323
  NO_PLAN_VIEW=false;
17036
18324
  V2_PROJECTION=v2ProjectionForSheet(canonical.sheet);
17037
18325
  P=DEV_MODE?ModelCmd.deepFreezeProjection(V2_PROJECTION.plan):V2_PROJECTION.plan;
18326
+ syncElevationContext();
17038
18327
  // clip = the drawing's display-space crop. A contract may ship WITHOUT a raster/clip (a shared or
17039
18328
  // committed contract strips raster_b64 for confidentiality), so fall back to the members' bounding
17040
18329
  // box (padded) → the editor renders members on a blank canvas instead of crashing on P.clip[0].
@@ -17057,7 +18346,6 @@ function setPlan(i){
17057
18346
  csaxisMode=false;setCsMode(); // set-axes tool resets per plan; P.frame itself is per-plan data (persisted), so it stays
17058
18347
  snapOnlyClear2d();closeSnapMenu(); // a snap override never outlives its plan (different geometry)
17059
18348
  disarmCm(); // Move/Copy resets per plan too (its counts persist — they're session prefs, not plan data)
17060
- defaultTOS=198;
17061
18349
  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)
17062
18350
  setMode();render();fitToWindow();
17063
18351
  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)
@@ -17657,17 +18945,17 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
17657
18945
  refSheetOn=_srs2;C.filter=sf;P.sheet=ssh;_ovSnapEls=null;P.members=sm;P.segments=ss;P.dims=sd;dimsVisible=sdv;zoom=sz;}
17658
18946
  // 11) member length — true 3D distance between the two end nodes: level beam = plan run, plumb column = TOS−BOS
17659
18947
  // height (its plan points coincide → 0 plan distance), and a SLOPED member picks up its elevation rise.
17660
- {const sf=FT,st=defaultTOS;FT=12;defaultTOS=198;
18948
+ {const sf=FT,st=defaultTOS;FT=12;defaultTOS=204;
17661
18949
  ok(near(_lenFt({role:'beam',wp:[[0,0],[120,0]]}),10),'_lenFt level beam = plan run (no TOS delta)');
17662
18950
  ok(near(_lenFt({role:'column',wp:[[0,0],[0,0]],col:{bos:0,tos:120,tosDef:false}}),10),'_lenFt plumb column = |TOS−BOS| height (not ~0 plan distance)');
17663
- ok(near(_lenFt({role:'column',wp:[[5,5],[5,5]],col:{bos:12,tos:null,tosDef:true}}),(198-12)/12),'_lenFt column default TOS follows the level');
18951
+ ok(near(_lenFt({role:'column',wp:[[5,5],[5,5]],col:{bos:12,tos:null,tosDef:true}}),(204-12)/12),'_lenFt column default TOS follows the level');
17664
18952
  // sloped brace: 3 ft plan run + 3 ft TOS rise → true length √(3²+3²), NOT the 3 ft plan projection
17665
18953
  ok(near(_lenFt({role:'beam',wp:[[0,0],[36,0]],ends:[{tos:0,tosDef:false},{tos:36,tosDef:false}]}),Math.hypot(3,0,3)),'_lenFt sloped beam = true 3D length (plan run + TOS rise)');
17666
18954
  // battered column: 4 ft plan lean + 12 ft rise → √(4²+12²), not the bare height
17667
18955
  ok(near(_lenFt({role:'column',wp:[[0,0],[48,0]],col:{bos:0,tos:144,tosDef:false}}),Math.hypot(4,0,12)),'_lenFt battered column includes the plan lean');
17668
18956
  // _mTons (BOM) shares the SAME 3D helper → agrees with the inspector (no BOM-vs-display divergence), incl. default-follow
17669
18957
  const dc={role:'column',profile:'W10X49',col:{bos:0,tos:null,tosDef:true}};
17670
- ok(near(_mTons(dc,10,198), _lenFt(dc)*49/2000),'_mTons shares _len3dFt with the display (agree even for a default-follow column)');
18958
+ ok(near(_mTons(dc,10,204), _lenFt(dc)*49/2000),'_mTons shares _len3dFt with the display (agree even for a default-follow column)');
17671
18959
  FT=sf;defaultTOS=st;}
17672
18960
  // 12) Tekla area-select — window (L→R drag) = fully enclosed; crossing (R→L drag) = touched
17673
18961
  {const r=[0,0,10,10],win=(a,b)=>inRect(a,r)&&inRect(b,r),crs=(a,b)=>rectHit(a,b,r);
@@ -17788,14 +19076,14 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
17788
19076
 
17789
19077
  // onElevateMember materialises an unset T.O.S from the OWNING sheet's datum (and from 0, like the
17790
19078
  // bake, when that sheet has none) — never from the active sheet's defaultTOS
17791
- {const savedPlans=C.plans,savedP=P,savedTos=defaultTOS;defaultTOS=198;
19079
+ {const savedPlans=C.plans,savedP=P,savedTos=defaultTOS;defaultTOS=204;
17792
19080
  const off={sheet:'S-OFF2',pt_per_ft:36,default_tos:348,members:[],dims:[]};
17793
19081
  const bm={id:'el1',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
17794
19082
  const noDef={sheet:'S-NODEF',pt_per_ft:12,members:[],dims:[]};
17795
19083
  const bm2={id:'el2',role:'beam',profile:'W16X26',wp:[[0,0],[100,0]],ends:[{},{}]};
17796
19084
  off.members=[bm];noDef.members=[bm2];C.plans=[savedP,off,noDef];
17797
19085
  view3dApi.onElevateMember('el1',12);
17798
- ok(Math.abs(bm.ends[0].tos-360)<1e-6,'onElevateMember materialises from the OWNING sheet datum (348+12), not the active one (198+12)');
19086
+ ok(Math.abs(bm.ends[0].tos-360)<1e-6,'onElevateMember materialises from the OWNING sheet datum (348+12), not the active one (204+12)');
17799
19087
  view3dApi.onElevateMember('el2',12);
17800
19088
  ok(Math.abs(bm2.ends[0].tos-12)<1e-6,'a sheet with no default_tos resolves to 0 like the bake, not to the active sheet');
17801
19089
  C.plans=savedPlans;P=savedP;defaultTOS=savedTos;}
@@ -17881,7 +19169,7 @@ if(new URLSearchParams(location.search).get('selftest')==='1'){(function(){
17881
19169
  const leg=(id,wp,ends,off)=>({id,role:'beam',memberType:'brace',profile:'HSS6X6X5/8',wp,
17882
19170
  brace:{type:'vertical',floor:'above',offset:off},ends});
17883
19171
  const AB=[[0,0],[240,0]],BA=[[240,0],[0,0]];
17884
- const lo={tos:0,tosDef:false},hi={tos:198,tosDef:false};
19172
+ const lo={tos:0,tosDef:false},hi={tos:204,tosDef:false};
17885
19173
  // RIGHT: same canonical wp order, transposed elevations → two distinct signatures → both kept.
17886
19174
  P.members=[leg('lA',AB,[lo,hi],12),leg('lB',AB,[hi,lo],-12)];
17887
19175
  ok(redundantDups().length===0,'redundantDups keeps BOTH legs of a correctly-emitted X');