@floless/app 0.149.1 → 0.151.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.
Files changed (50) hide show
  1. package/dist/floless-server.cjs +104263 -88361
  2. package/dist/schemas/drawing-check.profile.v1.schema.json +45 -2
  3. package/dist/schemas/steel.model.v2.schema.json +9 -0
  4. package/dist/skills/floless-app-approval/SKILL.md +79 -4
  5. package/dist/skills/floless-app-onboarding/SKILL.md +200 -87
  6. package/dist/skills/floless-app-onboarding/references/aware-runtime.md +27 -18
  7. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +207 -0
  8. package/dist/skills/floless-app-routines/SKILL.md +4 -1
  9. package/dist/skills/floless-app-routines/references/routines-api.md +14 -2
  10. package/dist/skills/floless-app-steel-model/SKILL.md +4 -2
  11. package/dist/skills/floless-app-steel-takeoff/SKILL.md +14 -9
  12. package/dist/skills/floless-app-workflows/SKILL.md +2 -2
  13. package/dist/templates/tekla-parser.flo +13 -3
  14. package/dist/web/agents.js +983 -0
  15. package/dist/web/app.css +556 -43
  16. package/dist/web/app.js +34 -112
  17. package/dist/web/aware.js +1774 -169
  18. package/dist/web/chat.css +62 -1
  19. package/dist/web/chat.js +1666 -59
  20. package/dist/web/commands-drawing-check.js +15 -0
  21. package/dist/web/commands-revit.js +5 -0
  22. package/dist/web/commands-shell.js +955 -53
  23. package/dist/web/commands-tekla-parser.js +8 -1
  24. package/dist/web/connections.js +57 -14
  25. package/dist/web/drawing-check-editor.html +10 -2
  26. package/dist/web/drawing-check-editor.js +569 -40
  27. package/dist/web/drawing-check-overlay.js +45 -2
  28. package/dist/web/guide.js +675 -0
  29. package/dist/web/index.html +162 -31
  30. package/dist/web/instructor.js +91 -8
  31. package/dist/web/leave-guard.js +1 -0
  32. package/dist/web/left-pane.js +20 -1
  33. package/dist/web/local-discovery.js +12 -2
  34. package/dist/web/model-editor.css +32 -32
  35. package/dist/web/model-panel-bridge.js +11 -3
  36. package/dist/web/model-viewport-lighting.js +4 -2
  37. package/dist/web/model-viewport-revit-adapter.js +3 -0
  38. package/dist/web/model-viewport-toolbar.js +6 -3
  39. package/dist/web/model-viewport.js +11 -1
  40. package/dist/web/revit-editor.css +14 -14
  41. package/dist/web/revit-editor.js +64 -12
  42. package/dist/web/steel-3d-core.js +133 -0
  43. package/dist/web/steel-3d-view.js +10 -0
  44. package/dist/web/steel-editor.html +171 -39
  45. package/dist/web/steel-model-v2-client-validation.js +11 -0
  46. package/dist/web/steel-model-v2-commands.js +80 -5
  47. package/dist/web/tool-updates.js +533 -0
  48. package/dist/web/workspaces.js +896 -123
  49. package/package.json +2 -2
  50. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +0 -156
@@ -5,7 +5,7 @@
5
5
  // the person's ticks, starts a run the server performs with fixed code, and draws the stored result with
6
6
  // the SAME overlay module the run report uses (drawing-check-overlay.js), so the two cannot disagree.
7
7
  // Wording rule: FloLess "looked at" a sheet; only a person marks one checked.
8
- import { DEFAULT_COLOURS, hatchDefs, overlaySvg } from './drawing-check-overlay.js';
8
+ import { DEFAULT_COLOURS, hatchDefs, overlaySvg, withAccepted } from './drawing-check-overlay.js';
9
9
 
10
10
  // ── pure helpers (exported for server/drawing-check-ui.test.ts) ─────────────────────────────────
11
11
 
@@ -18,13 +18,19 @@ export function paddedViewBox(bbox, pad) {
18
18
  return { x: x0 - pad, y: y0 - pad, w: Math.max(1, x1 - x0) + 2 * pad, h: Math.max(1, y1 - y0) + 2 * pad };
19
19
  }
20
20
 
21
+ /** Evidence that sits on the shown drawing: the other half of a cross-sheet finding is not on this sheet. */
22
+ export function onDrawing(evidence, drawing) {
23
+ return evidence.filter((e) => !(e.drawing && drawing && e.drawing !== drawing));
24
+ }
25
+
21
26
  /**
22
27
  * What clicking an item in the list does to the view: zoom to its FIRST evidence box with ITEM_PAD
23
28
  * points around it, or — for an item written in the sheet margin, or one with no box — fit the page.
24
29
  * Returns the note to show beside the item, if any.
25
30
  */
