@floless/app 0.111.3 → 0.112.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -949,6 +949,12 @@
949
949
  renderReadinessState = null;
950
950
  track('workspace_project_opened', { app: p.app }); // a real open (card click or post-create landing)
951
951
  lastRevState = 'none'; stopRevisionPoll(); closeRevReview(); // fresh project — drop any prior revision-poll state and any open review
952
+ // …and any open CONVERSION, for the same reason. The header project combo reaches `openProject`
953
+ // without going through `closeProject`, so switching projects under an open migrate modal would
954
+ // otherwise leave it on screen bound to `migState.projectId` — the project just navigated away
955
+ // from. Narrow (the backdrop covers the combo, so only an untrapped Tab reaches it) and the symmetry
956
+ // is the point: `closeRevReview` on the line above exists for exactly this.
957
+ migReady = null; closeMigrate();
952
958
  // Per-project, like everything above it: never let one project's answer describe another's. Not
953
959
  // observable today (every history render is preceded by a fetch that sets it, and a failed fetch
954
960
  // renders no rows), but leaving a stale cross-project value in place is the shape of bug this
@@ -987,6 +993,14 @@
987
993
  // have applied a review to a project that was no longer on screen. The card is hidden two lines
988
994
  // down for the same reason; the modal was simply missed.
989
995
  closeRevReview();
996
+ // AND SO IS THE CONVERSION OFFER, for the same reason plus one of its own. `migReady` is derived
997
+ // from the OPEN project's contract and is what gates the `⋯` menu item — left set, the landing
998
+ // kebab for the project just closed would still offer "Convert to the 3D model…", and clicking it
999
+ // would do nothing at all, because `openMigrate` bails on a null `current`. A menu item that is
1000
+ // visible and inert is worse than one that is absent. (Found by the code review; the modal below
1001
+ // was already per-project, the two variables behind it were not.)
1002
+ migReady = null;
1003
+ closeMigrate();
990
1004
  lastRevState = 'none'; $revisionCard.hidden = true; closeProjMenu(); applyMode(); syncWorkspaceGuide();
991
1005
  }
992
1006
  document.getElementById('ws-back').addEventListener('click', closeProject);
@@ -1024,6 +1038,10 @@
1024
1038
  if ($sourcePlaceholder) $sourcePlaceholder.hidden = !(s === 'drawings' && !drawingsHasFrame);
1025
1039
  $drawingsBar.hidden = s !== 'drawings';
1026
1040
  renderRevisionCard(); // reflect any pending/failed revision read (card shows only on the Drawings step)
1041
+ // The conversion offer is Model-step scoped, and re-derived on every entry rather than cached:
1042
+ // the project's contract can change under this shell (a revision read, another tab, the editor's
1043
+ // own save), and a banner offering to convert a project that is already v2 is worse than none.
1044
+ refreshMigrateGate();
1027
1045
  // Exports is a shell-rendered pane (not an iframe): show/hide + (re)paint on open.
1028
1046
  const showExports = s === 'exports';
1029
1047
  $wsExports.hidden = !showExports;
@@ -3458,14 +3476,110 @@
3458
3476
  return row;
3459
3477
  }
3460
3478
 
3479
+ /** Grid sub-values that are ARRAYS OF OBJECTS or MAPS — shown as a count, see `gridDiffRows`. */
3480
+ const GRID_COUNTED = ['axes', 'lines', 'ends'];
3481
+
3482
+ /**
3483
+ * A grid before → after, expanded into ONE LINE PER CHANGED SUB-KEY (P7c-2).
3484
+ *
3485
+ * Without this the row renders `shortVal` of a whole `ModelGrid`, which is a 57-character JSON
3486
+ * truncation — `{"on":true,"origin":[0,0],"x":"0'-0\", 25'-…` — and nobody can consent to that.
3487
+ *
3488
+ * DRIVEN BY THE UNION OF KEYS, not by a list of the ones we know about. A fixed list would silently
3489
+ * show nothing at all for a grid that differs only in a key the list forgot, and the document is
3490
+ * unvalidated by construction — so the list decides only how a value is DISPLAYED, never whether it
3491
+ * appears.
3492
+ *
3493
+ * DETECTED ON THE WHOLE VALUE, DISPLAYED AS A COUNT. Comparing `axes.length` to decide whether to
3494
+ * draw the row would hide every same-count edit — an axis relabelled, a grid line moved — which is
3495
+ * the failure mode this expansion exists to fix, one level further in.
3496
+ */
3497
+ /**
3498
+ * `fieldLine`, plus the one guarantee it cannot make on its own: A ROW NEVER RENDERS BOTH SIDES THE
3499
+ * SAME. If it did, the line would be a positive statement that nothing moved, printed underneath a
3500
+ * checkbox asking the user to consent to a change — worse than omitting the row.
3501
+ *
3502
+ * ONE RULE RATHER THAN A CASE PER SHAPE, because `shortVal` abbreviates in three different ways and
3503
+ * every one of them can collapse a real difference:
3504
+ * • a string over 60 chars is cut at 57 — an 8-bay grid whose LAST bay moved renders identically
3505
+ * on both sides (review measured exactly this; the fixture's 13-character grid never reached it);
3506
+ * • a list over 3 entries becomes `a, b, c +N more` — an edit past the third is invisible;
3507
+ * • an array of objects becomes `…, …, …`, which is why `axes`/`lines`/`ends` show a COUNT, and a
3508
+ * same-count edit then renders `10 → 10`.
3509
+ * Comparing what was actually RENDERED catches all three, and any fourth that `shortVal` grows.
3510
+ */
3511
+ function diffLine(key, before, after, tip) {
3512
+ const row = fieldLine(key, before, after);
3513
+ const chips = row.querySelectorAll('.hd-prof');
3514
+ if (chips.length === 2 && chips[0].textContent === chips[1].textContent) {
3515
+ // Appended to the RENDERED text, not passed back through `shortVal`, which would re-truncate the
3516
+ // marker off the end of exactly the long values that need it.
3517
+ chips[1].textContent += ' (edited)';
3518
+ row.setAttribute('data-tip', tip || 'Both sides abbreviate to the same text — the change is inside the value.');
3519
+ } else if (tip) row.setAttribute('data-tip', tip);
3520
+ return row;
3521
+ }
3522
+
3523
+ function gridDiffRows(b, a) {
3524
+ const rows = [];
3525
+ // CANONICAL, matching what the SERVER compared when it decided to propose at all. A raw stringify
3526
+ // calls a key REORDER a difference, and the server's `valuesDiffer` does not — so a grid staged
3527
+ // because `x` genuinely moved, whose `axes` were merely re-serialised in another key order, drew
3528
+ // an "Axes 10 → 10 (edited)" row claiming an edit that never happened. Wrong in the opposite
3529
+ // direction from the bug the `(edited)` marker exists to fix, and just as misleading on a consent
3530
+ // screen. Object keys sort; ARRAY order is left alone, because `axes[0]` is not `axes[1]`.
3531
+ const canon = (v) => JSON.stringify(v ?? null, (_k, val) => (
3532
+ val && typeof val === 'object' && !Array.isArray(val)
3533
+ ? Object.fromEntries(Object.keys(val).sort().map((k) => [k, val[k]]))
3534
+ : val));
3535
+ const same = (x, y) => canon(x) === canon(y);
3536
+ const count = (v) => (Array.isArray(v) ? v.length : v && typeof v === 'object' ? Object.keys(v).length : 0);
3537
+ for (const k of new Set([...Object.keys(b), ...Object.keys(a)])) {
3538
+ // DETECTED ON THE WHOLE VALUE, always — the count and the abbreviation are display concerns only.
3539
+ if (same(b[k], a[k])) continue;
3540
+ rows.push(GRID_COUNTED.includes(k)
3541
+ ? diffLine(k, count(b[k]), count(a[k]), 'Shown as a count — the individual grid lines are not itemised here.')
3542
+ : diffLine(k, b[k], a[k]));
3543
+ }
3544
+ return rows;
3545
+ }
3546
+
3461
3547
  const KIND_LABEL = {
3462
3548
  'member-added': 'Member added', 'member-removed': 'Member removed', 'member-changed': 'Member changed',
3463
3549
  'plan-added': 'Sheet added', 'plan-changed': 'Sheet changed',
3464
3550
  };
