@floless/app 0.152.0 → 0.153.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@
7
7
  view and sends ONE thing back: the person's click, naming the batch it
8
8
  showed. Every string shown is the server's, set with textContent.
9
9
 
10
- States: a pill only when something is offered or needs the person; the
10
+ States: a pill only when something is offered, needs the person, or a check started from this page is still running; the
11
11
  dialog lists "Ready to approve" cards, "Needs you" rows, the downloads
12
12
  line and the consequence footnote; after the click, the results replace
13
13
  the cards in a live region.
@@ -18,6 +18,10 @@
18
18
  been on it. It asks for that at most once a second (a slow answer skips a
19
19
  tick) and only while the dialog is open and a check is running; those
20
20
  answers are shown, never applied as the view.
21
+
22
+ A running check never holds the person in the dialog (#2143): Esc and the cancel button (it reads "Close" while a check
23
+ runs, "Not now" otherwise) leave it, the check goes on in the server, and the footer pill says so until the Check
24
+ request this page sent is answered. Only an approval locks the dialog.
21
25
  ────────────────────────────────────────────────────────────────────────── */
22
26
  (function () {
23
27
  'use strict';
@@ -65,9 +69,14 @@
65
69
  view = Object.assign({}, view, { cleanup: next });
66
70
  return true;
67
71
  }
68
- var busy = false;
69
- var checking = false; // the Check for updates request is in flight
72
+ var approving = false; // an approval is running: the one thing that holds the dialog, because its results are shown only here
73
+ var checking = false; // the Check for updates request is in flight; the person may close the dialog meanwhile
74
+ var checkController = null; // cancels that request when its answer never comes back
75
+ var answerLost = false; // that request was given up on
76
+ var quietAsks = 0; // progress answers in a row saying nothing runs while the Check request is still unanswered
70
77
  var returnFocus = null;
78
+ var PILL_TIP = $pill.getAttribute('data-tip');
79
+ var LOST_ANSWER_AFTER_QUIET_ASKS = 3; // three idle progress answers in a row (about 1 s apart): the answer to the Check request is taken as lost
71
80
 
72
81
  // ── A running check, as the server describes it ───────────────────────────────────────────────────────────
73
82
  // The clock is deliberately here although the headless-run styling avoids one (web/app.css, "Headless runs (#571
@@ -90,7 +99,8 @@
90
99
  var POLL_PATIENCE_MS = 6000;
91
100
 
92
101
  function checkInFlight() { return checking || !!(view && view.checking); }
93
- function checkRunning() { return $modal.classList.contains('show') && checkInFlight(); }
102
+ function isOpen() { return $modal.classList.contains('show'); }
103
+ function checkRunning() { return isOpen() && checkInFlight(); }
94
104
 
95
105
  function elapsedText(seconds) {
96
106
  var nb = '\u00a0'; // never wraps between the number and its unit
@@ -162,6 +172,8 @@
162
172
  });
163
173
  $progress.appendChild(list);
164
174
  }
175
+ // Not while contact is lost: the page cannot say then that the check keeps going.
176
+ if (!lostContact) $progress.appendChild(el('div', 'tool-updates-progress-hint', 'You can close this dialog. The check keeps going, and what it finds shows at the bottom of the screen.'));
165
177
  paintedSteps = signature;
166
178
  }
167
179
  announce(steps);
@@ -192,8 +204,11 @@
192
204
  // is queued behind another has no steps yet: the old ones go with it rather than freeze with a running clock.