26
- export function focusItem(view, item) {
27
- const box = item && !item.margin && item.evidence && item.evidence[0] && item.evidence[0].bbox;
31
+ export function focusItem(view, item, drawing) {
32
+ const here = item && item.evidence ? onDrawing(item.evidence, drawing) : [];
33
+ const box = item && !item.margin && here[0] && here[0].bbox;
28
34
  if (box) { view.fitTo(box, ITEM_PAD); return ''; }
29
35
  view.fit();
30
36
  return item && item.margin ? 'Written in the sheet margin.' : 'This item has no place on the drawing to show.';
@@ -217,6 +223,142 @@ export function unsignedTip(signature) {
217
223
  : 'The run record couldn’t be signed on this PC, so nothing proves these results were not changed since the run.';
218
224
  }
219
225
 
226
+ /** A person's recorded decision on a finding, in the run page's words. The status it relabels stays shown beside it. @param {*} d */
227
+ export function decisionWords(d) {
228
+ const what = d.choice === 'accept' ? `Accepted as drawn by ${d.by}: ${d.reason || ''}` : `RFI raised (${d.rfi || ''})`;
229
+ const carried = !d.carriedFrom ? '' : d.carriedFrom.unverified ? ' · carried over from an earlier run whose record could not be verified' : ' · carried over from an earlier run';
230
+ return `${what}${carried}`;
231
+ }
232
+
233
+ /** @typedef {{ current: Record<string, any>, mismatched: any[], offers: any[], rfiText: Record<string, string>, signature: any }} RunDecisions */
234
+
235
+ /** No decisions loaded (yet, or they could not be read): nothing is decided, nothing is offered. @type {Readonly<RunDecisions>} */
236
+ export const NO_DECISIONS = Object.freeze({ current: {}, mismatched: [], unreadableLines: [], offers: [], rfiText: {}, signature: null });
237
+
238
+ /** Said when a decision was recorded but the decisions could not be read back: what is on screen stays. */
239
+ export const DECISIONS_STALE = 'Recorded. FloLess couldn’t refresh the decisions; reload the page to see them.';
240
+
241
+ /** Said in the run bar when another run could not be opened: nothing was switched (owner ruling 2026-10-04). */
242
+ export const OPEN_FAILED = 'FloLess couldn’t open that check. The current one is still shown. Try again.';
243
+ /** Said in the run bar when something in flight failed while the person was leaving the run: it stays open. */
244
+ export const LEAVE_STAYED = 'Your last change on this run didn’t go through, so FloLess kept this run open. The reason is shown where you made the change. Try again, or leave the run again to go on without it.';
245
+
246
+ /**
247
+ * What the run bar's status line (#run-status) says: while leaving a run waits for what is in flight on it, a spinner
248
+ * and where FloLess goes next; after a failed open or a change that did not go through, why the run is still shown.
249
+ * @param {{ text: string, wait?: boolean } | null} st
250
+ */
251
+ export function runStatusHtml(st) {
252
+ if (!st) return '';
253
+ // A finished check offered, not opened: "Open it" is a run button, like a row of the runs list.
254
+ if (st.offer) return `<span>${esc(st.text)}</span><button type="button" class="link" data-run="${esc(st.offer)}" data-command-id="drawing-check.open-finished-check">Open it</button>`;
255
+ return st.wait ? `<span class="spin" aria-hidden="true"></span><span>${esc(st.text)}</span>` : `<span class="err-line">${esc(st.text)}</span>`;
256
+ }
257
+
258
+ /**
259
+ * The decisions recorded on this page but not yet seen in a refresh (`{ findingId, at, after }`), after a refresh
260
+ * answered `body`. One is confirmed only by a refresh whose decisions could all be read and that shows a decision on
261
+ * its finding at least as new as the one recorded (`at`, the time the server recorded it), or, with no time from the
262
+ * server, newer than the decision shown before it was recorded (`after`). Anything less keeps it pending, so the
263
+ * finding offers no action that would record it twice (defect A, owner ruling 2026-10-04).
264
+ * @param {{ findingId: string, at: string, after: string }[]} pending @param {*} body
265
+ */
266
+ export function stillPending(pending, body) {
267
+ if (!body || body.unreadable) return pending;
268
+ const current = body.current || {};
269
+ return pending.filter((p) => {
270
+ const d = current[p.findingId];
271
+ const at = d && typeof d.at === 'string' ? d.at : null;
272
+ return !(at !== null && (p.at ? at >= p.at : at > (p.after || '')));
273
+ });
274
+ }
275
+
276
+ /**
277
+ * The finding ids still pending on one run, from the page's per-run list. Pending is kept per run id, so a decision
278
+ * recorded on one run stays pending when another run is opened and this one opened again (defect A, owner ruling
279
+ * 2026-10-04 "Split"): only a refresh of THIS run that shows the decision clears it.
280
+ * @param {Record<string, { findingId: string }[]>} byRun @param {string | undefined} runId
281
+ */
282
+ export const pendingIds = (byRun, runId) => ((runId && byRun && byRun[runId]) || []).map((p) => p.findingId);
283
+
284
+ /**
285
+ * Finding ids whose latest decision is "accept as drawn": their boxes are drawn in the accepted style. None when
286
+ * the run's record does not verify (`unverified`): the dash-dot line would vouch for a decision nothing proves, so
287
+ * the box keeps its plain status and only the text line says "(unverified)". Never a `pending` finding: a newer
288
+ * decision on it was recorded and not yet shown, so the acceptance on screen may already be replaced (defect B,
289
+ * owner ruling 2026-10-04 "Split") and must not be drawn as standing.
290
+ * @param {*} dec @param {boolean} [unverified] @param {string[]} [pending]
291
+ */
292
+ export const acceptedFindingIds = (dec, unverified = false, pending = []) => (unverified ? []
293
+ : Object.values((dec && dec.current) || {}).filter((d) => d.choice === 'accept' && !pending.includes(d.findingId)).map((d) => d.findingId));
294
+
295
+ /**
296
+ * The selected item's open findings (wrong or couldn't tell), each with its decision and the three things a
297
+ * person can do: fix the drawing (records nothing), raise an RFI, or accept it as drawn on a stated reason.
298
+ * An earlier run's decision on the same finding is offered, never applied. `unverified`: the run's record no
299
+ * longer verifies, so its decisions are labelled like its results. `carryNote`: a carry-over that could not be
300
+ * recorded (the offer went stale) — said on its own finding, with "Record it as a new decision". `pending`:
301
+ * findings whose decision was recorded but no refresh has shown yet (see stillPending): they say so and offer no
302
+ * action, even when an earlier decision on them is still shown, so nothing invites recording it twice.
303
+ * @param {*} it
304
+ * @param {RunDecisions} [dec]
305
+ * @param {{ unverified?: boolean, carryNote?: { findingId: string, text: string } | null, colours?: Record<string, string>, pending?: string[] }} [opts]
306
+ */
307
+ export function findingsHtml(it, dec = NO_DECISIONS, { unverified = false, carryNote = null, colours = statusColours(), pending = [] } = {}) {
308
+ const all = Array.isArray(it.findings) ? it.findings : [];
309
+ const open = all.filter((f) => f.status !== 'pass');
310
+ if (!open.length) return '';
311
+ const cards = open.map((f) => {
312
+ const k = all.indexOf(f);
313
+ const num = all.length > 1 ? `${it.n}.${k + 1}` : String(it.n);
314
+ const d = dec.current[f.id];
315
+ const offer = d ? null : dec.offers.find((o) => o.findingId === f.id);
316
+ const fid = esc(f.id);
317
+ // Not a live region: re-drawing the list would re-announce every decision. One shared #dec-live says the new one.
318
+ const decided = d ? `<p class="decided">${esc(decisionWords(d))}${unverified ? ' <span class="unv">(unverified)</span>' : ''}</p>` : '';
319
+ const earlier = offer && (offer.from.choice === 'accept'
320
+ ? `accepted as drawn by ${esc(offer.from.by)}, ‘${esc(offer.from.reason || '')}’` : `RFI raised by ${esc(offer.from.by)} (${esc(offer.from.rfi || '')})`);
321
+ const carry = offer ? `<div class="carry"><p class="note">An earlier run has a decision on this: ${earlier}.${offer.unverified ? ' <span class="unv">(unverified: that run’s record could not be verified)</span>' : ''}</p>
322
+ <button type="button" data-act="finding-carry" data-finding="${fid}" data-command-id="drawing-check.finding-carry-over">Carry it over to this run</button></div>` : '';
323
+ // The box colour and line this finding has on the drawing; an accepted one takes the Wrong colour. The overlay
324
+ // draws accepted as dash-dot, which CSS borders cannot, so the swatch is dashed (the nearest a border gets).
325
+ // On an unverified record the drawing keeps the plain status, and so does the swatch; and while a newer decision
326
+ // on it is pending, the acceptance shown may already be replaced, so it is not drawn as accepted either.
327
+ const accepted = !!d && d.choice === 'accept' && !unverified && !pending.includes(f.id);
328
+ const sw = LINE[accepted ? 'fail' : f.status] || LINE.fail;
329
+ const swatch = `<i class="swatch" aria-hidden="true" style="border-top:${sw.w + 0.6}px ${accepted || sw.dash ? 'dashed' : 'solid'} ${esc(colours[accepted ? 'fail' : f.status] || colours.fail)}"></i>`;
330
+ const again = d ? '<p class="note">Recording again replaces this decision.</p>' : '';
331
+ const stale = carryNote && carryNote.findingId === f.id ? `<div class="carry" role="alert"><p class="err-line">${esc(carryNote.text)}</p>
332
+ <button type="button" data-act="finding-record-new" data-finding="${fid}" data-command-id="drawing-check.finding-record-new">Record it as a new decision</button></div>` : '';
333
+ const head = `<div class="finding" role="group" aria-labelledby="fh-${fid}" data-finding-card="${fid}"><div class="fh" id="fh-${fid}">${swatch}<b>${esc(num)}</b> <span class="fst">${STATUS_WORD[f.status] || esc(f.status)}</span></div>
334
+ <p class="freason">${esc(f.reason)}</p>`;
335
+ // Pending until a refresh shows THIS decision: an earlier decision still on screen must not bring the actions back.
336
+ if (pending.includes(f.id)) return `${head}<p class="decided">Recorded — reload the page to see it.</p></div>`;
337
+ return `${head}${decided}${carry}${stale}
338
+ ${again}<div class="row-actions"><button type="button" data-act="finding-fix" data-finding="${fid}" data-command-id="drawing-check.finding-fix" data-tip="Nothing is recorded. Correct the drawing, then check it again.">Fix the drawing</button>
339
+ <button type="button" data-act="finding-rfi" data-finding="${fid}" data-command-id="drawing-check.finding-rfi">Raise an RFI</button>
340
+ <button type="button" data-act="finding-accept" data-finding="${fid}" data-command-id="drawing-check.finding-accept">Accept as drawn</button></div></div>`;
341
+ }).join('');
342
+ return `<div class="findings" role="group" aria-label="What to do about item ${esc(it.n)}">${cards}</div>`;
343
+ }
344
+
345
+ /**
346
+ * What an item's status line adds once some of its open findings are decided: '' when none is. A `pending` finding
347
+ * is decided (its decision was recorded) but which way is not shown yet, so it is counted, never summed up as
348
+ * "accepted as drawn" or "RFI raised" on the strength of the decision it may have replaced.
349
+ */
350
+ export function decidedSuffix(it, dec = NO_DECISIONS, pending = []) {
351
+ const open = (Array.isArray(it.findings) ? it.findings : []).filter((f) => f.status !== 'pass');
352
+ const decided = open.filter((f) => dec.current[f.id] || pending.includes(f.id));
353
+ if (!decided.length) return '';
354
+ const shown = decided.filter((f) => !pending.includes(f.id)).map((f) => dec.current[f.id]);
355
+ if (decided.length === open.length && shown.length === decided.length) {
356
+ if (shown.every((d) => d.choice === 'accept')) return ' · accepted as drawn';
357
+ if (shown.every((d) => d.choice === 'rfi')) return ' · RFI raised';
358
+ }
359
+ return ` · ${decided.length} of ${open.length} decided`;
360
+ }
361
+
220
362
  /** "1 question about the title block": the notice at the top of the Checklist tab, or '' when none. */
221
363
  export function pendingAsksNotice(tb) {
222
364
  const n = (tb && tb.asks && tb.asks.length) || 0;
@@ -291,6 +433,12 @@ function boot() {
291
433
  draft: null, etag: null, review: null, reviewError: '', runs: [], runsError: '', colours: null, colourWarning: null,
292
434
  tab: null, loadError: '', uploadNote: '', newSinceApproval: 0, checklistError: '', conflict: false, titleNote: '', titleNoteField: '', tbSaving: false, tbChanges: [], typed: {},
293
435
  running: null, run: null, sheet: 0, selectedN: null, itemNote: '', exportCard: null, runError: '',
436
+ // Decisions recorded but not yet shown by a refresh, per run id (see stillPending). Only the run on screen writes
437
+ // it; it is kept per run so that coming back to a run whose decisions still cannot be read never brings back the
438
+ // actions that would record one twice (defect A).
439
+ decisions: NO_DECISIONS, decisionsError: '', carryNote: null, pendingByRun: {},
440
+ // The run bar's status line (runStatusHtml): leaving a run that is still saving, or why it is still shown.
441
+ runStatus: null,
294
442
  };
295
443
 
296
444
  async function call(path, opts = {}) {
@@ -579,11 +727,16 @@ function boot() {
579
727
  scrim.className = 'scrim';
580
728
  scrim.innerHTML = `<div class="dialog" role="dialog" aria-modal="true" aria-labelledby="dlg-title"><h2 id="dlg-title">${esc(title)}</h2><div class="body">${body}</div><div class="foot">${foot}</div></div>`;
581
729
  document.body.appendChild(scrim);
582
- openDialog = { scrim, returnFocus: returnFocus || document.activeElement };
730
+ const back = returnFocus || document.activeElement;
731
+ // A button that a repaint replaces is gone by close time: remember how to find its successor.
732
+ // Failing that, the finding's Accept button: "Record it as a new decision" disappears once its note clears.
733
+ const again = back && back.dataset && back.dataset.act && back.dataset.finding
734
+ ? [`[data-act="${back.dataset.act}"][data-finding="${back.dataset.finding}"]`, `[data-act="finding-accept"][data-finding="${back.dataset.finding}"]`] : [];
735
+ openDialog = { scrim, returnFocus: back, again };
583
736
  scrim.addEventListener('keydown', (e) => {
584
737
  if (e.key === 'Escape') { e.preventDefault(); closeDialog(); return; }
585
738
  if (e.key !== 'Tab') return;
586
- const f = [...scrim.querySelectorAll('button:not([disabled]),input:not([disabled])')].filter((el) => !(el.type === 'radio' && !el.checked));
739
+ const f = [...scrim.querySelectorAll('button:not([disabled]),input:not([disabled]),textarea:not([disabled])')].filter((el) => !(el.type === 'radio' && !el.checked));
587
740
  if (!f.length) return;
588
741
  if (e.shiftKey && document.activeElement === f[0]) { e.preventDefault(); f.at(-1).focus(); }
589
742
  else if (!e.shiftKey && document.activeElement === f.at(-1)) { e.preventDefault(); f[0].focus(); }
@@ -593,9 +746,11 @@ function boot() {
593
746
  }
594
747
  function closeDialog(restore = true) {
595
748
  if (!openDialog) return;
596
- const { scrim, returnFocus } = openDialog;
749
+ const { scrim, returnFocus, again } = openDialog;
597
750
  openDialog = null; scrim.remove();
598
- if (restore && returnFocus && returnFocus.isConnected) returnFocus.focus();
751
+ if (!restore) return;
752
+ if (returnFocus && returnFocus.isConnected) returnFocus.focus();
753
+ else { const next = again.map((sel) => document.querySelector(sel)).find(Boolean); if (next) next.focus(); }
599
754
  }
600
755
 
601
756
  function addItemDialog() {
@@ -726,11 +881,44 @@ function boot() {
726
881
  }
727
882
  return paths;
728
883
  }
884
+ /**
885
+ * The latest approved checklist was made by a newer FloLess (owner ruling 7: it asks, it does not stop): say
886
+ * so, and offer the newest earlier approved version this FloLess can read when there is one. Resolves to
887
+ * that version number, or null on Close, so the run stops with the message.
888
+ */
889
+ function tooNewDialog(e) {
890
+ const earlier = Array.isArray(e.body.previousApproved) ? e.body.previousApproved[0] : undefined;
891
+ const offered = typeof earlier === 'number' ? earlier : undefined;
892
+ return new Promise((resolve) => {
893
+ let settled = false;
894
+ const finish = (v) => { if (settled) return; settled = true; closeDialog(); resolve(v); };
895
+ const scrim = showDialog({
896
+ title: 'This checklist is newer than this FloLess',
897
+ body: '<p>It was approved in a newer FloLess, which this one can’t read. To check against it, update FloLess, then check the drawings again.</p>'
898
+ + (offered === undefined ? '' : `<p>Or check these drawings against approved version ${offered}, which this FloLess can read. Every sheet will say this run used version ${offered}, not the latest.</p>`),
899
+ // The deliberate choice (an older version) sits left; Close is the primary on the right and keeps focus, so
900
+ // it stands in for "Update FloLess" and Enter never runs an older version.
901
+ foot: (offered === undefined ? '' : `<button type="button" data-dlg="older" data-command-id="drawing-check.check-with-version">Run version ${offered} instead</button>`)
902
+ + '<button type="button" class="primary" data-dlg="close" data-command-id="drawing-check.close-newer-notice">Close</button>',
903
+ returnFocus: root.querySelector('[data-act="check"]'),
904
+ onOpen: (sc) => {
905
+ sc.querySelector('[data-dlg="close"]').focus();
906
+ sc.addEventListener('click', (ev) => {
907
+ const act = ev.target.closest('[data-dlg]')?.dataset.dlg;
908
+ if (act === 'close') finish(null);
909
+ if (act === 'older' && offered !== undefined) finish(offered);
910
+ });
911
+ },
912
+ });
913
+ new MutationObserver((_, obs) => { if (!scrim.isConnected) { obs.disconnect(); if (!settled) { settled = true; resolve(null); } } }).observe(document.body, { childList: true });
914
+ });
915
+ }
729
916
  /**
730
917
  * The latest approved checklist cannot be read: offer the newest earlier approved version instead of
731
918
  * stopping. Resolves to that version number, or null when there is none or the person cancels.
732
919
  */
733
920
  function fallbackDialog(e) {
921
+ if (e && e.body && e.body.code === 'profile-too-new') return tooNewDialog(e);
734
922
  const offered = e && e.body && e.body.code === 'profile-unreadable' && Array.isArray(e.body.previousApproved) ? e.body.previousApproved[0] : undefined;
735
923
  if (typeof offered !== 'number') return Promise.resolve(null);
736
924
  return new Promise((resolve) => {
@@ -784,7 +972,7 @@ function boot() {
784
972
  const { body } = await call(`${base}/runs`, jsonOpts('POST', { drawings: paths, decisions, ...(version !== undefined ? { version } : {}) }));
785
973
  S.running = null;
786
974
  await loadRuns();
787
- await openRun(body.runId);
975
+ await checkFinished(body.runId);
788
976
  } catch (e) { S.running = null; S.runError = e.message; render(); }
789
977
  }
790
978
 
@@ -820,14 +1008,311 @@ function boot() {
820
1008
  });
821
1009
  }
822
1010
 
1011
+ // ── leaving a run (owner ruling 2026-10-04, "stop it at the source") ──
1012
+ // A run's reply can never land on another run, because the page never leaves a run while something it started is
1013
+ // still answering. Every operation that writes for the run on screen (a decision save with its read-back, a
1014
+ // carry-over, mark checked, export) is counted in `inFlight` (track). Leaving the run (another run, the runs list,
1015
+ // another tab) goes through leaveRun, the one place that waits for them; a run counts as switched only once the new
1016
+ // one has loaded (openRun). `navSeq`: the latest way out the person chose wins. `lastRead`: per run, the latest
1017
+ // decisions read asked for; an older answer is ignored. `lastFailed`: the last operation that settled on this run
1018
+ // failed, so the page reports "not saved" (contractSaveState) until another one works or the run is left.
1019
+ const inFlight = new Set(); let navSeq = 0, readSeq = 0, lastFailed = false; const lastRead = {};
1020
+
1021
+ /**
1022
+ * Run `job` (an operation on the run on screen) and count it as in flight until it settles. The job resolves to ''
1023
+ * (or nothing) when it worked, else to what went wrong, which it has already shown where the person made the change.
1024
+ */
1025
+ function track(job) {
1026
+ const p = job();
1027
+ inFlight.add(p);
1028
+ p.then((v) => { inFlight.delete(p); lastFailed = !!v; }, () => { inFlight.delete(p); lastFailed = true; });
1029
+ return p;
1030
+ }
1031
+ /** Wait until nothing is in flight. True when anything that settled meanwhile went wrong. */
1032
+ async function settled() {
1033
+ let failed = false;
1034
+ while (inFlight.size) {
1035
+ const outcomes = await Promise.allSettled([...inFlight]);
1036
+ failed = outcomes.some((o) => o.status === 'rejected' || !!o.value) || failed;
1037
+ }
1038
+ return failed;
1039
+ }
1040
+ /** Say `st` in the run bar's status line, in place (the node stays, so a screen reader hears the change). */
1041
+ function setRunStatus(st) {
1042
+ S.runStatus = st;
1043
+ const el = document.getElementById('run-status');
1044
+ if (el) el.innerHTML = runStatusHtml(st);
1045
+ }
1046
+ /**
1047
+ * The one place that waits: before the run on screen is left, everything in flight on it settles, with the run bar
1048
+ * saying so. Resolves true when it may be left. When something failed meanwhile, the run stays open (its reason is
1049
+ * shown where the change was made) and the run bar says why; leaving again goes, since nothing is in flight then.
1050
+ */
1051
+ async function leaveRun(where) {
1052
+ if (!S.run || !inFlight.size) return true;
1053
+ setRunStatus({ wait: true, text: `Saving your last change on this run… FloLess will ${where} when it’s done.` });
1054
+ if (await settled()) { setRunStatus({ text: LEAVE_STAYED }); return false; }
1055
+ setRunStatus(null);
1056
+ return true;
1057
+ }
1058
+
1059
+ /**
1060
+ * Open a run. It is fetched with its decisions first, both for THIS open; the run on screen (if any) is left only
1061
+ * after that, through leaveRun, and the page changes over in one step: its dialog closes, then S.run, its decisions
1062
+ * and the overlay become the new run's. If the run or its decisions cannot be loaded, nothing changes and the run bar
1063
+ * says so: a run is never shown with its decisions blank.
1064
+ */
823
1065
  async function openRun(runId) {
1066
+ const my = ++navSeq;
824
1067
  S.runError = '';
1068
+ let body, decisions;
825
1069
  try {
826
- const { body } = await call(`${base}/runs/${encodeURIComponent(runId)}`);
827
- S.run = body.result; S.runLabels = body.labels || {}; S.sheet = 0; S.selectedN = null; S.itemNote = ''; S.exportCard = null; S.tab = 'runs';
828
- } catch (e) { S.runError = e.message; }
1070
+ ({ body } = await call(`${base}/runs/${encodeURIComponent(runId)}`));
1071
+ ({ body: decisions } = await call(`${base}/runs/${encodeURIComponent(runId)}/decisions`));
1072
+ } catch (e) {
1073
+ if (my !== navSeq) return;
1074
+ if (S.run) setRunStatus({ text: OPEN_FAILED }); else { S.runError = e.message; render(); }
1075
+ return;
1076
+ }
1077
+ // A way out chosen later wins: this run arriving, or its wait ending, after it changes nothing.
1078
+ if (my !== navSeq || !await leaveRun('open the other run') || my !== navSeq) return;
1079
+ if (S.run) closeDialog(false);
1080
+ S.run = body.result; S.runLabels = body.labels || {}; S.sheet = 0; S.selectedN = null; S.itemNote = ''; S.exportCard = null; S.tab = 'runs';
1081
+ // Pending decisions are NOT cleared: they belong to their run, and only a refresh that shows them clears them.
1082
+ S.carryNote = null; S.runStatus = null; lastFailed = false;
1083
+ // This open's read is now the latest for the run.
1084
+ lastRead[runId] = ++readSeq;
1085
+ applyDecisions(runId, decisions);
1086
+ render();
1087
+ }
1088
+ /**
1089
+ * A check started earlier has finished. Its run opens, unless a dialog is open on the run on screen (it may hold
1090
+ * typed text or an error): then the run bar offers it, and it opens only when the person asks.
1091
+ */
1092
+ async function checkFinished(runId) {
1093
+ if (S.run && openDialog) { setRunStatus({ text: 'The check you started has finished.', offer: runId }); return; }
1094
+ await openRun(runId);
1095
+ }
1096
+ /** "← Runs": leave the run on screen (leaveRun) for the runs list. */
1097
+ async function backToRuns() {
1098
+ const my = ++navSeq;
1099
+ if (!await leaveRun('go back to the runs') || my !== navSeq) return;
1100
+ if (S.run) closeDialog(false);
1101
+ S.run = null; S.runStatus = null; lastFailed = false;
829
1102
  render();
830
1103
  }
1104
+ /** Another tab leaves the run on screen (leaveRun); the Runs tab keeps it. Resolves true once the tab is shown. */
1105
+ async function showTab(tab) {
1106
+ if (tab !== 'runs') {
1107
+ const my = ++navSeq;
1108
+ if (!await leaveRun('open that tab') || my !== navSeq) return false;
1109
+ if (S.run) closeDialog(false);
1110
+ S.run = null; S.runStatus = null; lastFailed = false;
1111
+ }
1112
+ S.tab = tab; render();
1113
+ return true;
1114
+ }
1115
+
1116
+ /**
1117
+ * Read a run's finding decisions, the earlier ones a re-run may carry over, and the paste-ready RFI requests.
1118
+ * Resolves to a function that applies the answer to the page (returning false when they could not be read), or to
1119
+ * null when a newer read of that run was asked for since: only the latest read for a run is shown. `keep`: on a
1120
+ * failure, leave what is on screen (a decision just recorded must not vanish, and its finding must not offer Accept
1121
+ * again, because a refresh failed).
1122
+ */
1123
+ async function readDecisions(runId, keep = false) {
1124
+ const mine = lastRead[runId] = ++readSeq;
1125
+ let body = null, error = null;
1126
+ try { ({ body } = await call(`${base}/runs/${encodeURIComponent(runId)}/decisions`)); } catch (e) { error = e; }
1127
+ if (lastRead[runId] !== mine) return null;
1128
+ return () => {
1129
+ if (error) {
1130
+ if (keep) { S.decisionsError = DECISIONS_STALE; return false; }
1131
+ S.decisions = NO_DECISIONS;
1132
+ S.decisionsError = `Your decisions on this run couldn’t be loaded, so none are shown. ${error.message}`;
1133
+ return false;
1134
+ }
1135
+ applyDecisions(runId, body);
1136
+ return true;
1137
+ };
1138
+ }
1139
+ /** Show a decisions answer for the run on screen. */
1140
+ function applyDecisions(runId, body) {
1141
+ S.decisions = { current: body.current || {}, mismatched: body.mismatched || [], unreadableLines: body.unreadableLines || [], offers: body.offers || [], rfiText: body.rfiText || {}, signature: body.signature || null };
1142
+ // The record is there but could not be read: say so, never show its findings as simply undecided.
1143
+ S.decisionsError = body.unreadable || '';
1144
+ // Only a decision this refresh shows is no longer pending.
1145
+ const still = stillPending(S.pendingByRun[runId] || [], body);
1146
+ if (still.length) S.pendingByRun[runId] = still; else delete S.pendingByRun[runId];
1147
+ if (body.signature) S.run.signature = body.signature;
1148
+ }
1149
+ /** Refresh the decisions of the run on screen: true when read, false when not, null when a newer read superseded it. */
1150
+ async function loadDecisions({ keep = false } = {}) {
1151
+ if (!S.run) return true;
1152
+ const apply = await readDecisions(S.run.runId, keep);
1153
+ return apply ? apply() : null;
1154
+ }
1155
+
1156
+ /**
1157
+ * Record one decision on the run on screen; the server names who decided. Resolves to '' when recorded, else what
1158
+ * went wrong. Tracked: leaving the run waits for the save and its read-back.
1159
+ */
1160
+ async function recordDecision(payload) {
1161
+ return track(async () => {
1162
+ const runId = S.run.runId;
1163
+ // What the run showed is taken BEFORE the save: stillPending compares the refresh with it.
1164
+ const shownBefore = S.decisions.current[payload.findingId];
1165
+ try {
1166
+ const { body } = await call(`${base}/runs/${encodeURIComponent(runId)}/decisions`, jsonOpts('POST', payload));
1167
+ // The finding is pending from here until a refresh shows this decision (stillPending), never merely because
1168
+ // the refresh worked: one whose decisions are unreadable, or that shows an earlier decision, confirms nothing.
1169
+ S.pendingByRun[runId] = [...(S.pendingByRun[runId] || []).filter((p) => p.findingId !== payload.findingId),
1170
+ { findingId: payload.findingId, at: typeof body.recordedAt === 'string' ? body.recordedAt : '', after: (shownBefore && shownBefore.at) || '' }];
1171
+ if (S.carryNote && S.carryNote.findingId === payload.findingId) S.carryNote = null;
1172
+ // As "mark checked": the record may have come back unsigned or unverified, and the badge says so now.
1173
+ if (body.signature) S.run.signature = body.signature;
1174
+ // Recorded. If the decisions cannot be read back (here, or by the server), what is on screen stays, the person
1175
+ // is told to reload (never "nothing was recorded"), and this finding is marked recorded with its actions
1176
+ // withheld until a refresh works, so nothing invites recording it twice.
1177
+ const read = await loadDecisions({ keep: true });
1178
+ // A newer read of this run was asked for meanwhile (another decision's): that one paints and says what it shows.
1179
+ if (read === null) return '';
1180
+ const fresh = read && !pendingIds(S.pendingByRun, runId).includes(payload.findingId);
1181
+ if (!fresh && !S.decisionsError) S.decisionsError = DECISIONS_STALE;
1182
+ // Not a full re-render: that would rebuild the stage and lose the zoom and the focus the person is working at.
1183
+ paintOverlay(); paintSide(); paintRunChips();
1184
+ const live = document.getElementById('dec-live'), d = S.decisions.current[payload.findingId];
1185
+ if (live) live.textContent = fresh && d ? `Recorded: ${decisionWords(d)}` : DECISIONS_STALE;
1186
+ return '';
1187
+ } catch (e) { return e.message; }
1188
+ });
1189
+ }
1190
+
1191
+ /** The two run-bar parts a decision can change, replaced alone: the "Not signed" chip and the accepted legend entry. */
1192
+ function paintRunChips() {
1193
+ const r = S.run; if (!r) return;
1194
+ const sign = document.getElementById('rb-sign'), acc = document.getElementById('lg-accepted');
1195
+ if (sign) sign.innerHTML = unsignedChipHtml(r);
1196
+ if (acc) acc.innerHTML = acceptedLegendHtml(statusColours(S.colours));
1197
+ }
1198
+ function unsignedChipHtml(r) { return r.signature && r.signature.status === 'unsigned' ? `<span class="chip" data-tip="${esc(unsignedTip(r.signature))}">Not signed</span>` : ''; }
1199
+ function runUnverified() { return !!(S.run && S.run.signature && S.run.signature.unverified); }
1200
+ function acceptedLegendHtml(colours) { return acceptedFindingIds(S.decisions, runUnverified(), pendingIds(S.pendingByRun, S.run && S.run.runId)).length
1201
+ ? `<span><svg width="18" height="8" aria-hidden="true"><line x1="1" y1="4" x2="17" y2="4" stroke="${esc(colours.fail)}" stroke-width="3" stroke-dasharray="6 2 1 2"/></svg>Accepted as drawn</span>` : ''; }
1202
+
1203
+ /** Show a dialog field's error: tied to the field, and the field takes focus back. */
1204
+ function fieldError(scrim, fieldSel, text, invalid = true) {
1205
+ const err = scrim.querySelector('#fd-err'), field = scrim.querySelector(fieldSel);
1206
+ err.hidden = false; err.textContent = text;
1207
+ // Only an empty field is "invalid"; a server failure is not the field's fault.
1208
+ if (invalid) field.setAttribute('aria-invalid', 'true');
1209
+ field.focus();
1210
+ }
1211
+
1212
+ function findingOf(id) {
1213
+ const s = sheetOf();
1214
+ for (const it of (s && s.items) || []) { const f = (it.findings || []).find((x) => x.id === id); if (f) return { it, f }; }
1215
+ return null;
1216
+ }
1217
+
1218
+ function acceptDialog(findingId, prefill = '') {
1219
+ const hit = findingOf(findingId); if (!hit) return;
1220
+ showDialog({
1221
+ title: 'Accept as drawn',
1222
+ body: `<p class="note">${esc(hit.f.reason)}</p>
1223
+ <label class="field"><span>What does the drawing rely on?</span><textarea id="fd-reason" rows="3" maxlength="500" spellcheck="true" data-command-id="drawing-check.accept-reason" aria-required="true" aria-describedby="fd-err">${esc(prefill)}</textarea></label>
1224
+ <p class="note">It stays “${esc(STATUS_WORD[hit.f.status])}” on the run, the report and the PDF, labelled as accepted as drawn by you with this reason. On the drawing its box takes the Wrong colour with a dash-dot outline. It never counts as fine.</p>
1225
+ <p class="err-line" id="fd-err" role="alert" hidden></p>`,
1226
+ foot: '<button type="button" data-dlg="cancel" data-command-id="drawing-check.cancel-decision">Cancel</button><button type="button" class="primary" data-dlg="record" data-command-id="drawing-check.record-decision">Record</button>',
1227
+ onOpen: (scrim) => {
1228
+ scrim.querySelector('#fd-reason').focus();
1229
+ scrim.addEventListener('click', async (e) => {
1230
+ const act = e.target.closest('[data-dlg]')?.dataset.dlg;
1231
+ if (act === 'cancel') { closeDialog(); return; }
1232
+ if (act !== 'record') return;
1233
+ const reason = scrim.querySelector('#fd-reason').value.trim();
1234
+ scrim.querySelector('#fd-reason').removeAttribute('aria-invalid');
1235
+ if (!reason) { fieldError(scrim, '#fd-reason', 'Say what the drawing relies on. The reason is part of the record.'); return; }
1236
+ const btn = e.target.closest('[data-dlg]'); btn.disabled = true;
1237
+ const failed = await recordDecision({ findingId, choice: 'accept', reason });
1238
+ if (!openDialog || openDialog.scrim !== scrim) return;
1239
+ if (failed) { btn.disabled = false; fieldError(scrim, '#fd-reason', `Nothing was recorded. ${failed}`, false); return; }
1240
+ closeDialog();
1241
+ });
1242
+ },
1243
+ });
1244
+ }
1245
+
1246
+ function rfiDialog(findingId, prefill = '') {
1247
+ const hit = findingOf(findingId); if (!hit) return;
1248
+ const request = S.decisions.rfiText[findingId] || '';
1249
+ showDialog({
1250
+ title: 'Raise an RFI',
1251
+ // No request to copy (the server had none for this finding): the person is told so and says it themselves,
1252
+ // rather than facing an empty box and a dead Copy button.
1253
+ body: (request
1254
+ ? `<p class="note">FloLess doesn’t raise the RFI itself. Copy this request into your AI terminal, then record the RFI reference it gives you.</p>
1255
+ <label class="field"><span>Request for your AI terminal</span><textarea id="fd-request" rows="6" readonly data-command-id="drawing-check.rfi-request">${esc(request)}</textarea></label>
1256
+ <div class="row-actions"><button type="button" data-dlg="copy" data-command-id="drawing-check.copy-rfi-request">Copy request</button><span class="note" id="fd-copied" role="status"></span></div>`
1257
+ : '<p class="note">FloLess couldn’t prepare the request for this finding. Describe it to your AI terminal yourself, then record the RFI reference it gives you here.</p>')
1258
+ + `<label class="field"><span>RFI reference</span><input type="text" id="fd-rfi" maxlength="80" spellcheck="false" autocomplete="off" data-command-id="drawing-check.rfi-reference" placeholder="e.g. RFI-014" value="${esc(prefill)}" aria-describedby="fd-err"></label>
1259
+ <p class="err-line" id="fd-err" role="alert" hidden></p>`,
1260
+ foot: '<button type="button" data-dlg="cancel" data-command-id="drawing-check.cancel-decision">Cancel</button><button type="button" class="primary" data-dlg="record" data-command-id="drawing-check.record-decision">Record</button>',
1261
+ onOpen: (scrim) => {
1262
+ scrim.querySelector(request ? '[data-dlg="copy"]' : '#fd-rfi').focus();
1263
+ scrim.addEventListener('click', async (e) => {
1264
+ const act = e.target.closest('[data-dlg]')?.dataset.dlg;
1265
+ if (act === 'cancel') { closeDialog(); return; }
1266
+ if (act === 'copy') {
1267
+ const area = scrim.querySelector('#fd-request'); const said = scrim.querySelector('#fd-copied');
1268
+ try { await navigator.clipboard.writeText(area.value); said.textContent = 'Copied.'; }
1269
+ catch { area.select(); said.textContent = 'Selected. Press Ctrl+C to copy.'; }
1270
+ return;
1271
+ }
1272
+ if (act !== 'record') return;
1273
+ const rfi = scrim.querySelector('#fd-rfi').value.trim();
1274
+ scrim.querySelector('#fd-rfi').removeAttribute('aria-invalid');
1275
+ if (!rfi) { fieldError(scrim, '#fd-rfi', 'Give the RFI reference, so the record says which RFI answers this.'); return; }
1276
+ const btn = e.target.closest('[data-dlg]'); btn.disabled = true;
1277
+ const failed = await recordDecision({ findingId, choice: 'rfi', rfi });
1278
+ if (!openDialog || openDialog.scrim !== scrim) return;
1279
+ if (failed) { btn.disabled = false; fieldError(scrim, '#fd-rfi', `Nothing was recorded. ${failed}`, false); return; }
1280
+ closeDialog();
1281
+ });
1282
+ scrim.querySelector('#fd-rfi').addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); scrim.querySelector('[data-dlg="record"]').click(); } });
1283
+ },
1284
+ });
1285
+ }
1286
+
1287
+ /**
1288
+ * Carry an earlier run's decision over: recorded in THIS run as a new decision citing the old one. Nothing
1289
+ * refuses: when the offer went stale, the decisions are read again and the person is offered to record the
1290
+ * same choice as a new decision (the dialog pre-filled), said on that finding, not in the export card.
1291
+ */
1292
+ async function carryOver(findingId, btn) {
1293
+ const offer = S.decisions.offers.find((o) => o.findingId === findingId); if (!offer) return;
1294
+ // Tracked as a whole, so leaving the run waits for the reload after a stale offer too, and the job resolves to the
1295
+ // failure: a leave that starts after the save failed but before the reload ends still keeps the run open.
1296
+ return track(async () => {
1297
+ if (btn) btn.disabled = true;
1298
+ S.carryNote = null;
1299
+ const failed = await recordDecision({ findingId, choice: offer.from.choice,
1300
+ ...(offer.from.reason ? { reason: offer.from.reason } : {}), ...(offer.from.rfi ? { rfi: offer.from.rfi } : {}),
1301
+ carriedFrom: { runId: offer.fromRunId, at: offer.from.at } });
1302
+ // The button that was pressed is gone with the repaint: focus the finding's remaining action instead of <body>.
1303
+ if (!failed) { document.querySelector(`[data-act="finding-accept"][data-finding="${findingId}"]`)?.focus(); return; }
1304
+ await loadDecisions();
1305
+ S.carryNote = { findingId, text: `Nothing was carried over. ${failed}`, choice: offer.from.choice, reason: offer.from.reason || '', rfi: offer.from.rfi || '' };
1306
+ paintOverlay(); paintSide();
1307
+ return failed;
1308
+ });
1309
+ }
1310
+
1311
+ /** "Record it as a new decision": the stale offer's choice, in its dialog, pre-filled for the person to confirm. */
1312
+ function recordAsNew(findingId) {
1313
+ const note = S.carryNote && S.carryNote.findingId === findingId ? S.carryNote : null; if (!note) return;
1314
+ if (note.choice === 'accept') acceptDialog(findingId, note.reason); else rfiDialog(findingId, note.rfi);
1315
+ }
831
1316
 
832
1317
  // ── run view ──
833
1318
  // The run's own version's item names first: renaming an item later never relabels an old run.
@@ -846,12 +1331,16 @@ function boot() {
846
1331
  }).join('');
847
1332
  const colours = statusColours(S.colours);
848
1333
  const legend = ['pass', 'fail', 'dont-know'].map((k) => `<span><svg width="18" height="8" aria-hidden="true"><line x1="1" y1="4" x2="17" y2="4" stroke="${esc(colours[k])}" stroke-width="${LINE[k].w + 0.6}" ${LINE[k].dash ? `stroke-dasharray="${LINE[k].dash}"` : ''}/></svg>${STATUS_WORD[k]}</span>`).join('')
1334
+ + `<span id="lg-accepted">${acceptedLegendHtml(colours)}</span>`
849
1335
  + '<span><i class="hatched" aria-hidden="true"></i>FloLess doesn’t check</span>';
850
- const unsigned = r.signature && r.signature.status === 'unsigned';
851
1336
  return `<div class="runbar"><button type="button" data-act="back" data-command-id="drawing-check.back-to-runs">← Runs</button><span class="title">${esc(when)}</span><span class="note">${esc(r.profile.client)} · v${r.profile.version}</span>
852
1337
  ${r.warnings.length ? `<button type="button" class="chip warn" data-act="warnings" data-command-id="drawing-check.show-decisions">${r.warnings.length} decision${r.warnings.length === 1 ? '' : 's'}</button>` : ''}
853
- ${unsigned ? `<span class="chip" data-tip="${esc(unsignedTip(r.signature))}">Not signed</span>` : ''}
1338
+ <span id="rb-sign">${unsignedChipHtml(r)}</span>
1339
+ <span class="note" id="run-status" role="status" aria-live="polite" style="display:inline-flex;align-items:center;gap:6px">${runStatusHtml(S.runStatus)}</span>
854
1340
  <span class="sp"></span><button type="button" data-act="export" data-command-id="drawing-check.export" ${s && s.status === 'checked' ? '' : 'disabled'}>Export marked-up PDF</button></div>
1341
+ <!-- The one place a recorded decision is announced. It lives here, outside #side, so repainting the side panel never
1342
+ recreates it (a region created and filled in the same task is not announced). -->
1343
+ <p class="sr-only" id="dec-live" role="status"></p>
855
1344
  <div class="runview"><div class="sheets" aria-label="Sheets">${strip}</div>
856
1345
  <div class="stage" id="stage" tabindex="0" aria-label="Marked-up drawing. Plus and minus zoom, 0 fits the page, arrows pan.">
857
1346
  <svg class="view" id="view" xmlns="http://www.w3.org/2000/svg"></svg>
@@ -880,9 +1369,18 @@ function boot() {
880
1369
  out += '<h3>Items</h3>' + s.items.map((it) => {
881
1370
  const on = S.selectedN === it.n;
882
1371
  return `<button type="button" class="item" data-n="${it.n}" data-command-id="drawing-check.item" aria-pressed="${on}"><span class="tag" style="color:${esc(colours[it.status])}">${it.n}</span>
883
- <span><span class="lab">${esc(labelOf(it.itemId))}</span><span class="st"><i class="swatch" style="border-top:${LINE[it.status].w + 0.6}px ${LINE[it.status].dash ? 'dashed' : 'solid'} ${esc(colours[it.status])}"></i>${STATUS_WORD[it.status]}</span></span>
884
- ${on ? `<span class="why">${esc(it.reason)}${S.itemNote ? ` ${esc(S.itemNote)}` : ''}</span>` : ''}</button>`;
1372
+ <span><span class="lab">${esc(labelOf(it.itemId))}</span><span class="st"><i class="swatch" style="border-top:${LINE[it.status].w + 0.6}px ${LINE[it.status].dash ? 'dashed' : 'solid'} ${esc(colours[it.status])}"></i>${STATUS_WORD[it.status]}${decidedSuffix(it, S.decisions, pendingIds(S.pendingByRun, r.runId))}</span></span>
1373
+ ${on ? `<span class="why">${esc(it.reason)}${S.itemNote ? ` ${esc(S.itemNote)}` : ''}</span>` : ''}</button>`
1374
+ + (on ? findingsHtml(it, S.decisions, { unverified: !!(r.signature && r.signature.unverified), carryNote: S.carryNote, colours, pending: pendingIds(S.pendingByRun, r.runId) }) : '');
885
1375
  }).join('');
