@floless/app 0.120.2 → 0.121.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.
@@ -38,6 +38,15 @@
38
38
  const $wsHistory = document.getElementById('ws-history');
39
39
  const $wsKnowledge = document.getElementById('ws-knowledge');
40
40
  const $wsKnowledgeFile = document.getElementById('ws-knowledge-file');
41
+ const $approveBtn = document.getElementById('ws-approve');
42
+ const $approvalModal = document.getElementById('approval-review-modal');
43
+ const $approvalDialog = $approvalModal && $approvalModal.querySelector('.approval-review');
44
+ const $approvalSub = document.getElementById('approval-review-sub');
45
+ const $approvalImpact = document.getElementById('approval-review-impact');
46
+ const $approvalBody = document.getElementById('approval-review-body');
47
+ const $approvalCounts = document.getElementById('approval-review-counts');
48
+ const $approvalCancel = document.getElementById('approval-review-cancel');
49
+ const $approvalConfirm = document.getElementById('approval-review-confirm');
41
50
  const frames = {
42
51
  model: document.getElementById('ws-frame-model'),
43
52
  drawings: document.getElementById('ws-frame-drawings'),
@@ -414,6 +423,13 @@
414
423
  let wsAppEntries = wsDefaultAppEntries();
415
424
  let current = null; // the open project (null = landing)
416
425
 
426
+ // One server-derived answer owns every approval-facing surface. Unknown/error states fail closed;
427
+ // approvedAt remains compatibility metadata only and is never used to invent pending/clean state.
428
+ let approvalState = { status: 'unavailable', review: null, pendingCount: 0, headVersion: null, error: '' };
429
+ let approvalStateGen = 0;
430
+ let approvalDialogState = null; // { projectId, review, decisions, returnFocus, stale }
431
+ let exportSourcesState = { status: 'unavailable', data: null, selected: null, open: false };
432
+
417
433
  /**
418
434
  * Does the open project hold a model, as far as the Exports pane knows? (#490)
419
435
  *
@@ -440,8 +456,70 @@
440
456
  /** The header's AUTHORED tooltip, captured from the static markup so the has-a-model state restores
441
457
  * it verbatim. The first cut substituted "exports unlock after it", which is a FALSE description of
442
458
  * an already-approved project — its exports are unlocked and its gate is gone. */
443
- const APPROVE_TIP = document.getElementById('ws-approve')?.getAttribute('data-tip')
444
- || 'Locks in this version — your edits already auto-save; this is the sign-off.';
459
+ const APPROVE_TIP = $approveBtn?.getAttribute('data-tip')
460
+ || 'Review every pending change before signing off.';
461
+
462
+ function renderApprovalHeader() {
463
+ if (!$approveBtn) return;
464
+ const s = approvalState;
465
+ let label = 'Review & approve';
466
+ let tip = APPROVE_TIP;
467
+ let unavailable = false;
468
+ if (!exportsHasModel) {
469
+ label = 'Review unavailable';
470
+ tip = `Nothing to approve yet — read a drawing on ${stepLabel('drawings')} first`;
471
+ unavailable = true;
472
+ } else if (s.status === 'loading') {
473
+ label = 'Checking changes…';
474
+ tip = 'Checking the working copy against the latest approved version.';
475
+ unavailable = true;
476
+ } else if (s.status === 'error' || s.status === 'unavailable') {
477
+ label = 'Review unavailable';
478
+ tip = s.error || 'Approval status is unavailable — try again.';
479
+ unavailable = true;
480
+ } else if (s.pendingCount > 0) {
481
+ label = s.headVersion ? `Review changes · ${s.pendingCount}` : 'Review & approve';
482
+ } else if (s.headVersion) {
483
+ label = `Approved · v${s.headVersion}`;
484
+ tip = 'The working copy matches the latest approved version.';
485
+ unavailable = true;
486
+ }
487
+ $approveBtn.textContent = label;
488
+ $approveBtn.setAttribute('aria-disabled', String(unavailable));
489
+ $approveBtn.setAttribute('data-tip', tip);
490
+ $approveBtn.classList.toggle('approval-clean', s.status === 'ready' && !!s.headVersion && s.pendingCount === 0);
491
+ }
492
+
493
+ function approvalHeadVersion(review) {
494
+ return review && review.moveForward && Number.isInteger(Number(review.moveForward.toVersion))
495
+ ? Number(review.moveForward.toVersion)
496
+ : review && review.base && Number.isInteger(Number(review.base.version)) ? Number(review.base.version) : null;
497
+ }
498
+
499
+ async function refreshApprovalState(projectId = current && current.id) {
500
+ if (!projectId || !current || current.id !== projectId) return null;
501
+ const gen = ++approvalStateGen;
502
+ approvalState = { status: 'loading', review: null, pendingCount: 0, headVersion: null, error: '' };
503
+ renderApprovalHeader();
504
+ try {
505
+ const review = await api(`/api/projects/${encodeURIComponent(projectId)}/approval-review`);
506
+ if (gen !== approvalStateGen || !current || current.id !== projectId) return null;
507
+ const groups = Array.isArray(review.groups) ? review.groups : [];
508
+ const headVersion = approvalHeadVersion(review);
509
+ approvalState = { status: 'ready', review, pendingCount: groups.length, headVersion, error: '' };
510
+ renderApprovalHeader();
511
+ syncWorkspaceGuide();
512
+ if (!$wsExports.hidden) paintExports(current.approvedAt);
513
+ return review;
514
+ } catch (error) {
515
+ if (gen !== approvalStateGen || !current || current.id !== projectId) return null;
516
+ approvalState = { status: 'error', review: null, pendingCount: 0, headVersion: null,
517
+ error: (error && error.message) || 'Approval status is unavailable — try again.' };
518
+ renderApprovalHeader();
519
+ if (!$wsExports.hidden) paintExports(current.approvedAt);
520
+ return null;
521
+ }
522
+ }
445
523
 
446
524
  // The open app's visible label for a step key (Model→"Model" for steel, "Traced" for vectorize) —
447
525
  // so shared chrome (banners, prompts) names the app's OWN step, never hard-coded steel vocabulary.
@@ -463,7 +541,8 @@
463
541
  // `exported` = an SVG export file exists (from the last export listing); best-known from
464
542
  // exportState, which renderExports() populates. Unknown before Exports is opened → false.
465
543
  const exported = !!(exportState && exportState.svg && exportState.svg.exportedAt);
466
- bridge.setWorkspaceGuide({ app: current.app, name: current.name, displayName: projectAppName(current), approved: !!current.approvedAt, exported });
544
+ bridge.setWorkspaceGuide({ app: current.app, name: current.name, displayName: projectAppName(current),
545
+ approved: approvalState.status === 'ready' && !!approvalState.headVersion && approvalState.pendingCount === 0, exported });
467
546
  }
468
547
 
469
548
  // ── mode ────────────────────────────────────────────────────────────────────
@@ -1270,6 +1349,7 @@
1270
1349
  refreshModelPresence(p.id, p.app).catch((e) => { // gate the header CHECK Approve for THIS project (#490)
1271
1350
  console.error('[workspaces] could not resolve model presence', e);
1272
1351
  });
1352
+ refreshApprovalState(p.id).catch((e) => console.error('[workspaces] could not load approval state', e));
1273
1353
  }
1274
1354
 
1275
1355
  /**
@@ -1293,15 +1373,14 @@
1293
1373
  /** Push the answer to the flag AND the header together, so no two surfaces can disagree. */
1294
1374
  function applyModelPresence(present) {
1295
1375
  exportsHasModel = present;
1296
- const btn = document.getElementById('ws-approve');
1297
- if (!btn) return;
1298
- btn.setAttribute('aria-disabled', String(!present));
1299
- btn.setAttribute('data-tip', present
1300
- ? APPROVE_TIP
1301
- : `Nothing to approve yet — read a drawing on ${stepLabel('drawings')} first`);
1376
+ renderApprovalHeader();
1302
1377
  }
