@floless/app 0.133.2 → 0.134.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.
@@ -33,6 +33,7 @@
33
33
  const $crumbName = document.getElementById('ws-crumb-name');
34
34
  const $status = document.getElementById('ws-status');
35
35
  const $stepTabs = document.getElementById('ws-step-tabs');
36
+ const $stageGuidance = document.getElementById('ws-stage-guidance');
36
37
  const $projMenu = document.getElementById('ws-proj-menu');
37
38
  const $wsExports = document.getElementById('ws-exports');
38
39
  const $wsHistory = document.getElementById('ws-history');
@@ -267,7 +268,7 @@
267
268
  filter: '/steel-filter.html',
268
269
  steps: [
269
270
  { key: 'knowledge', label: 'Knowledge' }, // per-project KB — the job's context, consulted by everything
270
- { key: 'drawings', label: 'Drawings' },
271
+ { key: 'drawings', label: 'Drawing Filter' },
271
272
  { key: 'model', label: 'Model' },
272
273
  { key: 'exports', label: 'Exports' },
273
274
  { key: 'history', label: 'History' },
@@ -433,6 +434,9 @@
433
434
  */
434
435
  let projectContractLifecycle = 'unknown';
435
436
  let exportsHasModel = false;
437
+ // A project may open on Model/Exports/History while its lifecycle probe is still in flight. Keep
438
+ // that requested destination only until the probe settles; an explicit tab click cancels it.
439
+ let pendingPresenceStep = null;
436
440
 
437
441
  /** Sequence number for model-presence probes. A project-id check is NOT a staleness guard: two
438
442
  * probes can be in flight for the SAME project, and an older "absent" answer landing last would
@@ -487,15 +491,83 @@
487
491
  $approveBtn.classList.toggle('approval-clean', s.status === 'ready' && !!s.headVersion && s.pendingCount === 0);
488
492
  }
489
493
 
494
+ /**
495
+ * Reasons a surface below already words BETTER than the server does, because it can attach the
496
+ * next step: `no-contract` becomes "Nothing to export yet — Go to <Drawings>", and
497
+ * `filter-checkpoint` becomes "read the selected drawing content first". Listing the ones we
498
+ * localise — rather than allow-listing the ones we pass through — is the safe direction: an
499
+ * unrecognised future reason falls through to `approvalRefusalNote` and gets SPOKEN, which is the
500
+ * failure this whole change is about. Swallowing an unknown refusal is how #574 happened.
501
+ */
502
+ const LOCALLY_WORDED_REFUSALS = ['no-contract', 'filter-checkpoint'];
503
+
504
+ /**
505
+ * The server's own plain-English refusal for a project that cannot be signed off at all, or `''`
506
+ * when approval is merely unavailable for the moment (loading, a failed probe, nothing read yet).
507
+ *
508
+ * ONE source of truth for the three surfaces that each used to answer this on their own — the
509
+ * header tooltip, the Exports gate, and History. #574 is what the drift looked like: the server
510
+ * wrote "duplicate it from the Workspaces list to sign off", the header eventually learned to
511
+ * repeat it, and the other two went on offering an Approve that could never complete.
512
+ */
513
+ function approvalRefusalNote() {
514
+ if (approvalState.status !== 'unreviewable') return '';
515
+ if (LOCALLY_WORDED_REFUSALS.includes(approvalState.reason)) return '';
516
+ return approvalState.error || 'This project cannot be approved.';
517
+ }
518
+
490
519
  function approvalHeadVersion(review) {
491
520
  return review && review.moveForward && Number.isInteger(Number(review.moveForward.toVersion))
492
521
  ? Number(review.moveForward.toVersion)
493
522
  : review && review.base && Number.isInteger(Number(review.base.version)) ? Number(review.base.version) : null;
494
523
  }
495
524
 
525
+ /**
526
+ * Resolves once `approvalState` reflects a FINISHED probe — not merely once the request came back.
527
+ * The distinction is the whole point: a waiter that raced the response would resume before this
528
+ * function had assigned the state it is waiting to read.
529
+ *
530
+ * It exists so a surface whose own request depends on the verdict can wait for the probe already
531
+ * in flight instead of firing a doomed one alongside it (`awaitApprovalVerdict` below).
532
+ */
533
+ let approvalSettled = null;
534
+
535
+ /**
536
+ * Park until the in-flight approval probe has settled, and only while one is actually running.
537
+ *
538
+ * Cheap in the common case — by the time a step is opened the probe started at project-open has
539
+ * long since finished, so this awaits an already-resolved promise. It only ever waits when the
540
+ * surface genuinely cannot answer its own question yet, and in that case it had to wait anyway to
541
+ * paint the right copy.
542
+ *
543
+ * CANNOT DEADLOCK against `refreshApprovalState`, which calls back into `renderHistory` on its
544
+ * refusal branch: every one of its exits assigns a non-`loading` status BEFORE re-rendering, so
545
+ * the guard below is already false by the time it re-enters.
546
+ */
547
+ async function awaitApprovalVerdict() {
548
+ // Loops because a probe can be SUPERSEDED while a surface is parked on it, and one `await` then
549
+ // resumes on the wrong answer. The revision-read completion path is a live example: it starts a
550
+ // fresh probe and re-renders History on the next line, so the parked render is woken by the OLD
551
+ // probe's release while `approvalState` has already been reset to `loading` by the NEW one. It
552
+ // then reads "no refusal" — from a verdict that does not exist yet — and sends the request this
553
+ // whole mechanism exists to withhold.
554
+ //
555
+ // This is not a poll and cannot spin: each turn parks on a DISTINCT promise, and it only goes
556
+ // round again when `approvalSettled` has been replaced, which only a newer probe does. If the
557
+ // promise we waited on is still the current one, that probe wrote the state and we are done —
558
+ // the identity check is the loop's guarantee of termination, not an optimisation.
559
+ while (approvalState.status === 'loading' && approvalSettled) {
560
+ const pending = approvalSettled;
561
+ await pending;
562
+ if (approvalSettled === pending) break;
563
+ }
564
+ }
565
+
496
566
  async function refreshApprovalState(projectId = current && current.id) {
497
567
  if (!projectId || !current || current.id !== projectId) return null;
498
568
  const gen = ++approvalStateGen;
569
+ let settle;
570
+ approvalSettled = new Promise((resolve) => { settle = resolve; });
499
571
  approvalState = { status: 'loading', review: null, pendingCount: 0, headVersion: null, error: '' };
500
572
  renderApprovalHeader();
501
573
  try {
@@ -511,6 +583,12 @@
511
583
  renderApprovalHeader();
512
584
  syncWorkspaceGuide();
513
585
  if (!$wsExports.hidden) paintExports(current.approvedAt);
586
+ // No History re-render here. An earlier cut of this change had one, to repair a History
587
+ // that had painted while the status was still `loading` — but `renderHistory` now parks on
588
+ // `awaitApprovalVerdict()` instead, so it cannot paint from a loading state in the first
589
+ // place. Keeping both would start a SECOND concurrent render racing the parked one for the
590
+ // same DOM. The other callers that legitimately need a repaint (approve, discard, rollback)
591
+ // already call `renderHistory` themselves.
514
592
  return null;
515
593
  }
516
594
  const groups = Array.isArray(review.groups) ? review.groups : [];
@@ -527,6 +605,10 @@
527
605
  renderApprovalHeader();
528
606
  if (!$wsExports.hidden) paintExports(current.approvedAt);
529
607
  return null;
608
+ } finally {
609
+ // EVERY exit below the `loading` assignment, including the staleness returns that leave the
610
+ // state to a newer probe. A waiter must never be stranded on a probe that quietly gave up.
611
+ settle();
530
612
  }
531
613
  }
532
614
 
@@ -1603,6 +1685,12 @@
1603
1685
  return;
1604
1686
  }
1605
1687
  current = p;
1688
+ // Project lifecycle is project-scoped. Reset it before the first setStep so one project's model
1689
+ // cannot unlock another project's tabs (or one empty project redirect a modeled project forever).
1690
+ projectContractLifecycle = 'unknown';
1691
+ exportsHasModel = false;
1692
+ modelPresenceGen++;
1693
+ pendingPresenceStep = null;
1606
1694
  exportState = null;
1607
1695
  hostReadinessStates = {};
1608
1696
  renderReadinessState = null;