193
205
  if (body.checking) {
194
206
  progress = body.progress || null;
207
+ quietAsks = 0;
195
208
  } else {
196
209
  progress = null; // nothing is running: no steps, and no clock counting on one
210
+ // The server has said "idle" three times running yet the Check request is unanswered: its answer is taken as lost, not late.
211
+ if (checking && ++quietAsks >= LOST_ANSWER_AFTER_QUIET_ASKS && checkController) { answerLost = true; checkController.abort(); }
197
212
  // A check that ended without this page asking (a background one): the page reads the view and repaints, one read at a time.
198
213
  if (!checking && !rereading) {
199
214
  rereading = true;
@@ -256,7 +271,10 @@
256
271
 
257
272
  async function call(path, method, payload, signal) {
258
273
  var res = await fetch(path, { method: method || 'GET', headers: { 'content-type': 'application/json' }, body: payload, signal: signal });
259
- var body = await res.json().catch(function () { return { ok: false, error: 'FloLess received an unreadable answer (HTTP ' + res.status + ').' }; });
274
+ var body = await res.json().catch(function (error) {
275
+ if (error && error.name === 'AbortError') throw error; // the page gave this request up: not "an unreadable answer"
276
+ return { ok: false, error: 'FloLess received an unreadable answer (HTTP ' + res.status + ').' };
277
+ });
260
278
  if (!res.ok && body.ok !== true && !body.results) {
261
279
  var error = new Error(body.error || ('HTTP ' + res.status));
262
280
  error.body = body;
@@ -277,10 +295,13 @@
277
295
  var needs = view && view.supported ? view.needsYou || [] : [];
278
296
  var cleanup = cleanupNeeds();
279
297
  var urgent = offers.filter(function (o) { return !!o.advisory; }).length;
280
- if (!offers.length && !needs.length && !cleanup.length) {
298
+ // Only a check this page started: a background pass is not something the person is waiting for.
299
+ if (!offers.length && !needs.length && !cleanup.length && !checking) {
300
+ // A pill that disappears under the keyboard's focus must not drop focus to the page behind.
301
+ if (document.activeElement === $pill) { var menu = document.getElementById('menu-btn'); if (menu) menu.focus(); }
281
302
  $pill.hidden = true;
282
303
  $pill.removeAttribute('data-state');
283
- if ($modal.classList.contains('show') && !results) paint();
304
+ if (isOpen() && !results) paint();
284
305
  return;
285
306
  }
286
307
  var text;
@@ -296,18 +317,25 @@
296
317
  var days = Math.max.apply(null, offers.map(function (o) { return o.waitingDays || 0; }));
297
318
  text += ' · waiting ' + plural(days, 'day', 'days');
298
319
  }
299
- } else {
320
+ } else if (needs.length || cleanup.length) {
300
321
  state = 'needs';
301
322
  var folders = cleanup.filter(function (c) { return c.kind !== 'unreadable'; }).length;
302
323
  if (needs.length && cleanup.length) text = (needs.length + cleanup.length) + ' things need you';
303
324
  else if (needs.length) text = plural(needs.length, 'workflow needs you', 'workflows need you');
304
325
  else if (folders === cleanup.length) text = plural(folders, 'folder needs you', 'folders need you');
305
326
  else text = plural(cleanup.length, 'item needs you', 'items need you');
327
+ } else {
328
+ state = 'checking';
329
+ text = 'Checking for tool updates…';
306
330
  }
331
+ // Something to act on keeps its wording and colour; a running check is added to it, not put in its place.
332
+ if (checking && state !== 'checking') text += ' · checking…';
307
333
  $pill.textContent = text;
308
334
  $pill.setAttribute('data-state', state);
335
+ $pill.setAttribute('data-tip', !checking ? PILL_TIP : state === 'checking'
336
+ ? 'Still checking for tool updates. Open to watch it.' : PILL_TIP + '. A check is also running.');
309
337
  $pill.hidden = false;
310
- if ($modal.classList.contains('show') && !busy && !results) paint();
338
+ if (isOpen() && !approving && !results) paint();
311
339
  }
312
340
 
313
341
  // ── The dialog ─────────────────────────────────────────────────────────────
@@ -387,7 +415,7 @@
387
415
  var busyHere = forgetting === item.path;
388
416
  var button = el('button', 'tool-updates-open', busyHere ? 'Removing…' : 'Remove from list');
389
417
  button.type = 'button';
390
- button.disabled = busyHere || busy;
418
+ lock(button, forgetReason());
391
419
  button.setAttribute('data-command-id', 'shell.tool-updates-forget-folder');
392
420
  button.setAttribute('data-tip', 'Stop keeping old tool versions for the workflows in this folder');
393
421
  button.setAttribute('aria-label', 'Remove ' + (item.name || item.path) + ' from the list');
@@ -398,7 +426,7 @@
398
426
  }
399
427
 
400
428
  async function forgetFolder(item) {
401
- if (busy || forgetting) return;
429
+ if (approving || checking || forgetting) return;
402
430
  var path = item.path;
403
431
  var ok = false;
404
432
  forgetting = path;
@@ -586,27 +614,42 @@
586
614
  $approve.hidden = !canApprove;
587
615
  if (canApprove) $approve.textContent = 'Approve ' + plural(offers.length, 'workflow', 'workflows');
588
616
  $check.hidden = !!results || !(view && view.supported);
589
- $cancel.textContent = results ? 'Done' : 'Not now';
617
+ // "Not now" would read as cancelling the check, which closing the dialog does not do.
618
+ $cancel.textContent = results ? 'Done' : checkInFlight() ? 'Close' : 'Not now';
590
619
  }
591
620
 
592
- function setBusy(on, label) {
593
- busy = on;
594
- // Not while a check runs: a busy dialog can make a screen reader hold back the step announcements inside it.
595
- $modal.setAttribute('aria-busy', on && !checking ? 'true' : 'false');
596
- [$check, $cancel, $approve].forEach(function (b) { b.disabled = on; });
597
- Array.prototype.forEach.call($body.querySelectorAll('[data-command-id="shell.tool-updates-forget-folder"]'), function (b) { b.disabled = on || !!forgetting; });
598
- if (on && label) $approve.textContent = label;
621
+ /** A control that cannot be used right now says why (Instructor reads data-blocked-reason only while it is disabled). */
622
+ function lock(button, reason) {
623
+ button.disabled = !!reason;
624
+ if (reason) button.setAttribute('data-blocked-reason', reason); else button.removeAttribute('data-blocked-reason');
625
+ }
626
+
627
+ /** Why a button that needs the dialog to itself is held, or '' when nothing holds it. */
628
+ function heldReason(whileChecking) { return approving ? 'Approving now.' : checking ? whileChecking : ''; }
629
+
630
+ /** Why a Remove from list button is held (any row: one folder is removed at a time). */
631
+ function forgetReason() { return heldReason('Wait for the check to finish.') || (forgetting ? 'Removing a folder now.' : ''); }
632
+
633
+ function syncControls() {
634
+ // Only an approval is busy for the screen reader: a busy dialog can make it hold back the step announcements inside.
635
+ $modal.setAttribute('aria-busy', approving ? 'true' : 'false');
636
+ lock($check, heldReason('A check is already running.'));
637
+ lock($approve, heldReason('Wait for the check to finish, then approve.'));
638
+ lock($cancel, approving ? 'Approving now.' : '');
639
+ Array.prototype.forEach.call($body.querySelectorAll('[data-command-id="shell.tool-updates-forget-folder"]'), function (b) { lock(b, forgetReason()); });
599
640
  }
600
641
 
601
642
  async function refresh() {
602
643
  var ticket = nextTicket();
603
644
  try {
604
645
  var body = await call('/api/tool-updates');
646
+ // Only the server's own answer can be the view: a body that is not one keeps the last view on screen.
647
+ if (!body || body.ok !== true) throw new Error('not the server\'s answer');
605
648
  applyView(ticket, body);
606
649
  } catch (error) {
607
650
  // Keep the last answer on screen (and its pill): a dropped request is not "nothing to update".
608
651
  console.warn('tool updates unavailable', error);
609
- if ($modal.classList.contains('show') && !busy) $live.textContent = 'FloLess could not check for tool updates just now. What is shown is from the last check.';
652
+ if (isOpen() && !approving && !checking) $live.textContent = 'FloLess could not check for tool updates just now. What is shown is from the last check.';
610
653
  }
611
654
  paintPill();
612
655
  syncProgress();
@@ -621,15 +664,17 @@
621
664
  syncProgress();
622
665
  // Focus the title, not the primary: approving is consequential and Enter on open must not do it.
623
666
  setTimeout(function () { $title.focus(); }, 0);
624
- void refresh().then(function () { if ($modal.classList.contains('show') && !busy && !results) paint(); });
667
+ void refresh().then(function () { if (isOpen() && !approving && !results) paint(); });
625
668
  }
626
669
 
627
670
  function close() {
628
- if (busy) return;
671
+ if (approving) return;
629
672
  $modal.classList.remove('show');
630
673
  syncProgress();
631
674
  if (results) { results = null; }
632
- if (returnFocus && document.contains(returnFocus)) returnFocus.focus();
675
+ // The pill may have gone while the dialog was open (a check that found nothing): then the menu button, never the page behind.
676
+ var back = returnFocus && !returnFocus.hidden && document.contains(returnFocus) ? returnFocus : document.getElementById('menu-btn');
677
+ if (back) back.focus();
633
678
  returnFocus = null;
634
679
  }
635
680
 
@@ -650,36 +695,90 @@
650
695
  else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
651
696
  });