1376
+ if (S.decisionsError) out += `<p class="err-line" role="alert">${esc(S.decisionsError)}</p>`;
1377
+ if (S.decisions.mismatched.length) {
1378
+ out += '<h3>Decisions that do not match this run (ignored)</h3>' + S.decisions.mismatched.map((d) => `<p class="note">${esc(decisionWords(d))} · ${esc(String(d.at).slice(0, 10))}</p>`).join('');
1379
+ }
1380
+ // Lines that look like decisions but could not be read: named by record line, never applied, never echoed.
1381
+ if ((S.decisions.unreadableLines || []).length) {
1382
+ out += '<h3>Decisions that could not be read</h3>' + S.decisions.unreadableLines.map((l) => `<p class="note">${esc(l)}</p>`).join('');
1383
+ }
886
1384
  const qs = s.items.filter((it) => it.status === 'dont-know');
887
1385
  if (qs.length) out += '<h3>Questions for you</h3>' + qs.map((it) => `<div class="qcard"><b>${it.n}. ${esc(labelOf(it.itemId))}</b><br>${esc(it.reason)}</div>`).join('');
888
1386
  if (s.uncovered && s.uncovered.length) out += `<h3>What FloLess doesn’t check</h3><p class="note"><i class="hatched" aria-hidden="true"></i> FloLess does not check geometry (dimensions, holes, welds), so the hatched drawing area is not checked. Check it yourself.</p>`;