3465
3551
  const KIND_CLASS = {
3466
3552
  'member-added': 'k-added', 'member-removed': 'k-removed', 'member-changed': 'k-changed',
3467
- 'plan-added': 'k-added', 'plan-changed': 'k-changed',
3553
+ 'plan-added': 'k-added', 'plan-changed': 'k-changed', 'model-changed': 'k-changed',
3468
3554
  };
3555
+ /**
3556
+ * ROOT fields a revision read may propose, and how to name one (P7c-2).
3557
+ *
3558
+ * KEYED BY FIELD, not by kind, and there is no `KIND_LABEL['model-changed']` on purpose. Two reasons,
3559
+ * both from the design pass:
3560
+ *
3561
+ * • "Model changed" collides with this very modal's own stale-review banner, which reads "The model
3562
+ * changed while you were reviewing" — a different concept entirely. A MODEL CHANGED badge beside
3563
+ * that sentence is a real misread for someone deciding yes/no quickly.
3564
+ * • A per-kind label would be a lie the moment a SECOND root field becomes proposable, because the
3565
+ * kind cannot tell them apart. Keying on the field is what makes the label stay true, and it is
3566
+ * free here only because a `model-changed` carries its `key` — one proposal per root field.
3567
+ *
3568
+ * "Structural grid" rather than "Grid": this app also has a per-plan `plan.grid` overlay, so a bare
3569
+ * "Grid" leaves a detailer wondering which one. The fallback keeps an unmapped future field readable
3570
+ * instead of reintroducing the empty title this dictionary exists to prevent.
3571
+ */
3572
+ const ROOT_FIELD = { grid: { badge: 'Grid changed', title: 'Structural grid' } };
3573
+ // `Object.hasOwn`, NOT `ROOT_FIELD[key] ||`. A plain object inherits `constructor`, `toString`,
3574
+ // `valueOf` and friends, so the bare lookup returns a truthy inherited value for those keys, the
3575
+ // fallback never fires, and `rf.badge`/`rf.title` come back `undefined` — an EMPTY badge and an empty
3576
+ // title, which is precisely the unnamed `aria-labelledby` target this dictionary exists to prevent.
3577
+ // Latent while `grid` is the only proposable root field, and the same idiom this file already warns
3578
+ // about for `accept['constructor']` in `confirmRevisionReview` — found here by review, in the commit
3579
+ // that introduced it.
3580
+ const rootField = (key) => (Object.hasOwn(ROOT_FIELD, key)
3581
+ ? ROOT_FIELD[key]
3582
+ : { badge: `${prettyKey(key)} changed`, title: prettyKey(key) });
3469
3583
  /** The 2–3 headline fields worth showing for a member — not the whole record. */
3470
3584
  const MEMBER_HEADLINE = ['profile', 'role', 'material'];
3471
3585
  /** Shared by `member-added` and `member-removed`, so the two member rows cannot drift apart. */
@@ -3482,8 +3596,13 @@
3482
3596
  label.appendChild(box);
3483
3597
  const main = revEl('div', 'rev-row-main');
3484
3598
  const head = revEl('div', 'rev-row-head');
3485
- head.appendChild(revEl('span', 'rev-kind-badge', KIND_LABEL[p.kind] || p.kind));
3486
- const title = revEl('span', 'rev-row-title', p.memberId || p.sheet || '');
3599
+ // A `model-changed` has neither a memberId nor a sheet, so the ordinary title expression yields an
3600
+ // EMPTY span — which is also the checkbox's `aria-labelledby` target, i.e. an unnamed checkbox on
3601
+ // the most consequential row in the modal. Named from the field instead, exactly as every other row
3602
+ // is named from its subject.
3603
+ const rf = p.kind === 'model-changed' ? rootField(p.key) : null;
3604
+ head.appendChild(revEl('span', 'rev-kind-badge', rf ? rf.badge : (KIND_LABEL[p.kind] || p.kind)));
3605
+ const title = revEl('span', 'rev-row-title', rf ? rf.title : (p.memberId || p.sheet || ''));
3487
3606
  title.id = `${id}-title`;
3488
3607
  head.appendChild(title);
3489
3608
  main.appendChild(head);
@@ -3500,6 +3619,46 @@
3500
3619
  const fields = revEl('div', 'rev-fields');
3501
3620
  for (const f of p.fields || []) fields.appendChild(fieldLine(f.key, f.before, f.after));
3502
3621
  desc.push(fields);