652
697
 
698
+ /** A line in the corner, for the end of a check the person left running. It takes no focus. A warning stays until it is closed: the person went away for a long check. */
699
+ function toast(text, kind) {
700
+ try { showToast(text, kind, kind === 'warn' ? { persistent: true } : undefined); } catch (error) { console.warn('tool update toast failed', error); }
701
+ }
702
+
653
703
  $check.addEventListener('click', async function () {
704
+ if (checking || approving) return;
705
+ var controller = new AbortController();
706
+ checkController = controller;
654
707
  checking = true;
655
- setBusy(true);
656
- $live.textContent = ''; // the panel below says what is being checked; the live line is for what came of it
657
- syncProgress();
708
+ var said = ''; // what the end of the check says: in the live line when the dialog is open, in a corner message when it was closed
709
+ var failed = false;
710
+ var downloadProblem = false;
658
711
  try {
712
+ answerLost = false;
713
+ quietAsks = 0;
714
+ syncControls();
715
+ // A button just disabled had the keyboard (Check, Approve or Remove from list), or focus was already outside the dialog
716
+ // (a browser that does not focus a button on a click): left alone, focus is on the page behind the dialog, where Esc is
717
+ // not heard and Tab leaves the dialog. Parked on the title (as open() does), Esc closes it and Tab stays inside.
718
+ var held = document.activeElement;
719
+ if (!held || !$dialog.contains(held) || held.disabled) $title.focus();
720
+ $live.textContent = ''; // the panel below says what is being checked; the live line is for what came of it
721
+ paintPill(); // the pill carries the running check once the dialog is closed; with the dialog open it also paints the panel
659
722
  var ticket = nextTicket();
660
- var answer = await call('/api/tool-updates/check', 'POST');
661
- applyView(ticket, answer);
723
+ var answer = await call('/api/tool-updates/check', 'POST', undefined, controller.signal);
724
+ // Only the server's own answer can be the view: a body that is not one must not replace what is on screen.
725
+ if (answer && answer.ok === true) applyView(ticket, answer);
726
+ // Said from the check's own answer, not from the view on screen: a dialog reopened mid-check re-reads the server, and that
727
+ // re-read (the previous pass's result) takes a later ticket than this answer and so wins the view.
662
728
  var n = (answer.offers || []).length;
663
- $live.textContent = n ? plural(n, 'workflow is', 'workflows are') + ' ready to approve.' : 'No workflows to approve.';
729
+ said = n ? plural(n, 'workflow is', 'workflows are') + ' ready to approve.' : 'No workflows to approve.';
730
+ downloadProblem = !!(answer.downloads && answer.downloads.error);
731
+ // Not a finished check: a 200 whose body is not the server's answer (ok is not true), or one carrying the server's own
732
+ // sentence (AWARE not asked, or too old). Both are read from THIS request's answer, never from a newer re-read.
733
+ if (answer.ok !== true || answer.sentence) {
734
+ console.warn('tool update check did not run', answer.sentence || answer.error || '');
735
+ failed = true;
736
+ said = 'The tool update check did not go through. Try again in a moment.';
737
+ }
664
738
  // The cleanup pass Check now started keeps running after this answer, and may already have finished and been
665
739
  // re-read: read the server again so this (older) answer never stands over a newer cleanup result.
666
740
  void refresh();
667
741
  } catch (error) {
668
- $live.textContent = error.message;
742
+ if (answerLost) {
743
+ // The server said three times running that nothing was running: it finished and its answer never got here, or the
744
+ // request never reached it. The page cannot tell which, so it says only what it knows and reads the view again.
745
+ said = 'FloLess got no answer to the check and cannot say whether it ran. Nothing is running now, and the list is what FloLess last read. You can check again.';
746
+ void refresh();
747
+ } else {
748
+ console.warn('tool update check failed', error);
749
+ failed = true;
750
+ said = 'The tool update check did not go through. Try again in a moment.';
751
+ }
669
752
  } finally {
753
+ var left = !isOpen(); // closed while it ran: nothing below repaints it, moves focus into it, or writes its live line (only the button states are reset)
670
754
  checking = false;
671
- setBusy(false);
672
- paint();
673
- paintPill();
674
- // The button was disabled while busy, which drops focus to the page: put it back where the person was.
675
- if (!$check.hidden) $check.focus(); else $title.focus();
755
+ checkController = null;
756
+ answerLost = false;
757
+ // What came of it is said before anything is repainted, so a repaint that throws cannot swallow it.
758
+ if (left) {
759
+ if (failed) toast('The tool update check did not go through. Open Tool updates to try again.', 'warn');
760
+ else if (downloadProblem) toast('Tool update check finished, but downloading new tool versions ran into a problem. Open Tool updates for details.', 'warn');
761
+ else toast('Tool update check finished. ' + said, 'ok');
762
+ } else {
763
+ $live.textContent = said;
764
+ }
765
+ syncControls();
766
+ paintPill(); // also repaints an open dialog; the panel goes unless the view still says a check is running
767
+ if (!left) {
768
+ // Put focus back on Check if it is still parked on the title (above) or fell out of the dialog; anywhere else the
769
+ // person put it themselves.
770
+ var kept = document.activeElement;
771
+ if (!kept || kept === $title || !$dialog.contains(kept)) { if (!$check.hidden) $check.focus(); else $title.focus(); }
772
+ }
676
773
  }
677
774
  });