1303
1378
  function closeProject() {
1304
1379
  current = null;
1380
+ approvalStateGen++;
1381
+ approvalState = { status: 'unavailable', review: null, pendingCount: 0, headVersion: null, error: '' };
1382
+ exportSourcesState = { status: 'unavailable', data: null, selected: null, open: false };
1383
+ closeApprovalReview();
1305
1384
  exportState = null;
1306
1385
  hostReadinessStates = {};
1307
1386
  renderReadinessState = null;
@@ -1392,7 +1471,7 @@
1392
1471
  // Shared by the header ✓ Approve and the Exports-tab gate link ("Approve this version"), so the
1393
1472
  // sign-off is one flow. On success it stamps current.approvedAt (server returns it) so the
1394
1473
  // Exports gate unlocks without a reload.
1395
- async function approveProject() {
1474
+ async function legacyApproveProject() {
1396
1475
  if (!current) return;
1397
1476
  // The flag, not the attribute — `aria-disabled` is advisory and the button stays clickable BY
1398
1477
  // DESIGN (that is what keeps its data-tip reachable), so this is the check that actually holds.
@@ -1430,7 +1509,10 @@
1430
1509
  // fires. flushContract() PUTs the live contract and resolves; a save failure aborts the bake.
1431
1510
  const win = frames.model && frames.model.contentWindow;
1432
1511
  if (win && typeof win.flushContract === 'function') await win.flushContract();
1433
- const res = await api(`/api/contract/${encodeURIComponent(approvingProject.app)}/approve?project=${encodeURIComponent(approvingProject.id)}`, { method: 'POST' });
1512
+ throw new Error('Legacy one-click approval is disabled; use Review and approve.');
1513
+ // Kept only so this retired branch remains parseable while its surrounding historical comments
1514
+ // are removed in a later cleanup; execution cannot cross the throw above.
1515
+ const res = null;
1434
1516
  if (res && res.approvedAt) approvingProject.approvedAt = res.approvedAt; // unlock exports
1435
1517
  const stillOpen = current && current.id === approvingProject.id;
1436
1518
  if (stillOpen && !$wsHistory.hidden && res && res.version && Number.isInteger(Number(res.version.n))) {
@@ -1452,7 +1534,200 @@
1452
1534
  showToast('Approve failed: ' + (err && err.message || err), 'warn');
1453
1535
  } finally { btn.disabled = false; btn.textContent = prev; }
1454
1536
  }
1455
- document.getElementById('ws-approve').addEventListener('click', approveProject);
1537
+ const approvalDecisionLabel = (decision) => decision === 'approve' ? 'Approve this change' : 'Leave pending';
1538
+
1539
+ function renderApprovalReview() {
1540
+ if (!approvalDialogState) return;
1541
+ const review = approvalDialogState.review;
1542
+ const groups = Array.isArray(review.groups) ? review.groups : [];
1543
+ const decisions = approvalDialogState.decisions;
1544
+ const conflicts = review.moveForward && Array.isArray(review.moveForward.conflicts) ? review.moveForward.conflicts : [];
1545
+ const conflictDecisions = approvalDialogState.conflicts || {};
1546
+ $approvalSub.textContent = review.moveForward
1547
+ ? `Your changes from v${review.moveForward.fromVersion} will be applied on top of approved v${review.moveForward.toVersion}`
1548
+ : review.base ? `Compared with approved v${review.base.version}` : 'First approval · full-model baseline';
1549
+ $approvalImpact.textContent = [review.summary, ...(Array.isArray(review.cautions) ? review.cautions : [])].filter(Boolean).join(' ');
1550
+ const groupHtml = groups.map((group) => {
1551
+ const picked = decisions[group.id];
1552
+ const facts = Array.isArray(group.technicalFacts) && group.technicalFacts.length
1553
+ ? `<details class="approval-tech"><summary>Technical details</summary>${group.technicalFacts.map((fact) => `<div><b>${escapeHtml(String(fact.label || 'Detail'))}</b> <span>${escapeHtml(String(JSON.stringify(fact.before) ?? '—'))} → ${escapeHtml(String(JSON.stringify(fact.after) ?? '—'))}</span></div>`).join('')}</details>` : '';
1554
+ const discard = review.selective ? `<button type="button" class="approval-discard" data-approval-discard="${escapeAttr(group.id)}">Discard change…</button>` : '';
1555
+ return `<section class="approval-group" data-approval-group="${escapeAttr(group.id)}"><div class="approval-group-head"><div>`
1556
+ + `<span class="approval-risk ${escapeAttr(String(group.risk || 'low'))}">${escapeHtml(String(group.risk || 'low'))}</span><b>${escapeHtml(String(group.headline || group.category || 'Change'))}</b></div>`
1557
+ + `<span>${escapeHtml(String(group.location || ''))}</span></div><p>${escapeHtml(String(group.detail || ''))}</p>`
1558
+ + `<div class="approval-decisions" role="radiogroup" aria-label="Decision for ${escapeAttr(String(group.headline || 'change'))}">`
1559
+ + ['approve', 'leave-pending'].map((decision) => `<button type="button" role="radio" aria-checked="${String(picked === decision)}" class="${picked === decision ? 'selected' : ''}" data-approval-decision="${decision}" data-group-id="${escapeAttr(group.id)}">${approvalDecisionLabel(decision)}</button>`).join('')
1560
+ + `</div>${facts}${discard}</section>`;
1561
+ }).join('');
1562
+ const requiredConflictDecision = (conflict) => {
1563
+ const linked = (conflict.groupIds || []).map((id) => decisions[id]);
1564
+ if (linked.length && linked.every((value) => value === 'approve')) return 'use-draft';
1565
+ if (!linked.length || linked.every((value) => value === 'leave-pending')) return 'keep-latest-pending';
1566
+ return null;
1567
+ };
1568
+ const conflictHtml = conflicts.map((conflict) => {
1569
+ const picked = conflictDecisions[conflict.id];
1570
+ const required = requiredConflictDecision(conflict);
1571
+ return `<section class="approval-group approval-conflict" data-approval-conflict-card="${escapeAttr(conflict.id)}"><div class="approval-group-head"><div><span class="approval-risk high">overlap</span><b>${escapeHtml(conflict.headline)}</b></div><span>${escapeHtml(conflict.path)}</span></div><p>${escapeHtml(conflict.detail)}</p>`
1572
+ + `<div class="approval-decisions" role="radiogroup" aria-label="Overlap decision for ${escapeAttr(conflict.path)}">`
1573
+ + `<button type="button" role="radio" aria-checked="${String(picked === 'use-draft')}" class="${picked === 'use-draft' ? 'selected' : ''}" data-approval-conflict="use-draft" data-conflict-id="${escapeAttr(conflict.id)}"${required !== 'use-draft' ? ' disabled' : ''}>Use my DRAFT value</button>`
1574
+ + `<button type="button" role="radio" aria-checked="${String(picked === 'keep-latest-pending')}" class="${picked === 'keep-latest-pending' ? 'selected' : ''}" data-approval-conflict="keep-latest-pending" data-conflict-id="${escapeAttr(conflict.id)}"${required !== 'keep-latest-pending' ? ' disabled' : ''}>Keep v${escapeHtml(String(review.moveForward.toVersion))} · save mine as pending</button></div></section>`;
1575
+ }).join('');
1576
+ $approvalBody.innerHTML = groupHtml + conflictHtml || '<div class="approval-empty">No pending changes. The working copy already matches the latest approved version.</div>';
1577
+ const values = Object.values(decisions);
1578
+ const approved = values.filter((value) => value === 'approve').length;
1579
+ const remaining = groups.length - values.length;
1580
+ const remainingConflicts = conflicts.filter((conflict) => conflictDecisions[conflict.id] !== requiredConflictDecision(conflict)).length;
1581
+ $approvalCounts.textContent = remaining > 0 ? `${values.length} of ${groups.length} changes decided · ${remaining} still need review`
1582
+ : remainingConflicts > 0 ? `${remainingConflicts} overlap${remainingConflicts === 1 ? '' : 's'} still need a decision`
1583
+ : approved ? `${approved} change${approved === 1 ? '' : 's'} will be approved · ${groups.length - approved} left pending`
1584
+ : groups.length ? 'All changes will remain pending' : 'Nothing needs approval';
1585
+ $approvalConfirm.textContent = approved ? `Approve ${approved} change${approved === 1 ? '' : 's'}` : 'Approve selected changes';
1586
+ $approvalConfirm.disabled = remaining !== 0 || remainingConflicts !== 0 || approved === 0 || groups.length === 0 || approvalDialogState.stale;
1587
+ }
1588
+
1589
+ function closeApprovalReview() {
1590
+ if (!$approvalModal) return;
1591
+ const st = approvalDialogState;
1592
+ approvalDialogState = null;
1593
+ $approvalModal.classList.remove('show');
1594
+ $approvalModal.removeAttribute('aria-busy');
1595
+ if (st && st.returnFocus && st.returnFocus.isConnected) st.returnFocus.focus();
1596
+ }
1597
+
1598
+ async function approveProject() {
1599
+ if (!current || !$approvalModal || !$approvalDialog) return;
1600
+ if (!exportsHasModel) {
1601
+ showToast(`There’s no model to approve yet — read a drawing on ${stepLabel('drawings')} first.`, 'warn');
1602
+ return;
1603
+ }
1604
+ const project = current;
1605
+ $approvalModal.classList.add('show');
1606
+ $approvalModal.setAttribute('aria-busy', 'true');
1607
+ $approvalSub.textContent = 'Loading the server comparison…';
1608
+ $approvalImpact.textContent = '';
1609
+ $approvalBody.innerHTML = '<div class="approval-loading"><span class="rtn-spinner" aria-hidden="true"></span> Comparing changes…</div>';
1610
+ $approvalCounts.textContent = '';
1611
+ $approvalConfirm.disabled = true;
1612
+ approvalDialogState = { projectId: project.id, review: { groups: [] }, decisions: {}, conflicts: {}, returnFocus: document.activeElement, stale: false };
1613
+ $approvalDialog.focus();
1614
+ try {
1615
+ const win = frames.model && frames.model.contentWindow;
1616
+ // History is server-owned after partial approval and may hide an editor whose in-memory draft
1617
+ // predates that partition. Other tabs can be reached immediately after an edit, before the
1618
+ // debounce saves, so they must still flush even though the iframe is hidden.
1619
+ if (currentStep !== 'history' && win && typeof win.flushContract === 'function') await win.flushContract();
1620
+ const review = await api(`/api/projects/${encodeURIComponent(project.id)}/approval-review`);
1621
+ if (!current || current.id !== project.id || !approvalDialogState) return;
1622
+ approvalDialogState.review = review;
1623
+ approvalState = { status: 'ready', review, pendingCount: Array.isArray(review.groups) ? review.groups.length : 0,
1624
+ headVersion: approvalHeadVersion(review), error: '' };
1625
+ renderApprovalHeader();
1626
+ renderApprovalReview();
1627
+ } catch (error) {
1628
+ if (!approvalDialogState) return;
1629
+ approvalDialogState.stale = true;
1630
+ $approvalSub.textContent = 'Approval status unavailable';
1631
+ $approvalImpact.textContent = (error && error.message) || 'Could not load the comparison.';
1632
+ $approvalBody.innerHTML = '<div class="approval-empty">Close this review and try again. Nothing was approved.</div>';
1633
+ } finally { $approvalModal.removeAttribute('aria-busy'); }
1634
+ }
1635
+
1636
+ async function confirmApprovalReview() {
1637
+ const st = approvalDialogState;
1638
+ if (!st || $approvalConfirm.disabled || !current || current.id !== st.projectId) return;
1639
+ const project = current;
1640
+ $approvalModal.setAttribute('aria-busy', 'true');
1641
+ $approvalConfirm.disabled = true;
1642
+ try {
1643
+ const res = await api(`/api/contract/${encodeURIComponent(project.app)}/approve?project=${encodeURIComponent(project.id)}`, {
1644
+ method: 'POST', body: JSON.stringify({ mode: st.review.mode || 'head', reviewId: st.review.reviewId, decisions: st.decisions, conflicts: st.conflicts, claimedChannel: 'browser' }),
1645
+ });
1646
+ if (res && res.approvedAt) project.approvedAt = res.approvedAt;
1647
+ const n = res && res.version && Number(res.version.n);
1648
+ if (Number.isInteger(n)) expandDiffOnce = { projectId: project.id, n };
1649
+ reloadModelFromServerTruth();
1650
+ closeApprovalReview();
1651
+ await refreshApprovalState(project.id);
1652
+ const pending = Number.isInteger(Number(res && res.pendingCount)) ? Number(res.pendingCount) : approvalState.pendingCount;
1653
+ const saved = res && res.savedWorkCheckpoint;
1654
+ showToast(`Approved${Number.isInteger(n) ? ` as v${n}` : ''}. ${pending ? `${pending} change${pending === 1 ? '' : 's'} remain pending${saved ? ' in Saved work' : ''}; approved exports omit them unless you explicitly choose DRAFT.` : 'No changes remain pending.'}`, 'ok');
1655
+ track('workspace_project_approved', { app: project.app });
1656
+ if (bridge.markWorkspaceApproved && wsDescOf(project)?.docGuide) bridge.markWorkspaceApproved(project.app);
1657
+ if (!$wsExports.hidden) renderExports();
1658
+ if (!$wsHistory.hidden) await renderHistory();
1659
+ } catch (error) {
1660
+ if (approvalDialogState && error && error.body && error.body.code === 'approval-review-stale') {
1661
+ approvalDialogState.stale = true;
1662
+ $approvalImpact.textContent = 'The working copy changed. Your decisions were not applied. Close and reopen to reload the comparison.';
1663
+ renderApprovalReview();
1664
+ } else showToast('Approve failed: ' + ((error && error.message) || error), 'warn');
1665
+ } finally { if (approvalDialogState) $approvalModal.removeAttribute('aria-busy'); }
1666
+ }
1667
+
1668
+ async function discardApprovalChange(groupId) {
1669
+ const st = approvalDialogState;
1670
+ if (!st || !st.review.selective || !bridge.formModal) return;
1671
+ const group = (st.review.groups || []).find((candidate) => candidate.id === groupId);
1672
+ if (!group) return;
1673
+ const accepted = await bridge.formModal({ title: `Discard “${group.headline || 'this change'}”?`, sub: `${group.detail || 'This change'} will return to the approved value. This edits the working copy; it does not approve anything.`, fields: [], okLabel: 'Discard change', danger: true });
1674
+ if (!accepted || !approvalDialogState) return;
1675
+ try {
1676
+ const res = await api(`/api/projects/${encodeURIComponent(st.projectId)}/approval-review/discard`, {
1677
+ method: 'POST', body: JSON.stringify({ reviewId: st.review.reviewId, changes: [groupId], claimedChannel: 'browser' }),
1678
+ });
1679
+ st.review = res.review;
1680
+ st.decisions = {};
1681
+ st.conflicts = {};
1682
+ reloadModelFromServerTruth();
1683
+ renderApprovalReview();
1684
+ await refreshApprovalState(st.projectId);
1685
+ showToast('Discarded the selected working-copy change. Nothing was approved.', 'ok');
1686
+ } catch (error) { showToast('Discard failed: ' + ((error && error.message) || error), 'warn'); }
1687
+ }
1688
+
1689
+ $approvalBody?.addEventListener('click', (event) => {
1690
+ const decision = event.target.closest('[data-approval-decision]');
1691
+ if (decision && approvalDialogState) {
1692
+ const group = (approvalDialogState.review.groups || []).find((candidate) => candidate.id === decision.dataset.groupId);
1693
+ if (!group) return;
1694
+ for (const linked of approvalDialogState.review.groups || []) {
1695
+ if (linked.dependencyGroup === group.dependencyGroup) approvalDialogState.decisions[linked.id] = decision.dataset.approvalDecision;
1696
+ }
1697
+ for (const conflict of (approvalDialogState.review.moveForward && approvalDialogState.review.moveForward.conflicts) || []) {
1698
+ if ((conflict.groupIds || []).some((id) => id === group.id)) delete approvalDialogState.conflicts[conflict.id];
1699
+ }
1700
+ renderApprovalReview();
1701
+ return;
1702
+ }
1703
+ const conflict = event.target.closest('[data-approval-conflict]');
1704
+ if (conflict && approvalDialogState) {
1705
+ approvalDialogState.conflicts[conflict.dataset.conflictId] = conflict.dataset.approvalConflict;
1706
+ renderApprovalReview();
1707
+ return;
1708
+ }
1709
+ const discard = event.target.closest('[data-approval-discard]');
1710
+ if (discard) discardApprovalChange(discard.dataset.approvalDiscard);
1711
+ });
1712
+ $approvalCancel?.addEventListener('click', closeApprovalReview);
1713
+ $approvalConfirm?.addEventListener('click', confirmApprovalReview);
1714
+ $approvalModal?.addEventListener('mousedown', (event) => { if (event.target === $approvalModal) closeApprovalReview(); });
1715
+ $approvalModal?.addEventListener('keydown', (event) => {
1716
+ if (event.key === 'Escape') { event.preventDefault(); closeApprovalReview(); return; }
1717
+ if (event.key !== 'Tab') return;
1718
+ const focusable = Array.from($approvalModal.querySelectorAll('button:not([disabled]), summary, [tabindex="0"]')).filter((node) => !node.hidden);
1719
+ if (!focusable.length) return;
1720
+ const first = focusable[0], last = focusable[focusable.length - 1];
1721
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
1722
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
1723
+ });
1724
+ $approveBtn?.addEventListener('click', () => {
1725
+ if ($approveBtn.getAttribute('aria-disabled') === 'true') {
1726
+ if (approvalState.status === 'error' || approvalState.status === 'unavailable') refreshApprovalState();
1727
+ return;
1728
+ }
1729
+ approveProject();
1730
+ });
1456
1731
 
1457
1732
  // ── Find in model bridge (app.js Ctrl+F delegates here in Workspaces mode) ──────
1458
1733
  // Active only when a project is open on the Model step, the editor iframe is loaded and exposes
@@ -2647,8 +2922,8 @@
2647
2922
  * keyboard user can still switch projects while it is open — which would POST the render at a
2648
2923
  * DIFFERENT project than the one whose id keys `exportBusy` and the receipts.
2649
2924
  */
2650
- function exportUrl(kind, projectId, appId) {
2651
- const qs = `?project=${encodeURIComponent(projectId)}`;
2925
+ function exportUrl(kind, projectId, appId, sourceHandle) {
2926
+ const qs = `?project=${encodeURIComponent(projectId)}${sourceHandle ? `&sourceHandle=${encodeURIComponent(sourceHandle)}` : ''}`;
2652
2927
  const base = `/api/contract/${encodeURIComponent(appId)}`;
2653
2928
  // The BATCH route: one request, one project lock, every picked format. Three separate requests
2654
2929
  // would release the lock between formats — long enough for a render to take it and leave this
@@ -3056,8 +3331,8 @@
3056
3331
  }
3057
3332
 
3058
3333
  // ── The destination chooser ───────────────────────────────────────────────────────────────────
3059
- const hostSendUrl = (host, projectId, appId) => {
3060
- const qs = `?project=${encodeURIComponent(projectId)}`;
3334
+ const hostSendUrl = (host, projectId, appId, sourceHandle) => {
3335
+ const qs = `?project=${encodeURIComponent(projectId)}&sourceHandle=${encodeURIComponent(sourceHandle)}`;
3061
3336
  const base = `/api/contract/${encodeURIComponent(appId)}`;
3062
3337
  // Tekla keeps its original route (its readiness probe can tell "open but no model loaded",
3063
3338
  // which the generic one cannot); the other three share the newer one.
@@ -3191,7 +3466,7 @@
3191
3466
  * be minutes old by the time a third host's turn comes round, and an application closed since
3192
3467
  * then must be reported rather than sent into.
3193
3468
  */
3194
- async function sendToHosts(hosts, projectId, app, approvedAt) {
3469
+ async function sendToHosts(hosts, projectId, app, approvedAt, sourceHandles, sourceKind) {
3195
3470
  const busyKey = `${projectId}:send-host`;
3196
3471
  if (exportBusy.has(busyKey)) return;
3197
3472
  exportBusy.add(busyKey);
@@ -3229,8 +3504,8 @@
3229
3504
  // bridge, and that is the longest gap in this loop.
3230
3505
  if (approvalMoved()) { aborted.push(...hosts.slice(i)); break; }
3231
3506
  try {
3232
- const res = await api(hostSendUrl(host, projectId, app), { method: 'POST' });
3233
- track('workspace_export', { app, kind: `send:${host}` });
3507
+ const res = await api(hostSendUrl(host, projectId, app, sourceHandles[i]), { method: 'POST' });
3508
+ track('workspace_export', { app, kind: `send:${host}`, sourceKind });
3234
3509
  let summary = null;
3235
3510
  if (res.counts) {
3236
3511
  exportReceipts.set(`${projectId}:send:${host}`, {
@@ -3249,6 +3524,10 @@
3249
3524
  }
3250
3525
  }
3251
3526
  } finally {
3527
+ await Promise.allSettled(sourceHandles.map((handleId) => api(
3528
+ `/api/projects/${encodeURIComponent(projectId)}/export-captures/${encodeURIComponent(handleId)}/release`,
3529
+ { method: 'POST' },
3530
+ )));
3252
3531
  sendProgress = null;
3253
3532
  exportBusy.delete(busyKey);
3254
3533
  }
@@ -3263,6 +3542,7 @@
3263
3542
  const clean = done.filter((d) => !d.partial);
3264
3543
  const partial = done.filter((d) => d.partial);
3265
3544
  if (done.length || failed.length || aborted.length) {
3545
+ if (done.length) exportSourcesState.selected = null;
3266
3546
  const sentence = [
3267
3547
  clean.length ? `Sent to ${sequenceText(clean.map((d) => d.host))}.` : '',
3268
3548
  ...partial.map((d) => `${hostLabel(d.host)} took it with gaps — ${d.text}.`),
@@ -3310,7 +3590,10 @@
3310
3590
  hostChoices.set(projectId, picked);
3311
3591
  // The user may have switched projects while the dialog was open — the send must not land on
3312
3592
  // whatever is open NOW. Everything below is keyed to the captured project.
3313
- return sendToHosts(picked, projectId, app, approvedAt);
3593
+ let sources;
3594
+ try { sources = await captureSelectedExportSources(projectId, picked.length); }
3595
+ catch (error) { showToast((error && error.message) || 'Couldn’t freeze the export source.', 'warn'); return; }
3596
+ return sendToHosts(picked, projectId, app, approvedAt, sources.map((source) => source.handleId), sources[0].kind);
3314
3597
  }
3315
3598
 
3316
3599
  // Links created this session, per project: `${projectId}:share-3d` -> { url, approvedAt }. Held in
@@ -3913,6 +4196,58 @@
3913
4196
  card?.querySelector('.e-recovery:not([disabled]), [data-export]:not([disabled])')?.focus();
3914
4197
  }
3915
4198
 
4199
+ function exportSourceOptions(data) {
4200
+ if (!data) return [];
4201
+ const out = [];
4202
+ if (data.default) out.push({ selector: { kind: 'latest-approved' }, label: `Latest approved · v${data.default.version}`, group: 'Recommended' });
4203
+ if (data.working) out.push({
4204
+ selector: {
4205
+ kind: 'working', expectedEtag: data.working.etag,
4206
+ ...(data.working.epoch !== null && Number.isInteger(Number(data.working.epoch)) ? { expectedEpoch: Number(data.working.epoch) } : {}),
4207
+ },
4208
+ label: 'Working copy · DRAFT', group: 'Drafts',
4209
+ });
4210
+ for (const saved of data.checkpoints || []) out.push({ selector: { kind: 'checkpoint', checkpointId: saved.checkpointId, expectedHash: saved.hash }, label: `Checkpoint ${String(saved.checkpointId).slice(0, 8)} · DRAFT`, group: 'Drafts', sub: saved.baseVersion ? `Pending work from v${saved.baseVersion}` : 'No approved baseline' });
4211
+ for (const row of data.approved || []) {
4212
+ if (!data.default || Number(row.version) !== Number(data.default.version)) out.push({ selector: { kind: 'approved', version: row.version }, label: `Older approved · v${row.version}`, group: 'Approved history' });
4213
+ }
4214
+ return out;
4215
+ }
4216
+
4217
+ function currentExportSourceOption() {
4218
+ const options = exportSourceOptions(exportSourcesState.data);
4219
+ if (exportSourcesState.selected) {
4220
+ const key = JSON.stringify(exportSourcesState.selected);
4221
+ const found = options.find((option) => JSON.stringify(option.selector) === key);
4222
+ if (found) return found;
4223
+ }
4224
+ return options.find((option) => option.selector.kind === 'latest-approved') || null;
4225
+ }
4226
+
4227
+ function exportSourceHtml() {
4228
+ if (exportSourcesState.status === 'loading') return '<div class="export-source-status" role="status">Loading export sources…</div>';
4229
+ if (exportSourcesState.status !== 'ready') return '<div class="export-source-status unavailable" role="status">Export sources unavailable — retry by reopening Exports.</div>';
4230
+ const options = exportSourceOptions(exportSourcesState.data);
4231
+ const selected = currentExportSourceOption();
4232
+ const selectedKey = selected ? JSON.stringify(selected.selector) : '';
4233
+ const grouped = ['Recommended', 'Drafts', 'Approved history'].map((group) => {
4234
+ const rows = options.filter((option) => option.group === group);
4235
+ if (!rows.length) return '';
4236
+ return `<div class="export-source-group" role="group" aria-label="${escapeAttr(group)}"><div class="export-source-group-label">${escapeHtml(group)}</div>`
4237
+ + rows.map((option) => { const key = JSON.stringify(option.selector); return `<button type="button" class="export-source-option${key === selectedKey ? ' selected' : ''}" role="option" aria-selected="${String(key === selectedKey)}" data-export-source="${escapeAttr(key)}"><span>${escapeHtml(option.label)}</span>${option.sub ? `<small>${escapeHtml(option.sub)}</small>` : ''}</button>`; }).join('') + '</div>';
4238
+ }).join('');
4239
+ let warning = '';
4240
+ if (selected && selected.selector.kind === 'latest-approved') {
4241
+ warning = approvalState.pendingCount ? `<div class="export-source-banner"><b>${approvalState.pendingCount} pending change${approvalState.pendingCount === 1 ? '' : 's'} aren’t included.</b> Exports use approved v${approvalState.headVersion}. <button type="button" data-review-changes>Review changes</button></div>` : '';
4242
+ } else if (selected && (selected.selector.kind === 'working' || selected.selector.kind === 'checkpoint')) {
4243
+ warning = '<div class="export-source-banner draft"><b>DRAFT · Unapproved changes will be included.</b> This source is frozen when export starts.</div>';
4244
+ } else if (selected && selected.selector.kind === 'approved') {
4245
+ warning = `<div class="export-source-banner historical"><b>Older approved v${escapeHtml(String(selected.selector.version))}</b> · current approved is v${escapeHtml(String(approvalState.headVersion || '—'))}.</div>`;
4246
+ }
4247
+ const raw = selected ? '<button type="button" class="export-source-raw" data-export-raw>Export raw package</button>' : '';
4248
+ return `<div class="export-source"><label id="export-source-label">Export source</label><div class="export-source-combo"><button type="button" class="wf-trigger export-source-trigger" aria-haspopup="listbox" aria-expanded="${String(exportSourcesState.open)}" aria-labelledby="export-source-label export-source-value"><span id="export-source-value">${escapeHtml(selected ? selected.label : 'Choose export source')}</span><span class="wf-caret" aria-hidden="true">▾</span></button><div class="wf-popover export-source-popover" role="listbox" aria-label="Export source"${exportSourcesState.open ? '' : ' hidden'}>${grouped}</div></div>${raw}${warning}</div>`;
4249
+ }
4250
+
3916
4251
  function paintExports(approvedAt, requestedRestoreKind) {
3917
4252
  const hasModel = exportsHasModel;
3918
4253
  // An explicit kind says "put them back on the button they pressed" — but only if they are still
@@ -3924,8 +4259,11 @@
3924
4259
  const restoreIdentity = requestedRestoreKind && stillHere
3925
4260
  ? { attr: 'data-export', value: requestedRestoreKind, cardKind: requestedRestoreKind }
3926
4261
  : exportFocusIdentity(document.activeElement);
3927
- const approved = !!approvedAt;
3928
- let html = '';
4262
+ // Cards are enabled by an explicit source, not by the mutable working-copy sign-off flag. Latest
4263
+ // approved is selected by default when present; a no-baseline project stays closed until the
4264
+ // person deliberately chooses its DRAFT working copy/checkpoint.
4265
+ const approved = exportSourcesState.status === 'ready' && !!currentExportSourceOption();
4266
+ let html = exportSourceHtml();
3929
4267
  if (!approved) {
3930
4268
  // Same split as History's empty state (#490): with a model, Approve is genuinely the unlocking
3931
4269
  // action; with none, `POST …/approve` 404s, so pointing at it is a dead end and the real next
@@ -3948,7 +4286,7 @@
3948
4286
  // caption. The note's job — per the comment above — is to justify the exports-FOLDER button
3949
4287
  // staying enabled, not to claim the export actions work unapproved. "Polishing is optional" was
3950
4288
  // the true and useful half, and it survives; only the opening clause overreached.
3951
- html += `<div class="exports-note"><b>Any approved version can be exported</b> — polishing further ` +
4289
+ html += `<div class="exports-note"><b>Any saved source can be exported</b> — approved is the safe default, while DRAFT and older versions stay explicit. Polishing further ` +
3952
4290
  `is optional. Each writes to this project’s <button type="button" class="exports-note-link" data-open-exports-folder ` +
3953
4291
  `aria-label="Open the exports folder" data-tip="Open this project’s exports folder">▤ exports</button> folder.</div>`;
3954
4292
  const cards = (wsApp() && wsApp().exports) || [];
@@ -4078,6 +4416,7 @@
4078
4416
  // inside the pane this fix is for, reachable by opening an empty project and clicking Exports
4079
4417
  // while the open-time probe is still in flight.
4080
4418
  const paintedWith = exportsHasModel;
4419
+ exportSourcesState.status = 'loading';
4081
4420
  paintExports(current.approvedAt, restoreKind);
4082
4421
  const gen = ++modelPresenceGen;
4083
4422
  const modelPresent = await projectHasContract(id, app);
@@ -4087,11 +4426,19 @@
4087
4426
  let state = null;
4088
4427
  let approvedAt = current.approvedAt; // fallback if the fetch fails (best-known)
4089
4428
  const exportPromise = api(`/api/contract/${encodeURIComponent(app)}/exports?project=${encodeURIComponent(id)}`);
4429
+ const sourcePromise = api(`/api/projects/${encodeURIComponent(id)}/export-sources`);
4090
4430
  const readinessPromise = hasHosts ? refreshHostReadiness() : Promise.resolve(null);
4091
4431
  const renderReadyPromise = hasRender ? api('/api/render/readiness') : Promise.resolve(null);
4092
- const [exportResult, readinessResult, renderReadyResult] = await Promise.allSettled([
4093
- exportPromise, readinessPromise, renderReadyPromise,
4432
+ const [exportResult, readinessResult, renderReadyResult, sourceResult] = await Promise.allSettled([
4433
+ exportPromise, readinessPromise, renderReadyPromise, sourcePromise,
4094
4434
  ]);
4435
+ if (sourceResult.status === 'fulfilled') {
4436
+ exportSourcesState.status = 'ready';
4437
+ exportSourcesState.data = sourceResult.value;
4438
+ if (!currentExportSourceOption()) exportSourcesState.selected = null;
4439
+ } else {
4440
+ exportSourcesState = { status: 'unavailable', data: null, selected: null, open: false };
4441
+ }
4095
4442
  if (hasRender) {
4096
4443
  // A readiness probe that fails is reported as unknown-with-a-retry, never as ready — the
4097
4444
  // same honesty the export listing keeps ("Status unavailable", never a fake "not exported").
@@ -4145,6 +4492,45 @@
4145
4492
  paintExports(approvedAt, restoreKind);
4146
4493
  }
4147
4494
 
4495
+ async function captureSelectedExportSources(projectId, copies = 1) {
4496
+ const option = currentExportSourceOption();
4497
+ if (!option) throw new Error('Choose an export source first.');
4498
+ let selector = option.selector;
4499
+ if (option.selector.kind === 'working') {
4500
+ const win = frames.model && frames.model.contentWindow;
4501
+ if (win && typeof win.flushContract === 'function') await win.flushContract();
4502
+ const fresh = await api(`/api/projects/${encodeURIComponent(projectId)}/export-sources`);
4503
+ if (!fresh || !fresh.working || typeof fresh.working.etag !== 'string') throw new Error('Working revision identity is unavailable.');
4504
+ selector = { kind: 'working', expectedEtag: fresh.working.etag };
4505
+ if (fresh.working.epoch !== null && fresh.working.epoch !== undefined) selector.expectedEpoch = Number(fresh.working.epoch);
4506
+ }
4507
+ const captured = await api(`/api/projects/${encodeURIComponent(projectId)}/export-captures`, {
4508
+ method: 'POST', body: JSON.stringify({ selector, copies }),
4509
+ });
4510
+ if (!captured || !captured.source || !captured.source.handleId) throw new Error('The export source could not be frozen.');
4511
+ return Array.isArray(captured.sources) && captured.sources.length === copies ? captured.sources : [captured.source];
4512
+ }
4513
+
4514
+ async function captureSelectedExportSource(projectId) {
4515
+ return (await captureSelectedExportSources(projectId, 1))[0];
4516
+ }
4517
+
4518
+ async function exportRawSelectedSource() {
4519
+ if (!current) return;
4520
+ const projectId = current.id;
4521
+ try {
4522
+ const source = await captureSelectedExportSource(projectId);
4523
+ const result = await api(`/api/projects/${encodeURIComponent(projectId)}/export-raw`, {
4524
+ method: 'POST', body: JSON.stringify({ sourceHandle: source.handleId }),
4525
+ });
4526
+ exportSourcesState.selected = null;
4527
+ showToast(`Exported raw package — ${result.filename}`, 'ok');
4528
+ if (current && current.id === projectId) await renderExports();
4529
+ } catch (error) {
4530
+ showToast('Raw export failed: ' + ((error && error.message) || error), 'warn');
4531
+ }
4532
+ }
4533
+
4148
4534
  async function doExport(kind) {
4149
4535
  if (!current) return;
4150
4536
  // Sending to a CAD application is its own flow end to end: it asks WHERE first, then performs
@@ -4187,6 +4573,9 @@
4187
4573
  }, 1000);
4188
4574
  }
4189
4575
 
4576
+ let capturedSource;
4577
+ try { capturedSource = await captureSelectedExportSource(projectId); }
4578
+ catch (error) { showToast((error && error.message) || 'Couldn’t freeze the export source.', 'warn'); return; }
4190
4579
  exportBusy.add(busyKey);
4191
4580
  // The delegated click can report BODY as active by the time this synchronous repaint runs.
4192
4581
  // Carry the activated kind through the first replacement explicitly; later repaints infer
@@ -4199,7 +4588,7 @@
4199
4588
  try {
4200
4589
  // `for=share` tells the server this document is about to be PUBLISHED, so it can refuse on an
4201
4590
  // AWARE too old to render the display modes this card offers. The local 3D view sends no flag.
4202
- const rendered = await api(`/api/contract/${encodeURIComponent(app)}/export-3d?project=${encodeURIComponent(projectId)}&for=share`, { method: 'POST' });
4591
+ const rendered = await api(`/api/contract/${encodeURIComponent(app)}/export-3d?project=${encodeURIComponent(projectId)}&for=share&sourceHandle=${encodeURIComponent(capturedSource.handleId)}`, { method: 'POST' });
4203
4592
  if (!rendered.ok || !rendered.report || !rendered.report.html) {
4204
4593
  throw new Error(rendered.error || 'the 3D render produced no document');
4205
4594
  }
@@ -4255,7 +4644,7 @@
4255
4644
  try {
4256
4645
  // Render and the BOM are the exports whose POST carries a body — the options their modal collected.
4257
4646
  const body = renderOptions || bomOptions;
4258
- const res = await api(exportUrl(kind, projectId, app), body
4647
+ const res = await api(exportUrl(kind, projectId, app, capturedSource.handleId), body
4259
4648
  ? { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }
4260
4649
  : { method: 'POST' });
4261
4650
  if (kind === 'bom') {
@@ -4285,7 +4674,8 @@
4285
4674
  if (current && current.id === projectId) paintExports(current.approvedAt);
4286
4675
  });
4287
4676
  }
4288
- track('workspace_export', { app, kind }); // a successful export/bake (e.g. { app:'vectorize', kind:'svg' })
4677
+ exportSourcesState.selected = null; // non-default sources are one-shot; a later export returns to latest approved
4678
+ track('workspace_export', { app, kind, sourceKind: capturedSource.kind }); // a successful export/bake
4289
4679
  if (res.counts) exportReceipts.set(`${projectId}:${kind}`, {
4290
4680
  counts: res.counts,
4291
4681
  warnings: res.warnings || [],
@@ -4507,6 +4897,23 @@
4507
4897
  }
4508
4898
 
4509
4899
  $wsExports.addEventListener('click', (e) => {
4900
+ const sourceTrigger = e.target.closest('.export-source-trigger');
4901
+ if (sourceTrigger && exportSourcesState.status === 'ready') {
4902
+ exportSourcesState.open = !exportSourcesState.open;
4903
+ paintExports(current && current.approvedAt);
4904
+ if (exportSourcesState.open) $wsExports.querySelector('.export-source-option.selected, .export-source-option')?.focus();
4905
+ return;
4906
+ }
4907
+ const sourceOption = e.target.closest('[data-export-source]');
4908
+ if (sourceOption) {
4909
+ try { exportSourcesState.selected = JSON.parse(sourceOption.dataset.exportSource); } catch { return; }
4910
+ exportSourcesState.open = false;
4911
+ paintExports(current && current.approvedAt);
4912
+ $wsExports.querySelector('.export-source-trigger')?.focus();
4913
+ return;
4914
+ }
4915
+ if (e.target.closest('[data-review-changes]')) { approveProject(); return; }
4916
+ if (e.target.closest('[data-export-raw]')) { exportRawSelectedSource(); return; }
4510
4917
  if (e.target.closest('#ws-exports-approve')) { approveProject(); return; }
4511
4918
  // The no-model gate's real next step — mirrors History's #hist-go-drawings.
4512
4919
  if (e.target.closest('#ws-exports-go-drawings')) { setStep('drawings'); return; }
@@ -4559,6 +4966,18 @@
4559
4966
  return;
4560
4967
  }
4561
4968
  });
4969
+ $wsExports.addEventListener('keydown', (e) => {
4970
+ if (e.key === 'Escape' && exportSourcesState.open) {
4971
+ e.preventDefault(); exportSourcesState.open = false; paintExports(current && current.approvedAt);
4972
+ $wsExports.querySelector('.export-source-trigger')?.focus(); return;
4973
+ }
4974
+ const option = e.target.closest('.export-source-option');
4975
+ if (!option || (e.key !== 'ArrowDown' && e.key !== 'ArrowUp')) return;
4976
+ e.preventDefault();
4977
+ const options = Array.from($wsExports.querySelectorAll('.export-source-option'));
4978
+ const at = options.indexOf(option);
4979
+ options[(at + (e.key === 'ArrowDown' ? 1 : -1) + options.length) % options.length]?.focus();
4980
+ });
4562
4981
 
4563
4982
  // ── Revisions: attach a revised drawing set → queue a compose-time read (Slice 4b) ──
4564
4983
  // The browser records intent + files and QUEUES the read; the terminal AI reads and commits a
@@ -6168,9 +6587,9 @@
6168
6587
 
6169
6588
  function versionRowHtml(v) {
6170
6589
  // Rolling back to the version you're already on is a no-op — omit the button (blank cell), never disable it.
6171
- const action = v.current
6590
+ const action = v.current || v.canStartApprovedRevision !== true
6172
6591
  ? ''
6173
- : `<button type="button" class="btn-mini" data-rollback="${escapeAttr(String(v.n))}" data-tip="Restore this version as a new version">↺ Rollback</button>`;
6592
+ : `<button type="button" class="btn-mini" data-rollback="${escapeAttr(String(v.n))}" data-tip="Begin a new working revision from this approved snapshot">Start from v${escapeHtml(String(v.n))}…</button>`;
6174
6593
  // "What changed" disclosure — only when the semantic diff APPLIES and the version has a
6175
6594
  // predecessor (n>1). v1 is the baseline, and a no-diff app (vectorize) gets NO toggle on ANY row —
6176
6595
  // an ABSENT control, never a disabled one (spec §4.4, mirroring the v1-baseline branch).
@@ -6198,6 +6617,26 @@
6198
6617
  return verRow + diffRow;
6199
6618
  }
6200
6619
 
6620
+ function savedWorkHtml(checkpoints, unavailable) {
6621
+ let body;
6622
+ if (unavailable) {
6623
+ body = '<div class="saved-work-state warn" role="status">Saved work unavailable — retry by reopening History.</div>';
6624
+ } else if (!checkpoints.length) {
6625
+ body = '<div class="saved-work-state">No saved work yet. FloLess saves a checkpoint before you switch away from pending edits.</div>';
6626
+ } else {
6627
+ body = `<div class="saved-work-list">${checkpoints.map((saved) => {
6628
+ const base = saved.base && Number.isInteger(Number(saved.base.version)) ? `Pending work from v${saved.base.version}` : 'Pending work with no approved baseline';
6629
+ const allowed = Array.isArray(saved.allowedActions) ? saved.allowedActions : [];
6630
+ const resume = allowed.includes('resume')
6631
+ ? `<button type="button" class="btn-mini" data-resume-checkpoint="${escapeAttr(String(saved.id))}" data-tip="Switch the working copy to this exact saved checkpoint">Resume exact checkpoint</button>`
6632
+ : '';
6633
+ return `<article class="saved-work-card"><div><b>${escapeHtml(base)}</b><span>${escapeHtml(histWhen(saved.capturedAt))} · ${escapeHtml(String(saved.id || '').slice(0, 8))}</span></div>`
6634
+ + `<p>This checkpoint stays attached to its original approved base; it is never applied backward into another revision.</p>${resume}</article>`;
6635
+ }).join('')}</div>`;
6636
+ }
6637
+ return `<section class="saved-work" aria-labelledby="saved-work-title"><div class="saved-work-head"><h3 id="saved-work-title">Saved work</h3><span>Unapproved checkpoints</span></div>${body}</section>`;
6638
+ }
6639
+
6201
6640
  async function renderHistory() {
6202
6641
  if (!current) return;
6203
6642
  const id = current.id;
@@ -6207,6 +6646,9 @@
6207
6646
  let approvedAt;
6208
6647
  let nextDiffSupported = false;
6209
6648
  let nextDiffEligibleVersions = null;
6649
+ const checkpointPromise = api(`/api/projects/${encodeURIComponent(id)}/checkpoints`);
6650
+ let checkpoints = [];
6651
+ let checkpointsUnavailable = false;
6210
6652
  try {
6211
6653
  const r = await api(`/api/projects/${encodeURIComponent(id)}/versions`);
6212
6654
  rows = Array.isArray(r.versions) ? r.versions : [];
@@ -6215,12 +6657,17 @@
6215
6657
  nextDiffEligibleVersions = hasOwnField(r, 'diffEligibleVersions') ? r.diffEligibleVersions : null;
6216
6658
  approvedAt = r.approvedAt || undefined;
6217
6659
  } catch (err) {
6660
+ await checkpointPromise.catch(() => null);
6218
6661
  showToast('Couldn’t load history: ' + ((err && err.message) || err), 'warn');
6219
6662
  if (current && current.id === id && !$wsHistory.hidden) {
6220
6663
  $wsHistory.innerHTML = '<div class="hist-empty">History unavailable — try again.</div>';
6221
6664
  }
6222
6665
  return;
6223
6666
  }
6667
+ try {
6668
+ const saved = await checkpointPromise;
6669
+ checkpoints = Array.isArray(saved.checkpoints) ? saved.checkpoints : [];
6670
+ } catch { checkpointsUnavailable = true; }
6224
6671
  if (!current || current.id !== id || $wsHistory.hidden) return; // switched away mid-await
6225
6672
  histDiffSupported = nextDiffSupported;
6226
6673
  histDiffEligibleVersions = nextDiffEligibleVersions;
@@ -6264,28 +6711,30 @@
6264
6711
  empty.append('Nothing here yet — ', btn, ' to get started.');
6265
6712
  }
6266
6713
  $wsHistory.replaceChildren(empty);
6714
+ $wsHistory.insertAdjacentHTML('beforeend', savedWorkHtml(checkpoints, checkpointsUnavailable));
6267
6715
  return;
6268
6716
  }
6269
6717
  // Working copy = the draft; when it isn't signed off (approvedAt cleared by an edit or a
6270
6718
  // rollback) surface it honestly ABOVE the table (not as a fake row) and name the Exports lock.
6271
6719
  const headKind = rows.length && rows[0].current ? rows[0].kind : undefined;
6272
6720
  const headIsInitialRead = headKind === 'revision-read' && Number(rows[0].n) <= 1;
6273
- const working = !approvedAt
6721
+ const working = approvalState.status === 'ready' && approvalState.pendingCount > 0
6274
6722
  ? (headKind === 'revision-read'
6275
6723
  ? `<div class="hist-working">● <b>The AI read ${headIsInitialRead ? 'the initial' : 'a revised'} drawing set — review it before signing.</b> ` +
6276
- `Open <b>${escapeHtml(stepLabel('model'))}</b> to check the change, then <button type="button" id="hist-approve">Approve</button> to sign off. Exports stay locked until you do.</div>`
6724
+ `Open <b>${escapeHtml(stepLabel('model'))}</b> to check the change, then <button type="button" id="hist-approve">Review changes</button>. Exports keep using ${approvalState.headVersion ? `approved v${approvalState.headVersion}` : 'an explicitly selected DRAFT'}.</div>`
6277
6725
  : '<div class="hist-working">● <b>Working copy isn’t signed off.</b> ' +
6278
- '<button type="button" id="hist-approve">Approve</button> to sign off this version. Exports stay locked until you do.</div>')
6726
+ `<button type="button" id="hist-approve">Review changes</button>. Exports keep using ${approvalState.headVersion ? `approved v${approvalState.headVersion}` : 'an explicitly selected DRAFT'}.</div>`)
6279
6727
  : '';
6280
6728
  $wsHistory.innerHTML =
6281
- '<div class="hist-note">Every <b>Approve</b> and <b>Rollback</b> records a version. Rollback is non-destructive — it restores a version as a <i>new</i> one.</div>' +
6729
+ '<div class="hist-note"><b>Approved versions</b> are immutable. Starting from an older version creates a new working revision; it never rewrites history.</div>' +
6282
6730
  working +
6283
6731
  // Version/Gate/action are fixed-narrow; When/By auto-size to their nowrap content (fixing them
6284
6732
  // wider than the content wastes room and needlessly wraps Change). Change flexes to the rest.
6285
6733
  '<table class="hist"><thead><tr>' +
6286
6734
  '<th style="width:44px">Version</th><th>When</th><th>By</th>' +
6287
6735
  '<th style="width:80px">Gate</th><th style="width:99%">Change</th><th style="width:92px"></th>' +
6288
- '</tr></thead><tbody>' + rows.map(versionRowHtml).join('') + '</tbody></table>';
6736
+ '</tr></thead><tbody>' + rows.map(versionRowHtml).join('') + '</tbody></table>'
6737
+ + savedWorkHtml(checkpoints, checkpointsUnavailable);
6289
6738
  if (expandDiffOnce && expandDiffOnce.projectId === id) {
6290
6739
  const toggle = $wsHistory.querySelector(`.hd-toggle[data-diff="${CSS.escape(String(expandDiffOnce.n))}"]`);
6291
6740
  expandDiffOnce = null;
@@ -6307,11 +6756,10 @@
6307
6756
  const pop = document.createElement('div');
6308
6757
  pop.className = 'hist-confirm';
6309
6758
  pop.innerHTML =
6310
- `<div class="hc-title">Restore v${escapeHtml(String(n))} as a new version?</div>` +
6311
- `<div class="hc-body">History isn’t erased — this adds a new version copied from v${escapeHtml(String(n))}. ` +
6312
- `Exports re-lock until you Approve again.</div>` +
6759
+ `<div class="hc-title">Start a new working revision from v${escapeHtml(String(n))}?</div>` +
6760
+ `<div class="hc-body">Your current pending work is saved first. Approval later applies only what you author from v${escapeHtml(String(n))} onto the latest approved version; history is never erased.</div>` +
6313
6761
  `<div class="hc-act"><button type="button" class="hc-cancel">Cancel</button>` +
6314
- `<button type="button" class="hc-go" data-hc-go="${escapeAttr(String(n))}">↺ Rollback to v${escapeHtml(String(n))}</button></div>`;
6762
+ `<button type="button" class="hc-go" data-hc-go="${escapeAttr(String(n))}">Start from v${escapeHtml(String(n))}</button></div>`;
6315
6763
  $wsHistory.appendChild(pop);
6316
6764
  const pr = $wsHistory.getBoundingClientRect();
6317
6765
  const br = btn.getBoundingClientRect();
@@ -6320,12 +6768,40 @@
6320
6768
  document.addEventListener('mousedown', onDocDownForConfirm, true);
6321
6769
  }
6322
6770
 
6771
+ // Approval partitioning, discard, History start, and checkpoint resume all replace the server
6772
+ // working contract. Throw away the editor document that supplied the old ETag immediately: when
6773
+ // hidden it must not be able to PUT pre-partition bytes later; when visible it reloads the exact
6774
+ // server result now so the canvas and the next review begin from the same revision.
6775
+ function reloadModelFromServerTruth() {
6776
+ frames.model.dataset.loaded = '';
6777
+ frames.model.src = 'about:blank';
6778
+ if (!frames.model.hidden && frames.model.dataset.want) {
6779
+ frames.model.src = frames.model.dataset.want;
6780
+ frames.model.dataset.loaded = '1';
6781
+ }
6782
+ }
6783
+
6323
6784
  async function rollbackTo(n) {
6324
6785
  if (!current) return;
6325
6786
  const proj = current;
6326
6787
  closeRollbackConfirm();
6327
6788
  try {
6328
- await api(`/api/projects/${encodeURIComponent(proj.id)}/versions/${encodeURIComponent(n)}/rollback`, { method: 'POST' });
6789
+ const win = frames.model && frames.model.contentWindow;
6790
+ // History owns the server-side working revision. Its hidden editor can still hold the
6791
+ // pre-partial-approval document (the server has already reduced that draft to the groups left
6792
+ // pending), so flushing the hidden iframe here can resurrect approved changes or leave this
6793
+ // action waiting on an obsolete editor write queue. A visible editor is the only one with new
6794
+ // unsaved interaction to flush; navigation to History already waits for ordinary autosave.
6795
+ if (!frames.model.hidden && win && typeof win.flushContract === 'function') await win.flushContract();
6796
+ const sources = await api(`/api/projects/${encodeURIComponent(proj.id)}/export-sources`);
6797
+ const working = sources && sources.working;
6798
+ if (!working || typeof working.etag !== 'string'
6799
+ || (working.epoch !== null && !Number.isInteger(Number(working.epoch)))) {
6800
+ throw new Error('Working revision identity is unavailable. Reload History before starting.');
6801
+ }
6802
+ const started = await api(`/api/projects/${encodeURIComponent(proj.id)}/revisions/start`, {
6803
+ method: 'POST', body: JSON.stringify({ version: n, expectedEtag: working.etag, expectedEpoch: working.epoch === null ? null : Number(working.epoch) }),
6804
+ });
6329
6805
  proj.approvedAt = undefined; // rollback re-locks exports (the server cleared the sign-off)
6330
6806
  // Drop the editor's localStorage draft, or the rollback silently undoes itself. restoreSaved()
6331
6807
  // re-overlays that draft's members/dims/details on the editor's NEXT boot whenever dataSig()
@@ -6336,17 +6812,44 @@
6336
6812
  // draft can only put the user's pre-rollback edits back on top of the version they restored.
6337
6813
  // Same origin, and the key is the one the editor builds from ?app=.
6338
6814
  try { localStorage.removeItem('steeltakeoff:edits:v1:' + proj.app); } catch (_) { /* blocked storage */ }
6339
- showToast(`Restored v${n} as a new version — Exports re-locked; Approve to re-enable`, 'ok');
6815
+ showToast((started && started.message) || `Started a DRAFT from v${n}. Exports still default to the latest approved version.`, 'ok');
6340
6816
  // Reload the editor iframe so it shows the restored geometry (it fetched the contract on load).
6341
- frames.model.dataset.loaded = '';
6342
- frames.model.src = 'about:blank';
6343
- if (!frames.model.hidden) { frames.model.src = frames.model.dataset.want; frames.model.dataset.loaded = '1'; }
6817
+ reloadModelFromServerTruth();
6818
+ await refreshApprovalState(proj.id);
6344
6819
  renderHistory();
6345
6820
  } catch (err) {
6346
6821
  showToast('Rollback failed: ' + ((err && err.message) || err), 'warn');
6347
6822
  }
6348
6823
  }
6349
6824
 
6825
+ async function resumeCheckpoint(checkpointId) {
6826
+ if (!current) return;
6827
+ const proj = current;
6828
+ try {
6829
+ const win = frames.model && frames.model.contentWindow;
6830
+ // Do not write a hidden editor's stale in-memory draft over the exact checkpoint selected in
6831
+ // History. See rollbackTo(): only a visible editor can contain interaction not yet autosaved.
6832
+ if (!frames.model.hidden && win && typeof win.flushContract === 'function') await win.flushContract();
6833
+ const sources = await api(`/api/projects/${encodeURIComponent(proj.id)}/export-sources`);
6834
+ const working = sources && sources.working;
6835
+ if (!working || typeof working.etag !== 'string'
6836
+ || (working.epoch !== null && !Number.isInteger(Number(working.epoch)))) {
6837
+ throw new Error('Working revision identity is unavailable. Reload Saved work.');
6838
+ }
6839
+ await api(`/api/projects/${encodeURIComponent(proj.id)}/checkpoints/${encodeURIComponent(checkpointId)}/resume`, {
6840
+ method: 'POST',
6841
+ body: JSON.stringify({ expectedEtag: working.etag, expectedEpoch: working.epoch === null ? null : Number(working.epoch) }),
6842
+ });
6843
+ try { localStorage.removeItem('steeltakeoff:edits:v1:' + proj.app); } catch (_) { /* blocked storage */ }
6844
+ showToast('Resumed the exact saved DRAFT. Its original approved base is preserved.', 'ok');
6845
+ reloadModelFromServerTruth();
6846
+ await refreshApprovalState(proj.id);
6847
+ renderHistory();
6848
+ } catch (err) {
6849
+ showToast('Couldn’t resume saved work: ' + ((err && err.message) || err), 'warn');
6850
+ }
6851
+ }
6852
+
6350
6853
  // ── "What changed" semantic diff (Slice 5) ─────────────────────────────────
6351
6854
  // The panel is DOM-built with textContent for every AI/drawing-supplied string (marks, profiles,
6352
6855
  // connection summaries) — never innerHTML, per the file's security contract.
@@ -6733,6 +7236,8 @@
6733
7236
  if (go) { rollbackTo(Number(go.dataset.hcGo)); return; }
6734
7237
  const roll = e.target.closest('[data-rollback]');
6735
7238
  if (roll) { showRollbackConfirm(roll, Number(roll.dataset.rollback)); return; }
7239
+ const resume = e.target.closest('[data-resume-checkpoint]');
7240
+ if (resume) { resumeCheckpoint(resume.dataset.resumeCheckpoint); return; }
6736
7241
  const tog = e.target.closest('.hd-toggle');
6737
7242
  if (tog) { toggleDiff(tog); return; }
6738
7243
  const opt = e.target.closest('[data-base-opt]');