@@ -1621,6 +1709,9 @@
1621
1709
  // the 'model' frame loads the app's editor; the 'drawings' frame loads its filter (steel) OR is
1622
1710
  // left empty when the app has no filter step (vectorize — its Source step shows a placeholder).
1623
1711
  const d = wsDescOf(p); // guaranteed present — the guard above bailed on an unknown app
1712
+ if (d.filter && ['model', 'exports', 'history'].includes(initialStep)) {
1713
+ pendingPresenceStep = { projectId: p.id, step: initialStep };
1714
+ }
1624
1715
  // The LIVE app id, deliberately: the frames address the server with it (contract reads, saves),
1625
1716
  // and after a rename only the live id resolves. Only the descriptor came from the lineage root.
1626
1717
  const qs = `?app=${encodeURIComponent(p.app)}&project=${encodeURIComponent(p.id)}`;
@@ -1629,7 +1720,23 @@
1629
1720
  renderStepTabs(); // paint the tab labels for THIS app before the first step shows
1630
1721
  frames.model.src = 'about:blank'; frames.drawings.src = 'about:blank'; // reset any previous project
1631
1722
  frames.model.dataset.loaded = ''; frames.drawings.dataset.loaded = '';
1632
- setStep(initialStep);
1723
+ // BEFORE the first step renders, and that order is the fix rather than a tidy-up.
1724
+ //
1725
+ // `initialStep` is not always 'model' — a project re-opened from the picker keeps `currentStep`,
1726
+ // so switching project while standing on History renders History first. Started after
1727
+ // `setStep`, the probe does not exist yet when `renderHistory` reaches `awaitApprovalVerdict()`:
1728
+ // the status is still whatever the PREVIOUS project left behind, the waiter correctly declines
1729
+ // to park on a probe nobody started, and the doomed `/checkpoints` request goes out after all.
1730
+ //
1731
+ // Calling it here is enough on its own: `refreshApprovalState` publishes both the `loading`
1732
+ // status and `approvalSettled` SYNCHRONOUSLY, before its first await, so any render that follows
1733
+ // this line sees a probe to park on. The waiter is deliberately NOT taught to block on a
1734
+ // not-yet-started probe — that would hang any surface rendered outside a project open.
1735
+ refreshApprovalState(p.id).catch((e) => console.error('[workspaces] could not load approval state', e));
1736
+ // A steel project's lifecycle answer arrives asynchronously. Do not briefly open (or falsely
1737
+ // refuse) a later stage while that answer is unknown: hold the requested destination, show the
1738
+ // first actionable stage, and restore the destination only after an explicit `model` answer.
1739
+ setStep(pendingPresenceStep ? 'drawings' : initialStep);
1633
1740
  applyMode();
1634
1741
  syncWorkspaceGuide(); // point the shared beacon at THIS project's document lifecycle
1635
1742
  // Detached, but never silent: the lifecycle probe cannot reject, yet the code after its await can
@@ -1638,7 +1745,6 @@
1638
1745
  refreshModelPresence(p.id, p.app).catch((e) => { // gate the header CHECK Approve for THIS project (#490)
1639
1746
  console.error('[workspaces] could not resolve model presence', e);
1640
1747
  });
1641
- refreshApprovalState(p.id).catch((e) => console.error('[workspaces] could not load approval state', e));
1642
1748
  }
1643
1749
 
1644
1750
  /**
@@ -1656,7 +1762,14 @@
1656
1762
  const gen = ++modelPresenceGen;
1657
1763
  const present = await projectContractState(projectId, appId);
1658
1764
  if (gen !== modelPresenceGen || !current || current.id !== projectId) return; // superseded
1765
+ const restore = pendingPresenceStep?.projectId === projectId ? pendingPresenceStep.step : '';
1766
+ // A timeout/network error is not evidence that this project has no model. Keep the requested
1767
+ // destination so activating the locked tab can retry the probe and restore it after recovery.
1768
+ if (present !== 'unknown') pendingPresenceStep = null;
1659
1769
  applyModelPresence(present);
1770
+ // `unknown` deliberately fails closed and may have redirected the requested destination to the
1771
+ // Drawing Filter. Restore it only when this same project's authoritative answer says a model exists.
1772
+ if (present === 'model' && restore && currentStep === 'drawings') setStep(restore);
1660
1773
  }
1661
1774
 
1662
1775
  /** Push the answer to the flag AND the header together, so no two surfaces can disagree. */
@@ -1664,6 +1777,7 @@
1664
1777
  projectContractLifecycle = present;
1665
1778
  exportsHasModel = present === 'model';
1666
1779
  renderApprovalHeader();
1780
+ applyStageGating();
1667
1781
  }
1668
1782
  function closeProject() {
1669
1783
  current = null;
@@ -1689,7 +1803,7 @@
1689
1803
  // was already per-project, the two variables behind it were not.)
1690
1804
  // Reset with the rest of the per-project state — this file resets `histDiffSupported` for exactly
1691
1805
  // this reason. Bumping the generation also voids any probe still in flight for the closing project.
1692
- projectContractLifecycle = 'unknown'; exportsHasModel = false; modelPresenceGen++;
1806
+ projectContractLifecycle = 'unknown'; exportsHasModel = false; modelPresenceGen++; pendingPresenceStep = null;
1693
1807
  closeProjMenu(); applyMode(); syncWorkspaceGuide(); // revision state cleared by resetRevisionState() above
1694
1808
  }
1695
1809
  document.getElementById('ws-back').addEventListener('click', closeProject);
@@ -1704,11 +1818,129 @@
1704
1818
  const byKey = new Map(d.steps.map((st) => [st.key, st.label]));
1705
1819
  $stepTabs.querySelectorAll('button[data-step]').forEach((b) => {
1706
1820
  const label = byKey.get(b.dataset.step);
1707
- if (label) b.textContent = label;
1821
+ if (label) {
1822
+ b.textContent = label;
1823
+ b.setAttribute('data-command-id', `shell.workspace-step#${label}`);
1824
+ }
1708
1825
  });
1709
1826
  }
1710
1827
 
