@floless/app 0.160.0 → 0.162.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 (40) hide show
  1. package/aware-version-pin.mjs +43 -0
  2. package/dist/floless-server.cjs +126990 -120010
  3. package/dist/schemas/steel.model.v2.schema.json +23 -0
  4. package/dist/skills/floless-app-knowledge/SKILL.md +6 -5
  5. package/dist/skills/floless-app-rfi/SKILL.md +18 -5
  6. package/dist/skills/floless-app-steel-model/SKILL.md +28 -6
  7. package/dist/skills/floless-app-steel-takeoff/SKILL.md +579 -282
  8. package/dist/templates/floless-workspace-read.flo +9 -1
  9. package/dist/templates/steel-model.flo +6 -2
  10. package/dist/templates/viewer-3d-demo.flo +8 -2
  11. package/dist/web/app.css +198 -17
  12. package/dist/web/app.js +23 -0
  13. package/dist/web/aware.js +303 -54
  14. package/dist/web/chat-question-card.js +10 -3
  15. package/dist/web/chat.css +79 -5
  16. package/dist/web/chat.js +1513 -243
  17. package/dist/web/commands-drawing-check.js +1 -0
  18. package/dist/web/commands-filter.js +11 -0
  19. package/dist/web/commands-shell.js +467 -29
  20. package/dist/web/commands-steel.js +40 -38
  21. package/dist/web/drawing-check-editor.js +76 -3
  22. package/dist/web/index.html +46 -2
  23. package/dist/web/instructor.js +5 -3
  24. package/dist/web/leave-guard.js +12 -2
  25. package/dist/web/pages.js +43 -12
  26. package/dist/web/project-history.js +349 -0
  27. package/dist/web/project-reconciliation.js +1 -0
  28. package/dist/web/project-rfis.js +260 -21
  29. package/dist/web/startup-admission.js +53 -7
  30. package/dist/web/steel-3d-core.js +115 -6
  31. package/dist/web/steel-3d-view.js +61 -5
  32. package/dist/web/steel-editor.html +439 -118
  33. package/dist/web/steel-filter.html +139 -0
  34. package/dist/web/steel-model-v2-commands.js +3 -3
  35. package/dist/web/steel-model-v2-projection.js +132 -4
  36. package/dist/web/steel-plan-transform.js +78 -0
  37. package/dist/web/tool-updates.js +59 -3
  38. package/dist/web/workspaces.js +1553 -196
  39. package/launch.mjs +36 -5
  40. package/package.json +6 -4
package/dist/web/chat.js CHANGED
@@ -156,6 +156,9 @@
156
156
  const ATTACHMENT_KIND_LABELS = { 'application/pdf': 'PDF', 'application/x-step': 'IFC', 'application/dxf': 'DXF', 'text/plain': 'Data' };
157
157
  const MB = 1024 * 1024;
158
158
 
159
+ /** The project this conversation is about, when it is a project's chat (#2777: where a drawing place can be opened). */
160
+ const chatProjectId = () => (state.scope?.owner?.kind === 'project' && typeof state.scope.owner.projectId === 'string' ? state.scope.owner.projectId : null);
161
+
159
162
  function ownerQuery(owner = state.scope?.owner) {
160
163
  if (!owner) return '';
161
164
  const ownerId = owner.kind === 'project' ? owner.projectId : owner.kind === 'workflow' ? owner.workflowId : 'workspace';
@@ -647,6 +650,7 @@
647
650
  drawings: 'drawing-filter', model: 'project-model', exports: 'project-exports',
648
651
  history: 'project-history', knowledge: 'project-knowledge', pages: 'project-pages',
649
652
  workflows: 'project-workflows', // #2470 R6.2
653
+ rfis: 'project-rfis', // #2470 R6.6 (General's pane) and R6.6c (a steel project's RFI page, in the editor frame)
650
654
  }[selectedStep || ''] || 'project-list';
651
655
  const workspaceProjectOpen = document.getElementById('ws-project')?.hidden === false;
652
656
  const dashboardVisible = document.getElementById('dashboard')?.hidden === false;
@@ -693,6 +697,8 @@
693
697
  case 'project-knowledge': return shellText('ws-knowledge');
694
698
  case 'project-pages': return shellText('ws-pages');
695
699
  case 'project-workflows': return shellText('ws-workflows');
700
+ // A General project's RFIs are a shell pane; a steel project's are the editor's own RFI page in the model frame.
701
+ case 'project-rfis': return document.getElementById('ws-rfis')?.hidden === false ? shellText('ws-rfis') : readVisibleFrameText('ws-frame-model');
696
702
  case 'project-list': return shellText('ws-landing');
697
703
  case 'workflow-list': return shellText('wf-landing');
698
704
  case 'agent-list': case 'agent-page': return shellText('agents-surface');
@@ -708,7 +714,7 @@
708
714
  function floLessContextLabel(context = currentFloLessContext()) {
709
715
  const labels = {
710
716
  'drawing-filter': 'Drawing Filter', 'project-model': 'project model', 'project-exports': 'project exports',
711
- 'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-pages': 'project Pages', 'project-workflows': 'project Workflows', 'project-list': 'project list',
717
+ 'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-pages': 'project Pages', 'project-workflows': 'project Workflows', 'project-rfis': 'project RFIs', 'project-list': 'project list',
712
718
  'workflow-canvas': 'workflow canvas', dashboard: 'dashboard', report: 'report', '3d-report': '3D report',
713
719
  'model-editor': 'model editor', 'workflow-list': 'workflow list', 'agent-list': 'list of agents', 'agent-page': 'agent page',
714
720
  };
@@ -2060,9 +2066,78 @@
2060
2066
  const CITE_ANCHOR = /^[a-z0-9-]{1,16}$/;
2061
2067
  const INLINE_DIRECTIVE = /:(cite|assume)\[([^\]\n]{1,120})\]/g;
2062
2068
 
2069
+ /*
2070
+ * #2725: emphasis by CommonMark's delimiter rules, one line at a time, so a `*` or `_` inside a word stays what it is:
2071
+ * `BL15*120` keeps its star, `floless_scope_add` its underscores, and `**BL15*120**` is bold BL15*120. A run of `*` or
2072
+ * `_` opens only when it is left-flanking and closes only when right-flanking, and neither opens or closes inside a
2073
+ * word: CommonMark allows that for `*`, but it would turn `305*165*40` into 305<em>165</em>40. Runs on escaped HTML,
2074
+ * where an entity's `&` and `;` count as the punctuation they stand for.
2075
+ */
2063
2076
  function markdownEmphasis(html) {
2064
- return html.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>').replace(/__([^_\n]+)__/g, '<strong>$1</strong>')
2065
- .replace(/\*([^*\n]+)\*/g, '<em>$1</em>').replace(/_([^_\n]+)_/g, '<em>$1</em>');
2077
+ return html.split('\n').map(markdownEmphasisLine).join('\n');
2078
+ }
2079
+
2080
+ function markdownEmphasisLine(line) {
2081
+ const space = (character) => character === undefined || /\s/.test(character);
2082
+ // An inline slot's private-use markers stand for a citation or assumption, so they bound emphasis like punctuation.
2083
+ const punct = (character) => character !== undefined && /[\p{P}\p{S}\uE000\uE001]/u.test(character);
2084
+ const parts = [];
2085
+ let last = 0;
2086
+ for (const run of line.matchAll(/\*+|_+/g)) {
2087
+ parts.push(line.slice(last, run.index));
2088
+ // Neighbours are read whole, so an emoji beside `**Done**🎉` is the symbol it is, not half a surrogate pair.
2089
+ const pair = run.index > 1 && /[\uDC00-\uDFFF]/.test(line[run.index - 1]);
2090
+ const before = run.index > 0 ? line.slice(run.index - (pair ? 2 : 1), run.index) : undefined;
2091
+ const end = run.index + run[0].length;
2092
+ const after = end < line.length ? String.fromCodePoint(line.codePointAt(end)) : undefined;
2093
+ const left = !space(after) && (!punct(after) || space(before) || punct(before));
2094
+ const right = !space(before) && (!punct(before) || space(after) || punct(after));
2095
+ parts.push({
2096
+ mark: run[0][0], length: run[0].length, count: run[0].length, opens: [], closes: [],
2097
+ canOpen: left && (!right || punct(before)),
2098
+ canClose: right && (!left || punct(after)),
2099
+ });
2100
+ last = run.index + run[0].length;
2101
+ }
2102
+ if (parts.length === 0) return line;
2103
+ parts.push(line.slice(last));
2104
+ // The openers still waiting, oldest first; `floor` remembers, per kind of closer, the newest opener already found
2105
+ // useless for it, so each search starts above it and the whole line is processed in near-linear time.
2106
+ const openers = [];
2107
+ const floor = new Map();
2108
+ let sequence = 0;
2109
+ for (const closer of parts) {
2110
+ if (typeof closer === 'string') continue;
2111
+ closer.sequence = sequence += 1;
2112
+ if (closer.canClose) {
2113
+ const kind = `${closer.mark}${closer.canOpen ? 1 : 0}${closer.length % 3}`;
2114
+ while (closer.count > 0) {
2115
+ let at = openers.length - 1;
2116
+ for (; at >= 0 && openers[at].sequence > (floor.get(kind) ?? 0); at -= 1) {
2117
+ const opener = openers[at];
2118
+ const oddMatch = (opener.canClose || closer.canOpen) && (opener.length + closer.length) % 3 === 0
2119
+ && !(opener.length % 3 === 0 && closer.length % 3 === 0);
2120
+ if (opener.mark === closer.mark && !oddMatch) break;
2121
+ }
2122
+ if (at < 0 || openers[at].sequence <= (floor.get(kind) ?? 0)) {
2123
+ floor.set(kind, openers.length ? openers[openers.length - 1].sequence : 0);
2124
+ break;
2125
+ }
2126
+ const opener = openers[at];
2127
+ const tag = opener.count >= 2 && closer.count >= 2 ? 'strong' : 'em';
2128
+ const used = tag === 'strong' ? 2 : 1;
2129
+ opener.count -= used;
2130
+ closer.count -= used;
2131
+ opener.opens.push(`<${tag}>`);
2132
+ closer.closes.push(`</${tag}>`);
2133
+ // Delimiters between the pair can no longer open anything; an exhausted opener leaves too.
2134
+ openers.length = opener.count > 0 ? at + 1 : at;
2135
+ }
2136
+ }
2137
+ if (closer.canOpen && closer.count > 0) openers.push(closer);
2138
+ }
2139
+ return parts.map((part) => (typeof part === 'string' ? part
2140
+ : `${part.closes.join('')}${part.mark.repeat(part.count)}${part.opens.reverse().join('')}`)).join('');
2066
2141
  }
2067
2142
 
2068
2143
  /** Plain text with emphasis and (inside an answer) directive slots; the slot markers are characters no text can hold. */
@@ -2306,12 +2381,29 @@
2306
2381
 
2307
2382
  function citeText(x, max) { return typeof x === 'string' && x.length > 0 && x.length <= max && !/[\u0000-\u001F\u007F]/.test(x); }
2308
2383
 
2309
- /** A chosen source as the server stores it (`normalizeChosenSource`): a sheet with the picture digest kept at choosing, or a member. */
2384
+ /**
2385
+ * A chosen source as the server stores it (`normalizeChosenSource`): a sheet with the picture digest kept at choosing, a
2386
+ * member, #2692 a Knowledge page at a version with its content digest, or a file of this conversation (no project).
2387
+ */
2310
2388
  function chosenSourceOf(value) {
2311
2389
  if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some((key) => !['kind', 'label', 'ref'].includes(key))) return null;
2312
2390
  const r = value.ref;
2313
- if (!r || typeof r !== 'object' || Array.isArray(r) || !citeText(value.label, 160) || !citeText(r.projectId, 200) || !citeText(r.projectUuid, 200)) return null;
2314
2391
  const hex = /^[0-9a-f]{64}$/;
2392
+ if (!r || typeof r !== 'object' || Array.isArray(r) || !citeText(value.label, 160)) return null;
2393
+ if (value.kind === 'attachment') {
2394
+ if (Object.keys(r).some((key) => !['attachmentId', 'fileName', 'mediaType', 'bytes', 'digest'].includes(key))
2395
+ || typeof r.attachmentId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r.attachmentId)
2396
+ || !citeText(r.fileName, 255) || !citeText(r.mediaType, 120) || !Number.isSafeInteger(r.bytes) || r.bytes < 1
2397
+ || typeof r.digest !== 'string' || !hex.test(r.digest)) return null;
2398
+ return { kind: 'attachment', label: value.label, ref: r };
2399
+ }
2400
+ if (!citeText(r.projectId, 200) || !citeText(r.projectUuid, 200)) return null;
2401
+ if (value.kind === 'kb-page') {
2402
+ if (Object.keys(r).some((key) => !['projectId', 'projectUuid', 'generationId', 'slug', 'contentDigest'].includes(key))
2403
+ || typeof r.generationId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(r.generationId)
2404
+ || typeof r.slug !== 'string' || !/^[a-z0-9][a-z0-9._-]*$/.test(r.slug) || typeof r.contentDigest !== 'string' || !hex.test(r.contentDigest)) return null;
2405
+ return { kind: 'kb-page', label: value.label, ref: r };
2406
+ }
2315
2407
  if (value.kind === 'sheet') {
2316
2408
  if (Object.keys(r).some((key) => !['projectId', 'projectUuid', 'appId', 'pageId', 'sourceHash', 'sheet', 'pageNumber', 'representation', 'imageDigests'].includes(key))
2317
2409
  || !citeText(r.appId, 100) || !citeText(r.pageId, 200) || typeof r.sourceHash !== 'string' || !hex.test(r.sourceHash) || !citeText(r.sheet, 200)
@@ -2501,9 +2593,10 @@
2501
2593
  const ask = button('Ask for the source', 'shell.chat-cite-ask', 'ai-chat-source-action');
2502
2594
  ask.dataset.tip = 'Puts a question in the message box asking where this comes from. Nothing is sent until you press Send';
2503
2595
  ask.addEventListener('click', () => addToMessageBox(`${unsourcedClaim(turnId, row.anchor)}: which sheet, model member, attached file, project file or Knowledge page does it come from? Cite it, or say plainly that it is an assumption.`));
2504
- // #2643: the person names the source themself: a sheet or model member of a project in this conversation.
2596
+ // #2643: the person names the source themself: a sheet, model member or (#2692) Knowledge page of a project in this
2597
+ // conversation, or a file sent with one of its messages.
2505
2598
  const choose = button('Choose a source…', 'shell.chat-cite-choose', 'ai-chat-source-action');
2506
- choose.dataset.tip = 'Pick the sheet or model member this claim comes from. It is recorded as chosen by you, with the date; nothing checks the claim';
2599
+ choose.dataset.tip = 'Pick the sheet, model member, Knowledge page or attached file this claim comes from. It is recorded as chosen by you, with the date; nothing checks the claim';
2507
2600
  choose.setAttribute('aria-haspopup', 'dialog');
2508
2601
  choose.addEventListener('click', () => openSourcePicker(row, turnId, null));
2509
2602
  if (row.assumption) {
@@ -2529,13 +2622,14 @@
2529
2622
  chip.append(cited, why, sourceActions(ask, choose, assume));
2530
2623
  return chip;
2531
2624
  }
2532
- if (entry.kind === 'sheet') {
2625
+ if (entry.kind === 'sheet' && entry.ref?.representation === 'sheet') {
2533
2626
  const thumb = document.createElement('img'); thumb.alt = ''; thumb.loading = 'lazy';
2534
2627
  // A preview is only the picture the AI was shown (never a render): a tiles look or a changed picture has none.
2535
2628
  const preview = citationUrl(row, 'image', '&thumb=1');
2536
2629
  if (preview) {
2537
2630
  thumb.src = preview;
2538
- thumb.addEventListener('error', () => thumb.remove(), { once: true });
2631
+ // Keep the preview's space if the stored picture is gone: removing it shrinks this row after every repaint.
2632
+ thumb.addEventListener('error', () => { thumb.style.visibility = 'hidden'; }, { once: true });
2539
2633
  chip.append(thumb);
2540
2634
  }
2541
2635
  }
@@ -2582,7 +2676,8 @@
2582
2676
  const preview = citationUrl(view, 'image', '&thumb=1');
2583
2677
  if (preview) {
2584
2678
  thumb.src = preview;
2585
- thumb.addEventListener('error', () => thumb.remove(), { once: true });
2679
+ // A missing picture must not change the source row's height or wrapping while the answer streams.
2680
+ thumb.addEventListener('error', () => { thumb.style.visibility = 'hidden'; }, { once: true });
2586
2681
  chip.append(thumb);
2587
2682
  }
2588
2683
  }
@@ -2598,7 +2693,7 @@
2598
2693
  const change = button('Change…', 'shell.chat-cite-change', 'ai-chat-source-action quiet');
2599
2694
  change.setAttribute('aria-label', 'Change the source for this claim');
2600
2695
  change.setAttribute('aria-haspopup', 'dialog');
2601
- change.dataset.tip = 'Pick a different sheet or model member. The earlier choice stays in the record';
2696
+ change.dataset.tip = 'Pick a different source. The earlier choice stays in the record';
2602
2697
  change.addEventListener('click', () => openSourcePicker(row, turnId, row.choice.eventId));
2603
2698
  chip.append(open, marks, change);
2604
2699
  const earlier = row.choices.length > 1 ? row.choices[row.choices.length - 2] : null;
@@ -2652,38 +2747,50 @@
2652
2747
  chip.append(note);
2653
2748
  }
2654
2749
 
2750
+ /** #2692: what the picker can list, in order: the project's drawings and model, its Knowledge, and this conversation's files. */
2751
+ const SOURCE_KINDS = [
2752
+ { id: 'refs', label: 'Drawings & model', search: 'Search sheets and model members', list: 'Sheets and model members' },
2753
+ { id: 'kb', label: 'Knowledge', search: 'Search this project’s Knowledge', list: 'Knowledge pages' },
2754
+ { id: 'files', label: 'Attached files', search: 'Search attached files by name', list: 'Attached files' },
2755
+ ];
2756
+
2655
2757
  /**
2656
2758
  * #2643: "Choose a source…" — the @ list's sources (the project's sheets and model members, the same rows and the same
2657
- * read), in a small dialog under the claim's chip. Not the message box's @ list: nothing goes in the message. The pick is
2658
- * sent by identity with a request id made when it is picked (a retry sends the same one); the server resolves the source
2659
- * from the project's own records. Everything the save needs is taken now, from the chip as painted: a reply that lands
2660
- * after the person moved on (another conversation, the list closed) changes nothing on screen.
2759
+ * read) and, #2692, the project's published Knowledge pages and the files sent with this conversation's messages, in a
2760
+ * small dialog under the claim's chip. Not the message box's @ list: nothing goes in the message. The pick is sent by
2761
+ * identity with a request id made when it is picked (a retry sends the same one); the server resolves the source from
2762
+ * FloLess's own records. Everything the save needs is taken now, from the chip as painted: a reply that lands after the
2763
+ * person moved on (another conversation, the list closed) changes nothing on screen.
2661
2764
  */
2662
2765
  function openSourcePicker(row, turnId, replaces) {
2663
2766
  closeSourcePicker(false);
2664
2767
  if (!row.chatId) { announce('Open this conversation again to choose a source.'); return; }
2665
2768
  const command = replaces ? 'shell.chat-cite-change' : 'shell.chat-cite-choose';
2666
- const picker = { row, turnId, replaces, command, chatId: row.chatId, projects: null, projectId: null, query: '', refs: [], heldBack: 0,
2769
+ const picker = { row, turnId, replaces, command, chatId: row.chatId, projects: null, projectId: null, kind: null, query: '', items: [], more: [],
2667
2770
  status: 'loading', note: '', active: -1, seq: 0, timer: null, saving: null, problem: '', pending: null };
2668
2771
  state.sourcePicker = picker;
2669
2772
  const dialog = document.createElement('div'); dialog.className = 'ai-chat-source-picker';
2670
2773
  dialog.setAttribute('role', 'dialog'); dialog.setAttribute('aria-label', 'Choose a source');
2671
2774
  const head = Object.assign(document.createElement('p'), { className: 'ai-chat-source-picker-head', textContent: 'Choose the source for this claim' });
2775
+ const kinds = document.createElement('div'); kinds.className = 'ai-chat-source-picker-kinds'; kinds.hidden = true;
2776
+ kinds.setAttribute('role', 'group'); kinds.setAttribute('aria-label', 'What to choose from');
2672
2777
  const projects = document.createElement('div'); projects.className = 'ai-chat-source-picker-projects'; projects.hidden = true;
2778
+ projects.setAttribute('role', 'group'); projects.setAttribute('aria-label', 'Project');
2673
2779
  const input = document.createElement('input');
2674
- input.type = 'search'; input.className = 'ai-chat-source-picker-input'; input.placeholder = 'Search sheets and model members';
2780
+ input.type = 'search'; input.className = 'ai-chat-source-picker-input'; input.placeholder = SOURCE_KINDS[0].search;
2675
2781
  input.setAttribute('role', 'combobox'); input.setAttribute('aria-autocomplete', 'list'); input.setAttribute('aria-expanded', 'true');
2676
- input.setAttribute('aria-label', 'Search sheets and model members'); input.autocomplete = 'off'; input.spellcheck = false;
2782
+ input.setAttribute('aria-label', SOURCE_KINDS[0].search); input.autocomplete = 'off'; input.spellcheck = false;
2677
2783
  const list = document.createElement('div'); list.className = 'ai-chat-source-picker-list'; list.id = 'chat-source-picker-list';
2678
- list.setAttribute('role', 'listbox'); list.setAttribute('aria-label', 'Sheets and model members');
2784
+ list.setAttribute('role', 'listbox'); list.setAttribute('aria-label', SOURCE_KINDS[0].list);
2679
2785
  input.setAttribute('aria-controls', list.id);
2680
2786
  const foot = document.createElement('p'); foot.className = 'ai-chat-source-picker-foot'; foot.setAttribute('role', 'status');
2681
- const limit = Object.assign(document.createElement('p'), { className: 'ai-chat-source-picker-limit',
2682
- textContent: 'Sheets and model members only. For a Knowledge page or an attached file, use Ask for the source.' });
2683
- dialog.append(head, projects, input, list, foot, limit);
2684
- picker.dialog = dialog; picker.input = input; picker.list = list; picker.foot = foot; picker.projectRow = projects;
2787
+ // What choosing is, and is not: a record of the person's pick, never a check of the claim.
2788
+ const hint = Object.assign(document.createElement('p'), { className: 'ai-chat-source-picker-limit',
2789
+ textContent: 'Choosing records that you picked this source. It does not show the claim is correct.' });
2790
+ dialog.append(head, kinds, projects, input, list, foot, hint);
2791
+ picker.dialog = dialog; picker.input = input; picker.list = list; picker.foot = foot; picker.projectRow = projects; picker.kindRow = kinds;
2685
2792
  (ui.feed.closest('.ai-chat-shell') || document.body).append(dialog);
2686
- input.addEventListener('input', () => { picker.query = input.value; searchSources(picker); });
2793
+ input.addEventListener('input', () => { picker.query = input.value; searchSources(picker, picker.kind === 'files' ? 0 : 200); });
2687
2794
  input.addEventListener('keydown', (event) => sourcePickerKey(picker, event));
2688
2795
  dialog.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeSourcePicker(true); } });
2689
2796
  // A click elsewhere closes it and leaves the focus where the person clicked.
@@ -2730,6 +2837,45 @@
2730
2837
  box.style.top = `${Math.round(below + height <= window.innerHeight - 8 ? below : Math.max(8, at.top - height - 4))}px`;
2731
2838
  }
2732
2839
 
