@floless/app 0.168.0 → 0.170.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 (80) hide show
  1. package/cli-actions.mjs +8 -1
  2. package/dist/floless-server.cjs +125533 -99597
  3. package/dist/schemas/drawing-check.profile.v1.schema.json +12 -2
  4. package/dist/schemas/steel.model.v2.schema.json +2 -1
  5. package/dist/skills/floless-app-knowledge/SKILL.md +43 -13
  6. package/dist/skills/floless-app-new-workflow/SKILL.md +8 -1
  7. package/dist/skills/floless-app-rfi/SKILL.md +4 -2
  8. package/dist/skills/floless-app-routines/SKILL.md +2 -2
  9. package/dist/skills/floless-app-routines/references/routines-api.md +20 -8
  10. package/dist/skills/floless-app-steel-model/SKILL.md +8 -5
  11. package/dist/skills/floless-app-steel-takeoff/SKILL.md +31 -1
  12. package/dist/skills/floless-app-workflows/SKILL.md +22 -3
  13. package/dist/skills/floless-app-workflows/references/agent-steps.md +40 -6
  14. package/dist/skills/floless-app-workflows/references/exec-contract.md +27 -0
  15. package/dist/skills/floless-app-workflows/references/script-runner.md +105 -0
  16. package/dist/templates/college-phase-exporter.flo +7 -2
  17. package/dist/templates/trimble-list-projects.flo +10 -2
  18. package/dist/web/agent-steps.js +90 -19
  19. package/dist/web/agents.js +77 -31
  20. package/dist/web/app.css +267 -4
  21. package/dist/web/app.js +71 -7
  22. package/dist/web/aware-update-client.js +4 -4
  23. package/dist/web/aware.js +1277 -219
  24. package/dist/web/chat.css +10 -0
  25. package/dist/web/chat.js +407 -117
  26. package/dist/web/checkpoint-standard.js +5 -3
  27. package/dist/web/commands-drawing-check.js +4 -0
  28. package/dist/web/commands-shell.js +551 -15
  29. package/dist/web/commands-steel.js +68 -2
  30. package/dist/web/commands-vector.js +69 -0
  31. package/dist/web/drawing-check-editor.html +10 -0
  32. package/dist/web/drawing-check-editor.js +821 -237
  33. package/dist/web/failure-copy.js +50 -2
  34. package/dist/web/filter-ai-proposal.js +11 -8
  35. package/dist/web/flo-3d.js +310 -0
  36. package/dist/web/flo-card.js +72 -0
  37. package/dist/web/guide.js +33 -24
  38. package/dist/web/index.html +95 -5
  39. package/dist/web/instructor.js +102 -15
  40. package/dist/web/left-pane.js +4 -1
  41. package/dist/web/local-discovery.js +8 -7
  42. package/dist/web/missed-routines.js +239 -0
  43. package/dist/web/model-editor-steel-adapter.js +41 -1
  44. package/dist/web/model-measure.js +6 -0
  45. package/dist/web/model-spatial-panel.js +19 -4
  46. package/dist/web/model-spatial-tools.js +3 -3
  47. package/dist/web/model-viewport-revit-adapter.js +3 -3
  48. package/dist/web/model-viewport-toolbar.js +11 -0
  49. package/dist/web/origin-rule.js +155 -0
  50. package/dist/web/pages.js +17 -14
  51. package/dist/web/panels.js +1 -1
  52. package/dist/web/project-access.js +1 -1
  53. package/dist/web/project-history.js +2 -2
  54. package/dist/web/project-modules.js +5 -5
  55. package/dist/web/project-reconciliation.js +1 -1
  56. package/dist/web/project-rfis.js +8 -3
  57. package/dist/web/project-workflows.js +8 -6
  58. package/dist/web/renderers.js +6 -0
  59. package/dist/web/report-csp.js +68 -0
  60. package/dist/web/revit-editor.js +22 -8
  61. package/dist/web/run-history.js +14 -4
  62. package/dist/web/steel-3d-core.js +39 -9
  63. package/dist/web/steel-3d-flo.js +331 -0
  64. package/dist/web/steel-3d-view.js +164 -0
  65. package/dist/web/steel-ai-marks.js +3 -1
  66. package/dist/web/steel-editor.html +583 -129
  67. package/dist/web/steel-environments.js +297 -0
  68. package/dist/web/steel-filter.html +3 -2
  69. package/dist/web/steel-model-v2-client-validation.js +8 -1
  70. package/dist/web/steel-model-v2-commands.js +23 -9
  71. package/dist/web/steel-model-v2-projection.js +1 -1
  72. package/dist/web/step-rename.js +3 -2
  73. package/dist/web/terminal-requests.js +79 -1
  74. package/dist/web/tool-updates.js +9 -7
  75. package/dist/web/vector-3d.html +1 -1
  76. package/dist/web/vector-editor.html +50 -8
  77. package/dist/web/workspace-root-management.js +1 -1
  78. package/dist/web/workspaces.js +2334 -253
  79. package/launch.mjs +5 -0
  80. package/package.json +11 -8
