@floless/app 0.134.0 → 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
@@ -1681,6 +1685,12 @@
1681
1685
  return;
1682
1686
  }
1683
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;
1684
1694
  exportState = null;
1685
1695
  hostReadinessStates = {};
1686
1696
  renderReadinessState = null;
@@ -1699,6 +1709,9 @@
1699
1709
  // the 'model' frame loads the app's editor; the 'drawings' frame loads its filter (steel) OR is
1700
1710
  // left empty when the app has no filter step (vectorize — its Source step shows a placeholder).
1701
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
+ }
1702
1715
  // The LIVE app id, deliberately: the frames address the server with it (contract reads, saves),
1703
1716
  // and after a rename only the live id resolves. Only the descriptor came from the lineage root.
1704
1717
  const qs = `?app=${encodeURIComponent(p.app)}&project=${encodeURIComponent(p.id)}`;
@@ -1720,7 +1733,10 @@
1720
1733
  // this line sees a probe to park on. The waiter is deliberately NOT taught to block on a
1721
1734
  // not-yet-started probe — that would hang any surface rendered outside a project open.
1722
1735
  refreshApprovalState(p.id).catch((e) => console.error('[workspaces] could not load approval state', e));
1723
- setStep(initialStep);
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);
1724
1740
  applyMode();
1725
1741
  syncWorkspaceGuide(); // point the shared beacon at THIS project's document lifecycle
1726
1742
  // Detached, but never silent: the lifecycle probe cannot reject, yet the code after its await can
@@ -1746,7 +1762,14 @@
1746
1762
  const gen = ++modelPresenceGen;
1747
1763
  const present = await projectContractState(projectId, appId);
1748
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;
1749
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);
1750
1773
  }
1751
1774
 
1752
1775
  /** Push the answer to the flag AND the header together, so no two surfaces can disagree. */
@@ -1754,6 +1777,7 @@
1754
1777
  projectContractLifecycle = present;
1755
1778
  exportsHasModel = present === 'model';
1756
1779
  renderApprovalHeader();
1780
+ applyStageGating();
1757
1781
  }
1758
1782
  function closeProject() {
1759
1783
  current = null;
@@ -1779,7 +1803,7 @@
1779
1803
  // was already per-project, the two variables behind it were not.)
1780
1804
  // Reset with the rest of the per-project state — this file resets `histDiffSupported` for exactly
1781
1805
  // this reason. Bumping the generation also voids any probe still in flight for the closing project.
1782
- projectContractLifecycle = 'unknown'; exportsHasModel = false; modelPresenceGen++;
1806
+ projectContractLifecycle = 'unknown'; exportsHasModel = false; modelPresenceGen++; pendingPresenceStep = null;
1783
1807
  closeProjMenu(); applyMode(); syncWorkspaceGuide(); // revision state cleared by resetRevisionState() above
1784
1808
  }
1785
1809
  document.getElementById('ws-back').addEventListener('click', closeProject);
@@ -1794,11 +1818,129 @@
1794
1818
  const byKey = new Map(d.steps.map((st) => [st.key, st.label]));
1795
1819
  $stepTabs.querySelectorAll('button[data-step]').forEach((b) => {
1796
1820
  const label = byKey.get(b.dataset.step);
1797
- if (label) b.textContent = label;
1821
+ if (label) {
1822
+ b.textContent = label;
1823
+ b.setAttribute('data-command-id', `shell.workspace-step#${label}`);
1824
+ }
1798
1825
  });
1799
1826
  }
1800
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
+
1801
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
+ }
1802
1944
  currentStep = s;
1803
1945
  $stepTabs.querySelectorAll('button').forEach((b) => {
1804
1946
  const on = b.dataset.step === s;
@@ -1837,10 +1979,24 @@
1837
1979
  // in-flight preview read), and forget the cached state so re-entering re-reads rather than
1838
1980
  // flashing a stale column.
1839
1981
  else { stopKnowledgePoll(); kbCloseConfirm(); kbResetViewer(); knowledgeState = null; }
1982
+ applyStageGating();
1840
1983
  }
1841
1984
  $stepTabs.addEventListener('click', (e) => {
1842
1985
  const b = e.target.closest('button[data-step]');
1843
- 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
+ }
1844
2000
  });