2840
+ /**
2841
+ * #2692: the files a person may choose — those sent with a message, never a draft not yet sent and never a picture given as
2842
+ * an answer to a question card (the server's `choosableAttachments`), newest first.
2843
+ */
2844
+ function choosableFiles() {
2845
+ return (state.chat?.attachments ?? []).filter((file) => file && file.turnId !== null && file.turnId !== undefined && file.purpose !== 'answer-evidence')
2846
+ .slice().sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
2847
+ }
2848
+
2849
+ function fileSizeLabel(bytes) {
2850
+ const n = Number(bytes) || 0;
2851
+ if (n < 1024) return `${n} bytes`;
2852
+ if (n < 1024 * 1024) return `${Math.max(1, Math.round(n / 1024))} KB`;
2853
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
2854
+ }
2855
+
2856
+ /**
2857
+ * #2692: one row of the list, whatever its kind: what is shown, and what is sent — the pick by identity, the project it is
2858
+ * in (none for a file) and the decision's key. Everything is taken from the answer that listed the row, never from the
2859
+ * picker's state at the moment of the click, so a Knowledge page carries the version it was listed from.
2860
+ */
2861
+ function sourceItemOf(kind, value, projectId, generationId) {
2862
+ if (kind === 'files') {
2863
+ const pick = { kind: 'attachment', attachmentId: value.attachmentId };
2864
+ const name = value.fileName;
2865
+ return { key: JSON.stringify(['file', String(value.attachmentId).toLowerCase()]), pick, projectId: null, label: name, name,
2866
+ meta: `${fileSizeLabel(value.bytes)} · sent ${assumedWhen({ assumedAt: value.createdAt })}`, tip: `${name} · attached to this conversation` };
2867
+ }
2868
+ if (kind === 'kb') {
2869
+ const pick = { kind: 'kb-page', slug: value.slug, generationId };
2870
+ const name = value.title || value.slug;
2871
+ return { key: JSON.stringify(['kb', projectId, generationId, value.slug]), pick, projectId, label: name, name, meta: value.slug,
2872
+ tip: `Knowledge page ${name} · ${value.slug}` };
2873
+ }
2874
+ const item = mentionOf(value);
2875
+ return { key: JSON.stringify(['ref', projectId, item.key]), pick: item.pick, projectId, label: item.label,
2876
+ name: `${value.kind === 'sheet' ? 'Sheet' : 'Member'} ${item.label}`, meta: refDetail(value), tip: item.tip };
2877
+ }
2878
+
2733
2879
  async function loadSourceProjects(picker) {
2734
2880
  let projects = null;
2735
2881
  try {
@@ -2739,52 +2885,126 @@
2739
2885
  if (state.sourcePicker !== picker || state.chat?.chatId !== picker.chatId) return;
2740
2886
  if (!projects) { picker.status = 'error'; picker.note = 'FloLess could not read which projects are in this conversation.'; paintSourcePicker(picker); return; }
2741
2887
  picker.projects = projects;
2742
- if (!projects.length) {
2888
+ picker.projectId = projects[0]?.projectId ?? null;
2889
+ // A conversation with a project starts on its drawings and model; one with only files, on its files.
2890
+ if (!projects.length && !choosableFiles().length) {
2743
2891
  picker.status = 'note';
2744
- picker.note = 'This conversation has no project, so there are no sheets or model members to choose from. Ask for the source instead.';
2892
+ picker.note = 'Nothing to choose from yet: this conversation has no project and no file sent with a message. Ask for the source instead.';
2745
2893
  paintSourcePicker(picker);
2746
2894
  return;
2747
2895
  }
2748
- picker.projectId = projects[0].projectId;
2896
+ setSourceKind(picker, projects.length ? 'refs' : 'files', false);
2897
+ }
2898
+
2899
+ /** Switches what the list shows. The search starts again, empty, and the focus stays where the person is. */
2900
+ function setSourceKind(picker, kind, keepFocus = true) {
2901
+ picker.kind = kind;
2902
+ picker.query = ''; picker.input.value = '';
2903
+ picker.items = []; picker.more = []; picker.active = -1; picker.problem = '';
2904
+ picker.status = 'loading';
2905
+ paintSourcePicker(picker);
2749
2906
  searchSources(picker, 0);
2907
+ if (!keepFocus) picker.input.focus({ preventScroll: true });
2750
2908
  }
2751
2909
 
2752
2910
  function searchSources(picker, delay = 150) {
2753
- if (!picker.projectId) return;
2754
2911
  clearTimeout(picker.timer);
2755
2912
  const seq = ++picker.seq;
2913
+ const kind = picker.kind;
2914
+ if (!kind) return;
2756
2915
  picker.stale = true;
2757
- picker.timer = setTimeout(async () => {
2758
- let body = null;
2759
- try { body = await request(`/api/projects/${encodeURIComponent(picker.projectId)}/refs?q=${encodeURIComponent(picker.query)}&kinds=sheet,member`); }
2760
- catch { body = null; }
2761
- // A newer search, a closed list or another conversation: this answer is for a question nobody is asking now.
2762
- if (state.sourcePicker !== picker || picker.seq !== seq || state.chat?.chatId !== picker.chatId) return;
2916
+ const settle = (fill) => {
2917
+ // A newer search, another kind or project, a closed list or another conversation: this answer is for a question
2918
+ // nobody is asking now.
2919
+ if (state.sourcePicker !== picker || picker.seq !== seq || picker.kind !== kind || state.chat?.chatId !== picker.chatId) return;
2763
2920
  picker.stale = false;
2764
- if (!body) { picker.status = 'error'; picker.note = 'FloLess could not list this project’s sheets and members just now.'; }
2765
- else if (body.status && body.status !== 'ok') { picker.status = 'note'; picker.note = String(body.note || ''); }
2766
- else {
2767
- picker.refs = Array.isArray(body.refs) ? body.refs : [];
2768
- picker.heldBack = Number(body.heldBack) || 0;
2769
- picker.status = picker.refs.length ? 'options' : 'empty';
2770
- }
2921
+ picker.items = []; picker.more = [];
2922
+ fill();
2923
+ if (picker.status === 'options' && !picker.items.length) picker.status = 'empty';
2771
2924
  picker.active = picker.status === 'options' ? 0 : -1;
2772
2925
  paintSourcePicker(picker);
2773
- announce(picker.status === 'options' ? `${picker.refs.length + picker.heldBack} ${picker.refs.length + picker.heldBack === 1 ? 'match' : 'matches'}`
2926
+ announce(picker.status === 'options' ? `${picker.items.length} ${picker.items.length === 1 ? 'match' : 'matches'}`
2774
2927
  : picker.status === 'empty' ? 'No matches' : picker.note);
2928
+ };
2929
+ if (kind === 'files') {
2930
+ const q = picker.query.trim().toLowerCase();
2931
+ settle(() => {
2932
+ const files = choosableFiles();
2933
+ if (!files.length) { picker.status = 'note'; picker.note = 'No file has been sent with a message in this conversation yet. A file appears here once it is sent.'; return; }
2934
+ picker.items = files.filter((file) => !q || String(file.fileName).toLowerCase().includes(q)).map((file) => sourceItemOf('files', file, null, null));
2935
+ picker.status = 'options';
2936
+ });
2937
+ return;
2938
+ }
2939
+ const projectId = picker.projectId;
2940
+ if (!projectId) {
2941
+ settle(() => { picker.status = 'note'; picker.note = kind === 'kb' ? 'This conversation has no project, so there is no Knowledge to choose from.'
2942
+ : 'This conversation has no project, so there are no sheets or model members to choose from.'; });
2943
+ return;
2944
+ }
2945
+ picker.timer = setTimeout(async () => {
2946
+ let body = null;
2947
+ const url = kind === 'kb'
2948
+ ? `/api/chat/conversations/${encodeURIComponent(picker.chatId)}/knowledge?${picker.row.owner}&projectId=${encodeURIComponent(projectId)}&q=${encodeURIComponent(picker.query)}&limit=20`
2949
+ : `/api/projects/${encodeURIComponent(projectId)}/refs?q=${encodeURIComponent(picker.query)}&kinds=sheet,member`;
2950
+ try { body = await request(url); } catch { body = null; }
2951
+ if (picker.projectId !== projectId) return;
2952
+ settle(() => {
2953
+ if (!body) {
2954
+ picker.status = 'error';
2955
+ picker.note = kind === 'kb' ? 'FloLess could not read this project’s Knowledge just now.' : 'FloLess could not list this project’s sheets and members just now.';
2956
+ } else if (kind === 'kb') {
2957
+ const generationId = body.generation?.generationId;
2958
+ if (!generationId) { picker.status = 'note'; picker.note = 'This project has no published Knowledge yet.'; return; }
2959
+ if (body.needsQuery) { picker.status = 'note'; picker.note = 'Type to search this project’s Knowledge.'; return; }
2960
+ picker.items = (Array.isArray(body.pages) ? body.pages : []).filter((page) => page && typeof page.slug === 'string')
2961
+ .map((page) => sourceItemOf('kb', page, projectId, generationId));
2962
+ // A search that could not look at every page, or found more than it lists, says so: "no match" is never claimed.
2963
+ if (body.incomplete) picker.more.push('FloLess could not look through every page just now, so some may be missing.');
2964
+ if (body.moreMatches) picker.more.push('More pages match. Type more of the name to narrow the list.');
2965
+ picker.status = 'options';
2966
+ if (!picker.items.length && picker.more.length) { picker.status = 'note'; picker.note = picker.more.shift(); }
2967
+ } else if (body.status && body.status !== 'ok') { picker.status = 'note'; picker.note = String(body.note || ''); }
2968
+ else {
2969
+ picker.items = (Array.isArray(body.refs) ? body.refs : []).map((ref) => sourceItemOf('refs', ref, projectId, null));
2970
+ const heldBack = Number(body.heldBack) || 0;
2971
+ if (heldBack) picker.more.push(`${heldBack} more match. Type more of the name to narrow the list.`);
2972
+ picker.status = 'options';
2973
+ }
2974
+ });
2775
2975
  }, delay);
2776
2976
  }
2777
2977
 
2778
2978
  function paintSourcePicker(picker) {
2779
- const { list, foot, input, projectRow } = picker;
2979
+ const { list, foot, input, projectRow, kindRow } = picker;
2980
+ const kind = SOURCE_KINDS.find((row) => row.id === picker.kind) ?? SOURCE_KINDS[0];
2981
+ // The two rows are rebuilt on every paint: a person on one of their buttons stays on it (by what it does).
2982
+ const focused = document.activeElement;
2983
+ const refocus = focused && (kindRow.contains(focused) || projectRow.contains(focused)) ? focused.dataset.commandId : null;
2984
+ kindRow.replaceChildren();
2985
+ kindRow.hidden = !picker.kind;
2986
+ for (const option of picker.kind ? SOURCE_KINDS : []) {
2987
+ const pick = button(option.label, `shell.chat-cite-choose-kind#${option.id}`, 'ai-chat-source-picker-project');
2988
+ pick.setAttribute('aria-pressed', String(option.id === picker.kind));
2989
+ pick.addEventListener('click', () => { if (picker.kind !== option.id && !picker.saving) setSourceKind(picker, option.id); });
2990
+ kindRow.append(pick);
2991
+ }
2780
2992
  projectRow.replaceChildren();
2781
- projectRow.hidden = !(picker.projects?.length > 1);
2782
- for (const project of picker.projects?.length > 1 ? picker.projects : []) {
2993
+ const listsProjects = picker.kind !== 'files' && picker.projects?.length > 1;
2994
+ projectRow.hidden = !listsProjects;
2995
+ for (const project of listsProjects ? picker.projects : []) {
2783
2996
  const pick = button(project.label || 'Project', `shell.chat-cite-choose-project#${project.projectId}`, 'ai-chat-source-picker-project');
2784
2997
  pick.setAttribute('aria-pressed', String(project.projectId === picker.projectId));
2785
- pick.addEventListener('click', () => { picker.projectId = project.projectId; picker.status = 'loading'; paintSourcePicker(picker); searchSources(picker, 0); input.focus(); });
2998
+ pick.addEventListener('click', () => {
2999
+ if (picker.saving) return;
3000
+ picker.projectId = project.projectId; picker.status = 'loading'; picker.items = []; picker.more = [];
3001
+ paintSourcePicker(picker); searchSources(picker, 0); input.focus();
3002
+ });
2786
3003
  projectRow.append(pick);
2787
3004
  }
3005
+ if (refocus) [...kindRow.children, ...projectRow.children].find((node) => node.dataset.commandId === refocus)?.focus({ preventScroll: true });
3006
+ input.placeholder = kind.search; input.setAttribute('aria-label', kind.search);
3007
+ list.setAttribute('aria-label', kind.list);
2788
3008
  list.replaceChildren();
2789
3009
  const status = (text) => {
2790
3010
  const line = Object.assign(document.createElement('div'), { className: 'ai-chat-mention-status', textContent: text });
@@ -2792,18 +3012,21 @@
2792
3012
  list.append(line);
2793
3013
  };
2794
3014
  let activeId = '';
2795
- if (picker.status === 'loading') status('Loading the project’s sheets and members…');
2796
- else if (picker.status === 'note') status(picker.note);
2797
- else if (picker.status === 'empty') status(picker.query ? `Nothing matches “${picker.query}”.` : 'This project has no sheets or model members yet.');
2798
- else if (picker.status === 'error') {
3015
+ if (picker.status === 'loading') {
3016
+ status(picker.kind === 'kb' ? 'Looking through this project’s Knowledge…' : picker.kind === 'files' ? 'Listing attached files…'
3017
+ : picker.kind ? 'Loading the project’s sheets and members…' : 'Loading what you can choose from…');
3018
+ } else if (picker.status === 'note') status(picker.note);
3019
+ else if (picker.status === 'empty') {
3020
+ status(picker.query ? `Nothing matches “${picker.query}”.` : picker.kind === 'kb' ? 'This project’s Knowledge has no pages.'
3021
+ : 'This project has no sheets or model members yet.');
3022
+ } else if (picker.status === 'error') {
2799
3023
  status(picker.note);
2800
3024
  const retry = button('Try again', 'shell.chat-cite-choose-retry', 'ai-chat-choice');
2801
3025
  retry.setAttribute('role', 'option');
2802
3026
  retry.addEventListener('click', () => { picker.status = 'loading'; paintSourcePicker(picker); if (picker.projects) searchSources(picker, 0); else loadSourceProjects(picker); });
2803
3027
  list.append(retry);
2804
3028
  } else {
2805
- picker.refs.forEach((ref, index) => {
2806
- const item = mentionOf(ref);
3029
+ picker.items.forEach((item, index) => {
2807
3030
  const option = button('', `shell.chat-cite-choose-pick#${item.key}`, 'ai-chat-choice ai-chat-mention-option');
2808
3031
  option.id = `chat-source-option-${index}`; option.tabIndex = -1;
2809
3032
  option.setAttribute('role', 'option'); option.setAttribute('aria-selected', String(index === picker.active));
@@ -2812,15 +3035,15 @@
2812
3035
  const busy = picker.saving?.key === item.key;
2813
3036
  if (picker.saving) option.setAttribute('aria-disabled', 'true');
2814
3037
  if (busy) option.setAttribute('aria-busy', 'true');
2815
- const name = Object.assign(document.createElement('span'), { className: 'ai-chat-mention-name', textContent: `${ref.kind === 'sheet' ? 'Sheet' : 'Member'} ${item.label}` });
2816
- const meta = Object.assign(document.createElement('small'), { className: 'ai-chat-skill-origin', textContent: refDetail(ref) });
3038
+ const name = Object.assign(document.createElement('span'), { className: 'ai-chat-mention-name', textContent: item.name });
3039
+ const meta = Object.assign(document.createElement('small'), { className: 'ai-chat-skill-origin', textContent: item.meta });
2817
3040
  option.append(name, meta);
2818
3041
  option.addEventListener('pointerdown', (event) => event.preventDefault()); // the search box keeps focus
2819
- option.addEventListener('click', () => chooseSource(picker, ref));
3042
+ option.addEventListener('click', () => chooseSource(picker, item));
2820
3043
  list.append(option);
2821
3044
  if (index === picker.active) activeId = option.id;
2822
3045
  });
2823
- if (picker.heldBack) status(`${picker.heldBack} more match. Type more of the name to narrow the list.`);
3046
+ for (const line of picker.more) status(line);
2824
3047
  }
2825
3048
  if (activeId) { input.setAttribute('aria-activedescendant', activeId); document.getElementById(activeId)?.scrollIntoView?.({ block: 'nearest' }); }
2826
3049
  else input.removeAttribute('aria-activedescendant');
@@ -2831,25 +3054,23 @@
2831
3054
 
2832
3055
  function sourcePickerKey(picker, event) {
2833
3056
  if (event.isComposing) return;
2834
- const count = picker.status === 'options' ? picker.refs.length : 0;
3057
+ const count = picker.status === 'options' ? picker.items.length : 0;
2835
3058
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
2836
3059
  event.preventDefault();
2837
3060
  if (count) { picker.active = (picker.active + (event.key === 'ArrowDown' ? 1 : -1) + count) % count; paintSourcePicker(picker); }
2838
3061
  } else if (event.key === 'Enter') {
2839
3062
  event.preventDefault();
2840
- if (count && picker.refs[picker.active]) chooseSource(picker, picker.refs[picker.active]);
3063
+ if (count && picker.items[picker.active]) chooseSource(picker, picker.items[picker.active]);
2841
3064
  }
2842
3065
  }
2843
3066
 
2844
3067
  /** Records the pick. A failure keeps the list open with the server's sentence; the claim stays as it was. */
2845
- async function chooseSource(picker, ref) {
3068
+ async function chooseSource(picker, item) {
2846
3069
  if (picker.saving) return;
2847
3070
  if (picker.stale) { announce('Still looking. Pick again when the list updates.'); return; }
2848
- const item = mentionOf(ref);
2849
3071
  // The same pick again after a failure is the same decision, so it keeps its request id; another pick is a new one.
2850
- // The same sheet identity can be in two projects, so the project is part of what was picked.
2851
- const decision = JSON.stringify([picker.projectId, item.key]);
2852
- if (picker.pending?.key !== decision) picker.pending = { key: decision, requestId: crypto.randomUUID() };
3072
+ // The key holds the project (the same sheet identity can be in two projects) and, for a page, the version.
3073
+ if (picker.pending?.key !== item.key) picker.pending = { key: item.key, requestId: crypto.randomUUID() };
2853
3074
  picker.saving = { key: item.key }; picker.problem = '';
2854
3075
  paintSourcePicker(picker);
2855
3076
  const { row, turnId } = picker;
@@ -2857,7 +3078,7 @@
2857
3078
  try {
2858
3079
  const result = await request(`/api/chat/conversations/${encodeURIComponent(row.chatId)}/citations/${encodeURIComponent(row.citationId)}/choose`, {
2859
3080
  method: 'POST', body: JSON.stringify({ owner: row.ownerObject, turnId, anchor: row.anchor, claim: unsourcedClaimWords(turnId, row.anchor) || null,
2860
- projectId: picker.projectId, pick: item.pick, requestId: picker.pending.requestId, replaces: picker.replaces }),
3081
+ projectId: item.projectId, pick: item.pick, requestId: picker.pending.requestId, replaces: picker.replaces }),
2861
3082
  });
2862
3083
  saved = result?.event ?? null;
2863
3084
  } catch (error) {
@@ -2880,6 +3101,63 @@
2880
3101
  picker.input.focus({ preventScroll: true });
2881
3102
  }
2882
3103
 
3104
+ /*
3105
+ * #2777 slices B and C: the places the AI asked FloLess to show (`floless_place`), as one strip under its answer, above
3106
+ * the question it asks about them. FloLess resolved every place itself; the event carries each place with the digest
3107
+ * its picture link must name, so a chip can only open what FloLess found. An entry it could not place says why.
3108
+ */
3109
+ /** Whether a label names this sheet as a whole token: "S1" is not named by a label about "S10". */
3110
+ const namesSheet = (label, sheet) => new RegExp(`(?<![A-Za-z0-9])${sheet.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![A-Za-z0-9])`).test(label);
3111
+ const placeBox = (v) => Array.isArray(v) && v.length === 4 && v.every((n) => typeof n === 'number' && Number.isFinite(n));
3112
+ function placeOfEntry(entry) {
3113
+ const place = entry && typeof entry === 'object' ? entry.place : null;
3114
+ if (!place || typeof place !== 'object' || (place.kind !== 'region' && place.kind !== 'sheet')) return null;
3115
+ if (typeof place.sheet !== 'string' || !place.sheet || !Number.isInteger(place.page) || typeof place.pageId !== 'string'
3116
+ || !/^[0-9a-f]{64}$/.test(String(place.sourceHash || '')) || !placeBox(place.pageBounds)) return null;
3117
+ if (place.kind === 'region' && !placeBox(place.region)) return null;
3118
+ return typeof entry.digest === 'string' && /^[0-9a-f]{64}$/.test(entry.digest) ? place : null;
3119
+ }
3120
+ function renderPlaceStrip(event) {
3121
+ const entries = Array.isArray(event.payload?.entries) ? event.payload.entries.slice(0, 8) : [];
3122
+ if (!entries.length || !state.chat?.chatId) return null;
3123
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-sources ai-chat-place-strip';
3124
+ const head = document.createElement('span'); head.className = 'ai-chat-sources-head'; head.textContent = 'Where this is on the drawings';
3125
+ head.dataset.tip = 'FloLess found each place on this read’s drawings. It shows where to look, not that what the AI says about it is right.';
3126
+ const list = document.createElement('div'); list.className = 'ai-chat-sources-list';
3127
+ const notes = [];
3128
+ entries.forEach((entry, ix) => {
3129
+ const label = typeof entry?.label === 'string' && entry.label.trim() ? entry.label.trim().slice(0, 120) : `Place ${ix + 1}`;
3130
+ const place = placeOfEntry(entry);
3131
+ if (!place) {
3132
+ notes.push(`${label}: ${typeof entry?.unplaced === 'string' && entry.unplaced ? entry.unplaced : 'FloLess could not show this place.'}`);
3133
+ return;
3134
+ }
3135
+ const marked = place.kind === 'region';
3136
+ const chip = button('', `shell.chat-place-open#${event.eventId} ${ix}`, 'ai-chat-source-chip ai-chat-place-chip');
3137
+ chip.dataset.commandInstanceLabel = `${label} on ${place.sheet}`;
3138
+ chip.setAttribute('aria-label', `Open sheet ${place.sheet}: ${label}`);
3139
+ chip.dataset.tip = marked ? `Opens sheet ${place.sheet} with this place outlined` : `Opens sheet ${place.sheet}; no area is marked`;
3140
+ chip.append(Object.assign(document.createElement('span'), { className: 'ai-chat-place-chip-label', textContent: label }),
3141
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-sheet', textContent: place.sheet }));
3142
+ const url = `/api/chat/places/${encodeURIComponent(state.chat.chatId)}/${encodeURIComponent(event.eventId)}/${ix}?${new URLSearchParams({ digest: entry.digest })}&${ownerQuery()}`;
3143
+ // A label that already names the sheet is not told it again ("Column line on S-301 on S-301").
3144
+ const titled = namesSheet(label, place.sheet) ? label : `${label} on ${place.sheet}`;
3145
+ chip.addEventListener('click', () => openDrawingPlace(place, {
3146
+ title: titled, opener: chip, url,
3147
+ note: marked ? `FloLess outlined, on page ${place.page} of ${place.sheet}, the place the AI named. It shows where to look, not that what the AI says about it is right.`
3148
+ : `The read marked this sheet but not a spot on it, so no area is outlined. Look over the whole sheet.`,
3149
+ commands: { close: 'shell.chat-place-close', view: 'shell.chat-place-view' },
3150
+ again: { label: 'Ask the AI to show it again', commandId: 'shell.chat-place-again', tip: 'Puts the request in the message box. Nothing is sent until you press Send',
3151
+ run: () => { addToMessageBox(`Show me again where "${label}" is on the drawings.`); ui.input.focus?.(); } },
3152
+ ...(chatProjectId() ? { filter: { projectId: chatProjectId(), commandId: 'shell.chat-place-open-filter' } } : {}),
3153
+ }));
3154
+ list.append(chip);
3155
+ });
3156
+ wrap.append(head, list);
3157
+ for (const text of notes) wrap.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-height-unplaced', textContent: `Not placed on the drawings: ${text}` }));
3158
+ return wrap;
3159
+ }
3160
+
2883
3161
  /** The Sources row of one answer, shown once, under the answer, after its last citation. */
2884
3162
  function renderCitationSources(event) {
2885
3163
  const last = state.events.filter((candidate) => candidate.type === 'citation' && candidate.turnId === event.turnId).at(-1);
@@ -2978,6 +3256,145 @@
2978
3256
  return chip?.querySelector('.ai-chat-source-open') ?? null;
2979
3257
  }
2980
3258
 
3259
+ /** One drawing viewport for cited sheets, attached images and outlined drawing places. No source lookup lives here. */
3260
+ function drawingViewport(place, viewCommand = 'shell.chat-drawing-fit') {
3261
+ const commands = { view: viewCommand };
3262
+ const views = document.createElement('div'); views.className = 'ai-chat-evidence-views'; views.setAttribute('role', 'group'); views.setAttribute('aria-label', 'How much of the sheet to show');
3263
+ const area = button('This area', commands.view, 'ai-chat-evidence-view');
3264
+ const whole = button('Whole sheet', commands.view, 'ai-chat-evidence-view');
3265
+ area.dataset.commandInstanceLabel = 'this area'; whole.dataset.commandInstanceLabel = 'the whole sheet';
3266
+ const marked = Array.isArray(place.region);
3267
+ views.append(...(marked ? [area, whole] : [whole]));
3268
+ // Not one of the views: it leaves this viewer for another screen, so it sits beside the group, never in it.
3269
+ const bar = document.createElement('div'); bar.className = 'ai-chat-evidence-bar';
3270
+ bar.append(views);
3271
+ let crop = evidenceCrop(place);
3272
+ const frame = document.createElement('div'); frame.className = 'ai-chat-evidence-frame';
3273
+ /*
3274
+ * What the frame shows, in page units, always shaped like the frame so the drawing is never stretched. "This area" and
3275
+ * "Whole sheet" set it; zoom (the buttons, the wheel, a double-click, + and -) and pan (a drag, the arrow keys) move
3276
+ * it. It may zoom out until the whole sheet fits and in to a fiftieth of the sheet's width, and never pans the page
3277
+ * out of the frame.
3278
+ */
3279
+ let view = null;
3280
+ const paintView = () => {
3281
+ const image = frame.querySelector('img');
3282
+ if (image && view) Object.assign(image.style, { width: `${(crop.pageW / view.w) * 100}%`, left: `${(-(view.x0 - crop.px0) / view.w) * 100}%`, top: `${(-(view.y0 - crop.py0) / view.h) * 100}%` });
3283
+ if (!view) return;
3284
+ const ratio = view.h / view.w;
3285
+ zoomIn.disabled = view.w <= crop.pageW / 50 + 1e-9;
3286
+ zoomOut.disabled = view.w >= Math.max(crop.pageW, crop.pageH / ratio) - 1e-9;
3287
+ };
3288
+ const clampView = (v) => {
3289
+ const ratio = v.h / v.w;
3290
+ const w = Math.min(Math.max(v.w, crop.pageW / 50), Math.max(crop.pageW, crop.pageH / ratio));
3291
+ const h = w * ratio;
3292
+ // Smaller than the page on an axis: kept on the page. Larger: the page centred, so nothing drifts off.
3293
+ const fit = (lo, size, min, extent) => (size >= extent ? min + (extent - size) / 2 : Math.min(Math.max(lo, min), min + extent - size));
3294
+ return { x0: fit(v.x0, w, crop.px0, crop.pageW), y0: fit(v.y0, h, crop.py0, crop.pageH), w, h };
3295
+ };
3296
+ const moved = () => { area.setAttribute('aria-pressed', 'false'); whole.setAttribute('aria-pressed', 'false'); frame.dataset.view = 'zoomed'; };
3297
+ /** Zoom by `factor` (above 1 is in) about a point of the frame, given as fractions of its width and height. */
3298
+ const zoomAt = (factor, fx = 0.5, fy = 0.5) => {
3299
+ if (!view) return;
3300
+ const px = view.x0 + fx * view.w, py = view.y0 + fy * view.h;
3301
+ const next = clampView({ x0: 0, y0: 0, w: view.w / factor, h: view.h / factor });
3302
+ view = clampView({ x0: px - fx * next.w, y0: py - fy * next.h, w: next.w, h: next.h });
3303
+ moved(); paintView();
3304
+ };
3305
+ const panBy = (dx, dy) => { if (!view) return; view = clampView({ ...view, x0: view.x0 + dx, y0: view.y0 + dy }); moved(); paintView(); };
3306
+ // The view "0" goes back to: the last one chosen with This area or Whole sheet.
3307
+ let shownAll = !marked;
3308
+ const show = (all) => {
3309
+ shownAll = all;
3310
+ area.setAttribute('aria-pressed', String(!all)); whole.setAttribute('aria-pressed', String(all));
3311
+ frame.dataset.view = all ? 'sheet' : 'area';
3312
+ const c = all ? { x0: crop.px0, y0: crop.py0, w: crop.pageW, h: crop.pageH } : crop;
3313
+ // Shaped like the crop and never taller than most of the window: narrowed, not squashed, so the picture stays true.
3314
+ frame.style.aspectRatio = `${c.w} / ${c.h}`;
3315
+ frame.style.width = `min(100%, calc(62vh * ${c.w / c.h}))`;
3316
+ view = { x0: c.x0, y0: c.y0, w: c.w, h: c.h };
3317
+ paintView();
3318
+ };
3319
+ const zoom = document.createElement('div'); zoom.className = 'ai-chat-evidence-zoom'; zoom.setAttribute('role', 'group'); zoom.setAttribute('aria-label', 'Zoom the drawing');
3320
+ const zoomOut = button('−', 'shell.chat-drawing-zoom-out', 'ai-chat-evidence-zoom-out');
3321
+ const zoomIn = button('+', 'shell.chat-drawing-zoom-in', 'ai-chat-evidence-zoom-in');
3322
+ zoomOut.setAttribute('aria-label', 'Zoom out'); zoomOut.dataset.tip = 'Zoom out (or scroll down on the drawing, or press -)';
3323
+ zoomIn.setAttribute('aria-label', 'Zoom in'); zoomIn.dataset.tip = 'Zoom in (or scroll up on the drawing, or press +)';
3324
+ zoomOut.addEventListener('click', () => zoomAt(1 / 1.5));
3325
+ zoomIn.addEventListener('click', () => zoomAt(1.5));
3326
+ zoom.append(zoomOut, zoomIn);
3327
+ bar.insertBefore(zoom, views.nextSibling);
3328
+ // The drawing itself: scroll to zoom where the pointer is, drag to move it, double-click to zoom in there.
3329
+ frame.tabIndex = 0;
3330
+ frame.setAttribute('role', 'group');
3331
+ frame.setAttribute('aria-label', 'Drawing. Drag or use the arrow keys to move it; scroll, or press + and -, to zoom; 0 goes back.');
3332
+ frame.dataset.commandId = 'shell.chat-drawing-pan';
3333
+ const fraction = (event) => { const r = frame.getBoundingClientRect(); return [Math.min(1, Math.max(0, (event.clientX - r.left) / r.width)), Math.min(1, Math.max(0, (event.clientY - r.top) / r.height))]; };
3334
+ frame.addEventListener('wheel', (event) => {
3335
+ // Wheel and touchpad zoom belong to this drawing, including at its zoom limits.
3336
+ if (!view || !event.deltaY) return;
3337
+ const zoomingIn = event.deltaY < 0;
3338
+ event.preventDefault();
3339
+ if (zoomingIn ? zoomIn.disabled : zoomOut.disabled) return;
3340
+ zoomAt(zoomingIn ? 1.2 : 1 / 1.2, ...fraction(event));
3341
+ }, { passive: false });
3342
+ frame.addEventListener('dblclick', (event) => { event.preventDefault(); zoomAt(1.5, ...fraction(event)); });
3343
+ let drag = null;
3344
+ frame.addEventListener('pointerdown', (event) => {
3345
+ if (!view || event.button !== 0) return;
3346
+ event.preventDefault();
3347
+ // preventDefault (no text selection, no image drag) also stops the click focusing the drawing, so it is focused here:
3348
+ // after a click the arrow keys, + / - and 0 act on it.
3349
+ frame.focus({ preventScroll: true });
3350
+ frame.setPointerCapture?.(event.pointerId);
3351
+ drag = { id: event.pointerId, x: event.clientX, y: event.clientY, from: { ...view } };
3352
+ frame.classList.add('dragging');
3353
+ });
3354
+ frame.addEventListener('pointermove', (event) => {
3355
+ if (!drag || event.pointerId !== drag.id) return;
3356
+ const r = frame.getBoundingClientRect();
3357
+ view = clampView({ ...drag.from, x0: drag.from.x0 - ((event.clientX - drag.x) / r.width) * drag.from.w, y0: drag.from.y0 - ((event.clientY - drag.y) / r.height) * drag.from.h });
3358
+ moved(); paintView();
3359
+ });
3360
+ const endDrag = (event) => { if (!drag || event.pointerId !== drag.id) return; drag = null; frame.classList.remove('dragging'); };
3361
+ frame.addEventListener('pointerup', endDrag);
3362
+ frame.addEventListener('pointercancel', endDrag);
3363
+ frame.addEventListener('keydown', (event) => {
3364
+ if (!view || event.ctrlKey || event.metaKey || event.altKey) return;
3365
+ const step = 0.1;
3366
+ const keys = { ArrowLeft: () => panBy(-view.w * step, 0), ArrowRight: () => panBy(view.w * step, 0), ArrowUp: () => panBy(0, -view.h * step), ArrowDown: () => panBy(0, view.h * step),
3367
+ '+': () => zoomAt(1.5), '=': () => zoomAt(1.5), '-': () => zoomAt(1 / 1.5), '0': () => show(shownAll) };
3368
+ // The numpad's keys, and a layout whose + needs Shift, still zoom.
3369
+ const byCode = { NumpadAdd: '+', NumpadSubtract: '-', Equal: '+', Minus: '-' };
3370
+ const run = keys[event.key] || keys[byCode[event.code]];
3371
+ if (!run) return;
3372
+ event.preventDefault();
3373
+ run();
3374
+ });
3375
+ area.addEventListener('click', () => show(false));
3376
+ whole.addEventListener('click', () => show(true));
3377
+ show(!marked);
3378
+ frame.setAttribute('aria-busy', 'true');
3379
+ const setImage = async (image, current = () => true, useImageSize = false) => {
3380
+ // Blob receipt is not a visible drawing: finish loading only once the browser can decode its pixels.
3381
+ if (typeof image.decode === 'function') await image.decode();
3382
+ if (!current()) return false;
3383
+ if (useImageSize && image.naturalWidth > 0 && image.naturalHeight > 0) {
3384
+ place = { pageBounds: [0, 0, image.naturalWidth, image.naturalHeight] };
3385
+ crop = evidenceCrop(place);
3386
+ }
3387
+ image.draggable = false;
3388
+ frame.replaceChildren(image);
3389
+ frame.removeAttribute('aria-busy');
3390
+ show(!marked);
3391
+ return true;
3392
+ };
3393
+ return { bar, frame, setImage };
3394
+ }
3395
+
3396
+ const CHOSEN_NOT_AS_ATTACHED = 'This file is no longer the plain file that was attached: it was changed, or something else now stands in its place. FloLess does not open it as the file you chose. Attach the file again if you still need it.';
3397
+
2981
3398
  async function openCitedSource(row, turnId) {
2982
3399
  const entry = row.entry;
2983
3400
  const dialog = document.createElement('dialog'); dialog.className = 'ai-chat-source-viewer';
@@ -2989,9 +3406,14 @@
2989
3406
  // viewer is removed, its picture released and focus handed back to the chip, once, whichever way it closes.
2990
3407
  let picture = null;
2991
3408
  let finished = false;
3409
+ const controller = new AbortController();
3410
+ let loadingTimer = null;
3411
+ let viewport = null;
2992
3412
  const finish = () => {
2993
3413
  if (finished) return;
2994
3414
  finished = true;
3415
+ controller.abort();
3416
+ clearTimeout(loadingTimer);
2995
3417
  if (dialog.open) dialog.close();
2996
3418
  hide();
2997
3419
  if (picture) URL.revokeObjectURL(picture);
@@ -3008,12 +3430,38 @@
3008
3430
  dialog.append(head, note, body);
3009
3431
  const hide = showChatViewer(dialog, finish);
3010
3432
  close.focus({ preventScroll: true });
3433
+ const drawing = entry.kind === 'sheet' || (entry.kind === 'attachment' && entry.ref?.mediaType?.startsWith('image/'));
3434
+ const mountDrawing = () => {
3435
+ if (viewport) return viewport;
3436
+ dialog.classList.add('ai-chat-evidence-viewer');
3437
+ viewport = drawingViewport({ pageBounds: [0, 0, 1, 1] });
3438
+ dialog.insertBefore(viewport.bar, body);
3439
+ body.append(viewport.frame);
3440
+ return viewport;
3441
+ };
3442
+ if (drawing) mountDrawing();
3443
+ loadingTimer = setTimeout(() => { if (!finished && !body.querySelector('img')) status.textContent = `Still loading ${citationLabel(entry)}. You can close this window while it loads.`; }, 4000);
3444
+ const loaded = () => clearTimeout(loadingTimer);
3445
+ const retry = () => {
3446
+ if (finished || dialog.querySelector('.ai-chat-drawing-retry')) return;
3447
+ loaded();
3448
+ viewport?.frame.remove(); viewport?.bar.remove();
3449
+ const again = button('Try again', 'shell.chat-drawing-retry', 'ai-chat-source-viewer-knowledge ai-chat-drawing-retry');
3450
+ again.addEventListener('click', () => { finish(); void openCitedSource(row, turnId); });
3451
+ dialog.append(again);
3452
+ };
3011
3453
  const refused = async (response) => {
3012
3454
  if (response.status === 404) return 'FloLess no longer holds this source, or its project is no longer part of this conversation.';
3013
3455
  if (response.status === 410) {
3014
- if (entry.kind !== 'attachment') return 'This Knowledge page has changed since the answer, so FloLess does not show it as the page the answer cited.';
3456
+ // #2692: a chosen source says it changed since the person chose it, never since an answer cited it.
3457
+ if (entry.kind !== 'attachment') {
3458
+ return entry.chosen ? 'This Knowledge page has changed since you chose it, so FloLess does not show it as the page you chose.'
3459
+ : 'This Knowledge page has changed since the answer, so FloLess does not show it as the page the answer cited.';
3460
+ }
3015
3461
  // Changed bytes, or no longer the plain file that was attached: the server says which.
3016
3462
  const said = await response.json().catch(() => null);
3463
+ if (entry.chosen && said?.code === 'citation-source-changed') return 'This file has changed since you chose it, so FloLess does not show it as the file you chose.';
3464
+ if (entry.chosen && said?.code === 'citation-source-not-as-attached') return CHOSEN_NOT_AS_ATTACHED;
3017
3465
  return typeof said?.message === 'string' && said.message ? said.message : 'This file has changed since the answer cited it, so FloLess does not show it as the cited file.';
3018
3466
  }
3019
3467
  // 503: FloLess could not check it just now; anything else is said as "try again", never as "gone".
@@ -3039,23 +3487,24 @@
3039
3487
  return;
3040
3488
  }
3041
3489
  if (entry.kind === 'sheet') {
3042
- const response = await fetch(citationUrl(row, 'image'), { credentials: 'same-origin', cache: 'no-store' });
3043
- if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3490
+ const response = await fetch(citationUrl(row, 'image'), { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
3491
+ if (!response.ok) { const why = await refused(response); if (!finished) { status.textContent = why; retry(); } return; }
3044
3492
  const shown = response.headers.get('X-FloLess-Shown') || 'as-seen';
3045
3493
  const bytes = await response.blob();
3046
3494
  // Checked after every wait: a viewer closed meanwhile creates nothing it would never release.
3047
3495
  if (finished) return;
3048
3496
  picture = URL.createObjectURL(bytes);
3049
3497
  const image = Object.assign(document.createElement('img'), { src: picture, alt: `${entry.label}${shown === 'as-seen' ? '' : ', rendered from the source drawing'}` });
3498
+ if (!await mountDrawing().setImage(image, () => !finished, true)) return;
3499
+ loaded();
3050
3500
  status.textContent = SHOWN[shown] || SHOWN['as-seen'];
3051
- body.append(image);
3052
3501
  return;
3053
3502
  }
3054
3503
  if (entry.kind === 'member') { await showCitedMember(row, { dialog, body, status, finish, refused, done: () => finished }); return; }
3055
3504
  if (entry.kind === 'project-file') {
3056
3505
  // #2701: a file of the project's folder, checked now against the size and digest it was cited with.
3057
- const response = await fetch(citationUrl(row, 'project-file'), { credentials: 'same-origin', cache: 'no-store' });
3058
- if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3506
+ const response = await fetch(citationUrl(row, 'project-file'), { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
3507
+ if (!response.ok) { const why = await refused(response); if (!finished) { status.textContent = why; retry(); } return; }
3059
3508
  const { file } = await response.json();
3060
3509
  if (finished) return;
3061
3510
  if (!file) { status.textContent = 'FloLess could not open this source right now. Try again in a moment.'; return; }
@@ -3071,20 +3520,24 @@
3071
3520
  return;
3072
3521
  }
3073
3522
  if (entry.kind === 'attachment') {
3074
- const response = await fetch(citationUrl(row, 'attachment'), { credentials: 'same-origin', cache: 'no-store' });
3075
- if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3523
+ const response = await fetch(citationUrl(row, 'attachment'), { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
3524
+ if (!response.ok) { const why = await refused(response); if (!finished) { status.textContent = why; retry(); } return; }
3076
3525
  const type = (response.headers.get('Content-Type') || '').split(';')[0].trim().toLowerCase();
3077
3526
  if (type.startsWith('image/')) {
3078
3527
  const bytes = await response.blob();
3079
3528
  if (finished) return;
3080
3529
  picture = URL.createObjectURL(bytes);
3530
+ const image = Object.assign(document.createElement('img'), { src: picture, alt: entry.label });
3531
+ if (!await mountDrawing().setImage(image, () => !finished, true)) return;
3532
+ loaded();
3081
3533
  status.textContent = 'The file as it was attached.';
3082
- body.append(Object.assign(document.createElement('img'), { src: picture, alt: entry.label }));
3083
3534
  } else if (type === 'text/plain') {
3084
3535
  const text = await response.text();
3085
3536
  if (finished) return;
3086
3537
  // A data file reaches the AI cut to its first 16,000 characters (attachment-text.ts MAX_TEXT_CHARS): said, never hidden.
3087
- status.textContent = 'The file as it was attached. The AI is given at most the first 16,000 characters of a data file.';
3538
+ // #2692: a file the person chose says nothing about what the AI was given: the choice records no read.
3539
+ status.textContent = entry.chosen ? 'The file as it was attached.'
3540
+ : 'The file as it was attached. The AI is given at most the first 16,000 characters of a data file.';
3088
3541
  const shown = [...text];
3089
3542
  const pre = Object.assign(document.createElement('pre'), { className: 'ai-chat-source-viewer-text', tabIndex: 0,
3090
3543
  textContent: shown.length > 16000 ? shown.slice(0, 16000).join('') : text });
@@ -3109,8 +3562,9 @@
3109
3562
  const why = {
3110
3563
  'chat-page-closed': 'This conversation is no longer the one open here. Open it again, then press Open in its default app.',
3111
3564
  'citation-source-unavailable': 'FloLess no longer holds this file in this conversation, so there is nothing to open.',
3112
- 'citation-source-changed': 'This file has changed since the answer cited it, so FloLess does not open it as the cited file.',
3113
- 'citation-source-not-as-attached': 'This file is no longer the plain file that was attached, so FloLess does not open it as the cited file. Attach the file again if you still need it.',
3565
+ 'citation-source-changed': entry.chosen ? 'This file has changed since you chose it, so FloLess does not open it as the file you chose.'
3566
+ : 'This file has changed since the answer cited it, so FloLess does not open it as the cited file.',
3567
+ 'citation-source-not-as-attached': entry.chosen ? CHOSEN_NOT_AS_ATTACHED : 'This file is no longer the plain file that was attached, so FloLess does not open it as the cited file. Attach the file again if you still need it.',
3114
3568
  'citation-source-unreadable': 'FloLess could not check this file just now. Try again in a moment.',
3115
3569
  }[error?.code] || '';
3116
3570
  if (!why) console.error('[chat] a cited file could not be opened in its app', error);
@@ -3120,11 +3574,11 @@
3120
3574
  dialog.append(external);
3121
3575
  return;
3122
3576
  }
3123
- const response = await fetch(citationUrl(row, 'page'), { credentials: 'same-origin', cache: 'no-store' });
3124
- if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3577
+ const response = await fetch(citationUrl(row, 'page'), { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
3578
+ if (!response.ok) { const why = await refused(response); if (!finished) { status.textContent = why; retry(); } return; }
3125
3579
  const { page } = await response.json();
3126
3580
  if (finished) return;
3127
- status.textContent = 'The Knowledge page as it was when the answer cited it.';
3581
+ status.textContent = entry.chosen ? 'The Knowledge page as it was when you chose it.' : 'The Knowledge page as it was when the answer cited it.';
3128
3582
  const article = document.createElement('div'); article.className = 'ai-chat-message-body ai-chat-source-viewer-page';
3129
3583
  article.innerHTML = markdownHtml(page.body);
3130
3584
  const knowledge = button('Open in Knowledge', 'shell.chat-cite-open-knowledge', 'ai-chat-source-viewer-knowledge');
@@ -3136,9 +3590,11 @@
3136
3590
  body.append(article);
3137
3591
  dialog.append(knowledge);
3138
3592
  } catch (error) {
3593
+ if (finished) return;
3139
3594
  console.error('[chat] a cited source could not be opened', error);
3140
- if (!finished) status.textContent = 'FloLess could not open this source right now. Try again in a moment.';
3141
- }
3595
+ status.textContent = 'FloLess could not open this source right now. Try again to check and open the same source.';
3596
+ retry();
3597
+ } finally { loaded(); }
3142
3598
  }
3143
3599
 
3144
3600
  /**
@@ -3411,6 +3867,21 @@
3411
3867
  const REQUEST_CARD_HIDDEN_KEY = 'floless:chat-hidden-request-cards';
3412
3868
  state.requestCards = state.requestCards || new Map();
3413
3869
  state.requestCardsAt = state.requestCardsAt || 0;
3870
+ // Click state belongs to the request, not the article replaced by every stream/poll repaint (#2694).
3871
+ const requestCardUi = new Map();
3872
+ function requestCardEntry(requestId) {
3873
+ if (!requestCardUi.has(requestId)) requestCardUi.set(requestId, { busy: null, hold: null, note: '', askError: '' });
3874
+ return requestCardUi.get(requestId);
3875
+ }
3876
+ function liveRequestCard(requestId) {
3877
+ return [...(ui.feed?.querySelectorAll('.ai-chat-request-card[data-request-id]') || [])]
3878
+ .find((card) => card.dataset.requestId === requestId) || null;
3879
+ }
3880
+ function repaintRequestCard(requestId) {
3881
+ const card = liveRequestCard(requestId);
3882
+ if (card) paintRequestCard(card);
3883
+ return card;
3884
+ }
3414
3885
 
3415
3886
  function hiddenRequestCards() {
3416
3887
  try {
@@ -3461,6 +3932,19 @@
3461
3932
  // for the AI to start it), or the AI. The line says the card's own live word either way.
3462
3933
  if (finished) item.dataset.waits = 'done';
3463
3934
  else item.dataset.waits = live?.attention?.state === 'needs-you' && live.attention.code !== 'waiting-to-start' ? 'you' : 'ai';
3935
+ const entry = requestCardEntry(requestId);
3936
+ // A fresh terminal verdict retires this choice, not the whole entry: an old Stop must never
3937
+ // survive after the server says there is no work left. Unknown/in-flight status keeps it.
3938
+ if (live && (live.found === false || set)) { entry.hold = null; entry.askError = ''; }
3939
+ if (dismiss) dismiss.disabled = Boolean(entry.busy || entry.hold);
3940
+ if (undo) undo.disabled = Boolean(entry.busy);
3941
+ let note = item.querySelector('.ai-chat-request-note');
3942
+ if (entry.note) {
3943
+ if (!note) { note = document.createElement('p'); note.className = 'ai-chat-request-note'; note.setAttribute('role', 'status'); item.append(note); }
3944
+ note.textContent = entry.note;
3945
+ } else note?.remove();
3946
+ if (entry.hold) paintRequestAsk(item, entry);
3947
+ else item.querySelector('.ai-chat-request-ask')?.remove();
3464
3948
  }
3465
3949
 
3466
3950
  function initRequestCard(item, event) {
@@ -3483,6 +3967,8 @@
3483
3967
  catch { return; /* the card keeps what it last knew; the next poll tries again */ }
3484
3968
  if (!Array.isArray(statuses)) return;
3485
3969
  for (const live of statuses) if (live?.id) state.requestCards.set(live.id, live);
3970
+ // Only an authoritative removal retires transient state; folding or a conversation repaint does not.
3971
+ for (const live of statuses) if (live?.id && live.found === false) requestCardUi.delete(live.id);
3486
3972
  // A hidden card's line reads these on the conversation's next repaint (the chat poll, every 5 s).
3487
3973
  for (const card of ui.feed.querySelectorAll('.ai-chat-request-card[data-request-id]')) paintRequestCard(card);
3488
3974
  }
@@ -3498,6 +3984,8 @@
3498
3984
  async function dismissRequestFromCard(item) {
3499
3985
  const requestId = item.dataset.requestId;
3500
3986
  if (!requestId) return;
3987
+ const entry = requestCardEntry(requestId);
3988
+ if (entry.busy || entry.hold) return;
3501
3989
  // #2678: the person's own click holds the card open (its Undo, its ask, its note stay in front of them), counted from
3502
3990
  // the click so a collapse while it is answered still wins.
3503
3991
  openFeedCard(item.dataset.cardEventId);
@@ -3510,53 +3998,91 @@
3510
3998
  announce('This request is already finished, so there is nothing to dismiss.');
3511
3999
  return;
3512
4000
  }
3513
- const dismiss = item.querySelector('.ai-chat-request-dismiss');
3514
- if (dismiss) dismiss.disabled = true;
3515
- item.querySelector('.ai-chat-request-note')?.remove(); // a new try replaces the last failure's note
4001
+ entry.busy = 'dismiss'; entry.note = '';
4002
+ paintRequestCard(item);
3516
4003
  try {
4004
+ // Learn the current choices before asking the server to dismiss: being held is an ordinary
4005
+ // choice, not a knowingly failed write. The POST below still owns its atomic race check.
4006
+ const projection = await request(`/api/requests/status?ids=${encodeURIComponent(requestId)}`, { timeoutMs: 10000 });
4007
+ const fresh = Array.isArray(projection?.statuses) ? projection.statuses.find((row) => row?.id === requestId) : null;
4008
+ if (!fresh || typeof fresh.found !== 'boolean' || !Object.hasOwn(fresh, 'hold') || !Object.hasOwn(fresh, 'lifecycle')
4009
+ || (fresh.lifecycle !== null && (typeof fresh.lifecycle !== 'object' || !REQUEST_CARD_WORDS[fresh.lifecycle.state]))
4010
+ || (fresh.hold !== null && (typeof fresh.hold !== 'object' || Array.isArray(fresh.hold)
4011
+ || typeof fresh.hold.kind !== 'string' || typeof fresh.hold.why !== 'string' || !Object.hasOwn(fresh.hold, 'stop')))) {
4012
+ cardNotice(requestId, 'FloLess couldn’t check whether this request is being worked on. Nothing was dismissed; try Dismiss again.');
4013
+ return;
4014
+ }
4015
+ state.requestCards.set(requestId, fresh);
4016
+ item = liveRequestCard(requestId);
4017
+ if (!fresh.found || fresh.lifecycle) {
4018
+ entry.busy = null;
4019
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-actions button:not([hidden])')?.focus();
4020
+ announce('This request is already finished, so there is nothing to dismiss.');
4021
+ return;
4022
+ }
4023
+ if (fresh.hold) { entry.busy = null; askStopThenDismiss(requestId, fresh.hold); return; }
3517
4024
  const done = await lifecycleCall(requestId, 'dismiss');
4025
+ item = liveRequestCard(requestId);
3518
4026
  if (done.ok) {
4027
+ entry.busy = null;
3519
4028
  state.requestCards.set(requestId, { id: requestId, found: true, lifecycle: { state: 'dismissed' }, attention: { state: 'not-now', code: 'dismissed', label: 'Dismissed' } });
3520
- paintRequestCard(item);
3521
- item.querySelector('.ai-chat-request-undo')?.focus();
4029
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-undo')?.focus();
3522
4030
  announce('Request dismissed. Undo is on the card.');
3523
4031
  return;
3524
4032
  }
3525
- if (done.body?.code === 'request-held' && done.body.hold) { askStopThenDismiss(item, done.body.hold); return; }
4033
+ if (done.body?.code === 'request-held' && done.body.hold) { entry.busy = null; askStopThenDismiss(requestId, done.body.hold); return; }
3526
4034
  if (done.status === 404 || done.body?.code === 'request-already-set-aside') { void refreshRequestCards({ force: true }); return; }
3527
- cardNotice(item, done.body?.error || 'FloLess couldn’t dismiss that request. It is still in Requests; try Dismiss again.');
4035
+ cardNotice(requestId, done.body?.error || 'FloLess couldn’t dismiss that request. It is still in Requests; try Dismiss again.');
3528
4036
  } catch {
3529
- cardNotice(item, 'FloLess couldn’t reach the server, so the request was not dismissed. Try Dismiss again in a moment.');
4037
+ cardNotice(requestId, 'FloLess couldn’t reach the server, so the request was not dismissed. Try Dismiss again in a moment.');
3530
4038
  } finally {
3531
- if (dismiss) dismiss.disabled = false;
4039
+ entry.busy = null; repaintRequestCard(requestId);
3532
4040
  }
3533
4041
  }
3534
4042
 
3535
4043
  /** A failure said where the person is looking (on the card) as well as to a screen reader: never only one of the two. */
3536
- function cardNotice(item, text) {
3537
- item.querySelector('.ai-chat-request-note')?.remove();
3538
- const note = document.createElement('p');
3539
- note.className = 'ai-chat-request-note'; note.setAttribute('role', 'status'); note.textContent = text;
3540
- item.append(note);
4044
+ function cardNotice(requestId, text) {
4045
+ requestCardEntry(requestId).note = text;
4046
+ repaintRequestCard(requestId);
3541
4047
  announce(text);
3542
4048
  }
3543
4049
 
3544
4050
  /** The AI is working on it: ask - stop that work and dismiss, or keep the request. Nothing happened yet. */
3545
- function askStopThenDismiss(item, hold) {
3546
- item.querySelector('.ai-chat-request-ask')?.remove();
4051
+ function askStopThenDismiss(requestId, hold) {
4052
+ const entry = requestCardEntry(requestId);
4053
+ entry.hold = hold; entry.askError = '';
4054
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-ask button')?.focus();
4055
+ }
4056
+ function paintRequestAsk(item, entry) {
4057
+ const requestId = item.dataset.requestId;
4058
+ const hold = entry.hold;
4059
+ const existing = item.querySelector('.ai-chat-request-ask');
4060
+ if (existing) {
4061
+ existing.querySelector('p').textContent = entry.askError || `${hold.why || 'The AI is working on this request.'} Nothing was changed.`;
4062
+ for (const button of existing.querySelectorAll('button')) button.disabled = Boolean(entry.busy);
4063
+ return;
4064
+ }
3547
4065
  const ask = document.createElement('div'); ask.className = 'ai-chat-request-ask'; ask.setAttribute('role', 'group'); ask.setAttribute('aria-label', 'This request is being worked on');
4066
+ const keepRequest = () => {
4067
+ if (entry.busy) return;
4068
+ entry.hold = null; entry.askError = '';
4069
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-dismiss')?.focus();
4070
+ };
3548
4071
  // Escape means Keep it: the safe default.
3549
- ask.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.stopPropagation(); ask.remove(); item.querySelector('.ai-chat-request-dismiss')?.focus(); } });
3550
- const why = document.createElement('p'); why.textContent = `${hold.why || 'The AI is working on this request.'} Nothing was changed.`;
4072
+ ask.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.stopPropagation(); keepRequest(); } });
4073
+ const why = document.createElement('p'); why.textContent = entry.askError || `${hold.why || 'The AI is working on this request.'} Nothing was changed.`;
3551
4074
  const row = document.createElement('div'); row.className = 'ai-chat-request-ask-actions';
3552
4075
  const keep = button('Keep it', `shell.chat-request-keep#${item.dataset.requestId || 'linked request'}`);
3553
- keep.addEventListener('click', () => { ask.remove(); item.querySelector('.ai-chat-request-dismiss')?.focus(); });
4076
+ keep.disabled = Boolean(entry.busy);
4077
+ keep.addEventListener('click', keepRequest);
3554
4078
  row.append(keep);
3555
4079
  const stop = hold.stop;
3556
4080
  if (stop) {
3557
4081
  const go = button('Stop it and dismiss', `shell.chat-request-stop-dismiss#${item.dataset.requestId || 'linked request'}`, 'danger');
4082
+ go.disabled = Boolean(entry.busy);
3558
4083
  go.addEventListener('click', async () => {
3559
- go.disabled = true; keep.disabled = true;
4084
+ if (entry.busy) return;
4085
+ entry.busy = 'stop'; entry.askError = ''; repaintRequestCard(requestId);
3560
4086
  openFeedCard(item.dataset.cardEventId); // #2678: as Dismiss: the Undo it offers stays in front of them
3561
4087
  let stopped = true; // a stale stop means the work had already ended or changed: never claimed as "stopped"
3562
4088
  try {
@@ -3569,43 +4095,52 @@
3569
4095
  await request(`/api/requests/${encodeURIComponent(stop.requestId)}/run/stop`, { method: 'POST', body: JSON.stringify(stop.leaseId ? { expectLeaseId: stop.leaseId } : {}) });
3570
4096
  }
3571
4097
  } catch (error) {
3572
- if (error?.code !== 'stop-stale') { why.textContent = 'FloLess couldn’t stop that work, so the request was not dismissed.'; go.disabled = false; keep.disabled = false; return; }
4098
+ if (error?.code !== 'stop-stale') {
4099
+ entry.askError = 'FloLess couldn’t stop that work, so the request was not dismissed.';
4100
+ entry.busy = null; repaintRequestCard(requestId); announce(entry.askError); return;
4101
+ }
3573
4102
  stopped = false;
3574
4103
  }
3575
- const again = await lifecycleCall(item.dataset.requestId, 'dismiss').catch(() => null);
4104
+ const again = await lifecycleCall(requestId, 'dismiss').catch(() => null);
4105
+ entry.busy = null;
3576
4106
  if (again?.ok) {
3577
- ask.remove();
3578
- state.requestCards.set(item.dataset.requestId, { id: item.dataset.requestId, found: true, lifecycle: { state: 'dismissed' }, attention: { state: 'not-now', code: 'dismissed', label: 'Dismissed' } });
3579
- paintRequestCard(item);
3580
- item.querySelector('.ai-chat-request-undo')?.focus();
4107
+ entry.hold = null; entry.askError = '';
4108
+ state.requestCards.set(requestId, { id: requestId, found: true, lifecycle: { state: 'dismissed' }, attention: { state: 'not-now', code: 'dismissed', label: 'Dismissed' } });
4109
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-undo')?.focus();
3581
4110
  } else {
3582
4111
  // A stop that went through is said, so the person does not think the AI is still working; a stale one is not claimed.
3583
- why.textContent = again?.body?.code === 'request-held'
4112
+ entry.askError = again?.body?.code === 'request-held'
3584
4113
  ? (stopped ? 'The work was stopped and is still winding down. Try again in a moment.' : 'Something is still working on this request. Try again in a moment.')
3585
4114
  : `${stopped ? 'The work was stopped, but the request' : 'The request'} couldn’t be set aside. It is still in Requests; try again.`;
3586
- go.disabled = false; keep.disabled = false;
4115
+ repaintRequestCard(requestId); announce(entry.askError);
3587
4116
  }
3588
4117
  });
3589
4118
  row.append(go);
3590
4119
  }
3591
4120
  ask.append(why, row);
3592
4121
  item.append(ask);
3593
- keep.focus();
3594
4122
  }
3595
4123
 
3596
4124
  async function restoreRequestFromCard(item) {
3597
4125
  const requestId = item.dataset.requestId;
3598
- const undo = item.querySelector('.ai-chat-request-undo');
3599
- if (undo) undo.disabled = true;
3600
- item.querySelector('.ai-chat-request-note')?.remove();
4126
+ const entry = requestCardEntry(requestId);
4127
+ if (entry.busy) return;
4128
+ entry.busy = 'restore'; entry.note = ''; paintRequestCard(item);
4129
+ let restored = false;
3601
4130
  try {
3602
4131
  const done = await lifecycleCall(requestId, 'restore');
3603
- if (!done.ok) { cardNotice(item, done.body?.error || 'FloLess couldn’t put that request back. It is still in Requests → Done; try Undo again.'); return; }
3604
- forgetHiddenRequestCard(item.dataset.cardEventId);
4132
+ if (!done.ok) { cardNotice(requestId, done.body?.error || 'FloLess couldn’t put that request back. It is still in Requests → Done; try Undo again.'); return; }
4133
+ item = liveRequestCard(requestId);
4134
+ if (item) forgetHiddenRequestCard(item.dataset.cardEventId);
3605
4135
  await refreshRequestCards({ force: true });
4136
+ restored = true;
3606
4137
  } catch {
3607
- cardNotice(item, 'FloLess couldn’t reach the server, so the request was not put back. Try Undo again in a moment.');
3608
- } finally { if (undo) undo.disabled = false; }
4138
+ cardNotice(requestId, 'FloLess couldn’t reach the server, so the request was not put back. Try Undo again in a moment.');
4139
+ } finally {
4140
+ entry.busy = null;
4141
+ const card = repaintRequestCard(requestId);
4142
+ if (restored) card?.querySelector('.ai-chat-request-dismiss:not([hidden])')?.focus();
4143
+ }
3609
4144
  }
3610
4145
 
3611
4146
  // #1907: the plain name of one of the person's connectors — the same rule the server words its cards with.
@@ -3632,8 +4167,47 @@
3632
4167
  return item;
3633
4168
  }
3634
4169
 
4170
+ /** One completed auto-review record, using the same disclosure and per-chat state as answer receipts. */
4171
+ function renderAutoReviewReceipt(event) {
4172
+ const chatId = state.chat?.chatId || '';
4173
+ if (receiptFoldsChat !== chatId) { receiptFolds.clear(); receiptFoldsChat = chatId; }
4174
+ const key = `auto-review:${event.eventId}`;
4175
+ let fold = receiptFolds.get(key);
4176
+ if (!fold) {
4177
+ fold = newReceiptFold(key);
4178
+ fold.root.classList.add('auto-review', 'ai-chat-auto-review-receipt');
4179
+ fold.toggle.dataset.commandId = `shell.chat-auto-review-details#${event.eventId}`;
4180
+ fold.toggle.dataset.commandInstanceLabel = 'this auto-approved action';
4181
+ fold.text.textContent = 'Auto-approved · Details';
4182
+ fold.body.setAttribute('aria-label', 'Auto-approval details');
4183
+ const record = document.createElement('pre');
4184
+ record.className = 'ai-chat-auto-review-record';
4185
+ record.tabIndex = 0;
4186
+ record.dataset.commandId = `shell.chat-auto-review-record#${event.eventId}`;
4187
+ record.dataset.commandInstanceLabel = 'this auto-approved action';
4188
+ record.setAttribute('aria-label', 'Auto-approval record');
4189
+ fold.body.append(record);
4190
+ fold.root.addEventListener('keydown', (keyEvent) => {
4191
+ if (keyEvent.key !== 'Escape' || !fold.open || keyEvent.defaultPrevented) return;
4192
+ keyEvent.preventDefault(); keyEvent.stopPropagation();
4193
+ fold.toggle.click(); fold.toggle.focus({ preventScroll: true });
4194
+ });
4195
+ }
4196
+ fold.root.dataset.eventId = event.eventId;
4197
+ fold.root.dataset.eventSequence = String(event.sequence);
4198
+ const record = fold.body.firstElementChild;
4199
+ const payload = event.payload || {};
4200
+ const message = [String(payload.message ?? ''),
4201
+ typeof payload.command === 'string' ? `Command\n${payload.command}` : '',
4202
+ typeof payload.reviewExplanation === 'string' ? `Review explanation\n${payload.reviewExplanation}` : '',
4203
+ ].filter(Boolean).join('\n\n');
4204
+ if (record.textContent !== message) record.textContent = message;
4205
+ return fold.root;
4206
+ }
4207
+
3635
4208
  /** A refusal FloLess wrote for the person (`plain`), shown as is: what happened, why, and what to do next. */
3636
4209
  function renderPlainNotice(event) {
4210
+ if (event.payload?.tool === 'auto-review' && event.payload.decision === 'approved') return renderAutoReviewReceipt(event);
3637
4211
  const item = document.createElement('div');
3638
4212
  // #2037: a Codex auto-review decision is a receipt, not a failure: approved is information, held back is a notice.
3639
4213
  const review = event.payload?.tool === 'auto-review' ? event.payload.decision : null;
@@ -4894,7 +5468,8 @@
4894
5468
  /** The crop of the page around a place: the area and some room around it, never smaller than a fifth of the page. */
4895
5469
  function evidenceCrop(place) {
4896
5470
  const [px0, py0, px1, py1] = place.pageBounds;
4897
- const [rx0, ry0, rx1, ry1] = place.region;
5471
+ // #2777: a place with no marked area (an RFI on a sheet, a level read from its picture) is the whole sheet.
5472
+ const [rx0, ry0, rx1, ry1] = Array.isArray(place.region) ? place.region : place.pageBounds;
4898
5473
  const grow = (lo, hi, min, max) => {
4899
5474
  const pad = Math.max((hi - lo) * 0.15, (max - min) * 0.01);
4900
5475
  let a = lo - pad, b = hi + pad;
@@ -4910,70 +5485,118 @@
4910
5485
  }
4911
5486
 
4912
5487
  /** The place's page in the cited-source viewer, cropped to the place, with the whole sheet a press away. */
4913
- async function openReadinessEvidence(place, row, card, opener) {
4914
- const title = String(place.title || place.label);
5488
+ function openReadinessEvidence(place, row, card, opener) {
5489
+ return openDrawingPlace(place, {
5490
+ title: String(place.title || place.label), note: EVIDENCE_ORIGIN[place.origin].note(place), opener,
5491
+ url: `/api/projects/${encodeURIComponent(card.projectId)}/connections/${encodeURIComponent(row.jointId)}/evidence/drawing?key=${encodeURIComponent(place.key)}&digest=${encodeURIComponent(place.digest)}`,
5492
+ commands: { close: 'shell.chat-readiness-evidence-close', view: 'shell.chat-readiness-evidence-view' },
5493
+ again: { label: 'Ask for the readiness card again', commandId: 'shell.chat-readiness-evidence-again', tip: 'Puts the request in the message box. Nothing is sent until you press Send',
5494
+ run: () => { addToMessageBox(`Show the readiness of connection ${row.jointId} again.`); ui.input.focus?.(); } },
5495
+ ...(place.sourceHash && place.pageId ? { filter: { projectId: card.projectId, commandId: 'shell.chat-place-open-filter' } } : {}),
5496
+ });
5497
+ }
5498
+
5499
+ /**
5500
+ * #2777 slice D: "Open in Drawing Filter" for a place. The Drawing Filter does the showing; the viewer says what it did,
5501
+ * never more: it waits for the Filter's own outcome (as "Open in the model" waits for the editor's), closes once the place
5502
+ * is shown, and otherwise stays open with the reason in sight, so a place that could not be shown is never silent.
5503
+ */
5504
+ function drawingFilterButton(place, filter, { shown, refused }) {
5505
+ const open = button('Open in Drawing Filter', filter.commandId, 'ai-chat-evidence-view ai-chat-evidence-filter');
5506
+ open.dataset.tip = 'Opens this sheet in the project\u2019s Drawing Filter with the place marked. Nothing changes';
5507
+ if (filter.instanceLabel) open.dataset.commandInstanceLabel = filter.instanceLabel;
5508
+ open.addEventListener('click', async () => {
5509
+ if (open.getAttribute('aria-busy') === 'true') return;
5510
+ const unreachable = 'FloLess could not open the Drawing Filter from here. Open the project’s Drawings step from Workspaces, then try again.';
5511
+ open.setAttribute('aria-busy', 'true');
5512
+ let said;
5513
+ try {
5514
+ if (typeof window.flolessWorkspaces?.openDrawingAt !== 'function') said = unreachable;
5515
+ else {
5516
+ const outcome = await window.flolessWorkspaces.openDrawingAt({ projectId: filter.projectId, place: {
5517
+ sourceHash: place.sourceHash, pageId: place.pageId, sheet: place.sheet, ...(Array.isArray(place.region) ? { region: place.region } : {}) } });
5518
+ if (outcome?.superseded) return;
5519
+ if (outcome?.ok === true) { shown(); announce(`Showing the place on sheet ${place.sheet} in the Drawing Filter.`); return; }
5520
+ said = outcome?.said || `The place on sheet ${place.sheet} was not shown. Open the Drawings step, then press Open in Drawing Filter again.`;
5521
+ }
5522
+ } catch (error) {
5523
+ if (error?.plain !== true) console.error('[chat] Open in Drawing Filter failed', error);
5524
+ said = error?.plain === true && error.message ? error.message : unreachable;
5525
+ } finally {
5526
+ open.removeAttribute('aria-busy');
5527
+ }
5528
+ if (said) refused(said);
5529
+ });
5530
+ return open;
5531
+ }
5532
+
5533
+ /**
5534
+ * A page of a drawing in the cited-source viewer, cropped to a place (`pageBounds`, `region`, `sheet`, `page`), with the
5535
+ * whole sheet a press away. Shared by the readiness card (#2451) and the height card (#2777); `again` is the way on
5536
+ * when the place changed or is gone, never something done for the person. A place with no `region` is a whole sheet:
5537
+ * it opens on the sheet and offers no "This area", since there is no area to show. `filter` (#2777 slice D) adds
5538
+ * "Open in Drawing Filter", which shows the same place in the project's Drawing Filter.
5539
+ */
5540
+ async function openDrawingPlace(place, { title, note: noteText, url, opener, commands, again, filter }) {
4915
5541
  const dialog = document.createElement('dialog'); dialog.className = 'ai-chat-source-viewer ai-chat-evidence-viewer';
4916
5542
  dialog.setAttribute('aria-label', title);
4917
5543
  const head = document.createElement('div'); head.className = 'ai-chat-source-viewer-head';
4918
- const close = button('Close', 'shell.chat-readiness-evidence-close', 'ai-chat-source-viewer-close');
5544
+ const close = button('Close', commands.close, 'ai-chat-source-viewer-close');
4919
5545
  let picture = null;
4920
5546
  let finished = false;
5547
+ const controller = new AbortController();
5548
+ let loadingTimer = null;
4921
5549
  const finish = () => {
4922
5550
  if (finished) return;
4923
5551
  finished = true;
5552
+ controller.abort();
5553
+ clearTimeout(loadingTimer);
4924
5554
  if (dialog.open) dialog.close();
4925
5555
  hide();
4926
5556
  if (picture) URL.revokeObjectURL(picture);
4927
- if (opener?.isConnected) opener.focus({ preventScroll: true });
5557
+ const returnTo = opener?.isConnected ? opener : opener?.dataset.commandId
5558
+ ? [...document.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === opener.dataset.commandId) : null;
5559
+ returnTo?.focus({ preventScroll: true });
4928
5560
  };
4929
5561
  close.addEventListener('click', finish);
4930
5562
  dialog.addEventListener('close', finish);
4931
5563
  head.append(Object.assign(document.createElement('strong'), { textContent: title }), close);
4932
- const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: EVIDENCE_ORIGIN[place.origin].note(place) });
4933
- const views = document.createElement('div'); views.className = 'ai-chat-evidence-views'; views.setAttribute('role', 'group'); views.setAttribute('aria-label', 'How much of the sheet to show');
4934
- const area = button('This area', 'shell.chat-readiness-evidence-view', 'ai-chat-evidence-view');
4935
- const whole = button('Whole sheet', 'shell.chat-readiness-evidence-view', 'ai-chat-evidence-view');
4936
- area.dataset.commandInstanceLabel = 'this area'; whole.dataset.commandInstanceLabel = 'the whole sheet';
4937
- views.append(area, whole);
5564
+ const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: noteText });
5565
+ const filterNote = Object.assign(document.createElement('p'), { className: 'ai-chat-evidence-filter-note', hidden: true });
5566
+ filterNote.setAttribute('role', 'status');
5567
+ const marked = Array.isArray(place.region);
5568
+ const viewport = drawingViewport(place, commands.view);
5569
+ const { bar, frame } = viewport;
5570
+ if (filter?.projectId && filter.commandId) {
5571
+ bar.append(drawingFilterButton(place, filter, {
5572
+ shown: () => finish(),
5573
+ // Said where the person clicked, and read out: the picture stays, so they can still look at the place here.
5574
+ refused: (said) => { if (finished) return; filterNote.textContent = said; filterNote.hidden = false; announce(said); },
5575
+ }));
5576
+ }
4938
5577
  const body = document.createElement('div'); body.className = 'ai-chat-source-viewer-body';
4939
5578
  const status = Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-status', textContent: 'Loading the drawing…' });
4940
5579
  status.setAttribute('role', 'status');
4941
- const crop = evidenceCrop(place);
4942
- const frame = document.createElement('div'); frame.className = 'ai-chat-evidence-frame';
4943
- const show = (all) => {
4944
- area.setAttribute('aria-pressed', String(!all)); whole.setAttribute('aria-pressed', String(all));
4945
- frame.dataset.view = all ? 'sheet' : 'area';
4946
- const c = all ? { x0: crop.px0, y0: crop.py0, w: crop.pageW, h: crop.pageH } : crop;
4947
- // Shaped like the crop and never taller than most of the window: narrowed, not squashed, so the picture stays true.
4948
- frame.style.aspectRatio = `${c.w} / ${c.h}`;
4949
- frame.style.width = `min(100%, calc(62vh * ${c.w / c.h}))`;
4950
- const image = frame.querySelector('img');
4951
- if (image) Object.assign(image.style, { width: `${(crop.pageW / c.w) * 100}%`, left: `${(-(c.x0 - crop.px0) / c.w) * 100}%`, top: `${(-(c.y0 - crop.py0) / c.h) * 100}%` });
4952
- };
4953
- area.addEventListener('click', () => show(false));
4954
- whole.addEventListener('click', () => show(true));
4955
- show(false);
4956
5580
  body.append(status, frame);
4957
- dialog.append(head, note, views, body);
5581
+ dialog.append(head, note, bar, filterNote, body);
4958
5582
  const hide = showChatViewer(dialog, finish);
4959
5583
  close.focus({ preventScroll: true });
5584
+ loadingTimer = setTimeout(() => { if (!finished && !frame.querySelector('img')) status.textContent = `Still loading ${place.sheet}. You can close this window while it loads.`; }, 4000);
4960
5585
  // A place that changed or is gone says so and offers the way on: the card asked for again, never sent for the person.
4961
5586
  const offerAgain = (why) => {
4962
5587
  if (finished) return;
5588
+ clearTimeout(loadingTimer);
4963
5589
  status.textContent = why;
4964
- frame.remove(); views.remove();
4965
- const again = button('Ask for the readiness card again', 'shell.chat-readiness-evidence-again', 'ai-chat-source-viewer-knowledge');
4966
- again.dataset.tip = 'Puts the request in the message box. Nothing is sent until you press Send';
4967
- again.addEventListener('click', () => {
4968
- finish();
4969
- addToMessageBox(`Show the readiness of connection ${row.jointId} again.`);
4970
- ui.input.focus?.();
4971
- });
4972
- dialog.append(again);
5590
+ frame.remove(); bar.remove(); filterNote.remove();
5591
+ const way = button(again.label, again.commandId, 'ai-chat-source-viewer-knowledge');
5592
+ if (again.tip) way.dataset.tip = again.tip;
5593
+ way.addEventListener('click', () => { finish(); again.run(); });
5594
+ const retry = button('Try again', 'shell.chat-drawing-retry', 'ai-chat-source-viewer-knowledge ai-chat-drawing-retry');
5595
+ retry.addEventListener('click', () => { finish(); void openDrawingPlace(place, { title, note: noteText, url, opener, commands, again, filter }); });
5596
+ dialog.append(retry, way);
4973
5597
  };
4974
5598
  try {
4975
- const url = `/api/projects/${encodeURIComponent(card.projectId)}/connections/${encodeURIComponent(row.jointId)}/evidence/drawing?key=${encodeURIComponent(place.key)}&digest=${encodeURIComponent(place.digest)}`;
4976
- const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store' });
5599
+ const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
4977
5600
  if (finished) return;
4978
5601
  if (!response.ok) {
4979
5602
  const said = await response.json().catch(() => null);
@@ -4983,14 +5606,14 @@
4983
5606
  const bytes = await response.blob();
4984
5607
  if (finished) return;
4985
5608
  picture = URL.createObjectURL(bytes);
4986
- const image = Object.assign(document.createElement('img'), { src: picture, alt: `${title}, page ${place.page}, with the area outlined` });
4987
- frame.append(image);
4988
- show(false);
5609
+ const image = Object.assign(document.createElement('img'), { src: picture, alt: marked ? `${title}, page ${place.page}, with the area outlined` : `${title}, page ${place.page}` });
5610
+ if (!await viewport.setImage(image, () => !finished)) return;
4989
5611
  status.textContent = `${place.sheet} · page ${place.page}`;
4990
5612
  } catch (error) {
5613
+ if (finished) return;
4991
5614
  console.error('[chat] a drawing place could not be opened', error);
4992
5615
  offerAgain('FloLess could not open this drawing just now. Try again in a moment.');
4993
- }
5616
+ } finally { clearTimeout(loadingTimer); }
4994
5617
  }
4995
5618
 
4996
5619
  /*
@@ -6170,7 +6793,7 @@
6170
6793
  // follows); a message refused or not sent stops counting, and the card is back.
6171
6794
  const movedPast = (waits === 'you' || movedPastFeedCards.has(id)) && feedCardAnsweredInChat(event, id);
6172
6795
  if (movedPast) movedPastFeedCards.add(id);
6173
- const byItself = !feedCardFolded(node) && ((waits === 'done' && !openedFeedCards.has(id)) || movedPast);
6796
+ const byItself = !feedCardFolded(node) && (((waits === 'done' || mark?.dataset.autoFold === 'true') && !openedFeedCards.has(id)) || movedPast);
6174
6797
  if (hiddenFeedCards.has(id) || byItself) {
6175
6798
  const { sentence, full } = feedCardSentence(node, kind, mark);
6176
6799
  // Amber while the person's choice waits, blue while the AI or the read still works, quiet once it is finished.
@@ -6209,10 +6832,17 @@
6209
6832
  if (shell.firstChild !== node || shell.lastChild !== hide) shell.replaceChildren(node, hide);
6210
6833
  return shell;
6211
6834
  }
6212
- /** Keyboard into a card: on the control `commandId` names, else its first usable control, else the card itself. */
6835
+ /** Keyboard into a card: on the control `commandId` names, else its first usable control in sight, else its first control, else the card itself. */
6213
6836
  function focusFeedCard(card, commandId = null) {
6214
6837
  const controls = [...card.querySelectorAll('button, a[href], input, select, textarea, [tabindex="0"]')].filter((node) => !node.disabled && !node.closest('[hidden]'));
6215
- const target = (commandId && controls.find((node) => node.dataset.commandId === commandId)) || controls[0] || card;
6838
+ // Not a control scrolled out of its card's list, even partly: the list stays where the person left it, so focus would be
6839
+ // out of sight. A control `commandId` names is used even when out of sight.
6840
+ const inSight = (node) => {
6841
+ const list = node.closest('.ai-chat-height-rows'); if (!list?.getBoundingClientRect) return true;
6842
+ const at = node.getBoundingClientRect(), box = list.getBoundingClientRect();
6843
+ return at.top >= box.top && at.bottom <= box.bottom;
6844
+ };
6845
+ const target = (commandId && controls.find((node) => node.dataset.commandId === commandId)) || controls.find(inSight) || controls[0] || card;
6216
6846
  if (target === card && !card.hasAttribute('tabindex')) card.tabIndex = -1;
6217
6847
  target.focus({ preventScroll: true });
6218
6848
  return target;
@@ -6239,6 +6869,7 @@
6239
6869
  }
6240
6870
 
6241
6871
  function renderEvent(event) {
6872
+ if (event.type === 'height-question-state') { applyHeightQuestionState(event); return null; }
6242
6873
  if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
6243
6874
  if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
6244
6875
  if (event.type === 'assistant-message' && event.payload?.filterAi && !event.payload?.delta) return renderFilterAnswer(event);
@@ -6389,15 +7020,17 @@
6389
7020
  * Typed text is not in the signature on purpose: it lives in the field and in `drafts`, and a keystroke is not a
6390
7021
  * reason to rebuild. Everything else a card paints from belongs in it.
6391
7022
  */
6392
- const CARD_SIGNATURE_SKIP = new Set(['node', 'nodeSig', 'drafts', 'bulkDraft', 'rowsScroll', 'bodyScroll', 'reloadPending', 'loading', 'slotNode', 'slotDrafts', 'slotSig']);
7023
+ const CARD_SIGNATURE_SKIP = new Set(['node', 'nodeSig', 'drafts', 'bulkDraft', 'rowsScroll', 'bodyScroll', 'reloadPending', 'loading', 'checkedAt', 'slotNode', 'slotDrafts', 'slotSig']);
6393
7024
  function cardSignature(entry, eventId, sequence) {
6394
7025
  settleNotSent(entry);
6395
7026
  const sources = [];
6396
7027
  for (const [scope, source] of answerSources) {
6397
- if (scope.split(':')[1] !== entry.questionId) continue;
7028
+ if (scope.startsWith('h:')) {
7029
+ if (!heightSourceBelongs(entry, scope)) continue;
7030
+ } else if (scope.split(':')[1] !== entry.questionId) continue;
6398
7031
  sources.push([scope, source.open, Boolean(source.note), source.files.map((file) => file.attachmentId), source.uploading, source.error]);
6399
7032
  }
6400
- return JSON.stringify([eventId, sequence, sources, entry], (key, value) => {
7033
+ return JSON.stringify([eventId, sequence, sources, entry, Boolean(entry.view?.ends && heightClarificationPending(entry))], (key, value) => {
6401
7034
  if (CARD_SIGNATURE_SKIP.has(key)) return undefined;
6402
7035
  if (value instanceof Map) return [...value];
6403
7036
  if (value instanceof Set) return [...value];
@@ -6420,13 +7053,88 @@
6420
7053
  entry = { key, requestId, questionId, chatId, view: null, loading: false, loadError: '', drafts: new Map(),
6421
7054
  changing: new Set(), rowErrors: new Map(), cardError: '', busy: false, selected: new Set(), bulkDraft: '' };
6422
7055
  heightCards.set(key, entry);
7056
+ restoreHeightDraft(entry);
6423
7057
  }
6424
7058
  return entry;
6425
7059
  }
6426
7060
 
7061
+ // Synchronous per-conversation storage: an older asynchronous response cannot restore an earlier draft.
7062
+ const heightDraftKey = (entry) => `floless-height-draft/v1/${encodeURIComponent(entry.chatId)}/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}`;
7063
+ function saveHeightDraft(entry) {
7064
+ try {
7065
+ const sources = [...answerSources].filter(([scope]) => heightSourceBelongs(entry, scope))
7066
+ .map(([scope, source]) => {
7067
+ if (scope === heightSourceScope(entry) && !source.scopeEnds && (source.note?.trim() || source.files.length)) source.scopeEnds = entry.slotQuestionKey === 'batch-value' ? [...entry.selected] : drawingRows('height', entry).filter((row) => row.status !== 'superseded').map(heightEndKey);
7068
+ return [scope, { open: source.open, note: source.note, scopeEnds: source.scopeEnds, files: source.files.map(({ url, ...file }) => file) }];
7069
+ });
7070
+ const slots = [...(entry.slotDrafts || [])].filter(([key]) => key !== 'finish');
7071
+ const value = { slots, sources, retiredDrafts: [...(entry.retiredDrafts || [])], projectId: entry.projectId, activeItem: entry.activeItem, slotPhase: entry.slotPhase, selected: [...entry.selected] };
7072
+ if (!window.sessionStorage) return; // Older embedded browsers keep the live draft only.
7073
+ window.sessionStorage.setItem(heightDraftKey(entry), JSON.stringify(value));
7074
+ entry.draftStorageError = '';
7075
+ } catch { entry.draftStorageError = 'Your draft is kept in this window, but FloLess could not keep it for a reload. Copy your text before refreshing; keep this window open to finish the answer.'; }
7076
+ }
7077
+ function restoreHeightDraft(entry) {
7078
+ try {
7079
+ const value = JSON.parse(window.sessionStorage?.getItem(heightDraftKey(entry)) || 'null');
7080
+ if (!value || !Array.isArray(value.slots) || !Array.isArray(value.sources)) return;
7081
+ entry.slotDrafts = new Map(value.slots.filter(([key, draft]) => typeof key === 'string' && Array.isArray(draft?.rows)).map(([key, draft]) => [key, { ...draft, pending: false }]));
7082
+ if (Array.isArray(value.retiredDrafts)) entry.retiredDrafts = new Map(value.retiredDrafts);
7083
+ if (typeof value.projectId === 'string') entry.projectId = value.projectId;
7084
+ entry.activeItem = value.activeItem; entry.slotPhase = value.slotPhase; entry.selected = new Set(value.selected || []);
7085
+ for (const [savedScope, source] of value.sources) {
7086
+ const scope = restoredHeightSourceScope(entry, savedScope);
7087
+ if (!scope || !Array.isArray(source.files)) continue;
7088
+ const recovered = { ...source, restored: true, uploading: 0, error: '', files: source.files.map((file) => ({ ...file, url: '' })) };
7089
+ answerSources.set(scope, recovered);
7090
+ }
7091
+ } catch { /* Invalid stored drafts never affect authoritative questions or answers. */ }
7092
+ }
7093
+ function checkHeightDraftPictures(entry) {
7094
+ if (entry.view?.readRemoved) return;
7095
+ for (const [scope, source] of answerSources) {
7096
+ if (!source.restored || !(heightSourceBelongs(entry, scope))) continue;
7097
+ source.restored = false;
7098
+ for (const file of source.files) {
7099
+ const url = heightDraftEvidenceUrl(entry, file.attachmentId);
7100
+ if (!url) { source.error = 'Open this question in its original project to check the saved picture; your text is kept.'; continue; }
7101
+ file.url = url;
7102
+ fetch(url, { credentials: 'same-origin' }).then((response) => {
7103
+ if (!response.ok && source.files.includes(file)) { source.error = response.status === 404 || response.status === 410
7104
+ ? `The saved picture ${file.fileName} is no longer available. Remove it and attach it again; your text is kept.`
7105
+ : 'FloLess could not check your saved pictures just now. Try again before submitting; your text is kept.'; repaintHeightCard(entry); }
7106
+ }).catch(() => { source.error = 'FloLess could not check your saved pictures. Try again before submitting; your text is kept.'; repaintHeightCard(entry); });
7107
+ }
7108
+ }
7109
+ }
7110
+ const heightStateEvents = new Set();
7111
+ function applyHeightQuestionState(event) {
7112
+ if (heightStateEvents.has(event.eventId)) return;
7113
+ heightStateEvents.add(event.eventId);
7114
+ const payload = event.payload || {}, entry = heightCards.get(`${payload.requestId}/${payload.questionId}`);
7115
+ if (!entry || entry.chatId !== event.chatId) return;
7116
+ if (entry.loading || entry.busy) entry.reloadPending = true; else loadHeightQuestion(entry);
7117
+ }
7118
+ function heightResponsibility(row) {
7119
+ return row.responsibility || (row.status === 'superseded' ? 'replaced' : row.answer && row.answer.how !== 'evidence' ? 'answered' : row.answer ? 'investigating' : row.proposed ? 'proposal' : 'needs-answer');
7120
+ }
7121
+ function heightStateText(row) {
7122
+ const state = heightResponsibility(row);
7123
+ const label = { investigating: 'AI investigating', 'needs-answer': 'Needs your answer', proposal: 'Proposed height — needs your confirmation', answered: 'Answered', replaced: 'Replaced by a newer question', 'resolved-from-drawings': 'Resolved from drawings', 'no-longer-needed': 'No longer needed' }[state];
7124
+ return `${label}${row.lifecycle?.reason ? ` · ${row.lifecycle.reason}` : state === 'needs-answer' && row.noProposal ? ` · ${row.noProposal}` : ''}`;
7125
+ }
7126
+ function heightStudyText(row) {
7127
+ const study = row.lifecycle?.investigation;
7128
+ return study ? [`Reader-reported study (${study.provenance})${study.datum ? ` · datum ${study.datum}` : ''}.`, ...study.checked.map((check) => `${check.sheet}${check.detail ? ` · ${check.detail}` : ''}: ${check.finding}`), !study.checked.length ? 'No source checks recorded.' : '', ...(study.conflicts || []), study.derivation ? `${study.derivation.inputs.join('; ')}. ${study.derivation.basis}` : '', study.limitations].filter(Boolean).join(' ') : !row.proposed && ['needs-answer', 'investigating'].includes(heightResponsibility(row)) ? 'No source checks recorded.' : '';
7129
+ }
7130
+
6427
7131
  const heightEndKey = (row) => `${row.memberId}\u0000${row.end}`;
6428
7132
  const heightEndWord = (row) => (row.endWord === 'from' ? 'start' : 'end');
6429
- const heightAnswerText = (answer) => (answer?.how === 'typed' ? `You typed ${answer.typed}` : `Confirmed ${answer?.shownAs || ''}`);
7133
+ // #2788: a confirmed proposal keeps where it came from, so a derived height never reads as one taken off a drawing.
7134
+ const heightProposalSaid = (proposal) => (!proposal ? '' : proposal.how === 'derived' ? `, which the read derived from ${proposal.basis}`
7135
+ : proposal.how === 'measured' ? `, which the read measured on the drawings${proposal.basis ? ` (${proposal.basis})` : ''}`
7136
+ : proposal.basis ? `, read off the drawings (${proposal.basis})` : ', read off the drawings');
7137
+ const heightAnswerText = (answer) => (answer?.how === 'typed' ? `You typed ${answer.typed}` : `Confirmed ${answer?.shownAs || ''}${heightProposalSaid(answer?.proposal)}`);
6430
7138
  /*
6431
7139
  * #1903: a row about a member ALREADY in the model. The server snapshotted that end when the question was
6432
7140
  * asked; the card says what it held THEN (the model can change before the person answers, and the review
@@ -6448,7 +7156,8 @@
6448
7156
  // The server's sentence, then what to do next when it names a step (a damaged record says to discard the read).
6449
7157
  const heightErrorText = (error, fallback) => {
6450
7158
  const next = (error?.recovery || []).map((step) => step && typeof step.action === 'string' ? step.action : '').filter(Boolean);
6451
- return [error?.message || fallback, ...next].join(' ');
7159
+ const message = /failed to fetch|fetch failed|networkerror|load failed/i.test(error?.message || '') ? fallback : (error?.message || fallback);
7160
+ return [message, ...next].join(' ');
6452
7161
  };
6453
7162
  // Refusals that mean the card is out of date: reload it from the server's record so it shows the truth.
6454
7163
  const HEIGHT_STALE = new Set(['height-question-changed', 'height-question-closed', 'height-question-superseded']);
@@ -6459,13 +7168,74 @@
6459
7168
  const CARD_READ_FINISHED = new Set(['height-question-unknown-read', 'setup-question-unknown-read']);
6460
7169
  const CARD_FINISHED_TEXT = 'This drawing read is closed, so this card can no longer change. If the read published a model, your answers are in it: open Model to see them.';
6461
7170
 
7171
+ const heightSourceScope = (entry, key = 'bulk') => `h:${JSON.stringify([entry.chatId, entry.requestId, entry.questionId, key])}`;
7172
+ function heightSourceBelongs(entry, scope) {
7173
+ try {
7174
+ if (typeof scope !== 'string' || !scope.startsWith('h:[')) return false;
7175
+ const identity = JSON.parse(scope.slice(2));
7176
+ return Array.isArray(identity) && identity.length === 4 && identity[0] === entry.chatId && identity[1] === entry.requestId
7177
+ && identity[2] === entry.questionId && typeof identity[3] === 'string';
7178
+ } catch { return false; }
7179
+ }
7180
+ // Legacy scopes carry no chat/read identity. Translate them ONLY from this entry's already-scoped storage envelope.
7181
+ function restoredHeightSourceScope(entry, scope) {
7182
+ if (heightSourceBelongs(entry, scope)) return scope;
7183
+ if (scope === `hb:${entry.questionId}`) return heightSourceScope(entry);
7184
+ const prefix = `h:${entry.questionId}:`;
7185
+ return typeof scope === 'string' && scope.startsWith(prefix) ? heightSourceScope(entry, scope.slice(prefix.length)) : null;
7186
+ }
7187
+ const mergeHeightClarification = (origin, addition) => origin && addition && (origin === addition || origin.endsWith(`\n\n${addition}`)) ? origin : origin && addition ? `${origin}\n\n${addition}` : (addition || origin || '');
7188
+ const heightDraftFileIds = new WeakMap(); let heightDraftFileN = 0;
7189
+ const heightDraftFileId = (file) => { if (!heightDraftFileIds.has(file)) heightDraftFileIds.set(file, ++heightDraftFileN); return heightDraftFileIds.get(file); };
7190
+ function heightDraftSnapshot(entry, scope, draftKey) {
7191
+ const source = answerSources.get(scope);
7192
+ const draft = entry.slotDrafts?.get(draftKey)?.rows[0];
7193
+ return JSON.stringify([source?.note || '', (source?.files || []).map((file) => file.attachmentId).sort(), draft ? [draft.other, draft.choices, draft.reason, draft.otherOpen] : null, (source?.failedUploads || []).map(heightDraftFileId), source?.uploading || 0]);
7194
+ }
7195
+ function reconcileHeightSubmission(entry) {
7196
+ if (!entry.failedSubmission || !entry.view) return;
7197
+ const same = entry.failedSubmission.every((input) => {
7198
+ const row = entry.view.ends.find((item) => heightEndKey(item) === heightEndKey(input));
7199
+ const answer = row?.answer;
7200
+ return answer && answer.how === (input.action === 'type' ? 'typed' : input.action === 'confirm' ? 'confirmed' : 'evidence')
7201
+ && (input.action !== 'type' || answer.typed === input.typed.trim())
7202
+ && (input.action !== 'confirm' || answer.value === input.shown)
7203
+ && (answer.note || '') === input.expectedNote
7204
+ && JSON.stringify((answer.evidence || []).map((file) => file.attachmentId).sort()) === JSON.stringify(input.expectedFiles);
7205
+ });
7206
+ if (!same) {
7207
+ for (const input of entry.failedSubmission) entry.changing.add(heightEndKey(input));
7208
+ return;
7209
+ }
7210
+ let newer = false;
7211
+ const unchanged = new Map(entry.failedSubmission.map((input) => [input, heightDraftSnapshot(entry, input.scope, input.draftKey) === input.draftSnapshot]));
7212
+ for (const input of entry.failedSubmission) {
7213
+ const key = heightEndKey(input);
7214
+ if (!unchanged.get(input)) {
7215
+ newer = true; entry.changing.add(key);
7216
+ continue;
7217
+ }
7218
+ entry.changing.delete(key); entry.drafts.delete(key); entry.slotDrafts?.delete(input.draftKey); clearAnswerSource(input.scope);
7219
+ }
7220
+ entry.failedSubmission = null; entry.saveFailed = false; entry.rowErrors.clear();
7221
+ entry.cardError = newer ? 'Your earlier answer was saved. Your newer edits and files are kept here; submit them when ready.' : '';
7222
+ if (!newer) entry.activeItem = null;
7223
+ }
6462
7224
  function loadHeightQuestion(entry) {
6463
7225
  if (entry.loading) return;
7226
+ entry.checkedAt = Date.now();
6464
7227
  entry.loading = true;
6465
7228
  request(`/api/chat/height-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}?${new URLSearchParams({ chatId: entry.chatId || '' })}`)
6466
7229
  .then((result) => {
6467
- if (result?.readClosed) { entry.finished = true; entry.view = null; } else entry.view = result.question;
7230
+ if (result.question && (result.question.revision || 0) < (entry.view?.revision || 0)) return;
7231
+ for (const row of result.question?.ends || []) {
7232
+ const prior = entry.view?.ends?.find((old) => heightEndKey(old) === heightEndKey(row));
7233
+ if (row.lifecycleRevision !== prior?.lifecycleRevision) entry.changing.delete(heightEndKey(row));
7234
+ }
7235
+ if (result?.readClosed) { entry.finished = true; if (entry.view) entry.view = { ...entry.view, open: false, readRemoved: true }; } else entry.view = result.question;
7236
+ if (entry.view) checkHeightDraftPictures(entry);
6468
7237
  entry.loadError = '';
7238
+ reconcileHeightSubmission(entry);
6469
7239
  // #1903: an existing member's "in the model" height is shown in the question's units, which needs
6470
7240
  // the shared helper; repaint once it has loaded.
6471
7241
  if (entry.view?.ends?.some((row) => row.inModel) && !displayUnitsModule) loadDisplayUnitsModule().then(() => repaintHeightCard(entry));
@@ -6478,19 +7248,27 @@
6478
7248
  }
6479
7249
 
6480
7250
  function repaintHeightCard(entry) {
7251
+ saveHeightDraft(entry);
6481
7252
  const old = ui.feed?.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
6482
7253
  if (!old) { drawingSlotRepaint(); return; }
6483
7254
  const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
6484
7255
  const caret = focused ? textCaret(document.activeElement) : null;
6485
7256
  const next = rememberCard(entry, paintHeightCard(entry, old.dataset.eventId, old.dataset.eventSequence), old.dataset.eventId, old.dataset.eventSequence);
6486
7257
  old.replaceWith(next);
7258
+ keepRowsScroll(next);
6487
7259
  if (focused) focusHeightControl(next, focused, caret);
6488
7260
  }
6489
7261
 
7262
+ /** A rebuilt card's list goes back where the person left it: only a shown list can scroll (paintEvents does the same). */
7263
+ function keepRowsScroll(card) {
7264
+ const list = card.querySelector('.ai-chat-height-rows');
7265
+ if (list && typeof list.keptScrollTop === 'number') list.scrollTop = list.keptScrollTop;
7266
+ }
7267
+
6490
7268
  /** The caret of a focused text field, or null (a radio or checkbox has none, and reading it can throw). */
6491
7269
  function textCaret(control) {
6492
7270
  try {
6493
- if (control?.tagName === 'INPUT' && (control.type === 'text' || !control.type) && typeof control.selectionStart === 'number') {
7271
+ if ((control?.tagName === 'TEXTAREA' || control?.tagName === 'INPUT' && (control.type === 'text' || !control.type)) && typeof control.selectionStart === 'number') {
6494
7272
  return { start: control.selectionStart, end: control.selectionEnd, direction: control.selectionDirection || 'none' };
6495
7273
  }
6496
7274
  } catch { /* no caret */ }
@@ -6502,7 +7280,7 @@
6502
7280
  if (!control) return false;
6503
7281
  control.focus({ preventScroll: true });
6504
7282
  // Text fields only: a radio or checkbox has no caret, and setSelectionRange on one throws (#1906).
6505
- if (control.tagName === 'INPUT' && (control.type === 'text' || !control.type)) {
7283
+ if (control.tagName === 'TEXTAREA' || control.tagName === 'INPUT' && (control.type === 'text' || !control.type)) {
6506
7284
  // Where the person's caret was, not the end: a repaint mid-word must not move it (#2163).
6507
7285
  if (caret) control.setSelectionRange?.(Math.min(caret.start, control.value.length), Math.min(caret.end, control.value.length), caret.direction);
6508
7286
  else control.setSelectionRange?.(control.value.length, control.value.length);
@@ -6513,10 +7291,13 @@
6513
7291
  function renderHeightQuestion(event) {
6514
7292
  const payload = event.payload || {};
6515
7293
  const entry = heightCardState(String(payload.requestId || ''), String(payload.questionId || ''), String(event.chatId || state.chat?.chatId || ''));
7294
+ const projectId = drawingEntryCurrent(entry) && state.scope?.owner?.kind === 'project' ? state.scope.owner.projectId : payload.projectId || (typeof chatProjectId === 'function' ? chatProjectId() : '');
7295
+ if (projectId) entry.projectId = String(projectId);
6516
7296
  if (!entry.view && !entry.loadError && !entry.finished) {
6517
7297
  if (!entry.loading) refreshEarlierCards(heightCards, entry, loadHeightQuestion);
6518
7298
  loadHeightQuestion(entry);
6519
7299
  }
7300
+ else if (entry.view?.open && !entry.busy && Date.now() - (entry.checkedAt || 0) > 5000) loadHeightQuestion(entry);
6520
7301
  return reusableCard(entry, event.eventId, String(event.sequence))
6521
7302
  || rememberCard(entry, paintHeightCard(entry, event.eventId, String(event.sequence)), event.eventId, String(event.sequence));
6522
7303
  }
@@ -6536,6 +7317,147 @@
6536
7317
  return paintDrawingHistory('height', entry, eventId, sequence);
6537
7318
  }
6538
7319
 
7320
+ /*
7321
+ * #2777: where on the drawings a height question means. FloLess outlined the drawing element the read took the end from
7322
+ * (or, for a member already in the model, the one the model was read from); the picture opens that sheet at the place,
7323
+ * whole sheet a press away. An end FloLess could not place says so, and nothing pretends a whole sheet is the spot.
7324
+ */
7325
+ /*
7326
+ * One picture at a time: only the answer step shows one, so only the current place's page is held. Moving to another
7327
+ * place lets the last one go; a load the person moved on from keeps nothing. (Review stop signal, operator 2026-10-26:
7328
+ * rebuilt from a many-picture cache whose eviction kept finding new ways to hold or drop bytes.)
7329
+ */
7330
+ let heightPlacePicture = null;
7331
+ const HEIGHT_PLACE_RETRY_MS = 15000;
7332
+ /** The server's own answer about the place (it changed, its drawing is gone, the link is wrong): shown, not retried. */
7333
+ const HEIGHT_PLACE_FINAL = new Set([400, 404, 409, 413, 415]);
7334
+ const heightPlaceUrl = (entry, row) => `/api/chat/height-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}/place?${new URLSearchParams({ memberId: row.memberId, end: String(row.end), digest: row.placeDigest, chatId: entry.chatId || '' })}`;
7335
+ const heightPlaced = (row) => Boolean(row.place && row.placeDigest);
7336
+ const heightUnplacedText = (row) => (row.unplaced ? `Not placed on the drawings: ${row.unplaced}` : 'The read did not say where on the drawings it read this end.');
7337
+ function openHeightPlace(entry, row, opener) {
7338
+ const place = row.place;
7339
+ return openDrawingPlace(place, {
7340
+ title: `${row.label} on ${place.sheet}`, opener, url: heightPlaceUrl(entry, row),
7341
+ note: `FloLess outlined, on page ${place.page} of ${place.sheet}, the drawing element ${place.by === 'model' ? 'this member was read from' : 'the read took this height from'}. It shows where to look, not that the height is right.`,
7342
+ commands: { close: 'shell.chat-height-place-close', view: 'shell.chat-height-place-view' },
7343
+ again: { label: 'Reload the height card', commandId: 'shell.chat-height-place-again', run: () => loadHeightQuestion(entry) },
7344
+ filter: { projectId: chatProjectId(), commandId: 'shell.chat-place-open-filter' },
7345
+ });
7346
+ }
7347
+ /** The picture of the place, fetched once per place the card showed (its digest), shared by every repaint of the card. */
7348
+ function paintHeightPlacePicture(entry, row, frame) {
7349
+ paintPlacePicture({ digest: row.placeDigest, url: heightPlaceUrl(entry, row), place: row.place }, frame);
7350
+ }
7351
+ /**
7352
+ * The answer step's place picture (#2777), for the height card and the setup card alike. One slot: only one answer step
7353
+ * is on screen, so only its picture is held; a place the card no longer shows lets go of the one before.
7354
+ */
7355
+ function paintPlacePicture({ digest, url, place }, frame) {
7356
+ const paint = (target, record) => {
7357
+ target.dataset.state = record.state;
7358
+ target.setAttribute('aria-busy', String(record.state === 'loading'));
7359
+ target.replaceChildren();
7360
+ if (record.state === 'ready') {
7361
+ const crop = evidenceCrop(place);
7362
+ const image = Object.assign(document.createElement('img'), { src: record.url, alt: '' });
7363
+ Object.assign(image.style, { width: `${(crop.pageW / crop.w) * 100}%`, left: `${(-(crop.x0 - crop.px0) / crop.w) * 100}%`, top: `${(-(crop.y0 - crop.py0) / crop.h) * 100}%` });
7364
+ target.append(image);
7365
+ } else if (record.state === 'error') {
7366
+ target.append(Object.assign(document.createElement('span'), { className: 'ai-chat-height-place-missing', textContent: record.said }));
7367
+ }
7368
+ };
7369
+ const unavailable = 'Preview unavailable just now. Opening the sheet may still work.';
7370
+ let record = heightPlacePicture;
7371
+ const retry = record?.digest === digest && record.state === 'error' && record.retryAt && Date.now() >= record.retryAt;
7372
+ if (!record || record.digest !== digest || retry) {
7373
+ if (record?.url) URL.revokeObjectURL(record.url);
7374
+ record = heightPlacePicture = { digest, state: 'loading', frame: null };
7375
+ const loading = record;
7376
+ const current = () => heightPlacePicture === loading;
7377
+ fetch(url, { credentials: 'same-origin', cache: 'no-store' })
7378
+ .then(async (response) => {
7379
+ if (!current()) return;
7380
+ if (response.ok) {
7381
+ const bytes = await response.blob();
7382
+ if (current()) Object.assign(loading, { url: URL.createObjectURL(bytes), state: 'ready' });
7383
+ return;
7384
+ }
7385
+ const said = await response.json().catch(() => null);
7386
+ Object.assign(loading, { state: 'error' }, HEIGHT_PLACE_FINAL.has(response.status)
7387
+ ? { said: typeof said?.error === 'string' && said.error ? said.error : 'FloLess could not show this place on the drawings.' }
7388
+ : { said: unavailable, retryAt: Date.now() + HEIGHT_PLACE_RETRY_MS });
7389
+ })
7390
+ .catch((error) => {
7391
+ console.warn('[chat] the picture of a question\'s place on the drawings could not be loaded', error);
7392
+ if (current()) Object.assign(loading, { state: 'error', said: unavailable, retryAt: Date.now() + HEIGHT_PLACE_RETRY_MS });
7393
+ })
7394
+ .finally(() => { if (current() && loading.frame?.isConnected) paint(loading.frame, loading); loading.frame = null; });
7395
+ }
7396
+ // Only the frame painted last waits for the picture: an earlier paint's frame is no longer on screen.
7397
+ if (record.state === 'loading') record.frame = frame;
7398
+ paint(frame, record);
7399
+ }
7400
+ /** The answer step's picture: the cropped sheet with the place outlined, one button that opens it; or why there is none. */
7401
+ function heightPlaceFigure(entry, row) {
7402
+ if (!heightPlaced(row)) return Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-ask-context ai-chat-height-unplaced', textContent: heightUnplacedText(row) });
7403
+ const open = button('', `shell.chat-height-open-place#${entry.questionId} ${row.memberId} ${row.endWord}`, 'ai-chat-height-place');
7404
+ open.dataset.commandInstanceLabel = `${row.label} on ${row.place.sheet}`;
7405
+ open.setAttribute('aria-label', `Open sheet ${row.place.sheet} at ${row.label}`);
7406
+ open.dataset.tip = `Opens sheet ${row.place.sheet} with this place outlined`;
7407
+ const crop = evidenceCrop(row.place);
7408
+ const frame = document.createElement('span'); frame.className = 'ai-chat-height-place-frame';
7409
+ // Shaped like the crop, never taller than a short picture: narrowed, not squashed, so the drawing stays true.
7410
+ frame.style.aspectRatio = `${crop.w} / ${crop.h}`;
7411
+ frame.style.width = `min(100%, calc(110px * ${crop.w / crop.h}))`;
7412
+ const caption = document.createElement('span'); caption.className = 'ai-chat-height-place-caption';
7413
+ caption.append(Object.assign(document.createElement('strong'), { textContent: 'Open on sheet' }),
7414
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-sheet', textContent: `${row.place.sheet} · page ${row.place.page}` }),
7415
+ Object.assign(document.createElement('span'), { textContent: row.place.by === 'model' ? 'FloLess outlined where this member was read' : 'FloLess outlined where the read took this height' }));
7416
+ open.append(frame, caption);
7417
+ open.addEventListener('click', () => openHeightPlace(entry, row, open));
7418
+ paintHeightPlacePicture(entry, row, frame);
7419
+ return open;
7420
+ }
7421
+ /** A row's sheet, as a small button in the card's list: the same place, no picture, so a long list stays short. */
7422
+ function heightPlaceChip(entry, row, phase = null) {
7423
+ if (!heightPlaced(row)) return null;
7424
+ const command = phase ? `shell.chat-height-batch-place#${entry.questionId} ${phase} ${row.memberId} ${row.endWord}` : `shell.chat-height-row-place#${entry.questionId} ${row.memberId} ${row.endWord}`;
7425
+ const chip = button(phase ? 'Show on drawing' : row.place.sheet, command, 'ai-chat-height-sheet');
7426
+ chip.dataset.commandInstanceLabel = `${row.label}${phase ? ` · ${heightEndWord(row)}` : ''} on ${row.place.sheet}`;
7427
+ chip.setAttribute('aria-label', phase ? `Show ${row.label} · ${heightEndWord(row)} on sheet ${row.place.sheet}` : `Open sheet ${row.place.sheet} at ${row.label}`);
7428
+ chip.dataset.tip = `Opens sheet ${row.place.sheet} with this place outlined`;
7429
+ chip.addEventListener('click', () => openHeightPlace(entry, row, chip));
7430
+ return chip;
7431
+ }
7432
+ /** Grouped answers keep every end's own place beside its label; drawing bytes load only when its button is pressed. */
7433
+ function heightBatchPlaces(entry, rows, phase, descriptions = []) {
7434
+ const list = document.createElement('ol'); list.className = 'ai-chat-height-rows ai-chat-height-batch-places';
7435
+ list.setAttribute('aria-label', 'Member ends on the drawings');
7436
+ rows.forEach((row, index) => {
7437
+ const item = document.createElement('li'); item.className = 'ai-chat-height-row';
7438
+ const line = document.createElement('div'); line.className = 'ai-chat-height-labelline';
7439
+ line.append(Object.assign(document.createElement('span'), { className: 'ai-chat-height-label', textContent: `${row.label} · ${heightEndWord(row)}` }));
7440
+ const chip = heightPlaceChip(entry, row, phase); if (chip) line.append(chip);
7441
+ item.append(line);
7442
+ if (descriptions[index]) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-ask-context', textContent: descriptions[index] }));
7443
+ const context = row.place ? `${row.place.sheet} · page ${row.place.page}` : '';
7444
+ item.append(Object.assign(document.createElement('span'), { className: 'ai-chat-height-meta',
7445
+ textContent: heightPlaced(row) ? context : [context, heightUnplacedText(row)].filter(Boolean).join(' · ') }));
7446
+ list.append(item);
7447
+ });
7448
+ return list;
7449
+ }
7450
+ /** #2774: where a proposed height came from, in the option's own words. A derived one is an assumption and says how. */
7451
+ function heightProposalWords(proposed) {
7452
+ // #2802: an elevation printed on the sheet and measured from a datum shows the conversion, so the person confirms it.
7453
+ const datum = proposed.datum ? ` (${proposed.asRead} on ${proposed.datum.name} = ${proposed.datum.asDrawn}, world ${proposed.datum.worldZMm} mm, is ${proposed.value} mm)` : '';
7454
+ if (proposed.how === 'derived') return { description: `Derived, an assumption: ${proposed.basis}${datum}`, tag: 'DERIVED' };
7455
+ if (proposed.how === 'measured') return { description: `Measured on the drawings${proposed.basis ? `: ${proposed.basis}` : ''}${datum}`, tag: 'MEASURED' };
7456
+ if (proposed.how === 'read') return { description: `Read off the drawings${proposed.basis ? `: ${proposed.basis}` : ''}${datum}` };
7457
+ return { description: `Use the value proposed for this member end${datum}` };
7458
+ }
7459
+ const heightNoProposalText = (row) => `${row.noProposal ? `No height proposed: ${row.noProposal}` : 'The read proposed no height and gave no reason.'}${!row.lifecycle?.investigation ? ' No source checks recorded.' : ''}`;
7460
+
6539
7461
  function paintHeightRow(entry, row, open) {
6540
7462
  const key = heightEndKey(row);
6541
7463
  const item = document.createElement('li'); item.className = 'ai-chat-height-row';
@@ -6547,11 +7469,14 @@
6547
7469
  const label = document.createElement('div'); label.className = 'ai-chat-height-label'; label.textContent = row.label;
6548
7470
  label.dataset.tip = row.label;
6549
7471
  labelLine.append(label);
7472
+ const chip = heightPlaceChip(entry, row);
7473
+ if (chip) labelLine.append(chip);
6550
7474
  const meta = document.createElement('div'); meta.className = 'ai-chat-height-meta';
6551
7475
  // #1903: an existing member's PROFILE comes from the model, not from the read's label, so a label that
6552
7476
  // names the wrong member is visibly at odds with what the id really is.
6553
7477
  meta.textContent = [row.inModel?.profile, row.memberId, heightEndWord(row)].filter(Boolean).join(' · ');
6554
7478
  item.append(labelLine, meta);
7479
+ if (row.answer?.how === 'evidence' && row.lifecycle) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `${heightStateText(row)}. ${heightStudyText(row)}` }));
6555
7480
  if (row.inModel) {
6556
7481
  const inModel = document.createElement('div'); inModel.className = 'ai-chat-height-inmodel';
6557
7482
  inModel.textContent = `${heightInModelText(row.inModel, entry.view?.units)} ${HEIGHT_PROPOSED_TEXT}`;
@@ -6572,9 +7497,11 @@
6572
7497
  // #2167: a note with no picture and no height is honest about it: no height is claimed, the AI is asked to find it.
6573
7498
  const noteOnly = picture && !row.answer.evidence?.length;
6574
7499
  const text = document.createElement('span');
6575
- text.textContent = noteOnly ? 'Note sent. The read will look for the height.' : picture ? 'Waiting for the read to read your picture' : heightAnswerText(row.answer);
7500
+ text.textContent = picture && heightResponsibility(row) === 'needs-answer' ? 'Your earlier note or picture is kept. The read needs your answer now.'
7501
+ : picture && ['resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row)) ? 'Your earlier note or picture is kept as evidence. The status above explains how the question ended.'
7502
+ : picture ? 'Clarification saved. Height still unresolved; tell the read to work out a proposal.' : heightAnswerText(row.answer);
6576
7503
  done.append(glyph, text);
6577
- if (open) {
7504
+ if (open && !['resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row))) {
6578
7505
  const change = heightActionButton(picture ? 'Answer now' : 'Change', idFor('change'), instance, 'ai-chat-height-change', entry.busy ? 'A height is still being saved — wait for it to finish' : null);
6579
7506
  change.setAttribute('aria-label', picture ? `Answer the height for ${row.label} yourself instead` : `Change the height for ${row.label}`);
6580
7507
  change.addEventListener('click', () => {
@@ -6585,8 +7512,9 @@
6585
7512
  done.append(change);
6586
7513
  }
6587
7514
  item.append(done);
6588
- const source = paintAnsweredSource(entry.requestId, row.answer, sourceIdFor, instance);
7515
+ const source = paintAnsweredSource(entry.requestId, entry.view?.readRemoved ? { ...row.answer, evidence: [] } : row.answer, sourceIdFor, instance);
6589
7516
  if (source) item.append(source);
7517
+ if (entry.view?.readRemoved && row.answer.evidence?.length) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Pictures recorded with this answer: ${row.answer.evidence.map((file) => file.fileName).join(', ')}. This read is closed, so these pictures cannot be opened here. Review the saved model's answer evidence or your original files.` }));
6590
7518
  return item;
6591
7519
  }
6592
7520
  if (!open) {
@@ -6608,11 +7536,24 @@
6608
7536
  const ownedSlot = drawingEntryCurrent(entry) && ui.approvalTray?.querySelector('.ai-chat-drawing-step')?.dataset.drawingStep;
6609
7537
  const ownedNode = ownedSlot ? ui.approvalTray.querySelector('.ai-chat-drawing-step') : null;
6610
7538
  const pendingFocusId = ownedNode?.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
6611
- const failedField = ownedNode && ([...ownedNode.querySelectorAll('input')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
7539
+ const failedField = ownedNode && ([...ownedNode.querySelectorAll('input, textarea')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
6612
7540
  const failedFieldId = failedField?.dataset.commandId, failedCaret = failedField ? textCaret(failedField) : null;
6613
7541
  let saved = false;
6614
- const scopeOf = (answer) => sharedScope || `h:${entry.questionId}:${heightEndKey(answer)}`;
7542
+ const scopeOf = (answer) => sharedScope || heightSourceScope(entry, heightEndKey(answer));
6615
7543
  const withSource = answers.map((answer) => ({ ...answer, ...answerSourcePayload(scopeOf(answer)) }));
7544
+ const unfinished = answers.map((answer) => answerSources.get(scopeOf(answer))).find((source) => source?.uploading || source?.failedUploads?.length);
7545
+ if (unfinished) {
7546
+ const message = unfinished.uploading ? 'A file is still uploading. Your answer is kept; wait for it to finish, then Submit.' : 'A selected file was not uploaded. Retry its upload or choose Leave out next to that file, then Submit. Your answer and file are kept until you decide.';
7547
+ if (rowKey) entry.rowErrors.set(rowKey, message); else entry.cardError = message; repaintHeightCard(entry); return false;
7548
+ }
7549
+ if (withSource.some((answer) => answer.note?.length > MAX_HEIGHT_CLARIFICATION)) {
7550
+ const message = 'Your clarification is longer than 8,000 characters. Your full draft and files are kept. Keep a copy and shorten it, or send additional context in chat; chat context does not confirm a height.';
7551
+ if (rowKey) entry.rowErrors.set(rowKey, message); else entry.cardError = message; repaintHeightCard(entry); return false;
7552
+ }
7553
+ const submissionDrafts = new Map(withSource.map((input) => {
7554
+ const scope = scopeOf(input), draftKey = sharedScope ? 'batch-value' : heightEndKey(input);
7555
+ return [heightEndKey(input), { draftKey, draftSnapshot: heightDraftSnapshot(entry, scope, draftKey) }];
7556
+ }));
6616
7557
  entry.busy = true; entry.cardError = ''; if (rowKey) entry.rowErrors.delete(rowKey);
6617
7558
  repaintHeightCard(entry);
6618
7559
  try {
@@ -6623,16 +7564,17 @@
6623
7564
  ...withSource.flatMap((answer) => answer.evidence || []),
6624
7565
  ...[entry.view, result.question].flatMap((view) => (view?.ends || []).flatMap((row) => [...row.answer?.evidence || [], ...row.inherited || []])).map((ref) => ref.attachmentId),
6625
7566
  ]);
6626
- entry.view = result.question;
7567
+ if ((result.question?.revision || 0) >= (entry.view?.revision || 0)) entry.view = result.question;
6627
7568
  // Answering on the card means the person is on it: a message sent while its save kept failing does not fold it now.
6628
- saved = true; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
7569
+ saved = true; entry.failedSubmission = null; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
6629
7570
  for (const answer of answers) {
6630
7571
  const key = heightEndKey(answer);
7572
+ if (result.question?.ends?.find((row) => heightEndKey(row) === key)?.answer) entry.slotDrafts?.delete(key);
6631
7573
  entry.changing.delete(key); entry.drafts.delete(key); entry.selected.delete(key);
6632
7574
  if (entry.activeItem === key) { entry.activeItem = null; entry.reopenedAt = 0; }
6633
7575
  clearAnswerSource(scopeOf(answer));
6634
7576
  if (sharedScope) {
6635
- const rowScope = `h:${entry.questionId}:${key}`, source = answerSources.get(rowScope);
7577
+ const rowScope = heightSourceScope(entry, key), source = answerSources.get(rowScope);
6636
7578
  if (source) {
6637
7579
  source.note = '';
6638
7580
  for (const file of [...source.files]) {
@@ -6657,10 +7599,16 @@
6657
7599
  }
6658
7600
  if (sharedScope) entry.bulkDraft = '';
6659
7601
  } catch (error) {
6660
- let message = heightErrorText(error, 'FloLess could not save this height. Try again.');
7602
+ let message = heightErrorText(error, 'FloLess could not confirm that this answer was saved because the connection was interrupted. Your draft and files are kept. Submit again to check and retry.');
6661
7603
  if (error?.code === 'answer-evidence-unknown') message = dropStaleAnswerFiles([...new Set(answers.map(scopeOf))], entry);
6662
7604
  // A failed save, apart from the card's other notices: the hidden line says so and the card never hides by itself.
6663
7605
  entry.saveFailed = true;
7606
+ entry.failedSubmission = withSource.map((input) => {
7607
+ const row = entry.view?.ends.find((item) => heightEndKey(item) === heightEndKey(input));
7608
+ const origin = row?.answer?.note || row?.inheritedNote, addition = input.note;
7609
+ return { ...input, ...submissionDrafts.get(heightEndKey(input)), scope: scopeOf(input), expectedNote: mergeHeightClarification(origin, addition),
7610
+ expectedFiles: [...new Set([...(input.evidence || []), ...(row?.inherited || []).map((file) => file.attachmentId)])].sort() };
7611
+ });
6664
7612
  // Dropped, not kept: a reload that fails must show its own error and Try again, which only an
6665
7613
  // empty card does — an old view would hide both behind rows that are out of date.
6666
7614
  if (HEIGHT_STALE.has(error?.code)) { entry.cardError = message; entry.view = null; loadHeightQuestion(entry); }
@@ -6703,6 +7651,7 @@
6703
7651
  return at < CARD_ORDINALS.length ? `the ${CARD_ORDINALS[at]} ${noun}` : `${noun} ${at + 1} of ${keys.length}`;
6704
7652
  }
6705
7653
  const heightTellText = (entry) => `I've answered ${cardPlace(entry, 'data-height-question', 'height card')}.`;
7654
+ const heightClarificationText = (entry) => `I saved clarification on ${cardPlace(entry, 'data-height-question', 'height card')}. Please read the saved explanation and attachments and work out a proposal; the height is still unresolved.`;
6706
7655
  const setupTellText = (entry) => `I've answered ${cardPlace(entry, 'data-setup-question', 'read setup card')}.`;
6707
7656
 
6708
7657
  /*
@@ -6731,17 +7680,18 @@
6731
7680
 
6732
7681
  function answerSource(scope) {
6733
7682
  let source = answerSources.get(scope);
6734
- if (!source) { source = { open: false, note: '', files: [], uploading: 0, error: '' }; answerSources.set(scope, source); }
7683
+ if (!source) { source = { open: false, note: '', files: [], failedUploads: [], uploading: 0, error: '' }; answerSources.set(scope, source); }
6735
7684
  return source;
6736
7685
  }
6737
7686
  /** What an answer carries from its source box: the note and the uploaded files' ids. */
6738
7687
  function answerSourcePayload(scope) {
6739
7688
  const source = answerSources.get(scope);
6740
7689
  if (!source) return {};
6741
- const note = source.note.trim();
7690
+ const note = scope.startsWith('h:') ? (source.note.trim() ? source.note : '') : source.note.trim();
6742
7691
  return { ...(note ? { note } : {}), ...(source.files.length ? { evidence: source.files.map((file) => file.attachmentId) } : {}) };
6743
7692
  }
6744
7693
  const MAX_ANSWER_NOTE = 160;
7694
+ const MAX_HEIGHT_CLARIFICATION = 8000;
6745
7695
  // #2167: asked for nothing at all. Said plainly, with the three things that would count.
6746
7696
  const NO_HEIGHT_NO_SOURCE = 'Type a height, or add a note or a picture and the AI will work it out.';
6747
7697
  /** True when the source box holds a note or an attached picture the person could send instead of a height. */
@@ -6784,6 +7734,7 @@
6784
7734
  }
6785
7735
  for (const file of incoming) {
6786
7736
  if (answerSources.get(scope) !== source) break;
7737
+ source.failedUploads = (source.failedUploads || []).filter((held) => held !== file);
6787
7738
  source.uploading += 1; ctx.repaint();
6788
7739
  try {
6789
7740
  const data = await fileBase64(file);
@@ -6804,9 +7755,12 @@
6804
7755
  }
6805
7756
  source.files.push({ ...ref, url: file.type.startsWith('image/') ? URL.createObjectURL(file) : '' });
6806
7757
  } catch (error) {
6807
- source.error = error?.message || `FloLess could not attach “${file.name}”. Try again.`;
7758
+ if (!(source.failedUploads || []).includes(file)) (source.failedUploads ??= []).push(file);
7759
+ source.error = heightErrorText(error, `FloLess could not upload “${file.name}” because the connection was interrupted. Your answer and file are kept here. Retry the upload.`);
6808
7760
  } finally {
6809
- source.uploading -= 1; ctx.repaint();
7761
+ source.uploading -= 1;
7762
+ if (source.failedUploads?.length) source.error = 'A selected file was not uploaded. Retry its upload or choose Leave out next to it, then Submit. Your answer and file are kept until you decide.';
7763
+ ctx.repaint();
6810
7764
  }
6811
7765
  }
6812
7766
  }
@@ -6872,11 +7826,11 @@
6872
7826
  }
6873
7827
 
6874
7828
  /** One recorded picture as a chip: thumbnail for a picture, its name, and a button that opens it. */
6875
- function answerPictureChip(requestId, ref, commandId, instance) {
7829
+ function answerPictureChip(requestId, ref, commandId, instance, pictureUrl = evidenceUrl(requestId, ref.attachmentId)) {
6876
7830
  const chip = document.createElement('span'); chip.className = 'ai-chat-attachment ai-chat-answer-picture';
6877
7831
  if (ref.mediaType.startsWith('image/')) {
6878
7832
  const preview = document.createElement('img'); preview.alt = ''; preview.loading = 'lazy';
6879
- preview.src = evidenceUrl(requestId, ref.attachmentId);
7833
+ preview.src = pictureUrl;
6880
7834
  // A picture the browser cannot show becomes the server's reason, never a broken image (review #1906).
6881
7835
  preview.addEventListener('error', () => {
6882
7836
  const slot = Object.assign(document.createElement('span'), { className: 'ai-chat-answer-missing', textContent: 'checking…' });
@@ -6890,7 +7844,7 @@
6890
7844
  open.dataset.commandInstanceLabel = instance;
6891
7845
  open.dataset.tip = `Open ${ref.fileName}`;
6892
7846
  open.setAttribute('aria-label', `Open ${ref.fileName}`);
6893
- open.addEventListener('click', () => { window.open(evidenceUrl(requestId, ref.attachmentId), '_blank', 'noopener'); });
7847
+ open.addEventListener('click', () => { window.open(pictureUrl, '_blank', 'noopener'); });
6894
7848
  chip.append(open);
6895
7849
  return chip;
6896
7850
  }
@@ -6903,12 +7857,24 @@
6903
7857
  function paintAnswerSource(scope, ctx) {
6904
7858
  const source = answerSource(scope);
6905
7859
  const wrap = document.createElement('div'); wrap.className = 'ai-chat-answer-source';
7860
+ if (ctx.inheritedNote) wrap.append(Object.assign(document.createElement('p'), { className: 'ai-chat-answer-lead ai-chat-inherited-clarification', textContent: `Your earlier clarification: ${ctx.inheritedNote}` }));
6906
7861
  if (ctx.inherited?.length) {
6907
7862
  const kept = document.createElement('div'); kept.className = 'ai-chat-answer-files';
6908
7863
  const lead = document.createElement('span'); lead.className = 'ai-chat-answer-lead'; lead.textContent = 'Your picture';
6909
7864
  kept.append(lead, ...ctx.inherited.map((ref) => answerPictureChip(ctx.requestId, ref, ctx.idFor('picture-open', ref.attachmentId), ctx.instance)));
6910
7865
  wrap.append(kept);
6911
7866
  }
7867
+ for (const file of source.failedUploads || []) {
7868
+ const retry = button(`Retry upload: ${file.name}`, ctx.idFor('attach', `retry ${file.name}`), 'ai-chat-answer-add');
7869
+ retry.dataset.commandInstanceLabel = ctx.instance;
7870
+ if (ctx.busyReason || source.uploading) { const why = ctx.busyReason || 'Wait for the current upload to finish'; retry.setAttribute('aria-disabled', 'true'); retry.dataset.blockedReason = why; retry.dataset.tip = why; }
7871
+ retry.addEventListener('click', () => { if (retry.getAttribute('aria-disabled') !== 'true') attachAnswerFiles(scope, ctx, [file]); });
7872
+ const omit = button(`Leave out ${file.name}`, ctx.idFor('picture-remove', `failed ${file.name}`), 'ai-chat-answer-add');
7873
+ omit.dataset.commandInstanceLabel = ctx.instance; omit.setAttribute('aria-label', `Leave out the file ${file.name} that was not uploaded`);
7874
+ if (ctx.busyReason || source.uploading) { const why = ctx.busyReason || 'Wait for the current upload to finish'; omit.setAttribute('aria-disabled', 'true'); omit.dataset.blockedReason = why; omit.dataset.tip = why; }
7875
+ omit.addEventListener('click', () => { if (omit.getAttribute('aria-disabled') === 'true') return; source.failedUploads = source.failedUploads.filter((held) => held !== file); if (!source.failedUploads.length) source.error = ''; ctx.repaint(); });
7876
+ wrap.append(retry, omit);
7877
+ }
6912
7878
  const hasDraft = ctx.alwaysOpen || source.open || source.note || source.files.length || source.uploading;
6913
7879
  if (!hasDraft) {
6914
7880
  const add = button('+ Add source', ctx.idFor('source'), 'ai-chat-answer-add');
@@ -6924,13 +7890,24 @@
6924
7890
  }
6925
7891
  const box = document.createElement('div'); box.className = 'ai-chat-answer-box';
6926
7892
  const line = document.createElement('div'); line.className = 'ai-chat-answer-line';
6927
- const note = document.createElement('input');
6928
- note.type = 'text'; note.className = 'ai-chat-height-input ai-chat-answer-note'; note.maxLength = 160; note.autocomplete = 'off';
6929
- note.placeholder = 'Source, e.g. per 7/S-502 (optional)';
7893
+ const note = document.createElement(ctx.clarification ? 'textarea' : 'input');
7894
+ if (ctx.clarification) { note.rows = 4; wrap.classList.add('ai-chat-answer-clarification'); }
7895
+ else { note.type = 'text'; note.maxLength = 160; }
7896
+ note.className = `ai-chat-height-input ai-chat-answer-note${ctx.clarification ? ' ai-chat-answer-clarification' : ''}`; note.autocomplete = 'off';
7897
+ note.placeholder = ctx.clarification ? 'Use the stair landing level shown in this detail; the hanger sits on it.' : 'Source, e.g. per 7/S-502 (optional)';
6930
7898
  note.dataset.commandId = ctx.idFor('note'); note.dataset.commandInstanceLabel = ctx.instance;
6931
- note.setAttribute('aria-label', `Source note for ${ctx.label}`);
7899
+ note.setAttribute('aria-label', `${ctx.clarification ? 'Explain what to use' : 'Source note'} for ${ctx.label}`);
6932
7900
  note.value = source.note;
6933
7901
  if (ctx.busyReason) { note.readOnly = true; note.setAttribute('aria-disabled', 'true'); note.dataset.blockedReason = ctx.busyReason; note.dataset.tip = ctx.busyReason; }
7902
+ let counter;
7903
+ if (ctx.clarification) {
7904
+ const heading = Object.assign(document.createElement('label'), { className: 'ai-chat-answer-lead', textContent: 'Explain what to use (optional)' });
7905
+ note.id = `clarification-${encodeURIComponent(scope)}`; heading.htmlFor = note.id; box.append(heading);
7906
+ counter = Object.assign(document.createElement('p'), { className: 'ai-chat-answer-lead' });
7907
+ note.setAttribute('aria-describedby', `${note.id}-limit`); counter.id = `${note.id}-limit`;
7908
+ const count = () => { counter.textContent = `${note.value.length.toLocaleString()} / 8,000 characters. Without a Height, this saves clarification for the read; the height stays unresolved.`; note.setAttribute('aria-invalid', String(note.value.length > MAX_HEIGHT_CLARIFICATION)); };
7909
+ note.addEventListener('input', count); count();
7910
+ }
6934
7911
  note.addEventListener('input', () => { source.note = note.value; ctx.onDraftChange?.(); });
6935
7912
  const clip = document.createElement('button');
6936
7913
  clip.type = 'button'; clip.className = 'ai-chat-answer-clip';
@@ -6952,6 +7929,7 @@
6952
7929
  }
6953
7930
  line.append(note, clip, picker);
6954
7931
  box.append(line);
7932
+ if (counter) box.append(counter);
6955
7933
  // Paste and drop, like the composer: a screenshot pasted while this box has focus attaches to the answer.
6956
7934
  box.addEventListener('paste', (event) => {
6957
7935
  if (ctx.busyReason) return;
@@ -7092,11 +8070,14 @@
7092
8070
  function drawingRowOpen(kind, entry, row) {
7093
8071
  if (!entry.view?.open || row.status === 'superseded' || row.frozen) return false;
7094
8072
  const key = drawingRowKey(kind, row);
8073
+ if (kind === 'height' && ['resolved-from-drawings', 'no-longer-needed', 'replaced'].includes(heightResponsibility(row))) return false;
7095
8074
  if (entry.changing.has(key)) return true;
7096
- return kind === 'setup' ? row.status === 'open' : !row.answer;
8075
+ if (kind === 'height' && heightResponsibility(row) === 'investigating') return false;
8076
+ return kind === 'setup' ? row.status === 'open' : !row.answer || ['needs-answer', 'proposal'].includes(heightResponsibility(row));
7097
8077
  }
7098
8078
  function drawingEntryCurrent(entry) { return entry.chatId === state.chat?.chatId; }
7099
8079
  function drawingSlotRepaint() {
8080
+ for (const entry of heightCards.values()) saveHeightDraft(entry);
7100
8081
  paintDrawingQuestionSlot();
7101
8082
  }
7102
8083
  /*
@@ -7208,9 +8189,10 @@
7208
8189
  function reopenDrawingItem(kind, entry, key) {
7209
8190
  const row = drawingRows(kind, entry).find((row) => drawingRowKey(kind, row) === key);
7210
8191
  if (entry.busy || !entry.view?.open || !row || row.frozen || row.status === 'superseded') return;
8192
+ if (kind === 'height' && ['resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row))) return;
7211
8193
  showDrawingSlot(entry.chatId);
7212
8194
  entry.changing.add(key); entry.activeItem = key; entry.finishActive = false; entry.reopenedAt = (state.drawingActivationOrder = (state.drawingActivationOrder || 0) + 1);
7213
- if (row.answer?.note && row.answer.how !== 'none') { const source = answerSource(`${kind === 'setup' ? 's' : 'h'}:${entry.questionId}:${key}`); source.open = true; source.note ||= row.answer.note; }
8195
+ if (kind === 'setup' && row.answer?.note && row.answer.how !== 'none') { const source = answerSource((kind === 'setup' ? `s:${entry.questionId}:${key}` : heightSourceScope(entry, key))); source.open = true; source.note ||= row.answer.note; }
7214
8196
  entry.slotPhase = 'row';
7215
8197
  (kind === 'setup' ? repaintSetupCard : repaintHeightCard)(entry);
7216
8198
  drawingSlotRepaint();
@@ -7227,14 +8209,24 @@
7227
8209
  const answered = live.filter((row) => row.answer);
7228
8210
  const settled = kind === 'setup' ? live.filter(setupSettled).length : live.filter((row) => row.status === 'confirmed' || row.status === 'typed').length;
7229
8211
  const allAnswered = live.length > 0 && answered.length === live.length;
8212
+ const heightStates = kind === 'height' ? live.map(heightResponsibility) : [];
8213
+ const unresolved = heightStates.filter((s) => ['needs-answer', 'proposal', 'investigating'].includes(s));
7230
8214
  card.dataset.state = !entry.view ? (entry.finished ? 'closed' : 'loading') : !entry.view.open ? 'closed'
7231
8215
  : allAnswered ? (settled === live.length ? 'answered' : 'waiting-for-read') : 'open';
8216
+ if (kind === 'height' && entry.view) card.dataset.state = !live.length ? 'replaced' : settled === live.length ? 'answered'
8217
+ : !entry.view.open && unresolved.length ? 'closed-unresolved' : !unresolved.length ? 'resolved'
8218
+ : heightStates.includes('needs-answer') ? 'needs-answer' : heightStates.includes('proposal') ? 'proposal' : 'investigating';
7232
8219
  // #2678: a hidden card's line says what still waits: the person's answers, or the read.
7233
- const waits = { open: 'you', 'waiting-for-read': 'ai', answered: 'done', closed: 'done' }[card.dataset.state];
8220
+ const waits = { open: 'you', 'waiting-for-read': 'ai', answered: 'done', closed: 'done', replaced: 'done', resolved: 'done', investigating: 'ai', 'needs-answer': 'you', proposal: 'you', 'closed-unresolved': 'ai' }[card.dataset.state];
7234
8221
  if (waits) card.dataset.waits = waits;
8222
+ if (kind === 'height' && entry.view) {
8223
+ card.dataset.waitsSays = card.dataset.state === 'closed-unresolved' ? 'Read closed with unresolved heights. Open the model or start a new read to review them.'
8224
+ : live.length === 1 ? heightStateText(live[0]) : `${settled} answered · ${heightStates.filter((s) => s === 'investigating').length} AI investigating · ${heightStates.filter((s) => s === 'needs-answer' || s === 'proposal').length} need you${!live.length ? ' · Replaced by newer questions' : ''}`;
8225
+ if (['investigating', 'resolved', 'replaced', 'closed-unresolved'].includes(card.dataset.state)) card.dataset.autoFold = 'true';
8226
+ }
7235
8227
  const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
7236
8228
  const heading = document.createElement('strong'); heading.textContent = title;
7237
- const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state'; chip.textContent = card.dataset.state;
8229
+ const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state'; chip.textContent = ({ investigating: 'AI investigating', 'needs-answer': 'Needs your answer', proposal: 'Needs your confirmation', 'closed-unresolved': 'Closed · unresolved heights' })[card.dataset.state] || card.dataset.state;
7238
8230
  head.append(heading, chip); card.append(head);
7239
8231
  if (!entry.view) {
7240
8232
  const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
@@ -7246,16 +8238,21 @@
7246
8238
  }
7247
8239
  } else {
7248
8240
  const count = document.createElement('p'); count.className = 'ai-chat-height-count'; count.setAttribute('aria-live', 'polite');
7249
- count.textContent = `${kind === 'setup' ? settled : answered.length} of ${live.length} ${kind === 'setup' ? 'settled' : 'answered'}`; card.append(count);
8241
+ count.textContent = kind === 'setup' ? `${settled} of ${live.length} settled` : `${settled} of ${live.length} heights answered${answered.length > settled ? ` · ${answered.length - settled} clarification${answered.length - settled === 1 ? '' : 's'} saved` : ''}`; card.append(count);
7250
8242
  if (kind === 'height' && entry.view.open) {
7251
8243
  const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
7252
8244
  note.textContent = rows.some((row) => row.inModel)
7253
- ? 'Only you can answer these heights. For a new member, what you confirm or type goes straight into the model; for one already in the model, it is proposed in the review.'
7254
- : 'Only you can answer these heights. What you confirm or type goes straight into the model.';
8245
+ ? 'Only you can confirm or type a height. It goes into a new member or becomes a proposal in the review for an existing member. An explanation stays unresolved; save it, then use Tell the read for a proposal.'
8246
+ : 'Only you can confirm or type a height for the model. Explanations stay unresolved; save one, then use Tell the read for a proposal.';
7255
8247
  card.append(note);
7256
- }
7257
- if (entry.view.open && allAnswered) {
7258
- const next = heightActionButton('Tell / send to the read', `shell.chat-${kind}-next-step#${entry.questionId}`, `${kind === 'setup' ? 'setup' : 'height'} question ${entry.view.n}`, 'ai-chat-height-change', entry.busy ? 'An answer is still being saved — wait for it to finish' : null);
8248
+ // #2774: the person asked for a height on every end; any end without one says why, and the card counts them.
8249
+ const bare = entry.view.proposeAll ? live.filter((row) => !row.proposed && !row.answer).length : 0;
8250
+ if (bare) card.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-height-unproposed',
8251
+ textContent: `You asked for a height on every end. The read could not propose ${bare === 1 ? 'one end' : `${bare} ends`}; each says why.` }));
8252
+ }
8253
+ const clarificationReady = kind === 'height' && heightClarificationPending(entry);
8254
+ if (entry.view.open && (clarificationReady || allAnswered && !(kind === 'height' && live.some((row) => heightResponsibility(row) !== 'answered')))) {
8255
+ const next = heightActionButton(clarificationReady ? 'Tell / send clarification to the read' : 'Tell / send to the read', `shell.chat-${kind}-next-step#${entry.questionId}`, clarificationReady ? 'saved clarification; height unresolved' : `${kind === 'setup' ? 'setup' : 'height'} question ${entry.view.n}`, 'ai-chat-height-change', entry.busy ? 'An answer is still being saved — wait for it to finish' : null);
7259
8256
  next.dataset.tip = 'Choose whether to put the message in the box or send it now';
7260
8257
  next.addEventListener('click', () => {
7261
8258
  if (entry.busy) return;
@@ -7266,6 +8263,13 @@
7266
8263
  card.append(next);
7267
8264
  }
7268
8265
  const list = document.createElement('ol'); list.className = 'ai-chat-height-rows';
8266
+ // Every repaint builds a new list (Answer, Back, a saved answer, a feed repaint of a changed card), and a new list
8267
+ // starts at its top. The list carries where the person left it, and keepRowsScroll or paintEvents puts it back once
8268
+ // it is in the page (owner, 2026-10-25: Answer on row 21 of 48 jumped to row 1). A hidden list (AI Chat collapsed)
8269
+ // reads 0 and forgets its place, so only a shown list records it, and it goes back there when it shows again.
8270
+ list.addEventListener('scroll', () => { if (list.clientHeight) entry.rowsScroll = list.scrollTop; }, { passive: true });
8271
+ list.keptScrollTop = entry.rowsScroll || 0;
8272
+ if (typeof ResizeObserver === 'function') new ResizeObserver(() => { if (list.clientHeight) list.scrollTop = entry.rowsScroll || 0; }).observe(list);
7269
8273
  for (const row of rows) {
7270
8274
  const key = drawingRowKey(kind, row);
7271
8275
  let item;
@@ -7277,27 +8281,81 @@
7277
8281
  } else {
7278
8282
  item = document.createElement('li'); item.className = 'ai-chat-height-row'; item.dataset.status = row.status; item.dataset.key = key;
7279
8283
  const label = document.createElement('span'); label.textContent = row.label || (row.kind === 'origin' ? 'Model origin' : viewName(row)); item.append(label);
7280
- if (entry.view.open) {
7281
- const answer = heightActionButton('Answer', `shell.chat-${kind}-change#${entry.questionId} ${key}`, label.textContent, 'ai-chat-height-change', null);
8284
+ if (kind === 'height') {
8285
+ const status = document.createElement('p'); status.className = 'ai-chat-filter-note'; status.textContent = heightStateText(row); item.append(status);
8286
+ if (heightStudyText(row)) {
8287
+ const details = document.createElement('p'); details.className = 'ai-chat-filter-note';
8288
+ details.textContent = heightStudyText(row); item.append(details);
8289
+ }
8290
+ }
8291
+ const firstPlace = kind === 'setup' && row.kind === 'level' ? setupPlaceItems(row)[0] : null;
8292
+ const chip = kind === 'height' ? heightPlaceChip(entry, row) : firstPlace ? setupPlaceChip(entry, row, firstPlace) : null;
8293
+ if (chip) item.append(chip);
8294
+ if (entry.view.open && !(kind === 'height' && ['resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row)))) {
8295
+ const answer = heightActionButton(kind === 'height' && heightResponsibility(row) === 'investigating' ? 'Answer yourself' : 'Answer', `shell.chat-${kind}-change#${entry.questionId} ${key}`, label.textContent, 'ai-chat-height-change', null);
7282
8296
  answer.addEventListener('click', () => reopenDrawingItem(kind, entry, key)); item.append(answer);
7283
8297
  }
7284
8298
  }
8299
+ if (kind === 'height' && ['replaced', 'resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row))) {
8300
+ const draft = entry.slotDrafts?.get(key), source = answerSources.get(heightSourceScope(entry, key));
8301
+ const text = draft?.rows?.map((r) => r.other || r.reason || '').filter(Boolean).join(' ');
8302
+ if (text || source?.note) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Unsent draft kept here: ${[text, source?.note].filter(Boolean).join(' · ')}. Nothing from this draft was submitted or transferred to another question.` }));
8303
+ for (const file of source?.files || []) item.append(retainedHeightPicture(entry, file, `shell.chat-answer-picture-open#${entry.questionId} ${key} ${file.attachmentId}`, `unsent picture for ${row.label}`));
8304
+ const batch = entry.slotDrafts?.get('batch-value'), shared = answerSources.get(heightSourceScope(entry));
8305
+ const batchEnds = batch?.scopeEnds || [], sharedEnds = shared?.scopeEnds || batchEnds;
8306
+ entry.retiredDrafts ??= new Map();
8307
+ if (!entry.retiredDrafts.has(key)) entry.retiredDrafts.set(key, {
8308
+ text: batchEnds.includes(key) ? batch.rows?.map((r) => r.other || r.reason || '').filter(Boolean).join(' ') || '' : '',
8309
+ note: sharedEnds.includes(key) ? shared?.note || '' : '',
8310
+ files: sharedEnds.includes(key) ? (shared?.files || []).map(({ url, ...file }) => ({ ...file })) : [],
8311
+ scopeEnds: [...new Set([...batchEnds, ...sharedEnds])],
8312
+ });
8313
+ // A later save for the still-open siblings clears their live batch, never this retired end's original recovery.
8314
+ const recovery = entry.retiredDrafts.get(key), sharedText = recovery.text, sharedNote = recovery.note;
8315
+ const scope = recovery.scopeEnds.map((end) => rows.find((r) => heightEndKey(r) === end)?.label || end).join('; ');
8316
+ if (sharedText || sharedNote) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Shared unsent draft kept for its original ends (${scope}): ${[sharedText, sharedNote].filter(Boolean).join(' · ')}. It has not been applied to this end or moved to another question.` }));
8317
+ for (const file of recovery.files) item.append(retainedHeightPicture(entry, file, `shell.chat-answer-picture-open#${entry.questionId} bulk ${file.attachmentId}`, `shared unsent picture for ${scope}`));
8318
+ }
8319
+ if (kind === 'height' && row.place && !row.placeDigest && row.unplaced) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: row.unplaced }));
7285
8320
  list.append(item);
7286
8321
  }
7287
8322
  card.append(list);
7288
8323
  }
7289
- const unused = kind === 'height' ? drawingRows(kind, entry).filter((row) => answerSources.get(`h:${entry.questionId}:${heightEndKey(row)}`)?.files.some((file) => file.cleanupPending)) : [];
8324
+ const unused = kind === 'height' ? drawingRows(kind, entry).filter((row) => answerSources.get(heightSourceScope(entry, heightEndKey(row)))?.files.some((file) => file.cleanupPending)) : [];
7290
8325
  const cleanup = unused.length ? `Your heights were saved. Some unused pictures could not be removed. Choose Change for each listed end, then Remove on its unused pictures: ${unused.map((row) => `${row.label} · ${row.memberId} · ${heightEndWord(row)}`).join('; ')}. You do not need to submit the heights again.` : '';
7291
8326
  const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert'); error.textContent = [entry.cardError, cleanup].filter(Boolean).join(' '); card.append(error);
8327
+ if (kind === 'height' && entry.draftStorageError) card.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: entry.draftStorageError }));
8328
+ if (kind === 'height' && entry.cardError && card.dataset.state === 'investigating') error.textContent = `Previous answer was not saved; draft retained. ${entry.cardError}`;
8329
+ if (kind === 'height') {
8330
+ const kept = [...(entry.slotDrafts || [])].filter(([key, draft]) => !rows.some((row) => ['replaced', 'resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row)) && heightEndKey(row) === key) && draft.rows?.some((row) => row.other?.trim() || row.reason?.trim()));
8331
+ if (kept.length && ['replaced', 'resolved', 'closed-unresolved'].includes(card.dataset.state)) {
8332
+ const draft = document.createElement('p'); draft.className = 'ai-chat-filter-note'; draft.textContent = `Unsent draft kept on this original question: ${kept.map(([, item]) => item.rows.map((r) => r.other || r.reason || '').join(' ')).join('; ')}. It was not transferred to the newer question.`; card.append(draft);
8333
+ }
8334
+ if (['replaced', 'resolved', 'closed-unresolved'].includes(card.dataset.state)) for (const [scope, source] of answerSources) {
8335
+ if (!heightSourceBelongs(entry, scope)) continue;
8336
+ if (rows.some((row) => ['replaced', 'resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row)) && scope === heightSourceScope(entry, heightEndKey(row)))) continue;
8337
+ if (source.note) card.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Unsent source note kept on this question: ${source.note}` }));
8338
+ for (const file of source.files) {
8339
+ card.append(retainedHeightPicture(entry, file, `shell.chat-answer-picture-open#${entry.questionId} draft ${file.attachmentId}`, `unsent picture on height question ${entry.view.n}`));
8340
+ }
8341
+ }
8342
+ }
7292
8343
  drawingSlotRepaint();
7293
8344
  return card;
7294
8345
  }
7295
8346
  function drawingSource(kind, entry, scope, label, idFor, row, onDraftChange) {
7296
8347
  return paintAnswerSource(scope, { requestId: entry.requestId, chatId: entry.chatId, repaint: () => { (kind === 'setup' ? repaintSetupCard : repaintHeightCard)(entry); drawingSlotRepaint(); },
7297
8348
  removeFile: (file) => request(`/api/chat/answer-evidence/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(file.attachmentId)}`, { method: 'DELETE', body: JSON.stringify({ chatId: entry.chatId }) }),
7298
- label, instance: label, idFor, inherited: row?.inherited, busyReason: entry.busy ? 'An answer is still being saved — wait for it to finish' : null,
8349
+ label, instance: label, idFor, inherited: row?.inherited, inheritedNote: (kind === 'height' ? row?.answer?.note : null) || row?.inheritedNote, clarification: kind === 'height', busyReason: entry.busy ? 'An answer is still being saved — wait for it to finish' : null,
7299
8350
  allowPictureOnly: false, onDraftChange, alwaysOpen: Boolean(entry.slotDrafts?.get(entry.slotQuestionKey)?.rows[0]?.otherOpen) });
7300
8351
  }
8352
+ function retainedHeightPicture(entry, file, commandId, instance) {
8353
+ const url = heightDraftEvidenceUrl(entry, file.attachmentId);
8354
+ return entry.view?.readRemoved || !url ? Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Retained unsent picture: ${file.fileName}. This read is closed or its original project is unavailable here, so the picture cannot be opened here. Your draft reference is kept; attach the original file to a new question if needed.` }) : answerPictureChip(entry.requestId, file, commandId, instance, url);
8355
+ }
8356
+ function heightDraftEvidenceUrl(entry, attachmentId) {
8357
+ return entry.projectId ? `/api/chat/conversations/${encodeURIComponent(entry.chatId)}/attachments/${encodeURIComponent(attachmentId)}?${new URLSearchParams({ ownerKind: 'project', ownerId: entry.projectId })}` : '';
8358
+ }
7301
8359
  /**
7302
8360
  * The card's last step ("Tell the read what to look at next") has nothing left to do once a message saying so went to
7303
8361
  * the read after the card's last answer (owner, 2026-10-23: the card stayed while the AI was already working on it).
@@ -7316,11 +8374,38 @@
7316
8374
  && String(event.payload?.text || '').includes(told));
7317
8375
  }
7318
8376
 
8377
+ function heightClarificationPending(entry) {
8378
+ if (!entry.view?.open) return false;
8379
+ const rows = drawingRows('height', entry).filter((row) => row.status !== 'superseded'
8380
+ && ['investigating', 'needs-answer', 'proposal'].includes(heightResponsibility(row))
8381
+ && row.answer?.how === 'evidence' && (row.answer.note?.trim() || row.answer.evidence?.length));
8382
+ if (!rows.length) return false;
8383
+ const lastEvidence = Math.max(0, ...rows.map((row) => Date.parse(row.answer.answeredAt || '') || 0));
8384
+ const text = heightClarificationText(entry);
8385
+ return !state.events.some((event) => event.type === 'user-message' && !event.optimistic && event.eventId
8386
+ && event.chatId === entry.chatId && !event.payload?.source
8387
+ && (Date.parse(event.createdAt || '') || 0) > lastEvidence
8388
+ && (!(event.payload?.followup || event.payload?.deliveryState) || ['accepted', 'queued-next'].includes(followupDelivery(event)))
8389
+ && String(event.payload?.text || '').includes(text));
8390
+ }
8391
+ function drawingClarificationStep(entry) {
8392
+ return { key: 'clarification', label: 'saved clarification; height unresolved', question: { id: 'clarification', header: 'Heights',
8393
+ question: 'Clarification saved — height unresolved', allowOther: false,
8394
+ context: ['Your explanation and attachments are saved. Send a message to ask the read to work out a proposal. The height remains unresolved.'],
8395
+ hint: 'Tell the read puts a message in the box. Send to the read sends it now.',
8396
+ options: [{ shown: 'Tell the read', description: 'Put the clarification notice in the box so you can add to it' }, { shown: 'Send to the read', description: 'Send the notice now, keeping your words and files' }] },
8397
+ commit: async (answer) => { const text = heightClarificationText(entry);
8398
+ if (answer.choices[0] === 0) tellReadAnswered(entry, text, repaintHeightCard); else await sendToReadAnswered(entry, text, repaintHeightCard); return false; } };
8399
+ }
8400
+
7319
8401
  function drawingStep(kind, entry) {
7320
8402
  const open = drawingRows(kind, entry).filter((row) => drawingRowOpen(kind, entry, row));
7321
8403
  const row = open.find((row) => drawingRowKey(kind, row) === entry.activeItem) || open[0];
8404
+ const clarificationReady = kind === 'height' && heightClarificationPending(entry);
8405
+ if (clarificationReady && (entry.finishActive || !row)) return drawingClarificationStep(entry);
7322
8406
  if (!row) {
7323
8407
  const live = drawingRows(kind, entry).filter((row) => row.status !== 'superseded');
8408
+ if (kind === 'height' && live.some((item) => heightResponsibility(item) !== 'answered')) return null;
7324
8409
  if (!entry.view?.open || !live.length || !live.every((row) => row.answer)) return null;
7325
8410
  if (drawingFinishTold(kind, entry, live)) return null;
7326
8411
  return { key: 'finish', question: { id: 'finish', header: kind === 'setup' ? 'Read setup' : 'Heights', question: 'Your answers are recorded. Tell the read what to look at next.', allowOther: false,
@@ -7330,20 +8415,25 @@
7330
8415
  if (answer.choices[0] === 0) tellReadAnswered(entry, text, repaint); else await sendToReadAnswered(entry, text, repaint); return false; } };
7331
8416
  }
7332
8417
  if (kind === 'height' && open.length > 1 && entry.slotPhase !== 'row') return drawingHeightBatch(entry, open);
7333
- const key = drawingRowKey(kind, row), scope = `${kind === 'setup' ? 's' : 'h'}:${entry.questionId}:${key}`;
8418
+ const key = drawingRowKey(kind, row), scope = (kind === 'setup' ? `s:${entry.questionId}:${key}` : heightSourceScope(entry, key));
7334
8419
  const label = row.label || (row.kind === 'origin' ? 'the model origin' : viewName(row));
7335
8420
  const q = { id: key, header: kind === 'setup' ? 'Read setup' : 'Height', question: label, options: [], recommended: null, context: [] };
7336
8421
  const live = drawingRows(kind, entry).filter((item) => item.status !== 'superseded');
7337
8422
  q.progress = { index: live.indexOf(row), total: live.length };
7338
8423
  const choices = [];
7339
8424
  if (kind === 'height') {
8425
+ q.otherInputLabel = 'Height (optional)';
8426
+ q.otherPlaceholder = entry.view.units === 'mm' ? '4870 mm, or 4.87 for metres' : `15'-11 3/4"; a bare number is inches`;
7340
8427
  if (row.inModel) {
7341
8428
  q.context.push(
7342
8429
  `${row.inModel.profile || ''} · ${row.memberId} · ${heightEndWord(row)}. ${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}`
7343
8430
  );
7344
8431
  }
7345
- else q.context.push(`${row.memberId} · ${heightEndWord(row)}. Only you can answer. What you confirm or type goes straight into the model.`);
7346
- if (row.proposed) { q.options.push({ shown: `Confirm ${row.proposed.asRead}`, description: 'Use the value proposed for this member end' }); choices.push({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value }); q.recommended = 0; }
8432
+ else q.context.push(`${row.memberId} · ${heightEndWord(row)}. Only you can confirm or enter a numeric height. An explanation or attachment leaves the height unresolved until you confirm a proposal.`);
8433
+ q.context.push(heightStateText(row));
8434
+ if (row.proposed) { q.options.push({ shown: `Confirm ${row.proposed.asRead}`, ...heightProposalWords(row.proposed) }); choices.push({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value }); q.recommended = 0; }
8435
+ else q.context.push(heightNoProposalText(row));
8436
+ q.figure = () => heightPlaceFigure(entry, row);
7347
8437
  if (row.fromEvidence) q.context.push(row.inherited?.length ? 'The read’s reading of your picture. Check it before you confirm.' : 'The read’s reading of your note. Check it before you confirm.');
7348
8438
  } else if (row.kind === 'origin') {
7349
8439
  q.question = 'Which grid crossing is the model’s origin (0, 0)?'; q.layout = 'grid'; q.confirmSelection = true;
@@ -7354,9 +8444,13 @@
7354
8444
  } else {
7355
8445
  if (row.clue) q.context.push(row.clue);
7356
8446
  if (row.noSingleLevel) q.context.push(`No single level on the drawings: ${row.noSingleLevel.why}`);
8447
+ // Options follow row.proposals in order, so the selected option's index names its proposal.
8448
+ // A choice past the proposals ("No single level") has no place of its own, so it gets no picture.
8449
+ if (row.kind === 'level') q.figure = (choice) => setupPlaceFigure(entry, row, Number.isInteger(choice) ? (row.proposals[choice] ?? SETUP_NO_PROPOSAL) : null);
7357
8450
  row.proposals.forEach((proposal) => { q.options.push({ shown: row.kind === 'scale' ? `${proposal.pageFit ? 'Use for this plan' : 'Confirm'}: ${proposal.standard} · ${proposal.mmPerPx} mm per drawing point` : `Confirm ${proposal.asRead}`,
7358
8451
  description: row.kind === 'scale' ? proposal.evidence : levelEvidence(proposal), tag: (row.kind === 'scale' ? scaleTag : levelTag)[proposal.source] || 'PROPOSED' }); choices.push({ key, action: 'confirm', choice: proposal.id, shown: row.kind === 'scale' ? proposal.mmPerPx : proposal.value }); });
7359
8452
  }
8453
+ if (kind === 'setup' && (row.kind === 'origin' || row.kind === 'scale')) q.context.push('This setup question has no saved drawing location. Inspect the drawing set in Drawing Filter, or ask the read to point out the context.');
7360
8454
  if (kind === 'setup' && row.kind !== 'scale') { q.options.push({ shown: row.kind === 'origin' ? 'None of these' : 'No single level', description: 'Tell the read what to use instead', requiresNote: { placeholder: 'Add a short reason', max: MAX_ANSWER_NOTE } }); choices.push({ key, action: 'none' }); }
7361
8455
  if (kind === 'setup') { const banner = setupConflictBanner(row); if (banner) q.context.push(banner.textContent); }
7362
8456
  const controlKey = kind === 'height' ? `${row.memberId} ${row.endWord}` : key;
@@ -7364,7 +8458,7 @@
7364
8458
  const previous = live.slice(0, live.indexOf(row)).filter((item) => !item.frozen).at(-1);
7365
8459
  const backToMode = kind === 'height' && !previous && open.length > 1;
7366
8460
  return { key, question: q, scope, row, label, actions: choices, backToMode,
7367
- back: previous ? () => reopenDrawingItem(kind, entry, drawingRowKey(kind, previous)) : backToMode ? () => { entry.slotPhase = null; entry.activeItem = null; entry.slotSig = null; drawingSlotRepaint(); } : null,
8461
+ back: previous ? () => reopenDrawingItem(kind, entry, drawingRowKey(kind, previous)) : backToMode ? () => { entry.slotPhase = null; entry.activeItem = null; entry.slotSig = null; engageDrawingEntry(entry); drawingSlotRepaint(); } : null,
7368
8462
  source: (_index, onDraftChange) => drawingSource(kind, entry, scope, label, idFor, row, onDraftChange),
7369
8463
  validate: (_step, draft) => {
7370
8464
  const answer = draft.rows[0]; if (answer.choices.length) return '';
@@ -7384,7 +8478,7 @@
7384
8478
  const base = { header: 'Heights', allowOther: false, id: 'batch', recommended: null };
7385
8479
  if (!entry.slotPhase) {
7386
8480
  const confirmable = rows.every((row) => !row.answer && row.proposed);
7387
- const scope = `hb:${entry.questionId}`, label = `all ${rows.length} proposed member ends`;
8481
+ const scope = heightSourceScope(entry), label = `all ${rows.length} proposed member ends`;
7388
8482
  const idFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra === undefined ? '' : ` ${extra}`}`;
7389
8483
  const inherited = [...new Map(rows.flatMap((row) => row.inherited || []).map((ref) => [ref.attachmentId, ref])).values()];
7390
8484
  const options = [];
@@ -7394,29 +8488,30 @@
7394
8488
  source: confirmable ? (_index, onDraftChange) => drawingSource('height', entry, scope, label, idFor, { inherited }, onDraftChange) : null,
7395
8489
  question: { ...base, question: 'How would you like to answer these heights?', options, recommended: confirmable ? 0 : null,
7396
8490
  hint: confirmable ? 'Confirm all saves these values. The other choices only choose how to answer.' : 'Choose how to answer; no heights are saved yet.',
7397
- context: [...rows.map((row) => `${row.label} · ${row.inModel?.profile ? `${row.inModel.profile} · ` : ''}${row.memberId} · ${heightEndWord(row)}.${row.proposed ? ` Proposed: ${row.proposed.asRead} (${row.proposed.value} mm).` : ''} ${row.inModel ? `${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}` : 'What you confirm or type goes straight into the model.'}${row.fromEvidence ? ` The read’s reading of your ${row.inherited?.length ? 'picture' : 'note'}. Check it before you confirm.` : ''}`), ...(confirmable ? [`Optional source for all ${rows.length} heights. Each end keeps its own proposed value.`] : [])] }, commit: async (answer) => {
8491
+ figure: () => heightBatchPlaces(entry, rows, 'batch-intro', rows.map((row) => `${row.label} · ${row.inModel?.profile ? `${row.inModel.profile} · ` : ''}${heightEndWord(row)}.${heightPlaced(row) ? ` On ${row.place.sheet}.` : ''}${row.proposed ? ` Proposed: ${row.proposed.asRead} (${row.proposed.value} mm)${row.proposed.how === 'derived' ? `, derived, an assumption: ${row.proposed.basis}` : ''}.` : ` ${heightNoProposalText(row).replace(/[^.!?]$/, '$&.')}`} ${row.inModel ? `${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}` : 'What you confirm or type goes straight into the model.'}${row.fromEvidence ? ` The read’s reading of your ${row.inherited?.length ? 'picture' : 'note'}. Check it before you confirm.` : ''}`)),
8492
+ context: [...(confirmable ? [`Optional source for all ${rows.length} heights. Each end keeps its own proposed value.`] : [])] }, commit: async (answer) => {
7398
8493
  if (confirmable && answer.choices[0] === 0) return submitHeightAnswers(entry, rows.map((row) => ({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value })), null, hasAnswerSource(scope) ? scope : null);
7399
- entry.slotPhase = answer.choices[0] === options.length - 1 ? 'row' : 'select'; return true;
8494
+ entry.slotPhase = answer.choices[0] === options.length - 1 ? 'row' : 'select'; engageDrawingEntry(entry); return true;
7400
8495
  } };
7401
8496
  }
7402
8497
  if (entry.slotPhase === 'select') {
7403
8498
  const groups = new Map();
7404
8499
  for (const row of rows) { const members = groups.get(row.group) || []; members.push(row); groups.set(row.group, members); }
7405
8500
  const ordered = [...groups.values()].flat();
7406
- return { key: 'batch-select', rows: ordered, question: { ...base, allowClear: true, hint: 'Select ends, then Submit. No heights are saved yet.', question: 'Which member ends should share one answer?', multiSelect: true, options: ordered.map((row) => ({ shown: row.label, group: row.group, description: `${row.memberId} · ${heightEndWord(row)}` })) },
8501
+ return { key: 'batch-select', rows: ordered, question: { ...base, figure: () => heightBatchPlaces(entry, ordered, 'batch-select'), allowClear: true, hint: 'Select ends, then Submit. No heights are saved yet.', question: 'Which member ends should share one answer?', multiSelect: true, options: ordered.map((row) => ({ shown: row.label, group: row.group, description: [row.inModel?.profile, heightEndWord(row)].filter(Boolean).join(' · ') })) },
7407
8502
  initial: ordered.map((row, index) => entry.selected.size ? entry.selected.has(heightEndKey(row)) ? index : -1 : index).filter((index) => index >= 0),
7408
8503
  back: () => { entry.slotPhase = null; entry.slotSig = null; drawingSlotRepaint(); },
7409
- commit: async (answer) => { entry.selected = new Set(answer.choices.map((index) => heightEndKey(ordered[index]))); entry.slotPhase = 'value'; return true; } };
8504
+ commit: async (answer) => { entry.selected = new Set(answer.choices.map((index) => heightEndKey(ordered[index]))); entry.slotPhase = 'value'; engageDrawingEntry(entry); return true; } };
7410
8505
  }
7411
8506
  const chosen = rows.filter((row) => entry.selected.has(heightEndKey(row)));
7412
8507
  if (!chosen.length) { entry.slotPhase = 'select'; return drawingHeightBatch(entry, rows); }
7413
8508
  const shared = chosen.every((row) => row.proposed && row.proposed.value === chosen[0].proposed?.value);
7414
- const scope = `hb:${entry.questionId}`, label = `${chosen.length} selected member ends`, idFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra === undefined ? '' : ` ${extra}`}`;
8509
+ const scope = heightSourceScope(entry), label = `${chosen.length} selected member ends`, idFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra === undefined ? '' : ` ${extra}`}`;
7415
8510
  const inherited = [...new Map(chosen.flatMap((row) => row.inherited || []).map((ref) => [ref.attachmentId, ref])).values()];
7416
8511
  const context = chosen.filter((row) => row.inModel).map((row) => `${row.label}: ${row.inModel.profile || ''}. ${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}`);
7417
8512
  if (chosen.some((row) => row.fromEvidence)) context.push(inherited.length ? 'The read’s reading of your picture. Check it before you confirm.' : 'The read’s reading of your note. Check it before you confirm.');
7418
8513
  return { key: 'batch-value', scope, label, back: () => { entry.slotPhase = 'select'; entry.slotSig = null; drawingSlotRepaint(); },
7419
- question: { ...base, allowOther: true, context, question: `What height should the ${chosen.length} selected ends use?`,
8514
+ question: { ...base, figure: () => heightBatchPlaces(entry, chosen, 'batch-value'), allowOther: true, otherInputLabel: 'Height (optional)', otherPlaceholder: entry.view.units === 'mm' ? '4870 mm, or 4.87 for metres' : `15'-11 3/4"; a bare number is inches`, context, question: `What height should the ${chosen.length} selected ends use?`,
7420
8515
  options: shared ? [{ shown: `Confirm ${chosen[0].proposed.asRead} for ${chosen.length}`, description: 'Every selected end has this same proposed value' }] : [], recommended: shared ? 0 : null },
7421
8516
  source: (_index, onDraftChange) => drawingSource('height', entry, scope, label, idFor, { inherited }, onDraftChange), validate: (_step, draft) => draft.rows[0].choices.length || draft.rows[0].other.trim() || hasAnswerSource(scope) ? '' : NO_HEIGHT_NO_SOURCE,
7422
8517
  commit: async (answer) => { const answers = chosen.map((row) => ({ memberId: row.memberId, end: row.end, ...(answer.choices.length ? { action: 'confirm', shown: row.proposed.value } : answer.other ? { action: 'type', typed: answer.other } : { action: 'evidence' }) }));
@@ -7424,6 +8519,16 @@
7424
8519
  if (saved) { entry.slotPhase = null; entry.slotDrafts?.delete('batch-value'); entry.slotDrafts?.delete('batch-select'); }
7425
8520
  return saved; } };
7426
8521
  }
8522
+ /*
8523
+ * #2793: the card the person last acted in keeps the tray, until they act in another. Going Back to a card's own
8524
+ * "How would you like to answer…" step is acting in it: without this, the tray fell back to the OLDEST open card.
8525
+ */
8526
+ function engageDrawingEntry(entry) {
8527
+ // Another card's "Tell the read" step was shown because the person last acted there; acting here moves on from it.
8528
+ for (const other of [...setupCards.values(), ...heightCards.values()]) if (other !== entry) other.finishActive = false;
8529
+ entry.engaged = true; entry.reopenedAt = (state.drawingActivationOrder = (state.drawingActivationOrder || 0) + 1);
8530
+ }
8531
+ const drawingEntryHeld = (entry) => Boolean(entry.finishActive || entry.engaged || entry.changing.has(entry.activeItem));
7427
8532
  function paintDrawingQuestionSlot() {
7428
8533
  const tray = ui.approvalTray; if (!tray || !window.FlolessQuestionCard) return false;
7429
8534
  const showing = tray.querySelector('.ai-chat-drawing-step');
@@ -7432,20 +8537,32 @@
7432
8537
  if (state.chat?.pendingApproval || tray.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope):not(.ai-chat-drawing-step), .ai-chat-approval-hidden')) { showing?.remove(); return false; }
7433
8538
  const entries = [...setupCards.values()].map((entry) => ({ kind: 'setup', entry })).concat([...heightCards.values()].map((entry) => ({ kind: 'height', entry })))
7434
8539
  .filter(({ entry }) => drawingEntryCurrent(entry) && entry.view?.open && !entry.reloadPending && !entry.loading)
7435
- .sort((a, b) => ((b.entry.finishActive || b.entry.changing.has(b.entry.activeItem)) ? b.entry.reopenedAt || 0 : 0)
7436
- - ((a.entry.finishActive || a.entry.changing.has(a.entry.activeItem)) ? a.entry.reopenedAt || 0 : 0) || a.entry.sequence - b.entry.sequence);
8540
+ .sort((a, b) => (drawingEntryHeld(b.entry) ? b.entry.reopenedAt || 0 : 0) - (drawingEntryHeld(a.entry) ? a.entry.reopenedAt || 0 : 0) || a.entry.sequence - b.entry.sequence);
7437
8541
  const waiting = entries.map(({ kind, entry }) => ({ kind, entry, step: drawingStep(kind, entry) })).filter(({ step }) => step);
7438
8542
  const hidden = waiting.filter(({ entry }) => drawingCardHidden(entry));
7439
8543
  const candidates = waiting.filter((candidate) => !hidden.includes(candidate));
7440
8544
  const units = drawingUnitsCandidate(); if (units) (drawingCardHidden(units.entry) ? hidden : candidates).push(units);
7441
- let chosen = candidates.find(({ entry, step }) => entry.finishActive && step.key === 'finish') || candidates.find(({ step }) => step.key !== 'finish') || candidates[0];
8545
+ // A card's "Tell the read" step wins only while that card is the one the person acted in last (#2793): candidates
8546
+ // are sorted newest action first, so a finish step further down was left behind when they moved to another card.
8547
+ let chosen = candidates.find(({ entry, step }, index) => entry.finishActive && ['finish', 'clarification'].includes(step.key) && index === 0) || candidates.find(({ step }) => !['finish', 'clarification'].includes(step.key)) || candidates[0];
7442
8548
  if (heldFocus && personIsTyping()) {
7443
8549
  const current = candidates.find(({ entry, step }) => `${entry.chatId}/${entry.key}/${step.key}` === showing.dataset.drawingStep);
7444
8550
  const activated = chosen?.entry.finishActive || (chosen?.entry.reopenedAt || 0) > (current?.entry.reopenedAt || 0);
7445
8551
  if (current && !activated) chosen = current;
7446
8552
  }
7447
8553
  if (!chosen && hidden.length) return paintDrawingHiddenLine(tray, showing, hidden);
7448
- if (!chosen) { showing?.remove(); return false; }
8554
+ if (!chosen) {
8555
+ const parked = entries.flatMap(({ kind, entry }) => kind === 'height' ? drawingRows(kind, entry).filter((row) => heightResponsibility(row) === 'investigating' && !entry.changing.has(heightEndKey(row))).map((row) => ({ entry, row })) : []);
8556
+ if (parked.length) {
8557
+ const { entry, row } = parked[0];
8558
+ if (showing && showing !== drawingHiddenLine) showing.remove();
8559
+ drawingHiddenLine = paintHiddenLine(drawingHiddenLine, tray, { className: 'ai-chat-drawing-step', label: 'Heights',
8560
+ sentence: `AI investigating · ${row.label} · ${row.lifecycle?.reason || 'The read is looking for this height.'}${parked.length > 1 ? ` · ${parked.length} ends` : ''}${entry.saveFailed ? ' Previous answer was not saved; draft retained.' : ''} · Answer yourself`,
8561
+ commandId: `shell.chat-height-change#${entry.questionId} ${heightEndKey(row)}`, instance: row.label, show: () => reopenDrawingItem('height', entry, heightEndKey(row)) });
8562
+ drawingHiddenLine.dataset.drawingStep = `investigating/${entry.key}`; return true;
8563
+ }
8564
+ showing?.remove(); return false;
8565
+ }
7449
8566
  const { kind, entry, step } = chosen, key = `${entry.chatId}/${entry.key}/${step.key}`;
7450
8567
  if (showing && showing.dataset.drawingStep !== key) showing.remove();
7451
8568
  entry.slotDrafts ??= new Map();
@@ -7456,6 +8573,7 @@
7456
8573
  if (step.row?.answer?.how === 'typed' && entry.changing.has(step.key)) { draft.rows[0].otherOpen = true; draft.rows[0].other = step.row.answer.typed; }
7457
8574
  entry.slotDrafts.set(step.key, draft);
7458
8575
  }
8576
+ if (kind === 'height' && step.key === 'batch-value' && !draft.scopeEnds) draft.scopeEnds = [...entry.selected];
7459
8577
  const choiceSignature = JSON.stringify(step.question.options);
7460
8578
  if (draft.choiceSignature && draft.choiceSignature !== choiceSignature) draft.rows[0].choices = [];
7461
8579
  draft.choiceSignature = choiceSignature;
@@ -7463,18 +8581,20 @@
7463
8581
  entry.slotQuestionKey = step.key;
7464
8582
  const sig = JSON.stringify([key, entry.view, entry.busy, entry.cardError, [...entry.rowErrors], [...entry.changing], [...entry.selected || []], entry.slotPhase,
7465
8583
  // Typing refreshes Submit availability/carrier in place; note text must not invalidate the live field on a poll.
7466
- source && [source.open, source.files.map((file) => file.attachmentId), source.uploading, source.error], draft.pending, draft.rows[0].choices, draft.rows[0].otherOpen]);
8584
+ source && [source.open, source.files.map((file) => file.attachmentId), (source.failedUploads || []).map(heightDraftFileId), source.uploading, source.error], draft.pending, draft.rows[0].choices, draft.rows[0].otherOpen]);
7467
8585
  const node = entry.slotNode || document.createElement('section'); entry.slotNode = node;
7468
8586
  if (node.isConnected && entry.slotSig === sig) return true;
7469
- const editingSelections = [...node.querySelectorAll('input[data-command-id]')].map((field) => ({ id: field.dataset.commandId, caret: textCaret(field) })).filter(({ caret }) => caret);
8587
+ const editingSelections = [...node.querySelectorAll('input[data-command-id], textarea[data-command-id]')].map((field) => ({ id: field.dataset.commandId, caret: textCaret(field) })).filter(({ caret }) => caret);
7470
8588
  const focused = node.contains(document.activeElement) ? document.activeElement : heldFocus;
7471
8589
  const focusId = focused?.dataset.commandId, caret = focused ? textCaret(focused) : null;
7472
8590
  const freshStep = node.dataset.drawingStep !== key;
7473
8591
  const sameStepScroll = freshStep ? null : tray.scrollTop;
7474
8592
  if (freshStep) { delete node.dataset.armedAt; node.lastDrawingField = null; }
7475
8593
  if (!node.drawingFieldFocus) {
7476
- node.drawingFieldFocus = (event) => { if (event.target.tagName === 'INPUT' && (event.target.type === 'text' || !event.target.type)) node.lastDrawingField = event.target.dataset.commandId; };
8594
+ node.drawingFieldFocus = (event) => { if ((event.target.tagName === 'TEXTAREA' || event.target.tagName === 'INPUT' && (event.target.type === 'text' || !event.target.type))) node.lastDrawingField = event.target.dataset.commandId; };
7477
8595
  node.addEventListener('focusin', node.drawingFieldFocus);
8596
+ node.addEventListener('input', () => { if (kind === 'height') saveHeightDraft(entry); });
8597
+ node.addEventListener('change', () => { if (kind === 'height') saveHeightDraft(entry); });
7478
8598
  }
7479
8599
  node.className = 'ai-chat-approval ai-chat-ask-card ai-chat-drawing-step'; node.dataset.drawingStep = key;
7480
8600
  if (!node.isConnected) tray.append(node);
@@ -7493,7 +8613,7 @@
7493
8613
  // Rebuilding the same question temporarily shrinks the tray and clamps its scroll position.
7494
8614
  if (sameStepScroll !== null) tray.scrollTop = sameStepScroll;
7495
8615
  for (const { id, caret } of editingSelections) {
7496
- const field = [...node.querySelectorAll('input[data-command-id]')].find((control) => control.dataset.commandId === id);
8616
+ const field = [...node.querySelectorAll('input[data-command-id], textarea[data-command-id]')].find((control) => control.dataset.commandId === id);
7497
8617
  field?.setSelectionRange?.(Math.min(caret.start, field.value.length), Math.min(caret.end, field.value.length), caret.direction);
7498
8618
  }
7499
8619
  if (focusId) {
@@ -7507,7 +8627,7 @@
7507
8627
  const rowKey = step.row && kind === 'height' ? `${step.row.memberId} ${step.row.endWord}` : step.key;
7508
8628
  let name = what, suffix = rowKey, instance = step.label || step.question.header;
7509
8629
  if (kind === 'units') return { id: `shell.chat-units-choose#${extra === 0 ? 'ft-in' : 'mm'}`, instance: extra === 0 ? 'feet and inches' : 'metric (mm)' };
7510
- if (step.key === 'finish') name = extra === 0 ? 'tell-read' : 'send-read';
8630
+ if (step.key === 'finish' || step.key === 'clarification') name = extra === 0 ? 'tell-read' : 'send-read';
7511
8631
  else if (what === 'option') {
7512
8632
  if (step.key === 'batch-intro') { name = extra === 0 && step.question.recommended === 0 ? 'confirm-all' : 'mode'; if (name === 'mode') suffix += ` ${extra}`; }
7513
8633
  else if (step.key === 'batch-select') { name = 'select'; const row = step.rows[extra]; suffix = `${row.memberId} ${row.endWord}`; instance = row.label; }
@@ -7555,6 +8675,99 @@
7555
8675
  return entry;
7556
8676
  }
7557
8677
 
8678
+
8679
+ /*
8680
+ * #2777 slice B: a level on the setup card shows where the read took it from. Each proposal carries the places of the
8681
+ * readings it stands for (`places`: `{ place, digest }` FloLess resolved, or `{ unplaced }` with the reason); a place with
8682
+ * no `region` is a whole sheet (a level read from the picture of a sheet, not from its text). The answer step shows the
8683
+ * first place as a picture labelled with its level, and every other place as a chip labelled with its level and sheet,
8684
+ * so no picture ever stands unlabelled for a choice it is not.
8685
+ */
8686
+ /** The answer step's "No single level" (or any choice that is not a proposal): it has no place to show. */
8687
+ const SETUP_NO_PROPOSAL = Object.freeze({ none: true });
8688
+ const setupPlaceUrl = (entry, row, item) => `/api/chat/setup-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}/place?${new URLSearchParams({
8689
+ key: row.key, proposal: item.proposal.id, ix: String(item.ix), digest: item.digest, chatId: entry.chatId || '' })}`;
8690
+ function setupPlaceItems(row, only) {
8691
+ const items = [];
8692
+ for (const proposal of row.proposals || []) {
8693
+ if (only && proposal !== only) continue;
8694
+ (Array.isArray(proposal.places) ? proposal.places : []).forEach((entry, ix) => {
8695
+ if (entry && entry.place && entry.digest) items.push({ proposal, ix, place: entry.place, digest: entry.digest });
8696
+ });
8697
+ }
8698
+ return items;
8699
+ }
8700
+ const setupUnplaced = (row) => (row.proposals || []).flatMap((proposal) => (proposal.places || []).filter((entry) => entry && entry.unplaced)
8701
+ .map((entry) => `${proposal.asRead}: ${entry.unplaced}`));
8702
+ const setupPlaceInstance = (item) => `${item.proposal.asRead} on ${item.place.sheet}`;
8703
+ function openSetupPlace(entry, row, item, opener) {
8704
+ const marked = Array.isArray(item.place.region);
8705
+ return openDrawingPlace(item.place, {
8706
+ title: `Level ${item.proposal.asRead} on ${item.place.sheet}`, opener, url: setupPlaceUrl(entry, row, item),
8707
+ note: marked ? `FloLess outlined, on page ${item.place.page} of ${item.place.sheet}, the text the read took this level from. It shows where to look, not that the level is right.`
8708
+ : `The read took this level from its picture of ${item.place.sheet}, not from text on it, so no area is marked. Check the sheet yourself.`,
8709
+ commands: { close: 'shell.chat-setup-place-close', view: 'shell.chat-setup-place-view' },
8710
+ again: { label: 'Reload the setup card', commandId: 'shell.chat-setup-place-again', run: () => loadSetupQuestion(entry) },
8711
+ filter: { projectId: chatProjectId(), commandId: 'shell.chat-place-open-filter' },
8712
+ });
8713
+ }
8714
+ function setupPlaceChip(entry, row, item) {
8715
+ const chip = button(`${item.proposal.asRead} · ${item.place.sheet}`, `shell.chat-setup-row-place#${entry.questionId} ${row.key} ${item.proposal.id} ${item.ix}`, 'ai-chat-height-sheet');
8716
+ chip.dataset.commandInstanceLabel = setupPlaceInstance(item);
8717
+ chip.setAttribute('aria-label', `Open sheet ${item.place.sheet} where the read took level ${item.proposal.asRead}`);
8718
+ chip.dataset.tip = Array.isArray(item.place.region) ? `Opens sheet ${item.place.sheet} with this place outlined` : `Opens sheet ${item.place.sheet}; no area is marked`;
8719
+ chip.addEventListener('click', () => openSetupPlace(entry, row, item, chip));
8720
+ return chip;
8721
+ }
8722
+ /**
8723
+ * The setup answer step's picture for a level row: the selected level's first place (or, with nothing selected, the first
8724
+ * level's), labelled with its level; every other place as a chip labelled with its level and sheet; or why there is none.
8725
+ */
8726
+ function setupPlaceFigure(entry, row, chosen) {
8727
+ if (chosen === SETUP_NO_PROPOSAL) return null;
8728
+ const all = setupPlaceItems(row);
8729
+ // The selected level with no place of its own says so; it never borrows another level's picture.
8730
+ if (chosen && !all.some((item) => item.proposal === chosen)) {
8731
+ const why = (chosen.places || []).filter((entry) => entry && entry.unplaced).map((entry) => entry.unplaced);
8732
+ return Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-ask-context ai-chat-height-unplaced',
8733
+ textContent: why.length ? `Not placed on the drawings: ${why.join(' ')}` : `The read did not say where on the drawings it took ${chosen.asRead}.` });
8734
+ }
8735
+ const items = chosen ? [...all.filter((item) => item.proposal === chosen), ...all.filter((item) => item.proposal !== chosen)] : all;
8736
+ const unplaced = setupUnplaced(row);
8737
+ if (!items.length) {
8738
+ return Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-ask-context ai-chat-height-unplaced', textContent: unplaced.length
8739
+ ? `Not placed on the drawings: ${unplaced.join(' ')}`
8740
+ : 'The read supplied no drawing location for this level. Ask it to locate the level, or inspect the drawing set in Drawing Filter.' });
8741
+ }
8742
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-setup-places';
8743
+ const first = items[0];
8744
+ const marked = Array.isArray(first.place.region);
8745
+ const open = button('', `shell.chat-setup-open-place#${entry.questionId} ${row.key} ${first.proposal.id} ${first.ix}`, 'ai-chat-height-place');
8746
+ open.dataset.commandInstanceLabel = setupPlaceInstance(first);
8747
+ open.setAttribute('aria-label', `Open sheet ${first.place.sheet} where the read took level ${first.proposal.asRead}`);
8748
+ open.dataset.tip = marked ? `Opens sheet ${first.place.sheet} with this place outlined` : `Opens sheet ${first.place.sheet}; no area is marked`;
8749
+ const crop = evidenceCrop(first.place);
8750
+ const frame = document.createElement('span'); frame.className = 'ai-chat-height-place-frame';
8751
+ frame.style.aspectRatio = `${crop.w} / ${crop.h}`;
8752
+ frame.style.width = `min(100%, calc(110px * ${crop.w / crop.h}))`;
8753
+ const caption = document.createElement('span'); caption.className = 'ai-chat-height-place-caption';
8754
+ caption.append(Object.assign(document.createElement('strong'), { textContent: 'Open on sheet' }),
8755
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-sheet', textContent: `${first.place.sheet} · page ${first.place.page}` }),
8756
+ Object.assign(document.createElement('span'), { textContent: `${items.length > 1 ? `Place 1 of ${items.length}: ` : ''}where the read took ${first.proposal.asRead}${chosen ? '' : ' (the first choice; pick one to see its place)'}${marked ? '' : ' (no area marked)'}` }));
8757
+ open.append(frame, caption);
8758
+ open.addEventListener('click', () => openSetupPlace(entry, row, first, open));
8759
+ paintPlacePicture({ digest: first.digest, url: setupPlaceUrl(entry, row, first), place: first.place }, frame);
8760
+ wrap.append(open);
8761
+ if (items.length > 1) {
8762
+ const more = document.createElement('div'); more.className = 'ai-chat-setup-place-chips';
8763
+ more.setAttribute('role', 'group'); more.setAttribute('aria-label', 'Other places the read took these levels from');
8764
+ for (const item of items.slice(1)) more.append(setupPlaceChip(entry, row, item));
8765
+ wrap.append(more);
8766
+ }
8767
+ if (unplaced.length) wrap.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-height-unplaced', textContent: `Not placed on the drawings: ${unplaced.join(' ')}` }));
8768
+ return wrap;
8769
+ }
8770
+
7558
8771
  function loadSetupQuestion(entry) {
7559
8772
  if (entry.loading) return;
7560
8773
  entry.loading = true;
@@ -7574,6 +8787,7 @@
7574
8787
  const caret = focused ? textCaret(document.activeElement) : null;
7575
8788
  const next = rememberCard(entry, paintSetupCard(entry, old.dataset.eventId, old.dataset.eventSequence), old.dataset.eventId, old.dataset.eventSequence);
7576
8789
  old.replaceWith(next);
8790
+ keepRowsScroll(next);
7577
8791
  if (focused) focusHeightControl(next, focused, caret);
7578
8792
  }
7579
8793
 
@@ -7590,7 +8804,7 @@
7590
8804
 
7591
8805
  const setupSettled = (row) => row.status === 'settled';
7592
8806
  const setupLive = (row) => row.status !== 'superseded';
7593
- const scaleTag = { floless: 'FLOLESS FIT', 'floless-candidate': 'FLOLESS CANDIDATE', read: 'THE READ’S MEASUREMENT', 'read-of-picture': 'THE READ’S READING OF YOUR PICTURE' };
8807
+ const scaleTag = { floless: 'FLOLESS FIT', 'floless-candidate': 'FLOLESS CANDIDATE', 'floless-scale-bar': 'THE SHEET’S SCALE BAR', read: 'THE READ’S MEASUREMENT', 'read-of-picture': 'THE READ’S READING OF YOUR PICTURE' };
7594
8808
  const levelTag = { 'drawing-text': 'ON THE DRAWING', 'drawing-picture': 'READ OFF THE PICTURE · NOT CHECKED', 'read-of-picture': 'THE READ’S READING OF YOUR PICTURE' };
7595
8809
  const originText = (o) => `${o.xLabel}/${o.yLabel}`;
7596
8810
  const viewName = (row) => `${row.view.sheet}${row.view.title ? ` · ${row.view.title}` : ''}`;
@@ -7656,6 +8870,12 @@
7656
8870
  const text = document.createElement('span');
7657
8871
  text.textContent = row.status === 'needs-new-choices' ? `${setupAnswerText(row)}. Waiting for the read to offer other points.` : setupAnswerText(row);
7658
8872
  done.append(glyph, text);
8873
+ // #2777: the place of the level the person confirmed, the same chip the list shows.
8874
+ // By the proposal the person confirmed; an answer recorded before that was kept counts only when its value is unique.
8875
+ const sameValue = row.kind === 'level' && row.answer?.how === 'confirmed' ? (row.proposals || []).filter((proposal) => proposal.value === row.answer.value) : [];
8876
+ const chosen = row.answer?.proposalId ? (row.proposals || []).find((proposal) => proposal.id === row.answer.proposalId) : sameValue.length === 1 ? sameValue[0] : null;
8877
+ const chosenPlace = chosen ? setupPlaceItems(row, chosen)[0] : null;
8878
+ if (chosenPlace) done.append(setupPlaceChip(entry, row, chosenPlace));
7659
8879
  if (open && !row.frozen) {
7660
8880
  const change = heightActionButton('Change', idFor('change'), instance, 'ai-chat-height-change', entry.busy ? 'An answer is still being saved — wait for it to finish' : null);
7661
8881
  change.setAttribute('aria-label', `Change your answer for ${instance}`);
@@ -7723,7 +8943,7 @@
7723
8943
  const ownedSlot = drawingEntryCurrent(entry) && ui.approvalTray?.querySelector('.ai-chat-drawing-step')?.dataset.drawingStep;
7724
8944
  const ownedNode = ownedSlot ? ui.approvalTray.querySelector('.ai-chat-drawing-step') : null;
7725
8945
  const pendingFocusId = ownedNode?.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
7726
- const failedField = ownedNode && ([...ownedNode.querySelectorAll('input')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
8946
+ const failedField = ownedNode && ([...ownedNode.querySelectorAll('input, textarea')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
7727
8947
  const failedFieldId = failedField?.dataset.commandId, failedCaret = failedField ? textCaret(failedField) : null;
7728
8948
  let saved = false;
7729
8949
  const withSource = answers.map((answer) => withAnswerSource(answer, answerSourcePayload(`s:${entry.questionId}:${answer.key}`)));
@@ -7742,7 +8962,7 @@
7742
8962
  method: 'POST', body: JSON.stringify({ chatId: entry.chatId, answers: withSource }),
7743
8963
  });
7744
8964
  entry.view = result.question;
7745
- saved = true; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
8965
+ saved = true; entry.failedSubmission = null; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
7746
8966
  for (const answer of answers) {
7747
8967
  entry.changing.delete(answer.key); entry.drafts.delete(answer.key); entry.drafts.delete(`${answer.key}\u0000none`);
7748
8968
  if (entry.activeItem === answer.key) { entry.activeItem = null; entry.reopenedAt = 0; }
@@ -8174,6 +9394,31 @@
8174
9394
  // writing again ends it, and so does a declined approval (it never will run). Codex ends each tool by its own item
8175
9395
  // id (#2102), so one finishing does not end another running beside it.
8176
9396
  const TOOL_ENDED = new Set(['completed', 'failed', 'denied', 'declined', 'error']);
9397
+ // #2848: describe only work whose lifetime the provider actually reports. Claude's starts have no
9398
+ // matching ends, so its label stays generic (its existing avatar heuristic is separate). Never lift
9399
+ // commands, inputs, reasoning or earlier assistant narration into a claim about current work.
9400
+ function liveActivityText() {
9401
+ if (!turnIsVisiblyActive()) return '';
9402
+ if (state.source && state.source.readyState !== 1) return 'Reconnecting to this conversation…';
9403
+ if (state.chat?.state === 'awaiting-approval' || state.chat?.pendingApproval) {
9404
+ return state.chat?.pendingApproval?.kind === 'question' ? 'Waiting for your answer…' : 'Waiting for your approval…';
9405
+ }
9406
+ if (state.chat?.provider !== 'codex') return 'Processing your request…';
9407
+ const running = new Map();
9408
+ for (const event of state.events || []) {
9409
+ if (event.turnId !== state.chat?.activeTurn?.turnId || event.type !== 'tool' || event.payload?.plain === true) continue;
9410
+ const key = event.providerItemId;
9411
+ // An unmatched/historical receipt is not evidence that a tool is running now.
9412
+ if (!key) continue;
9413
+ if (TOOL_ENDED.has(event.payload?.status)) running.delete(key);
9414
+ else if (event.payload?.status === 'inProgress') running.set(key, event.payload);
9415
+ }
9416
+ const tool = [...running.values()].at(-1);
9417
+ if (tool?.tool === 'webSearch') return 'Searching the web…';
9418
+ if (tool?.tool === 'file-change') return 'Updating files…';
9419
+ return 'Processing your request…';
9420
+ }
9421
+
8177
9422
  function liveFloMood() {
8178
9423
  if (state.chat?.state === 'awaiting-approval' || state.chat?.pendingApproval) return 'idle';
8179
9424
  const turnId = state.chat?.activeTurn?.turnId;
@@ -8194,18 +9439,21 @@
8194
9439
  }
8195
9440
 
8196
9441
  // The feed is rebuilt on every event, so the live row is one kept node: Flo carries on instead of restarting
8197
- // on every streamed word. The row is decoration; announceLiveResponseOnce speaks for it.
9442
+ // on every streamed word. Only the avatar is decoration; the full label remains readable even
9443
+ // when CSS truncates it. The separate live region announces coalesced changes.
8198
9444
  function renderLiveStatus() {
8199
9445
  if (!state.liveFlo) {
8200
9446
  const item = document.createElement('div'); item.className = 'ai-chat-live-status';
8201
- item.setAttribute('aria-hidden', 'true');
8202
9447
  const label = document.createElement('span'); label.className = 'ai-chat-live-label';
9448
+ const flo = typeof floAvatar === 'function' ? floAvatar(item, { size: 22, mood: 'thinking', hatRoom: true }) : null;
8203
9449
  item.append(label);
8204
- state.liveFlo = { item, flo: typeof floAvatar === 'function' ? floAvatar(item, { size: 22, mood: 'thinking', hatRoom: true }) : null };
9450
+ state.liveFlo = { item, label, flo };
8205
9451
  }
8206
9452
  const mood = liveFloMood();
8207
9453
  state.liveFlo.item.dataset.mood = mood;
8208
9454
  state.liveFlo.flo?.setMood(mood, mood === 'working');
9455
+ const text = liveActivityText();
9456
+ if (state.liveFlo.label.textContent !== text) state.liveFlo.label.textContent = text;
8209
9457
  return state.liveFlo.item;
8210
9458
  }
8211
9459
 
@@ -8214,6 +9462,10 @@
8214
9462
  const wasResponding = state.liveStatusTurnId !== null;
8215
9463
  if (!turnId) {
8216
9464
  state.liveStatusTurnId = null;
9465
+ state.liveActivityAnnouncement = null;
9466
+ if (state.liveActivityTimer) clearTimeout(state.liveActivityTimer);
9467
+ state.liveActivityTimer = null;
9468
+ if (state.liveFlo) state.liveFlo.label.textContent = '';
8217
9469
  // The screen-reader announcement is a transient status. Once the durable turn ends,
8218
9470
  // leaving its text behind makes the finished chat sound as though it is still working.
8219
9471
  // Cleared once, when that turn ends — not on every idle repaint: the 5 s poll repaints the
@@ -8222,15 +9474,25 @@
8222
9474
  if (wasResponding) ui.status.textContent = '';
8223
9475
  return;
8224
9476
  }
8225
- if (state.liveStatusTurnId === turnId) return;
9477
+ const chatId = state.chat?.chatId;
9478
+ const text = liveActivityText();
9479
+ const key = JSON.stringify([chatId, turnId, text]);
9480
+ if (state.liveActivityAnnouncement === key) return;
9481
+ if (state.liveActivityTimer) clearTimeout(state.liveActivityTimer);
9482
+ const first = state.liveStatusTurnId !== turnId || state.liveStatusChatId !== chatId;
8226
9483
  state.liveStatusTurnId = turnId;
8227
- const provider = providerLabels[state.chat?.provider] || 'AI';
8228
- ui.status.textContent = '';
8229
- requestAnimationFrame(() => {
9484
+ state.liveStatusChatId = chatId;
9485
+ state.liveActivityAnnouncement = key;
9486
+ if (first) ui.status.textContent = '';
9487
+ const announce = () => {
8230
9488
  // Recovery or completion may land between scheduling and painting this transient sentence.
8231
- if (!turnIsVisiblyActive() || state.chat?.activeTurn?.turnId !== turnId || state.liveStatusTurnId !== turnId) return;
8232
- ui.status.textContent = `${provider} is responding.`;
8233
- });
9489
+ if (!turnIsVisiblyActive() || state.chat?.chatId !== chatId || state.chat?.activeTurn?.turnId !== turnId
9490
+ || state.liveActivityAnnouncement !== key || liveActivityText() !== text) return;
9491
+ state.liveActivityTimer = null;
9492
+ if (ui.status.textContent !== text) ui.status.textContent = text;
9493
+ };
9494
+ if (first) requestAnimationFrame(announce);
9495
+ else state.liveActivityTimer = setTimeout(announce, 750);
8234
9496
  }
8235
9497
 
8236
9498
  function renderedAnswerTarget(events, eventId, turnId, type = 'assistant-message') {
@@ -8310,7 +9572,7 @@
8310
9572
  } catch { caret = null; } // a checkbox or radio has no caret, and some engines throw on reading it
8311
9573
  // A reused card node is detached and re-attached here, and a detached element forgets its scroll: the height
8312
9574
  // card's lists, and the readiness card's own scroll area and table (#2439), are noted and put back below.
8313
- for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table')) {
9575
+ for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table, .ai-chat-auto-review-record')) {
8314
9576
  list.keptScrollTop = list.scrollTop; list.keptScrollLeft = list.scrollLeft;
8315
9577
  }
8316
9578
  ui.feed.replaceChildren();
@@ -8389,6 +9651,8 @@
8389
9651
  if (node) links.push({ turnId: event.turnId, node });
8390
9652
  continue;
8391
9653
  }
9654
+ // #2777: the places an answer showed on the drawings, held under it like its sources.
9655
+ if (event.type === 'place') { const node = renderPlaceStrip(event); if (node) links.push({ turnId: event.turnId, node }); continue; }
8392
9656
  if (['tool', 'usage', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
8393
9657
  // FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
8394
9658
  // held and shown under the answer, so they never cut one answer into fragments.
@@ -8409,6 +9673,11 @@
8409
9673
  // never looks like a failed response. Recovery deliberately has no live indicator.
8410
9674
  if (turnIsVisiblyActive()) ui.feed.append(renderLiveStatus());
8411
9675
  }
9676
+ // Lists first, so a card that takes the keyboard below lands on a control the person can see (focusFeedCard).
9677
+ for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table, .ai-chat-auto-review-record')) {
9678
+ if (typeof list.keptScrollTop === 'number' && list.scrollTop !== list.keptScrollTop) list.scrollTop = list.keptScrollTop;
9679
+ if (typeof list.keptScrollLeft === 'number' && list.scrollLeft !== list.keptScrollLeft) list.scrollLeft = list.keptScrollLeft;
9680
+ }
8412
9681
  let refocused = null;
8413
9682
  if (focusedNode?.isConnected && ui.feed.contains(focusedNode)) {
8414
9683
  if (document.activeElement !== focusedNode) focusedNode.focus({ preventScroll: true });
@@ -8438,10 +9707,6 @@
8438
9707
  if (refocused && caret) {
8439
9708
  try { refocused.setSelectionRange(caret.start, caret.end, caret.direction); } catch { /* no caret on this control */ }
8440
9709
  }
8441
- for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table')) {
8442
- if (typeof list.keptScrollTop === 'number' && list.scrollTop !== list.keptScrollTop) list.scrollTop = list.keptScrollTop;
8443
- if (typeof list.keptScrollLeft === 'number' && list.scrollLeft !== list.keptScrollLeft) list.scrollLeft = list.keptScrollLeft;
8444
- }
8445
9710
  // Removing a focused control makes the browser lay out the half-built feed, which clamps its scroll near the top.
8446
9711
  // Scrolled up, the reader stays where they were. At the end, they are put back there now, before any scroll event
8447
9712
  // can read that clamp as the reader moving up (keepFeedFollowing); the frame below settles late layout.
@@ -8453,7 +9718,11 @@
8453
9718
  if (state.feedLeftEnd || state.answerJump) return; // the reader moved up, or another conversation jumped to an answer
8454
9719
  ui.feed.scrollTop = ui.feed.scrollHeight;
8455
9720
  // A control that kept keyboard focus across the repaint (the questions card sits above the answer) stays in sight.
8456
- if (ui.feed.contains(document.activeElement)) document.activeElement.scrollIntoView({ block: 'nearest' });
9721
+ // In a card's own list it is the list that is brought into sight: scrolling to the control would pull a list the
9722
+ // person scrolled away from back to it, under their pointer, on every 5 s poll.
9723
+ if (ui.feed.contains(document.activeElement)) {
9724
+ (document.activeElement.closest('.ai-chat-height-rows') || document.activeElement).scrollIntoView({ block: 'nearest' });
9725
+ }
8457
9726
  updateOffscreenActivity();
8458
9727
  });
8459
9728
  }
@@ -10571,6 +11840,7 @@
10571
11840
  source.onerror = () => {
10572
11841
  if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
10573
11842
  ui.hint.textContent = 'Reconnecting to this conversation…';
11843
+ paintEvents();
10574
11844
  if (source.readyState === EventSource.CLOSED) scheduleEventReconnect(chatId, scope, generation);
10575
11845
  };
10576
11846
  }