@floless/app 0.141.0 → 0.141.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.
@@ -0,0 +1,480 @@
1
+ /* ──────────────────────────────────────────────────────────────────────────
2
+ Leave guard — "is everything saved?" before FloLess stops or signs out.
3
+
4
+ Two actions leave the workspace for good: "Stop FloLess" in the ≡ menu ends the local server,
5
+ and "Sign Out" in the account menu reloads onto the sign-in screen. Both would silently lose
6
+ unsaved work, so both ask this module first — the normal procedure before closing an app.
7
+
8
+ PROVIDERS. Each surface that can hold unsaved work registers a provider: a function returning
9
+ the items it has unresolved RIGHT NOW. An item is
10
+ { id, label, detail, save?(): Promise<boolean>, discard?(), unchecked? }
11
+ aware.js registers the workflow inputs, the running workflow and the full-window editor overlay;
12
+ workspaces.js registers the project's editor frames. `save()` resolves true only when the
13
+ surface re-reads as saved; the guard re-collects after saving regardless, so a surface that says
14
+ "done" but is still dirty keeps the dialog open.
15
+
16
+ FAIL CLOSED. A probe that throws (a frame mid-navigation, an unexpected page) is reported as
17
+ "could not be checked" — it blocks the silent path; the user can still choose to go on without
18
+ saving. An editor frame is saved only when its own state reads exactly `clean`.
19
+
20
+ THE DIALOG is its own #leave-guard-modal (the #confirm-modal look, not its owner): modal over the
21
+ whole window, so nothing is edited behind it. Immediately before resolving "go ahead" it probes
22
+ once more, and returns to the dialog if something new became unsaved or a run started meanwhile.
23
+
24
+ Also here: the Stop FloLess flow itself and the "FloLess has stopped" screen, because stopping is
25
+ the one caller that must also quieten the page (polls, live streams, the reconnect overlay).
26
+ ────────────────────────────────────────────────────────────────────────── */
27
+ (function () {
28
+ 'use strict';
29
+
30
+ var providers = [];
31
+
32
+ /* Live streams are tracked so a stopped page can close them. Without this, every EventSource
33
+ retries forever against a server that is gone on purpose, and each retry is a console error. */
34
+ var liveStreams = new Set();
35
+ if (typeof window.EventSource === 'function') {
36
+ var NativeEventSource = window.EventSource;
37
+ var TrackedEventSource = function (url, init) {
38
+ var es = new NativeEventSource(url, init);
39
+ if (window.__flolessStopped) { es.close(); return es; }
40
+ liveStreams.add(es);
41
+ return es;
42
+ };
43
+ TrackedEventSource.prototype = NativeEventSource.prototype;
44
+ ['CONNECTING', 'OPEN', 'CLOSED'].forEach(function (k) { TrackedEventSource[k] = NativeEventSource[k]; });
45
+ window.EventSource = TrackedEventSource;
46
+ }
47
+
48
+ /* ── probing ───────────────────────────────────────────────────────────── */
49
+
50
+ var FRAME_PAGES = [
51
+ { match: /steel-filter\.html/, label: 'The Drawing Filter' },
52
+ { match: /steel-editor\.html/, label: 'The model editor' },
53
+ { match: /vector-editor\.html/, label: 'The drawing editor' },
54
+ ];
55
+ var STATE_DETAIL = {
56
+ dirty: 'has changes that are not saved yet.',
57
+ saving: 'is still saving your last change.',
58
+ error: 'could not save your last change.',
59
+ conflict: 'was changed somewhere else, so your last change did not save. Open it to choose which version to keep.',
60
+ };
61
+
62
+ function frameLabel(src) {
63
+ for (var i = 0; i < FRAME_PAGES.length; i++) if (FRAME_PAGES[i].match.test(src)) return FRAME_PAGES[i].label;
64
+ return 'An open editor';
65
+ }
66
+
67
+ /** One frame's unresolved items. Shared by aware.js and workspaces.js through registerFrame(). */
68
+ function probeFrame(frame, key) {
69
+ if (!frame) return [];
70
+ var src = frame.getAttribute('src') || '';
71
+ if (!src || src === 'about:blank') return [];
72
+ var id = 'frame:' + key;
73
+ var label = frameLabel(src);
74
+ var win;
75
+ try {
76
+ win = frame.contentWindow;
77
+ if (!win) return [];
78
+ void win.location.href; // same-origin proof; throws for a foreign page
79
+ } catch (_) {
80
+ return [{ id: id, label: label, detail: 'could not be checked for unsaved changes.', unchecked: true }];
81
+ }
82
+ try {
83
+ var guard = win.__floGuard;
84
+ if (guard && typeof guard.isDirty === 'function') {
85
+ if (!guard.isDirty()) return [];
86
+ return [{
87
+ id: id, label: label, detail: STATE_DETAIL.dirty,
88
+ save: async function () { var ok = await guard.save(); return ok === true && !guard.isDirty(); },
89
+ discard: function () { try { guard.discard(); } catch (_) { /* the page is going away */ } },
90
+ }];
91
+ }
92
+ if (typeof win.contractSaveState === 'function') {
93
+ var state = win.contractSaveState();
94
+ if (state === 'clean') return [];
95
+ var flush = typeof win.flushContract === 'function' ? win.flushContract : null;
96
+ return [{
97
+ id: id, label: label, detail: STATE_DETAIL[state] || STATE_DETAIL.dirty,
98
+ save: flush ? async function () { await flush(); return win.contractSaveState() === 'clean'; } : null,
99
+ }];
100
+ }
101
+ return []; // a page with no save state (a viewer, or one still loading) holds nothing to lose
102
+ } catch (_) {
103
+ return [{ id: id, label: label, detail: 'could not be checked for unsaved changes.', unchecked: true }];
104
+ }
105
+ }
106
+
107
+ function register(provider) { if (typeof provider === 'function') providers.push(provider); }
108
+ function registerFrame(frame, key) { register(function () { return probeFrame(frame, key); }); }
109
+
110
+ /** Everything unresolved right now: { items, running } — never throws. */
111
+ async function collect() {
112
+ var items = [];
113
+ var running = null;
114
+ for (var i = 0; i < providers.length; i++) {
115
+ var got;
116
+ try { got = await providers[i](); }
117
+ catch (_) { got = [{ id: 'provider:' + i, label: 'Part of FloLess', detail: 'could not be checked for unsaved changes.', unchecked: true }]; }
118
+ (Array.isArray(got) ? got : []).forEach(function (item) {
119
+ if (!item || !item.id) return;
120
+ if (item.kind === 'running') running = item;
121
+ else items.push(item);
122
+ });
123
+ }
124
+ return { items: items, running: running };
125
+ }
126
+
127
+ /* ── the dialog ────────────────────────────────────────────────────────── */
128
+
129
+ var COPY = {
130
+ stop: {
131
+ title: 'Stop FloLess?',
132
+ clean: 'FloLess will close on this computer. Open it again from the Start menu or the desktop shortcut whenever you need it.',
133
+ unsaved: 'Some of your work is not saved yet. Save it before FloLess closes?',
134
+ running: 'A workflow is running. Stopping FloLess ends it.',
135
+ confirm: 'Stop FloLess', save: 'Save and stop', discard: 'Stop without saving',
136
+ working: 'Stopping FloLess…',
137
+ failed: 'FloLess could not stop just now, so it is still running. Try again in a moment.',
138
+ },
139
+ signout: {
140
+ title: 'Sign out of FloLess?',
141
+ clean: 'You will need to sign in again to keep working.',
142
+ unsaved: 'Some of your work is not saved yet. Save it before you sign out?',
143
+ running: 'A workflow is still running. It will finish on its own; you’ll need to sign in again to see the result.',
144
+ confirm: 'Sign out', save: 'Save and sign out', discard: 'Sign out without saving',
145
+ working: 'Signing out…',
146
+ failed: 'FloLess could not sign you out just now, so you are still signed in. Try again in a moment.',
147
+ },
148
+ };
149
+
150
+ var $modal = null;
151
+ var openPromise = null;
152
+ // The open question's handlers. The buttons, backdrop and keys are wired ONCE (wireOnce) and
153
+ // route here, so no listener is left behind between questions.
154
+ var current = null;
155
+ var wired = false;
156
+ function wireOnce() {
157
+ if (wired) return;
158
+ wired = true;
159
+ var route = function (name) { return function (e) { if (current) current[name](e); }; };
160
+ el('leave-guard-cancel').addEventListener('click', route('cancel'));
161
+ el('leave-guard-confirm').addEventListener('click', route('confirm'));
162
+ el('leave-guard-discard').addEventListener('click', route('discard'));
163
+ el('leave-guard-save').addEventListener('click', route('save'));
164
+ $modal.addEventListener('mousedown', route('backdropDown'));
165
+ $modal.addEventListener('click', route('backdropClick'));
166
+ // Capture: this question sits above every other dialog, so its keys must not reach them.
167
+ document.addEventListener('keydown', route('key'), true);
168
+ }
169
+
170
+ function el(id) { return document.getElementById(id); }
171
+
172
+ function renderItems(items, failed) {
173
+ var list = el('leave-guard-list');
174
+ list.replaceChildren();
175
+ items.forEach(function (item) {
176
+ var li = document.createElement('li');
177
+ li.dataset.itemId = item.id;
178
+ var name = document.createElement('strong');
179
+ name.textContent = item.label;
180
+ li.append(name, document.createTextNode(' ' + item.detail));
181
+ if (failed && failed.has(item.id)) {
182
+ li.classList.add('lg-failed');
183
+ var why = document.createElement('span');
184
+ why.className = 'lg-why';
185
+ why.textContent = item.unchecked || !item.save
186
+ ? 'FloLess cannot save this for you. Open it and save it, or continue without saving.'
187
+ : 'Saving did not finish. Open it to see what went wrong, or continue without saving.';
188
+ li.appendChild(why);
189
+ }
190
+ list.appendChild(li);
191
+ });
192
+ el('leave-guard-unsaved').hidden = items.length === 0;
193
+ }
194
+
195
+ function render(action, snapshot, note, failed) {
196
+ var copy = COPY[action];
197
+ var unsaved = snapshot.items.length > 0;
198
+ el('leave-guard-title').textContent = copy.title;
199
+ el('leave-guard-sub').textContent = unsaved ? copy.unsaved : copy.clean;
200
+ renderItems(snapshot.items, failed);
201
+ var run = el('leave-guard-running');
202
+ run.textContent = snapshot.running ? copy.running : '';
203
+ run.hidden = !snapshot.running;
204
+ var noteEl = el('leave-guard-note');
205
+ noteEl.textContent = note || '';
206
+ noteEl.hidden = !note;
207
+ el('leave-guard-confirm').textContent = copy.confirm;
208
+ el('leave-guard-save').textContent = copy.save;
209
+ el('leave-guard-discard').textContent = copy.discard;
210
+ el('leave-guard-confirm').hidden = unsaved;
211
+ el('leave-guard-save').hidden = !unsaved;
212
+ el('leave-guard-discard').hidden = !unsaved;
213
+ }
214
+
215
+ /** Resolves like `p`, or false once `ms` pass — a save that never answers counts as not saved,
216
+ * so one stuck write cannot hold the whole-window question busy for good. */
217
+ function withTimeout(p, ms) {
218
+ var timer;
219
+ var timeout = new Promise(function (resolve) { timer = setTimeout(function () { resolve(false); }, ms); });
220
+ return Promise.race([Promise.resolve(p), timeout]).finally(function () { clearTimeout(timer); });
221
+ }
222
+
223
+ function idsOf(snapshot) { return new Set(snapshot.items.map(function (i) { return i.id; })); }
224
+
225
+ /** Something the user was NOT shown appeared since they decided: a new unsaved item or a new run. */
226
+ function grewSince(decided, fresh) {
227
+ var seen = idsOf(decided);
228
+ if (fresh.running && !decided.running) return true;
229
+ return fresh.items.some(function (i) { return !seen.has(i.id); });
230
+ }
231
+
232
+ /**
233
+ * Ask before stopping or signing out. Resolves true when the caller should go ahead NOW (the last
234
+ * probe has just run), false when the user cancelled. Idempotent while open.
235
+ *
236
+ * opts.commit (optional): the action itself — async, resolving { ok, message }. It runs while the
237
+ * dialog stays open and busy, so nothing can be edited between the last probe and the server's
238
+ * answer; "without saving" discards only after it succeeded; and a refusal is explained in the
239
+ * dialog, which stays open (nothing was discarded, nothing was left).
240
+ */
241
+ function confirm(opts) {
242
+ var action = opts && opts.action === 'signout' ? 'signout' : 'stop';
243
+ if (openPromise) return openPromise;
244
+ $modal = $modal || el('leave-guard-modal');
245
+ var other = el('confirm-modal');
246
+ if (!$modal || (other && other.classList.contains('show'))) return Promise.resolve(false);
247
+
248
+ openPromise = new Promise(function (resolve) {
249
+ var returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
250
+ var covered = Array.from(document.querySelectorAll('.modal-backdrop.show'))
251
+ .filter(function (m) { return m !== $modal; })
252
+ .map(function (m) { return { m: m, inert: !!m.inert, hidden: m.getAttribute('aria-hidden') }; });
253
+ covered.forEach(function (c) { c.m.inert = true; c.m.setAttribute('aria-hidden', 'true'); });
254
+ var snapshot = { items: [], running: null };
255
+ var busy = false;
256
+ var settled = false;
257
+
258
+ function setBusy(on, label) {
259
+ busy = on;
260
+ ['leave-guard-confirm', 'leave-guard-save', 'leave-guard-discard'].forEach(function (id) { el(id).disabled = on; });
261
+ $modal.setAttribute('aria-busy', on ? 'true' : 'false');
262
+ if (label) el('leave-guard-save').textContent = label;
263
+ }
264
+
265
+ function done(result) {
266
+ if (settled) return;
267
+ settled = true;
268
+ $modal.classList.remove('show');
269
+ covered.forEach(function (c) {
270
+ c.m.inert = c.inert;
271
+ if (c.hidden === null) c.m.removeAttribute('aria-hidden'); else c.m.setAttribute('aria-hidden', c.hidden);
272
+ });
273
+ current = null;
274
+ openPromise = null;
275
+ if (!result) {
276
+ // Back to whatever opened the question; a menu row that has since closed with its menu
277
+ // is not reachable, so the caller's opener (the ≡ button, the avatar) takes it instead.
278
+ var usable = function (n) { return n && n.isConnected && (typeof n.getClientRects !== 'function' || n.getClientRects().length) && !n.matches(':disabled,[aria-disabled="true"]'); };
279
+ var target = usable(returnFocus) ? returnFocus : (opts && usable(opts.returnFocus) ? opts.returnFocus : null);
280
+ if (target) target.focus();
281
+ }
282
+ resolve(result);
283
+ }
284
+
285
+ /* The last word before acting: probe again, and go back to the dialog if the picture grew. */
286
+ async function proceed(decided, discardAll) {
287
+ var fresh = await collect();
288
+ if (settled) return;
289
+ if (grewSince(decided, fresh)) {
290
+ snapshot = fresh;
291
+ render(action, snapshot, 'Something changed while you were deciding. Check the list again.');
292
+ setBusy(false);
293
+ focusDefault();
294
+ return;
295
+ }
296
+ if (opts && typeof opts.commit === 'function') {
297
+ el('leave-guard-sub').textContent = COPY[action].working;
298
+ var outcome = null;
299
+ try { outcome = await opts.commit(); } catch (_) { outcome = null; }
300
+ if (settled) return;
301
+ if (!outcome || !outcome.ok) {
302
+ snapshot = fresh;
303
+ render(action, snapshot, (outcome && outcome.message) || COPY[action].failed);
304
+ setBusy(false);
305
+ focusDefault();
306
+ return;
307
+ }
308
+ }
309
+ if (discardAll) fresh.items.forEach(function (i) { if (typeof i.discard === 'function') i.discard(); });
310
+ window.__flolessLeaving = true; // no browser "Leave site?" prompt on the way out
311
+ done(true);
312
+ }
313
+
314
+ async function saveAll() {
315
+ setBusy(true, 'Saving…');
316
+ var failed = new Set();
317
+ for (var i = 0; i < snapshot.items.length; i++) {
318
+ var item = snapshot.items[i];
319
+ if (typeof item.save !== 'function') { failed.add(item.id); continue; }
320
+ try { if (!(await withTimeout(item.save(), api.saveTimeoutMs))) failed.add(item.id); }
321
+ catch (_) { failed.add(item.id); }
322
+ }
323
+ if (settled) return;
324
+ var fresh = await collect();
325
+ if (settled) return;
326
+ // A save that said it failed keeps us here even if its item no longer shows up (an editor
327
+ // closed mid-save): its change is not known to be saved, so it stays on the list.
328
+ var freshIds = idsOf(fresh);
329
+ snapshot.items.forEach(function (it) { if (failed.has(it.id) && !freshIds.has(it.id)) fresh.items.push(it); });
330
+ // Anything still unresolved after saving — whether its save said so or not — keeps us here.
331
+ fresh.items.forEach(function (it) { failed.add(it.id); });
332
+ if (fresh.items.length || (fresh.running && !snapshot.running)) {
333
+ snapshot = fresh;
334
+ render(action, snapshot, fresh.items.length ? 'Some of your work could not be saved:' : '', failed);
335
+ setBusy(false);
336
+ el('leave-guard-save').textContent = COPY[action].save;
337
+ focusDefault();
338
+ return;
339
+ }
340
+ await proceed(fresh, false);
341
+ }
342
+
343
+ function focusDefault() { setTimeout(function () { el('leave-guard-cancel').focus(); }, 0); }
344
+
345
+ function onKey(e) {
346
+ if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); if (!busy) done(false); return; }
347
+ if (e.key !== 'Tab') return;
348
+ e.stopPropagation();
349
+ var focusable = Array.from($modal.querySelectorAll('button:not([disabled]):not([hidden])'))
350
+ .filter(function (b) { return b.getClientRects().length; });
351
+ if (!focusable.length) { e.preventDefault(); return; }
352
+ var first = focusable[0]; var last = focusable[focusable.length - 1];
353
+ if (e.shiftKey && (document.activeElement === first || !$modal.contains(document.activeElement))) { e.preventDefault(); last.focus(); }
354
+ else if (!e.shiftKey && (document.activeElement === last || !$modal.contains(document.activeElement))) { e.preventDefault(); first.focus(); }
355
+ }
356
+
357
+ var downOnBackdrop = false;
358
+ wireOnce();
359
+ current = {
360
+ cancel: function () { if (!busy) done(false); },
361
+ confirm: function () { if (busy) return; setBusy(true); proceed(snapshot, false); },
362
+ discard: function () { if (busy) return; setBusy(true); proceed(snapshot, true); },
363
+ save: function () { if (!busy) saveAll(); },
364
+ // A backdrop click closes only when the press also began on it (a text-selection drag doesn't).
365
+ backdropDown: function (e) { downOnBackdrop = e.target === $modal; },
366
+ backdropClick: function (e) { var hit = e.target === $modal && downOnBackdrop; downOnBackdrop = false; if (hit && !busy) done(false); },
367
+ key: onKey,
368
+ };
369
+
370
+ // Show the dialog at once (modal: nothing is edited behind it while we look), then fill it in.
371
+ el('leave-guard-title').textContent = COPY[action].title;
372
+ el('leave-guard-sub').textContent = 'Checking for unsaved work…';
373
+ el('leave-guard-unsaved').hidden = true;
374
+ el('leave-guard-running').hidden = true;
375
+ el('leave-guard-note').hidden = true;
376
+ ['leave-guard-save', 'leave-guard-discard'].forEach(function (id) { el(id).hidden = true; });
377
+ el('leave-guard-confirm').hidden = false;
378
+ el('leave-guard-confirm').textContent = COPY[action].confirm;
379
+ setBusy(true);
380
+ $modal.classList.add('show');
381
+ focusDefault();
382
+ collect().then(function (s) {
383
+ if (settled) return;
384
+ snapshot = s;
385
+ render(action, snapshot);
386
+ setBusy(false);
387
+ });
388
+ });
389
+ return openPromise;
390
+ }
391
+
392
+ /* ── Stop FloLess ──────────────────────────────────────────────────────── */
393
+
394
+ var stopping = false;
395
+
396
+
397
+ /** After the server confirmed: quieten the page so it neither polls nor shows "Reconnecting…". */
398
+ function quiesce() {
399
+ window.__flolessStopped = true;
400
+ liveStreams.forEach(function (es) { try { es.close(); } catch (_) { /* already closed */ } });
401
+ liveStreams.clear();
402
+ // Anything the page still asks for would only fail against a server that is gone on purpose.
403
+ var nativeFetch = window.fetch;
404
+ window.fetch = function (input, init) {
405
+ var url = typeof input === 'string' ? input : (input && input.url) || '';
406
+ var sameOrigin = url.charAt(0) === '/' || url.indexOf(location.origin) === 0;
407
+ return sameOrigin ? new Promise(function () { /* never: the server is gone */ }) : nativeFetch.call(window, input, init);
408
+ };
409
+ document.querySelectorAll('iframe').forEach(function (f) { try { f.src = 'about:blank'; } catch (_) { /* detached */ } });
410
+ var overlay = document.getElementById('server-offline-overlay');
411
+ if (overlay) overlay.remove();
412
+ }
413
+
414
+ function renderStopped() {
415
+ if (document.getElementById('app-stopped')) return;
416
+ var mark = document.querySelector('header .brand .mark svg');
417
+ var wrap = document.createElement('div');
418
+ wrap.id = 'app-stopped';
419
+ wrap.setAttribute('role', 'alertdialog');
420
+ wrap.setAttribute('aria-modal', 'true');
421
+ wrap.setAttribute('aria-labelledby', 'app-stopped-title');
422
+ wrap.setAttribute('aria-describedby', 'app-stopped-body');
423
+ wrap.innerHTML =
424
+ '<div class="as-card" tabindex="-1">' +
425
+ '<div class="as-mark" aria-hidden="true"></div>' +
426
+ '<h1 id="app-stopped-title">FloLess has stopped</h1>' +
427
+ '<p id="app-stopped-body">FloLess is no longer running. You can close this tab.</p>' +
428
+ '<a class="as-start" id="app-stopped-start" href="floless://start" data-command-id="app.start-again"' +
429
+ ' data-tip="Opens FloLess again on this computer">Start FloLess again</a>' +
430
+ '<p class="as-status" id="app-stopped-status" role="status"></p>' +
431
+ '</div>';
432
+ if (mark) wrap.querySelector('.as-mark').appendChild(mark.cloneNode(true));
433
+ // Everything behind the panel is dead — take it out of the tab order and the accessibility tree.
434
+ Array.from(document.body.children).forEach(function (child) { if (child !== wrap) child.inert = true; });
435
+ document.body.appendChild(wrap);
436
+ // A real link the user clicks: a scripted click on an external protocol is dropped by Chromium.
437
+ document.getElementById('app-stopped-start').addEventListener('click', function () {
438
+ document.getElementById('app-stopped-status').textContent =
439
+ 'Starting FloLess… When it is ready, reload this tab. If nothing happens, open FloLess from the Start menu.';
440
+ });
441
+ wrap.querySelector('.as-card').focus();
442
+ }
443
+
444
+ /** The server's answer to POST /api/app/stop, in words for the dialog. Only a refusal the server
445
+ * words for people is passed through; anything else gets the generic sentence. */
446
+ var STOP_REFUSALS = { 'supervisor-still-running': true };
447
+ async function requestStop() {
448
+ var res;
449
+ try { res = await fetch('/api/app/stop', { method: 'POST' }); }
450
+ catch (_) {
451
+ return { ok: false, message: 'FloLess could not be reached to stop it. It may already have stopped — reload this tab to check.' };
452
+ }
453
+ if (res.status === 202) return { ok: true };
454
+ var body = await res.json().catch(function () { return {}; });
455
+ return { ok: false, message: body && STOP_REFUSALS[body.code] && body.error ? body.error : null };
456
+ }
457
+
458
+ async function stopApp() {
459
+ if (stopping || window.__flolessStopped) return;
460
+ stopping = true;
461
+ try {
462
+ var go = await confirm({ action: 'stop', returnFocus: document.getElementById('menu-btn'), commit: requestStop });
463
+ if (!go) return;
464
+ quiesce();
465
+ renderStopped();
466
+ } finally {
467
+ if (!window.__flolessStopped) stopping = false;
468
+ }
469
+ }
470
+
471
+ var api = window.flolessLeaveGuard = {
472
+ saveTimeoutMs: 20000, // how long one item's save may take before it counts as not saved
473
+ register: register,
474
+ registerFrame: registerFrame,
475
+ probeFrame: probeFrame,
476
+ collect: collect,
477
+ confirm: confirm,
478
+ stopApp: stopApp,
479
+ };
480
+ })();
@@ -784,7 +784,7 @@ body.publication-blocked #empty{position:static;flex:1}
784
784
  which broadcast) — that failure is the AI's to report, in the terminal where the user asked