1845
2001
 
1846
2002
  // ── Approve (per-project) ───────────────────────────────────────────────────
@@ -5371,7 +5527,9 @@
5371
5527
  let revBaseProject = null; // …and WHICH project it was captured in; a baseline means nothing anywhere else
5372
5528
  let revCardReq = null;
5373
5529
  let revisionPoll = null;
5374
- 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
5375
5533
  let revRequestsFailed = false; // one log per outage, not one per 3-second poll tick
5376
5534
  /**
5377
5535
  * Every piece of revision state above is PER-PROJECT, so opening or closing one must clear all of
@@ -5399,6 +5557,7 @@
5399
5557
  revCardReq = null;
5400
5558
  $revisionCard._renderKey = '';
5401
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
5402
5561
  stopRevisionPoll();
5403
5562
  $revisionCard.hidden = true;
5404
5563
  $revisionCard.replaceChildren();
@@ -5425,28 +5584,40 @@
5425
5584
  });
5426
5585
  }
5427
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
+
5428
5597
  async function attachRevision(files) {
5429
5598
  const proj = current; // capture — the user may switch projects during the async file reads / POST
5430
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;
5431
5605
  const returnFocus = document.activeElement;
5432
5606
  let snapshots;
5433
5607
  try { snapshots = await Promise.all(files.map(readFileAsSnapshot)); }
5434
5608
  catch { showToast('Could not read the selected files', 'warn'); return; }
5435
- 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
5436
5610
  let res;
5437
5611
  try {
5438
5612
  res = await api(`/api/projects/${encodeURIComponent(proj.id)}/revision-requests`, {
5439
5613
  method: 'POST', body: JSON.stringify({ appId: proj.app, snapshots }),
5440
5614
  });
5441
- } 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; }
5442
5616
  const req = res && res.request;
5443
5617
  // Copy the paste-ready instruction so the user can hand it to their terminal AI (best-effort).
5444
- let copied = false;
5445
- if (req && bridge.copyRequest) {
5446
- try { copied = (await bridge.copyRequest(req)) === 'ok'; } catch { copied = false; }
5447
- }
5618
+ const copied = await copyAttachedRevision(req, ownsAttach);
5448
5619
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {}); // refresh the footer Requests popover
5449
- 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
5450
5621
  revBaseVersion = (req && typeof req.baseVersion === 'number') ? req.baseVersion : 0;
5451
5622
  revBaseProject = proj.id; // the baseline belongs to THIS project — see resetRevisionState
5452
5623
  showToast(`${revBaseVersion <= 0 ? 'Initial' : 'Revised'} set queued — ${files.length} file${files.length > 1 ? 's' : ''} for your terminal AI`, 'ok');
@@ -5465,25 +5636,52 @@
5465
5636
 
5466
5637
  function buildPendingCard(req) {
5467
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
+ }
5468
5646
  if (req.prepassReady) {
5469
5647
  // The terminal AI has completed the deterministic pre-read; it is now waiting on the real Filter
5470
5648
  // Save checkpoint below, not on another pasted instruction. A static dot avoids claiming work is
5471
5649
  // still running, and the real action only focuses the existing Filter iframe — it never fakes Save.
5472
5650
  const dot = revEl('span', 'wrc-dot'); dot.setAttribute('aria-hidden', 'true');
5473
5651
  const txt = revEl('span', 'wrc-text');
5474
- txt.appendChild(revEl('b', null, 'Steel Filter is ready.'));
5475
- txt.appendChild(document.createTextNode(' Review the Steel Filter and Save to continue the read.'));
5476
- const review = revEl('button', 'btn-mini', 'Review Filter');
5477
- 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');
5478
5657
  return [dot, txt, review];
5479
5658
  }
5480
- 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');
5481
5672
  const txt = revEl('span', 'wrc-text');
5482
- txt.appendChild(revEl('b', null, `Reading the ${isInitialRevisionRead(req) ? 'initial' : 'revised'} set…`));
5483
- 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.`));
5484
5681
  const copy = revEl('button', 'btn-mini', '⧉ Copy');
5485
- copy.type = 'button'; copy.dataset.revcopy = ''; copy.setAttribute('data-tip', 'Copy the instruction again');
5486
- 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];
5487
5685
  }
5488
5686
  function buildStagedCard(req) {
5489
5687
  // A STATIC dot, not the pending spinner: the read has finished and nothing is in flight. The
@@ -5494,7 +5692,7 @@
5494
5692
  txt.appendChild(document.createTextNode(' Nothing has been applied yet — decide what this read may change.'));
5495
5693
  const actions = revEl('span', 'wrc-actions');
5496
5694
  const review = revEl('button', 'btn-mini', 'Review changes');
5497
- review.type = 'button'; review.dataset.revreview = '';
5695
+ review.type = 'button'; review.dataset.revreview = ''; review.dataset.commandId = 'shell.revision-review-open';
5498
5696
  actions.appendChild(review);
5499
5697
  return [dot, txt, actions];
5500
5698
  }
@@ -5504,12 +5702,38 @@
5504
5702
  txt.appendChild(revEl('b', null, 'The read failed.'));
5505
5703
  txt.appendChild(document.createTextNode(' '));
5506
5704
  txt.appendChild(revEl('span', 'wrc-err-detail', req.error || 'The read could not be completed.'));
5507
- 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.`));
5508
5709
  const actions = revEl('span', 'wrc-actions');
5509
- const dismiss = revEl('button', 'btn-mini', 'Dismiss'); dismiss.type = 'button'; dismiss.dataset.revdismiss = '';
5510
- 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
+ }
5511
5715
  return [ico, txt, actions];
5512
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
+ }
5513
5737
 
5514
5738
  async function renderRevisionCard() {
5515
5739
  // GENERATION, not just the captured object — the idiom `refreshModelPresence`/`refreshApprovalState`
@@ -5521,6 +5745,10 @@
5521
5745
  const gen = ++revisionGen;
5522
5746
  const proj = current;
5523
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;
5524
5752
  let reqs = [];
5525
5753
  // ONCE PER OUTAGE, not once per tick. This runs on a 3-second poll, so an unguarded log turns a
5526
5754
  // server restart into a wall of red — the same "every open logs an error" noise #600 was written
@@ -5540,12 +5768,27 @@
5540
5768
  // breadcrumb, mid-poll) or paint the old project's revision state over the newly opened one.
5541
5769
  if (gen !== revisionGen || !current || current.id !== proj.id) return;
5542
5770
  const mine = reqs.filter((r) => r && r.type === 'revision-read' && r.project === proj.id);
5543
- const failed = mine.find((r) => r.status === 'failed');
5544
- const staged = mine.find((r) => r.status === 'staged');
5545
- const pending = mine.find((r) => r.status === 'pending');
5546
- // `failed` first, then `staged`, then `pending` — most-resolved wins, so a project holding both a
5547
- // finished review and a newly queued read shows the one the user can act on.
5548
- 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';
5549
5792
  // Was pending, now nothing in flight. Confirm a NEW version actually committed (the head advanced
5550
5793
  // past the attach baseVersion) before celebrating — a bare request DELETE (Dismiss / footer-clear)
5551
5794
  // must NOT show a false "complete" toast or re-lock exports.
@@ -5590,66 +5833,123 @@
5590
5833
  }
5591
5834
  }
5592
5835
  lastRevState = state;
5593
- if (state === 'none') { stopRevisionPoll(); $revisionCard.hidden = true; $revisionCard.replaceChildren(); return; }
5594
- // `failed` STOPS the poll; `staged` KEEPS it, and the design note that said otherwise rested on an
5595
- // assumption review disproved. It read "staged is resolved and actionable, nothing changes on its
5596
- // own" — true of THIS tab's user, false of the system: a second tab, the footer's Clear all, or a
5597
- // request DELETE removes the request without this tab acting. With the poll stopped there was
5598
- // nothing left to notice, so the card sat offering "Review changes" for a review that no longer
5599
- // existed, and the button led to a 410.
5600
- //
5601
- // The reason the poll was stopped in the first place is real, so it is handled directly instead:
5602
- // a tick must not re-render the card underneath an OPEN review. That is what `revReviewState`
5603
- // guards below — the poll keeps running, and only the repaint waits.
5604
- if (state === 'failed') stopRevisionPoll();
5605
- else if (!revisionPoll) startRevisionPoll(); // a pending read seen on load → keep it fresh
5606
- 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
5607
5853
  // A REVIEW IS OPEN — leave the card alone. Repainting it would replace the button focus returns to,
5608
5854
  // and the modal is the authority on this request until it closes. If the request vanished from
5609
5855
  // under it, the modal's own confirm learns that from the server and closes; the next tick then
5610
5856
  // paints the truth.
5611
5857
  if (revReviewState) return;
5612
- revCardReq = failed || staged || pending;
5613
- if (pending?.prepassReady && frames.drawings.dataset.want) {
5614
- const u = new URL(frames.drawings.dataset.want, location.origin);
5615
- if (u.searchParams.get('revisionRequest') !== pending.id) {
5616
- u.searchParams.set('revisionRequest', pending.id);
5617
- frames.drawings.dataset.want = u.pathname + u.search;
5618
- if (frames.drawings.dataset.loaded) frames.drawings.src = frames.drawings.dataset.want;
5619
- }
5620
- }
5621
- 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 || '' : ''}`;
5622
5859
  if ($revisionCard._renderKey === cardKey && !$revisionCard.hidden) return; // preserve focus across the 3 s poll
5623
5860
  const restoreFocus = typeof document !== 'undefined' && $revisionCard.contains(document.activeElement);
5624
5861
  $revisionCard._renderKey = cardKey;
5625
- $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' : '');
5626
5864
  $revisionCard.replaceChildren(...(
5627
5865
  state === 'failed' ? buildFailedCard(failed)
5628
5866
  : state === 'staged' ? buildStagedCard(staged)
5629
- : buildPendingCard(pending)));
5867
+ : state === 'pending' ? buildPendingCard(pending)
5868
+ : buildUnavailableCard()));
5630
5869
  $revisionCard.hidden = false;
5870
+ applyStageGating();
5631
5871
  if (restoreFocus) $revisionCard.querySelector('button')?.focus();
5632
5872
  }
5633
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
+
5634
5941
  $revisionCard.addEventListener('click', async (e) => {
5635
5942
  const req = revCardReq;
5636
5943
  if (!req) return;
5637
5944
  if (e.target.closest('[data-revreview]')) {
5638
5945
  openRevisionReview(req);
5639
5946
  } else if (e.target.closest('[data-revcopy]') && bridge.copyRequest) {
5640
- // "no instruction body" must not be reported as "copy blocked": that sends the user to the
5641
- // Requests panel, where the ⧉ gives the real reason and contradicts this toast.
5642
- const res = await bridge.copyRequest(req);
5643
- if (res === 'ok') showToast('Instruction copied', 'ok');
5644
- else if (res === 'empty') showToast('Nothing to copy — this request has no instruction', 'err');
5645
- else showToast('Copy blocked — use the Requests panel', 'warn');
5947
+ const copyButton = e.target.closest('[data-revcopy]');
5948
+ await copyRevisionCardRequest(req, copyButton);
5646
5949
  } else if (e.target.closest('[data-revfilter]')) {
5647
- frames.drawings?.focus();
5950
+ focusDrawingFilterSave();
5648
5951
  } else if (e.target.closest('[data-revdismiss]')) {
5649
- try { await api(`/api/requests/${encodeURIComponent(req.id)}`, { method: 'DELETE' }); } catch { /* already gone */ }
5650
- lastRevState = 'none';
5651
- if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
5652
- renderRevisionCard();
5952
+ await dismissFailedRevision(req);
5653
5953
  }
5654
5954
  });
5655
5955