678
775
 
679
776
  $approve.addEventListener('click', async function () {
680
- if (!view || !view.batchId) return;
777
+ if (!view || !view.batchId || checking || approving) return;
681
778
  var apps = (view.offers || []).map(function (o) { return o.app; });
682
- setBusy(true, 'Approving…');
779
+ approving = true;
780
+ syncControls();
781
+ $approve.textContent = 'Approving…';
683
782
  $live.textContent = 'Approving ' + plural(apps.length, 'workflow', 'workflows') + '…';
684
783
  try {
685
784
  var ticket = nextTicket();
@@ -703,7 +802,8 @@
703
802
  await refresh();
704
803
  $live.textContent = 'FloLess did not hear back after your approval, so it cannot say yet which workflows moved. The list below is what is still waiting.';
705
804
  } finally {
706
- setBusy(false);
805
+ approving = false;
806
+ syncControls();
707
807
  paint();
708
808
  paintPill();
709
809
  var head = document.getElementById('tool-updates-results-head');
@@ -350,6 +350,12 @@
350
350
  const $revisionCard = document.getElementById('ws-revision-card');
351
351
  const $revisionFile = document.getElementById('ws-revision-file');
352
352
  const $sourcePlaceholder = document.getElementById('ws-source-placeholder'); // shown for a filter-less Source step
353
+ // While a Revit or Tekla read is in flight the Source pane shows Flo working, hat on, as over a running workflow
354
+ // (#2079). It sits in the hidden .ws-source-spin slot that data-importing reveals, and only moves while on screen.
355
+ {
356
+ const slot = $sourcePlaceholder?.querySelector('.ws-source-spin');
357
+ if (slot && typeof floAvatar === 'function') { slot.classList.add('ws-source-flo'); floAvatar(slot, { size: 40, mood: 'working', hat: true }); }
358
+ }
353
359
  const $revitSourceActions = document.getElementById('ws-source-actions');
354
360
  const $revitOpenModel = document.getElementById('ws-revit-open-model');
355
361
  const $revitReplace = document.getElementById('ws-revit-replace');
@@ -1533,7 +1539,7 @@
1533
1539
  // project open" for the whole pending window and close the project the user asked to stay in —
1534
1540
  // and the read would then drop them in Workflows anyway.
1535
1541
  const pending = $switch.getAttribute('aria-busy') === 'true';
1536
- if (!pending && b.dataset.mode === 'workspaces' && mode === 'workspaces' && current) { closeProject(); return; }
1542
+ if (!pending && b.dataset.mode === 'workspaces' && mode === 'workspaces' && current) { void leaveProjectToList(b); return; }
1537
1543
  // #1890: the active Workflows tab goes home to the Workflows landing, the same way.
1538
1544
  if (!pending && b.dataset.mode === 'workflows' && mode === 'workflows' && bridge.showWorkflowsLanding) { bridge.showWorkflowsLanding(); return; }
1539
1545
  // #2007: and the active Agents tab goes home to the list of agents.
@@ -2041,7 +2047,7 @@
2041
2047
  // UNPROMPTED. Tracked separately rather than smuggled in here.
2042
2048
  const target = mine.id;
2043
2049
  try {
2044
- await openProject(target, currentStep);
2050
+ await openProject(target, currentStep, { skipLeaveGuard: true });
2045
2051
  } catch (err) {
2046
2052
  // THE REJECTING TWIN of the branch below, and it needs the same sentence: `openProject`
2047
2053
  // reassigns `current` and repaints the header BEFORE it re-srcs the frames, so a throw in
@@ -3111,7 +3117,11 @@
3111
3117
  if (current?.id !== project.id) return;
3112
3118
  if (!state?.canReplace) throw new Error('Tekla Parser replacement access is unavailable.');
3113
3119
  const operation = await uploadTeklaForProject(project, source, state.generation);
3114
- if (current?.id === project.id) pollRevitImport(operation.operationId, project.id);
3120
+ if (current?.id === project.id) {
3121
+ // As a new project's read does: the copy check is over, so its "cannot be cancelled" no longer stands.
3122
+ paintRevitSourceState('Waiting for AWARE', 'Your copied Tekla source is waiting for the entitled read-only parser.');
3123
+ pollRevitImport(operation.operationId, project.id);
3124
+ }
3115
3125
  } catch (error) {
3116
3126
  if (current?.id !== project.id) return;
3117
3127
  if (error?.name === 'AbortError') {
@@ -4559,6 +4569,14 @@
4559
4569
  if (activeImportPolls.has(pollKey)) return;
4560
4570
  activeImportPolls.add(pollKey);
4561
4571
  const isCurrentImport = () => current?.id === projectId && revitActiveOperation?.operationId === operationId;
4572
+ // Every live state of the read shows it in flight, with its Cancel, from the moment it is admitted. A project
4573
+ // opened just as its upload was admitted can drop its own in-flight paint (refreshRevitSourceState yields to the
4574
+ // newer operation), leaving the idle glyph under "Reading model"; a Tekla read still carries the copy check's
4575
+ // 'uploading' paint, which has no Cancel although the admitted operation has a cancel route.
4576
+ const showReadInFlight = () => {
4577
+ if ($revitCancel?.hidden || $sourcePlaceholder?.getAttribute('data-importing') !== 'true') paintRevitSourceActions('active', true);
4578
+ };
4579
+ if (isCurrentImport()) showReadInFlight();
4562
4580
  try {
4563
4581
  for (;;) {
4564
4582
  await new Promise((resolve) => setTimeout(resolve, 800));
@@ -4594,7 +4612,7 @@
4594
4612
  validating: ['Checking model integrity', 'Verifying the signed source and display packages…'],
4595
4613
  publishing: ['Publishing draft', 'Saving the verified read-only model snapshot…'],
4596
4614
  }[operation.state];
4597
- if (copy) { paintRevitSourceState(copy[0], copy[1]); continue; }
4615
+ if (copy) { paintRevitSourceState(copy[0], copy[1]); showReadInFlight(); continue; }
4598
4616
  if (operation.state === 'ready') {
4599
4617
  revitActiveOperation = null;
4600
4618
  paintRevitSourceState(tekla ? 'Read-only snapshot ready to review' : 'Model ready to review', 'The model is available on the Model tab. It is not approved yet.');
@@ -4711,9 +4729,18 @@
4711
4729
  }
4712
4730
 
4713
4731
  // ── open project ────────────────────────────────────────────────────────────
4714
- async function openProject(id, initialStep = 'model') {
4732
+ // `opts.skipLeaveGuard` is for the rename re-open only (the project is the same one under a new id and
4733
+ // its old id is already gone, so there is nothing to save to). Every other open of a DIFFERENT project
4734
+ // while one is open asks about unsaved work first — the card click, the switcher, Show in chat, Open
4735
+ // knowledge, create/import — so no path replaces the editors behind the user's back.
4736
+ let openNavSeq = 0;
4737
+ async function openProject(id, initialStep = 'model', opts) {
4738
+ const nav = opts || {};
4739
+ // Latest navigation wins from the first line: an older open still waiting on a lookup must not replace a newer one.
4740
+ const navToken = ++openNavSeq;
4715
4741
  let p = projects.find((x) => x.id === id);
4716
4742
  if (!p) { try { p = (await api('/api/projects')).projects.find((x) => x.id === id); } catch { /* fall through */ } }
4743
+ if (navToken !== openNavSeq) return STAYED_IN_PROJECT;
4717
4744
  if (!p) { showToast('Project not found — it may have been archived.', 'warn'); return loadProjects(); }
4718
4745
  // Never a broken open (spec §3.2): a project whose app has no client descriptor can't be rendered
4719
4746
  // — toast and bail BEFORE mutating any view state, matching the create-card skip. wsApp() would
@@ -4727,6 +4754,8 @@
4727
4754
  showToast('Workspaces has no view for this project’s app yet — ask the AI to add one.', 'warn');
4728
4755
  return;
4729
4756
  }
4757
+ if (!nav.skipLeaveGuard && current && current.id !== p.id && !(await leaveOpenProject(nav.returnFocus))) return STAYED_IN_PROJECT;
4758
+ if (navToken !== openNavSeq) return STAYED_IN_PROJECT;
4730
4759
  current = p;
4731
4760
  // #1890: a new workspace conversation suggests this project's units (the one opened last).
4732
4761
  try { localStorage.setItem('floless:last-project', p.id); } catch { /* private mode: no suggestion */ }
@@ -4907,6 +4936,46 @@
4907
4936
  $revisionCard.className = 'ws-revision-card';
4908
4937
  return true;
4909
4938
  }
4939
+ /**
4940
+ * Leaving the open project for another one, or for the project list, replaces its editors, so
4941
+ * anything the Drawing Filter or the model editor has not saved would be lost with them. Ask first
4942
+ * — but only when something is actually unsaved. A drawing read running in AI Chat is not part of
4943
+ * the question: it keeps running on the server and its conversation, cards and approvals are there
4944
+ * again when this project is reopened. (Switching tab to Workflows or Agents only hides the editors,
4945
+ * so it needs no question.)
4946
+ */
4947
+ async function confirmLeaveProject(returnFocus) {
4948
+ const guard = window.flolessLeaveGuard;
4949
+ if (!guard || typeof guard.confirmIfUnsaved !== 'function' || !current) return true;
4950
+ // No `only`: action 'project' filters to this project's editor frames inside the guard itself.
4951
+ return guard.confirmIfUnsaved({ action: 'project', returnFocus });
4952
+ }
4953
+ /**
4954
+ * The ONE gate for replacing the open project's editors (another project, or the list). Latest
4955
+ * navigation wins: each call takes a token, and a call whose token has been superseded by the time
4956
+ * its question is answered resolves false, so two quick choices can never open the earlier one last.
4957
+ * The source project is held by id; if it is no longer the open one when the answer arrives (closed
4958
+ * or replaced meanwhile) the question is asked afresh for whatever is open now. Resolves true only
4959
+ * when nothing in the open project is unsaved at that moment, or the user chose to go on.
4960
+ */
4961
+ let leaveNavSeq = 0;
4962
+ async function leaveOpenProject(returnFocus) {
4963
+ const token = ++leaveNavSeq;
4964
+ for (let round = 0; round < 3; round++) {
4965
+ const sourceId = current ? current.id : null;
4966
+ if (!sourceId) return true;
4967
+ if (!(await confirmLeaveProject(returnFocus))) return false;
4968
+ if (token !== leaveNavSeq) return false;
4969
+ if ((current ? current.id : null) === sourceId) return true;
4970
+ }
4971
+ return false;
4972
+ }
4973
+ /** What openProject returns when the user chose to stay: callers that open on someone's behalf say so. */
4974
+ const STAYED_IN_PROJECT = Object.freeze({ stayed: true });
4975
+ async function leaveProjectToList(returnFocus) {
4976
+ if (!(await leaveOpenProject(returnFocus))) return;
4977
+ closeProject();
4978
+ }
4910
4979
  function closeProject() {
4911
4980
  current = null;
4912
4981
  approvalStateGen++;
@@ -4937,7 +5006,7 @@
4937
5006
  pendingPresenceToast = null;
4938
5007
  closeProjMenu(); applyMode(); syncWorkspaceGuide(); // revision state cleared by resetRevisionState() above
4939
5008
  }
4940
- document.getElementById('ws-back').addEventListener('click', closeProject);
5009
+ document.getElementById('ws-back').addEventListener('click', (e) => { void leaveProjectToList(e.currentTarget); });
4941
5010
 
4942
5011
  // Paint the step-tab LABELS from the current app's descriptor (Source/Traced for vectorize,
4943
5012
  // Drawings/Model for steel). The data-step KEYS stay stable (drawings/model/exports/history) so
@@ -5050,6 +5119,10 @@
5050
5119
  .map((item) => progressText(item.note))
5051
5120
  .filter(Boolean);
5052
5121
  const caution = cautions.length ? cautions.join(' · ') : null;
5122
+ // The read runs in AI Chat when the request is chat-owned; only a terminal-run read has a terminal session to return to (#2164).
5123
+ const inChat = req?.chatConversation?.executionOwner === 'chat';
5124
+ const backTo = inChat ? 'AI Chat' : 'the same terminal AI';
5125
+ const backToSession = inChat ? 'AI Chat' : 'the same terminal AI session that prepared it';
5053
5126
  let state = progress.status;
5054
5127
  let heading = 'Creating the first steel model';
5055
5128
  let nowLabel = 'Now';
@@ -5063,7 +5136,7 @@
5063
5136
  heading = 'Model creation is blocked';
5064
5137
  nowLabel = 'Blocked';
5065
5138
  now = progressText(progress.items.find((item) => item.state === 'blocked')?.note)
5066
- || 'Return to the same terminal AI for the blocking details.';
5139
+ || `Return to ${backTo} for the blocking details.`;
5067
5140
  } else if (progress.status === 'complete') {
5068
5141
  // A finished checklist is NOT a verified model: this request is still pending, nothing has
5069
5142
  // been submitted, and no audit has run. Only a signed post-audit surface may say the model
@@ -5071,11 +5144,11 @@
5071
5144
  heading = 'Drawing read finished';
5072
5145
  nowLabel = 'Done';
5073
5146
  now = null;
5074
- next = 'Return to the same terminal AI session that prepared it and let it submit the read.';
5147
+ next = `Return to ${backToSession} and let it submit the read.`;
5075
5148
  } else if (progress.status === 'cancelled') {
5076
5149
  heading = 'Model creation stopped';
5077
5150
  nowLabel = 'Stopped';
5078
- now = 'Return to the same terminal AI for next steps.';
5151
+ now = `Return to ${backTo} for next steps.`;
5079
5152
  next = null;
5080
5153
  }
5081
5154
  // A heartbeat nobody can refresh is not a heartbeat. Both arms below replace the forward-looking
@@ -5091,12 +5164,12 @@
5091
5164
  state = 'waiting';
5092
5165
  heading = 'No progress update in the last 8 minutes';
5093
5166
  nowLabel = 'Last reported';
5094
- next = 'Return to the same terminal AI session that prepared this read and ask it to continue.';
5167
+ next = inChat ? 'Ask the read in AI Chat to continue.' : 'Return to the same terminal AI session that prepared this read and ask it to continue.';
5095
5168
  } else if (stale && progress.status === 'complete') {
5096
5169
  state = 'waiting';
5097
5170
  heading = 'The drawing read finished but has not been submitted';
5098
5171
  nowLabel = 'Done';
5099
- next = 'Return to the same terminal AI session that prepared it and tell it to submit the read.';
5172
+ next = `Return to ${backToSession} and tell it to submit the read.`;
5100
5173
  }
5101
5174
  return {
5102
5175
  state,
@@ -14326,7 +14399,7 @@
14326
14399
  frontProject(project, id);
14327
14400
  // If the renamed project was the OPEN one, its editor iframes still carry ?project=<old id> —
14328
14401
  // re-open so they re-src to the new id (a stale id 404s the next contract read/write/autosave).
14329
- if (wasCurrent) await openProject(project.id);
14402
+ if (wasCurrent) await openProject(project.id, 'model', { skipLeaveGuard: true });
14330
14403
  showToast(`Renamed to "${project.name}"`, 'ok');
14331
14404
  } else if (action === 'duplicate') {
14332
14405
  dismissProgress = showToast(`Duplicating “${proj ? proj.name : 'project'}”…`, 'progress');
@@ -14713,10 +14786,10 @@
14713
14786
  projComboClearHighlight();
14714
14787
  if (focusTrigger && $projTrigger) $projTrigger.focus();
14715
14788
  }
14716
- function selectProjById(id) {
14789
+ async function selectProjById(id) {
14717
14790
  closeProjCombo(true);
14718
14791
  if (current && current.id === id) return; // already open — no-op, matches selectComboById
14719
- openProject(id);
14792
+ openProject(id, 'model', { returnFocus: $projTrigger }); // openProject asks about unsaved work itself
14720
14793
  }
14721
14794
  if ($projTrigger) {
14722
14795
  $projTrigger.addEventListener('click', (e) => {
@@ -14782,7 +14855,8 @@
14782
14855
  async function openKnowledgeStep(projectId) {
14783
14856
  if (typeof projectId !== 'string' || !projectId) throw new Error('That project could not be opened. Open it from Workspaces.');
14784
14857
  await setMode('workspaces');
14785
- await openProject(projectId, 'knowledge');
14858
+ const opened = await openProject(projectId, 'knowledge');
14859
+ if (opened === STAYED_IN_PROJECT) throw new Error('You stayed in this project, so the other one was not opened.');
14786
14860
  if (current?.id !== projectId) throw new Error('That project could not be opened. Open it from Workspaces.');
14787
14861
  }
14788
14862
 
@@ -14799,9 +14873,13 @@
14799
14873
  }
14800
14874
  await setMode('workspaces');
14801
14875
  if (owner.kind === 'project') {
14802
- await openProject(owner.projectId);
14876
+ const opened = await openProject(owner.projectId);
14877
+ if (opened === STAYED_IN_PROJECT) throw new Error('You stayed in this project, so the other one was not opened.');
14803
14878
  if (current?.id !== owner.projectId) throw new Error('That project could not be opened. Try Show in chat again after opening its project in Workspaces.');
14804
- } else closeProject();
14879
+ } else {
14880
+ await leaveProjectToList(null);
14881
+ if (current) throw new Error('You stayed in this project, so the conversation was not opened.');
14882
+ }
14805
14883
  }
14806
14884
 
14807
14885
  window.flolessWorkspaces = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floless/app",
3
- "version": "0.152.0",
3
+ "version": "0.153.0",
4
4
  "type": "module",
5
5
  "description": "Thin localhost host for floless.app — serves web/ and shells the aware CLI. No engine, no LLM.",
6
6
  "bin": {