3622
+ } else if (p.kind === 'model-changed') {
3623
+ const isGrid = p.key === 'grid';
3624
+ const obj = (v) => v && typeof v === 'object' && !Array.isArray(v);
3625
+ // NO DELETION BRANCH, and its absence is the point rather than an omission. An earlier cut of
3626
+ // this renderer had one, for a `model-changed` whose `after` was absent. Staging can no longer
3627
+ // produce that: a root proposal must carry a value, because an AI omitting a key it was told not
3628
+ // to author is not a request to delete it (see the root walk's guard). A branch for a shape the
3629
+ // server cannot emit would read as load-bearing while being dead, which this unit treats as
3630
+ // worse than none.
3631
+ if (isGrid && obj(p.after)) {
3632
+ // AGAINST `{}` WHEN THE MODEL HAS NO GRID YET, which is a real state rather than a defensive
3633
+ // flourish: `grid` is optional and nullable in v2 precisely so a migrated model can exist
3634
+ // before anything builds one. Requiring `before` to be an object too sent that case to the
3635
+ // single-line branch, where `shortVal` truncates the whole arriving grid to ~57 characters —
3636
+ // the unreadable render this expansion exists to prevent, on the one proposal that installs
3637
+ // the entire grid. Every sub-key now shows as an arrival instead.
3638
+ const fields = revEl('div', 'rev-fields');
3639
+ for (const row of gridDiffRows(obj(p.before) ? p.before : {}, p.after)) fields.appendChild(row);
3640
+ desc.push(fields);
3641
+ } else {
3642
+ // An unmapped root field, or a grid arriving where an object was not — the same single line
3643
+ // `plan-changed` would draw. Degrades to less detail, never to nothing.
3644
+ desc.push((() => { const f = revEl('div', 'rev-fields'); f.appendChild(fieldLine(p.key, p.before, p.after)); return f; })());
3645
+ }
3646
+ // UNCONDITIONAL, and deliberately over-stating on the rare cosmetic case (a visibility toggle).
3647
+ // The lines above show only what DIFFERS, while accepting swaps the whole value — so without this
3648
+ // sentence the row quietly implies a partial edit. Over-stating on a toggle is the right failure
3649
+ // direction for a consent screen; under-stating on a geometry move is not.
3650
+ //
3651
+ // Prose, not chrome: no new colour, icon or background. `k-removed` already owns the strongest
3652
+ // token in this modal for deletion, and borrowing it here to mean "important" would blur it —
3653
+ // besides inviting the reflexive no this file warns about. Only the clause that carries the
3654
+ // weight is emphasised, reusing the bare <b> the removal row already uses for its count.
3655
+ if (isGrid) {
3656
+ const note = revEl('div', 'rev-row-note');
3657
+ note.appendChild(document.createTextNode('This is model-wide — '));
3658
+ note.appendChild(revEl('b', null, 'every member and every dimension'));
3659
+ note.appendChild(document.createTextNode(' is positioned against this grid. Accepting replaces the whole grid, not only the lines shown above.'));
3660
+ desc.push(note);
3661
+ }
3503
3662
  } else if (p.kind === 'member-added' && p.member) {
3504
3663
  const sub = memberHeadline(p.member);
3505
3664
  if (sub) desc.push(revEl('div', 'rev-row-sub', sub));
@@ -3837,6 +3996,609 @@
3837
3996
  if (e.key === 'Escape') { e.preventDefault(); if (!$revReviewConfirm.disabled) closeRevReview(); }
3838
3997
  });
3839
3998
 
