@floless/app 0.149.0 → 0.150.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/floless-server.cjs +102295 -88314
  2. package/dist/schemas/drawing-check.profile.v1.schema.json +45 -2
  3. package/dist/schemas/steel.model.v2.schema.json +9 -0
  4. package/dist/skills/floless-app-approval/SKILL.md +79 -4
  5. package/dist/skills/floless-app-onboarding/SKILL.md +4 -4
  6. package/dist/skills/floless-app-onboarding/references/aware-runtime.md +1 -1
  7. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +15 -13
  8. package/dist/skills/floless-app-routines/SKILL.md +4 -1
  9. package/dist/skills/floless-app-routines/references/routines-api.md +14 -2
  10. package/dist/skills/floless-app-steel-model/SKILL.md +4 -2
  11. package/dist/skills/floless-app-steel-takeoff/SKILL.md +14 -9
  12. package/dist/skills/floless-app-workflows/SKILL.md +2 -2
  13. package/dist/templates/tekla-parser.flo +13 -3
  14. package/dist/web/agents.js +887 -0
  15. package/dist/web/app.css +458 -23
  16. package/dist/web/app.js +20 -5
  17. package/dist/web/aware.js +1339 -134
  18. package/dist/web/chat.css +68 -4
  19. package/dist/web/chat.js +1770 -55
  20. package/dist/web/commands-drawing-check.js +15 -0
  21. package/dist/web/commands-revit.js +5 -0
  22. package/dist/web/commands-shell.js +785 -50
  23. package/dist/web/commands-tekla-parser.js +8 -1
  24. package/dist/web/connections.js +57 -14
  25. package/dist/web/drawing-check-editor.html +10 -2
  26. package/dist/web/drawing-check-editor.js +569 -40
  27. package/dist/web/drawing-check-overlay.js +45 -2
  28. package/dist/web/index.html +102 -27
  29. package/dist/web/instructor.js +85 -8
  30. package/dist/web/leave-guard.js +1 -0
  31. package/dist/web/left-pane.js +20 -1
  32. package/dist/web/local-discovery.js +12 -2
  33. package/dist/web/model-editor.css +32 -32
  34. package/dist/web/model-panel-bridge.js +11 -3
  35. package/dist/web/model-viewport-lighting.js +4 -2
  36. package/dist/web/model-viewport-revit-adapter.js +3 -0
  37. package/dist/web/model-viewport-toolbar.js +6 -3
  38. package/dist/web/model-viewport.js +11 -1
  39. package/dist/web/revit-editor.css +14 -14
  40. package/dist/web/revit-editor.js +64 -12
  41. package/dist/web/steel-3d-core.js +133 -0
  42. package/dist/web/steel-3d-view.js +10 -0
  43. package/dist/web/steel-editor.html +171 -39
  44. package/dist/web/steel-model-v2-client-validation.js +11 -0
  45. package/dist/web/steel-model-v2-commands.js +80 -5
  46. package/dist/web/tool-updates.js +367 -0
  47. package/dist/web/workspaces.js +679 -59
  48. package/package.json +1 -1