@@ -135,11 +135,17 @@ export function liveRefreshFor(frame, { app, project }) {
135
135
  * they did not show before. '' when nothing a person would notice changed. `before`/`after` are { refs, designSet }
136
136
  * (designSet null when it could not be read: a reference then shows "could not read", which is not news).
137
137
  */
138
- export function referencesChangeNote(before, after) {
138
+ /**
139
+ * What changed in the reference drawings, as the status line says it. `own` = { added, removed }: the drawings the
140
+ * page's own writes added and took out (#2504, #3297). An addition is skipped only when an own addition explains it,
141
+ * a removal only when an own removal does; recording where a drawing came from explains neither, and a new warning
142
+ * on any drawing, the page's own included, is always said.
143
+ */
144
+ export function referencesChangeNote(before, after, own = { added: new Set(), removed: new Set() }) {
139
145
  const had = new Map((before.refs || []).map((r) => [r.sha256, r]));
140
146
  const has = new Set((after.refs || []).map((r) => r.sha256));
141
- const added = (after.refs || []).filter((r) => !had.has(r.sha256));
142
- const gone = (before.refs || []).filter((r) => !has.has(r.sha256));
147
+ const added = (after.refs || []).filter((r) => !had.has(r.sha256) && !own.added.has(r.sha256));
148
+ const gone = (before.refs || []).filter((r) => !has.has(r.sha256) && !own.removed.has(r.sha256));
143
149
  const warned = after.designSet ? (after.refs || []).filter((r) => {
144
150
  if (!had.has(r.sha256)) return false;
145
151
  const now = referenceDriftText(r, after.designSet);
@@ -235,6 +241,41 @@ export function mainPartHtml(it, { touched = false, note = '', locatedOn = false
235
241
  <p class="note">Normally the main part is the part-list row whose mark is the assembly mark in the drawing title. “Part list agrees with the title” and “Every part is located” both use it. Choose No only if this client lists the main part under a different mark.</p>
236
242
  ${unticked}${note ? `<p class="note" role="status">${esc(note)}</p>` : ''}</div>`;
237
243
  }
244
+ /**
245
+ * Whether this client writes inches without a mark on a dimension (`4`, `6 1/2`) (#2991): learned only when the
246
+ * references prove it, so the person may say so either way. Shown for an imperial checklist with no unit for every
247
+ * bare number (only then can it change a reading); '' otherwise. `bareInchSeen` says what the references showed.
248
+ * @param {any} lengths @param {{ touched?: boolean, note?: string }} [opts]
249
+ */
250
+ export function bareInchHtml(lengths, { touched = false, note = '' } = {}) {
251
+ if (!lengths || lengths.system !== 'imperial' || lengths.unitless) {
252
+ // No control here, but a choice saved on such a checklist (applied again after it changed) still says what it did.
253
+ return note ? `<section class="tb" aria-labelledby="dim-h"><h3 id="dim-h">Dimensions</h3><p class="note" role="status">${esc(note)}</p></section>` : '';
254
+ }
255
+ const on = lengths.bareInchValues === true, seen = lengths.bareInchSeen;
256
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
257
+ // What the references showed is counted narrowly: values with no inch mark on a chain with a feet-and-inches value,
258
+ // so "none found" is said, never "none there" - and only of references that were counted: a profile proposed
259
+ // before the count was kept claims nothing about them.
260
+ const shown = seen && seen.values > 0 ? `${plural(seen.values, 'value', 'values')} with no inch mark in a chain with feet and inches, on ${plural(seen.sheets, 'sheet', 'sheets')}` : '';
261
+ const chip = touched ? 'set by you' : on ? 'learned from the references' : shown ? 'too few seen in the references' : seen ? 'none found in the references' : 'not counted yet';
262
+ // Three separate facts: what runs do now, who set it, and what the references showed.
263
+ const does = on ? 'FloLess reads a number written alone in a dimension, such as 4 or 6 1/2, as inches.'
264
+ : 'FloLess does not guess: a number written alone in a dimension is reported as couldn’t tell.';
265
+ const source = touched ? `You set this; proposing again keeps it.${shown ? ` Your references show ${shown}.` : ''}`
266
+ : on ? `Learned from your reference drawings${shown ? `, which show ${shown}` : ''}.`
267
+ : shown ? `Your references show ${shown}: too few for FloLess to be sure. Choose Yes if this client writes inches this way.`
268
+ : seen ? 'FloLess found no values with no inch mark in a chain with feet and inches on your references. Choose Yes only if this client writes inches this way.'
269
+ : 'FloLess has not counted these on your references yet: proposing again from the references counts them. Choose Yes if this client writes inches this way.';
270
+ const why = `${does} ${source}`;
271
+ const opt = (v, isOn, words) => `<button type="button" role="radio" aria-checked="${isOn}" tabindex="${isOn ? 0 : -1}" data-bare-inches="${esc(v)}" data-command-id="drawing-check.bare-inches#${esc(v)}" data-command-instance-label="${esc(words)}">${esc(words)}</button>`;
272
+ // A setting of the whole checklist, not of one item: a section of its own, as the title block and the part list.
273
+ return `<section class="tb" aria-labelledby="dim-h"><h3 id="dim-h">Dimensions</h3><div class="clear-panel">
274
+ <p class="clear-head"><span id="bare-inch-h">Does this client write inches without a mark, such as 4 or 6 1/2?</span> <span class="chip">${esc(chip)}</span></p>
275
+ <div class="seg" role="radiogroup" aria-labelledby="bare-inch-h" aria-describedby="bare-inch-note">${opt('yes', on, 'Yes, read them as inches')}${opt('no', !on, 'No, say couldn’t tell')}</div>
276
+ <p class="note" id="bare-inch-note">${esc(why)} It applies to dimension values only.</p>
277
+ ${note ? `<p class="note" role="status">${esc(note)}</p>` : ''}</div></section>`;
278
+ }
238
279
  /** The largest line break a checklist may set, pt (server `MAX_LINE_BREAK_PT`). */
239
280
  export const MAX_LINE_BREAK_PT = 3;
240
281
  /**
@@ -289,7 +330,7 @@ export function clientFieldHtml(client) {
289
330
  // ── keeping keyboard focus across a re-render (pure, exported for server/drawing-check-ui.test.ts) ─
290
331
 
291
332
  /** The attributes that name a control stably across re-renders, in the order they are tried. */
292
- const FOCUS_KEYS = ['data-main-row', 'data-tb-label', 'data-tb-required', 'data-tb-remove', 'data-typed-label', 'data-typed-use', 'data-type-label', 'data-item', 'data-tab', 'data-act', 'id'];
333
+ const FOCUS_KEYS = ['data-main-row', 'data-bare-inches', 'data-tb-label', 'data-tb-required', 'data-tb-remove', 'data-typed-label', 'data-typed-use', 'data-type-label', 'data-item', 'data-tab', 'data-act', 'id'];
293
334
  const attrEsc = (v) => String(v).replace(/["\\]/g, '\\$&');
294
335
  /**
295
336
  * A selector that finds "the same control" in freshly rendered markup, or null. A read-mode button is
@@ -311,22 +352,73 @@ export function focusKey(el) {
311
352
  * Replace `container`'s markup and put keyboard focus back on the same control, if it is still there.
312
353
  * Every re-render of the page goes through this, so a re-render that lands while the person is on another
313
354
  * control (a PUT answering after they pressed Tab, a review that loads late) never drops their focus.
355
+ * @param {(el: any) => boolean} [keepTyped] @param {(el: any) => void} [leaving]
314
356
  */
315
- export function paintKeepingFocus(doc, container, html) {
357
+ export function paintKeepingFocus(doc, container, html, keepTyped = () => true, leaving = () => {}) {
316
358
  const active = doc.activeElement;
317
359
  const key = active && container.contains(active) ? focusKey(active) : null;
318
- // A text field being typed in keeps what was typed and where the caret was.
319
- const typing = key && active.tagName === 'INPUT' && /^(text|search|)$/i.test(active.type || '')
320
- ? { value: active.value, start: active.selectionStart, end: active.selectionEnd } : null;
360
+ // A text field being typed in stays in the page, the very same field, so it keeps its text, its caret and the
361
+ // browser's own record that it was edited: leaving it sends it exactly as if no repaint had happened (#3121).
362
+ // Text already sent as a choice is not typing (keepTyped says so): the field shows what was saved.
363
+ const typing = key && active.tagName === 'INPUT' && /^(text|search|)$/i.test(active.type || '') && keepTyped(active);
364
+ if (typing && paintAround(doc, container, html, active, key)) return true;
365
+ const was = typing ? { value: active.value, start: active.selectionStart, end: active.selectionEnd } : null;
366
+ // The field being typed in is about to leave the page (the new markup has no place for it, or this browser cannot
367
+ // move it there): the browser may say it changed as it goes, which is the repaint, not the person (`leaving`).
368
+ if (was) leaving(active);
321
369
  container.innerHTML = html;
322
370
  const again = key ? container.querySelector(key) : null;
323
- if (again && typing) {
324
- again.value = typing.value;
325
- if (typeof again.setSelectionRange === 'function' && typing.start != null) again.setSelectionRange(typing.start, typing.end);
371
+ // A browser that cannot move the field: its text and caret are copied into the new one instead.
372
+ if (again && was) {
373
+ again.value = was.value;
374
+ if (typeof again.setSelectionRange === 'function' && was.start != null) again.setSelectionRange(was.start, was.end);
326
375
  }
327
376
  if (again && again.focus) again.focus();
328
377
  return !!again;
329
378
  }
379
+ /**
380
+ * Put `html` into `container` with `live` in it, never taking `live` out of the page. Where the new markup holds the
381
+ * field at the same depth under the same kinds of element, its ancestors are kept and given the new markup's
382
+ * attributes, and everything beside them is replaced. Elsewhere, the new markup goes in beside the old and the field
383
+ * is moved into its place with `moveBefore`, which keeps focus, caret and the browser's edited state. False, with
384
+ * nothing changed, when the new markup has no place for the field or this browser cannot move it.
385
+ */
386
+ function paintAround(doc, container, html, live, key) {
387
+ const next = doc.createElement(container.tagName);
388
+ next.innerHTML = html;
389
+ const fresh = next.querySelector(key);
390
+ if (!fresh) return false;
391
+ // The field's value attribute is left alone: the text in it is the person's.
392
+ const syncAttributes = (L, F) => {
393
+ const keep = (name) => L === live && name === 'value';
394
+ for (const a of [...L.attributes]) if (!keep(a.name) && !F.hasAttribute(a.name)) L.removeAttribute(a.name);
395
+ for (const a of [...F.attributes]) if (!keep(a.name)) L.setAttribute(a.name, a.value);
396
+ };
397
+ const path = (el, top) => { const out = []; for (let n = el; n && n !== top; n = n.parentNode) out.unshift(n); return out; };
398
+ const liveP = path(live, container), freshP = path(fresh, next);
399
+ if (liveP.length !== freshP.length || liveP.some((n, i) => n.tagName !== freshP[i].tagName)) {
400
+ if (typeof fresh.parentNode.moveBefore !== 'function') return false;
401
+ const old = [...container.childNodes];
402
+ for (const n of [...next.childNodes]) container.appendChild(n);
403
+ syncAttributes(live, fresh);
404
+ fresh.parentNode.moveBefore(live, fresh);
405
+ fresh.remove();
406
+ for (const n of old) n.remove();
407
+ return true;
408
+ }
409
+ liveP.forEach((L, i) => {
410
+ const F = freshP[i], into = i ? liveP[i - 1] : container, from = i ? freshP[i - 1] : next;
411
+ syncAttributes(L, F);
412
+ for (const n of [...into.childNodes]) if (n !== L) n.remove();
413
+ let after = false;
414
+ for (const n of [...from.childNodes]) {
415
+ if (n === F) after = true;
416
+ else if (after) into.appendChild(n);
417
+ else into.insertBefore(n, L);
418
+ }
419
+ });
420
+ return true;
421
+ }
330
422
  /** After an edit: give focus back to the edited control only when nothing holds focus. */
331
423
  export function refocusIfLost(doc, container, selector) {
332
424
  if (doc.activeElement && doc.activeElement !== doc.body) return false;
@@ -373,6 +465,37 @@ export function fieldOrigin(f, pages) {
373
465
  return { text: pages ? `filled in on ${Math.round(f.support * pages)} of ${pages}` : 'learned from the references' };
374
466
  }
375
467
 
468
+ /**
469
+ * #2613: how a checklist item did on the reference sheets it was scored on, from its exact counts (`tally`). A rule that
470
+ * reads the drawing (slice 2, it carries `readability`) is scored only on the sheets it could read, so the line says so;
471
+ * a slice-1 item counts a sheet it could not read as not held, so the line names those. '' when there are no counts.
472
+ */
473
+ export function tallyLine(it) {
474
+ const t = it && it.tally;
475
+ if (!t || !t.sheets) return '';
476
+ const sheets = (n) => `${n} sheet${n === 1 ? '' : 's'}`;
477
+ if (typeof it.readability === 'number') {
478
+ if (!t.decided) return `could not be read on any of the ${sheets(t.sheets)}`;
479
+ return t.decided === t.sheets ? `held on ${t.held} of ${sheets(t.sheets)}` : `held on ${t.held} of the ${sheets(t.decided)} it could read · ${t.sheets} checked`;
480
+ }
481
+ return `seen on ${t.held} of ${sheets(t.sheets)}${t.decided < t.sheets ? ` (${t.sheets - t.decided} could not be read)` : ''}`;
482
+ }
483
+
484
+ /** The share bar beside a checklist item, with what the share is of; a dash, not 0%, when the rule could read nothing. */
485
+ export function freqHtml(it) {
486
+ if (!it || typeof it.frequency !== 'number') return '<span></span>';
487
+ const t = it.tally;
488
+ const slice2 = typeof it.readability === 'number';
489
+ if (t && (!t.sheets || (slice2 && !t.decided))) {
490
+ const why = t.sheets ? 'This check could not read any of the reference sheets' : 'This item was not measured on any reference sheet';
491
+ return `<span class="freq" data-tip="${why}"><span class="bar"><i style="width:0%"></i></span>—</span>`;
492
+ }
493
+ const pct = Math.round(it.frequency * 100);
494
+ const tip = slice2 ? 'Share of the sheets this check could read where it held. Sheets it could not read are left out.'
495
+ : `How often this held on the reference drawings${t && t.decided < t.sheets ? '. Unreadable sheets count as not held.' : ''}`;
496
+ return `<span class="freq${pct < 50 ? ' rare' : ''}" data-tip="${esc(tip)}"><span class="bar"><i style="width:${pct}%"></i></span>${pct}%</span>`;
497
+ }
498
+
376
499
  /** Where on the sheet a learned label sits, in words ("bottom right"), from its page-relative box. */
377
500
  export function whereOnSheet(box) {
378
501
  if (!box) return '';
@@ -381,6 +504,37 @@ export function whereOnSheet(box) {
381
504
  return v === 'middle' && h === 'centre' ? 'centre' : `${v} ${h}`;
382
505
  }
383
506
 
507
+ /**
508
+ * The band that says the checklist changed before some of the person's changes were saved, and which ones. It names
509
+ * no cause: another window, AI Chat or this page's own upload of several drawings all look the same from here. With the way back (#3121). `unsaved`: [{ what, gone }], in the order the person made them; `state`: 'ok'
510
+ * (the latest version is shown), 'behind' or 'reading' (it is being read), 'failed' (it could not be read). Nothing
511
+ * is lost and nothing is sent without the person: Apply makes the changes again on the version now shown.
512
+ */
513
+ export const UNSAVED_SHOWN = 5;
514
+ export function unsavedBandHtml({ unsaved = [], state = 'ok', showAll = false } = {}) {
515
+ const n = unsaved.length;
516
+ const line = (u) => `${esc(u.what)}${u.unusable ? ' <span class="note">— not a size FloLess can use, so it can’t be applied</span>'
517
+ : u.gone ? ' <span class="note">— no longer on the checklist, so it won’t be sent again</span>' : ''}`;
518
+ let head;
519
+ if (!n) head = '<p>The checklist changed since this page last showed it.</p>';
520
+ else if (n === 1) head = `<p>The checklist changed before your change went in, so it wasn’t saved: ${line(unsaved[0])}.</p>`;
521
+ else {
522
+ const shown = showAll ? unsaved : unsaved.slice(0, UNSAVED_SHOWN);
523
+ const more = n - shown.length;
524
+ head = `<p>The checklist changed before ${n} of your changes went in, so they weren’t saved:</p>
525
+ <ul class="unsaved-list${showAll ? ' all' : ''}" id="unsaved-list">${shown.map((u) => `<li>${line(u)}</li>`).join('')}</ul>
526
+ ${n > UNSAVED_SHOWN ? `<button type="button" class="link" data-act="unsaved-show-all" data-command-id="drawing-check.unsaved-show-all" aria-expanded="${showAll}" aria-controls="unsaved-list">${showAll ? 'Show fewer' : `Show all ${n}`}</button>${more ? ` <span class="note">and ${more} more</span>` : ''}` : ''}`;
527
+ }
528
+ const reading = state === 'reading' || state === 'behind';
529
+ const sendable = unsaved.filter((u) => !u.gone).length;
530
+ const tail = state === 'failed' ? 'Couldn’t get the latest version just now.' : reading ? 'Getting the latest version…' : 'The page now shows the latest version.';
531
+ const buttons = [
532
+ state === 'ok' && sendable ? `<button type="button" class="primary" data-act="unsaved-apply" data-command-id="drawing-check.unsaved-apply">${sendable === 1 ? 'Apply my change again' : 'Apply my changes again'}</button>` : '',
533
+ state === 'failed' ? '<button type="button" class="primary" data-act="reload" data-command-id="drawing-check.reload">Reload</button>' : '',
534
+ `<button type="button" data-act="unsaved-dismiss" data-command-id="drawing-check.unsaved-dismiss" data-tip="${n ? 'Discard these changes: nothing more is sent' : 'Hide this message'}">Dismiss</button>`,
535
+ ].filter(Boolean).join('');
536
+ return `<div class="band unsaved" role="status" aria-live="polite">${head}<p class="unsaved-state" tabindex="-1">${tail}</p><div class="row-actions">${buttons}</div></div>`;
537
+ }
384
538
  /**
385
539
  * One open question from proposing: the question, one button per candidate with where it was seen, and
386
540
  * "Neither: I'll type the label". Deliberately NO default and no "Suggested" tag, unlike the preflight
@@ -633,7 +787,7 @@ export function partListHtml(pl, { proposed = false } = {}) {
633
787
  const rows = layouts.map((l, i) => {
634
788
  const share = `learned from ${Math.round((l.support || 0) * 100)}% of the references`;
635
789
  const massWords = { 'line-mass': 'the row’s mass', 'unit-mass': 'each piece’s mass' };
636
- const cols = l.columns.map((c) => `${esc(c.label)}${massWords[c.role] ? ` <span class="origin-inline">(${massWords[c.role]})</span>` : ''}`).join(' · ');
790
+ const cols = l.columns.map((c) => `${esc(c.label)}${massWords[c.role] ? ` <span class="origin-inline">(${massWords[c.role]})</span>` : ''}${c.optional ? ' <span class="origin-inline">(not on every list)</span>' : ''}`).join(' · ');
637
791
  const shape = [l.turned ? 'Lettering turned a quarter, as on single-part sheets.' : '', l.rowsRun === 'up' ? 'A one-row strip, the values above their labels.' : ''].filter(Boolean).join(' ');
638
792
  const t = l.total;
639
793
  const ends = !t ? 'No total line was found.'
@@ -681,25 +835,78 @@ function boot() {
681
835
  // What changed in the reference drawings since the page last showed them, when the change came from elsewhere
682
836
  // (Knowledge, AI Chat, another window): said on the Reference drawings tab until the next such change (#2482).
683
837
  liveNote: '',
838
+ // The latest reference drawings could not be read: said apart from liveNote, until a read succeeds (#3297).
839
+ refsReadNote: '',
684
840
  };
685
841
 
686
842
  // This page's own writes still waiting for their answer: a refresh waits for them (refreshNow), so what the page
687
843
  // just did is never read back as a change made elsewhere. `ownWriteSeq` counts every write that started, so a
688
844
  // refresh already reading when the person makes a change knows its answer may hold that change (QA E2E, #2482).
689
- let ownWrites = 0, ownWriteSeq = 0;
845
+ // A write that adds or takes out reference drawings says what it expects to change (`ownRefs`, a list of
846
+ // { sha256, kind }) before it is sent, held in `ownRefPending` while it is out; its answer's `refChanges`, what the
847
+ // server says it actually changed, then go into `ownRefLog`. Whatever else a list from the server differs by was
848
+ // changed elsewhere and is said (#2504, #3297). What is said never waits for these writes.
849
+ // A write that has not answered after OWN_WRITE_WAIT_MS stops holding reads (#3302): it is not abandoned, its caller
850
+ // still takes its answer, but `ownWrites` no longer counts it, so a write that never answers cannot stall every
851
+ // refresh. `ownSettleSeq` counts writes that answered or failed: a read during which one settled may predate what
852
+ // it did, so it is read again (loadDraft). A write that cannot change the draft (a run, a decision on one, the
853
+ // markup colours) says so with `draftWrite: false` and holds nothing at all.
854
+ let ownWrites = 0, ownWriteSeq = 0, ownSettleSeq = 0, ownRefSeq = 0, ownRefLog = [], ownRefPending = new Map();
855
+ const OWN_WRITE_WAIT_MS = 60000;
690
856
  async function call(path, opts = {}) {
691
- const write = !!opts.method && opts.method !== 'GET';
692
- if (write) { ownWrites++; ownWriteSeq++; }
693
- try { return await callOnce(path, opts); } finally { if (write) ownWrites--; }
694
- }
695
- async function callOnce(path, opts) {
857
+ const { ownRefs, draftWrite = true, ...rest } = opts;
858
+ const write = draftWrite && !!rest.method && rest.method !== 'GET';
859
+ const seq = write ? ++ownWriteSeq : 0;
860
+ let counted = write;
861
+ const release = () => { if (counted) { counted = false; ownWrites--; } };
862
+ const overdue = write ? setTimeout(release, OWN_WRITE_WAIT_MS) : null;
863
+ if (write) ownWrites++;
864
+ if (write && ownRefs) ownRefPending.set(seq, ownRefs);
865
+ try {
866
+ const got = await callOnce(path, rest);
867
+ // The change is made: an answer that does not say what it changed costs only an announcement of the page's
868
+ // own change as made elsewhere, never the change itself.
869
+ if (write && ownRefs && got.body && Array.isArray(got.body.refChanges)) {
870
+ ownRefLog = [...ownRefLog, ...got.body.refChanges.map((c) => ({ seq: ++ownRefSeq, sha256: c.sha256, kind: c.kind }))];
871
+ }
872
+ return got;
873
+ } finally { if (write) { clearTimeout(overdue); release(); ownSettleSeq++; ownRefPending.delete(seq); } }
874
+ }
875
+ /** The drawings this page's own writes added and took out: logged after `seq`, and expected by those still out. */
876
+ function ownRefsAfter(seq) {
877
+ const own = { added: new Set(), removed: new Set() };
878
+ const put = (c) => { if (c.kind === 'added') own.added.add(c.sha256); else if (c.kind === 'removed') own.removed.add(c.sha256); };
879
+ for (const c of ownRefLog) if (c.seq > seq) put(c);
880
+ for (const list of ownRefPending.values()) for (const c of list) put(c);
881
+ return own;
882
+ }
883
+ // A read that never answers ends after READ_TIMEOUT_MS; a write only when its caller gives `deadlineMs` (a checklist
884
+ // save, which answers at once): a slow run or Propose is never cut off (#3302). A deadline that runs out, while
885
+ // waiting for the answer or while its body arrives, is said as such: the outcome of a write is then unknown.
886
+ async function callOnce(path, opts = {}) {
887
+ const { deadlineMs, ...rest } = opts;
888
+ const reads = /^(GET|HEAD)$/i.test(String(rest.method || 'GET'));
889
+ const own = rest.signal ? null : deadlineMs ? AbortSignal.timeout(deadlineMs) : reads ? AbortSignal.timeout(READ_TIMEOUT_MS) : null;
890
+ const timedOut = () => {
891
+ const e = new Error(reads ? 'FloLess didn’t answer in time. Try again in a moment.'
892
+ : 'FloLess didn’t answer in time, so it can’t tell whether your change was saved. The page reads the latest again.');
893
+ e.status = 0; e.forPerson = true; e.timedOut = true; return e;
894
+ };
895
+ const signal = own || rest.signal;
696
896
  let res;
697
- try { res = await fetch(path, { credentials: 'same-origin', ...opts }); }
698
- catch { const e = new Error('FloLess could not be reached. Check that it is still running, then try again.'); e.status = 0; throw e; }
897
+ try { res = await fetch(path, { credentials: 'same-origin', ...rest, ...(own ? { signal: own } : {}) }); }
898
+ catch {
899
+ if (signal && signal.aborted) throw timedOut();
900
+ const e = new Error('FloLess could not be reached. Check that it is still running, then try again.'); e.status = 0; e.forPerson = true; throw e;
901
+ }
699
902
  let body = null;
700
- try { body = await res.json(); } catch { /* an empty or non-JSON body */ }
903
+ try { body = await res.json(); } catch { if (signal && signal.aborted) throw timedOut(); /* else an empty or non-JSON body */ }
701
904
  if (!res.ok || (body && body.ok === false)) {
702
- const e = new Error((body && typeof body.error === 'string' && body.error) || 'That didn’t work. Try again.');
905
+ // #3097: the server's sentence only when it wrote one for the person (failure-copy.js), never raw exception text.
906
+ const said = typeof globalThis.personText === 'function' ? globalThis.personText(body) : '';
907
+ const e = new Error(said || (typeof globalThis.failureCopy === 'function'
908
+ ? globalThis.failureCopy({ status: res.status, body }, { retrySafe: reads }).text
909
+ : 'That didn’t work. Try again.'));
703
910
  e.status = res.status; e.body = body; throw e;
704
911
  }
705
912
  return { body, res };
@@ -707,10 +914,120 @@ function boot() {
707
914
  const jsonOpts = (method, data, extra = {}) => ({ method, headers: { 'content-type': 'application/json', ...extra }, body: JSON.stringify(data ?? {}) });
708
915
 
709
916
  // ── loading ──
917
+ // ── what the server holds, and the person's choices still on their way (#3121) ──
918
+ // S.saved is the draft as the server holds it, as far as this page knows; S.pending the person's checklist choices
919
+ // not answered yet, in order. S.draft is derived: the saved draft with every pending choice applied (rebuild), so a
920
+ // read or an answer can replace the saved draft at any time without flicking a pending tick back. Only adopt()
921
+ // changes S.saved, and it paints in the same task: what the person clicks on is always what was adopted, plus their
922
+ // own pending choices. S.gen counts versions this page did not make from what it showed (another window's change,
923
+ // an unconditional answer, a read that found a different draft); each choice carries the gen it was made on and is
924
+ // held, never sent, when that is no longer the gen on screen (choose). S.serial counts every adoption, so a late
925
+ // answer or read is never adopted over a newer one. S.sync: 'ok', 'behind' (a save was refused: the server holds a
926
+ // newer draft), 'reading' (that draft is being read) or 'failed'; S.complete is false while an answer that carried
927
+ // only part of the draft waits for the whole of it.
928
+ Object.assign(S, { saved: { draft: null, etag: null }, pending: [], unsaved: [], gen: 0, serial: 0, sync: 'ok', complete: true, showAllUnsaved: false });
929
+ let booted = false;
930
+ const syncState = () => (S.sync !== 'ok' ? S.sync : S.complete ? 'ok' : 'reading');
931
+ // An answer's draft parts replace the saved ones; an optional part the answer carries as null is deleted (Propose).
932
+ const OPTIONAL_PARTS = new Set(['titleBlock', 'partList', 'lengths']);
933
+ function rebuild() {
934
+ const d = S.saved.draft ? structuredClone(S.saved.draft) : null;
935
+ if (d) for (const c of S.pending) c.apply(d);
936
+ S.draft = d; S.etag = S.saved.etag;
937
+ // A change listed as not saved whose item, field or question is gone from the draft now shown says so, and is
938
+ // never sent again (Apply skips it).
939
+ for (const u of S.unsaved) u.gone = !!d && !u.apply(structuredClone(d));
940
+ }
941
+ // The checklist as it now stands, painted unless a run is on screen (no checklist control is, and the run view is
942
+ // not to be rebuilt by a draft change).
943
+ function paint() {
944
+ for (const show of heldDialogs) show();
945
+ if (!booted || (S.tab === 'runs' && S.run)) return;
946
+ renderKeepingScroll();
947
+ }
948
+ /**
949
+ * Take on a draft the server holds. `draft` replaces it whole; `parts` replaces those fields only (an answer carries
950
+ * part of the draft). `own`: a conditional write of this page's that was sent on the version shown, so its answer is
951
+ * what the person's own choice made of it. Anything else that brings a different version, or completes one that was
952
+ * shown in part, is a version the person has not seen: S.gen moves on.
953
+ */
954
+ function adopt({ draft, parts, etag, own = false }) {
955
+ const before = S.saved.etag, completing = !S.complete && draft !== undefined;
956
+ if (draft !== undefined) S.saved.draft = draft;
957
+ else {
958
+ S.saved.draft = S.saved.draft || {};
959
+ for (const [k, v] of Object.entries(parts)) { if (v == null && OPTIONAL_PARTS.has(k)) delete S.saved.draft[k]; else if (v !== undefined) S.saved.draft[k] = v; }
960
+ }
961
+ S.saved.etag = etag;
962
+ S.serial++;
963
+ if (!own && (etag !== before || completing)) S.gen++;
964
+ if (draft !== undefined) { S.complete = true; wholeDraftShown(); }
965
+ else if (!own) { S.complete = false; readAll(); }
966
+ rebuild();
967
+ paint();
968
+ }
969
+ /** A write's answer, `sent` = { etag, serial, cond } captured as it went out: adopted unless a newer draft was
970
+ * adopted while it was out, which it must not roll back; then the whole draft is read again. */
971
+ function adoptAnswer(sent, parts, etag) {
972
+ if (S.serial !== sent.serial) { S.complete = false; readAll(); rebuild(); paint(); return false; }
973
+ adopt({ parts, etag, own: !!sent.cond && sent.etag === S.saved.etag });
974
+ return true;
975
+ }
976
+ const sending = (etag = S.saved.etag) => ({ etag, serial: S.serial, cond: true });
977
+ // Read the whole draft on the checklist queue: after a refusal (every choice already queued is held at its turn,
978
+ // since S.sync is not 'ok'), and after an answer that carried only part of it. Choices made after this is queued
979
+ // wait behind it, so when their turn comes the whole draft has been shown.
980
+ let readQueued = false;
981
+ function readAll() {
982
+ if (readQueued) return;
983
+ readQueued = true;
984
+ // Nothing is counted as said from the moment this read is queued until a whole draft is shown (by this read, or
985
+ // any other: Reload, a refresh), so an answer that was not taken on (it lost on serial) is not counted as said
986
+ // before the read shows what it did. What the whole draft brings is said once it is adopted, before the approval
987
+ // status is read, so a slow review read never holds the status line (#3297).
988
+ refsAwaitDraft = true;
989
+ void itemsQueue(async () => {
990
+ readQueued = false;
991
+ if (S.sync === 'behind' || S.sync === 'failed') S.sync = 'reading';
992
+ paint();
993
+ const batch = refsBatchOpen();
994
+ try {
995
+ if (await readDraftSettled()) { S.sync = 'ok'; S.refsReadNote = ''; batch.close(); await loadReview(); paint(); return; }
996
+ } catch { /* not read: said as failed below */ }
997
+ batch.close();
998
+ S.sync = 'failed';
999
+ paint();
1000
+ });
1001
+ }
1002
+ /**
1003
+ * Read the draft until a read is adopted: true when one is, false when every try came back stale. A read made while
1004
+ * this page's own write is out (an upload of several drawings) waits for it without using up a try: only reads with
1005
+ * nothing of ours out count, so the page does not call the latest version unreadable. Throws when a read fails.
1006
+ */
1007
+ async function readDraftSettled() {
1008
+ for (let tries = 0, waits = 0; tries < 5 && waits < 200; ) {
1009
+ if (await loadDraft() !== 'stale') return true;
1010
+ if (ownWrites > 0) waits++; else tries++;
1011
+ await new Promise((r) => setTimeout(r, 300)); // read again after it
1012
+ }
1013
+ return false;
1014
+ }
1015
+ // A read the server never answers ends after this long, so it cannot hold the reference status line (#3297).
1016
+ const READ_TIMEOUT_MS = 30000;
1017
+ const timedRead = (url) => fetch(url, { credentials: 'same-origin', signal: AbortSignal.timeout(READ_TIMEOUT_MS) });
1018
+ /** Read the draft. 'adopted' or 'same' (what was read is shown), or 'stale': a write of this page's own was out,
1019
+ * started or answered while it read, or another adoption landed, so the answer may predate it and nothing is
1020
+ * adopted. */
710
1021
  async function loadDraft() {
711
- S.clearNote = ''; S.mainNote = ''; S.breakNote = ''; S.breakError = ''; S.breakTyped = null; // a note about the last change says nothing true about a draft read afresh
712
- const res = await fetch(`/api/contract/${encodeURIComponent(APP)}?project=${encodeURIComponent(PROJECT)}&quietMissing=1`, { credentials: 'same-origin' });
713
- if (res.status === 204) { S.draft = null; S.etag = null; return; }
1022
+ const token = { serial: S.serial, seq: ownWriteSeq, settled: ownSettleSeq, busy: ownWrites > 0 };
1023
+ const stale = () => token.busy || token.seq !== ownWriteSeq || token.settled !== ownSettleSeq || token.serial !== S.serial;
1024
+ const res = await timedRead(`/api/contract/${encodeURIComponent(APP)}?project=${encodeURIComponent(PROJECT)}&quietMissing=1`);
1025
+ if (res.status === 204) {
1026
+ if (stale()) return 'stale';
1027
+ const same = S.saved.etag === null && S.complete;
1028
+ adopt({ draft: null, etag: null });
1029
+ return same ? 'same' : 'adopted';
1030
+ }
714
1031
  if (res.status === 404) throw new Error('This profile could not be found. It may have been archived; open it again from Workspaces.');
715
1032
  // No Drawing Checker on this account: the server's own access copy explains it; "reload" would not help.
716
1033
  if (res.status === 403) {
@@ -720,11 +1037,15 @@ function boot() {
720
1037
  throw new Error(S.accessError);
721
1038
  }
722
1039
  if (!res.ok) throw new Error('This profile could not be read. Reload to try again.');
723
- S.draft = await res.json();
724
- S.etag = res.headers.get('ETag');
1040
+ const draft = await res.json(), etag = res.headers.get('ETag');
1041
+ if (stale()) return 'stale';
1042
+ S.clearNote = ''; S.mainNote = ''; S.bareNote = ''; S.breakNote = ''; S.breakError = ''; S.breakTyped = null; // a note about the last change says nothing true about a draft read afresh
1043
+ const same = etag === S.saved.etag && S.complete;
1044
+ adopt({ draft, etag });
1045
+ return same ? 'same' : 'adopted';
725
1046
  }
726
1047
  async function loadTitleChanges() {
727
- try { S.tbChanges = (await call(`${base}/title-block`)).body.changes || []; } catch { S.tbChanges = []; }
1048
+ try { return (await call(`${base}/title-block`)).body.changes || []; } catch { return []; }
728
1049
  }
729
1050
  /** The title-block changes to show in the approval dialog: a list, 'approved-unreadable', or 'failed'. */
730
1051
  async function titleChangesForApproval() {
@@ -734,15 +1055,23 @@ function boot() {
734
1055
  } catch { return 'failed'; }
735
1056
  }
736
1057
  async function loadReview() {
737
- S.reviewError = '';
738
1058
  // Both land before anything renders: a title-block summary arriving late used to re-render after focus
739
1059
  // had been put back, dropping it.
740
- const changes = loadTitleChanges();
741
- try {
742
- const { body } = await call(`/api/projects/${encodeURIComponent(PROJECT)}/approval-review`);
743
- S.review = body && body.reviewable ? body : null;
744
- } catch { S.review = null; S.reviewError = 'Approval status couldn’t be read. Reload to try again.'; }
745
- await changes;
1060
+ // A draft adopted while these were out may have changed what they say: they are shown only when no draft was
1061
+ // adopted meanwhile, and read again otherwise, a few times at most.
1062
+ for (let tries = 0; tries < 3; tries++) {
1063
+ const serial = S.serial;
1064
+ const changes = loadTitleChanges();
1065
+ let review = null, reviewError = '';
1066
+ try {
1067
+ const { body } = await call(`/api/projects/${encodeURIComponent(PROJECT)}/approval-review`);
1068
+ review = body && body.reviewable ? body : null;
1069
+ } catch { reviewError = 'Approval status couldn’t be read. Reload to try again.'; }
1070
+ const tbChanges = await changes;
1071
+ if (serial === S.serial) { S.review = review; S.reviewError = reviewError; S.tbChanges = tbChanges; return; }
1072
+ }
1073
+ // Every try was overtaken by a newer draft: what is shown may describe an earlier one, and the page says so (#3302).
1074
+ S.reviewError = 'The approval status may be out of date. Reload to see the latest.';
746
1075
  }
747
1076
  async function loadRuns() {
748
1077
  S.runsError = '';
@@ -762,29 +1091,53 @@ function boot() {
762
1091
  async function loadAll() {
763
1092
  S.accessError = '';
764
1093
  // allSettled, not all: every read must land before the page decides which failure to explain.
765
- const settled = await Promise.allSettled([loadDraft(), loadReview(), loadRuns(), loadColours(), loadDesignSet()]);
1094
+ // The draft and the design set are one reference batch, closed when both have landed: the runs, colours and review
1095
+ // reads never hold the reference status line (#3297).
1096
+ const batch = refsBatchOpen();
1097
+ const draftRead = loadDraft(), designSetRead = loadDesignSet();
1098
+ void Promise.allSettled([draftRead, designSetRead]).then(() => batch.close());
1099
+ const settled = await Promise.allSettled([draftRead, loadReview(), loadRuns(), loadColours(), designSetRead]);
766
1100
  const failed = settled.find((r) => r.status === 'rejected');
1101
+ // The whole draft was read and shown: the page is current again. A read that crossed a write of this page's
1102
+ // own adopted nothing; it is read again once that write has answered.
1103
+ if (settled[0].status === 'fulfilled') {
1104
+ if (settled[0].value === 'stale') refreshSoon({ draft: true });
1105
+ else { S.refsReadNote = ''; if (S.sync !== 'reading') S.sync = 'ok'; }
1106
+ }
767
1107
  S.loadError = failed ? (failed.reason && failed.reason.message) || 'This profile could not be read. Reload to try again.' : '';
768
1108
  // A module refusal (no Drawing Checker access) is the one answer that explains every other failure,
769
1109
  // so its own copy is what the page says.
770
1110
  if (S.accessError) S.loadError = S.accessError;
771
1111
  if (!S.tab) S.tab = landingTab({ hasApproved: hasApproved(), referenceCount: references().length });
1112
+ // What the first load found is what the person is first shown: changes are counted from it. Reload compares.
1113
+ if (!refsTold) refsTold = { ...refsNow(), seq: ownRefSeq };
1114
+ booted = true;
772
1115
  render();
773
1116
  }
774
1117
 
775
1118
  // ── shell ──
1119
+ // The text fields typed in since their text was last sent (#3121). A repaint keeps such a field in the page; one
1120
+ // that only has focus is drawn afresh and shows the version just adopted. Recorded from the typing itself.
1121
+ const typedIn = new WeakSet();
1122
+ // The field being typed in while a repaint takes it out of the page: the `change` its removal fires is ignored.
1123
+ let leavingField = null;
776
1124
  const TABS = [['references', 'Reference drawings'], ['checklist', 'Checklist'], ['runs', 'Runs'], ['colours', 'Markup colours']];
777
1125
  function render() {
778
1126
  const v = approvedVersion();
779
1127
  const client = (S.draft && S.draft.client) || 'Client profile';
780
- paintKeepingFocus(document, root, `
1128
+ let left = null;
1129
+ try { paintKeepingFocus(document, root, `
781
1130
  <header><span class="name">${esc(client)}</span>
782
1131
  ${v !== null ? `<span class="pill approved">v${v} approved</span>` : '<span class="pill">Draft</span>'}
783
1132
  ${S.review && S.review.groups && S.review.groups.length && v !== null ? '<span class="pill">Changes not approved</span>' : ''}
784
1133
  <span class="sp"></span></header>
785
1134
  <nav role="tablist" aria-label="Drawing Checker">${TABS.map(([k, l]) =>
786
1135
  `<button type="button" role="tab" id="tab-${k}" aria-controls="panel-${k}" aria-selected="${S.tab === k}" tabindex="${S.tab === k ? 0 : -1}" data-tab="${k}" data-command-id="drawing-check.tab#${esc(k)}" data-command-instance-label="${l}">${l}</button>`).join('')}</nav>
787
- <main>${S.loadError ? `<section role="tabpanel"><div class="wrap"><p class="${S.accessError ? 'band' : 'err-line'}" role="alert">${esc(S.loadError)}</p><button type="button" data-act="reload" data-command-id="drawing-check.reload">Reload</button></div></section>` : panel()}</main>`);
1136
+ <main>${S.loadError ? `<section role="tabpanel"><div class="wrap"><p class="${S.accessError ? 'band' : 'err-line'}" role="alert">${esc(S.loadError)}</p><button type="button" data-act="reload" data-command-id="drawing-check.reload">Reload</button></div></section>` : panel()}</main>`, (el) => typedIn.has(el), (el) => { leavingField = el; left = { el, value: el.value }; }); }
1137
+ finally { leavingField = null; }
1138
+ // Gone from the page: what was typed is listed as not saved, never sent unfinished and never silently lost. (A
1139
+ // browser that cannot move a field copies it into the new one, which then has focus.)
1140
+ if (left && !root.contains(document.activeElement)) holdTyping(left);
788
1141
  if (S.tab === 'runs' && S.run) mountRunView();
789
1142
  }
790
1143
  /** Repaint without moving the tab's scrolled list: render() replaces the scrolling panel, which starts at the top. */
@@ -803,8 +1156,48 @@ function boot() {
803
1156
  return S.run ? `<section ${attrs('runs', 'flush')}>${runViewHtml()}</section>` : `<section ${attrs('runs')}>${runsHtml()}</section>`;
804
1157
  }
805
1158
 
1159
+ // ── the reference status line (#2482, #2504, #3297) ──
1160
+ // `refsTold` is what the person was last shown on Reference drawings, with the position in ownRefLog it accounts
1161
+ // for. A change is worked out against it only when no reference batch is reading (refsSyncing), and the baseline
1162
+ // moves only when Reference drawings is drawn with what was compared, so a change taken in on another tab, or in
1163
+ // several steps, is said once, all together, when the person is next shown the list.
1164
+ let refsTold = null, refsSyncing = 0, refsDrawnKey = '', refsAwaitDraft = false;
1165
+ /** A whole draft was adopted: whatever an answer that was not taken on did is now on screen (readAll). */
1166
+ function wholeDraftShown() { refsAwaitDraft = false; }
1167
+ const refsNow = () => ({ refs: references(), designSet: S.designSetError ? null : S.designSet });
1168
+ /** The rows as drawn: which drawings, where they came from and any warning on them. */
1169
+ const refsKey = () => JSON.stringify(references().map((r) => [r.sha256, r.designIssue ? r.designIssue.issueId : null, referenceDrift(r)]));
1170
+ /** What changed since the person was last shown the list ('' for nothing to say), or null while a batch reads. */
1171
+ function refsChangeNow() {
1172
+ if (!refsTold || refsSyncing || refsAwaitDraft) return null;
1173
+ return referencesChangeNote(refsTold, refsNow(), ownRefsAfter(refsTold.seq));
1174
+ }
1175
+ /** One unit of reading the references (a draft and a design-set read together); closing it says what it brought. */
1176
+ function refsBatchOpen() {
1177
+ refsSyncing++;
1178
+ let open = true;
1179
+ return { close() { if (!open) return false; open = false; refsSyncing--; return deliverRefs(); } };
1180
+ }
1181
+ /** Draw Reference drawings again when there is something to say, or its rows changed without a repaint. */
1182
+ function deliverRefs() {
1183
+ if (!booted || refsSyncing || S.tab !== 'references' || S.run) return false;
1184
+ if (!refsChangeNow() && refsKey() === refsDrawnKey) return false;
1185
+ renderKeepingScroll();
1186
+ return true;
1187
+ }
1188
+ /** Called while drawing Reference drawings: take what changed into the status line and count it as said. */
1189
+ function sayRefsChange() {
1190
+ const note = refsChangeNow();
1191
+ if (note === null) return;
1192
+ if (note) S.liveNote = note;
1193
+ refsTold = { ...refsNow(), seq: ownRefSeq };
1194
+ ownRefLog = ownRefLog.filter((c) => c.seq > refsTold.seq);
1195
+ }
1196
+
806
1197
  // ── references ──
807
1198
  function referencesHtml() {
1199
+ sayRefsChange();
1200
+ refsDrawnKey = refsKey();
808
1201
  const refs = references();
809
1202
  const drop = (compact) => `<button type="button" class="drop${compact ? ' compact' : ''}" data-act="pick-refs" data-command-id="drawing-check.add-references">
810
1203
  <b>${compact ? 'Add more reference drawings' : 'Drop the shop drawings this client already signed off'}</b>
@@ -814,6 +1207,7 @@ function boot() {
814
1207
  ${S.newSinceApproval && approvedVersion() !== null ? `<div class="band">${S.newSinceApproval} new drawing${S.newSinceApproval === 1 ? ' isn’t' : 's aren’t'} in version ${approvedVersion()}. Propose again on the Checklist to include ${S.newSinceApproval === 1 ? 'it' : 'them'}.</div>` : ''}
815
1208
  ${S.uploadNote ? `<p class="note" role="status">${esc(S.uploadNote)}</p>` : ''}
816
1209
  ${S.liveNote ? `<p class="note" role="status" id="refs-live-note">${esc(S.liveNote)}</p>` : ''}
1210
+ ${S.refsReadNote ? `<p class="note" role="status" id="refs-read-note">${esc(S.refsReadNote)}</p>` : ''}
817
1211
  <div class="row-actions"><button type="button" data-act="use-design-set" data-command-id="drawing-check.use-design-set" data-tip="Add drawings from an issue in this project’s Knowledge">Use the design set…</button></div>
818
1212
  ${refs.length ? `<div class="list" style="margin-bottom:14px">${refs.map(referenceRow).join('')}</div>${drop(true)}` : drop(false)}
819
1213
  <input type="file" id="ref-file" accept=".pdf,application/pdf" multiple hidden></div>`;
@@ -823,9 +1217,12 @@ function boot() {
823
1217
  // A pull: the picker reads this profile's own design set (Knowledge) and the server copies the chosen files into the
824
1218
  // references, each recording the issue it came from. The design set is never written from here.
825
1219
  const dsUrl = `/api/projects/${encodeURIComponent(PROJECT)}/design-set`;
1220
+ let designSetSeq = 0;
826
1221
  async function loadDesignSet() {
827
- try { const { body } = await call(dsUrl); S.designSet = body; S.designSetError = ''; }
828
- catch (e) { S.designSet = null; S.designSetError = (e && e.message) || 'The design set could not be read.'; }
1222
+ const my = ++designSetSeq;
1223
+ // Only the latest read is shown: an answer that a newer read has overtaken would put an older design set back.
1224
+ try { const { body } = await call(dsUrl, { signal: AbortSignal.timeout(READ_TIMEOUT_MS) }); if (my === designSetSeq) { S.designSet = body; S.designSetError = ''; } }
1225
+ catch (e) { if (my === designSetSeq) { S.designSet = null; S.designSetError = (e && e.message) || 'The design set could not be read.'; } }
829
1226
  }
830
1227
  /** "12 Oct 2026" from YYYY-MM-DD or an ISO time; the input as it is when it is neither. */
831
1228
  const shortDate = (d) => {
@@ -865,19 +1262,24 @@ function boot() {
865
1262
  if (b.dataset.dlg === 'cancel') { closeDialog(); return; }
866
1263
  b.disabled = true;
867
1264
  try {
868
- const { body } = await call(`${base}/references/${encodeURIComponent(sha)}`, { method: 'DELETE', headers: S.etag ? { 'if-match': S.etag } : {} });
869
- S.draft.references = body.references; S.etag = body.etag; S.kept.delete(sha);
1265
+ const sent = sending(); // conditional on the version shown: its answer is the person's own change
1266
+ const { body } = await call(`${base}/references/${encodeURIComponent(sha)}`, { method: 'DELETE', headers: sent.etag ? { 'if-match': sent.etag } : {}, ownRefs: [{ sha256: sha, kind: 'removed' }] });
1267
+ adoptAnswer(sent, { references: body.references }, body.etag); S.kept.delete(sha);
870
1268
  S.uploadNote = `${ref.name} was taken out of the reference drawings. Propose again on the Checklist to update what was learned from it.`;
871
1269
  closeDialog(false);
872
- try { await Promise.all([loadDraft(), loadReview()]); }
1270
+ const batch = refsBatchOpen();
1271
+ try { await Promise.all([loadDraft().finally(() => batch.close()), loadReview()]); }
873
1272
  catch { S.uploadNote += ' Saved, but the page could not refresh. Reload the profile to see the latest.'; }
874
1273
  render(); document.querySelector('[data-act="use-design-set"]')?.focus();
875
1274
  } catch (err) {
876
1275
  b.disabled = false;
877
1276
  const line = scrim.querySelector('#rr-err');
878
- line.textContent = err.status === 412 || err.status === 428
879
- ? 'The checklist changed in another window. Close this, reload the profile, and try again.'
880
- : (err.message || 'It could not be taken out just now. Try again.');
1277
+ // Refused because the drawings changed elsewhere: the page reads them again itself, and says what changed.
1278
+ const stale = err.status === 412 || err.status === 428;
1279
+ if (stale) { S.complete = false; readAll(); }
1280
+ line.textContent = stale
1281
+ ? 'The checklist changed in another window, so it was not taken out. The page now shows the latest; close this and look again.'
1282
+ : errorText(err, { action: 'take it out of the reference drawings', unsure: 'Reload the profile to see whether it was taken out.' });
881
1283
  line.hidden = false;
882
1284
  }
883
1285
  });
@@ -975,11 +1377,13 @@ function boot() {
975
1377
  st.busy = true; paintFoot(); live.textContent = 'Adding…';
976
1378
  const p = st.plan;
977
1379
  try {
978
- const { body } = await call(`${base}/references/design-issue`, jsonOpts('POST',
1380
+ // Conditional on the version the plan was read from: the person's own change only if that is the one shown.
1381
+ const sent = { ...sending(p.draftEtag || null), cond: !!p.draftEtag };
1382
+ const { body } = await call(`${base}/references/design-issue`, { ...jsonOpts('POST',
979
1383
  { issueId: p.issueId, files: [...st.ticks].sort((a, b) => a - b), planKey: p.planKey, expected: p.expected },
980
- p.draftEtag ? { 'if-match': p.draftEtag } : {}));
981
- S.draft = S.draft || { references: [] };
982
- S.draft.references = body.references; if (body.etag) S.etag = body.etag;
1384
+ p.draftEtag ? { 'if-match': p.draftEtag } : {}),
1385
+ ownRefs: p.files.filter((f) => st.ticks.has(f.index) && f.sha256).map((f) => ({ sha256: f.sha256, kind: 'added' })) });
1386
+ if (body.etag) adoptAnswer(sent, { references: body.references }, body.etag);
983
1387
  if (body.added.length) S.newSinceApproval += body.added.length;
984
1388
  const parts = [];
985
1389
  if (body.added.length) parts.push(`${body.added.length} drawing${body.added.length === 1 ? '' : 's'} added from ${body.label}.`);
@@ -987,7 +1391,8 @@ function boot() {
987
1391
  if (!body.added.length && !body.recorded.length) parts.push(`Nothing changed: the chosen drawings are already references.`);
988
1392
  if (body.notAdded.length) parts.push(`${body.notAdded.length} not added: ${body.notAdded.map((n) => `${n.filename} (${n.reason})`).join('; ')}.`);
989
1393
  closeDialog(false);
990
- try { await Promise.all([loadDraft(), loadReview(), loadDesignSet()]); }
1394
+ const batch = refsBatchOpen();
1395
+ try { await Promise.all([Promise.all([loadDraft(), loadDesignSet()]).finally(() => batch.close()), loadReview()]); }
991
1396
  catch { parts.push('Saved, but the page could not refresh. Reload the profile to see the latest.'); }
992
1397
  S.uploadNote = parts.join(' ');
993
1398
  render(); document.querySelector('[data-act="use-design-set"]')?.focus();
@@ -996,7 +1401,8 @@ function boot() {
996
1401
  const code = e.body && e.body.code;
997
1402
  if (code === 'design-set-changed' || e.status === 412 || e.status === 428) {
998
1403
  st.note = code === 'design-set-changed' ? 'The design set changed — check the files again.' : 'The checklist changed in another window — check the files again.';
999
- await Promise.all([loadDraft(), loadDesignSet()]).catch(() => {});
1404
+ const batch = refsBatchOpen();
1405
+ await Promise.all([loadDraft(), loadDesignSet()]).catch(() => {}).finally(() => batch.close());
1000
1406
  if (code === 'design-set-changed' && e.body.plan) {
1001
1407
  const prev = st.ticks; st.plan = e.body.plan;
1002
1408
  st.ticks = new Set(st.plan.files.filter((f) => f.selectable && prev.has(f.index)).map((f) => f.index));
@@ -1040,6 +1446,14 @@ function boot() {
1040
1446
  else paintIssues();
1041
1447
  })();
1042
1448
  }
1449
+ /** The SHA-256 of a file, as the server names a reference drawing; '' when this browser cannot work it out (its
1450
+ * answer still says what it changed, so only an overlap with a change made elsewhere is less exact). */
1451
+ async function pdfDigest(file) {
1452
+ try {
1453
+ const d = new Uint8Array(await crypto.subtle.digest('SHA-256', await file.arrayBuffer()));
1454
+ return [...d].map((b) => b.toString(16).padStart(2, '0')).join('');
1455
+ } catch { return ''; }
1456
+ }
1043
1457
  async function uploadReferences(files) {
1044
1458
  const pdfs = [...files].filter((f) => /\.pdf$/i.test(f.name) || f.type === 'application/pdf');
1045
1459
  const skipped = files.length - pdfs.length;
@@ -1048,8 +1462,13 @@ function boot() {
1048
1462
  for (let i = 0; i < pdfs.length; i++) {
1049
1463
  S.uploadNote = `Adding ${pdfs[i].name} (${i + 1} of ${pdfs.length})…`; render();
1050
1464
  try {
1051
- const { body } = await call(`${base}/references?name=${encodeURIComponent(pdfs[i].name)}`, { method: 'POST', headers: { 'content-type': 'application/pdf' }, body: pdfs[i] });
1052
- if (S.draft) S.draft.references = body.references; added++;
1465
+ const sent = { ...sending(), cond: false }; // unconditional, like Propose
1466
+ const digest = await pdfDigest(pdfs[i]);
1467
+ const { body } = await call(`${base}/references?name=${encodeURIComponent(pdfs[i].name)}`, { method: 'POST', headers: { 'content-type': 'application/pdf' }, body: pdfs[i],
1468
+ ownRefs: digest ? [{ sha256: digest, kind: 'added' }] : [] });
1469
+ // Adopted even on a profile with no draft yet: the first upload creates it, and the read that follows shows it.
1470
+ adoptAnswer(sent, { references: body.references }, body.etag);
1471
+ added++;
1053
1472
  } catch (e) { failed.push(e.message); }
1054
1473
  }
1055
1474
  if (added) S.newSinceApproval += added;
@@ -1058,14 +1477,16 @@ function boot() {
1058
1477
  if (skipped) notes.push(`${skipped} file${skipped === 1 ? '' : 's'} skipped: not PDF${skipped === 1 ? '' : 's'}.`);
1059
1478
  notes.push(...failed);
1060
1479
  S.uploadNote = notes.join(' ');
1061
- await Promise.all([loadDraft(), loadReview()]).catch(() => {});
1480
+ // The whole draft, and the approval status with it, is read on the checklist queue after an upload's answer (adopt).
1062
1481
  render();
1063
1482
  }
1064
1483
 
1065
1484
  // ── checklist ──
1066
1485
  function checklistHtml() {
1486
+ // Held changes are listed even when another window left no references: they stay offered, never silently gone.
1487
+ const band = S.conflict || S.unsaved.length ? unsavedBandHtml({ unsaved: S.unsaved, state: syncState(), showAll: S.showAllUnsaved }) : '';
1067
1488
  if (!references().length) {
1068
- return `<div class="wrap"><h2>Checklist</h2><p class="lede">Add reference drawings first: the checklist is proposed from drawings this client already trusts.</p>
1489
+ return `<div class="wrap"><h2 tabindex="-1">Checklist</h2>${band}<p class="lede">Add reference drawings first: the checklist is proposed from drawings this client already trusts.</p>
1069
1490
  <button type="button" class="link" data-tab="references" data-command-id="drawing-check.tab#references" data-command-instance-label="Reference drawings">Go to Reference drawings</button></div>`;
1070
1491
  }
1071
1492
  const list = items();
@@ -1073,26 +1494,26 @@ function boot() {
1073
1494
  const anyTicked = list.some((i) => i.enabled);
1074
1495
  const changed = !!(S.review && S.review.groups && S.review.groups.length);
1075
1496
  const rows = list.map((it) => {
1076
- const pct = typeof it.frequency === 'number' ? Math.round(it.frequency * 100) : null;
1077
1497
  const origin = it.origin === 'client-standard'
1078
1498
  ? 'added from client standard'
1079
- : it.origin === 'redline' ? 'added from a redline' : pct !== null && pages ? `seen on ${Math.round(it.frequency * pages)} of ${pages}` : 'proposed from the references';
1499
+ : it.origin === 'redline' ? 'added from a redline' : tallyLine(it) || 'proposed from the references';
1080
1500
  return `<label class="check-row"><input type="checkbox" data-item="${esc(it.id)}" data-command-id="drawing-check.tick-item#${esc(it.id)}" data-command-instance-label="${esc(it.label)}"${it.enabled ? ' checked' : ''}>
1081
1501
  <span class="lbl">${esc(it.label)}<span class="origin">${esc(origin)}</span></span>
1082
- ${pct !== null ? `<span class="freq${pct < 50 ? ' rare' : ''}" data-tip="How often this held on the reference drawings"><span class="bar"><i style="width:${pct}%"></i></span>${pct}%</span>` : '<span></span>'}
1502
+ ${freqHtml(it)}
1083
1503
  <span class="kind">by code</span></label>${it.rule && it.rule.type === 'hole-bolt' ? clearancesHtml(it, S.clearNote) : ''}${it.rule && it.rule.type === 'part-list-agrees' && mainRowItem(list) === it
1084
1504
  ? mainPartHtml(it, { touched: ((S.draft && S.draft.touched) || []).includes(`item:${it.id}.mainRow`), note: S.mainNote, locatedOn: list.some((x) => x.enabled && x.rule && x.rule.type === 'parts-located') }) : ''}${it.rule && it.rule.type === 'parts-located'
1085
1505
  ? lineBreakHtml(it, { touched: ((S.draft && S.draft.touched) || []).includes(`item:${it.id}.lineBreakPt`), note: S.breakNote, error: S.breakError, typed: S.breakTyped }) : ''}`;
1086
1506
  }).join('');
1087
- return `<div class="wrap"><h2>Checklist</h2>
1507
+ return `<div class="wrap"><h2 tabindex="-1">Checklist</h2>
1088
1508
  <p class="lede">Common doesn’t mean required. Tick only what this client needs.</p>
1089
1509
  ${pendingAsksNotice(S.draft && S.draft.titleBlock)}
1090
1510
  ${clientFieldHtml((S.draft && S.draft.client) || '')}
1091
1511
  <div class="row-actions"><button type="button" class="${list.length ? '' : 'primary'}" data-act="propose" data-command-id="drawing-check.propose">${list.length ? 'Propose again from references' : 'Propose from references'}</button>
1092
1512
  <button type="button" data-act="add-item" data-command-id="drawing-check.add-item">Add item from client standard…</button></div>
1093
- ${S.conflict ? '<div class="band">This checklist changed in another window. Reload to see the latest. <button type="button" data-act="reload" data-command-id="drawing-check.reload">Reload</button></div>' : ''}
1513
+ ${band}
1094
1514
  ${S.checklistError ? `<p class="err-line" role="alert">${esc(S.checklistError)}</p>` : ''}
1095
1515
  ${list.length ? `<div class="list">${rows}</div>` : '<p class="note">No items yet. Propose them from the reference drawings.</p>'}
1516
+ ${bareInchHtml(S.draft && S.draft.lengths, { touched: ((S.draft && S.draft.touched) || []).includes('lengths.bareInchValues'), note: S.bareNote })}
1096
1517
  ${titleBlockHtml(S.draft && S.draft.titleBlock, { pages, note: S.titleNote, noteField: S.titleNoteField, saving: S.tbSaving, typed: S.typed })}
1097
1518
  ${partListHtml(S.draft && S.draft.partList, { proposed: list.length > 0 })}
1098
1519
  ${S.reviewError ? `<p class="note">${esc(S.reviewError)}</p>` : ''}
@@ -1121,157 +1542,280 @@ function boot() {
1121
1542
  },
1122
1543
  });
1123
1544
  }
1124
- // Rides the checklist queue: one draft, one etag, one PUT at a time.
1125
- function putClearances(standard) {
1545
+ // ── checklist choices: one queue, one draft, one etag, one PUT at a time (#3121) ──
1546
+ // A choice shows at once (its `apply`, on the derived draft) and goes out when its turn comes, with the etag the page
1547
+ // then holds. It is held, never sent, when the page has since adopted a version the person did not make from what
1548
+ // they saw (its gen is no longer S.gen), or a refusal said the server holds a newer one (S.sync is not 'ok'): sending
1549
+ // it then would write a choice made on the old draft over the newer one. A held choice is listed as not saved and
1550
+ // offered back (unsavedBandHtml), or kept in the dialog it came from. The handlers call these before any await, so
1551
+ // the gen a choice carries is the one on screen when the person acted.
1552
+ const itemsQueue = serialise();
1553
+ let itemsInFlight = 0, choiceSeq = 0;
1554
+ // A checklist save answers at once; one that has not answered after this long frees the queue behind it (#3302).
1555
+ const CHOICE_DEADLINE_MS = 60000;
1556
+ // The newest choice for each thing, and for each item or field the newest removal of it: an older choice that is
1557
+ // held after a newer one was made is not offered back over it.
1558
+ const latest = new Map(), removedAt = new Map();
1559
+ /**
1560
+ * Queue a choice. `key` names what it changes and `family` the item or field it belongs to (a removal, `removes`,
1561
+ * takes the family's other choices with it). `apply(draft)` shows it on a draft and says whether its target is still
1562
+ * there; `url`/`body` send it; `parts(body)` are the draft parts its answer brings; `answered(body, newest, fresh)` sets its
1563
+ * note (`fresh`: no newer version was taken on while it was out, so its answer is the one about to be shown); `failed(e)` says a failure that is not a refusal; `held()` and `settled()` tidy up. `what` says it in the
1564
+ * band, `redo()` makes it again. `dialog`: kept in the dialog it came from when held, not listed.
1565
+ * Resolves to the answer's body, null (failed) or 'held'.
1566
+ */
1567
+ function choose(c, { unsent = false } = {}) {
1568
+ c.seq = ++choiceSeq; c.gen = S.gen;
1569
+ latest.set(c.key, c.seq);
1570
+ if (c.removes) removedAt.set(c.family, c.seq);
1571
+ // The newest choice for a thing retires the offer of an older one.
1572
+ S.unsaved = S.unsaved.filter((u) => u.key !== c.key && !(c.removes && u.family === c.family));
1573
+ // Text still being typed when its field left the page: listed as not saved, never sent.
1574
+ if (unsent) { hold(c); return Promise.resolve('held'); }
1575
+ S.pending.push(c); rebuild(); paint();
1126
1576
  itemsInFlight++;
1127
1577
  return itemsQueue(async () => {
1128
- S.checklistError = ''; S.clearNote = '';
1129
1578
  try {
1130
- const { body } = await call(`${base}/clearances`, jsonOpts('PUT', { standard }, S.etag ? { 'if-match': S.etag } : {}));
1131
- S.etag = body.etag;
1132
- const filled = (body.items.find((i) => i.rule && i.rule.type === 'hole-bolt')?.rule.clearances || []).length;
1133
- S.clearNote = `Filled with ${filled} starter row${filled === 1 ? '' : 's'} from ${STANDARD_NAMES[standard]}.`;
1134
- // As putItems: only the LAST answer repaints the list, so ticks queued behind this fill never flick back.
1135
- if (itemsInFlight === 1) { S.draft.items = body.items; await loadReview(); render(); }
1136
- else {
1137
- // Not the last answer: keep the filled rows (the table must match the note), leave the rest of the list as it stands.
1138
- const mine = S.draft.items.find((i) => i.rule && i.rule.type === 'hole-bolt');
1139
- const theirs = body.items.find((i) => i.rule && i.rule.type === 'hole-bolt');
1140
- if (mine && theirs) mine.rule.clearances = theirs.rule.clearances;
1579
+ if (c.gen !== S.gen || S.sync !== 'ok') { hold(c); return 'held'; }
1580
+ const sent = sending();
1581
+ let body;
1582
+ try { ({ body } = await call(c.url, { ...jsonOpts('PUT', c.body, sent.etag ? { 'if-match': sent.etag } : {}), deadlineMs: CHOICE_DEADLINE_MS })); }
1583
+ catch (e) {
1584
+ if (e.status === 412 || e.status === 428) {
1585
+ // The server holds a newer draft: everything queued behind this is held at its turn, and the draft is
1586
+ // read once they have all had it (readAll queues behind them).
1587
+ S.conflict = true; S.sync = 'behind'; readAll();
1588
+ hold(c); return 'held';
1589
+ }
1590
+ S.pending = S.pending.filter((p) => p !== c); rebuild(); // its optimistic change goes; what is saved shows
1591
+ if (c.failed) c.failed(e); else S.checklistError = e.message;
1592
+ // No answer in time: it may have been saved or not, so the whole draft is read to show what was (#3302).
1593
+ if (e.timedOut) { S.complete = false; readAll(); }
1594
+ paint(); return null;
1141
1595
  }
1142
- } catch (e) {
1143
- if (e.status === 412 || e.status === 428) S.conflict = true;
1144
- else S.checklistError = e.message;
1145
- await loadDraft().catch(() => {});
1146
- render();
1147
- } finally { itemsInFlight--; }
1596
+ S.pending = S.pending.filter((p) => p !== c);
1597
+ if (c.answered) c.answered(body, latest.get(c.key) === c.seq, S.serial === sent.serial);
1598
+ if (adoptAnswer(sent, c.parts(body), body.etag) && itemsInFlight === 1) { await loadReview(); paint(); }
1599
+ return body;
1600
+ } finally {
1601
+ itemsInFlight--;
1602
+ if (c.settled) { c.settled(); paint(); }
1603
+ }
1148
1604
  });
1149
1605
  }
1150
- // The line break: one PUT on the checklist queue, as the main part setting. Each save is numbered: an earlier
1151
- // answer never puts back a value over a later one still queued (diff review r1), and the answer to the last save
1152
- // shows what was saved even when other edits are still queued.
1153
- let breakSaves = 0;
1154
- function putLineBreak(pt) {
1155
- itemsInFlight++;
1156
- const save = ++breakSaves;
1157
- return itemsQueue(async () => {
1158
- S.checklistError = ''; S.breakNote = '';
1159
- try {
1160
- const { body } = await call(`${base}/line-break`, jsonOpts('PUT', { pt }, S.etag ? { 'if-match': S.etag } : {}));
1161
- S.etag = body.etag;
1162
- S.breakNote = pt ? `The largest break closed is now ${pt} pt. The checklist has to be approved again.` : 'Breaks in drawn lines are no longer closed. The checklist has to be approved again.';
1163
- const r7 = body.items.find((x) => x.rule && x.rule.type === 'parts-located');
1164
- if (r7) S.draft.touched = [...new Set([...(S.draft.touched || []), `item:${r7.id}.lineBreakPt`])];
1165
- if (itemsInFlight === 1) { S.draft.items = body.items; await loadReview(); render(); }
1166
- else if (save === breakSaves) {
1167
- const mine = items().find((x) => x.rule && x.rule.type === 'parts-located');
1168
- if (mine && r7) { mine.rule.lineBreakPt = r7.rule.lineBreakPt; render(); }
1169
- }
1170
- // Otherwise a later save is still queued: its value stays as shown, and the note waits for its answer.
1171
- else S.breakNote = '';
1172
- } catch (e) {
1173
- if (e.status === 412 || e.status === 428) S.conflict = true;
1174
- else S.checklistError = e.message;
1175
- await loadDraft().catch(() => {});
1176
- render();
1177
- } finally { itemsInFlight--; }
1606
+ function hold(c) {
1607
+ S.pending = S.pending.filter((p) => p !== c);
1608
+ rebuild();
1609
+ if (c.held) c.held();
1610
+ const newest = latest.get(c.key) === c.seq && !((removedAt.get(c.family) || 0) > c.seq);
1611
+ if (newest && !c.dialog) {
1612
+ S.unsaved.push({ key: c.key, family: c.family, what: c.what, redo: c.redo, apply: c.apply, gone: !!S.draft && !c.apply(structuredClone(S.draft)) });
1613
+ }
1614
+ paint();
1615
+ }
1616
+ /** Apply my changes again: each listed change is made again on the draft now shown, in order, in this one task. */
1617
+ function applyUnsaved() {
1618
+ if (syncState() !== 'ok') return;
1619
+ // Making a change again takes it off the list (choose retires the older one of each key), so a second click finds
1620
+ // nothing to send twice; a change whose target is gone stays listed, never sent.
1621
+ const again = S.unsaved.filter((u) => !u.gone);
1622
+ S.conflict = false;
1623
+ for (const u of again) void u.redo();
1624
+ }
1625
+ const itemLabel = (id) => { const it = items().find((i) => i.id === id); return it ? (it.display || it.label || id) : id; };
1626
+ const fieldLabel = (name) => { const f = ((S.draft && S.draft.titleBlock && S.draft.titleBlock.fields) || []).find((x) => x.name === name); return (f && f.label) || FIELD_WORDS[name] || name; };
1627
+ const findItem = (d, id) => (d.items || []).find((i) => i.id === id);
1628
+ const findField = (d, name) => ((d.titleBlock && d.titleBlock.fields) || []).find((x) => x.name === name);
1629
+ const withTouched = (key) => [...new Set([...((S.saved.draft && S.saved.draft.touched) || []), key])];
1630
+
1631
+ function putClearances(standard) {
1632
+ S.checklistError = ''; S.clearNote = '';
1633
+ return choose({
1634
+ key: 'clearances', family: 'clearances', what: `Filled the clearance table from ${STANDARD_NAMES[standard]}`,
1635
+ url: `${base}/clearances`, body: { standard },
1636
+ apply: (d) => (d.items || []).some((i) => i.rule && i.rule.type === 'hole-bolt'),
1637
+ parts: (b) => ({ items: b.items }),
1638
+ answered: (b) => {
1639
+ const filled = (b.items.find((i) => i.rule && i.rule.type === 'hole-bolt')?.rule.clearances || []).length;
1640
+ S.clearNote = `Filled with ${filled} starter row${filled === 1 ? '' : 's'} from ${STANDARD_NAMES[standard]}.`;
1641
+ },
1642
+ redo: () => putClearances(standard),
1178
1643
  });
1179
1644
  }
1180
- // Whether the main part's mark is the assembly mark: one PUT on the checklist queue, as the clearance fill.
1181
- // Each main part click is numbered: an answer settles the choice on the page unless a later click is on its way.
1182
- let mainClicks = 0;
1645
+ // The line break. Its note waits for the answer to the newest line-break choice: an earlier answer says nothing
1646
+ // true about a value still on its way.
1647
+ function putLineBreak(pt, { unsent = false } = {}) {
1648
+ S.checklistError = ''; S.breakNote = '';
1649
+ const r7 = (d) => (d.items || []).find((x) => x.rule && x.rule.type === 'parts-located');
1650
+ return choose({
1651
+ key: 'line-break', family: 'line-break', what: pt ? `Set the line break to ${pt} pt` : 'Switched off closing breaks in drawn lines',
1652
+ url: `${base}/line-break`, body: { pt },
1653
+ apply: (d) => { const it = r7(d); if (it) it.rule.lineBreakPt = pt; return !!it; },
1654
+ parts: (b) => { const it = r7(b); return { items: b.items, ...(it ? { touched: withTouched(`item:${it.id}.lineBreakPt`) } : {}) }; },
1655
+ answered: (_b, newest) => {
1656
+ S.breakNote = !newest ? '' : pt ? `The largest break closed is now ${pt} pt. The checklist has to be approved again.` : 'Breaks in drawn lines are no longer closed. The checklist has to be approved again.';
1657
+ },
1658
+ redo: () => putLineBreak(pt),
1659
+ }, { unsent });
1660
+ }
1661
+ // Whether the main part's mark is the assembly mark.
1183
1662
  function putMainPart(assemblyMark) {
1184
- itemsInFlight++;
1185
- const click = ++mainClicks;
1186
- return itemsQueue(async () => {
1187
- S.checklistError = ''; S.mainNote = '';
1188
- try {
1189
- const { body } = await call(`${base}/main-part`, jsonOpts('PUT', { assemblyMark }, S.etag ? { 'if-match': S.etag } : {}));
1190
- S.etag = body.etag;
1191
- S.mainNote = `Main part set to “${assemblyMark ? 'same as the assembly mark' : 'the first marked row'}”. The checklist has to be approved again.`;
1192
- // The server marks the setting the person's; so does the page, for the "set by you" chip.
1193
- const r1 = mainRowItem(body.items);
1194
- if (r1) S.draft.touched = [...new Set([...(S.draft.touched || []), `item:${r1.id}.mainRow`])];
1195
- if (itemsInFlight === 1) { S.draft.items = body.items; await loadReview(); render(); }
1196
- else if (click === mainClicks) {
1197
- // Not the last answer, but the last main part click: what was saved is shown, even if a reload after
1198
- // another edit's refusal put back the old choice. Other items wait for the last answer (review r2).
1199
- const mine = mainRowItem(S.draft.items);
1200
- if (mine && r1 && mine.id === r1.id) { mine.rule.mainRow = r1.rule.mainRow; render(); }
1201
- }
1202
- // Otherwise a later click is still queued: its choice stays as shown.
1203
- } catch (e) {
1204
- if (e.status === 412 || e.status === 428) S.conflict = true;
1205
- else S.checklistError = e.message;
1206
- await loadDraft().catch(() => {});
1207
- render();
1208
- } finally { itemsInFlight--; }
1663
+ S.checklistError = ''; S.mainNote = '';
1664
+ const row = assemblyMark ? 'mark-equals-assembly' : 'first-marked-row';
1665
+ const words = assemblyMark ? 'same as the assembly mark' : 'the first marked row';
1666
+ return choose({
1667
+ key: 'main-part', family: 'main-part', what: `Set the main part to “${words}”`,
1668
+ url: `${base}/main-part`, body: { assemblyMark },
1669
+ apply: (d) => { const it = mainRowItem(d.items); if (it) it.rule.mainRow = row; return !!it; },
1670
+ // The server marks the setting the person's; so does the page, for the "set by you" chip.
1671
+ parts: (b) => { const r1 = mainRowItem(b.items); return { items: b.items, ...(r1 ? { touched: withTouched(`item:${r1.id}.mainRow`) } : {}) }; },
1672
+ answered: (_b, newest) => { if (newest) S.mainNote = `Main part set to “${words}”. The checklist has to be approved again.`; },
1673
+ redo: () => putMainPart(assemblyMark),
1209
1674
  });
1210
1675
  }
1211
- // Checklist edits go out ONE AT A TIME. Two quick ticks used to send the second PUT with the etag the
1212
- // page held before the first answered, which the server rightly refused (412) — shown as "changed in
1213
- // another window" and the tick reverted. Each queued PUT reads S.etag when it actually goes out.
1214
- const itemsQueue = serialise();
1215
- let itemsInFlight = 0;
1216
- function putItems(edits) {
1217
- itemsInFlight++;
1218
- return itemsQueue(async () => {
1219
- S.checklistError = '';
1220
- try {
1221
- const { body } = await call(`${base}/items`, jsonOpts('PUT', { items: edits }, S.etag ? { 'if-match': S.etag } : {}));
1222
- S.etag = body.etag;
1223
- // Only the LAST answer replaces the list: an earlier one predates ticks still queued behind it,
1224
- // and painting it would flick those ticks back until their own answer arrived. The list keeps its scroll.
1225
- if (itemsInFlight === 1) { S.draft.items = body.items; await loadReview(); renderKeepingScroll(); }
1226
- return body;
1227
- } catch (e) {
1228
- if (e.status === 412 || e.status === 428) S.conflict = true;
1229
- else S.checklistError = e.message;
1230
- await loadDraft().catch(() => {}); // show what the profile really holds, not the optimistic ticks
1231
- renderKeepingScroll();
1232
- return null;
1233
- } finally { itemsInFlight--; }
1676
+ // Whether this client writes inches without a mark (#2991). It is the person's from the click: the chip never credits
1677
+ // the references with their choice while it is out, and a choice held or failed takes that mark away with it.
1678
+ function putBareInches(bareInches) {
1679
+ S.checklistError = ''; S.bareNote = '';
1680
+ // What it was on the version the person chose on: choosing the answer already shown makes it theirs and changes no
1681
+ // reading, so its note never says that a reading changed (diff review r1).
1682
+ const was = !!(S.draft && S.draft.lengths && S.draft.lengths.bareInchValues === true);
1683
+ return choose({
1684
+ key: 'bare-inches', family: 'bare-inches',
1685
+ // In the control's own words, as the main part's line: "not inches" could be heard as "metric" (design review).
1686
+ what: `Set numbers without a mark to “${bareInches ? 'read them as inches' : 'say couldn’t tell'}”`,
1687
+ url: `${base}/bare-inches`, body: { bareInches },
1688
+ apply: (d) => {
1689
+ if (!d.lengths) return false;
1690
+ d.lengths.bareInchValues = bareInches;
1691
+ d.touched = [...new Set([...(d.touched || []), 'lengths.bareInchValues'])];
1692
+ return true;
1693
+ },
1694
+ parts: (b) => ({ lengths: b.lengths, touched: withTouched('lengths.bareInchValues') }),
1695
+ // Only the answer about to be shown says what was saved: one that lands after a newer version was taken on would
1696
+ // put its note (a metric warning, say) beside a setting it says nothing about (Codex plan review).
1697
+ answered: (b, newest, fresh) => {
1698
+ if (!newest || !fresh) return;
1699
+ const said = bareInches ? (was ? 'is still read as inches, now as your answer' : 'is now read as inches')
1700
+ : was ? 'is no longer read: it is reported as couldn’t tell' : 'is still reported as couldn’t tell, now as your answer';
1701
+ S.bareNote = b.warning ? b.warning : `A number without a mark on a dimension ${said}. The checklist has to be approved again.`;
1702
+ },
1703
+ redo: () => putBareInches(bareInches),
1234
1704
  });
1235
1705
  }
1236
- // The client goes out on the same queue as the ticks: one draft, one etag, one PUT at a time.
1237
- function putClient(client) {
1238
- itemsInFlight++;
1239
- return itemsQueue(async () => {
1240
- S.checklistError = '';
1241
- try {
1242
- const { body } = await call(`${base}/client`, jsonOpts('PUT', { client }, S.etag ? { 'if-match': S.etag } : {}));
1243
- S.etag = body.etag; S.draft.client = body.client;
1244
- await loadReview();
1245
- } catch (e) {
1246
- if (e.status === 412 || e.status === 428) S.conflict = true;
1247
- else S.checklistError = e.message;
1248
- await loadDraft().catch(() => {});
1249
- } finally { itemsInFlight--; }
1250
- render();
1706
+ /** One item edit: ticked or not, removed, or added (from the Add item dialog, which keeps it if it is held). */
1707
+ function putItems(edits, { dialog = false } = {}) {
1708
+ S.checklistError = '';
1709
+ const e = edits[0];
1710
+ const label = e.id ? itemLabel(e.id) : e.label;
1711
+ const kind = e.remove ? 'remove' : e.id ? 'enabled' : 'add';
1712
+ const family = e.id ? `item:${e.id}` : `item-add:${e.label}`;
1713
+ return choose({
1714
+ key: kind === 'add' ? family : `${family}:${kind}`, family, removes: kind === 'remove', dialog,
1715
+ what: kind === 'remove' ? `Removed “${label}”` : kind === 'add' ? `Added “${label}”` : `${e.enabled ? 'Ticked' : 'Unticked'} “${label}”`,
1716
+ url: `${base}/items`, body: { items: edits },
1717
+ apply: (d) => { if (kind === 'add') return true; const it = findItem(d, e.id); if (it && kind === 'enabled') it.enabled = e.enabled; return !!it; },
1718
+ parts: (b) => ({ items: b.items }),
1719
+ redo: () => putItems(edits, { dialog }),
1251
1720
  });
1252
1721
  }
1253
- // Title-block edits ride the same queue: one draft, one etag, one PUT at a time.
1254
- function putTitleBlock(change) {
1255
- itemsInFlight++;
1256
- return itemsQueue(async () => {
1257
- S.checklistError = ''; S.titleNote = ''; S.titleNoteField = '';
1258
- try {
1259
- const { body } = await call(`${base}/title-block`, jsonOpts('PUT', change, S.etag ? { 'if-match': S.etag } : {}));
1260
- S.etag = body.etag;
1261
- if (itemsInFlight === 1) { S.draft.titleBlock = body.titleBlock; S.draft.items = body.items; }
1262
- if (body.note) { S.titleNote = body.note; S.titleNoteField = body.noteField || ''; }
1722
+ // A field being typed in that a repaint took out of the page (another window's version has no place for it):
1723
+ // what was typed, if it would change anything, is listed as not saved with the way to make it on this version.
1724
+ function holdTyping({ el, value }) {
1725
+ const text = value.replace(/\s+/g, ' ').trim(), d = S.draft || {};
1726
+ if (el.id === 'client-name') { if (text && text !== d.client) putClient(text, { unsent: true }); return; }
1727
+ if (el.id === 'line-break-pt') {
1728
+ const got = parseLineBreak(value), it = (d.items || []).find((x) => x.rule && x.rule.type === 'parts-located');
1729
+ if (!('why' in got)) { if (!it || got.pt !== (it.rule.lineBreakPt ?? 0)) putLineBreak(got.pt, { unsent: true }); return; }
1730
+ // Not a size yet (half-typed, like "."): listed as typed so it is not lost, and only Dismiss is offered.
1731
+ if (text) {
1732
+ S.unsaved = S.unsaved.filter((u) => u.key !== 'line-break');
1733
+ S.unsaved.push({ key: 'line-break', family: 'line-break', what: `Typed “${text}” as the line break`, unusable: true, gone: true, apply: () => false, redo: () => {} });
1734
+ paint();
1735
+ }
1736
+ return;
1737
+ }
1738
+ if (el.dataset.tbLabel) {
1739
+ const f = findField(d, el.dataset.tbLabel);
1740
+ if (text && (!f || text !== f.label)) putTitleBlock({ field: el.dataset.tbLabel, label: text }, { unsent: true });
1741
+ return;
1742
+ }
1743
+ if (el.dataset.typedLabel && text) putTitleBlock({ answer: { ask: el.dataset.typedLabel, label: text } }, { unsent: true });
1744
+ }
1745
+ function putClient(client, { unsent = false } = {}) {
1746
+ S.checklistError = '';
1747
+ return choose({
1748
+ key: 'client', family: 'client', what: `Set the client name to “${client}”`,
1749
+ url: `${base}/client`, body: { client },
1750
+ apply: (d) => { d.client = client; return true; },
1751
+ parts: (b) => ({ client: b.client }),
1752
+ redo: () => putClient(client),
1753
+ }, { unsent });
1754
+ }
1755
+ /** A title-block change: an answer to a question, a field's read way, label or requiredness, removing a field,
1756
+ * or adding one (from the Add field dialog, which keeps it if it is held). */
1757
+ function putTitleBlock(change, { dialog = false, unsent = false } = {}) {
1758
+ S.checklistError = ''; S.titleNote = ''; S.titleNoteField = '';
1759
+ const tb = (d) => d.titleBlock || {};
1760
+ let key, family, what, apply = () => true;
1761
+ if (change.answer) {
1762
+ const { ask, choice, label } = change.answer;
1763
+ const a = (tb(S.draft || {}).asks || []).find((x) => x.id === ask);
1764
+ const said = label !== undefined ? `“${label}”` : (a && a.choices.find((x) => x.id === choice)?.label) || choice;
1765
+ key = family = `ask:${ask}`;
1766
+ what = `Answered “${a ? a.question : ask}”: ${said}`;
1767
+ apply = (d) => (tb(d).asks || []).some((x) => x.id === ask && (label !== undefined || x.choices.some((y) => y.id === choice)));
1768
+ } else if (change.add) {
1769
+ key = family = `field-add:${change.add.label}`;
1770
+ what = `Added the field “${change.add.label}”`;
1771
+ } else if (change.remove) {
1772
+ family = `field:${change.remove}`; key = `${family}:remove`;
1773
+ what = `Removed the field “${fieldLabel(change.remove)}”`;
1774
+ apply = (d) => !!findField(d, change.remove);
1775
+ } else {
1776
+ const name = change.field, L = fieldLabel(name);
1777
+ const prop = 'read' in change ? 'read' : 'label' in change ? 'label' : 'required';
1778
+ family = `field:${name}`; key = `${family}:${prop}`;
1779
+ what = prop === 'read' ? `Set “${L}” to read: ${(READ_WORDS[change.read] || change.read).toLowerCase()}`
1780
+ : prop === 'label' ? `Renamed “${L}” to “${change.label}”` : `Made “${L}” ${change.required ? 'required' : 'optional'}`;
1781
+ apply = (d) => { const f = findField(d, name); if (f) f[prop] = change[prop]; return !!f; };
1782
+ }
1783
+ return choose({
1784
+ key, family, removes: !!change.remove, what, apply, dialog,
1785
+ url: `${base}/title-block`, body: change,
1786
+ parts: (b) => ({ titleBlock: b.titleBlock, items: b.items }),
1787
+ answered: (b) => {
1788
+ if (b.note) { S.titleNote = b.note; S.titleNoteField = b.noteField || ''; }
1263
1789
  if (change.answer) delete S.typed[change.answer.ask];
1264
- await loadReview();
1265
- return body;
1266
- } catch (e) {
1267
- if (e.status === 412 || e.status === 428) S.conflict = true;
1790
+ },
1791
+ failed: (e) => {
1268
1792
  // A typed answer the server refused stays in its field, with the reason beside it.
1269
- else if (change.answer && change.answer.label !== undefined) S.typed[change.answer.ask] = { value: change.answer.label, error: e.message };
1270
- else S.checklistError = e.message;
1271
- await loadDraft().catch(() => {});
1272
- return null;
1273
- } finally { itemsInFlight--; S.tbSaving = false; render(); }
1274
- });
1793
+ if (change.answer && change.answer.label !== undefined) S.typed[change.answer.ask] = { value: change.answer.label, error: errorText(e, { action: 'save that answer' }) };
1794
+ else S.checklistError = errorText(e, { action: 'save the checklist' });
1795
+ },
1796
+ // A held typed answer is listed with the other changes; its field closes rather than keep text that was not saved.
1797
+ held: () => { if (change.answer) delete S.typed[change.answer.ask]; },
1798
+ settled: () => { S.tbSaving = false; },
1799
+ redo: () => putTitleBlock(change, { dialog }),
1800
+ }, { unsent });
1801
+ }
1802
+ // A dialog's add that was held: the dialog keeps what was typed and says why, while the latest version is read.
1803
+ const heldDialogs = new Set();
1804
+ function showHeldInDialog(scrim, btn, idleText, line) {
1805
+ const show = () => {
1806
+ if (!openDialog || openDialog.scrim !== scrim) { heldDialogs.delete(show); return; }
1807
+ const state = syncState();
1808
+ line.hidden = false;
1809
+ line.textContent = state === 'reading' ? 'Not added: the checklist changed while this was being added. Getting the latest version…'
1810
+ : state === 'failed' ? 'Not added: the checklist changed while this was being added, and the latest version couldn’t be read just now. Cancel, then reload the profile.'
1811
+ : 'Not added: the checklist changed while this was being added. The page behind this window now shows the latest. Add it again, or cancel to look first.';
1812
+ btn.hidden = state === 'failed';
1813
+ btn.disabled = state !== 'ok';
1814
+ btn.textContent = state === 'ok' ? idleText : 'Getting the latest version…';
1815
+ if (state === 'ok') heldDialogs.delete(show);
1816
+ };
1817
+ heldDialogs.add(show);
1818
+ show();
1275
1819
  }
1276
1820
  function addFieldDialog() {
1277
1821
  showDialog({
@@ -1292,8 +1836,9 @@ function boot() {
1292
1836
  const err = scrim.querySelector('#af-err');
1293
1837
  if (!label) { err.hidden = false; err.textContent = 'Write the label as it appears on the drawings.'; return; }
1294
1838
  e.target.disabled = true; e.target.textContent = 'Looking for it…';
1295
- const res = await putTitleBlock({ add: { label, required: scrim.querySelector('#af-required').checked } });
1839
+ const res = await putTitleBlock({ add: { label, required: scrim.querySelector('#af-required').checked } }, { dialog: true });
1296
1840
  if (!openDialog || openDialog.scrim !== scrim) return;
1841
+ if (res === 'held') { showHeldInDialog(scrim, scrim.querySelector('[data-dlg="add"]'), 'Add field', err); return; }
1297
1842
  if (!res) { e.target.disabled = false; e.target.textContent = 'Add field'; err.hidden = false; err.textContent = S.checklistError || 'The field could not be added. Try again.'; return; }
1298
1843
  closeDialog();
1299
1844
  });
@@ -1305,11 +1850,13 @@ function boot() {
1305
1850
  S.checklistError = ''; S.uploadNote = ''; S.clearNote = '';
1306
1851
  const btn = root.querySelector('[data-act="propose"]'); if (btn) { btn.disabled = true; btn.textContent = 'Reading the reference drawings…'; }
1307
1852
  try {
1853
+ // Unconditional: its answer may include another window's change, so it is a version the person has not seen,
1854
+ // and it carries only part of the draft: the whole draft is read after it (adopt).
1855
+ const sent = { ...sending(), cond: false };
1308
1856
  const { body } = await call(`${base}/propose`, { method: 'POST' });
1309
- S.draft.items = body.items; S.etag = body.etag; S.newSinceApproval = 0;
1310
- if (body.titleBlock) S.draft.titleBlock = body.titleBlock; else delete S.draft.titleBlock;
1311
- if (body.partList) S.draft.partList = body.partList; else delete S.draft.partList;
1312
- if (body.client) S.draft.client = body.client;
1857
+ S.newSinceApproval = 0; S.bareNote = '';
1858
+ // The lengths it learned afresh, or none: the Dimensions section never shows the previous references' setting.
1859
+ adoptAnswer(sent, { items: body.items, titleBlock: body.titleBlock ?? null, partList: body.partList ?? null, lengths: body.lengths ?? null, ...(body.client ? { client: body.client } : {}) }, body.etag);
1313
1860
  if (body.unreadable && body.unreadable.length) S.checklistError = `Couldn’t read ${body.unreadable.join(', ')}; the other drawings were used.`;
1314
1861
  await loadReview();
1315
1862
  } catch (e) { S.checklistError = e.message; }
@@ -1382,15 +1929,17 @@ function boot() {
1382
1929
  if (!label || !text) { err.hidden = false; err.textContent = 'Give the item a name and the text to look for.'; return; }
1383
1930
  e.target.disabled = true; e.target.textContent = 'Testing…';
1384
1931
  const before = new Set(items().map((i) => i.id));
1385
- const res = await putItems([{ label, text, display: label, enabled: true }]);
1932
+ const res = await putItems([{ label, text, display: label, enabled: true }], { dialog: true });
1386
1933
  if (!openDialog || openDialog.scrim !== scrim) return;
1934
+ if (res === 'held') { showHeldInDialog(scrim, scrim.querySelector('[data-dlg="test"]'), 'Add and test on reference drawings', err); return; }
1387
1935
  if (!res) { e.target.disabled = false; e.target.textContent = 'Add and test on reference drawings'; err.hidden = false; err.textContent = S.checklistError || 'The item could not be added. Try again.'; return; }
1388
1936
  const added = res.items.find((i) => !before.has(i.id));
1389
1937
  scrim.dataset.added = added ? added.id : '';
1390
- const f = added && typeof added.frequency === 'number' ? added.frequency : null;
1938
+ const t = added && added.tally && added.tally.sheets ? added.tally : null;
1939
+ const unread = t ? t.sheets - t.decided : 0;
1391
1940
  const out = scrim.querySelector('#ai-result'); out.hidden = false;
1392
- out.textContent = f === null ? 'Added. It could not be tested, because no reference drawing could be read.'
1393
- : `Found on ${Math.round(f * pages)} of ${pages} (${Math.round(f * 100)}%). Rare is fine if the client requires it.`;
1941
+ out.textContent = t === null ? 'Added. It could not be tested, because no reference drawing could be read.'
1942
+ : `Found on ${t.held} of ${t.sheets}${unread ? `, ${unread} could not be read` : ''} (${Math.round((t.held / t.sheets) * 100)}%). Rare is fine if the client requires it.`;
1394
1943
  scrim.querySelector('.foot').innerHTML = '<button type="button" data-dlg="remove">Remove it</button><button type="button" class="primary" data-dlg="done">Keep item</button>';
1395
1944
  scrim.querySelector('[data-dlg="done"]').focus();
1396
1945
  });
@@ -1483,7 +2032,7 @@ function boot() {
1483
2032
  const paths = [], names = [];
1484
2033
  for (const f of files) {
1485
2034
  const dataUrl = await new Promise((resolve, reject) => { const r = new FileReader(); r.onload = () => resolve(r.result); r.onerror = () => reject(new Error(`${f.name} could not be read.`)); r.readAsDataURL(f); });
1486
- const { body } = await call('/api/visual-input', jsonOpts('POST', { appId: APP, name: 'drawings', dataUrl }));
2035
+ const { body } = await call('/api/visual-input', { ...jsonOpts('POST', { appId: APP, name: 'drawings', dataUrl }), draftWrite: false });
1487
2036
  paths.push(body.path);
1488
2037
  names.push(f.name);
1489
2038
  }
@@ -1560,13 +2109,13 @@ function boot() {
1560
2109
  catch (e) { S.running = null; S.runError = e.message; render(); return; }
1561
2110
  let warnings = [];
1562
2111
  let version; // undefined: the latest approved version; a number: the earlier one the person chose
1563
- try { warnings = (await call(`${base}/preflight`, jsonOpts('POST', { drawings: paths, names }))).body.warnings || []; }
2112
+ try { warnings = (await call(`${base}/preflight`, { ...jsonOpts('POST', { drawings: paths, names }), draftWrite: false })).body.warnings || []; }
1564
2113
  catch (e) {
1565
2114
  S.running = null; render();
1566
2115
  version = await fallbackDialog(e);
1567
2116
  if (version === null) { S.runError = e.message; render(); return; }
1568
2117
  S.running = `Checking ${pdfs.length} drawing${pdfs.length === 1 ? '' : 's'} against version ${version}…`; render();
1569
- try { warnings = (await call(`${base}/preflight`, jsonOpts('POST', { drawings: paths, names, version }))).body.warnings || []; }
2118
+ try { warnings = (await call(`${base}/preflight`, { ...jsonOpts('POST', { drawings: paths, names, version }), draftWrite: false })).body.warnings || []; }
1570
2119
  catch (e2) { S.running = null; S.runError = e2.message; render(); return; }
1571
2120
  }
1572
2121
  let decisions = {};
@@ -1587,7 +2136,7 @@ function boot() {
1587
2136
  S.running = `Checking ${pdfs.length} drawing${pdfs.length === 1 ? '' : 's'}…`; render();
1588
2137
  }
1589
2138
  try {
1590
- const { body } = await call(`${base}/runs`, jsonOpts('POST', { drawings: paths, names, decisions, ...(version !== undefined ? { version } : {}) }));
2139
+ const { body } = await call(`${base}/runs`, { ...jsonOpts('POST', { drawings: paths, names, decisions, ...(version !== undefined ? { version } : {}) }), draftWrite: false });
1591
2140
  S.running = null;
1592
2141
  await loadRuns();
1593
2142
  await checkFinished(body.runId);
@@ -1786,7 +2335,7 @@ function boot() {
1786
2335
  // What the run showed is taken BEFORE the save: stillPending compares the refresh with it.
1787
2336
  const shownBefore = S.decisions.current[payload.findingId];
1788
2337
  try {
1789
- const { body } = await call(`${base}/runs/${encodeURIComponent(runId)}/decisions`, jsonOpts('POST', payload));
2338
+ const { body } = await call(`${base}/runs/${encodeURIComponent(runId)}/decisions`, { ...jsonOpts('POST', payload), draftWrite: false });
1790
2339
  // The finding is pending from here until a refresh shows this decision (stillPending), never merely because
1791
2340
  // the refresh worked: one whose decisions are unreadable, or that shows an earlier decision, confirms nothing.
1792
2341
  S.pendingByRun[runId] = [...(S.pendingByRun[runId] || []).filter((p) => p.findingId !== payload.findingId),
@@ -2155,7 +2704,7 @@ function boot() {
2155
2704
  return track(async () => {
2156
2705
  const btn = root.querySelector('[data-act="mark"]'); if (btn) btn.disabled = true;
2157
2706
  try {
2158
- const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/checked`, jsonOpts('POST', { drawing: s.drawing, page: s.page }));
2707
+ const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/checked`, { ...jsonOpts('POST', { drawing: s.drawing, page: s.page }), draftWrite: false });
2159
2708
  S.run.checkedBy = body.checkedBy || S.run.checkedBy;
2160
2709
  // The record may have come back unsigned or unverified: the badge must say so now, not after a reload.
2161
2710
  if (body.signature) S.run.signature = body.signature;
@@ -2171,7 +2720,7 @@ function boot() {
2171
2720
  const btn = root.querySelector('[data-act="export"]'); if (btn) { btn.disabled = true; btn.textContent = 'Exporting…'; }
2172
2721
  let failed = '';
2173
2722
  try {
2174
- const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/export`, jsonOpts('POST', { drawing: s.drawing }));
2723
+ const { body } = await call(`${base}/runs/${encodeURIComponent(S.run.runId)}/export`, { ...jsonOpts('POST', { drawing: s.drawing }), draftWrite: false });
2175
2724
  const fails = body.tagFailures || [];
2176
2725
  S.exportCard = `<div class="export-card" role="status"><b>${esc(body.filename)}</b> saved.
2177
2726
  ${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>` : ''}
@@ -2220,10 +2769,10 @@ function boot() {
2220
2769
  async function saveColours(next) {
2221
2770
  const err = document.getElementById('colour-err');
2222
2771
  try {
2223
- const { body } = await call(`${base}/colours`, jsonOpts('PUT', next));
2772
+ const { body } = await call(`${base}/colours`, { ...jsonOpts('PUT', next), draftWrite: false });
2224
2773
  S.colours = body.colours; S.colourWarning = body.warning; S.coloursUnread = false;
2225
2774
  render();
2226
- } catch (e) { if (err) { err.hidden = false; err.textContent = e.message; } }
2775
+ } catch (e) { if (err) { err.hidden = false; err.textContent = errorText(e, { action: 'save the markup colours', retrySafe: true }); } }
2227
2776
  }
2228
2777
 
2229
2778
  // ── events ──
@@ -2236,7 +2785,7 @@ function boot() {
2236
2785
  if (t.classList.contains('item')) { selectItem(Number(t.dataset.n)); return; }
2237
2786
  if (t.dataset.zoom) { ({ fit: () => view.fit(), in: () => view.zoom(0.8), out: () => view.zoom(1.25) })[t.dataset.zoom](); return; }
2238
2787
  if (t.dataset.file) {
2239
- try { await call(t.dataset.file === 'open' ? '/api/open-file' : '/api/reveal', jsonOpts('POST', { path: t.dataset.path })); }
2788
+ try { await call(t.dataset.file === 'open' ? '/api/open-file' : '/api/reveal', { ...jsonOpts('POST', { path: t.dataset.path }), draftWrite: false }); }
2240
2789
  catch { t.insertAdjacentHTML('afterend', '<span class="err-line"> That file could not be opened. It may have been moved.</span>'); }
2241
2790
  return;
2242
2791
  }
@@ -2267,22 +2816,35 @@ function boot() {
2267
2816
  if (t.dataset.tbRead) {
2268
2817
  const f = ((S.draft && S.draft.titleBlock && S.draft.titleBlock.fields) || []).find((x) => x.name === t.dataset.tbRead);
2269
2818
  const refocus = () => root.querySelector(`[data-tb-read="${CSS.escape(t.dataset.tbRead)}"][aria-checked="true"]`)?.focus();
2270
- if (f && f.read !== t.dataset.mode) { f.read = t.dataset.mode; render(); refocus(); await putTitleBlock({ field: f.name, read: t.dataset.mode }); }
2819
+ if (f && f.read !== t.dataset.mode) { const saving = putTitleBlock({ field: f.name, read: t.dataset.mode }); refocus(); await saving; }
2271
2820
  refocusIfLost(document, root, `[data-tb-read="${CSS.escape(t.dataset.tbRead)}"][aria-checked="true"]`);
2272
2821
  return;
2273
2822
  }
2274
2823
  if (t.dataset.mainRow) {
2275
2824
  const it = mainRowItem(items());
2276
2825
  const want = t.dataset.mainRow === 'yes', row = want ? 'mark-equals-assembly' : 'first-marked-row';
2277
- // As a read mode: the choice shows at once; the answer (or a reload after a refusal) settles it.
2826
+ // As a read mode: the choice shows at once; its answer settles it, or it is listed as not saved.
2278
2827
  if (it && it.rule.mainRow !== row) {
2279
- it.rule.mainRow = row; S.mainNote = ''; render();
2828
+ const saving = putMainPart(want);
2280
2829
  root.querySelector('[data-main-row][aria-checked="true"]')?.focus();
2281
- await putMainPart(want);
2830
+ await saving;
2282
2831
  }
2283
2832
  refocusIfLost(document, root, '[data-main-row][aria-checked="true"]');
2284
2833
  return;
2285
2834
  }
2835
+ if (t.dataset.bareInches) {
2836
+ const l = S.draft && S.draft.lengths, want = t.dataset.bareInches === 'yes';
2837
+ const mine = ((S.draft && S.draft.touched) || []).includes('lengths.bareInchValues');
2838
+ // As the main part: the choice shows at once; its answer settles it, or it is listed as not saved. Choosing the
2839
+ // answer already shown still records it as the person's, so proposing again keeps it.
2840
+ if (l && ((l.bareInchValues === true) !== want || !mine)) {
2841
+ const saving = putBareInches(want);
2842
+ root.querySelector('[data-bare-inches][aria-checked="true"]')?.focus();
2843
+ await saving;
2844
+ }
2845
+ refocusIfLost(document, root, '[data-bare-inches][aria-checked="true"]');
2846
+ return;
2847
+ }
2286
2848
  if (t.dataset.tbRemove) { await putTitleBlock({ remove: t.dataset.tbRemove }); return; }
2287
2849
  const act = t.dataset.act;
2288
2850
  if (act === 'add-field') { addFieldDialog(); return; }
@@ -2293,7 +2855,19 @@ function boot() {
2293
2855
  return;
2294
2856
  }
2295
2857
  // A refresh waits for this load (refreshNow awaits `loaded`), so a change announced while it runs is read after it.
2858
+ // Reload keeps the changes listed as not saved (#3121): they are the person's, offered until applied or dismissed.
2296
2859
  if (act === 'reload') { S.conflict = false; S.checklistError = ''; await (loaded = loadAll()); return; }
2860
+ if (act === 'unsaved-apply') {
2861
+ applyUnsaved();
2862
+ (root.querySelector('.unsaved-state') || root.querySelector('section[role=tabpanel] h2'))?.focus();
2863
+ return;
2864
+ }
2865
+ if (act === 'unsaved-dismiss') {
2866
+ S.unsaved = []; S.conflict = false; S.showAllUnsaved = false; render();
2867
+ root.querySelector('section[role=tabpanel] h2')?.focus();
2868
+ return;
2869
+ }
2870
+ if (act === 'unsaved-show-all') { S.showAllUnsaved = !S.showAllUnsaved; render(); root.querySelector('[data-act="unsaved-show-all"]')?.focus(); return; }
2297
2871
  if (act === 'pick-refs') { document.getElementById('ref-file')?.click(); return; }
2298
2872
  if (act === 'use-design-set') { designSetDialog(t); return; }
2299
2873
  if (act === 'pick-again') { designSetDialog(t, t.dataset.issue); return; }
@@ -2321,11 +2895,14 @@ function boot() {
2321
2895
  if (act === 'reset-colours') { await saveColours({ pass: DEFAULT_COLOURS.pass, fail: DEFAULT_COLOURS.fail, question: DEFAULT_COLOURS['dont-know'] }); }
2322
2896
  });
2323
2897
  root.addEventListener('input', (e) => {
2898
+ typedIn.add(e.target);
2324
2899
  const id = e.target.dataset && e.target.dataset.typedLabel;
2325
2900
  if (id) S.typed[id] = { value: e.target.value, error: '' };
2326
2901
  });
2327
2902
  root.addEventListener('change', async (e) => {
2328
2903
  const t = e.target;
2904
+ if (t === leavingField) return; // fired by the repaint taking it out of the page, not by the person
2905
+ typedIn.delete(t); // its text is sent (or put back) now: a repaint shows what was saved
2329
2906
  if (t.id === 'ref-file') { const files = [...t.files]; t.value = ''; if (files.length) await uploadReferences(files); return; }
2330
2907
  if (t.id === 'run-file') { const files = [...t.files]; t.value = ''; await checkDrawings(files); return; }
2331
2908
  if (t.id === 'client-name') {
@@ -2343,7 +2920,7 @@ function boot() {
2343
2920
  if ('why' in got) { S.breakError = got.why; S.breakTyped = t.value; S.breakNote = ''; render(); refocusIfLost(document, root, '#line-break-pt'); return; }
2344
2921
  S.breakError = ''; S.breakTyped = null;
2345
2922
  const was = typeof it.rule.lineBreakPt === 'number' ? it.rule.lineBreakPt : 0;
2346
- if (got.pt !== was) { it.rule.lineBreakPt = got.pt; render(); await putLineBreak(got.pt); }
2923
+ if (got.pt !== was) await putLineBreak(got.pt);
2347
2924
  else render();
2348
2925
  refocusIfLost(document, root, '#line-break-pt');
2349
2926
  return;
@@ -2371,8 +2948,6 @@ function boot() {
2371
2948
  // is painted now, so the footer's "N of M items ticked" counts it at once rather than when the save and the
2372
2949
  // review after it have answered (#2570). Focus stays on the box (paintKeepingFocus) and the list where it was
2373
2950
  // scrolled; an earlier tick's error is not announced again as if this one had failed.
2374
- const it = items().find((i) => i.id === t.dataset.item);
2375
- if (it) { it.enabled = t.checked; S.checklistError = ''; renderKeepingScroll(); }
2376
2951
  await putItems([{ id: t.dataset.item, enabled: t.checked }]);
2377
2952
  root.querySelector(`[data-item="${CSS.escape(t.dataset.item)}"]`)?.focus();
2378
2953
  return;
@@ -2387,7 +2962,7 @@ function boot() {
2387
2962
  // Tabs: arrow keys move between them (role=tablist); in a read-mode radiogroup they move the choice.
2388
2963
  root.addEventListener('keydown', (e) => {
2389
2964
  if (e.key === 'Enter' && e.target.dataset && e.target.dataset.typedLabel) {
2390
- e.preventDefault(); root.querySelector(`[data-typed-use="${CSS.escape(e.target.dataset.typedLabel)}"]`)?.click(); return;
2965
+ e.preventDefault(); typedIn.delete(e.target); root.querySelector(`[data-typed-use="${CSS.escape(e.target.dataset.typedLabel)}"]`)?.click(); return;
2391
2966
  }
2392
2967
  const radio = e.target.closest('.seg [role=radio]');
2393
2968
  if (radio && ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) {
@@ -2428,7 +3003,7 @@ function boot() {
2428
3003
  // AI Chat card, in another window. The page reads them again when the server says so (relayed by the workspace,
2429
3004
  // liveRefreshFor), when the person comes back to the Checker step, and when they open Reference drawings — the last
2430
3005
  // two also cover a missed event. Reads are coalesced and go out on the checklist queue, so they never interleave with a checklist PUT.
2431
- let want = {}, refreshTimer = null, loaded = null;
3006
+ let want = {}, refreshTimer = null, loaded = null, refreshWaitSince = 0;
2432
3007
  function refreshSoon(what) {
2433
3008
  if (what.designSet) want.designSet = true;
2434
3009
  if (what.draft) {
@@ -2439,32 +3014,41 @@ function boot() {
2439
3014
  if (!what.etag || (want.etag && want.etag !== what.etag)) want.anyDraft = true;
2440
3015
  else want.etag = what.etag;
2441
3016
  }
2442
- clearTimeout(refreshTimer);
2443
- refreshTimer = setTimeout(refreshNow, 200);
3017
+ // Coalesced into the timer already set, never restarted: events that keep coming cannot hold the read off (#3302).
3018
+ if (!refreshTimer) refreshTimer = setTimeout(refreshNow, 200);
2444
3019
  }
2445
3020
  function refreshNow() {
2446
- // Wait for this page's own writes: their answer brings the new etag, so their echo is not read as news.
2447
- if (ownWrites) { refreshTimer = setTimeout(refreshNow, 300); return; }
3021
+ refreshTimer = null;
3022
+ // Wait for this page's own writes: their answer brings the new etag, so their echo is not read as news. Not for
3023
+ // longer than OWN_WRITE_WAIT_MS from the first wait, however many writes follow (#3302): past it the refresh is
3024
+ // read, and a read a write of the page's own keeps stale ends in the "could not read the latest" line.
3025
+ if (ownWrites) {
3026
+ if (!refreshWaitSince) refreshWaitSince = Date.now();
3027
+ if (Date.now() - refreshWaitSince < OWN_WRITE_WAIT_MS) { refreshTimer = setTimeout(refreshNow, 300); return; }
3028
+ }
3029
+ refreshWaitSince = 0;
2448
3030
  const w = want; want = {};
2449
3031
  void itemsQueue(async () => {
2450
3032
  if (loaded) await loaded; // what was read before the page first painted is not a change
2451
3033
  if (S.loadError) return; // the page shows why it could not load, with Reload
2452
3034
  const draft = !!w.draft && (!!w.anyDraft || w.etag !== S.etag);
2453
3035
  if (!draft && !w.designSet) return;
2454
- const was = { refs: references(), designSet: S.designSetError ? null : S.designSet };
2455
- const seq = ownWriteSeq;
2456
- const before = JSON.stringify([S.draft, S.etag, S.designSet, S.designSetError, S.review]);
3036
+ const shown = () => JSON.stringify([S.draft, S.etag, S.designSet, S.designSetError, S.review, S.refsReadNote]);
3037
+ let drawn = shown();
2457
3038
  let failed = false;
3039
+ // The draft and the design set are read as one batch: what they bring is said once both have landed. A read
3040
+ // that crossed a write of this page's own adopted nothing (#3121) and is read again inside the batch, so the
3041
+ // batch never ends half-read (#3297).
3042
+ const batch = refsBatchOpen();
2458
3043
  await Promise.all([
2459
3044
  w.designSet ? loadDesignSet() : null,
2460
- draft ? loadDraft().then(loadReview).catch(() => { failed = true; }) : null,
3045
+ draft ? readDraftSettled().then((read) => { if (!read) failed = true; }, () => { failed = true; }) : null,
2461
3046
  ]);
2462
- if (before === JSON.stringify([S.draft, S.etag, S.designSet, S.designSetError, S.review]) && !failed) return;
2463
- const note = referencesChangeNote(was, { refs: references(), designSet: S.designSetError ? null : S.designSet });
2464
- if (failed) S.liveNote = 'This page could not read the latest reference drawings just now. Reload the profile to see them.';
2465
- // A write of this page's own that started while these reads were out may be what they found: it is shown, but
2466
- // not announced as a change made elsewhere (the page says what its own changes did).
2467
- else if (note && !ownWrites && ownWriteSeq === seq) S.liveNote = note;
3047
+ // Only a draft read settles this line: a design-set read alone says nothing about the reference list (PR #3308 review).
3048
+ if (draft) S.refsReadNote = failed ? 'This page could not read the latest reference drawings just now. Reload the profile to see them.' : '';
3049
+ if (batch.close()) drawn = shown(); // said, and drawn with it
3050
+ if (draft && !failed) await loadReview();
3051
+ if (drawn === shown()) return;
2468
3052
  // The run on screen does not show the references or the design set: it is left alone, and the next paint shows
2469
3053
  // what was read.
2470
3054
  if (S.tab === 'runs' && S.run) return;