3999
+ // ── Convert to the model (steel.takeoff/v1 → steel.model/v2, unit 5, P7e) ───────
4000
+ //
4001
+ // Preview what the conversion will do, confirm the judgement calls it had to make, commit. Before
4002
+ // this the only way to migrate a project was to call the API by hand.
4003
+ //
4004
+ // THE CONFIRM IS A SERVER PRECONDITION, not a screen convention. `/migrate` refuses a commit whose
4005
+ // body does not carry `acknowledgeDecisions` — the preview's `report.decisionsDigest` — so this modal
4006
+ // is where a human meets the list, but it is not the only thing standing between an unconfirmed
4007
+ // decision and a written document. See `decisionsDigest` in server/steel-model-migrate.ts for what
4008
+ // that precondition does and, just as importantly, does not prove.
4009
+
4010
+ const $migGate = document.getElementById('ws-migrate-gate');
4011
+ const $migModal = document.getElementById('migrate-modal');
4012
+ const $migSub = document.getElementById('migrate-sub');
4013
+ const $migChanged = document.getElementById('migrate-changed');
4014
+ const $migCounts = document.getElementById('migrate-counts');
4015
+ const $migBody = document.getElementById('migrate-body');
4016
+ const $migProgress = document.getElementById('migrate-progress');
4017
+ const $migConfirm = document.getElementById('migrate-confirm');
4018
+ const $migCancel = document.getElementById('migrate-cancel');
4019
+
4020
+ /**
4021
+ * Which cluster a decision belongs to, for grouping inside the modal.
4022
+ *
4023
+ * DEFAULT-DENY, exactly like `BULKABLE_DECISIONS` below and like the revision registry this app
4024
+ * already runs on: an unmapped code lands in "Other" rather than being folded into the
4025
+ * nearest-sounding topic. A wrong guess at grouping is worse than a visibly ungrouped item, because
4026
+ * a decision filed under the wrong heading is one the reader skims past believing they understood
4027
+ * it. `migrate-decisions.test.ts` asserts every emitted code resolves, so a new one upstream shows
4028
+ * up as a failing test rather than silently landing in the wrong cluster.
4029
+ */
4030
+ const MIGRATE_TOPIC = {
4031
+ 'grid-authority-unconfirmed': 'Grid and registration',
4032
+ 'grid-field-conflict': 'Grid and registration',
4033
+ 'grid-hidden-level-unioned': 'Grid and registration',
4034
+ 'grid-label-duplicate': 'Grid and registration',
4035
+ 'datum-ref-ambiguous': 'Grid and registration',
4036
+ 'datum-ref-unresolved': 'Grid and registration',
4037
+ 'datum-ref-malformed': 'Grid and registration',
4038
+ 'control-ref-malformed': 'Sheet controls',
4039
+ 'control-origin-unanchored': 'Sheet controls',
4040
+ 'control-ref-unresolved': 'Sheet controls',
4041
+ 'control-incomplete': 'Sheet controls',
4042
+ 'control-dropped': 'Sheet controls',
4043
+ 'elevation-default-missing': 'Elevations',
4044
+ 'elevation-in-inferred': 'Elevations',
4045
+ 'dedup-merge-proposed': 'Duplicate members',
4046
+ 'marker-unbound': 'Duplicate members',
4047
+ 'marker-merge-dependent': 'Duplicate members',
4048
+ 'col-metadata-unassigned': 'Member notes',
4049
+ 'drawing-hash-substituted': 'Where the evidence came from',
4050
+ 'observation-locator-provisional': 'Where the evidence came from',
4051
+ 'legacy-provenance-assumed': 'Where the evidence came from',
4052
+ 'field-unmapped': 'Things that will not carry across',
4053
+ 'enum-value-unsupported': 'Things that will not carry across',
4054
+ 'scratch-history-discarded': 'Things that will not carry across',
4055
+ 'view-camera-unframed': 'Saved views',
4056
+ 'view-generated-unresolved': 'Saved views',
4057
+ 'view-generated-regenerated': 'Saved views',
4058
+ };
4059
+ const migTopic = (code) => (Object.hasOwn(MIGRATE_TOPIC, code) ? MIGRATE_TOPIC[code] : 'Other');
4060
+
4061
+ /**
4062
+ * The decisions a bulk "Accept all" may cover — and NOTHING ELSE MAY.
4063
+ *
4064
+ * Two kinds of thing wear the same `decision` severity. An ACKNOWLEDGEMENT records a consequence the
4065
+ * user could not have avoided (undo history cannot cross the format change; a legacy document states
4066
+ * no provenance so one is assumed). A CHOICE names something that could have gone differently (which
4067
+ * sheet's grid became the model's; whether a column's note belongs to an end or the member). Epic §8
4068
+ * allows a bulk accept only over a "frozen, fully enumerated, zero-conflict set" and says any
4069
+ * unresolved field conflict means "the user chooses before commit" — so a control that ticks past a
4070
+ * choice is the thing that rule exists to forbid.
4071
+ *
4072
+ * THE TEST IS SCOPE: is this ONE global statement about the document as a whole, or a finding about a
4073
+ * particular modelled thing? A document-wide statement carries no `sheet` and no `path`, and accepting
4074
+ * the second one is the same act as accepting the first — there is nothing to compare, so a single
4075
+ * confirmation over the enumerated set says exactly what N confirmations would. Anything naming a
4076
+ * sheet, a member, a level or a view is a per-item judgement and stays a choice, because there
4077
+ * accepting one tells you nothing about the next.
4078
+ *
4079
+ * NOT "could an edit to the v1 remove it", which an earlier version of this comment claimed and review
4080
+ * immediately disproved: every code below can be removed by editing the source (add a `source.sha256`,
4081
+ * add a `source.elementId`, set a recognised `source.kind`, clear undo/redo, drop the unmapped field).
4082
+ * By that rule the list would have to be empty — the rule was simply wrong, not the set. Worth writing
4083
+ * down because it was the SECOND overclaim in this spot: the first was "records an unavoidable
4084
+ * consequence", which let `elevation-in-inferred`, `enum-value-unsupported`,
4085
+ * `view-generated-regenerated`, `grid-hidden-level-unioned` and `control-dropped` onto the list. Those
4086
+ * five each name a specific sheet or view, so bulk-ticking them accepted a per-item judgement in one
4087
+ * click — the epic §8 violation this list exists to prevent, one level in from the merge case that
4088
+ * prompted it. They are pinned in `mustNeverBulk` now.
4089
+ *
4090
+ * DEFAULT-DENY. A code not on this list is a choice and gets no bulk control, which means a decision
4091
+ * added by a later unit is per-item until someone deliberately promotes it — the safe direction to
4092
+ * fail. It also disposes of `marker-merge-dependent`, whose grouping should follow the merge it
4093
+ * depends on: the report carries no structured link to that merge, so rather than invent one, an
4094
+ * unlinkable dependent stays a choice, which is where it belongs anyway.
4095
+ *
4096
+ * `dedup-merge-proposed` is absent DELIBERATELY, including for proposals whose `conflicts` are empty.
4097
+ * Deciding bulk-eligibility per instance would be a second axis of logic, and getting it wrong once
4098
+ * reproduces exactly the defect the pre-code review caught here: `dedup-multi-match` being a `block`
4099
+ * rules out ambiguous and transitive candidates, but a pairwise-compatible clique can still disagree
4100
+ * on winner fields and remain tickable.
4101
+ */
4102
+ const BULKABLE_DECISIONS = new Set([
4103
+ 'drawing-hash-substituted', 'observation-locator-provisional', 'legacy-provenance-assumed',
4104
+ 'scratch-history-discarded', 'field-unmapped',
4105
+ ]);
4106
+ const migBulkable = (code) => BULKABLE_DECISIONS.has(code);
4107
+
4108
+ // What the gate banner and the `⋯` item know: the open project is v1 and these are its preconditions.
4109
+ // Null whenever the open project is not convertible, which is what keeps both affordances off.
4110
+ let migReady = null;
4111
+ // The open review: { projectId, etag, head, digest, decisions }.
4112
+ let migState = null;
4113
+
4114
+ /**
4115
+ * Re-read the open project's contract to decide whether the conversion is offered.
4116
+ *
4117
+ * A RAW `fetch`, not `api()` — the confirm needs the `ETag` header and neither `bridge.api` nor the
4118
+ * local fallback exposes headers (see the top of this file). Same idiom the steel editor uses.
4119
+ */
4120
+ async function refreshMigrateGate() {
4121
+ migReady = null;
4122
+ if ($migGate) { $migGate.replaceChildren(); $migGate.hidden = true; }
4123
+ if (!current || currentStep !== 'model') return;
4124
+ const projectId = current.id;
4125
+ const appId = current.app;
4126
+ try {
4127
+ const url = `/api/contract/${encodeURIComponent(appId)}?project=${encodeURIComponent(projectId)}&quietMissing=1`;
4128
+ const res = await fetch(url, { headers: { 'content-type': 'application/json' } });
4129
+ if (!res.ok) return;
4130
+ const etag = res.headers.get('ETag');
4131
+ const doc = await res.json().catch(() => null);
4132
+ // The baked-.flo fallback legitimately serves no ETag, and a conversion cannot be confirmed
4133
+ // against a document we cannot pin — so no tag means no offer, rather than an offer that 428s.
4134
+ if (!etag || !doc || doc.type !== 'steel.takeoff/v1') return;
4135
+ const vr = await api(`/api/projects/${encodeURIComponent(projectId)}/versions`).catch(() => null);
4136
+ // `versions[0].n`, NOT `versions.length`. The ledger is newest-first and `n` is CLAIMED rather
4137
+ // than counted, so the two differ the moment a project's history has a gap — and a count would
4138
+ // then 428 forever with a message about a version history the user cannot see anything wrong in.
4139
+ const head = (Array.isArray(vr && vr.versions) ? vr.versions : [])[0]?.n ?? 0;
4140
+ if (!current || current.id !== projectId || currentStep !== 'model') return; // moved during the fetch
4141
+ migReady = { projectId, appId, etag, head };
4142
+ renderMigrateGate();
4143
+ } catch { /* an offer that cannot be made is simply not made */ }
4144
+ }
4145
+
4146
+ function renderMigrateGate() {
4147
+ if (!$migGate) return;
4148
+ // EMPTIED as well as hidden. `hidden` alone leaves the old text in the DOM, so any future path that
4149
+ // shows this element again — or any CSS regression like the one that made `[hidden]` inert here —
4150
+ // shows a stale offer for a project that may already be converted.
4151
+ if (!migReady || !current || current.id !== migReady.projectId) {
4152
+ $migGate.replaceChildren();
4153
+ $migGate.hidden = true;
4154
+ return;
4155
+ }
4156
+ $migGate.replaceChildren();
4157
+ $migGate.appendChild(document.createTextNode('This project uses the older per-sheet format. '));
4158
+ const go = revEl('button', null, 'Convert to the 3D model →');
4159
+ go.type = 'button';
4160
+ go.setAttribute('data-migrate-open', '1');
4161
+ go.setAttribute('data-tip', 'See exactly what the conversion will do before anything changes');
4162
+ $migGate.appendChild(go);
4163
+ $migGate.hidden = false;
4164
+ }
4165
+
4166
+ /**
4167
+ * The preview, fetched RAW rather than through the shared `api()` helper.
4168
+ *
4169
+ * `api()` treats a body with `ok: false` as a failure and throws. The preview's `ok` IS
4170
+ * `report.ok`, which is false whenever the conversion needs any decision confirmed — the ordinary
4171
+ * case, and the entire reason this modal exists. Routed through `api()` the normal path became an
4172
+ * error toast and the modal never opened.
4173
+ *
4174
+ * Measured in the browser, not reasoned about: the route tests drive `inject()` and read the body
4175
+ * directly, so no server test could have seen this. Only a non-2xx status is an error here, and the
4176
+ * parsed body rides along on it so the caller can still read `code`.
4177
+ */
4178
+ async function migPreview(appId, projectId) {
4179
+ const res = await fetch(
4180
+ `/api/contract/${encodeURIComponent(appId)}/migrate-preview?project=${encodeURIComponent(projectId)}`,
4181
+ { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({}) });
4182
+ const body = await res.json().catch(() => null);
4183
+ if (!res.ok) {
4184
+ const err = new Error((body && body.error) || `HTTP ${res.status}`);
4185
+ err.body = body;
4186
+ throw err;
4187
+ }
4188
+ return body;
4189
+ }
4190
+
4191
+ /** One quiet line of what the conversion produces. Same `bits` idiom as `renderReview` — the zero
4192
+ * clause is omitted rather than printed as "0 of X". */
4193
+ function migCountsLine(report) {
4194
+ const c = (report && report.counts) || {};
4195
+ const bits = [];
4196
+ if (c.canonicalMembers) bits.push([String(c.canonicalMembers), ` model member${c.canonicalMembers > 1 ? 's' : ''}`]);
4197
+ if (c.observations) bits.push([String(c.observations), ` piece${c.observations > 1 ? 's' : ''} of evidence`]);
4198
+ const regs = (report && report.registrations) || [];
4199
+ if (regs.length) bits.push([String(regs.length), ` sheet${regs.length > 1 ? 's' : ''} registered onto the model frame`]);
4200
+ $migCounts.replaceChildren();
4201
+ if (!bits.length) { $migCounts.hidden = true; return; }
4202
+ bits.forEach(([n, rest], i) => {
4203
+ if (i) $migCounts.appendChild(document.createTextNode(' · '));
4204
+ $migCounts.appendChild(revEl('b', null, n));
4205
+ $migCounts.appendChild(document.createTextNode(rest));
4206
+ });
4207
+ $migCounts.appendChild(document.createTextNode(' — what this conversion produces.'));
4208
+ $migCounts.hidden = false;
4209
+ }
4210
+
4211
+ /** A label and a VALUE — not a transition. `fieldLine`'s arrow is wrong for a statement of fact. */
4212
+ function migFact(label, value) {
4213
+ const row = revEl('div', 'rev-field');
4214
+ row.appendChild(revEl('span', 'rev-field-key', prettyKey(label)));
4215
+ row.appendChild(revEl('span', 'hd-prof', value));
4216
+ return row;
4217
+ }
4218
+
4219
+ /** One tickable decision. `idx` indexes the decision list, which is what the progress count walks. */
4220
+ function migDecisionRow(issue, idx, proposal) {
4221
+ const row = revEl('div', 'rev-row k-changed');
4222
+ const id = `mig-dec-${idx}`;
4223
+ const label = revEl('label', 'rev-check');
4224
+ const box = document.createElement('input');
4225
+ box.type = 'checkbox';
4226
+ box.dataset.migidx = String(idx);
4227
+ box.dataset.migcode = issue.code;
4228
+ if (migBulkable(issue.code)) box.dataset.migbulk = '1';
4229
+ box.setAttribute('aria-labelledby', `${id}-title`);
4230
+ box.setAttribute('aria-describedby', `${id}-msg`);
4231
+ label.appendChild(box);
4232
+
4233
+ const main = revEl('div', 'rev-row-main');
4234
+ const head = revEl('div', 'rev-row-head');
4235
+ head.appendChild(revEl('span', 'rev-kind-badge', migBulkable(issue.code) ? 'Acknowledge' : 'Decide'));
4236
+ const title = revEl('span', 'rev-row-title', issue.sheet || issue.path || migTopic(issue.code));
4237
+ title.id = `${id}-title`;
4238
+ head.appendChild(title);
4239
+ main.appendChild(head);
4240
+
4241
+ const msg = revEl('div', 'rev-row-note', issue.message || issue.code);
4242
+ msg.id = `${id}-msg`;
4243
+ main.appendChild(msg);
4244
+
4245
+ // EVERY MEMBER NAMED, never a count. Epic §8 requires a merge to show its exact survivor and the
4246
+ // exact members retired into it; "3 members" is precisely the summary it forbids.
4247
+ if (proposal) {
4248
+ const fields = revEl('div', 'rev-fields');
4249
+ fields.appendChild(migFact('keeps', `${proposal.survivor.sheet}/${proposal.survivor.id}`));
4250
+ for (const m of proposal.members) {
4251
+ if (m.sheet === proposal.survivor.sheet && m.id === proposal.survivor.id) continue;
4252
+ fields.appendChild(migFact('retires',
4253
+ `${m.sheet}/${m.id}${m.swappedToSurvivor ? ' · reversed to match the survivor' : ''}`));
4254
+ }
4255
+ // `diffLine` HERE AND NOWHERE ELSE in this block, because here a before → after genuinely applies:
4256
+ // two members disagree and the merge keeps one value. The `keeps`/`retires` lines above are
4257
+ // statements of fact, not transitions — an earlier cut drew them with `fieldLine` and an empty
4258
+ // second value, which renders `Keeps S-201/C3 →`: an arrow pointing at nothing, on the one
4259
+ // screen where the user is consenting to members being retired. Found by review; unreachable in
4260
+ // the demo fixture, which produces no merge proposals at all, so the browser pass never drew it.
4261
+ for (const c of proposal.conflicts || []) {
4262
+ fields.appendChild(diffLine(c, 'the two disagree', 'the survivor’s value is kept',
4263
+ 'The members being merged do not agree on this field, and merging keeps the survivor’s.'));
4264
+ }
4265
+ main.appendChild(fields);
4266
+ }
4267
+
4268
+ row.appendChild(label);
4269
+ row.appendChild(main);
4270
+ return row;
4271
+ }
4272
+
4273
+ /** The refusal surfaces: a conversion that cannot happen, and a preview that cannot be committed. */
4274
+ function migRefusal(title, lead, lines) {
4275
+ const wrap = document.createDocumentFragment();
4276
+ wrap.appendChild(revEl('div', 'hd-empty', lead));
4277
+ if (lines.length) {
4278
+ const g = group(title, lines.length, null);
4279
+ for (const t of lines) g.appendChild(revEl('div', 'rev-issue', t));
4280
+ wrap.appendChild(g);
4281
+ }
4282
+ return wrap;
4283
+ }
4284
+
4285
+ function renderMigrate(payload) {
4286
+ const report = (payload && payload.report) || {};
4287
+ const issues = Array.isArray(report.issues) ? report.issues : [];
4288
+ const blocks = issues.filter((i) => i.severity === 'block');
4289
+ const decisions = issues.filter((i) => i.severity === 'decision');
4290
+ const notes = issues.filter((i) => i.severity === 'report');
4291
+ migCountsLine(report);
4292
+ const body = document.createDocumentFragment();
4293
+
4294
+ // 1. CANNOT CONVERT. No Confirm rendered at all — a block is not something you can tick past, and
4295
+ // an inert primary button reads as an invitation to find the way around it.
4296
+ if (!payload.candidate) {
4297
+ $migCounts.hidden = true;
4298
+ body.appendChild(migRefusal('What is in the way', blocks.length
4299
+ ? 'This project cannot be converted yet. Each of these has to be resolved in the drawings or the model first:'
4300
+ : 'This project cannot be converted yet.', blocks.map((b) => `${b.sheet ? `${b.sheet} — ` : ''}${b.message || b.code}`)));
4301
+ $migBody.replaceChildren(body);
4302
+ return { committable: false, decisions: [] };
4303
+ }
4304
+
4305
+ // 2. A DRAFT PREVIEW. The server strips the digest when it previewed posted bytes rather than the
4306
+ // stored document, because a draft-derived digest is one the commit can never accept. Unreachable
4307
+ // from this modal — it always previews the store — so this is a GUARD, kept because the
4308
+ // alternative is a renderer whose correctness depends on every future caller remembering to omit
4309
+ // one body key.
4310
+ if (payload.previewOf !== 'stored' || !report.decisionsDigest) {
4311
+ body.appendChild(migRefusal('', 'This preview was taken against unsaved changes rather than the '
4312
+ + 'stored model, so it cannot be converted from here. Save the model, then preview again.', []));
4313
+ $migBody.replaceChildren(body);
4314
+ return { committable: false, decisions: [] };
4315
+ }
4316
+
4317
+ // 3. THE ORDINARY PATH. Choices first, acknowledgements second: the section needing real judgement
4318
+ // leads, and the one that is a click each sits last, right above Confirm.
4319
+ const proposals = Array.isArray(report.mergeProposals) ? report.mergeProposals : [];
4320
+ const merges = decisions.filter((d) => d.code === 'dedup-merge-proposed');
4321
+ // BY CONSTRUCTION, not by assumption: `proposeMerges` pushes a proposal and its issue in the same
4322
+ // loop iteration, so the Nth issue is the Nth proposal. Length-checked anyway — if they ever fall
4323
+ // out of step the rows lose their detail rather than attributing one merge's members to another.
4324
+ const aligned = merges.length === proposals.length;
4325
+ const proposalFor = (issue) => (aligned && issue.code === 'dedup-merge-proposed'
4326
+ ? proposals[merges.indexOf(issue)] : null);
4327
+
4328
+ const byTopic = (list) => {
4329
+ const m = new Map();
4330
+ for (const d of list) {
4331
+ const t = migTopic(d.code);
4332
+ if (!m.has(t)) m.set(t, []);
4333
+ m.get(t).push(d);
4334
+ }
4335
+ return m;
4336
+ };
4337
+ const idxOf = new Map(decisions.map((d, i) => [d, i]));
4338
+ const choices = decisions.filter((d) => !migBulkable(d.code));
4339
+ const acks = decisions.filter((d) => migBulkable(d.code));
4340
+
4341
+ if (!decisions.length) {
4342
+ body.appendChild(revEl('div', 'hd-empty',
4343
+ 'This conversion needs no decisions from you — nothing had to be assumed or chosen.'));
4344
+ }
4345
+ // THE KIND IS THE OUTER AXIS and topic the inner one, so a topic can legitimately appear under both
4346
+ // — "Saved views" has one decision of each kind in the demo model. Without a heading naming the kind,
4347
+ // the reader sees the same title twice, one with a bulk control and one without, and no way to tell
4348
+ // why. Measured in the browser: the first cut of this shipped exactly that.
4349
+ const section = (text, sub) => {
4350
+ const h = revEl('div', 'mig-section');
4351
+ h.appendChild(revEl('span', 'mig-section-title', text));
4352
+ h.appendChild(revEl('span', 'mig-section-sub', sub));
4353
+ return h;
4354
+ };
4355
+ if (choices.length) {
4356
+ body.appendChild(section('Needs your decision',
4357
+ 'each of these could have gone another way — take them one at a time'));
4358
+ for (const [topic, list] of byTopic(choices)) {
4359
+ // `null` bucket → `group` renders no bulk bar. The absence IS the rule, not an oversight.
4360
+ const g = group(topic, list.length, null);
4361
+ for (const d of list) g.appendChild(migDecisionRow(d, idxOf.get(d), proposalFor(d)));
4362
+ body.appendChild(g);
4363
+ }
4364
+ }
4365
+ if (acks.length) {
4366
+ body.appendChild(section('To acknowledge',
4367
+ 'consequences of the change itself — nothing here could have gone another way'));
4368
+ for (const [topic, list] of byTopic(acks)) {
4369
+ const g = group(topic, list.length, `mig-${topic.replace(/\W+/g, '-')}`);
4370
+ for (const d of list) g.appendChild(migDecisionRow(d, idxOf.get(d), null));
4371
+ body.appendChild(g);
4372
+ }
4373
+ }
4374
+ if (notes.length) {
4375
+ const det = document.createElement('details');
4376
+ det.className = 'ws-archived rev-issues';
4377
+ if (!decisions.length) det.open = true;
4378
+ const sum = document.createElement('summary');
4379
+ sum.className = 'ws-archived-summary';
4380
+ sum.appendChild(revEl('span', 'ws-archived-caret', '›'));
4381
+ sum.appendChild(document.createTextNode('For your information '));
4382
+ sum.appendChild(revEl('span', 'ws-archived-count', String(notes.length)));
4383
+ det.appendChild(sum);
4384
+ for (const n of notes) {
4385
+ const r = revEl('div', 'rev-issue', n.message || n.code || '');
4386
+ r.appendChild(revEl('span', 'rev-issue-path', n.sheet || n.path || ''));
4387
+ det.appendChild(r);
4388
+ }
4389
+ body.appendChild(det);
4390
+ }
4391
+ $migBody.replaceChildren(body);
4392
+ return { committable: true, decisions };
4393
+ }
4394
+
4395
+ /**
4396
+ * The tick progress and the Confirm gate.
4397
+ *
4398
+ * `aria-disabled` rather than the `disabled` attribute, matching `.kb-organize` and `.ecard .e-act`:
4399
+ * a disabled button is unhoverable and unfocusable, so the `data-tip` explaining WHY would never
4400
+ * reach the person who needs it. The click handler checks the same flag.
4401
+ */
4402
+ function syncMigrateProgress() {
4403
+ if (!migState) return;
4404
+ const boxes = [...$migBody.querySelectorAll('input[type="checkbox"][data-migidx]')];
4405
+ const done = boxes.filter((b) => b.checked).length;
4406
+ const left = boxes.length - done;
4407
+ if (!boxes.length) { $migProgress.hidden = true; }
4408
+ else {
4409
+ $migProgress.replaceChildren();
4410
+ $migProgress.appendChild(revEl('b', null, String(done)));
4411
+ $migProgress.appendChild(document.createTextNode(` of ${boxes.length} confirmed`));
4412
+ if (left) $migProgress.appendChild(document.createTextNode(` — ${left} still to go.`));
4413
+ $migProgress.hidden = false;
4414
+ }
4415
+ const ready = left === 0;
4416
+ $migConfirm.setAttribute('aria-disabled', String(!ready));
4417
+ $migConfirm.setAttribute('data-tip', ready
4418
+ ? 'Convert this project — a new version is recorded'
4419
+ : `Confirm all ${boxes.length} before converting — ${left} left`);
4420
+ }
4421
+
4422
+ function closeMigrate() {
4423
+ $migModal.classList.remove('show');
4424
+ const st = migState;
4425
+ migState = null;
4426
+ $migChanged.hidden = true;
4427
+ $migConfirm.disabled = false;
4428
+ const back = st && st.returnFocus;
4429
+ if (back instanceof HTMLElement && back.isConnected) back.focus();
4430
+ }
4431
+
4432
+ async function openMigrate() {
4433
+ if (!current || !migReady || migReady.projectId !== current.id) return;
4434
+ const { projectId, appId, etag, head } = migReady;
4435
+ const returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
4436
+ let payload;
4437
+ try {
4438
+ payload = await migPreview(appId, projectId);
4439
+ } catch (err) {
4440
+ showToast('Could not preview the conversion: ' + ((err && err.message) || err), 'warn');
4441
+ return;
4442
+ }
4443
+ if (!current || current.id !== projectId) return; // switched projects during the fetch
4444
+ // RENDER BEFORE ADOPTING THE STATE, the ordering the revision modal was fixed to use: a throw
4445
+ // inside the renderer must not leave the state latched with no modal on screen.
4446
+ $migSub.textContent = 'Nothing changes until you confirm. This records a new version and cannot be undone.';
4447
+ $migChanged.hidden = true;
4448
+ const { committable } = renderMigrate(payload);
4449
+ $migConfirm.hidden = !committable;
4450
+ migState = { projectId, appId, etag, head, digest: payload.report && payload.report.decisionsDigest, returnFocus };
4451
+ if (committable) syncMigrateProgress(); else $migProgress.hidden = true;
4452
+ $migModal.classList.add('show');
4453
+ // The first thing still to do — which, with choices rendered first, is the harder work.
4454
+ const first = $migBody.querySelector('input[type="checkbox"]:not(:checked)');
4455
+ (first || $migCancel).focus();
4456
+ }
4457
+
4458
+ /** Re-preview in place after a stale precondition, clearing every tick. Mirrors the revision modal's
4459
+ * 409 branch, including its render-first-then-adopt ordering. */
4460
+ async function migRestage(why) {
4461
+ // CAPTURED, not re-read after the await. Cancel stays live while this is in flight (it is not part
4462
+ // of the busy chrome), so a user who cancels mid-restage sets `migState` to null — and building the
4463
+ // next state from the global afterwards would spread `null`, render into a closed modal, and leave a
4464
+ // half-formed `migState` behind it. The identity check below is what makes cancelling actually
4465
+ // cancel. Found by review.
4466
+ const st = migState;
4467
+ if (!st) return;
4468
+ const { projectId, appId } = st;
4469
+ let fresh, next;
4470
+ try {
4471
+ const res = await fetch(`/api/contract/${encodeURIComponent(appId)}?project=${encodeURIComponent(projectId)}`,
4472
+ { headers: { 'content-type': 'application/json' } });
4473
+ const etag = res.headers.get('ETag');
4474
+ const vr = await api(`/api/projects/${encodeURIComponent(projectId)}/versions`).catch(() => null);
4475
+ const head = (Array.isArray(vr && vr.versions) ? vr.versions : [])[0]?.n ?? 0;
4476
+ fresh = await migPreview(appId, projectId);
4477
+ if (!etag) throw new Error('the model no longer reports a version tag');
4478
+ next = { ...st, etag, head, digest: fresh.report && fresh.report.decisionsDigest };
4479
+ } catch (err) {
4480
+ if (migState !== st) return; // cancelled while we were asking; say nothing, close nothing
4481
+ showToast('Could not re-check the conversion: ' + ((err && err.message) || err), 'warn');
4482
+ closeMigrate();
4483
+ return;
4484
+ }
4485
+ // The review may have been cancelled or replaced while the three fetches were in flight. Rendering
4486
+ // now would paint into a modal the user has already dismissed.
4487
+ if (migState !== st) return;
4488
+ // RENDER BEFORE ADOPTING THE STATE — and an earlier cut of this function adopted first, which is
4489
+ // the very bug `openMigrate` carries a comment about and the revision modal was fixed for. It is
4490
+ // worse here than there: `renderMigrate` throwing after the swap would leave the OLD rows on screen,
4491
+ // still ticked, above a Confirm now carrying the NEW digest. That posts a decision set the user
4492
+ // never saw and earns a 200 for it. Rendering first means a throw leaves the stale-but-consistent
4493
+ // pair, and the caller's `finally` still restores the button.
4494
+ const { committable } = renderMigrate(fresh); // replaceChildren builds new, unticked inputs
4495
+ // ALL THREE ADOPTED TOGETHER. Taking a new digest against an old ETag would confirm a mixture of two
4496
+ // moments, which is the exact failure the preconditions exist to prevent.
4497
+ migState = next;
4498
+ $migConfirm.hidden = !committable;
4499
+ if (committable) syncMigrateProgress(); else $migProgress.hidden = true;
4500
+ $migChanged.replaceChildren();
4501
+ $migChanged.appendChild(revEl('b', null, why));
4502
+ $migChanged.appendChild(document.createTextNode(' This is the current preview, and your ticks were'
4503
+ + ' cleared — the same decision can mean something different against a model that moved.'));
4504
+ $migChanged.hidden = false;
4505
+ }
4506
+
4507
+ async function confirmMigrate() {
4508
+ const st = migState;
4509
+ if (!st) return;
4510
+ if ($migConfirm.getAttribute('aria-disabled') === 'true') return; // the gate, not just the styling
4511
+ $migConfirm.disabled = true;
4512
+ $migConfirm.setAttribute('aria-busy', 'true');
4513
+ const label = $migConfirm.textContent;
4514
+ $migConfirm.textContent = 'Converting…';
4515
+ try {
4516
+ let res;
4517
+ try {
4518
+ res = await api(`/api/contract/${encodeURIComponent(st.appId)}/migrate?project=${encodeURIComponent(st.projectId)}`, {
4519
+ method: 'POST',
4520
+ headers: { 'content-type': 'application/json', 'If-Match': st.etag },
4521
+ body: JSON.stringify({ expectLedgerHead: st.head, acknowledgeDecisions: st.digest }),
4522
+ });
4523
+ } catch (err) {
4524
+ const code = err && err.body && err.body.code;
4525
+ // THREE OUTCOMES, and the difference is whether re-previewing would tell the user anything.
4526
+ //
4527
+ // A moved document or ledger, or a mismatched digest: what they looked at is not what would be
4528
+ // written, but a fresh preview IS meaningful. Re-preview in place rather than closing, which
4529
+ // would lose their place. `contract-not-migratable` joins them — a re-preview renders the blocks
4530
+ // that now stand in the way, which is exactly what they need to see.
4531
+ if (code === 'precondition-failed' || code === 'precondition-required'
4532
+ || code === 'contract-not-migratable') {
4533
+ await migRestage('The project changed while you were reviewing.');
4534
+ return;
4535
+ }
4536
+ // ALREADY CONVERTED, OR GONE. Re-previewing would say nothing useful — there is no v1 left to
4537
+ // preview — so the modal CLOSES rather than sitting there re-clickable against a store that can
4538
+ // never accept it. Found by review: `runMigration` checks the contract TYPE before the ETag, so
4539
+ // another tab converting this same project earns `contract-type-unsupported`, not a precondition
4540
+ // failure, and the branch above would have left this modal open and repeat-clickable forever.
4541
+ // THE FULL SET, enumerated rather than sampled, because a code that falls through to the toast
4542
+ // below leaves the modal open and repeat-clickable. The commit route can return exactly:
4543
+ // `project-required` (unreachable — this caller always sends ?project), `unknown-project`,
4544
+ // `precondition-required`, `precondition-failed`, `contract-absent`,
4545
+ // `contract-type-unsupported`, `contract-not-migratable` and `contract-recovery-pending`.
4546
+ // The first branch takes the three worth re-previewing; these four are terminal.
4547
+ const TERMINAL = {
4548
+ 'contract-type-unsupported': 'This project has already been converted — it is on the 3D model now',
4549
+ 'contract-absent': 'That project no longer holds a contract to convert',
4550
+ 'unknown-project': 'That project no longer exists',
4551
+ 'contract-recovery-pending': 'This project has an unfinished conversion to recover first — reopen it and try again',
4552
+ };
4553
+ if (Object.hasOwn(TERMINAL, code)) {
4554
+ showToast(TERMINAL[code], 'warn');
4555
+ closeMigrate();
4556
+ refreshMigrateGate(); // the offer is gone, or was never valid; stop showing it
4557
+ return;
4558
+ }
4559
+ showToast('Could not convert: ' + ((err && err.message) || err), 'warn');
4560
+ return; // NOT closed — the review is still valid and their ticks are still worth something
4561
+ }
4562
+ // The store is v2 now. `clearApproval` ran inside the transaction, but this shell holds
4563
+ // `approvedAt` in memory and only refreshes it through the exports/history paths — so without
4564
+ // this line a stale "approved" badge survives a conversion that invalidated the sign-off.
4565
+ if (current && current.id === st.projectId) {
4566
+ current.approvedAt = undefined;
4567
+ if (!$wsHistory.hidden) renderHistory();
4568
+ if (!$wsExports.hidden) renderExports();
4569
+ syncWorkspaceGuide();
4570
+ }
4571
+ showToast(`Converted to the 3D model — version ${res.versionN} is on History`, 'ok');
4572
+ closeMigrate();
4573
+ refreshMigrateGate(); // the offer is gone: the project is no longer v1
4574
+ } finally {
4575
+ $migConfirm.disabled = false;
4576
+ $migConfirm.removeAttribute('aria-busy');
4577
+ $migConfirm.textContent = label;
4578
+ }
4579
+ }
4580
+
4581
+ $migBody.addEventListener('change', (e) => {
4582
+ if (e.target && e.target.matches('input[type="checkbox"][data-migidx]')) syncMigrateProgress();
4583
+ });
4584
+ $migBody.addEventListener('click', (e) => {
4585
+ const bulk = e.target.closest('[data-revbulk]');
4586
+ if (!bulk) return;
4587
+ const on = bulk.dataset.revbulkon === '1';
4588
+ // Scoped to the CLICKED GROUP, and additionally to rows the code list marks bulkable — belt and
4589
+ // braces, because a bulk bar can only appear on an acknowledgement group in the first place.
4590
+ const g = bulk.closest('.rev-group');
4591
+ for (const box of (g || $migBody).querySelectorAll('input[data-migbulk="1"]')) box.checked = on;
4592
+ syncMigrateProgress();
4593
+ });
4594
+ $migGate.addEventListener('click', (e) => { if (e.target.closest('[data-migrate-open]')) openMigrate(); });
4595
+ $migConfirm.addEventListener('click', confirmMigrate);
4596
+ $migCancel.addEventListener('click', closeMigrate);
4597
+ onBackdropDismiss($migModal, closeMigrate, () => !$migConfirm.disabled);
4598
+ $migModal.addEventListener('keydown', (e) => {
4599
+ if (e.key === 'Escape') { e.preventDefault(); if (!$migConfirm.disabled) closeMigrate(); }
4600
+ });
4601
+
3840
4602
  // ── History step ────────────────────────────────────────────────────────────────