@@ -2850,7 +2850,7 @@ text.mlentx{fill:#e2e8f0;text-anchor:middle;dominant-baseline:central;font-famil
2850
2850
  <button data-command-id="steel.copy-array" id=cpArrB>Copy array…</button>
2851
2851
  <button data-command-id="steel.copy-to-level" id=cpLevelB>Copy to level…</button>
2852
2852
  <div class=mlabel>Dragging</div>
2853
- <button data-command-id="steel.drag-to-move" id=dragMoveB role=menuitemcheckbox aria-checked=false data-tip="When ON, left-dragging a member moves it and Ctrl+drag copies it. When OFF (default), a drag does neither — a click only selects, so members can't be nudged by accident (the Move and Copy tools still work). Applies to 2D and 3D."><span class=mck aria-hidden=true></span>Drag to move/copy</button>
2853
+ <button data-command-id="steel.drag-to-move" id=dragMoveB role=menuitemcheckbox aria-checked=false data-tip="When ON, left-dragging a member moves it and Ctrl+drag copies it. When OFF (default), a drag does neither — a click only selects, so members can't be nudged by accident (the Move and Copy tools still work). Whole-member dragging works in 2D. In 3D, drag a member's end-nodes, use the Position handle, or use the Move tool."><span class=mck aria-hidden=true></span>Drag to move/copy</button>
2854
2854
  </div>
2855
2855
  </div>
2856
2856
  <span class=tb-sep></span>
@@ -3389,18 +3389,20 @@ function baseNamesLoaded(baseEtag, verdicts) {
3389
3389
  *
3390
3390
  * Best-effort: a storage failure here costs a false conflict prompt on the next reload, never data.
3391
3391
  */
3392
+ // Returns whether it re-stamped, i.e. whether the live row was this generation's own draft.
3392
3393
  function restampDraftBase(prev, next) {
3393
- if (!next) return;
3394
+ if (!next) return false;
3394
3395
  try {
3395
3396
  const raw = localStorage.getItem(draftKey());
3396
- if (!raw) return;
3397
+ if (!raw) return false;
3397
3398
  const d = JSON.parse(raw);
3398
- if (!d || typeof d !== 'object') return;
3399
+ if (!d || typeof d !== 'object') return false;
3399
3400
  // A row with no base is not a delta from `prev` in any checkable sense and must not inherit a tag.
3400
- if (d.baseEtag !== prev) return;
3401
+ if (d.baseEtag !== prev) return false;
3401
3402
  d.baseEtag = next;
3402
3403
  localStorage.setItem(draftKey(), JSON.stringify(d));
3403
- } catch (_) { /* the draft stays on its old base — a false "changed elsewhere" prompt, not a loss */ }
3404
+ return true;
3405
+ } catch (_) { return false; /* the draft stays on its old base — a false "changed elsewhere" prompt, not a loss */ }
3404
3406
  }
3405
3407
  /**
3406
3408
  * Write a PENDING in-memory edit into this browser's draft row, right now. Assigned by main().
@@ -3429,7 +3431,7 @@ const ownWrites = [];
3429
3431
  // ordinary writes; putting it in the bounded FIFO would eventually turn our own late event into an
3430
3432
  // apparent external edit. At most one RFI recovery owns the surface, and explicit settlement paths
3431
3433
  // remove these ids, so this set is bounded by active uncertain operations rather than edit traffic.
3432
- const uncertainWrites = new Set();
3434
+ const uncertainWrites = new Map(); // id -> the save sequence of the write that went uncertain (#1938: its recovery must not outrank a newer edit)
3433
3435
  // A pure backstop, not a working limit. queueWrite SERIALIZES this tab's writes, and an id is dropped on
3434
3436
  // success AND on every failure, so in steady state this holds at most one entry. The cap only matters if
3435
3437
  // some future path mints an id and never resolves it.
@@ -3460,13 +3462,13 @@ function claimMutation(id) { ownWrites.push(id); while (ownWrites.length > OWN_W
3460
3462
  * EVERY failure — a refused write produces no broadcast at all, so its id would otherwise sit in the list
3461
3463
  * forever, where the only thing it can do is wrongly suppress somebody else's event. */
3462
3464
  function releaseMutation(id) { const i = ownWrites.indexOf(id); if (i >= 0) ownWrites.splice(i, 1); }
3463
- function quarantineMutation(id) {
3465
+ function quarantineMutation(id, seq) {
3464
3466
  const i = ownWrites.indexOf(id);
3465
3467
  // The SSE echo can beat a slow response. In that case the write is already known to be ours and
3466
3468
  // consumed, so a later client-side timeout must not resurrect it as an uncertain identity.
3467
3469
  if (i < 0) return;
3468
3470
  ownWrites.splice(i, 1);
3469
- uncertainWrites.add(id);
3471
+ uncertainWrites.set(id, seq);
3470
3472
  }
3471
3473
  let C, PAL, WT;
3472
3474
  let CatalogPicker = null; // steel-catalog-picker.js — provider-neutral Profile and Material catalogue dialogs
@@ -3593,6 +3595,14 @@ const DEFAULT_PAL=['#60a5fa','#94a3b8','#f59e0b','#34d399','#f472b6','#a78bfa','
3593
3595
  // wasted traffic and makes the pill flicker in a way that reads as broken rather than informative.
3594
3596
  let serverEtag = null;
3595
3597
  let serverRevision = -1;
3598
+ // The work-point decisions the server last CONFIRMED, as `{id, ends}` rows for decided members only. They
3599
+ // are server-owned — a write that introduces, moves or clears one is refused — so this, not the live model,
3600
+ // is what an undo/redo restores them from: a refused edit (Swap ends moves them) or a delete that has not
3601
+ // saved yet leaves the live model disagreeing with the server. Refreshed on load, on a server install and
3602
+ // on every committed save.
3603
+ let serverDecided = [];
3604
+ const decidedMembers = (members) => (members || []).filter((m) => (m.ends || []).some((e) => e && e.workPointDecision))
3605
+ .map((m) => ({ id: m.id, ends: [0, 1].map((i) => (m.ends[i] && m.ends[i].workPointDecision ? { workPointDecision: structuredClone(m.ends[i].workPointDecision) } : {})) }));
3596
3606
  /**
3597
3607
  * How many times the VISIBLE document has changed. Not a save counter — `saveSeq` already is one, and
3598
3608
  * that is exactly why it cannot serve here: `flushContract` bumps `saveSeq` as well as `scheduleSave`
@@ -3737,7 +3747,7 @@ function handleContractChanged(m){
3737
3747
  a connection from clean to needs-review WITHOUT touching the sidecar, so no `review-changed` is
3738
3748
  emitted and reviewRevision does not move. Nothing else would ever ask. In Plan view, where the 3D
3739
3749
  scene does not exist, this is the only path that keeps the count honest. */
3740
- if(uncertain){uncertainWrites.delete(m.mutationId);if(m.storeRevision>serverRevision){const prev=serverEtag;serverEtag=m.etag;serverRevision=m.storeRevision;restampDraftBase(prev,m.etag);}reviewRefreshForOwnWrite();return;}
3750
+ if(uncertain){const uncertainSeq=uncertainWrites.get(m.mutationId);uncertainWrites.delete(m.mutationId);if(m.storeRevision>serverRevision){const prev=serverEtag;serverEtag=m.etag;serverRevision=m.storeRevision;restampDraftBase(prev,m.etag);}if(window.recoverStoredDecisions)window.recoverStoredDecisions(uncertainSeq);reviewRefreshForOwnWrite();return;}
3741
3751
  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;}
3742
3752
  if(m.storeRevision<=serverRevision)return;
3743
3753
  if(window.invalidateMemberEndReview)window.invalidateMemberEndReview('The model changed — check member ends again.');
@@ -4303,6 +4313,7 @@ async function boot() {
4303
4313
  if (hr.ok) DEV_MODE = (await hr.json()).appChannel === 'dev';
4304
4314
  } catch (_) { /* production-safe default: the diagnostic freeze stays off */ }
4305
4315
  C = loaded;
4316
+ serverDecided = decidedMembers(C.members);
4306
4317
  // The server's tag for the contract we just read. Every write echoes it back, so a write that would
4307
4318
  // land on top of someone else's is refused instead of silently winning.
4308
4319
  serverEtag = snapshotPayload.etag || res.headers.get('ETag');
@@ -4645,8 +4656,8 @@ function memberEndChoicesForReport(report,previous){
4645
4656
  function memberEndDistance(f,t){const a=f.currentPoint,z=a&&a.z&&Number.isFinite(a.z.known)?a.z.known:t.point.z.known;return Math.hypot(t.point.x-a.x,t.point.y-a.y,t.point.z.known-z);}
4646
4657
  // `id` rides in the snapshot, not just in the restore lookup (#938): restoring BY view id from a
4647
4658
  // snapshot that only recorded the page still collapses two views on one sheet onto each other.
4648
- function memberEndSnapshot(doc){return {v2:true,members:doc.members,provisional_members:doc.provisional_members||[],grid:doc.grid||null,plans:(doc.plans||[]).map(p=>({id:p.id,sheet:p.sheet,dims:p.dims||[],memberRefs:p.memberRefs||[],memberObservations:p.memberObservations||[],frame:p.frame||null,datum_ref:p.datum_ref,control2_ref:p.control2_ref})),joints:doc.joints||[],connections:doc.connections||[],details:doc.detail_placements||[],views:doc.views||[],member_types:doc.member_types||[],dim_style:doc.dim_style||null,member_styles:doc.member_styles||{},...(Array.isArray(doc.reference_models)?{reference_models:doc.reference_models}:{})};}
4649
- function installMemberEndContract(doc,etag,revision){
4659
+ function memberEndSnapshot(doc){return {v2:true,members:doc.members,provisional_members:doc.provisional_members||[],grid:doc.grid||null,plans:(doc.plans||[]).map(p=>({id:p.id,sheet:p.sheet,dims:p.dims||[],memberRefs:p.memberRefs||[],memberObservations:p.memberObservations||[],...(Object.hasOwn(p,'frame')?{frame:p.frame||null}:{}),datum_ref:p.datum_ref,control2_ref:p.control2_ref})),joints:doc.joints||[],connections:doc.connections||[],details:doc.detail_placements||[],views:doc.views||[],member_types:doc.member_types||[],dim_style:doc.dim_style||null,member_styles:doc.member_styles||{},...(Array.isArray(doc.reference_models)?{reference_models:doc.reference_models}:{})};}
4660
+ function installMemberEndContract(doc,etag,revision,keepHistory){
4650
4661
  V2_SESSION.restoreSnapshot(memberEndSnapshot(doc));V2_PROJECTIONS.clear();
4651
4662
  bumpRfiEpoch(); // #1090 — a server command replaced the model; the unresolved-size count is stale
4652
4663
  const activePlan=C.plans&&C.plans[C.active];
@@ -4655,9 +4666,68 @@ function installMemberEndContract(doc,etag,revision){
4655
4666
  syncElevationContext();
4656
4667
  // A server command replaces the model underneath the editor's local history. Retaining those snapshots
4657
4668
  // would let Ctrl+Z resurrect pre-command geometry without the server-owned decision/audit metadata.
4658
- undo.length=0;redo.length=0;updUR();
4669
+ // A save reply (`keepHistory`) is not a command: it is our own document with decisions staled, and
4670
+ // apply() restores decisions from `serverDecided`, so its history stays valid (see adoptSaveReply).
4671
+ if(!keepHistory){undo.length=0;redo.length=0;updUR();}
4672
+ serverDecided=decidedMembers(doc.members);
4659
4673
  bumpModelEditGeneration(); // the server replaced the document under the editor; nothing captured before this describes what is now on screen
4660
- const prev=serverEtag;serverEtag=etag;serverRevision=revision;restampDraftBase(prev,etag);conflicted=false;render();sync3D();
4674
+ // A restamped row is rewritten too: it still holds the document from BEFORE the server's change, and a
4675
+ // reload would put that back — a staled decision returning live, refused on the next save. A row from
4676
+ // another generation (a stale draft that could not be parked) is not ours to touch: only the user's own
4677
+ // next edit may replace it.
4678
+ const prev=serverEtag;serverEtag=etag;serverRevision=revision;if(restampDraftBase(prev,etag))persist();conflicted=false;render();sync3D();
4679
+ }
4680
+ // A save reply carries `contract` only when the write boundary staled retained work-point decisions — our
4681
+ // own document with server-owned fields changed. Wiping history here made the first edit after a drawing
4682
+ // read or a member-end Extend un-undoable. And when a newer edit is already pending, installing the reply
4683
+ // would revert it, so only the decisions are taken; that edit's own save then sends them back unchanged.
4684
+ function adoptSaveReply(doc,etag,revision,seq){
4685
+ if(seq===saveSeq)return installMemberEndContract(doc,etag,revision,true);
4686
+ const prev=serverEtag;serverEtag=etag;serverRevision=Math.max(serverRevision,revision);const ours=restampDraftBase(prev,etag);
4687
+ serverDecided=decidedMembers(doc.members);reconcileDecisions(); // after the tag: the write committed, whatever reconciling does
4688
+ if(ours)persist();
4689
+ }
4690
+ // #1938 - a write is known to have committed (its own-write echo moved the tag, or the uncertain-write echo
4691
+ // arrived) but its reply, the only carrier of a transformed contract, was lost. The tag advanced, the
4692
+ // decisions did not: the editor would keep a decision the server already staled and send it on the next
4693
+ // save, which the gateway refuses. Re-read the stored document and adopt its decisions exactly as a
4694
+ // transformed save reply is adopted. Only when the store still holds the tag we hold - a different tag is
4695
+ // somebody else's write and belongs to the external-change path.
4696
+ // Returns 'failed' when the stored document could not be read, otherwise true when it installed the whole stored document (nothing newer was pending), so a caller that
4697
+ // reports a generation can follow the install. `seq` is the write's OWN sequence: a newer edit, pending or
4698
+ // unsaved, must never be replaced by the older stored document, so then only the decisions are taken.
4699
+ // Reload would discard an edit that still sits in memory until its 500 ms save fires, so park it in the
4700
+ // browser draft first (the one the stale-draft banner restores). If it cannot be parked, say so instead.
4701
+ function reloadKeepingPendingEdit(){
4702
+ if(editorHasUnsavedWork()&&!parkDraftForExternalChange()){
4703
+ showAiUpdateBanner('Your latest edit could not be kept on this device, so reloading would lose it. Copy it out first.',{noReload:true});
4704
+ return;
4705
+ }
4706
+ location.reload();
4707
+ }
4708
+ async function recoverStoredDecisions(seq=saveSeq){
4709
+ const unreadable=(why)=>{
4710
+ console.warn('steel-editor: could not re-read the stored decisions after a lost save reply',why);
4711
+ showAiUpdateBanner('That save went through, but FloLess could not read back what the server kept — reload to pick up the latest version.',{onReload:reloadKeepingPendingEdit});
4712
+ return 'failed';
4713
+ };
4714
+ let body;
4715
+ try{const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+'/snapshot'+PROJECT_QS);if(!res.ok)return unreadable('HTTP '+res.status);body=await res.json();}
4716
+ catch(e){return unreadable(e);}
4717
+ if(!body||!body.contract||typeof body.etag!=='string'||!Number.isSafeInteger(body.storeRevision))return unreadable('malformed snapshot');
4718
+ if(body.etag!==serverEtag||!Array.isArray(body.contract.members))return false;
4719
+ if(JSON.stringify(decidedMembers(body.contract.members))===JSON.stringify(serverDecided))return false;
4720
+ const whole=seq===saveSeq&&saveT===null;
4721
+ adoptSaveReply(body.contract,body.etag,body.storeRevision,whole?seq:-1);
4722
+ return whole;
4723
+ }
4724
+ window.recoverStoredDecisions=recoverStoredDecisions; // the contract-event handler lives outside main()
4725
+ // A committed write moved what the server holds while a newer edit is pending, so that edit's document may
4726
+ // carry decisions the server no longer has (staled, or of a member this write deleted that an undo brought
4727
+ // back). Align them now, or its save is refused.
4728
+ function reconcileDecisions(){
4729
+ if(JSON.stringify(decidedMembers(C.members))===JSON.stringify(serverDecided))return;
4730
+ V2_SESSION.adoptWorkPointDecisions(serverDecided);render();sync3D();
4661
4731
  }
4662
4732
  async function memberEndRequest(path,body){
4663
4733
  if(!PROJECT)throw new Error('Member-end review is available inside a project.');
@@ -5353,11 +5423,23 @@ function commitMemberPositionProvider(id,patch,source){const m=byId(id);if(!m)re
5353
5423
  * branch it started on, IN BOTH DIRECTIONS: a slide is not frame-preserving to the bit (each endpoint
5354
5424
  * quantises independently, perturbing the direction by ~1e-9), so near the cone it can nudge a member
5355
5425
  * OUT of the seeded branch as easily as into it — and leaving the cone rebuilds a different section
5356
- * frame than the rigid preview showed.
5426
+ * frame than the rigid preview showed. The end-node drag has its own rule. All of it is ONE policy,
5427
+ * SteelCore.endpointFrameRefusal, which is the authority on the details.
5357
5428
  *
5358
5429
  * Returns a plain boolean. The pin, when one is applied, is announced here and only AFTER the write lands,
5359
5430
  * so a refused commit can never announce a pin that was never stored.
5360
5431
  */
5432
+ // One sentence for the column base→top rule, whichever path reaches it: a 3D end-node drag (refused in
5433
+ // commitMemberEndpointsProvider) or a typed Bottom/Top elevation (refused by the model and worded in edit()).
5434
+ const COLUMN_ORDER_REFUSAL='Couldn’t make that change: a column’s top can’t go below its bottom. Raise the top or lower the bottom.';
5435
+ // Why an end-node or reference-line move was refused by SteelCore.endpointFrameRefusal, one sentence per
5436
+ // reason it can return. None of them is about the SIZE of the move. An unknown reason is a programming
5437
+ // error, so it is logged and still refused in words rather than shown a sentence written for another case.
5438
+ const FRAME_REFUSAL={
5439
+ 'branch-flip':'This member is virtually plumb, so that move could rotate its profile — nothing moved. Type its end positions under Definition points in the Properties panel instead.',
5440
+ 'enters-plumb':'That would make the member plumb, which can rotate its profile — nothing moved. To make it plumb anyway, type its end positions under Definition points in the Properties panel.',
5441
+ reverses:'That would turn the member end for end, which can rotate its profile — nothing moved. Release the end before it passes the other end.',
5442
+ };
5361
5443
  function commitMemberEndpoints(id,spec,source){return runSteelAuthoring('stretch',{source:'reference-line-gizmo',selection:[id],pointsMm:[spec&&spec.from||[0,0,0],spec&&spec.to||[1,0,0]]},()=>commitMemberEndpointsProvider(id,spec,source));}
5362
5444
  function commitMemberEndpointsProvider(id,spec,source){
5363
5445
  const m=byId(id);if(!m)return positionRefuse('That member is no longer in the model.',source);
@@ -5370,18 +5452,34 @@ function commitMemberEndpointsProvider(id,spec,source){
5370
5452
  const q=(p)=>[SteelCore.quantizeMm(p[0]),SteelCore.quantizeMm(p[1]),SteelCore.quantizeMm(p[2])];
5371
5453
  const from=spec&&spec.from?q(spec.from):[...input.from],to=spec&&spec.to?q(spec.to):[...input.to];
5372
5454
  if(![...from,...to].every(Number.isFinite))return positionRefuse('That move produced a coordinate the model cannot store.',source);
5373
- const before=SteelCore.positionGizmoFrame(input.from,input.to,captured);
5374
- const after=SteelCore.positionGizmoFrame(from,to,captured);
5455
+ // The frame policy and the placement carry both read the frame the BAKE builds: the member's STORED
5456
+ // basis (global when it has none), not whatever authoring basis happens to be current (#1946).
5457
+ const storedBasis=input.canonical.positionBasis?{kind:'custom',x:input.canonical.positionBasis.x,y:input.canonical.positionBasis.y}:{kind:'global'};
5458
+ const before=SteelCore.positionGizmoFrame(input.from,input.to,storedBasis);
5459
+ const after=SteelCore.positionGizmoFrame(from,to,storedBasis);
5375
5460
  if(!after)return positionRefuse('That move leaves the member with no length.',source);
5376
5461
  const gesture=spec&&spec.gesture;
5462
+ // A column is stored base→top, and the model refuses one the other way round. Say so here, in words and
5463
+ // before the frame policy: dragging a plumb column's top below its base is ALSO a turn end for end, and
5464
+ // the column rule is the reason the user can act on.
5465
+ if(input.canonical.role==='column'&&from[2]>to[2])return positionRefuse(COLUMN_ORDER_REFUSAL,source);
5377
5466
  // A gesture that moves the line RIGIDLY (the axial slide, and since the redesign the two lateral
5378
5467
  // translates) must merely KEEP partFrame's branch, in both directions; a swing re-aims the member and
5379
- // has to land on the ordinary branch. This is a shared VALIDATION policy, not a claim that the two
5380
- // translations are numerically identical: each endpoint quantises independently, so near the degeneracy
5381
- // cone either one can cross the branch through rounding alone — which is exactly what this rejects.
5382
- if(SteelCore.directionPreservingGesture(gesture)?(!!after.degenerate!==!!(before&&before.degenerate))
5383
- :after.degenerate)return positionRefuse('That move would leave the section with no usable frame — try a smaller change.',source);
5384
- const pin=SteelCore.requiredDepthPin(input.canonical,{from:input.from,to:input.to},{from,to}).pin;
5468
+ // has to land on the ordinary branch; the end-node drag may not ENTER the plumb cone, nor turn end for
5469
+ // end inside it, but may stay in it — so a plumb column can be raised or lowered (#1933). One shared
5470
+ // VALIDATION policy, decided in SteelCore.endpointFrameRefusal. Slide and translate share the
5471
+ // keep-your-branch rule as a validation policy, not because the two are numerically identical: each
5472
+ // endpoint quantises independently, so near the degeneracy cone either one can cross the branch through
5473
+ // rounding alone, which is exactly what this rejects.
5474
+ const branch=SteelCore.endpointFrameRefusal(gesture,before,after);
5475
+ if(branch){
5476
+ if(!FRAME_REFUSAL[branch])console.error('steel: frame-branch refusal with no message',branch);
5477
+ return positionRefuse(FRAME_REFUSAL[branch]||'That move could rotate the member’s profile — nothing moved. Type its end positions under Definition points in the Properties panel instead.',source);
5478
+ }
5479
+ // #1946: carry the section's world orientation across a branch change or a reversal of the end-node drag.
5480
+ const carry=gesture==='endpoint'?SteelCore.endpointPlacementCompensationDetail(input.canonical,input.from,input.to,from,to,storedBasis):null;
5481
+ const placement=carry?carry.placement:null;
5482
+ const pin=SteelCore.requiredDepthPin(placement?{...input.canonical,...placement}:input.canonical,{from:input.from,to:input.to},{from,to}).pin;
5385
5483
  const current=positionAuthoringBasis();if(current.generation!==captured.generation)return positionRefuse('Frame changed — review the refreshed Profile Position and try again.',source);
5386
5484
  const ok=edit(()=>{MC().moveWorkPoints(m,{
5387
5485
  points:{from:{x:from[0],y:from[1],z:from[2]},to:{x:to[0],y:to[1],z:to[2]}},
@@ -5390,7 +5488,10 @@ function commitMemberEndpointsProvider(id,spec,source){
5390
5488
  // read, so the two agree by construction. Recomputing it here for a drag would compare the live member
5391
5489
  // against itself and render the staleness guard inert.
5392
5490
  expect:(spec&&spec.expect)||V2Commands.memberFingerprint(input.canonical),
5491
+ ...(placement?{placement}:{}),
5393
5492
  ...(pin===undefined?{}:{position:pin})});})===true;
5493
+ // The old width axis lay along the new member axis, so it cannot be kept; the depth axis was kept instead (#1946).
5494
+ if(ok&&carry&&carry.squared)toast('The section was turned so it stays square to the member.',false,5200);
5394
5495
  if(ok&&pin!==undefined)toast('Depth face pinned to “'+pin+'” so the steel stays where you put it.',false,5200);
5395
5496
  return ok;}
5396
5497
  /*
@@ -5755,7 +5856,7 @@ function syncDefaults(){for(const m of P.members)ModelCmd.syncToDefault(m,defaul
5755
5856
  // authored statement ("this control point is the model origin"), and JSON drops the undefined key, so
5756
5857
  // absence survives the round trip rather than being materialised.
5757
5858
  function snapshot(){
5758
- return JSON.stringify({v2:true,members:C.members,provisional_members:C.provisional_members||[],grid:C.grid||null,plans:C.plans.map(p=>({id:p.id,sheet:p.sheet,dims:p.dims||[],memberRefs:p.memberRefs||[],memberObservations:p.memberObservations||[],frame:p.frame||null,datum_ref:p.datum_ref,control2_ref:p.control2_ref})),joints:C.joints||[],connections:C.connections||[],details:C.detail_placements||[],views:C.views||[],member_types:C.member_types||[],dim_style:C.dim_style||null,member_styles:C.member_styles||{},clips:window.Steel3DView?.clipState?.()??null,...(Array.isArray(C.reference_models)?{reference_models:C.reference_models}:{})});
5859
+ return JSON.stringify({v2:true,members:C.members,provisional_members:C.provisional_members||[],grid:C.grid||null,plans:C.plans.map(p=>({id:p.id,sheet:p.sheet,dims:p.dims||[],memberRefs:p.memberRefs||[],memberObservations:p.memberObservations||[],...(Object.hasOwn(p,'frame')?{frame:p.frame||null}:{}),datum_ref:p.datum_ref,control2_ref:p.control2_ref})),joints:C.joints||[],connections:C.connections||[],details:C.detail_placements||[],views:C.views||[],member_types:C.member_types||[],dim_style:C.dim_style||null,member_styles:C.member_styles||{},clips:window.Steel3DView?.clipState?.()??null,...(Array.isArray(C.reference_models)?{reference_models:C.reference_models}:{})});
5759
5860
  }
5760
5861
  // Undo/redo is a SINGLE GLOBAL stack (not per-plane): snapshot() above captures EVERY plane's
5761
5862
  // members, so one whole-model stack is coherent — undo restores all planes at once, and a cross-
@@ -5779,9 +5880,11 @@ function refreshOverlayDims3d(){if(window.Steel3DView&&window.Steel3DView.refres
5779
5880
  // recomputing it there would scan every member in the model on every click on a beam. The count is a
5780
5881
  // function of the MODEL, and this is the one place the model changes.
5781
5882
  function pushUndo(prev){undo.push(prev);if(undo.length>200)undo.shift();redo.length=0;scheduleSave();bumpRfiEpoch();updUR();}
5782
- function apply(json){
5883
+ // `noSave` — a restore back to a state that is already the saved one (a refused edit, #1947) must not queue a
5884
+ // draft write: nothing changed, and an undo entry-less write would only churn the save pill.
5885
+ function apply(json,noSave){
5783
5886
  const d=JSON.parse(json);
5784
- V2_SESSION.restoreSnapshot(d);
5887
+ V2_SESSION.restoreSnapshot(d,{decisionsFrom:serverDecided}); // server-owned decisions come back as the server last confirmed them; a snapshot's own copy may be one the save boundary has since retired
5785
5888
  bumpRfiEpoch(); // #1090 — an undo/redo changes which sizes are unresolved; see bumpRfiEpoch
5786
5889
  // #1880 — the active view can be an ELEVATION (a 3D edit made while one is shown), and the plan
5787
5890
  // transform refuses anything that is not a plan: the same placeholder `setPlan` installs for it, then.
@@ -5802,7 +5905,7 @@ function apply(json){
5802
5905
  if('reference_models' in d)pushReferences(); // native sync3D cannot repaint the editor-only reference layer
5803
5906
  if('member_types' in d)C.member_types=sanitizeMemberTypes(d.member_types);
5804
5907
  if('member_styles' in d)C.member_styles=(d.member_styles&&typeof d.member_styles==='object'&&!Array.isArray(d.member_styles))?d.member_styles:{}; // F5: model-global per-type line styles ride the undo stack (like dim_style) so a setMemberLineStyle() edit() is undoable
5805
- scheduleSave();render();sync3D();}
5908
+ if(!noSave)scheduleSave();render();sync3D();}
5806
5909
  function doUndo(){if(!undo.length)return;return runSteelAuthoring('undo',{source:'history'},()=>{redo.push(snapshotLike());apply(undo.pop());});}
5807
5910
  function doRedo(){if(!redo.length)return;return runSteelAuthoring('redo',{source:'history'},()=>{undo.push(snapshotLike());apply(redo.pop());});}
5808
5911
  /**
@@ -5837,10 +5940,22 @@ function edit(fn){
5837
5940
  catch(err){
5838
5941
  if(err&&err.name==='V2CommandError'){
5839
5942
  drawDraft=null;drawBasisTok=null;dimDraft=null;cmDraft=null;drawPrevClear();dimPrevClear();cmPrevClear();
5943
+ // A column is stored base→top and the model refuses one stored the other way round — but only as
5944
+ // "<command> would leave steel.model/v2 invalid", which names neither the column nor what to do. A
5945
+ // typed Bottom above the Top gets the rule in words instead (the 3D end-node drag refuses before it
5946
+ // gets here, with the same sentence). Only when that rule is the SOLE problem: a refusal that also
5947
+ // carries another one keeps the generic text rather than naming half the reason. (#1933)
5840
5948
  const text=err.code==='elevation-unknown'
5841
5949
  ?`Couldn’t complete that edit: the elevation is unknown. Enter the TOS first.`
5950
+ :(err.code==='model-invalid'&&V2Validation&&V2Validation.onlyColumnEndpointOrder(err.details))
5951
+ ?COLUMN_ORDER_REFUSAL
5842
5952
  :(err.message||'That edit could not be applied safely.');
5843
- toast(text);render();return false;}
5953
+ // All-or-nothing (#1947): several edits run ONE model transaction per member (a multi-selection's Bottom/Top,
5954
+ // Reset all ends, Definition points), so an earlier one may already have been applied when a later one is
5955
+ // refused. Put the pre-edit model back — otherwise the applied part is on screen with no undo entry and no save.
5956
+ // The restore uses the server-confirmed work-point decisions (apply() passes decisionsFrom: serverDecided), exactly as undo does.
5957
+ try{apply(pv,true);}catch(restoreErr){console.error('steel: restoring the pre-edit model after a refused edit failed; repainting the current model instead',restoreErr);render();}
5958
+ toast(text);return false;}
5844
5959
  throw err;}
5845
5960
  pushUndo(pv);render();sync3D();return true;}
5846
5961
  // The common engine owns gesture lifecycle and immutable authoring intents; Steel remains the provider
@@ -6130,7 +6245,7 @@ async function persistServer(force,token){const seq=saveSeq;
6130
6245
  // Name this write so its own SSE echo is recognised by identity, not by a 2.5 s clock (unit 5, P1c-3).
6131
6246
  // Minted BEFORE the request, deliberately: the broadcast can reach us before the response does, and an
6132
6247
  // id we do not yet know would read as somebody else's write and reload the page mid-edit.
6133
- const mid=newMutationId();claimMutation(mid);
6248
+ const mid=newMutationId();claimMutation(mid);const tagAtSend=serverEtag;
6134
6249
  try{ // capture THIS intent's id (scheduleSave already bumped saveSeq for the edit) — a newer edit/flush bumps it again and invalidates this PUT's late response
6135
6250
  const headers={'content-type':'application/json','x-floless-mutation-id':mid};
6136
6251
  // TOTAL, as of P1c: a write with no precondition is refused (428), so every branch must send one.
@@ -6141,6 +6256,7 @@ async function persistServer(force,token){const seq=saveSeq;
6141
6256
  if(force)headers['if-match']='*';
6142
6257
  else if(serverEtag)headers['if-match']=serverEtag;
6143
6258
  else headers['if-none-match']='*';
6259
+ const sentDecided=decidedMembers(C.members); // what this write will make the server hold, if it commits without a transformed reply
6144
6260
  const res=await fetch('/api/contract/'+encodeURIComponent(APP_ID)+PROJECT_QS,{method:'PUT',headers,body:JSON.stringify(C)});
6145
6261
  // A REFUSED write produces no broadcast, so its id would sit in ownWrites forever — where the only
6146
6262
  // thing it can still do is wrongly suppress somebody else's event. Released on every leg below.
@@ -6162,7 +6278,7 @@ async function persistServer(force,token){const seq=saveSeq;
6162
6278
  // write is usually still in flight — the server broadcasts before it replies — so releasing here would
6163
6279
  // make the tab read its OWN echo as external and reload itself mid-edit. The id is released when the
6164
6280
  // echo consumes it, when the write fails, or when the SSE channel closes (nothing can echo after that).
6165
- 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;
6281
+ 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))adoptSaveReply(d.contract,t,d.storeRevision,seq);else{if(t){const pv=serverEtag;serverEtag=t;restampDraftBase(pv,t);}if(Number.isSafeInteger(d.storeRevision))serverRevision=Math.max(serverRevision,d.storeRevision);serverDecided=sentDecided;if(seq!==saveSeq)reconcileDecisions();}conflicted=false;
6166
6282
  // The write COMMITTED. Apply its revalidation report ONLY when we can prove it describes the live `C`:
6167
6283
  // the body was readable AND `seq===saveSeq` (no newer edit landed while this PUT was in flight). Otherwise
6168
6284
  // do NOTHING — no merge, no bookkeeping. That is safe because a joint whose removal we then miss is
@@ -6171,11 +6287,12 @@ async function persistServer(force,token){const seq=saveSeq;
6171
6287
  // Apply ONLY a report we can prove is current; otherwise do nothing — the server re-decides an
6172
6288
  // introduced joint on the next save, so a missed removal cannot survive (see the note above).
6173
6289
  if(bodyReadable&&usable&&seq===saveSeq)applyRevalidation(d.revalidation);
6290
+ if(!bodyReadable)recoverStoredDecisions(seq); // #1938 - committed, body lost: the tag moved but a staled decision did not
6174
6291
  } // chain the next edit off the new tag, and install any server-staled endpoint authority instead of leaving the browser on bytes the server deliberately transformed; then tell the user what the write-boundary revalidation did to their connections
6175
6292
  else releaseMutation(mid); // 400/500: nothing was written, so nothing will echo
6176
6293
  if(seq===saveSeq)setSaved(res.ok?'ok':'err'); // only the latest save owns the pill (a stale late response must not clobber a newer verdict)
6177
6294
  if(!res.ok)console.error('server save rejected ('+res.status+')',await res.text().catch(()=>'')); // 400 = schema reject: edits won't be what Approve bakes
6178
- }catch(e){releaseMutation(mid);if(seq===saveSeq)setSaved('err');console.error('server save failed',e);
6295
+ }catch(e){releaseMutation(mid);if(seq===saveSeq)setSaved('err');console.error('server save failed',e);if(serverEtag!==tagAtSend)recoverStoredDecisions(seq); // #1938 - the own-write echo moved the tag, so the write committed and only its reply was lost
6179
6296
  // The write may have committed even though we never saw the response — nothing to do here. `C.joints` can
6180
6297
  // then still carry a joint the store removed, and the NEXT save re-introduces it, which is exactly the
6181
6298
  // shape the server always re-decides. So the removal simply happens again, authoritatively.
@@ -6220,7 +6337,8 @@ async function flushContractWith(token, signal) {
6220
6337
  const seq = ++saveSeq;
6221
6338
  let adoptedTag = null; // the tag THIS write produced, reported back for the sign-off's precondition
6222
6339
  let publishedGeneration = modelEditGeneration;
6223
- let res;
6340
+ const tagAtSend = serverEtag;
6341
+ let res, sentDecided = serverDecided;
6224
6342
  try {
6225
6343
  // Conditional like every other write, and it MUST refresh the tag on success. Getting this wrong is
6226
6344
  // not theoretical — the first cut omitted both, so an Approve-time flush bypassed the precondition
@@ -6232,10 +6350,12 @@ async function flushContractWith(token, signal) {
6232
6350
  // Captured HERE, in the same synchronous expression that serialises the body, so it names the
6233
6351
  // document this PUT actually carried — not one an edit produced while the request was in flight.
6234
6352
  publishedGeneration = modelEditGeneration;
6353
+ sentDecided = decidedMembers(C.members); // same moment, same reason — see persistServer
6235
6354
  res = await fetch('/api/contract/' + encodeURIComponent(APP_ID) + PROJECT_QS, { method: 'PUT', headers, body: JSON.stringify(C), signal });
6236
6355
  } catch (e) {
6237
- if(signal&&signal.aborted){quarantineMutation(mid);throw e;}
6356
+ if(signal&&signal.aborted){quarantineMutation(mid, seq);throw e;}
6238
6357
  releaseMutation(mid); // nothing was written, so no broadcast will ever carry this id
6358
+ if (serverEtag !== tagAtSend) recoverStoredDecisions(seq); // #1938 - the echo already moved the tag, so the write DID commit: adopt what it staled
6239
6359
  if (seq === saveSeq) setSaved('err'); // B9: a network rejection must show "Save failed", not leave the pill stuck on "Saving…" (this fn cancels the debounced persistServer that would otherwise flag it)
6240
6360
  // Parity with persistServer: a lost response needs no bookkeeping here — a joint whose removal we missed
6241
6361
  // is re-introduced by the next save, and the server always re-decides an introduced joint.
@@ -6257,12 +6377,12 @@ async function flushContractWith(token, signal) {
6257
6377
  showConflictBanner();
6258
6378
  throw new Error('save conflict');
6259
6379
  }
6260
- if (res.ok) { let d = {}, bodyReadable = true; try { d = await res.json(); } catch (_) { bodyReadable = false; } if(signal&&signal.aborted)quarantineMutation(mid); 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;
6380
+ if (res.ok) { let d = {}, bodyReadable = true; try { d = await res.json(); } catch (_) { bodyReadable = false; } if(signal&&signal.aborted)quarantineMutation(mid, seq); const t = d.etag || res.headers.get('ETag'); adoptedTag = t || null; if (d.contract && t && Number.isSafeInteger(d.storeRevision)) { const generationBefore = modelEditGeneration; adoptSaveReply(d.contract, t, d.storeRevision, seq); /* #1936 - installing the reply re-bumps the generation although nothing the person looked at changed; report the post-install generation, but ONLY when nothing visible moved between the PUT and the install (a genuine concurrent edit still shows as a mismatch) */ if (generationBefore === publishedGeneration && modelEditGeneration === generationBefore + 1) publishedGeneration = modelEditGeneration; } else { if (t) { const pv = serverEtag; serverEtag = t; restampDraftBase(pv, t); } if (Number.isSafeInteger(d.storeRevision)) serverRevision = Math.max(serverRevision, d.storeRevision); serverDecided = sentDecided; if (seq !== saveSeq) reconcileDecisions(); } conflicted = false;
6261
6381
  // The flush committed. Same rule as persistServer: apply the report only when the body was readable and
6262
6382
  // `seq===saveSeq` (Approve awaits this flush, so the user CAN edit meanwhile and make it stale). Otherwise
6263
6383
  // do nothing — the next save re-introduces any joint whose removal we missed, and the server re-decides it.
6264
6384
  const usable = !!t || Number.isSafeInteger(d.storeRevision);
6265
- if (bodyReadable && usable && seq === saveSeq) applyRevalidation(d.revalidation); }
6385
+ if (bodyReadable && usable && seq === saveSeq) applyRevalidation(d.revalidation); if (!bodyReadable) { const generationBefore = modelEditGeneration; /* the sign-off reads the generation this returns, so the recovery lands before it, and a whole-document install is followed exactly like the reply install above */ const recovered = await recoverStoredDecisions(seq); if (recovered === 'failed') publishedGeneration = -1; /* the stored document was never confirmed, so no sign-off may match it: the person is asked to check again */ else if (recovered === true && generationBefore === publishedGeneration && modelEditGeneration === generationBefore + 1) publishedGeneration = modelEditGeneration; } }
6266
6386
  else releaseMutation(mid);
6267
6387
  if (seq === saveSeq) setSaved(res.ok ? 'ok' : 'err'); // only the latest save owns the pill
6268
6388
  if (!res.ok) throw new Error('save failed (' + res.status + ')');
@@ -6454,8 +6574,6 @@ function applyDraftFields(d){
6454
6574
  candidate.prop_labels=sanitizePropLabels(candidate.prop_labels,new Set((Array.isArray(candidate.views)?candidate.views:[]).map(v=>v&&v.id)));
6455
6575
  // A draft written before split/merge/delete kept label pins current can pin a member it no longer has.
6456
6576
  // Restoring that as-is makes every later save fail on the server, so the dead pins go now.
6457
- const deadPins=V2Commands.prunePropLabelPins(candidate);
6458
- if(deadPins)console.warn('steel-editor: dropped '+deadPins+' property-label pin(s) naming members this draft no longer has');
6459
6577
  // REFERENCES ARE RECONCILED, NEVER REPLACED — and this is not tidiness, it is a reference that
6460
6578
  // vanished in front of me. Which references EXIST is the server's answer: insert and remove are
6461
6579
  // routes that write the contract themselves, and `adoptReferenceWrite` then re-points this draft at
@@ -6475,6 +6593,16 @@ function applyDraftFields(d){
6475
6593
  }
6476
6594
  if(d.active!=null)candidate.active=d.active;
6477
6595
  try{
6596
+ // INSIDE the try (#1945): `members` has no sanitiser, so a corrupted draft can carry a non-list there
6597
+ // and the prune below would throw from the click handler with nothing shown. Anything that cannot be
6598
+ // pruned is a draft that cannot be applied — refused like every other malformed draft.
6599
+ const deadPins=V2Commands.prunePropLabelPins(candidate);
6600
+ if(deadPins)console.warn('steel-editor: dropped '+deadPins+' property-label pin(s) naming members this draft no longer has');
6601
+ // Decisions are server-owned like references, and a draft can hold an old copy: a build before the
6602
+ // undo fix re-stamped the draft onto a save's tag WITHOUT rewriting the decision that save staled,
6603
+ // so restoring it verbatim put a live decision back and refused every save. Inside the try, so a
6604
+ // malformed `members` is refused like any draft that fails validation.
6605
+ V2Commands.adoptWorkPointDecisions(candidate.members||[],serverDecided);
6478
6606
  V2_SESSION.replaceDocument(candidate,'restore browser draft');
6479
6607
  C.active=candidate.active;
6480
6608
  // The camera on screen is no restored view's snapshot, even when an id survived — so nothing is active,
@@ -9302,6 +9430,10 @@ function inspectorHeightNotes(m,canonical){
9302
9430
  box.append(chip,text);
9303
9431
  // #1906: the person's source note and pictures travel with the answer, so the model says why.
9304
9432
  if(typeof a.note==='string'&&a.note){const note=document.createElement('span');note.textContent=' Source: '+a.note+'.';box.append(note);}
9433
+ // #1903: on a member already in the model, the drawings stated another height here and the person
9434
+ // accepted their own answer over it in the review. Kept said, so the record shows the choice.
9435
+ const od=a.overDrawing;
9436
+ if(od&&Number.isFinite(od.low)&&Number.isFinite(od.high)){const over=document.createElement('span');over.textContent=' The drawings state '+(Math.abs(od.high-od.low)<0.5?fmtDispElev(od.low):'between '+fmtDispElev(od.low)+' and '+fmtDispElev(od.high))+' here; you accepted your answer in the review.';box.append(over);}
9305
9437
  for(const ref of Array.isArray(a.evidence)?a.evidence:[])box.append(' ',answerPictureButton(a.requestId,ref,String(a.label||'this end')));
9306
9438
  // Same anchor as the assumed note below: after the field's whole row, never inside the value cell.
9307
9439
  const aCell=input.closest('.pval'),aRow=aCell&&aCell.parentElement&&aCell.parentElement!==document.getElementById('panel')?aCell.parentElement:null;
@@ -12887,7 +13019,7 @@ document.getElementById('mrgB').onclick=()=>{const r=mergeCollinearJS(P.members)
12887
13019
  toast('Merged '+r.mergedAway+' segment'+(r.mergedAway===1?'':'s')+' into '+r.runs+' member'+(r.runs===1?'':'s'));};
12888
13020
  document.getElementById('undoB').onclick=doUndo;
12889
13021
  document.getElementById('redoB').onclick=doRedo;
12890
- document.getElementById('dragMoveB').onclick=()=>{setDragMove(!dragMoveOn);toast(dragMoveOn?'Drag to move/copy: ON — drag moves, Ctrl+drag copies':'Drag to move/copy: OFF — a click only selects');};
13022
+ document.getElementById('dragMoveB').onclick=()=>{setDragMove(!dragMoveOn);toast(dragMoveOn?'Drag to move/copy: ON — in 2D, drag moves and Ctrl+drag copies. In 3D, use the end-nodes, the Position handle or the Move tool':'Drag to move/copy: OFF — a click only selects');};
12891
13023
  setDragMove(dragMoveOn); // reflect the persisted state on load (body class + pill)
12892
13024
  /* #1571: an Esc this editor leaves unused closes the shell's editor overlay (web/overlay-escape.js). That reads
12893
13025
  preventDefault() as "this Esc was mine", but most rungs of the ladder below act without it. So the ladder's LAST
@@ -14357,7 +14489,7 @@ function paintChatQuestions(p){
14357
14489
  if(!selected.length&&!nothing)return;
14358
14490
  const box=ChatQuestions.renderChatQuestions({doc:document,chatLinks,selected,resolves:chatSubjectResolves,
14359
14491
  currentLabel:link=>subjectLabelText(subjectLabel({kind:link.kind,id:link.id})),commandPrefix:'steel',
14360
- onShow:link=>!!modelPanelBridge&&modelPanelBridge.openChat(link.chatId,link.messageEventId,PROJECT),
14492
+ onShow:link=>!!modelPanelBridge&&modelPanelBridge.openChat(link.chatId,link.messageEventId,PROJECT,link.owner),
14361
14493
  onRetry:()=>refreshChatLinks(true),toast,ui:chatQuestionsUi});
14362
14494
  if(box)p.append(box);
14363
14495
  }
@@ -20,6 +20,17 @@ export const POSITION_BASIS_CLIENT_VALIDATION_VERSION=POSITION_BASIS_CAPABILITY_
20
20
  const rows = (v) => Array.isArray(v) ? v : [];
21
21
  const object = (v) => v && typeof v === 'object' && !Array.isArray(v);
22
22
 
23
+ /**
24
+ * True when a refused command's validation issues are the column base→top rule and NOTHING else — the one
25
+ * refusal the steel editor words for people instead of "would leave steel.model/v2 invalid" (#1933). When
26
+ * another problem rides along, naming only this one would hide it, so the caller keeps its generic text.
27
+ * The issue code is this module's own, so the predicate lives beside the check that emits it.
28
+ */
29
+ export function onlyColumnEndpointOrder(issues) {
30
+ return Array.isArray(issues) && issues.length > 0
31
+ && issues.every((issue) => /^column-endpoint-order\b/.test(String(issue)));
32
+ }
33
+
23
34
  export function validateClientSteelModelV2(doc, schema) {
24
35
  const shape = validateSchemaSubset(doc, schema);
25
36
  const issues = shape.errors.map((e) => `${e.path}: ${e.message}`);
@@ -16,7 +16,7 @@ import { memberPresence, projectionLink } from './steel-model-v2-projection.js';
16
16
  import { gridLabelPatch, parseSpacings } from './grid-core.js';
17
17
  import { IN_TO_MM as IN_MM } from './steel-units.js';
18
18
  import {
19
- basisFromAxes, effectiveDepthPosition, effectiveWidthPosition, outlineFor, partFrame,
19
+ basisFromAxes, endpointPlacementCompensation, effectiveDepthPosition, effectiveWidthPosition, outlineFor, partFrame,
20
20
  positionOffsetVector, reversePlacement, sectionExtents,
21
21
  quantizeMm, requiredDepthPin,
22
22
  POSITION_BASIS_CAPABILITY_VERSION,
@@ -652,6 +652,25 @@ function deleteMembersFromDocument(doc, ids) {
652
652
  for (const plan of doc.plans || []) plan.memberRefs = (plan.memberRefs || []).filter((id) => !selected.has(id));
653
653
  }
654
654
 
655
+ /*
656
+ * `workPointDecision` is server-owned: a client write that introduces, replaces or clears one is refused
657
+ * (`member-end-decision-forbidden`), and only the save boundary or a member-end command changes it. So
658
+ * every member end takes the decision `authority` holds for that member id and end, or none — a member the
659
+ * authority no longer has (an undone delete) comes back undecided rather than re-minting authority.
660
+ */
661
+ export function adoptWorkPointDecisions(members, authority) {
662
+ const byId = new Map((authority || []).map((member) => [member.id, member]));
663
+ for (const member of members) {
664
+ for (const end of [0, 1]) {
665
+ const decision = byId.get(member.id)?.ends?.[end]?.workPointDecision;
666
+ if (decision) {
667
+ member.ends ??= [{}, {}];
668
+ member.ends[end] = { ...member.ends[end], workPointDecision: clone(decision) };
669
+ } else if (member.ends?.[end]) delete member.ends[end].workPointDecision;
670
+ }
671
+ }
672
+ }
673
+
655
674
  /** @param {any} model @param {{validate?: (doc: any) => any, mintId?: () => string, afterCommit?: (effect: any) => void, resolveSection?: (member:any) => any}} options */
656
675
  export function createV2CommandSession(model, options = {}) {
657
676
  const {
@@ -671,11 +690,17 @@ export function createV2CommandSession(model, options = {}) {
671
690
  return { structural: true };
672
691
  });
673
692
  },
674
- restoreSnapshot(saved) {
693
+ // `decisionsFrom`: an undo/redo rewinds the editor's own edits, never server-owned authority — see
694
+ // adoptWorkPointDecisions. A server document is installed without it, so its decisions stand.
695
+ restoreSnapshot(saved, { decisionsFrom } = {}) {
675
696
  return session.transact('restore undo snapshot', (draft) => {
676
697
  draft.members = Array.isArray(saved.members) ? clone(saved.members) : [];
698
+ if (decisionsFrom) adoptWorkPointDecisions(draft.members, decisionsFrom);
677
699
  if (Object.hasOwn(saved, 'provisional_members')) {
678
- draft.provisional_members = Array.isArray(saved.provisional_members) ? clone(saved.provisional_members) : [];
700
+ const prov = Array.isArray(saved.provisional_members) ? clone(saved.provisional_members) : [];
701
+ // An EMPTY list over a document that never had the key stays absent, so restoring back to the
702
+ // state an edit started from is exact — not "the same model plus an empty array" (#1947).
703
+ if (prov.length || Object.hasOwn(draft, 'provisional_members')) draft.provisional_members = prov;
679
704
  }
680
705
  draft.grid = Object.hasOwn(saved, 'grid') ? clone(saved.grid) : null;
681
706
  // Keyed by VIEW ID, not page (#938): with two views on one sheet a page-keyed map holds one of
@@ -687,7 +712,12 @@ export function createV2CommandSession(model, options = {}) {
687
712
  plan.dims = clone(row.dims || []);
688
713
  plan.memberRefs = clone(row.memberRefs || []);
689
714
  plan.memberObservations = clone(row.memberObservations || []);
690
- plan.frame = clone(row.frame || null);
715
+ // Absent stays absent (#1947): `frame: null` is not what a plan that never had one carries.
716
+ // A snapshot OMITS the key for a plan that had none (an own `frame: null` means it really was
717
+ // null), so a frame added since is removed again rather than replaced by `null`.
718
+ if (row.frame) plan.frame = clone(row.frame);
719
+ else if (!Object.hasOwn(row, 'frame')) delete plan.frame;
720
+ else if (Object.hasOwn(plan, 'frame') && plan.frame !== null) plan.frame = null;
691
721
  // Registration controls, restored by PRESENCE: an absent `datum_ref` says "this control point
692
722
  // is the model origin", so a missing key must delete rather than be skipped (#740). An
693
723
  // `undefined` VALUE is absent too (#1446): `memberEndSnapshot` maps `datum_ref: p.datum_ref`,
@@ -717,6 +747,13 @@ export function createV2CommandSession(model, options = {}) {
717
747
  return { structural: true };
718
748
  });
719
749
  },
750
+ /** Take the server's work-point decisions and nothing else, keeping every local edit. */
751
+ adoptWorkPointDecisions(authority) {
752
+ return session.transact('adopt work-point decisions', (draft) => {
753
+ adoptWorkPointDecisions(draft.members || [], authority);
754
+ return { structural: true };
755
+ });
756
+ },
720
757
  transact(label, mutator) {
721
758
  const draft = clone(model);
722
759
  const effect = mutator(draft) || {};
@@ -848,7 +885,42 @@ export function createV2CommandSession(model, options = {}) {
848
885
  // steel jumps. The commit must carry the drag-start face exactly when that would happen - and the
849
886
  // caller does not get to decide: this recomputes it from the CURRENT member and the QUANTISED
850
887
  // candidate points, through the same shared helper the editor predicts with.
851
- const need = requiredDepthPin(member, before, next);
888
+ // (d0) PLACEMENT CARRY (#1946). An end-node drag that moves partFrame between its branches, or turns
889
+ // the member end for end, must re-express the stored roll (and, on a reversal, the mirrored faces)
890
+ // in the SAME transaction, or the section turns about its own axis. Allow-listed so this stays a
891
+ // work-point mover, not a general member patcher; the pin below is decided against the member as it
892
+ // WILL be stored.
893
+ const placement = spec.placement && typeof spec.placement === 'object' ? spec.placement : {};
894
+ const PLACEMENT_KEYS = ['rot', 'position', 'positionOffset', 'positionH', 'positionHOffset'];
895
+ for (const key of Object.keys(placement)) {
896
+ const v = placement[key];
897
+ if (!PLACEMENT_KEYS.includes(key)
898
+ || (key === 'rot' || key === 'positionOffset' || key === 'positionHOffset' ? !(typeof v === 'number' && Number.isFinite(v)) : v !== undefined && typeof v !== 'string')) {
899
+ throw new V2CommandError('move-points-invalid', 'That move produced a placement the model can’t store.');
900
+ }
901
+ }
902
+ // The patch is VERIFIED against the compensation the geometry demands, not merely shape-checked: the
903
+ // same pure function the editor predicts with derives it from the before/after work points and the
904
+ // member's stored basis, and a caller may carry exactly that - nothing more, nothing less - or the
905
+ // move would rotate / offset the steel unmeasured. (A tolerance only for float noise.)
906
+ const storedBasis = member.positionBasis
907
+ ? { kind: 'custom', x: member.positionBasis.x, y: member.positionBasis.y } : { kind: 'global' };
908
+ const demanded = endpointPlacementCompensation(member, before.from, before.to, next.from, next.to, storedBasis) || {};
909
+ // Tight and NOT modulo 360: a roll that differs by whole turns is a different number to the trig that
910
+ // reads it, so it is refused rather than accepted. What is stored is always the DERIVED value.
911
+ const sameField = (key, a, b) => (typeof a === 'number' && typeof b === 'number') ? Math.abs(a - b) < 1e-6 : a === b;
912
+ // Only a SUPPLIED patch is verified. A move that carries none (the swings, slides and translates - the
913
+ // editor sends `placement` for the end-node gesture alone) behaves exactly as it always did.
914
+ for (const key of (spec.placement ? new Set([...Object.keys(placement), ...Object.keys(demanded)]) : [])) {
915
+ if (!sameField(key, placement[key], demanded[key])) {
916
+ throw new V2CommandError('move-points-placement',
917
+ 'That move carried a section turn or offset that doesn’t match what the move needs — nothing was moved.');
918
+ }
919
+ }
920
+ // A verified patch is replaced by the derived one, so stored placement is exactly the computed
921
+ // compensation (the caller's near-equal values are never written).
922
+ const carried = spec.placement ? demanded : placement;
923
+ const need = requiredDepthPin({ ...member, ...carried }, before, next);
852
924
  if (spec.position !== need.pin) {
853
925
  throw new V2CommandError('move-points-pin',
854
926
  need.pin === undefined
@@ -861,6 +933,9 @@ export function createV2CommandSession(model, options = {}) {
861
933
  // one end erases the mark on the other too.
862
934
  setEndpoint(member, index, { x, y, z: carryAssumed(member[key]?.z, { known: z }) });
863
935
  }
936
+ for (const key of Object.keys(carried)) {
937
+ if (carried[key] === undefined) delete member[key]; else member[key] = carried[key];
938
+ }
864
939
  if (need.pin !== undefined) member.position = need.pin;
865
940
  return { changedIds: [memberId] };
866
941
  });