@@ -919,7 +1417,10 @@ function boot() {
919
1417
  const colours = statusColours(S.colours);
920
1418
  const g = svg.querySelector('#ov');
921
1419
  if (!g) return;
922
- g.innerHTML = s.status === 'checked' ? overlaySvg(s, colours, { selectedN: S.selectedN }) : '';
1420
+ // Accepted findings keep their status colour and take the dash-dot line (display only; the result is unchanged);
1421
+ // one with a newer decision pending is drawn as its plain status until a refresh shows that decision.
1422
+ const accepted = acceptedFindingIds(S.decisions, runUnverified(), pendingIds(S.pendingByRun, S.run && S.run.runId));
1423
+ g.innerHTML = s.status === 'checked' ? overlaySvg(withAccepted(s, accepted), colours, { selectedN: S.selectedN }) : '';
923
1424
  // Spotlight, not a new colour: the selected item's boxes go heavier, everything else steps back.
924
1425
  if (S.selectedN !== null) {
925
1426
  g.querySelectorAll('[data-n]').forEach((el) => {
@@ -935,7 +1436,7 @@ function boot() {
935
1436
  const runId = S.run.runId;
936
1437
  const msg = document.getElementById('stage-msg');
937
1438
  // Until the page arrives, size the paper from the evidence so the boxes have somewhere to sit.
938
- const ext = s.items.flatMap((it) => it.evidence.map((e) => e.bbox)).concat(s.uncovered || []);
1439
+ const ext = s.items.flatMap((it) => onDrawing(it.evidence, s.drawing).map((e) => e.bbox)).concat(s.uncovered || []);
939
1440
  pageBox = ext.length ? [0, 0, Math.max(...ext.map((b) => b[2])) + 36, Math.max(...ext.map((b) => b[3])) + 36] : [0, 0, 842, 595];
940
1441
  svg.innerHTML = `${hatchDefs()}<rect class="sheet-frame" id="paper" x="0" y="0" width="${pageBox[2]}" height="${pageBox[3]}"/><g id="page"></g><g id="ov"></g>`;
941
1442
  paintOverlay(); vb = paddedViewBox(pageBox, 12); setVB();
@@ -1008,8 +1509,9 @@ function boot() {
1008
1509
 
1009
1510
  /** Item → box: select the row, zoom to its first evidence box (ITEM_PAD around it), show the reason. */
1010
1511
  function selectItem(n) {
1011
- const s = sheetOf(); const it = s && s.items.find((x) => x.n === n);
1012
- if (!it) return;
1512
+ const s = sheetOf(); const found = s && s.items.find((x) => x.n === n);
1513
+ if (!found) return;
1514
+ const it = { ...found, evidence: onDrawing(found.evidence, s.drawing) }; // only this drawing's boxes
1013
1515
  S.selectedN = n;
1014
1516
  S.itemNote = focusItem(view, it);
1015
1517
  paintOverlay(); paintSide();
@@ -1023,30 +1525,39 @@ function boot() {
1023
1525
  document.getElementById('stage')?.focus();
1024
1526
  }
1025
1527
 
1528
+ // Mark checked and export are tracked like a decision: leaving the run waits for their answer, so it lands on the
1529
+ // run it was sent from (owner ruling 2026-10-04, stop it at the source).
1026
1530
  async function markChecked() {
1027
1531
  const s = sheetOf(); if (!s) return;
1028
- const btn = root.querySelector('[data-act="mark"]'); if (btn) btn.disabled = true;
1029
- try {
1030
- const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/checked`, jsonOpts('POST', { drawing: s.drawing, page: s.page }));
1031
- S.run.checkedBy = body.checkedBy || S.run.checkedBy;
1032
- // The record may have come back unsigned or unverified: the badge must say so now, not after a reload.
1033
- if (body.signature) S.run.signature = body.signature;
1034
- render();
1035
- } catch (e) { if (btn) btn.disabled = false; S.exportCard = `<p class="err-line" role="alert">${esc(e.message)}</p>`; paintSide(); }
1532
+ return track(async () => {
1533
+ const btn = root.querySelector('[data-act="mark"]'); if (btn) btn.disabled = true;
1534
+ try {
1535
+ const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/checked`, jsonOpts('POST', { drawing: s.drawing, page: s.page }));
1536
+ S.run.checkedBy = body.checkedBy || S.run.checkedBy;
1537
+ // The record may have come back unsigned or unverified: the badge must say so now, not after a reload.
1538
+ if (body.signature) S.run.signature = body.signature;
1539
+ render();
1540
+ return '';
1541
+ } catch (e) { if (btn) btn.disabled = false; S.exportCard = `<p class="err-line" role="alert">${esc(e.message)}</p>`; paintSide(); return e.message; }
1542
+ });
1036
1543
  }
1037
1544
 
1038
1545
  async function exportPdf() {
1039
1546
  const s = sheetOf(); if (!s) return;
1040
- const btn = root.querySelector('[data-act="export"]'); if (btn) { btn.disabled = true; btn.textContent = 'Exporting…'; }
1041
- try {
1042
- const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/export`, jsonOpts('POST', { drawing: s.drawing }));
1043
- const fails = body.tagFailures || [];
1044
- S.exportCard = `<div class="export-card" role="status"><b>${esc(body.filename)}</b> saved.
1045
- ${fails.length ? `<details><summary>${fails.length} item number${fails.length === 1 ? '' : 's'} couldn’t be placed on the sheet. ${fails.length === 1 ? 'It is' : 'They’re'} listed on the cover page.</summary>${fails.map((f) => `<div class="note">${esc(tagFailureNote(f))}</div>`).join('')}</details>` : ''}
1046
- <div class="acts"><button type="button" data-file="open" data-path="${esc(body.path)}" data-command-id="drawing-check.export-open">Open</button><button type="button" data-file="reveal" data-path="${esc(body.path)}" data-command-id="drawing-check.export-reveal">Show in folder</button></div></div>`;
1047
- } catch (e) { S.exportCard = `<p class="err-line" role="alert">${esc(e.message)}</p>`; }
1048
- if (btn) { btn.disabled = false; btn.textContent = 'Export marked-up PDF'; }
1049
- paintSide();
1547
+ return track(async () => {
1548
+ const btn = root.querySelector('[data-act="export"]'); if (btn) { btn.disabled = true; btn.textContent = 'Exporting…'; }
1549
+ let failed = '';
1550
+ try {
1551
+ const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/export`, jsonOpts('POST', { drawing: s.drawing }));
1552
+ const fails = body.tagFailures || [];
1553
+ S.exportCard = `<div class="export-card" role="status"><b>${esc(body.filename)}</b> saved.
1554
+ ${fails.length ? `<details><summary>${fails.length} item number${fails.length === 1 ? '' : 's'} couldn’t be placed on the sheet. ${fails.length === 1 ? 'It is' : 'They’re'} listed on the cover page.</summary>${fails.map((f) => `<div class="note">${esc(tagFailureNote(f))}</div>`).join('')}</details>` : ''}
1555
+ <div class="acts"><button type="button" data-file="open" data-path="${esc(body.path)}" data-command-id="drawing-check.export-open">Open</button><button type="button" data-file="reveal" data-path="${esc(body.path)}" data-command-id="drawing-check.export-reveal">Show in folder</button></div></div>`;
1556
+ } catch (e) { failed = e.message; S.exportCard = `<p class="err-line" role="alert">${esc(e.message)}</p>`; }
1557
+ if (btn) { btn.disabled = false; btn.textContent = 'Export marked-up PDF'; }
1558
+ paintSide();
1559
+ return failed;
1560
+ });
1050
1561
  }
1051
1562
 
1052
1563
  function warningsDialog() {
@@ -1095,7 +1606,7 @@ function boot() {
1095
1606
  root.addEventListener('click', async (e) => {
1096
1607
  const t = e.target.closest('button, [data-tab]');
1097
1608
  if (!t) return;
1098
- if (t.dataset.tab) { S.tab = t.dataset.tab; if (S.tab !== 'runs') S.run = null; render(); document.getElementById(`tab-${S.tab}`)?.focus(); return; }
1609
+ if (t.dataset.tab) { if (await showTab(t.dataset.tab)) document.getElementById(`tab-${S.tab}`)?.focus(); return; }
1099
1610
  if (t.dataset.run) { await openRun(t.dataset.run); return; }
1100
1611
  if (t.dataset.sheet) { S.sheet = Number(t.dataset.sheet); S.selectedN = null; S.itemNote = ''; S.exportCard = null; render(); return; }
1101
1612
  if (t.classList.contains('item')) { selectItem(Number(t.dataset.n)); return; }
@@ -1151,11 +1662,20 @@ function boot() {
1151
1662
  if (act === 'add-item') { addItemDialog(); return; }
1152
1663
  if (act === 'approve') { approveDialog(); return; }
1153
1664
  if (act === 'check') { document.getElementById('run-file')?.click(); return; }
1154
- if (act === 'back') { S.run = null; render(); return; }
1665
+ if (act === 'back') { await backToRuns(); return; }
1155
1666
  if (act === 'mark') { await markChecked(); return; }
1156
1667
  if (act === 'export') { await exportPdf(); return; }
1157
1668
  if (act === 'warnings') { warningsDialog(); return; }
1158
1669
  if (act === 'retry-page') { await mountRunView(); return; }
1670
+ if (act === 'finding-fix') {
1671
+ const n = S.selectedN; S.selectedN = null; S.itemNote = ''; paintOverlay(); paintSide();
1672
+ // Focus stays in the list, on the item it was about (its card has just closed), not thrown to the drawing.
1673
+ (document.querySelector(`#side .item[data-n="${n}"]`) || document.getElementById('stage'))?.focus(); return;
1674
+ }
1675
+ if (act === 'finding-accept') { acceptDialog(t.dataset.finding); return; }
1676
+ if (act === 'finding-rfi') { rfiDialog(t.dataset.finding); return; }
1677
+ if (act === 'finding-carry') { await carryOver(t.dataset.finding, t); return; }
1678
+ if (act === 'finding-record-new') { recordAsNew(t.dataset.finding); return; }
1159
1679
  if (act === 'reset-colours') { await saveColours({ pass: DEFAULT_COLOURS.pass, fail: DEFAULT_COLOURS.fail, question: DEFAULT_COLOURS['dont-know'] }); }
1160
1680
  });
1161
1681
  root.addEventListener('input', (e) => {
@@ -1223,7 +1743,7 @@ function boot() {
1223
1743
  e.preventDefault();
1224
1744
  const keys = TABS.map(([k]) => k), i = keys.indexOf(S.tab);
1225
1745
  const next = e.key === 'Home' ? 0 : e.key === 'End' ? keys.length - 1 : (i + (e.key === 'ArrowRight' ? 1 : -1) + keys.length) % keys.length;
1226
- S.tab = keys[next]; if (S.tab !== 'runs') S.run = null; render(); document.getElementById(`tab-${S.tab}`)?.focus();
1746
+ showTab(keys[next]).then((shown) => { if (shown) document.getElementById(`tab-${S.tab}`)?.focus(); });
1227
1747
  });
1228
1748
  // Drop PDFs anywhere on the References tab.
1229
1749
  root.addEventListener('dragover', (e) => { if (S.tab !== 'references') return; e.preventDefault(); root.querySelector('.drop')?.classList.add('over'); });
@@ -1235,6 +1755,15 @@ function boot() {
1235
1755
  if (files.length) await uploadReferences(files);
1236
1756
  });
1237
1757
 
1758
+ // Closing the page while something is in flight on a run: the shell's leave guard asks first (it reads the editors'
1759
+ // contractSaveState, web/leave-guard.js) and can wait for it (flushContract); closing the tab directly gets the
1760
+ // browser's own prompt as the backstop.
1761
+ // A change that failed reads 'error' ("could not save your last change"), never 'clean'.
1762
+ function contractSaveState() { return inFlight.size ? 'saving' : lastFailed ? 'error' : 'clean'; }
1763
+ function flushContract() { return settled(); }
1764
+ window.contractSaveState = contractSaveState; window.flushContract = flushContract;
1765
+ window.addEventListener('beforeunload', (e) => { if (inFlight.size) { e.preventDefault(); e.returnValue = ''; } });
1766
+
1238
1767
  if (!PROJECT) { root.innerHTML = '<section role="tabpanel"><p class="err-line">Open this page from a Drawing Checker project.</p></section>'; return; }
1239
1768
  loadAll();
1240
1769
  }