3841
4603
  // The project's version ledger. A version = a commit (Approve = Model gate, Rollback = unsigned).
3842
4604
  // The draft contract is the working tree; an unapproved draft shows the working-copy banner.
@@ -4287,6 +5049,18 @@
4287
5049
  $projMenu.innerHTML = menuItem('rename', 'Rename…') + menuItem('duplicate', 'Duplicate') +
4288
5050
  menuItem('export', 'Export…') +
4289
5051
  '<div class="menu-divider"></div>' + menuItem('archive', 'Archive');
5052
+ // NO "Convert to the 3D model…" ITEM HERE, and its absence is a decision rather than an oversight.
5053
+ // A conversion is a lifecycle act, so this menu beside Rename/Duplicate/Archive is where it belongs
5054
+ // — and an earlier cut of this unit put it here. It was DEAD CODE, by construction: `openProjMenu`
5055
+ // is wired only to the LANDING-GRID kebab (the `$landing` click handler), `applyMode` hides the
5056
+ // landing whenever a project is open, and `migReady` is only ever set while a project IS open on its
5057
+ // Model step. The two conditions are mutually exclusive, so the branch could never render — except
5058
+ // in the one state where `migReady` leaked past `closeProject`, where it rendered an item that did
5059
+ // nothing at all. Found by review.
5060
+ //
5061
+ // Putting it back means surfacing it from the open-project chrome (the header picker), where
5062
+ // `migReady` can actually be true. Until then the Model-step banner carries discovery, and shipping
5063
+ // a branch with a comment describing behaviour that never happens is worse than shipping neither.
4290
5064
  const r = anchor.getBoundingClientRect();
4291
5065
  $projMenu.style.left = Math.round(Math.max(8, Math.min(r.left, window.innerWidth - 260))) + 'px';
4292
5066
  $projMenu.style.top = Math.round(r.bottom + 6) + 'px';