785
785
  for it — and a re-bake whose result is canonically equal to what is already stored, where
786
786
  there is nothing new to show. -->
787
- <p class="hint" style="margin-top:8px;max-width:340px">Ask your terminal AI to prepare the Drawing Filter. Its layers, line weights and colours will appear here automatically when ready.</p>
787
+ <p class="hint" style="margin-top:8px;max-width:340px">The AI reading your drawings prepares this filter. Its layers, line weights and colours will appear here automatically when ready.</p>
788
788
  </div>
789
789
  </div>
790
790
  <!-- The ONLY fit/zoom controls -- plus, after the divider, Hover info, which is a canvas READ tool
@@ -1866,8 +1866,8 @@ async function bootOnce(){
1866
1866
  // No filter at all IS "nobody has prepared this yet", and the bare empty state says so correctly.
1867
1867
  if(!F){ showEmpty(); return; }
1868
1868
  // A filter that WAS prepared and legitimately carries nothing is a different thing, and the bare
1869
- // empty state tells that user to "ask your terminal AI to prepare the Drawing Filter" — about a
1870
- // filter their AI already prepared. There is no way out of that loop: re-baking reproduces the same
1869
+ // empty state says the AI reading their drawings "prepares this filter" — about a filter their AI
1870
+ // already prepared. There is no way out of that loop: re-baking reproduces the same
1871
1871
  // empty screen, and nothing on it distinguishes "not started" from "started and found nothing".
1872
1872
  //
1873
1873
  // This is the same failure the 402/500 branch above was given its own copy to avoid, quoted there:
@@ -1877,7 +1877,7 @@ async function bootOnce(){
1877
1877
  // hundreds of thousands of phantom ones. A raster-only sheet lands here for the same reason.
1878
1878
  if(!sheets.some(s => Array.isArray(s.elements) && s.elements.length)){
1879
1879
  showEmpty('This drawing set has nothing to filter.', false,
1880
- 'Your terminal AI read this drawing set and found no vector linework or text on any sheet — a scan with no drawn lines reads this way. If that looks wrong, ask it to re-read the source file.');
1880
+ 'The AI read this drawing set and found no vector linework or text on any sheet — a scan with no drawn lines reads this way. If that looks wrong, ask it to re-read the source file.');
1881
1881
  return;
1882
1882
  }
1883
1883
  document.getElementById('empty').classList.remove('show');
@@ -1929,7 +1929,8 @@ function showEmpty(msg, publicationBlocked = false, detail = ''){
1929
1929
  body.hidden = !detail;
1930
1930
  if(msg){
1931
1931
  e.querySelector('h1').textContent = msg;
1932
- // The hint below explains how a filter gets BAKED ("your terminal AI reads the drawing once…"). Under an
1932
+ // The hint below explains how a filter gets BAKED ("The AI reading your drawings prepares this
1933
+ // filter…" — deliberately naming no terminal, because AI Chat may be the thing reading). Under an
1933
1934
  // error headline — "Could not reach the server.", a 402, "No app specified." — that answers a question
1934
1935
  // nobody asked and implies the thing is merely pending, so it goes away with the good news.
1935
1936
  const hint = e.querySelector('.hint');
@@ -587,20 +587,37 @@
587
587
  const bar = document.getElementById('conflictBanner'); if (bar) bar.remove();
588
588
  };
589
589
  }
590
+ let pendingWrites = 0; // queued or in-flight PUTs — contractSaveState() reads 'saving' until they settle
590
591
  function persistServer() {
591
592
  if (!editable || !C) return Promise.resolve(true);
592
593
  const gen = ++saveGen;
594
+ pendingWrites += 1;
593
595
  saveQueue = saveQueue.then(() => (gen === saveGen ? doPut() : true)); // superseded → the newer write carries C
594
- return saveQueue;
596
+ const tail = saveQueue;
597
+ const settle = () => { pendingWrites -= 1; };
598
+ tail.then(settle, settle);
599
+ return tail;
595
600
  }
596
- function scheduleSave() { if (!editable) return; setSaved('dirty'); clearTimeout(saveT); saveT = setTimeout(persistServer, 500); }
601
+ function scheduleSave() { if (!editable) return; setSaved('dirty'); clearTimeout(saveT); saveT = setTimeout(() => { saveT = 0; persistServer(); }, 500); }
597
602
  // The shell's Approve button awaits this before baking — throw so a rejected save aborts the bake.
598
603
  window.flushContract = async function flushContract() {
599
604
  if (!editable) return;
600
- clearTimeout(saveT);
605
+ clearTimeout(saveT); saveT = 0;
601
606
  const ok = await persistServer(); // queued behind any in-flight write → latest state, in order
602
607
  if (!ok) throw new Error('Save failed — the edited contract was rejected; fix it before Approve');
603
608
  };
609
+ // Mirrors the steel editor's contractSaveState() so the shell's leave guard (Stop FloLess / Sign
610
+ // Out) can tell a saved drawing from one with a queued or failed write. Only 'clean' is saved.
611
+ window.contractSaveState = function contractSaveState() {
612
+ if (!editable) return 'clean'; // a read-only view holds nothing to lose
613
+ const el = $('saveStat');
614
+ if (conflicted || (el && el.classList.contains('conflict'))) return 'conflict';
615
+ if (pendingWrites > 0) return 'saving';
616
+ if (saveT) return 'dirty';
617
+ if (el && el.classList.contains('err')) return 'error';
618
+ if (el && el.classList.contains('dirty')) return 'dirty';
619
+ return 'clean';
620
+ };
604
621
 
605
622
  // ── weak-trace review: Accept clears the flag (absent = trusted), Delete removes with 1-level Undo ──
606
623
  function isWeak(el) { return el.confidence != null && el.confidence < WEAK; }