1828
+ // Keep steel projects stage-by-stage while the first drawing read is in progress. The later tabs
1829
+ // stay visible so the user can see what comes next, but explain their prerequisite instead of
1830
+ // opening empty destinations during a potentially long terminal-AI read.
1831
+ function stageGateFor(step) {
1832
+ const d = wsApp();
1833
+ if (!d || !d.filter || !['model', 'exports', 'history'].includes(step)) return '';
1834
+ const initialRead = revCardReq && isInitialRevisionRead(revCardReq);
1835
+ const waitingForInitial = initialRead && lastRevState === 'pending';
1836
+ const stagedInitial = initialRead && lastRevState === 'staged';
1837
+ const failedInitial = initialRead && lastRevState === 'failed';
1838
+ const unavailableInitial = initialRead && lastRevState === 'unavailable';
1839
+ if (projectContractLifecycle === 'model') return '';
1840
+ if (stagedInitial) return 'The drawing read is complete. Open Drawing Filter and choose Review changes before using the later stages.';
1841
+ if (failedInitial) {
1842
+ if (revCardReq?.canClear === true) return 'The drawing read failed. Return to Drawing Filter, press Dismiss, then attach the drawing set again.';
1843
+ return `${revCardReq?.clearWhy || 'FloLess cannot safely release this drawing read yet.'} Open Requests for the available recovery.`;
1844
+ }
1845
+ if (unavailableInitial) return 'This drawing read uses a status this version of FloLess does not recognize. Open Requests for details and update FloLess before continuing.';
1846
+ if (projectContractLifecycle === 'unknown') return 'Checking which project stages are ready. Select this tab again to retry if the check does not finish.';
1847
+ if (step === 'model') {
1848
+ if (waitingForInitial && revCardReq?.filterSaved) return 'The Drawing Filter is saved. Return to the same terminal AI session that prepared it and tell it to continue the drawing read.';
1849
+ if (waitingForInitial && revCardReq?.prepassReady) return 'Review the selected lines, then press Save filter. After Save, return to the terminal AI that prepared it and tell it to continue.';
1850
+ if (waitingForInitial) return 'The initial drawing read is waiting for your terminal AI. The model unlocks after you review the Drawing Filter and press Save filter.';
1851
+ if (projectContractLifecycle === 'filter-checkpoint') return 'Attach the drawing set again in Drawing Filter to restart the read. The earlier request is no longer available to receive a saved filter.';
1852
+ return 'Read and save a Drawing Filter first. The model will unlock after the first drawing read.';
1853
+ }
1854
+ if (waitingForInitial) return `The ${step === 'exports' ? 'steel model' : 'first model'} must be ready before ${step === 'exports' ? 'exports' : 'history'} is available.`;
1855
+ if (projectContractLifecycle === 'filter-checkpoint') return `Attach the drawing set again in Drawing Filter before opening ${step === 'exports' ? 'Exports' : 'History'}. The earlier request can no longer continue.`;
1856
+ return `Create the first steel model before opening ${step === 'exports' ? 'Exports' : 'History'}.`;
1857
+ }
1858
+
1859
+ function applyStageGating() {
1860
+ const d = wsApp();
1861
+ if (!$stepTabs) return;
1862
+ if (!d || !d.filter) {
1863
+ // The tab strip is shared across projects. Remove every steel-only gate when switching to an
1864
+ // app without a Drawing Filter, or the next app inherits disabled tabs from the previous one.
1865
+ $stepTabs.querySelectorAll('button[data-step]').forEach((b) => {
1866
+ b.classList.remove('ws-step-locked');
1867
+ b.removeAttribute('aria-disabled');
1868
+ b.removeAttribute('data-stage-locked');
1869
+ b.removeAttribute('data-tip');
1870
+ b.removeAttribute('data-blocked-reason');
1871
+ b.setAttribute('tabindex', '0');
1872
+ });
1873
+ if ($stageGuidance) $stageGuidance.hidden = true;
1874
+ return;
1875
+ }
1876
+ let locked = false;
1877
+ $stepTabs.querySelectorAll('button[data-step]').forEach((b) => {
1878
+ const reason = stageGateFor(b.dataset.step);
1879
+ const isLocked = !!reason;
1880
+ locked ||= isLocked;
1881
+ b.classList.toggle('ws-step-locked', isLocked);
1882
+ b.setAttribute('aria-disabled', String(isLocked));
1883
+ if (isLocked) {
1884
+ b.setAttribute('data-stage-locked', 'true');
1885
+ b.setAttribute('data-tip', reason);
1886
+ b.setAttribute('data-blocked-reason', reason);
1887
+ // Keep locked tabs keyboard-reachable so their prerequisite is available to keyboard users
1888
+ // and to Instructor. Activation is still blocked by the click handler and setStep.
1889
+ b.setAttribute('tabindex', '0');
1890
+ } else {
1891
+ b.removeAttribute('data-stage-locked');
1892
+ b.removeAttribute('aria-disabled');
1893
+ b.removeAttribute('data-tip');
1894
+ b.removeAttribute('data-blocked-reason');
1895
+ b.setAttribute('tabindex', '0');
1896
+ }
1897
+ });
1898
+ // A project opened on the old default Model step can become gated when the lifecycle probe
1899
+ // returns. Move it to the first actionable stage instead of leaving a locked tab selected.
1900
+ if (currentStep !== 'drawings' && stageGateFor(currentStep)) {
1901
+ setStep('drawings');
1902
+ return;
1903
+ }
1904
+ if (!$stageGuidance) return;
1905
+ const initialRead = revCardReq && isInitialRevisionRead(revCardReq);
1906
+ const waitingForInitial = initialRead && lastRevState === 'pending';
1907
+ const stagedInitial = initialRead && lastRevState === 'staged';
1908
+ const failedInitial = initialRead && lastRevState === 'failed';
1909
+ const unavailableInitial = initialRead && lastRevState === 'unavailable';
1910
+ if (!locked) {
1911
+ $stageGuidance.hidden = true;
1912
+ $stageGuidance.textContent = '';
1913
+ return;
1914
+ }
1915
+ $stageGuidance.hidden = false;
1916
+ $stageGuidance.textContent = stagedInitial
1917
+ ? 'The drawing read is complete · Open Drawing Filter and choose Review changes before moving to Model, Exports, or History.'
1918
+ : failedInitial
1919
+ ? (revCardReq?.canClear === true
1920
+ ? 'The drawing read failed · Return to Drawing Filter, press Dismiss, then attach the drawing set again.'
1921
+ : `The drawing read failed · ${revCardReq?.clearWhy || 'FloLess cannot safely release this drawing read yet.'} Open Requests for the available recovery.`)
1922
+ : unavailableInitial
1923
+ ? 'This drawing read uses a status this version of FloLess does not recognize · Open Requests for details and update FloLess before continuing.'
1924
+ : projectContractLifecycle === 'unknown'
1925
+ ? 'Checking which project stages are ready… You can keep working in Drawing Filter. Select Model, Exports, or History to retry the check.'
1926
+ : waitingForInitial && revCardReq?.filterSaved
1927
+ ? 'Stage 1 of 4 complete · The Drawing Filter is saved. Return to the same terminal AI session that prepared it and tell it to continue the drawing read. Model, Exports, and History unlock when it finishes.'
1928
+ : waitingForInitial && revCardReq?.prepassReady
1929
+ ? 'Stage 1 of 4 · Review the selected layers, line weights, and colours below. Then press Save filter in the top-right corner, return to the terminal AI that prepared it, and tell it to continue. Model, Exports, and History unlock when the read finishes.'
1930
+ : waitingForInitial
1931
+ ? 'Stage 1 of 4 · Your initial drawing read is waiting for your terminal AI. Open Requests, copy it into Claude Code, Codex, or OpenCode, then return to review and save the Drawing Filter. Model, Exports, and History unlock afterward.'
1932
+ : projectContractLifecycle === 'filter-checkpoint'
1933
+ ? 'Stage 1 of 4 · The earlier drawing request is no longer available. Attach the drawing set again in Drawing Filter to restart the read. Model, Exports, and History unlock after it finishes.'
1934
+ : 'Start in Drawing Filter by attaching a PDF or image. The Model, Exports, and History stages unlock after the first steel model is created.';
1935
+ }
1936
+
1711
1937
  function setStep(s) {
1938
+ const lockedReason = stageGateFor(s);
1939
+ if (lockedReason) {
1940
+ if (currentStep !== 'drawings') setStep('drawings');
1941
+ showToast(lockedReason, 'warn');
1942
+ return;
1943
+ }
1712
1944
  currentStep = s;
1713
1945
  $stepTabs.querySelectorAll('button').forEach((b) => {
1714
1946
  const on = b.dataset.step === s;
@@ -1747,10 +1979,24 @@
1747
1979
  // in-flight preview read), and forget the cached state so re-entering re-reads rather than
1748
1980
  // flashing a stale column.
1749
1981
  else { stopKnowledgePoll(); kbCloseConfirm(); kbResetViewer(); knowledgeState = null; }
1982
+ applyStageGating();
1750
1983
  }
1751
1984
  $stepTabs.addEventListener('click', (e) => {
1752
1985
  const b = e.target.closest('button[data-step]');
1753
- if (b) setStep(b.dataset.step);
1986
+ if (b?.getAttribute('aria-disabled') === 'true') {
1987
+ e.preventDefault();
1988
+ const reason = stageGateFor(b.dataset.step);
1989
+ if (projectContractLifecycle === 'unknown' && current) {
1990
+ pendingPresenceStep = { projectId: current.id, step: b.dataset.step };
1991
+ refreshModelPresence(current.id, current.app).catch((err) => console.error('[workspaces] could not retry model presence', err));
1992
+ }
1993
+ if (reason) showToast(reason, 'warn');
1994
+ return;
1995
+ }
1996
+ if (b) {
1997
+ pendingPresenceStep = null;
1998
+ setStep(b.dataset.step);
1999
+ }
1754
2000
  });
1755
2001
 
1756
2002
  // ── Approve (per-project) ───────────────────────────────────────────────────
@@ -1759,6 +2005,10 @@
1759
2005
  // and the Exports gate link #ws-exports-approve ("Approve this version"). History stays a ledger,
1760
2006
  // so approval is deliberately not duplicated there.
1761
2007
  //
2008
+ // Every one of them is withheld — not disabled — when `approvalRefusalNote()` speaks: the header
2009
+ // renders a label, and the Exports gate renders the refusal instead of the link. `approveProject`
2010
+ // keeps its own guard regardless, because the refusal can arrive while a control is on screen.
2011
+ //
1762
2012
  // What unlocks the Exports gate without a reload is the confirm's refreshApprovalState() +
1763
2013
  // renderExports(), which re-read the server's approval state and export sources — NOT the
1764
2014
  // `approvedAt` stamp. The gate is `exportSourcesState.status === 'ready' && an explicit source`
@@ -4481,7 +4731,14 @@
4481
4731
 
4482
4732
  function exportSourceHtml() {
4483
4733
  if (exportSourcesState.status === 'loading') return '<div class="export-source-status" role="status">Loading export sources…</div>';
4484
- if (exportSourcesState.status !== 'ready') return '<div class="export-source-status unavailable" role="status">Export sources unavailable — retry by reopening Exports.</div>';
4734
+ // "Retry by reopening" is the right answer for a transient failure and the WRONG one for a
4735
+ // project whose export-sources route refuses on the same standing condition approval does — it
4736
+ // invites an action that cannot ever succeed. When the refusal is speaking, stay silent and let
4737
+ // the gate below carry the single true sentence rather than stacking a false one above it.
4738
+ if (exportSourcesState.status !== 'ready') {
4739
+ return approvalRefusalNote() ? ''
4740
+ : '<div class="export-source-status unavailable" role="status">Export sources unavailable — retry by reopening Exports.</div>';
4741
+ }
4485
4742
  const data = exportSourcesState.data || {};
4486
4743
  const options = exportSourceOptions(data);
4487
4744
  const selected = currentExportSourceOption();
@@ -4522,15 +4779,28 @@
4522
4779
  // approved is selected by default when present; a no-baseline project stays closed until the
4523
4780
  // person deliberately chooses its DRAFT working copy/checkpoint.
4524
4781
  const approved = projectContractLifecycle === 'model' && exportSourcesState.status === 'ready' && !!currentExportSourceOption();
4782
+ const approvalRefusal = approvalRefusalNote();
4525
4783
  let html = exportSourceHtml();
4526
4784
  if (!approved) {
4527
4785
  // Same split as History's empty state (#490): with a model, Approve is genuinely the unlocking
4528
4786
  // action; with none, `POST …/approve` 404s, so pointing at it is a dead end and the real next
4529
4787
  // step is to go read a drawing. `stepLabel('drawings')` because that label is per-app.
4788
+ // A project the server refuses to review can never reach sign-off, so "Approve this version"
4789
+ // is REMOVED here rather than left inert — the same reasoning History's empty state records
4790
+ // just below, and the reason the header shows a label instead of an armed button. What
4791
+ // replaces it is the server's own sentence, which already carries cause AND remedy.
4792
+ //
4793
+ // No DRAFT escape hatch is offered, and that is measured rather than assumed:
4794
+ // `GET …/export-sources` refuses a project with no incarnation for the SAME reason approval
4795
+ // does ("has no incarnation UUID"), so `exportSourcesState` never reaches `ready` and the
4796
+ // picker above holds no options at all. Naming a route the pane cannot actually offer would
4797
+ // repeat this bug one line further down.
4530
4798
  html += exportSourcesState.data?.defaultUnavailable?.reason === 'refused'
4531
4799
  ? `<div class="ws-exports-gate refused" role="alert">Exports are paused because the approved snapshot failed its integrity check. <button type="button" data-review-changes>Review approval</button></div>`
4532
4800
  : projectContractLifecycle === 'filter-checkpoint'
4533
4801
  ? '<div class="ws-exports-gate">Drawing Filter saved &mdash; read the selected drawing content to build the model before exporting.</div>'
4802
+ : approvalRefusal
4803
+ ? `<div class="ws-exports-gate">${escapeHtml(approvalRefusal)}</div>`
4534
4804
  : hasModel
4535
4805
  ? `<div class="ws-exports-gate">Exports go out after sign-off — ` +
4536
4806
  `<button type="button" id="ws-exports-approve">Approve this version</button> to enable them.</div>`
@@ -4674,14 +4944,32 @@
4674
4944
  if (exportsHasModel !== paintedWith) paintExports(current.approvedAt, restoreKind);
4675
4945
  let state = null;
4676
4946
  let approvedAt = current.approvedAt; // fallback if the fetch fails (best-known)
4947
+ // Don't ask a question whose answer we already hold. `/export-sources` refuses on exactly the
4948
+ // standing condition the approval probe has already reported, so the request can only come back
4949
+ // 409 — and Chromium prints "Failed to load resource" for EVERY non-2xx regardless of how
4950
+ // cleanly the page handles it. Not asking is the only way to keep the console quiet, and it is
4951
+ // the honest description of the state anyway: there is nothing to select, which is what
4952
+ // `unavailable` already means here. Unknown still asks, so a not-yet-settled probe cannot
4953
+ // suppress a listing that would have succeeded.
4954
+ await awaitApprovalVerdict();
4955
+ if (!current || current.id !== id || $wsExports.hidden) return; // switched away while it settled
4956
+ // EVERY request in this render starts BELOW the wait, and the four of them are followed
4957
+ // immediately by the `allSettled` that handles them — no await may separate the two.
4958
+ //
4959
+ // `exportPromise` used to be started above, which review caught: parking on the verdict left it
4960
+ // in flight with no handler attached, so a failure during the wait crossed a microtask
4961
+ // checkpoint unhandled and the browser logged it — the same defect this PR fixes for
4962
+ // `checkpointPromise`, reintroduced one line up by the wait itself. The `return` on the line
4963
+ // above made it worse: it abandoned the promise outright.
4964
+ const sourcesRefused = !!approvalRefusalNote();
4677
4965
  const exportPromise = api(`/api/contract/${encodeURIComponent(app)}/exports?project=${encodeURIComponent(id)}`);
4678
- const sourcePromise = api(`/api/projects/${encodeURIComponent(id)}/export-sources`);
4966
+ const sourcePromise = sourcesRefused ? null : api(`/api/projects/${encodeURIComponent(id)}/export-sources`);
4679
4967
  const readinessPromise = hasHosts ? refreshHostReadiness() : Promise.resolve(null);
4680
4968
  const renderReadyPromise = hasRender ? api('/api/render/readiness') : Promise.resolve(null);
4681
4969
  const [exportResult, readinessResult, renderReadyResult, sourceResult] = await Promise.allSettled([
4682
4970
  exportPromise, readinessPromise, renderReadyPromise, sourcePromise,
4683
4971
  ]);
4684
- if (sourceResult.status === 'fulfilled') {
4972
+ if (!sourcesRefused && sourceResult.status === 'fulfilled') {
4685
4973
  exportSourcesState.status = 'ready';
4686
4974
  exportSourcesState.data = sourceResult.value;
4687
4975
  if (!currentExportSourceOption()) exportSourcesState.selected = null;
@@ -5239,7 +5527,9 @@
5239
5527
  let revBaseProject = null; // …and WHICH project it was captured in; a baseline means nothing anywhere else
5240
5528
  let revCardReq = null;
5241
5529
  let revisionPoll = null;
5242
- let revisionGen = 0; // bumped per render AND by openProject/closeProject — see renderRevisionCard
5530
+ let revisionGen = 0; // newest-wins epoch for overlapping card renders — see renderRevisionCard
5531
+ let revisionOwnerGen = 0; // bumped only when navigation retires actions owned by the current project
5532
+ let revisionAttachGen = 0; // newest Attach owns its delayed copy/modal completion within that project
5243
5533
  let revRequestsFailed = false; // one log per outage, not one per 3-second poll tick
5244
5534
  /**
5245
5535
  * Every piece of revision state above is PER-PROJECT, so opening or closing one must clear all of
@@ -5267,6 +5557,7 @@
5267
5557
  revCardReq = null;
5268
5558
  $revisionCard._renderKey = '';
5269
5559
  revisionGen++; // voids any render still in flight for the project being left
5560
+ revisionOwnerGen++; // voids Attach/Copy work, without letting a routine poll do so
5270
5561
  stopRevisionPoll();
5271
5562
  $revisionCard.hidden = true;
5272
5563
  $revisionCard.replaceChildren();
@@ -5293,28 +5584,40 @@
5293
5584
  });
5294
5585
  }
5295
5586
 
5587
+ async function copyAttachedRevision(req, ownsAttach) {
5588
+ if (!req || !bridge.copyRequest || !ownsAttach()) return false;
5589
+ try {
5590
+ const result = await bridge.copyRequest(req, ownsAttach);
5591
+ return result === 'ok' && ownsAttach();
5592
+ } catch {
5593
+ return false;
5594
+ }
5595
+ }
5596
+
5296
5597
  async function attachRevision(files) {
5297
5598
  const proj = current; // capture — the user may switch projects during the async file reads / POST
5298
5599
  if (!proj || !files.length) return;
5600
+ const projectGeneration = revisionOwnerGen;
5601
+ const attachGeneration = ++revisionAttachGen;
5602
+ const ownsAttach = () => current === proj
5603
+ && revisionOwnerGen === projectGeneration
5604
+ && revisionAttachGen === attachGeneration;
5299
5605
  const returnFocus = document.activeElement;
5300
5606
  let snapshots;
5301
5607
  try { snapshots = await Promise.all(files.map(readFileAsSnapshot)); }
5302
5608
  catch { showToast('Could not read the selected files', 'warn'); return; }
5303
- if (current !== proj) return; // switched projects mid-read — abandon rather than queue against the wrong one
5609
+ if (!ownsAttach()) return; // switched/reopened/attached again mid-read — abandon this stale completion
5304
5610
  let res;
5305
5611
  try {
5306
5612
  res = await api(`/api/projects/${encodeURIComponent(proj.id)}/revision-requests`, {
5307
5613
  method: 'POST', body: JSON.stringify({ appId: proj.app, snapshots }),
5308
5614
  });
5309
- } catch (err) { showToast('Attach failed: ' + ((err && err.message) || err), 'warn'); return; }
5615
+ } catch (err) { if (ownsAttach()) showToast('Attach failed: ' + ((err && err.message) || err), 'warn'); return; }
5310
5616
  const req = res && res.request;
5311
5617
  // Copy the paste-ready instruction so the user can hand it to their terminal AI (best-effort).
5312
- let copied = false;
5313
- if (req && bridge.copyRequest) {
5314
- try { copied = (await bridge.copyRequest(req)) === 'ok'; } catch { copied = false; }
5315
- }
5618
+ const copied = await copyAttachedRevision(req, ownsAttach);
5316
5619
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {}); // refresh the footer Requests popover
5317
- if (current !== proj) return; // switched away while posting — don't drive the wrong project's card/poll
5620
+ if (!ownsAttach()) return; // don't drive a replaced project's card/poll/modal or narrate its Copy
5318
5621
  revBaseVersion = (req && typeof req.baseVersion === 'number') ? req.baseVersion : 0;
5319
5622
  revBaseProject = proj.id; // the baseline belongs to THIS project — see resetRevisionState
5320
5623
  showToast(`${revBaseVersion <= 0 ? 'Initial' : 'Revised'} set queued — ${files.length} file${files.length > 1 ? 's' : ''} for your terminal AI`, 'ok');
@@ -5333,25 +5636,52 @@
5333
5636
 
5334
5637
  function buildPendingCard(req) {
5335
5638
  const n = (req.sourceRefs && req.sourceRefs.length) || (req.snapshots && req.snapshots.length) || 1;
5639
+ if (req.prepassReady && req.filterSaved) {
5640
+ const dot = revEl('span', 'wrc-dot'); dot.setAttribute('aria-hidden', 'true');
5641
+ const txt = revEl('span', 'wrc-text');
5642
+ txt.appendChild(revEl('b', null, 'Drawing Filter saved.'));
5643
+ txt.appendChild(document.createTextNode(' Return to the same terminal AI session that prepared this Drawing Filter and tell it to continue the drawing read.'));
5644
+ return [dot, txt];
5645
+ }
5336
5646
  if (req.prepassReady) {
5337
5647
  // The terminal AI has completed the deterministic pre-read; it is now waiting on the real Filter
5338
5648
  // Save checkpoint below, not on another pasted instruction. A static dot avoids claiming work is
5339
5649
  // still running, and the real action only focuses the existing Filter iframe — it never fakes Save.
5340
5650
  const dot = revEl('span', 'wrc-dot'); dot.setAttribute('aria-hidden', 'true');
5341
5651
  const txt = revEl('span', 'wrc-text');
5342
- txt.appendChild(revEl('b', null, 'Steel Filter is ready.'));
5343
- txt.appendChild(document.createTextNode(' Review the Steel Filter and Save to continue the read.'));
5344
- const review = revEl('button', 'btn-mini', 'Review Filter');
5345
- review.type = 'button'; review.dataset.revfilter = ''; review.setAttribute('data-tip', 'Focus the Steel Filter below');
5652
+ txt.appendChild(revEl('b', null, 'Drawing Filter is ready.'));
5653
+ txt.appendChild(document.createTextNode(' Review the selected layers, line weights, and colours. Then press Save filter in the top-right corner, return to the terminal AI that prepared it, and tell it to continue the drawing read.'));
5654
+ const review = revEl('button', 'btn-mini', 'Open Drawing Filter');
5655
+ review.type = 'button'; review.dataset.revfilter = ''; review.dataset.commandId = 'shell.revision-filter-open';
5656
+ review.setAttribute('data-tip', 'Focus the Drawing Filter below');
5346
5657
  return [dot, txt, review];
5347
5658
  }
5348
- const spin = revEl('span', 'wrc-spin'); spin.setAttribute('aria-hidden', 'true');
5659
+ const runState = req.run && req.run.state;
5660
+ if (runState === 'queued' || runState === 'running') {
5661
+ // The terminal AI already owns this request. Do not offer Copy here: a second handoff is not a
5662
+ // useful fallback while the first one is active, and the Requests window carries the real Stop.
5663
+ const dot = revEl('span', 'wrc-dot'); dot.setAttribute('aria-hidden', 'true');
5664
+ const txt = revEl('span', 'wrc-text');
5665
+ txt.appendChild(revEl('b', null, `${isInitialRevisionRead(req) ? 'Initial' : 'Updated'} drawing read is running.`));
5666
+ txt.appendChild(document.createTextNode(` Your terminal AI is preparing ${n} file${n > 1 ? 's' : ''}. You can keep working in FloLess; progress and the next required step will appear here. Open Requests if you need to stop it.`));
5667
+ return [dot, txt];
5668
+ }
5669
+ // `pending` means the request is waiting for the terminal AI handoff; it does not prove that an
5670
+ // AI is actively reading. A spinner made a pasted instruction look like an already-running job.
5671
+ const dot = revEl('span', 'wrc-dot'); dot.setAttribute('aria-hidden', 'true');
5349
5672
  const txt = revEl('span', 'wrc-text');
5350
- txt.appendChild(revEl('b', null, `Reading the ${isInitialRevisionRead(req) ? 'initial' : 'revised'} set…`));
5351
- txt.appendChild(document.createTextNode(` ${n} file${n > 1 ? 's' : ''} queued for your terminal AI — paste the copied instruction there, or say “apply my floless request”.`));
5673
+ txt.appendChild(revEl('b', null, `${isInitialRevisionRead(req) ? 'Initial' : 'Updated'} drawing read is waiting for your terminal AI.`));
5674
+ // Runtime discovery belongs to the Requests surface, not this workspace card. `canRun` is only
5675
+ // server policy; it does not prove that a supported terminal AI is installed on this machine.
5676
+ // Phrase the optional shortcut conditionally so the card never points to a hidden control.
5677
+ const handoff = !isInitialRevisionRead(req) && req.canRun
5678
+ ? 'Open Requests. If Start automatically is shown, choose it; otherwise copy the request into Claude Code, Codex, or OpenCode.'
5679
+ : 'Open Requests and copy the request into Claude Code, Codex, or OpenCode.';
5680
+ txt.appendChild(document.createTextNode(` ${n} file${n > 1 ? 's' : ''} queued. ${handoff} Then return here. This may take up to 30 minutes.`));
5352
5681
  const copy = revEl('button', 'btn-mini', '⧉ Copy');
5353
- copy.type = 'button'; copy.dataset.revcopy = ''; copy.setAttribute('data-tip', 'Copy the instruction again');
5354
- return [spin, txt, copy];
5682
+ copy.type = 'button'; copy.dataset.revcopy = ''; copy.dataset.commandId = 'shell.revision-request-copy';
5683
+ copy.setAttribute('data-tip', 'Copy the instruction again');
5684
+ return [dot, txt, copy];
5355
5685
  }
5356
5686
  function buildStagedCard(req) {
5357
5687
  // A STATIC dot, not the pending spinner: the read has finished and nothing is in flight. The
@@ -5362,7 +5692,7 @@
5362
5692
  txt.appendChild(document.createTextNode(' Nothing has been applied yet — decide what this read may change.'));
5363
5693
  const actions = revEl('span', 'wrc-actions');
5364
5694
  const review = revEl('button', 'btn-mini', 'Review changes');
5365
- review.type = 'button'; review.dataset.revreview = '';
5695
+ review.type = 'button'; review.dataset.revreview = ''; review.dataset.commandId = 'shell.revision-review-open';
5366
5696
  actions.appendChild(review);
5367
5697
  return [dot, txt, actions];
5368
5698
  }
@@ -5372,12 +5702,38 @@
5372
5702
  txt.appendChild(revEl('b', null, 'The read failed.'));
5373
5703
  txt.appendChild(document.createTextNode(' '));
5374
5704
  txt.appendChild(revEl('span', 'wrc-err-detail', req.error || 'The read could not be completed.'));
5375
- txt.appendChild(document.createTextNode(' Attach the set again to retry.'));
5705
+ const canClear = req.canClear === true;
5706
+ txt.appendChild(document.createTextNode(canClear
5707
+ ? ' Press Dismiss, then attach the set again to retry.'
5708
+ : ` ${req.clearWhy || 'FloLess cannot safely release this drawing read yet.'} Open Requests for the available recovery.`));
5376
5709
  const actions = revEl('span', 'wrc-actions');
5377
- const dismiss = revEl('button', 'btn-mini', 'Dismiss'); dismiss.type = 'button'; dismiss.dataset.revdismiss = '';
5378
- actions.appendChild(dismiss);
5710
+ if (canClear) {
5711
+ const dismiss = revEl('button', 'btn-mini', 'Dismiss'); dismiss.type = 'button'; dismiss.dataset.revdismiss = '';
5712
+ dismiss.dataset.commandId = 'shell.revision-failure-dismiss';
5713
+ actions.appendChild(dismiss);
5714
+ }
5379
5715
  return [ico, txt, actions];
5380
5716
  }
5717
+ function buildUnavailableCard() {
5718
+ const ico = revEl('span', 'wrc-warn-ico', '⚠'); ico.setAttribute('aria-hidden', 'true');
5719
+ const txt = revEl('span', 'wrc-text');
5720
+ txt.appendChild(revEl('b', null, 'This drawing read cannot be shown by this version of FloLess.'));
5721
+ txt.appendChild(document.createTextNode(' Open Requests for details. If the request does not change, update FloLess before continuing.'));
5722
+ return [ico, txt];
5723
+ }
5724
+
5725
+ async function dismissFailedRevision(req) {
5726
+ try { await api(`/api/requests/${encodeURIComponent(req.id)}`, { method: 'DELETE' }); }
5727
+ catch (error) {
5728
+ showToast((error && error.message) || 'FloLess could not dismiss this drawing read.', 'warn');
5729
+ if (bridge.loadRequests) await bridge.loadRequests().catch(() => {});
5730
+ await renderRevisionCard();
5731
+ return;
5732
+ }
5733
+ lastRevState = 'none';
5734
+ if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
5735
+ await renderRevisionCard();
5736
+ }
5381
5737
 
5382
5738
  async function renderRevisionCard() {
5383
5739
  // GENERATION, not just the captured object — the idiom `refreshModelPresence`/`refreshApprovalState`
@@ -5389,6 +5745,10 @@
5389
5745
  const gen = ++revisionGen;
5390
5746
  const proj = current;
5391
5747
  if (!proj) { $revisionCard.hidden = true; return; }
5748
+ // Keep the last known card painted while the request list is reloading. Switching to another
5749
+ // stage and back must not turn a long-running terminal read into a blank strip for the few
5750
+ // seconds before /api/requests answers again.
5751
+ if (currentStep === 'drawings' && revCardReq && lastRevState !== 'none') $revisionCard.hidden = false;
5392
5752
  let reqs = [];
5393
5753
  // ONCE PER OUTAGE, not once per tick. This runs on a 3-second poll, so an unguarded log turns a
5394
5754
  // server restart into a wall of red — the same "every open logs an error" noise #600 was written
@@ -5408,12 +5768,27 @@
5408
5768
  // breadcrumb, mid-poll) or paint the old project's revision state over the newly opened one.
5409
5769
  if (gen !== revisionGen || !current || current.id !== proj.id) return;
5410
5770
  const mine = reqs.filter((r) => r && r.type === 'revision-read' && r.project === proj.id);
5411
- const failed = mine.find((r) => r.status === 'failed');
5412
- const staged = mine.find((r) => r.status === 'staged');
5413
- const pending = mine.find((r) => r.status === 'pending');
5414
- // `failed` first, then `staged`, then `pending` — most-resolved wins, so a project holding both a
5415
- // finished review and a newly queued read shows the one the user can act on.
5416
- const state = failed ? 'failed' : staged ? 'staged' : pending ? 'pending' : 'none';
5771
+ // One project can retain an old failed request after the user follows its recovery instruction and
5772
+ // attaches the set again. The request list is durable oldest-first; the newest lifecycle is the one
5773
+ // this card must follow. Status priority hid the retry behind the old failure and stopped this poll.
5774
+ const activeRequest = mine.reduce((latest, request) => {
5775
+ if (!latest) return request;
5776
+ const latestAt = Date.parse(latest.createdAt || '') || 0;
5777
+ const requestAt = Date.parse(request.createdAt || '') || 0;
5778
+ return requestAt >= latestAt ? request : latest;
5779
+ }, null);
5780
+ const failed = activeRequest && activeRequest.status === 'failed' ? activeRequest : null;
5781
+ const staged = activeRequest && activeRequest.status === 'staged' ? activeRequest : null;
5782
+ const pending = activeRequest && activeRequest.status === 'pending' ? activeRequest : null;
5783
+ // Request files are durable and may have been written by a newer build (or repaired by hand).
5784
+ // Never feed an unvalidated status into the renderer: the pending fallback expects a real pending
5785
+ // request and dereferences it. Keep the unfamiliar request visible and polling in a safe state so
5786
+ // the user gets an explanation instead of a crashed card and stale stage gates.
5787
+ const state = !activeRequest ? 'none'
5788
+ : failed ? 'failed'
5789
+ : staged ? 'staged'
5790
+ : pending ? 'pending'
5791
+ : 'unavailable';
5417
5792
  // Was pending, now nothing in flight. Confirm a NEW version actually committed (the head advanced
5418
5793
  // past the attach baseVersion) before celebrating — a bare request DELETE (Dismiss / footer-clear)
5419
5794
  // must NOT show a false "complete" toast or re-lock exports.
@@ -5458,66 +5833,123 @@
5458
5833
  }
5459
5834
  }
5460
5835
  lastRevState = state;
5461
- if (state === 'none') { stopRevisionPoll(); $revisionCard.hidden = true; $revisionCard.replaceChildren(); return; }
5462
- // `failed` STOPS the poll; `staged` KEEPS it, and the design note that said otherwise rested on an
5463
- // assumption review disproved. It read "staged is resolved and actionable, nothing changes on its
5464
- // own" — true of THIS tab's user, false of the system: a second tab, the footer's Clear all, or a
5465
- // request DELETE removes the request without this tab acting. With the poll stopped there was
5466
- // nothing left to notice, so the card sat offering "Review changes" for a review that no longer
5467
- // existed, and the button led to a 410.
5468
- //
5469
- // The reason the poll was stopped in the first place is real, so it is handled directly instead:
5470
- // a tick must not re-render the card underneath an OPEN review. That is what `revReviewState`
5471
- // guards below — the poll keeps running, and only the repaint waits.
5472
- if (state === 'failed') stopRevisionPoll();
5473
- else if (!revisionPoll) startRevisionPoll(); // a pending read seen on load → keep it fresh
5474
- if (currentStep !== 'drawings') { $revisionCard.hidden = true; return; } // card is Drawings-scoped
5836
+ if (state === 'none') {
5837
+ revCardReq = null;
5838
+ syncDrawingRevisionRequest('');
5839
+ stopRevisionPoll(); $revisionCard.hidden = true; $revisionCard.replaceChildren(); applyStageGating(); return;
5840
+ }
5841
+ // Every durable lifecycle keeps polling until its request disappears. Failed and staged cards can
5842
+ // both change from another tab (Attach again, Clear, or a review action); stopping either interval
5843
+ // leaves this workspace permanently showing the old request because request SSE is owned by the
5844
+ // shell, not this card. `revReviewState` below handles the real repaint risk while a review is open.
5845
+ if (!revisionPoll) startRevisionPoll();
5846
+ // The card is Drawing-Filter-scoped, but its REQUEST STATE is project-scoped. Keep that state and
5847
+ // the already-loaded iframe checkpoint fresh even while the user looks at another stage. Otherwise
5848
+ // returning to Drawing Filter briefly resurrects the old "reading" state and can leave Save filter
5849
+ // unaware that the terminal prepass finished until a later poll happens to repaint the tab.
5850
+ revCardReq = failed || staged || pending || activeRequest;
5851
+ syncDrawingRevisionRequest(pending?.prepassReady && !pending.filterSaved ? pending.id : '');
5852
+ if (currentStep !== 'drawings') { $revisionCard.hidden = true; applyStageGating(); return; } // card is Drawing Filter-scoped
5475
5853
  // A REVIEW IS OPEN — leave the card alone. Repainting it would replace the button focus returns to,
5476
5854
  // and the modal is the authority on this request until it closes. If the request vanished from
5477
5855
  // under it, the modal's own confirm learns that from the server and closes; the next tick then
5478
5856
  // paints the truth.
5479
5857
  if (revReviewState) return;
5480
- revCardReq = failed || staged || pending;
5481
- if (pending?.prepassReady && frames.drawings.dataset.want) {
5482
- const u = new URL(frames.drawings.dataset.want, location.origin);
5483
- if (u.searchParams.get('revisionRequest') !== pending.id) {
5484
- u.searchParams.set('revisionRequest', pending.id);
5485
- frames.drawings.dataset.want = u.pathname + u.search;
5486
- if (frames.drawings.dataset.loaded) frames.drawings.src = frames.drawings.dataset.want;
5487
- }
5488
- }
5489
- const cardKey = `${state}:${revCardReq ? revCardReq.id : ''}:${pending && pending.prepassReady ? 'filter-ready' : 'read-pending'}`;
5858
+ const cardKey = `${state}:${revCardReq ? revCardReq.id : ''}:${pending && pending.filterSaved ? 'filter-saved' : pending && pending.prepassReady ? 'filter-ready' : 'read-pending'}:${pending && pending.run ? pending.run.state || '' : ''}`;
5490
5859
  if ($revisionCard._renderKey === cardKey && !$revisionCard.hidden) return; // preserve focus across the 3 s poll
5491
5860
  const restoreFocus = typeof document !== 'undefined' && $revisionCard.contains(document.activeElement);
5492
5861
  $revisionCard._renderKey = cardKey;
5493
- $revisionCard.className = 'ws-revision-card state-' + state + (pending && pending.prepassReady ? ' state-filter-ready' : '');
5862
+ $revisionCard.className = 'ws-revision-card state-' + state
5863
+ + (pending && pending.filterSaved ? ' state-filter-saved' : pending && pending.prepassReady ? ' state-filter-ready' : '');
5494
5864
  $revisionCard.replaceChildren(...(
5495
5865
  state === 'failed' ? buildFailedCard(failed)
5496
5866
  : state === 'staged' ? buildStagedCard(staged)
5497
- : buildPendingCard(pending)));
5867
+ : state === 'pending' ? buildPendingCard(pending)
5868
+ : buildUnavailableCard()));
5498
5869
  $revisionCard.hidden = false;
5870
+ applyStageGating();
5499
5871
  if (restoreFocus) $revisionCard.querySelector('button')?.focus();
5500
5872
  }
5501
5873
 
5874
+ /** Keep the request checkpoint in the already-open Drawing Filter without navigating away edits. */
5875
+ function syncDrawingRevisionRequest(targetRequest) {
5876
+ const frame = frames.drawings;
5877
+ if (!frame?.dataset.want) return;
5878
+ const requestId = String(targetRequest || '');
5879
+ const wanted = new URL(frame.dataset.want, location.origin);
5880
+ if (requestId) wanted.searchParams.set('revisionRequest', requestId);
5881
+ else wanted.searchParams.delete('revisionRequest');
5882
+ frame.dataset.want = wanted.pathname + wanted.search;
5883
+ if (!frame.dataset.loaded) return;
5884
+ try {
5885
+ const checkpoint = frame.contentWindow?.__floRevisionCheckpoint;
5886
+ if (checkpoint && typeof checkpoint.setRequest === 'function') {
5887
+ checkpoint.setRequest(requestId);
5888
+ return;
5889
+ }
5890
+ const shown = new URL(frame.contentWindow.location.href);
5891
+ if ((shown.searchParams.get('revisionRequest') || '') === requestId) return;
5892
+ } catch { /* not ready or not same-origin yet — navigate to the authoritative target below */ }
5893
+ frame.src = frame.dataset.want;
5894
+ }
5895
+
5896
+ function focusDrawingFilterSave() {
5897
+ const frame = frames.drawings;
5898
+ if (!frame) return;
5899
+ let onLoad;
5900
+ const focusSave = () => {
5901
+ try {
5902
+ const shown = new URL(frame.contentWindow.location.href);
5903
+ const wanted = new URL(frame.dataset.want, location.origin);
5904
+ if (shown.pathname !== wanted.pathname || shown.search !== wanted.search) return false;
5905
+ const doc = frame.contentDocument;
5906
+ const save = doc?.getElementById('save');
5907
+ if (!save) return false;
5908
+ // A disabled button cannot receive focus. When the Filter still has no selected drawing
5909
+ // lines, focus the live required-step sentence instead so "Open Drawing Filter" lands on
5910
+ // the exact action the detailer must take, rather than silently leaving focus behind.
5911
+ const target = save.disabled ? doc.getElementById('saveRequiredStatus') : save;
5912
+ if (!target || target.hidden) return false;
5913
+ target.focus();
5914
+ if (onLoad) frame.removeEventListener('load', onLoad);
5915
+ return true;
5916
+ } catch { return false; }
5917
+ };
5918
+ onLoad = () => requestAnimationFrame(() => { if (!focusSave()) frame.focus(); });
5919
+ frame.addEventListener('load', onLoad, { once: true });
5920
+ if (!focusSave()) frame.focus();
5921
+ }
5922
+
5923
+ async function copyRevisionCardRequest(req, copyButton) {
5924
+ const copyProject = current;
5925
+ const copyGeneration = revisionOwnerGen;
5926
+ const copyRenderKey = $revisionCard._renderKey;
5927
+ const ownsCopy = () => current === copyProject
5928
+ && revisionOwnerGen === copyGeneration
5929
+ && revCardReq?.id === req.id
5930
+ && $revisionCard._renderKey === copyRenderKey
5931
+ && !!copyButton?.isConnected;
5932
+ // "no instruction body" must not be reported as "copy blocked": that sends the user to the
5933
+ // Requests panel, where the ⧉ gives the real reason and contradicts this toast.
5934
+ const res = await bridge.copyRequest(req, ownsCopy);
5935
+ if (res === 'stale' || !ownsCopy()) return;
5936
+ if (res === 'ok') showToast('Instruction copied', 'ok');
5937
+ else if (res === 'empty') showToast('Nothing to copy — this request has no instruction', 'err');
5938
+ else showToast('Copy blocked — use the Requests panel', 'warn');
5939
+ }
5940
+
5502
5941
  $revisionCard.addEventListener('click', async (e) => {
5503
5942
  const req = revCardReq;
5504
5943
  if (!req) return;
5505
5944
  if (e.target.closest('[data-revreview]')) {
5506
5945
  openRevisionReview(req);
5507
5946
  } else if (e.target.closest('[data-revcopy]') && bridge.copyRequest) {
5508
- // "no instruction body" must not be reported as "copy blocked": that sends the user to the
5509
- // Requests panel, where the ⧉ gives the real reason and contradicts this toast.
5510
- const res = await bridge.copyRequest(req);
5511
- if (res === 'ok') showToast('Instruction copied', 'ok');
5512
- else if (res === 'empty') showToast('Nothing to copy — this request has no instruction', 'err');
5513
- else showToast('Copy blocked — use the Requests panel', 'warn');
5947
+ const copyButton = e.target.closest('[data-revcopy]');
5948
+ await copyRevisionCardRequest(req, copyButton);
5514
5949
  } else if (e.target.closest('[data-revfilter]')) {
5515
- frames.drawings?.focus();
5950
+ focusDrawingFilterSave();
5516
5951
  } else if (e.target.closest('[data-revdismiss]')) {
5517
- try { await api(`/api/requests/${encodeURIComponent(req.id)}`, { method: 'DELETE' }); } catch { /* already gone */ }
5518
- lastRevState = 'none';
5519
- if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
5520
- renderRevisionCard();
5952
+ await dismissFailedRevision(req);
5521
5953
  }
5522
5954
  });
5523
5955
 
@@ -6216,7 +6648,15 @@
6216
6648
  function savedWorkHtml(checkpoints, unavailable) {
6217
6649
  let body;
6218
6650
  if (unavailable) {
6219
- body = '<div class="saved-work-state warn" role="status">Saved work unavailable — retry by reopening History.</div>';
6651
+ // Two very different unavailables, and only one of them is worth retrying. `/checkpoints`
6652
+ // refuses a project with no incarnation on the same standing condition approval does, so
6653
+ // "retry by reopening History" is an instruction that can never succeed — the Exports pane had
6654
+ // the identical false invitation above its gate (#574). The refusal is already stated in the
6655
+ // banner at the top of History, so this says what Saved work itself can never hold and stops
6656
+ // there, rather than repeating the sentence or inviting a pointless retry.
6657
+ body = approvalRefusalNote()
6658
+ ? '<div class="saved-work-state" role="status">Checkpoints are kept per project identity, so this project has none.</div>'
6659
+ : '<div class="saved-work-state warn" role="status">Saved work unavailable — retry by reopening History.</div>';
6220
6660
  } else if (!checkpoints.length) {
6221
6661
  body = '<div class="saved-work-state">No saved work yet. FloLess saves a checkpoint before you switch away from pending edits.</div>';
6222
6662
  } else {
@@ -6238,11 +6678,31 @@
6238
6678
  const id = current.id;
6239
6679
  closeBaseMenu(); // this re-render replaces the History HTML — drop any open base-picker's listener first
6240
6680
  $wsHistory.innerHTML = '<div class="hist-note">Loading history…</div>';
6681
+ await awaitApprovalVerdict();
6682
+ if (!current || current.id !== id || $wsHistory.hidden) return; // switched away while it settled
6241
6683
  let rows = [];
6242
6684
  let approvedAt;
6243
6685
  let nextDiffSupported = false;
6244
6686
  let nextDiffEligibleVersions = null;
6245
- const checkpointPromise = api(`/api/projects/${encodeURIComponent(id)}/checkpoints`);
6687
+ // The rejection handler is attached HERE, at creation, not at the `await` further down.
6688
+ //
6689
+ // The two requests are deliberately concurrent, but the handler used to go on only after
6690
+ // `/versions` had settled — so whenever `/checkpoints` rejected FIRST, its rejection crossed a
6691
+ // microtask checkpoint with nobody listening and the browser logged it as an uncaught error. It
6692
+ // never showed while `/checkpoints` only failed for transient reasons (rare, and usually slower
6693
+ // than `/versions`); a project with no incarnation makes it refuse INSTANTLY and every time, so
6694
+ // History was quietly printing to the console the very red line #574 exists to get rid of.
6695
+ // Settling to a tagged value instead of leaving it raw keeps the two outcomes explicit and means
6696
+ // no later reader can re-open the same hole by moving an await.
6697
+ // Not asked at all when the project is refused — `/checkpoints` refuses on the same standing
6698
+ // condition, and the browser logs every non-2xx whatever the page does with it. The wait above
6699
+ // is what makes the test trustworthy: without it a project restored straight onto History asks
6700
+ // while the verdict is still `loading`, gets its 409, and logs the very line this removes.
6701
+ // See the matching skip in `renderExports`.
6702
+ const checkpointPromise = approvalRefusalNote()
6703
+ ? Promise.resolve({ saved: null })
6704
+ : api(`/api/projects/${encodeURIComponent(id)}/checkpoints`)
6705
+ .then((saved) => ({ saved }), () => ({ saved: null }));
6246
6706
  let checkpoints = [];
6247
6707
  let checkpointsUnavailable = false;
6248
6708
  try {
@@ -6253,17 +6713,16 @@
6253
6713
  nextDiffEligibleVersions = hasOwnField(r, 'diffEligibleVersions') ? r.diffEligibleVersions : null;
6254
6714
  approvedAt = r.approvedAt || undefined;
6255
6715
  } catch (err) {
6256
- await checkpointPromise.catch(() => null);
6716
+ await checkpointPromise; // already settled to a tagged value — drained so it cannot outlive this render
6257
6717
  showToast('Couldn’t load history: ' + ((err && err.message) || err), 'warn');
6258
6718
  if (current && current.id === id && !$wsHistory.hidden) {
6259
6719
  $wsHistory.innerHTML = '<div class="hist-empty">History unavailable — try again.</div>';
6260
6720
  }
6261
6721
  return;
6262
6722
  }
6263
- try {
6264
- const saved = await checkpointPromise;
6265
- checkpoints = Array.isArray(saved.checkpoints) ? saved.checkpoints : [];
6266
- } catch { checkpointsUnavailable = true; }
6723
+ const { saved } = await checkpointPromise;
6724
+ if (saved === null) checkpointsUnavailable = true;
6725
+ else checkpoints = Array.isArray(saved.checkpoints) ? saved.checkpoints : [];
6267
6726
  if (!current || current.id !== id || $wsHistory.hidden) return; // switched away mid-await
6268
6727
  histDiffSupported = nextDiffSupported;
6269
6728
  histDiffEligibleVersions = nextDiffEligibleVersions;
@@ -6292,7 +6751,14 @@
6292
6751
  applyModelPresence(hasModel); // one answer, every surface — History used to keep its own
6293
6752
  const empty = document.createElement('div');
6294
6753
  empty.className = 'hist-empty';
6295
- if (hasModel === 'model') {
6754
+ const emptyRefusal = approvalRefusalNote();
6755
+ if (emptyRefusal) {
6756
+ // FIRST, because the branch below is the one that lies for a refused project: it points at
6757
+ // "Review & approve in the project header" to create v1, and on a project with no
6758
+ // incarnation that control is permanently a disabled "Review unavailable". A ledger that
6759
+ // will never gain a row should say why, not name the button that cannot add one.
6760
+ empty.append(emptyRefusal);
6761
+ } else if (hasModel === 'model') {
6296
6762
  empty.append('No approved versions yet. Review the model, then use Review & approve in the project header to create ');
6297
6763
  const v1 = document.createElement('b');
6298
6764
  v1.textContent = 'v1';
@@ -6314,7 +6780,14 @@
6314
6780
  // rollback) surface it honestly ABOVE the table (not as a fake row) and name the Exports lock.
6315
6781
  const headKind = rows.length && rows[0].current ? rows[0].kind : undefined;
6316
6782
  const headIsInitialRead = headKind === 'revision-read' && Number(rows[0].n) <= 1;
6317
- const working = approvalState.status === 'ready' && approvalState.pendingCount > 0
6783
+ // A refused project takes the banner FIRST. Its working copy genuinely is unsigned, but the
6784
+ // pending-changes wording below is unreachable for it (that branch needs `status === 'ready'`),
6785
+ // so History would otherwise print the immutability note and the table with nothing at all
6786
+ // saying why sign-off never happens — silence in the one place a reader goes to ask.
6787
+ const historyRefusal = approvalRefusalNote();
6788
+ const working = historyRefusal
6789
+ ? `<div class="hist-working">● <b>Not signed off.</b> ${escapeHtml(historyRefusal)}</div>`
6790
+ : approvalState.status === 'ready' && approvalState.pendingCount > 0
6318
6791
  ? (headKind === 'revision-read'
6319
6792
  ? `<div class="hist-working">● <b>The AI read ${headIsInitialRead ? 'the initial' : 'a revised'} drawing set — review it before signing.</b> ` +
6320
6793
  `Open <b>${escapeHtml(stepLabel('model'))}</b> to check the change, then use Review & approve in the project header. Exports keep using ${approvalState.headVersion ? `approved v${approvalState.headVersion}` : 'an explicitly selected DRAFT'}.</div>`