@floless/app 0.160.0 → 0.161.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.
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) {
@@ -2598,7 +2691,7 @@
2598
2691
  const change = button('Change…', 'shell.chat-cite-change', 'ai-chat-source-action quiet');
2599
2692
  change.setAttribute('aria-label', 'Change the source for this claim');
2600
2693
  change.setAttribute('aria-haspopup', 'dialog');
2601
- change.dataset.tip = 'Pick a different sheet or model member. The earlier choice stays in the record';
2694
+ change.dataset.tip = 'Pick a different source. The earlier choice stays in the record';
2602
2695
  change.addEventListener('click', () => openSourcePicker(row, turnId, row.choice.eventId));
2603
2696
  chip.append(open, marks, change);
2604
2697
  const earlier = row.choices.length > 1 ? row.choices[row.choices.length - 2] : null;
@@ -2652,38 +2745,50 @@
2652
2745
  chip.append(note);
2653
2746
  }
2654
2747
 
2748
+ /** #2692: what the picker can list, in order: the project's drawings and model, its Knowledge, and this conversation's files. */
2749
+ const SOURCE_KINDS = [
2750
+ { id: 'refs', label: 'Drawings & model', search: 'Search sheets and model members', list: 'Sheets and model members' },
2751
+ { id: 'kb', label: 'Knowledge', search: 'Search this project’s Knowledge', list: 'Knowledge pages' },
2752
+ { id: 'files', label: 'Attached files', search: 'Search attached files by name', list: 'Attached files' },
2753
+ ];
2754
+
2655
2755
  /**
2656
2756
  * #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.
2757
+ * read) and, #2692, the project's published Knowledge pages and the files sent with this conversation's messages, in a
2758
+ * small dialog under the claim's chip. Not the message box's @ list: nothing goes in the message. The pick is sent by
2759
+ * identity with a request id made when it is picked (a retry sends the same one); the server resolves the source from
2760
+ * FloLess's own records. Everything the save needs is taken now, from the chip as painted: a reply that lands after the
2761
+ * person moved on (another conversation, the list closed) changes nothing on screen.
2661
2762
  */
2662
2763
  function openSourcePicker(row, turnId, replaces) {
2663
2764
  closeSourcePicker(false);
2664
2765
  if (!row.chatId) { announce('Open this conversation again to choose a source.'); return; }
2665
2766
  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,
2767
+ const picker = { row, turnId, replaces, command, chatId: row.chatId, projects: null, projectId: null, kind: null, query: '', items: [], more: [],
2667
2768
  status: 'loading', note: '', active: -1, seq: 0, timer: null, saving: null, problem: '', pending: null };
2668
2769
  state.sourcePicker = picker;
2669
2770
  const dialog = document.createElement('div'); dialog.className = 'ai-chat-source-picker';
2670
2771
  dialog.setAttribute('role', 'dialog'); dialog.setAttribute('aria-label', 'Choose a source');
2671
2772
  const head = Object.assign(document.createElement('p'), { className: 'ai-chat-source-picker-head', textContent: 'Choose the source for this claim' });
2773
+ const kinds = document.createElement('div'); kinds.className = 'ai-chat-source-picker-kinds'; kinds.hidden = true;
2774
+ kinds.setAttribute('role', 'group'); kinds.setAttribute('aria-label', 'What to choose from');
2672
2775
  const projects = document.createElement('div'); projects.className = 'ai-chat-source-picker-projects'; projects.hidden = true;
2776
+ projects.setAttribute('role', 'group'); projects.setAttribute('aria-label', 'Project');
2673
2777
  const input = document.createElement('input');
2674
- input.type = 'search'; input.className = 'ai-chat-source-picker-input'; input.placeholder = 'Search sheets and model members';
2778
+ input.type = 'search'; input.className = 'ai-chat-source-picker-input'; input.placeholder = SOURCE_KINDS[0].search;
2675
2779
  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;
2780
+ input.setAttribute('aria-label', SOURCE_KINDS[0].search); input.autocomplete = 'off'; input.spellcheck = false;
2677
2781
  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');
2782
+ list.setAttribute('role', 'listbox'); list.setAttribute('aria-label', SOURCE_KINDS[0].list);
2679
2783
  input.setAttribute('aria-controls', list.id);
2680
2784
  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;
2785
+ // What choosing is, and is not: a record of the person's pick, never a check of the claim.
2786
+ const hint = Object.assign(document.createElement('p'), { className: 'ai-chat-source-picker-limit',
2787
+ textContent: 'Choosing records that you picked this source. It does not show the claim is correct.' });
2788
+ dialog.append(head, kinds, projects, input, list, foot, hint);
2789
+ picker.dialog = dialog; picker.input = input; picker.list = list; picker.foot = foot; picker.projectRow = projects; picker.kindRow = kinds;
2685
2790
  (ui.feed.closest('.ai-chat-shell') || document.body).append(dialog);
2686
- input.addEventListener('input', () => { picker.query = input.value; searchSources(picker); });
2791
+ input.addEventListener('input', () => { picker.query = input.value; searchSources(picker, picker.kind === 'files' ? 0 : 200); });
2687
2792
  input.addEventListener('keydown', (event) => sourcePickerKey(picker, event));
2688
2793
  dialog.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeSourcePicker(true); } });
2689
2794
  // A click elsewhere closes it and leaves the focus where the person clicked.
@@ -2730,6 +2835,45 @@
2730
2835
  box.style.top = `${Math.round(below + height <= window.innerHeight - 8 ? below : Math.max(8, at.top - height - 4))}px`;
2731
2836
  }
2732
2837
 
2838
+ /**
2839
+ * #2692: the files a person may choose — those sent with a message, never a draft not yet sent and never a picture given as
2840
+ * an answer to a question card (the server's `choosableAttachments`), newest first.
2841
+ */
2842
+ function choosableFiles() {
2843
+ return (state.chat?.attachments ?? []).filter((file) => file && file.turnId !== null && file.turnId !== undefined && file.purpose !== 'answer-evidence')
2844
+ .slice().sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
2845
+ }
2846
+
2847
+ function fileSizeLabel(bytes) {
2848
+ const n = Number(bytes) || 0;
2849
+ if (n < 1024) return `${n} bytes`;
2850
+ if (n < 1024 * 1024) return `${Math.max(1, Math.round(n / 1024))} KB`;
2851
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
2852
+ }
2853
+
2854
+ /**
2855
+ * #2692: one row of the list, whatever its kind: what is shown, and what is sent — the pick by identity, the project it is
2856
+ * in (none for a file) and the decision's key. Everything is taken from the answer that listed the row, never from the
2857
+ * picker's state at the moment of the click, so a Knowledge page carries the version it was listed from.
2858
+ */
2859
+ function sourceItemOf(kind, value, projectId, generationId) {
2860
+ if (kind === 'files') {
2861
+ const pick = { kind: 'attachment', attachmentId: value.attachmentId };
2862
+ const name = value.fileName;
2863
+ return { key: JSON.stringify(['file', String(value.attachmentId).toLowerCase()]), pick, projectId: null, label: name, name,
2864
+ meta: `${fileSizeLabel(value.bytes)} · sent ${assumedWhen({ assumedAt: value.createdAt })}`, tip: `${name} · attached to this conversation` };
2865
+ }
2866
+ if (kind === 'kb') {
2867
+ const pick = { kind: 'kb-page', slug: value.slug, generationId };
2868
+ const name = value.title || value.slug;
2869
+ return { key: JSON.stringify(['kb', projectId, generationId, value.slug]), pick, projectId, label: name, name, meta: value.slug,
2870
+ tip: `Knowledge page ${name} · ${value.slug}` };
2871
+ }
2872
+ const item = mentionOf(value);
2873
+ return { key: JSON.stringify(['ref', projectId, item.key]), pick: item.pick, projectId, label: item.label,
2874
+ name: `${value.kind === 'sheet' ? 'Sheet' : 'Member'} ${item.label}`, meta: refDetail(value), tip: item.tip };
2875
+ }
2876
+
2733
2877
  async function loadSourceProjects(picker) {
2734
2878
  let projects = null;
2735
2879
  try {
@@ -2739,52 +2883,126 @@
2739
2883
  if (state.sourcePicker !== picker || state.chat?.chatId !== picker.chatId) return;
2740
2884
  if (!projects) { picker.status = 'error'; picker.note = 'FloLess could not read which projects are in this conversation.'; paintSourcePicker(picker); return; }
2741
2885
  picker.projects = projects;
2742
- if (!projects.length) {
2886
+ picker.projectId = projects[0]?.projectId ?? null;
2887
+ // A conversation with a project starts on its drawings and model; one with only files, on its files.
2888
+ if (!projects.length && !choosableFiles().length) {
2743
2889
  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.';
2890
+ 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
2891
  paintSourcePicker(picker);
2746
2892
  return;
2747
2893
  }
2748
- picker.projectId = projects[0].projectId;
2894
+ setSourceKind(picker, projects.length ? 'refs' : 'files', false);
2895
+ }
2896
+
2897
+ /** Switches what the list shows. The search starts again, empty, and the focus stays where the person is. */
2898
+ function setSourceKind(picker, kind, keepFocus = true) {
2899
+ picker.kind = kind;
2900
+ picker.query = ''; picker.input.value = '';
2901
+ picker.items = []; picker.more = []; picker.active = -1; picker.problem = '';
2902
+ picker.status = 'loading';
2903
+ paintSourcePicker(picker);
2749
2904
  searchSources(picker, 0);
2905
+ if (!keepFocus) picker.input.focus({ preventScroll: true });
2750
2906
  }
2751
2907
 
2752
2908
  function searchSources(picker, delay = 150) {
2753
- if (!picker.projectId) return;
2754
2909
  clearTimeout(picker.timer);
2755
2910
  const seq = ++picker.seq;
2911
+ const kind = picker.kind;
2912
+ if (!kind) return;
2756
2913
  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;
2914
+ const settle = (fill) => {
2915
+ // A newer search, another kind or project, a closed list or another conversation: this answer is for a question
2916
+ // nobody is asking now.
2917
+ if (state.sourcePicker !== picker || picker.seq !== seq || picker.kind !== kind || state.chat?.chatId !== picker.chatId) return;
2763
2918
  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
- }
2919
+ picker.items = []; picker.more = [];
2920
+ fill();
2921
+ if (picker.status === 'options' && !picker.items.length) picker.status = 'empty';
2771
2922
  picker.active = picker.status === 'options' ? 0 : -1;
2772
2923
  paintSourcePicker(picker);
2773
- announce(picker.status === 'options' ? `${picker.refs.length + picker.heldBack} ${picker.refs.length + picker.heldBack === 1 ? 'match' : 'matches'}`
2924
+ announce(picker.status === 'options' ? `${picker.items.length} ${picker.items.length === 1 ? 'match' : 'matches'}`
2774
2925
  : picker.status === 'empty' ? 'No matches' : picker.note);
2926
+ };
2927
+ if (kind === 'files') {
2928
+ const q = picker.query.trim().toLowerCase();
2929
+ settle(() => {
2930
+ const files = choosableFiles();
2931
+ 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; }
2932
+ picker.items = files.filter((file) => !q || String(file.fileName).toLowerCase().includes(q)).map((file) => sourceItemOf('files', file, null, null));
2933
+ picker.status = 'options';
2934
+ });
2935
+ return;
2936
+ }
2937
+ const projectId = picker.projectId;
2938
+ if (!projectId) {
2939
+ settle(() => { picker.status = 'note'; picker.note = kind === 'kb' ? 'This conversation has no project, so there is no Knowledge to choose from.'
2940
+ : 'This conversation has no project, so there are no sheets or model members to choose from.'; });
2941
+ return;
2942
+ }
2943
+ picker.timer = setTimeout(async () => {
2944
+ let body = null;
2945
+ const url = kind === 'kb'
2946
+ ? `/api/chat/conversations/${encodeURIComponent(picker.chatId)}/knowledge?${picker.row.owner}&projectId=${encodeURIComponent(projectId)}&q=${encodeURIComponent(picker.query)}&limit=20`
2947
+ : `/api/projects/${encodeURIComponent(projectId)}/refs?q=${encodeURIComponent(picker.query)}&kinds=sheet,member`;
2948
+ try { body = await request(url); } catch { body = null; }
2949
+ if (picker.projectId !== projectId) return;
2950
+ settle(() => {
2951
+ if (!body) {
2952
+ picker.status = 'error';
2953
+ 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.';
2954
+ } else if (kind === 'kb') {
2955
+ const generationId = body.generation?.generationId;
2956
+ if (!generationId) { picker.status = 'note'; picker.note = 'This project has no published Knowledge yet.'; return; }
2957
+ if (body.needsQuery) { picker.status = 'note'; picker.note = 'Type to search this project’s Knowledge.'; return; }
2958
+ picker.items = (Array.isArray(body.pages) ? body.pages : []).filter((page) => page && typeof page.slug === 'string')
2959
+ .map((page) => sourceItemOf('kb', page, projectId, generationId));
2960
+ // A search that could not look at every page, or found more than it lists, says so: "no match" is never claimed.
2961
+ if (body.incomplete) picker.more.push('FloLess could not look through every page just now, so some may be missing.');
2962
+ if (body.moreMatches) picker.more.push('More pages match. Type more of the name to narrow the list.');
2963
+ picker.status = 'options';
2964
+ if (!picker.items.length && picker.more.length) { picker.status = 'note'; picker.note = picker.more.shift(); }
2965
+ } else if (body.status && body.status !== 'ok') { picker.status = 'note'; picker.note = String(body.note || ''); }
2966
+ else {
2967
+ picker.items = (Array.isArray(body.refs) ? body.refs : []).map((ref) => sourceItemOf('refs', ref, projectId, null));
2968
+ const heldBack = Number(body.heldBack) || 0;
2969
+ if (heldBack) picker.more.push(`${heldBack} more match. Type more of the name to narrow the list.`);
2970
+ picker.status = 'options';
2971
+ }
2972
+ });
2775
2973
  }, delay);
2776
2974
  }
2777
2975
 
2778
2976
  function paintSourcePicker(picker) {
2779
- const { list, foot, input, projectRow } = picker;
2977
+ const { list, foot, input, projectRow, kindRow } = picker;
2978
+ const kind = SOURCE_KINDS.find((row) => row.id === picker.kind) ?? SOURCE_KINDS[0];
2979
+ // The two rows are rebuilt on every paint: a person on one of their buttons stays on it (by what it does).
2980
+ const focused = document.activeElement;
2981
+ const refocus = focused && (kindRow.contains(focused) || projectRow.contains(focused)) ? focused.dataset.commandId : null;
2982
+ kindRow.replaceChildren();
2983
+ kindRow.hidden = !picker.kind;
2984
+ for (const option of picker.kind ? SOURCE_KINDS : []) {
2985
+ const pick = button(option.label, `shell.chat-cite-choose-kind#${option.id}`, 'ai-chat-source-picker-project');
2986
+ pick.setAttribute('aria-pressed', String(option.id === picker.kind));
2987
+ pick.addEventListener('click', () => { if (picker.kind !== option.id && !picker.saving) setSourceKind(picker, option.id); });
2988
+ kindRow.append(pick);
2989
+ }
2780
2990
  projectRow.replaceChildren();
2781
- projectRow.hidden = !(picker.projects?.length > 1);
2782
- for (const project of picker.projects?.length > 1 ? picker.projects : []) {
2991
+ const listsProjects = picker.kind !== 'files' && picker.projects?.length > 1;
2992
+ projectRow.hidden = !listsProjects;
2993
+ for (const project of listsProjects ? picker.projects : []) {
2783
2994
  const pick = button(project.label || 'Project', `shell.chat-cite-choose-project#${project.projectId}`, 'ai-chat-source-picker-project');
2784
2995
  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(); });
2996
+ pick.addEventListener('click', () => {
2997
+ if (picker.saving) return;
2998
+ picker.projectId = project.projectId; picker.status = 'loading'; picker.items = []; picker.more = [];
2999
+ paintSourcePicker(picker); searchSources(picker, 0); input.focus();
3000
+ });
2786
3001
  projectRow.append(pick);
2787
3002
  }
3003
+ if (refocus) [...kindRow.children, ...projectRow.children].find((node) => node.dataset.commandId === refocus)?.focus({ preventScroll: true });
3004
+ input.placeholder = kind.search; input.setAttribute('aria-label', kind.search);
3005
+ list.setAttribute('aria-label', kind.list);
2788
3006
  list.replaceChildren();
2789
3007
  const status = (text) => {
2790
3008
  const line = Object.assign(document.createElement('div'), { className: 'ai-chat-mention-status', textContent: text });
@@ -2792,18 +3010,21 @@
2792
3010
  list.append(line);
2793
3011
  };
2794
3012
  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') {
3013
+ if (picker.status === 'loading') {
3014
+ status(picker.kind === 'kb' ? 'Looking through this project’s Knowledge…' : picker.kind === 'files' ? 'Listing attached files…'
3015
+ : picker.kind ? 'Loading the project’s sheets and members…' : 'Loading what you can choose from…');
3016
+ } else if (picker.status === 'note') status(picker.note);
3017
+ else if (picker.status === 'empty') {
3018
+ status(picker.query ? `Nothing matches “${picker.query}”.` : picker.kind === 'kb' ? 'This project’s Knowledge has no pages.'
3019
+ : 'This project has no sheets or model members yet.');
3020
+ } else if (picker.status === 'error') {
2799
3021
  status(picker.note);
2800
3022
  const retry = button('Try again', 'shell.chat-cite-choose-retry', 'ai-chat-choice');
2801
3023
  retry.setAttribute('role', 'option');
2802
3024
  retry.addEventListener('click', () => { picker.status = 'loading'; paintSourcePicker(picker); if (picker.projects) searchSources(picker, 0); else loadSourceProjects(picker); });
2803
3025
  list.append(retry);
2804
3026
  } else {
2805
- picker.refs.forEach((ref, index) => {
2806
- const item = mentionOf(ref);
3027
+ picker.items.forEach((item, index) => {
2807
3028
  const option = button('', `shell.chat-cite-choose-pick#${item.key}`, 'ai-chat-choice ai-chat-mention-option');
2808
3029
  option.id = `chat-source-option-${index}`; option.tabIndex = -1;
2809
3030
  option.setAttribute('role', 'option'); option.setAttribute('aria-selected', String(index === picker.active));
@@ -2812,15 +3033,15 @@
2812
3033
  const busy = picker.saving?.key === item.key;
2813
3034
  if (picker.saving) option.setAttribute('aria-disabled', 'true');
2814
3035
  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) });
3036
+ const name = Object.assign(document.createElement('span'), { className: 'ai-chat-mention-name', textContent: item.name });
3037
+ const meta = Object.assign(document.createElement('small'), { className: 'ai-chat-skill-origin', textContent: item.meta });
2817
3038
  option.append(name, meta);
2818
3039
  option.addEventListener('pointerdown', (event) => event.preventDefault()); // the search box keeps focus
2819
- option.addEventListener('click', () => chooseSource(picker, ref));
3040
+ option.addEventListener('click', () => chooseSource(picker, item));
2820
3041
  list.append(option);
2821
3042
  if (index === picker.active) activeId = option.id;
2822
3043
  });
2823
- if (picker.heldBack) status(`${picker.heldBack} more match. Type more of the name to narrow the list.`);
3044
+ for (const line of picker.more) status(line);
2824
3045
  }
2825
3046
  if (activeId) { input.setAttribute('aria-activedescendant', activeId); document.getElementById(activeId)?.scrollIntoView?.({ block: 'nearest' }); }
2826
3047
  else input.removeAttribute('aria-activedescendant');
@@ -2831,25 +3052,23 @@
2831
3052
 
2832
3053
  function sourcePickerKey(picker, event) {
2833
3054
  if (event.isComposing) return;
2834
- const count = picker.status === 'options' ? picker.refs.length : 0;
3055
+ const count = picker.status === 'options' ? picker.items.length : 0;
2835
3056
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
2836
3057
  event.preventDefault();
2837
3058
  if (count) { picker.active = (picker.active + (event.key === 'ArrowDown' ? 1 : -1) + count) % count; paintSourcePicker(picker); }
2838
3059
  } else if (event.key === 'Enter') {
2839
3060
  event.preventDefault();
2840
- if (count && picker.refs[picker.active]) chooseSource(picker, picker.refs[picker.active]);
3061
+ if (count && picker.items[picker.active]) chooseSource(picker, picker.items[picker.active]);
2841
3062
  }
2842
3063
  }
2843
3064
 
2844
3065
  /** 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) {
3066
+ async function chooseSource(picker, item) {
2846
3067
  if (picker.saving) return;
2847
3068
  if (picker.stale) { announce('Still looking. Pick again when the list updates.'); return; }
2848
- const item = mentionOf(ref);
2849
3069
  // 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() };
3070
+ // The key holds the project (the same sheet identity can be in two projects) and, for a page, the version.
3071
+ if (picker.pending?.key !== item.key) picker.pending = { key: item.key, requestId: crypto.randomUUID() };
2853
3072
  picker.saving = { key: item.key }; picker.problem = '';
2854
3073
  paintSourcePicker(picker);
2855
3074
  const { row, turnId } = picker;
@@ -2857,7 +3076,7 @@
2857
3076
  try {
2858
3077
  const result = await request(`/api/chat/conversations/${encodeURIComponent(row.chatId)}/citations/${encodeURIComponent(row.citationId)}/choose`, {
2859
3078
  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 }),
3079
+ projectId: item.projectId, pick: item.pick, requestId: picker.pending.requestId, replaces: picker.replaces }),
2861
3080
  });
2862
3081
  saved = result?.event ?? null;
2863
3082
  } catch (error) {
@@ -2880,6 +3099,63 @@
2880
3099
  picker.input.focus({ preventScroll: true });
2881
3100
  }
2882
3101
 
3102
+ /*
3103
+ * #2777 slices B and C: the places the AI asked FloLess to show (`floless_place`), as one strip under its answer, above
3104
+ * the question it asks about them. FloLess resolved every place itself; the event carries each place with the digest
3105
+ * its picture link must name, so a chip can only open what FloLess found. An entry it could not place says why.
3106
+ */
3107
+ /** Whether a label names this sheet as a whole token: "S1" is not named by a label about "S10". */
3108
+ const namesSheet = (label, sheet) => new RegExp(`(?<![A-Za-z0-9])${sheet.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![A-Za-z0-9])`).test(label);
3109
+ const placeBox = (v) => Array.isArray(v) && v.length === 4 && v.every((n) => typeof n === 'number' && Number.isFinite(n));
3110
+ function placeOfEntry(entry) {
3111
+ const place = entry && typeof entry === 'object' ? entry.place : null;
3112
+ if (!place || typeof place !== 'object' || (place.kind !== 'region' && place.kind !== 'sheet')) return null;
3113
+ if (typeof place.sheet !== 'string' || !place.sheet || !Number.isInteger(place.page) || typeof place.pageId !== 'string'
3114
+ || !/^[0-9a-f]{64}$/.test(String(place.sourceHash || '')) || !placeBox(place.pageBounds)) return null;
3115
+ if (place.kind === 'region' && !placeBox(place.region)) return null;
3116
+ return typeof entry.digest === 'string' && /^[0-9a-f]{64}$/.test(entry.digest) ? place : null;
3117
+ }
3118
+ function renderPlaceStrip(event) {
3119
+ const entries = Array.isArray(event.payload?.entries) ? event.payload.entries.slice(0, 8) : [];
3120
+ if (!entries.length || !state.chat?.chatId) return null;
3121
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-sources ai-chat-place-strip';
3122
+ const head = document.createElement('span'); head.className = 'ai-chat-sources-head'; head.textContent = 'Where this is on the drawings';
3123
+ 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.';
3124
+ const list = document.createElement('div'); list.className = 'ai-chat-sources-list';
3125
+ const notes = [];
3126
+ entries.forEach((entry, ix) => {
3127
+ const label = typeof entry?.label === 'string' && entry.label.trim() ? entry.label.trim().slice(0, 120) : `Place ${ix + 1}`;
3128
+ const place = placeOfEntry(entry);
3129
+ if (!place) {
3130
+ notes.push(`${label}: ${typeof entry?.unplaced === 'string' && entry.unplaced ? entry.unplaced : 'FloLess could not show this place.'}`);
3131
+ return;
3132
+ }
3133
+ const marked = place.kind === 'region';
3134
+ const chip = button('', `shell.chat-place-open#${event.eventId} ${ix}`, 'ai-chat-source-chip ai-chat-place-chip');
3135
+ chip.dataset.commandInstanceLabel = `${label} on ${place.sheet}`;
3136
+ chip.setAttribute('aria-label', `Open sheet ${place.sheet}: ${label}`);
3137
+ chip.dataset.tip = marked ? `Opens sheet ${place.sheet} with this place outlined` : `Opens sheet ${place.sheet}; no area is marked`;
3138
+ chip.append(Object.assign(document.createElement('span'), { className: 'ai-chat-place-chip-label', textContent: label }),
3139
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-sheet', textContent: place.sheet }));
3140
+ const url = `/api/chat/places/${encodeURIComponent(state.chat.chatId)}/${encodeURIComponent(event.eventId)}/${ix}?${new URLSearchParams({ digest: entry.digest })}&${ownerQuery()}`;
3141
+ // A label that already names the sheet is not told it again ("Column line on S-301 on S-301").
3142
+ const titled = namesSheet(label, place.sheet) ? label : `${label} on ${place.sheet}`;
3143
+ chip.addEventListener('click', () => openDrawingPlace(place, {
3144
+ title: titled, opener: chip, url,
3145
+ 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.`
3146
+ : `The read marked this sheet but not a spot on it, so no area is outlined. Look over the whole sheet.`,
3147
+ commands: { close: 'shell.chat-place-close', view: 'shell.chat-place-view' },
3148
+ 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',
3149
+ run: () => { addToMessageBox(`Show me again where "${label}" is on the drawings.`); ui.input.focus?.(); } },
3150
+ ...(chatProjectId() ? { filter: { projectId: chatProjectId(), commandId: 'shell.chat-place-open-filter' } } : {}),
3151
+ }));
3152
+ list.append(chip);
3153
+ });
3154
+ wrap.append(head, list);
3155
+ 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}` }));
3156
+ return wrap;
3157
+ }
3158
+
2883
3159
  /** The Sources row of one answer, shown once, under the answer, after its last citation. */
2884
3160
  function renderCitationSources(event) {
2885
3161
  const last = state.events.filter((candidate) => candidate.type === 'citation' && candidate.turnId === event.turnId).at(-1);
@@ -2978,6 +3254,8 @@
2978
3254
  return chip?.querySelector('.ai-chat-source-open') ?? null;
2979
3255
  }
2980
3256
 
3257
+ 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.';
3258
+
2981
3259
  async function openCitedSource(row, turnId) {
2982
3260
  const entry = row.entry;
2983
3261
  const dialog = document.createElement('dialog'); dialog.className = 'ai-chat-source-viewer';
@@ -3011,9 +3289,15 @@
3011
3289
  const refused = async (response) => {
3012
3290
  if (response.status === 404) return 'FloLess no longer holds this source, or its project is no longer part of this conversation.';
3013
3291
  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.';
3292
+ // #2692: a chosen source says it changed since the person chose it, never since an answer cited it.
3293
+ if (entry.kind !== 'attachment') {
3294
+ return entry.chosen ? 'This Knowledge page has changed since you chose it, so FloLess does not show it as the page you chose.'
3295
+ : 'This Knowledge page has changed since the answer, so FloLess does not show it as the page the answer cited.';
3296
+ }
3015
3297
  // Changed bytes, or no longer the plain file that was attached: the server says which.
3016
3298
  const said = await response.json().catch(() => null);
3299
+ 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.';
3300
+ if (entry.chosen && said?.code === 'citation-source-not-as-attached') return CHOSEN_NOT_AS_ATTACHED;
3017
3301
  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
3302
  }
3019
3303
  // 503: FloLess could not check it just now; anything else is said as "try again", never as "gone".
@@ -3084,7 +3368,9 @@
3084
3368
  const text = await response.text();
3085
3369
  if (finished) return;
3086
3370
  // 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.';
3371
+ // #2692: a file the person chose says nothing about what the AI was given: the choice records no read.
3372
+ status.textContent = entry.chosen ? 'The file as it was attached.'
3373
+ : 'The file as it was attached. The AI is given at most the first 16,000 characters of a data file.';
3088
3374
  const shown = [...text];
3089
3375
  const pre = Object.assign(document.createElement('pre'), { className: 'ai-chat-source-viewer-text', tabIndex: 0,
3090
3376
  textContent: shown.length > 16000 ? shown.slice(0, 16000).join('') : text });
@@ -3109,8 +3395,9 @@
3109
3395
  const why = {
3110
3396
  'chat-page-closed': 'This conversation is no longer the one open here. Open it again, then press Open in its default app.',
3111
3397
  '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.',
3398
+ 'citation-source-changed': entry.chosen ? 'This file has changed since you chose it, so FloLess does not open it as the file you chose.'
3399
+ : 'This file has changed since the answer cited it, so FloLess does not open it as the cited file.',
3400
+ '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
3401
  'citation-source-unreadable': 'FloLess could not check this file just now. Try again in a moment.',
3115
3402
  }[error?.code] || '';
3116
3403
  if (!why) console.error('[chat] a cited file could not be opened in its app', error);
@@ -3124,7 +3411,7 @@
3124
3411
  if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3125
3412
  const { page } = await response.json();
3126
3413
  if (finished) return;
3127
- status.textContent = 'The Knowledge page as it was when the answer cited it.';
3414
+ 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
3415
  const article = document.createElement('div'); article.className = 'ai-chat-message-body ai-chat-source-viewer-page';
3129
3416
  article.innerHTML = markdownHtml(page.body);
3130
3417
  const knowledge = button('Open in Knowledge', 'shell.chat-cite-open-knowledge', 'ai-chat-source-viewer-knowledge');
@@ -3411,6 +3698,21 @@
3411
3698
  const REQUEST_CARD_HIDDEN_KEY = 'floless:chat-hidden-request-cards';
3412
3699
  state.requestCards = state.requestCards || new Map();
3413
3700
  state.requestCardsAt = state.requestCardsAt || 0;
3701
+ // Click state belongs to the request, not the article replaced by every stream/poll repaint (#2694).
3702
+ const requestCardUi = new Map();
3703
+ function requestCardEntry(requestId) {
3704
+ if (!requestCardUi.has(requestId)) requestCardUi.set(requestId, { busy: null, hold: null, note: '', askError: '' });
3705
+ return requestCardUi.get(requestId);
3706
+ }
3707
+ function liveRequestCard(requestId) {
3708
+ return [...(ui.feed?.querySelectorAll('.ai-chat-request-card[data-request-id]') || [])]
3709
+ .find((card) => card.dataset.requestId === requestId) || null;
3710
+ }
3711
+ function repaintRequestCard(requestId) {
3712
+ const card = liveRequestCard(requestId);
3713
+ if (card) paintRequestCard(card);
3714
+ return card;
3715
+ }
3414
3716
 
3415
3717
  function hiddenRequestCards() {
3416
3718
  try {
@@ -3461,6 +3763,19 @@
3461
3763
  // for the AI to start it), or the AI. The line says the card's own live word either way.
3462
3764
  if (finished) item.dataset.waits = 'done';
3463
3765
  else item.dataset.waits = live?.attention?.state === 'needs-you' && live.attention.code !== 'waiting-to-start' ? 'you' : 'ai';
3766
+ const entry = requestCardEntry(requestId);
3767
+ // A fresh terminal verdict retires this choice, not the whole entry: an old Stop must never
3768
+ // survive after the server says there is no work left. Unknown/in-flight status keeps it.
3769
+ if (live && (live.found === false || set)) { entry.hold = null; entry.askError = ''; }
3770
+ if (dismiss) dismiss.disabled = Boolean(entry.busy || entry.hold);
3771
+ if (undo) undo.disabled = Boolean(entry.busy);
3772
+ let note = item.querySelector('.ai-chat-request-note');
3773
+ if (entry.note) {
3774
+ if (!note) { note = document.createElement('p'); note.className = 'ai-chat-request-note'; note.setAttribute('role', 'status'); item.append(note); }
3775
+ note.textContent = entry.note;
3776
+ } else note?.remove();
3777
+ if (entry.hold) paintRequestAsk(item, entry);
3778
+ else item.querySelector('.ai-chat-request-ask')?.remove();
3464
3779
  }
3465
3780
 
3466
3781
  function initRequestCard(item, event) {
@@ -3483,6 +3798,8 @@
3483
3798
  catch { return; /* the card keeps what it last knew; the next poll tries again */ }
3484
3799
  if (!Array.isArray(statuses)) return;
3485
3800
  for (const live of statuses) if (live?.id) state.requestCards.set(live.id, live);
3801
+ // Only an authoritative removal retires transient state; folding or a conversation repaint does not.
3802
+ for (const live of statuses) if (live?.id && live.found === false) requestCardUi.delete(live.id);
3486
3803
  // A hidden card's line reads these on the conversation's next repaint (the chat poll, every 5 s).
3487
3804
  for (const card of ui.feed.querySelectorAll('.ai-chat-request-card[data-request-id]')) paintRequestCard(card);
3488
3805
  }
@@ -3498,6 +3815,8 @@
3498
3815
  async function dismissRequestFromCard(item) {
3499
3816
  const requestId = item.dataset.requestId;
3500
3817
  if (!requestId) return;
3818
+ const entry = requestCardEntry(requestId);
3819
+ if (entry.busy || entry.hold) return;
3501
3820
  // #2678: the person's own click holds the card open (its Undo, its ask, its note stay in front of them), counted from
3502
3821
  // the click so a collapse while it is answered still wins.
3503
3822
  openFeedCard(item.dataset.cardEventId);
@@ -3510,53 +3829,91 @@
3510
3829
  announce('This request is already finished, so there is nothing to dismiss.');
3511
3830
  return;
3512
3831
  }
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
3832
+ entry.busy = 'dismiss'; entry.note = '';
3833
+ paintRequestCard(item);
3516
3834
  try {
3835
+ // Learn the current choices before asking the server to dismiss: being held is an ordinary
3836
+ // choice, not a knowingly failed write. The POST below still owns its atomic race check.
3837
+ const projection = await request(`/api/requests/status?ids=${encodeURIComponent(requestId)}`, { timeoutMs: 10000 });
3838
+ const fresh = Array.isArray(projection?.statuses) ? projection.statuses.find((row) => row?.id === requestId) : null;
3839
+ if (!fresh || typeof fresh.found !== 'boolean' || !Object.hasOwn(fresh, 'hold') || !Object.hasOwn(fresh, 'lifecycle')
3840
+ || (fresh.lifecycle !== null && (typeof fresh.lifecycle !== 'object' || !REQUEST_CARD_WORDS[fresh.lifecycle.state]))
3841
+ || (fresh.hold !== null && (typeof fresh.hold !== 'object' || Array.isArray(fresh.hold)
3842
+ || typeof fresh.hold.kind !== 'string' || typeof fresh.hold.why !== 'string' || !Object.hasOwn(fresh.hold, 'stop')))) {
3843
+ cardNotice(requestId, 'FloLess couldn’t check whether this request is being worked on. Nothing was dismissed; try Dismiss again.');
3844
+ return;
3845
+ }
3846
+ state.requestCards.set(requestId, fresh);
3847
+ item = liveRequestCard(requestId);
3848
+ if (!fresh.found || fresh.lifecycle) {
3849
+ entry.busy = null;
3850
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-actions button:not([hidden])')?.focus();
3851
+ announce('This request is already finished, so there is nothing to dismiss.');
3852
+ return;
3853
+ }
3854
+ if (fresh.hold) { entry.busy = null; askStopThenDismiss(requestId, fresh.hold); return; }
3517
3855
  const done = await lifecycleCall(requestId, 'dismiss');
3856
+ item = liveRequestCard(requestId);
3518
3857
  if (done.ok) {
3858
+ entry.busy = null;
3519
3859
  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();
3860
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-undo')?.focus();
3522
3861
  announce('Request dismissed. Undo is on the card.');
3523
3862
  return;
3524
3863
  }
3525
- if (done.body?.code === 'request-held' && done.body.hold) { askStopThenDismiss(item, done.body.hold); return; }
3864
+ if (done.body?.code === 'request-held' && done.body.hold) { entry.busy = null; askStopThenDismiss(requestId, done.body.hold); return; }
3526
3865
  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.');
3866
+ cardNotice(requestId, done.body?.error || 'FloLess couldn’t dismiss that request. It is still in Requests; try Dismiss again.');
3528
3867
  } catch {
3529
- cardNotice(item, 'FloLess couldn’t reach the server, so the request was not dismissed. Try Dismiss again in a moment.');
3868
+ cardNotice(requestId, 'FloLess couldn’t reach the server, so the request was not dismissed. Try Dismiss again in a moment.');
3530
3869
  } finally {
3531
- if (dismiss) dismiss.disabled = false;
3870
+ entry.busy = null; repaintRequestCard(requestId);
3532
3871
  }
3533
3872
  }
3534
3873
 
3535
3874
  /** 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);
3875
+ function cardNotice(requestId, text) {
3876
+ requestCardEntry(requestId).note = text;
3877
+ repaintRequestCard(requestId);
3541
3878
  announce(text);
3542
3879
  }
3543
3880
 
3544
3881
  /** 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();
3882
+ function askStopThenDismiss(requestId, hold) {
3883
+ const entry = requestCardEntry(requestId);
3884
+ entry.hold = hold; entry.askError = '';
3885
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-ask button')?.focus();
3886
+ }
3887
+ function paintRequestAsk(item, entry) {
3888
+ const requestId = item.dataset.requestId;
3889
+ const hold = entry.hold;
3890
+ const existing = item.querySelector('.ai-chat-request-ask');
3891
+ if (existing) {
3892
+ existing.querySelector('p').textContent = entry.askError || `${hold.why || 'The AI is working on this request.'} Nothing was changed.`;
3893
+ for (const button of existing.querySelectorAll('button')) button.disabled = Boolean(entry.busy);
3894
+ return;
3895
+ }
3547
3896
  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');
3897
+ const keepRequest = () => {
3898
+ if (entry.busy) return;
3899
+ entry.hold = null; entry.askError = '';
3900
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-dismiss')?.focus();
3901
+ };
3548
3902
  // 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.`;
3903
+ ask.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.stopPropagation(); keepRequest(); } });
3904
+ const why = document.createElement('p'); why.textContent = entry.askError || `${hold.why || 'The AI is working on this request.'} Nothing was changed.`;
3551
3905
  const row = document.createElement('div'); row.className = 'ai-chat-request-ask-actions';
3552
3906
  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(); });
3907
+ keep.disabled = Boolean(entry.busy);
3908
+ keep.addEventListener('click', keepRequest);
3554
3909
  row.append(keep);
3555
3910
  const stop = hold.stop;
3556
3911
  if (stop) {
3557
3912
  const go = button('Stop it and dismiss', `shell.chat-request-stop-dismiss#${item.dataset.requestId || 'linked request'}`, 'danger');
3913
+ go.disabled = Boolean(entry.busy);
3558
3914
  go.addEventListener('click', async () => {
3559
- go.disabled = true; keep.disabled = true;
3915
+ if (entry.busy) return;
3916
+ entry.busy = 'stop'; entry.askError = ''; repaintRequestCard(requestId);
3560
3917
  openFeedCard(item.dataset.cardEventId); // #2678: as Dismiss: the Undo it offers stays in front of them
3561
3918
  let stopped = true; // a stale stop means the work had already ended or changed: never claimed as "stopped"
3562
3919
  try {
@@ -3569,43 +3926,52 @@
3569
3926
  await request(`/api/requests/${encodeURIComponent(stop.requestId)}/run/stop`, { method: 'POST', body: JSON.stringify(stop.leaseId ? { expectLeaseId: stop.leaseId } : {}) });
3570
3927
  }
3571
3928
  } 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; }
3929
+ if (error?.code !== 'stop-stale') {
3930
+ entry.askError = 'FloLess couldn’t stop that work, so the request was not dismissed.';
3931
+ entry.busy = null; repaintRequestCard(requestId); announce(entry.askError); return;
3932
+ }
3573
3933
  stopped = false;
3574
3934
  }
3575
- const again = await lifecycleCall(item.dataset.requestId, 'dismiss').catch(() => null);
3935
+ const again = await lifecycleCall(requestId, 'dismiss').catch(() => null);
3936
+ entry.busy = null;
3576
3937
  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();
3938
+ entry.hold = null; entry.askError = '';
3939
+ state.requestCards.set(requestId, { id: requestId, found: true, lifecycle: { state: 'dismissed' }, attention: { state: 'not-now', code: 'dismissed', label: 'Dismissed' } });
3940
+ repaintRequestCard(requestId)?.querySelector('.ai-chat-request-undo')?.focus();
3581
3941
  } else {
3582
3942
  // 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'
3943
+ entry.askError = again?.body?.code === 'request-held'
3584
3944
  ? (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
3945
  : `${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;
3946
+ repaintRequestCard(requestId); announce(entry.askError);
3587
3947
  }
3588
3948
  });
3589
3949
  row.append(go);
3590
3950
  }
3591
3951
  ask.append(why, row);
3592
3952
  item.append(ask);
3593
- keep.focus();
3594
3953
  }
3595
3954
 
3596
3955
  async function restoreRequestFromCard(item) {
3597
3956
  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();
3957
+ const entry = requestCardEntry(requestId);
3958
+ if (entry.busy) return;
3959
+ entry.busy = 'restore'; entry.note = ''; paintRequestCard(item);
3960
+ let restored = false;
3601
3961
  try {
3602
3962
  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);
3963
+ 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; }
3964
+ item = liveRequestCard(requestId);
3965
+ if (item) forgetHiddenRequestCard(item.dataset.cardEventId);
3605
3966
  await refreshRequestCards({ force: true });
3967
+ restored = true;
3606
3968
  } 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; }
3969
+ cardNotice(requestId, 'FloLess couldn’t reach the server, so the request was not put back. Try Undo again in a moment.');
3970
+ } finally {
3971
+ entry.busy = null;
3972
+ const card = repaintRequestCard(requestId);
3973
+ if (restored) card?.querySelector('.ai-chat-request-dismiss:not([hidden])')?.focus();
3974
+ }
3609
3975
  }
3610
3976
 
3611
3977
  // #1907: the plain name of one of the person's connectors — the same rule the server words its cards with.
@@ -4894,7 +5260,8 @@
4894
5260
  /** The crop of the page around a place: the area and some room around it, never smaller than a fifth of the page. */
4895
5261
  function evidenceCrop(place) {
4896
5262
  const [px0, py0, px1, py1] = place.pageBounds;
4897
- const [rx0, ry0, rx1, ry1] = place.region;
5263
+ // #2777: a place with no marked area (an RFI on a sheet, a level read from its picture) is the whole sheet.
5264
+ const [rx0, ry0, rx1, ry1] = Array.isArray(place.region) ? place.region : place.pageBounds;
4898
5265
  const grow = (lo, hi, min, max) => {
4899
5266
  const pad = Math.max((hi - lo) * 0.15, (max - min) * 0.01);
4900
5267
  let a = lo - pad, b = hi + pad;
@@ -4910,12 +5277,63 @@
4910
5277
  }
4911
5278
 
4912
5279
  /** 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);
5280
+ function openReadinessEvidence(place, row, card, opener) {
5281
+ return openDrawingPlace(place, {
5282
+ title: String(place.title || place.label), note: EVIDENCE_ORIGIN[place.origin].note(place), opener,
5283
+ url: `/api/projects/${encodeURIComponent(card.projectId)}/connections/${encodeURIComponent(row.jointId)}/evidence/drawing?key=${encodeURIComponent(place.key)}&digest=${encodeURIComponent(place.digest)}`,
5284
+ commands: { close: 'shell.chat-readiness-evidence-close', view: 'shell.chat-readiness-evidence-view' },
5285
+ 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',
5286
+ run: () => { addToMessageBox(`Show the readiness of connection ${row.jointId} again.`); ui.input.focus?.(); } },
5287
+ ...(place.sourceHash && place.pageId ? { filter: { projectId: card.projectId, commandId: 'shell.chat-place-open-filter' } } : {}),
5288
+ });
5289
+ }
5290
+
5291
+ /**
5292
+ * #2777 slice D: "Open in Drawing Filter" for a place. The Drawing Filter does the showing; the viewer says what it did,
5293
+ * never more: it waits for the Filter's own outcome (as "Open in the model" waits for the editor's), closes once the place
5294
+ * is shown, and otherwise stays open with the reason in sight, so a place that could not be shown is never silent.
5295
+ */
5296
+ function drawingFilterButton(place, filter, { shown, refused }) {
5297
+ const open = button('Open in Drawing Filter', filter.commandId, 'ai-chat-evidence-view ai-chat-evidence-filter');
5298
+ open.dataset.tip = 'Opens this sheet in the project\u2019s Drawing Filter with the place marked. Nothing changes';
5299
+ if (filter.instanceLabel) open.dataset.commandInstanceLabel = filter.instanceLabel;
5300
+ open.addEventListener('click', async () => {
5301
+ if (open.getAttribute('aria-busy') === 'true') return;
5302
+ const unreachable = 'FloLess could not open the Drawing Filter from here. Open the project’s Drawings step from Workspaces, then try again.';
5303
+ open.setAttribute('aria-busy', 'true');
5304
+ let said;
5305
+ try {
5306
+ if (typeof window.flolessWorkspaces?.openDrawingAt !== 'function') said = unreachable;
5307
+ else {
5308
+ const outcome = await window.flolessWorkspaces.openDrawingAt({ projectId: filter.projectId, place: {
5309
+ sourceHash: place.sourceHash, pageId: place.pageId, sheet: place.sheet, ...(Array.isArray(place.region) ? { region: place.region } : {}) } });
5310
+ if (outcome?.superseded) return;
5311
+ if (outcome?.ok === true) { shown(); announce(`Showing the place on sheet ${place.sheet} in the Drawing Filter.`); return; }
5312
+ said = outcome?.said || `The place on sheet ${place.sheet} was not shown. Open the Drawings step, then press Open in Drawing Filter again.`;
5313
+ }
5314
+ } catch (error) {
5315
+ if (error?.plain !== true) console.error('[chat] Open in Drawing Filter failed', error);
5316
+ said = error?.plain === true && error.message ? error.message : unreachable;
5317
+ } finally {
5318
+ open.removeAttribute('aria-busy');
5319
+ }
5320
+ if (said) refused(said);
5321
+ });
5322
+ return open;
5323
+ }
5324
+
5325
+ /**
5326
+ * A page of a drawing in the cited-source viewer, cropped to a place (`pageBounds`, `region`, `sheet`, `page`), with the
5327
+ * whole sheet a press away. Shared by the readiness card (#2451) and the height card (#2777); `again` is the way on
5328
+ * when the place changed or is gone, never something done for the person. A place with no `region` is a whole sheet:
5329
+ * it opens on the sheet and offers no "This area", since there is no area to show. `filter` (#2777 slice D) adds
5330
+ * "Open in Drawing Filter", which shows the same place in the project's Drawing Filter.
5331
+ */
5332
+ async function openDrawingPlace(place, { title, note: noteText, url, opener, commands, again, filter }) {
4915
5333
  const dialog = document.createElement('dialog'); dialog.className = 'ai-chat-source-viewer ai-chat-evidence-viewer';
4916
5334
  dialog.setAttribute('aria-label', title);
4917
5335
  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');
5336
+ const close = button('Close', commands.close, 'ai-chat-source-viewer-close');
4919
5337
  let picture = null;
4920
5338
  let finished = false;
4921
5339
  const finish = () => {
@@ -4929,50 +5347,150 @@
4929
5347
  close.addEventListener('click', finish);
4930
5348
  dialog.addEventListener('close', finish);
4931
5349
  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) });
5350
+ const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: noteText });
5351
+ const filterNote = Object.assign(document.createElement('p'), { className: 'ai-chat-evidence-filter-note', hidden: true });
5352
+ filterNote.setAttribute('role', 'status');
4933
5353
  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');
5354
+ const area = button('This area', commands.view, 'ai-chat-evidence-view');
5355
+ const whole = button('Whole sheet', commands.view, 'ai-chat-evidence-view');
4936
5356
  area.dataset.commandInstanceLabel = 'this area'; whole.dataset.commandInstanceLabel = 'the whole sheet';
4937
- views.append(area, whole);
5357
+ const marked = Array.isArray(place.region);
5358
+ views.append(...(marked ? [area, whole] : [whole]));
5359
+ // Not one of the views: it leaves this viewer for another screen, so it sits beside the group, never in it.
5360
+ const bar = document.createElement('div'); bar.className = 'ai-chat-evidence-bar';
5361
+ bar.append(views);
5362
+ if (filter?.projectId && filter.commandId) {
5363
+ bar.append(drawingFilterButton(place, filter, {
5364
+ shown: () => finish(),
5365
+ // Said where the person clicked, and read out: the picture stays, so they can still look at the place here.
5366
+ refused: (said) => { if (finished) return; filterNote.textContent = said; filterNote.hidden = false; announce(said); },
5367
+ }));
5368
+ }
4938
5369
  const body = document.createElement('div'); body.className = 'ai-chat-source-viewer-body';
4939
5370
  const status = Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-status', textContent: 'Loading the drawing…' });
4940
5371
  status.setAttribute('role', 'status');
4941
5372
  const crop = evidenceCrop(place);
4942
5373
  const frame = document.createElement('div'); frame.className = 'ai-chat-evidence-frame';
5374
+ /*
5375
+ * What the frame shows, in page units, always shaped like the frame so the drawing is never stretched. "This area" and
5376
+ * "Whole sheet" set it; zoom (the buttons, the wheel, a double-click, + and -) and pan (a drag, the arrow keys) move
5377
+ * 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
5378
+ * out of the frame.
5379
+ */
5380
+ let view = null;
5381
+ const paintView = () => {
5382
+ const image = frame.querySelector('img');
5383
+ 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}%` });
5384
+ if (!view) return;
5385
+ const ratio = view.h / view.w;
5386
+ zoomIn.disabled = view.w <= crop.pageW / 50 + 1e-9;
5387
+ zoomOut.disabled = view.w >= Math.max(crop.pageW, crop.pageH / ratio) - 1e-9;
5388
+ };
5389
+ const clampView = (v) => {
5390
+ const ratio = v.h / v.w;
5391
+ const w = Math.min(Math.max(v.w, crop.pageW / 50), Math.max(crop.pageW, crop.pageH / ratio));
5392
+ const h = w * ratio;
5393
+ // Smaller than the page on an axis: kept on the page. Larger: the page centred, so nothing drifts off.
5394
+ const fit = (lo, size, min, extent) => (size >= extent ? min + (extent - size) / 2 : Math.min(Math.max(lo, min), min + extent - size));
5395
+ return { x0: fit(v.x0, w, crop.px0, crop.pageW), y0: fit(v.y0, h, crop.py0, crop.pageH), w, h };
5396
+ };
5397
+ const moved = () => { area.setAttribute('aria-pressed', 'false'); whole.setAttribute('aria-pressed', 'false'); frame.dataset.view = 'zoomed'; };
5398
+ /** Zoom by `factor` (above 1 is in) about a point of the frame, given as fractions of its width and height. */
5399
+ const zoomAt = (factor, fx = 0.5, fy = 0.5) => {
5400
+ if (!view) return;
5401
+ const px = view.x0 + fx * view.w, py = view.y0 + fy * view.h;
5402
+ const next = clampView({ x0: 0, y0: 0, w: view.w / factor, h: view.h / factor });
5403
+ view = clampView({ x0: px - fx * next.w, y0: py - fy * next.h, w: next.w, h: next.h });
5404
+ moved(); paintView();
5405
+ };
5406
+ const panBy = (dx, dy) => { if (!view) return; view = clampView({ ...view, x0: view.x0 + dx, y0: view.y0 + dy }); moved(); paintView(); };
5407
+ // The view "0" goes back to: the last one chosen with This area or Whole sheet.
5408
+ let shownAll = !marked;
4943
5409
  const show = (all) => {
5410
+ shownAll = all;
4944
5411
  area.setAttribute('aria-pressed', String(!all)); whole.setAttribute('aria-pressed', String(all));
4945
5412
  frame.dataset.view = all ? 'sheet' : 'area';
4946
5413
  const c = all ? { x0: crop.px0, y0: crop.py0, w: crop.pageW, h: crop.pageH } : crop;
4947
5414
  // Shaped like the crop and never taller than most of the window: narrowed, not squashed, so the picture stays true.
4948
5415
  frame.style.aspectRatio = `${c.w} / ${c.h}`;
4949
5416
  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}%` });
5417
+ view = { x0: c.x0, y0: c.y0, w: c.w, h: c.h };
5418
+ paintView();
4952
5419
  };
5420
+ const zoom = document.createElement('div'); zoom.className = 'ai-chat-evidence-zoom'; zoom.setAttribute('role', 'group'); zoom.setAttribute('aria-label', 'Zoom the drawing');
5421
+ const zoomOut = button('−', 'shell.chat-drawing-zoom-out', 'ai-chat-evidence-zoom-out');
5422
+ const zoomIn = button('+', 'shell.chat-drawing-zoom-in', 'ai-chat-evidence-zoom-in');
5423
+ zoomOut.setAttribute('aria-label', 'Zoom out'); zoomOut.dataset.tip = 'Zoom out (or scroll down on the drawing, or press -)';
5424
+ zoomIn.setAttribute('aria-label', 'Zoom in'); zoomIn.dataset.tip = 'Zoom in (or scroll up on the drawing, or press +)';
5425
+ zoomOut.addEventListener('click', () => zoomAt(1 / 1.5));
5426
+ zoomIn.addEventListener('click', () => zoomAt(1.5));
5427
+ zoom.append(zoomOut, zoomIn);
5428
+ bar.insertBefore(zoom, views.nextSibling);
5429
+ // The drawing itself: scroll to zoom where the pointer is, drag to move it, double-click to zoom in there.
5430
+ frame.tabIndex = 0;
5431
+ frame.setAttribute('role', 'group');
5432
+ frame.setAttribute('aria-label', 'Drawing. Drag or use the arrow keys to move it; scroll, or press + and -, to zoom; 0 goes back.');
5433
+ frame.dataset.commandId = 'shell.chat-drawing-pan';
5434
+ 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))]; };
5435
+ frame.addEventListener('wheel', (event) => {
5436
+ // A sideways swipe is not a zoom, and at the limit the wheel scrolls the dialog as it would anywhere else.
5437
+ if (!view || !event.deltaY) return;
5438
+ const zoomingIn = event.deltaY < 0;
5439
+ if (zoomingIn ? zoomIn.disabled : zoomOut.disabled) return;
5440
+ event.preventDefault();
5441
+ zoomAt(zoomingIn ? 1.2 : 1 / 1.2, ...fraction(event));
5442
+ }, { passive: false });
5443
+ frame.addEventListener('dblclick', (event) => { event.preventDefault(); zoomAt(1.5, ...fraction(event)); });
5444
+ let drag = null;
5445
+ frame.addEventListener('pointerdown', (event) => {
5446
+ if (!view || event.button !== 0) return;
5447
+ event.preventDefault();
5448
+ // preventDefault (no text selection, no image drag) also stops the click focusing the drawing, so it is focused here:
5449
+ // after a click the arrow keys, + / - and 0 act on it.
5450
+ frame.focus({ preventScroll: true });
5451
+ frame.setPointerCapture?.(event.pointerId);
5452
+ drag = { id: event.pointerId, x: event.clientX, y: event.clientY, from: { ...view } };
5453
+ frame.classList.add('dragging');
5454
+ });
5455
+ frame.addEventListener('pointermove', (event) => {
5456
+ if (!drag || event.pointerId !== drag.id) return;
5457
+ const r = frame.getBoundingClientRect();
5458
+ 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 });
5459
+ moved(); paintView();
5460
+ });
5461
+ const endDrag = (event) => { if (!drag || event.pointerId !== drag.id) return; drag = null; frame.classList.remove('dragging'); };
5462
+ frame.addEventListener('pointerup', endDrag);
5463
+ frame.addEventListener('pointercancel', endDrag);
5464
+ frame.addEventListener('keydown', (event) => {
5465
+ if (!view) return;
5466
+ const step = 0.1;
5467
+ 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),
5468
+ '+': () => zoomAt(1.5), '=': () => zoomAt(1.5), '-': () => zoomAt(1 / 1.5), '0': () => show(shownAll) };
5469
+ // The numpad's keys, and a layout whose + needs Shift, still zoom.
5470
+ const byCode = { NumpadAdd: '+', NumpadSubtract: '-', Equal: '+', Minus: '-' };
5471
+ const run = keys[event.key] || keys[byCode[event.code]];
5472
+ if (!run) return;
5473
+ event.preventDefault();
5474
+ run();
5475
+ });
4953
5476
  area.addEventListener('click', () => show(false));
4954
5477
  whole.addEventListener('click', () => show(true));
4955
- show(false);
5478
+ show(!marked);
4956
5479
  body.append(status, frame);
4957
- dialog.append(head, note, views, body);
5480
+ dialog.append(head, note, bar, filterNote, body);
4958
5481
  const hide = showChatViewer(dialog, finish);
4959
5482
  close.focus({ preventScroll: true });
4960
5483
  // 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
5484
  const offerAgain = (why) => {
4962
5485
  if (finished) return;
4963
5486
  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);
5487
+ frame.remove(); bar.remove(); filterNote.remove();
5488
+ const way = button(again.label, again.commandId, 'ai-chat-source-viewer-knowledge');
5489
+ if (again.tip) way.dataset.tip = again.tip;
5490
+ way.addEventListener('click', () => { finish(); again.run(); });
5491
+ dialog.append(way);
4973
5492
  };
4974
5493
  try {
4975
- const url = `/api/projects/${encodeURIComponent(card.projectId)}/connections/${encodeURIComponent(row.jointId)}/evidence/drawing?key=${encodeURIComponent(place.key)}&digest=${encodeURIComponent(place.digest)}`;
4976
5494
  const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store' });
4977
5495
  if (finished) return;
4978
5496
  if (!response.ok) {
@@ -4983,9 +5501,10 @@
4983
5501
  const bytes = await response.blob();
4984
5502
  if (finished) return;
4985
5503
  picture = URL.createObjectURL(bytes);
4986
- const image = Object.assign(document.createElement('img'), { src: picture, alt: `${title}, page ${place.page}, with the area outlined` });
5504
+ const image = Object.assign(document.createElement('img'), { src: picture, alt: marked ? `${title}, page ${place.page}, with the area outlined` : `${title}, page ${place.page}` });
5505
+ image.draggable = false;
4987
5506
  frame.append(image);
4988
- show(false);
5507
+ paintView();
4989
5508
  status.textContent = `${place.sheet} · page ${place.page}`;
4990
5509
  } catch (error) {
4991
5510
  console.error('[chat] a drawing place could not be opened', error);
@@ -6209,10 +6728,17 @@
6209
6728
  if (shell.firstChild !== node || shell.lastChild !== hide) shell.replaceChildren(node, hide);
6210
6729
  return shell;
6211
6730
  }
6212
- /** Keyboard into a card: on the control `commandId` names, else its first usable control, else the card itself. */
6731
+ /** 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
6732
  function focusFeedCard(card, commandId = null) {
6214
6733
  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;
6734
+ // Not a control scrolled out of its card's list, even partly: the list stays where the person left it, so focus would be
6735
+ // out of sight. A control `commandId` names is used even when out of sight.
6736
+ const inSight = (node) => {
6737
+ const list = node.closest('.ai-chat-height-rows'); if (!list?.getBoundingClientRect) return true;
6738
+ const at = node.getBoundingClientRect(), box = list.getBoundingClientRect();
6739
+ return at.top >= box.top && at.bottom <= box.bottom;
6740
+ };
6741
+ const target = (commandId && controls.find((node) => node.dataset.commandId === commandId)) || controls.find(inSight) || controls[0] || card;
6216
6742
  if (target === card && !card.hasAttribute('tabindex')) card.tabIndex = -1;
6217
6743
  target.focus({ preventScroll: true });
6218
6744
  return target;
@@ -6426,7 +6952,11 @@
6426
6952
 
6427
6953
  const heightEndKey = (row) => `${row.memberId}\u0000${row.end}`;
6428
6954
  const heightEndWord = (row) => (row.endWord === 'from' ? 'start' : 'end');
6429
- const heightAnswerText = (answer) => (answer?.how === 'typed' ? `You typed ${answer.typed}` : `Confirmed ${answer?.shownAs || ''}`);
6955
+ // #2788: a confirmed proposal keeps where it came from, so a derived height never reads as one taken off a drawing.
6956
+ const heightProposalSaid = (proposal) => (!proposal ? '' : proposal.how === 'derived' ? `, which the read derived from ${proposal.basis}`
6957
+ : proposal.how === 'measured' ? `, which the read measured on the drawings${proposal.basis ? ` (${proposal.basis})` : ''}`
6958
+ : proposal.basis ? `, read off the drawings (${proposal.basis})` : ', read off the drawings');
6959
+ const heightAnswerText = (answer) => (answer?.how === 'typed' ? `You typed ${answer.typed}` : `Confirmed ${answer?.shownAs || ''}${heightProposalSaid(answer?.proposal)}`);
6430
6960
  /*
6431
6961
  * #1903: a row about a member ALREADY in the model. The server snapshotted that end when the question was
6432
6962
  * asked; the card says what it held THEN (the model can change before the person answers, and the review
@@ -6484,9 +7014,16 @@
6484
7014
  const caret = focused ? textCaret(document.activeElement) : null;
6485
7015
  const next = rememberCard(entry, paintHeightCard(entry, old.dataset.eventId, old.dataset.eventSequence), old.dataset.eventId, old.dataset.eventSequence);
6486
7016
  old.replaceWith(next);
7017
+ keepRowsScroll(next);
6487
7018
  if (focused) focusHeightControl(next, focused, caret);
6488
7019
  }
6489
7020
 
7021
+ /** A rebuilt card's list goes back where the person left it: only a shown list can scroll (paintEvents does the same). */
7022
+ function keepRowsScroll(card) {
7023
+ const list = card.querySelector('.ai-chat-height-rows');
7024
+ if (list && typeof list.keptScrollTop === 'number') list.scrollTop = list.keptScrollTop;
7025
+ }
7026
+
6490
7027
  /** The caret of a focused text field, or null (a radio or checkbox has none, and reading it can throw). */
6491
7028
  function textCaret(control) {
6492
7029
  try {
@@ -6536,6 +7073,128 @@
6536
7073
  return paintDrawingHistory('height', entry, eventId, sequence);
6537
7074
  }
6538
7075
 
7076
+ /*
7077
+ * #2777: where on the drawings a height question means. FloLess outlined the drawing element the read took the end from
7078
+ * (or, for a member already in the model, the one the model was read from); the picture opens that sheet at the place,
7079
+ * whole sheet a press away. An end FloLess could not place says so, and nothing pretends a whole sheet is the spot.
7080
+ */
7081
+ /*
7082
+ * One picture at a time: only the answer step shows one, so only the current place's page is held. Moving to another
7083
+ * place lets the last one go; a load the person moved on from keeps nothing. (Review stop signal, operator 2026-10-26:
7084
+ * rebuilt from a many-picture cache whose eviction kept finding new ways to hold or drop bytes.)
7085
+ */
7086
+ let heightPlacePicture = null;
7087
+ const HEIGHT_PLACE_RETRY_MS = 15000;
7088
+ /** The server's own answer about the place (it changed, its drawing is gone, the link is wrong): shown, not retried. */
7089
+ const HEIGHT_PLACE_FINAL = new Set([400, 404, 409, 413, 415]);
7090
+ 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 || '' })}`;
7091
+ const heightPlaced = (row) => Boolean(row.place && row.placeDigest);
7092
+ 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.');
7093
+ function openHeightPlace(entry, row, opener) {
7094
+ const place = row.place;
7095
+ return openDrawingPlace(place, {
7096
+ title: `${row.label} on ${place.sheet}`, opener, url: heightPlaceUrl(entry, row),
7097
+ 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.`,
7098
+ commands: { close: 'shell.chat-height-place-close', view: 'shell.chat-height-place-view' },
7099
+ again: { label: 'Reload the height card', commandId: 'shell.chat-height-place-again', run: () => loadHeightQuestion(entry) },
7100
+ filter: { projectId: chatProjectId(), commandId: 'shell.chat-place-open-filter' },
7101
+ });
7102
+ }
7103
+ /** The picture of the place, fetched once per place the card showed (its digest), shared by every repaint of the card. */
7104
+ function paintHeightPlacePicture(entry, row, frame) {
7105
+ paintPlacePicture({ digest: row.placeDigest, url: heightPlaceUrl(entry, row), place: row.place }, frame);
7106
+ }
7107
+ /**
7108
+ * The answer step's place picture (#2777), for the height card and the setup card alike. One slot: only one answer step
7109
+ * is on screen, so only its picture is held; a place the card no longer shows lets go of the one before.
7110
+ */
7111
+ function paintPlacePicture({ digest, url, place }, frame) {
7112
+ const paint = (target, record) => {
7113
+ target.dataset.state = record.state;
7114
+ target.setAttribute('aria-busy', String(record.state === 'loading'));
7115
+ target.replaceChildren();
7116
+ if (record.state === 'ready') {
7117
+ const crop = evidenceCrop(place);
7118
+ const image = Object.assign(document.createElement('img'), { src: record.url, alt: '' });
7119
+ 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}%` });
7120
+ target.append(image);
7121
+ } else if (record.state === 'error') {
7122
+ target.append(Object.assign(document.createElement('span'), { className: 'ai-chat-height-place-missing', textContent: record.said }));
7123
+ }
7124
+ };
7125
+ const unavailable = 'Preview unavailable just now. Opening the sheet may still work.';
7126
+ let record = heightPlacePicture;
7127
+ const retry = record?.digest === digest && record.state === 'error' && record.retryAt && Date.now() >= record.retryAt;
7128
+ if (!record || record.digest !== digest || retry) {
7129
+ if (record?.url) URL.revokeObjectURL(record.url);
7130
+ record = heightPlacePicture = { digest, state: 'loading', frame: null };
7131
+ const loading = record;
7132
+ const current = () => heightPlacePicture === loading;
7133
+ fetch(url, { credentials: 'same-origin', cache: 'no-store' })
7134
+ .then(async (response) => {
7135
+ if (!current()) return;
7136
+ if (response.ok) {
7137
+ const bytes = await response.blob();
7138
+ if (current()) Object.assign(loading, { url: URL.createObjectURL(bytes), state: 'ready' });
7139
+ return;
7140
+ }
7141
+ const said = await response.json().catch(() => null);
7142
+ Object.assign(loading, { state: 'error' }, HEIGHT_PLACE_FINAL.has(response.status)
7143
+ ? { said: typeof said?.error === 'string' && said.error ? said.error : 'FloLess could not show this place on the drawings.' }
7144
+ : { said: unavailable, retryAt: Date.now() + HEIGHT_PLACE_RETRY_MS });
7145
+ })
7146
+ .catch((error) => {
7147
+ console.warn('[chat] the picture of a question\'s place on the drawings could not be loaded', error);
7148
+ if (current()) Object.assign(loading, { state: 'error', said: unavailable, retryAt: Date.now() + HEIGHT_PLACE_RETRY_MS });
7149
+ })
7150
+ .finally(() => { if (current() && loading.frame?.isConnected) paint(loading.frame, loading); loading.frame = null; });
7151
+ }
7152
+ // Only the frame painted last waits for the picture: an earlier paint's frame is no longer on screen.
7153
+ if (record.state === 'loading') record.frame = frame;
7154
+ paint(frame, record);
7155
+ }
7156
+ /** The answer step's picture: the cropped sheet with the place outlined, one button that opens it; or why there is none. */
7157
+ function heightPlaceFigure(entry, row) {
7158
+ 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) });
7159
+ const open = button('', `shell.chat-height-open-place#${entry.questionId} ${row.memberId} ${row.endWord}`, 'ai-chat-height-place');
7160
+ open.dataset.commandInstanceLabel = `${row.label} on ${row.place.sheet}`;
7161
+ open.setAttribute('aria-label', `Open sheet ${row.place.sheet} at ${row.label}`);
7162
+ open.dataset.tip = `Opens sheet ${row.place.sheet} with this place outlined`;
7163
+ const crop = evidenceCrop(row.place);
7164
+ const frame = document.createElement('span'); frame.className = 'ai-chat-height-place-frame';
7165
+ // Shaped like the crop, never taller than a short picture: narrowed, not squashed, so the drawing stays true.
7166
+ frame.style.aspectRatio = `${crop.w} / ${crop.h}`;
7167
+ frame.style.width = `min(100%, calc(110px * ${crop.w / crop.h}))`;
7168
+ const caption = document.createElement('span'); caption.className = 'ai-chat-height-place-caption';
7169
+ caption.append(Object.assign(document.createElement('strong'), { textContent: 'Open on sheet' }),
7170
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-sheet', textContent: `${row.place.sheet} · page ${row.place.page}` }),
7171
+ 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' }));
7172
+ open.append(frame, caption);
7173
+ open.addEventListener('click', () => openHeightPlace(entry, row, open));
7174
+ paintHeightPlacePicture(entry, row, frame);
7175
+ return open;
7176
+ }
7177
+ /** A row's sheet, as a small button in the card's list: the same place, no picture, so a long list stays short. */
7178
+ function heightPlaceChip(entry, row) {
7179
+ if (!heightPlaced(row)) return null;
7180
+ const chip = button(row.place.sheet, `shell.chat-height-row-place#${entry.questionId} ${row.memberId} ${row.endWord}`, 'ai-chat-height-sheet');
7181
+ chip.dataset.commandInstanceLabel = `${row.label} on ${row.place.sheet}`;
7182
+ chip.setAttribute('aria-label', `Open sheet ${row.place.sheet} at ${row.label}`);
7183
+ chip.dataset.tip = `Opens sheet ${row.place.sheet} with this place outlined`;
7184
+ chip.addEventListener('click', () => openHeightPlace(entry, row, chip));
7185
+ return chip;
7186
+ }
7187
+ /** #2774: where a proposed height came from, in the option's own words. A derived one is an assumption and says how. */
7188
+ function heightProposalWords(proposed) {
7189
+ // #2802: an elevation printed on the sheet and measured from a datum shows the conversion, so the person confirms it.
7190
+ const datum = proposed.datum ? ` (${proposed.asRead} on ${proposed.datum.name} = ${proposed.datum.asDrawn}, world ${proposed.datum.worldZMm} mm, is ${proposed.value} mm)` : '';
7191
+ if (proposed.how === 'derived') return { description: `Derived, an assumption: ${proposed.basis}${datum}`, tag: 'DERIVED' };
7192
+ if (proposed.how === 'measured') return { description: `Measured on the drawings${proposed.basis ? `: ${proposed.basis}` : ''}${datum}`, tag: 'MEASURED' };
7193
+ if (proposed.how === 'read') return { description: `Read off the drawings${proposed.basis ? `: ${proposed.basis}` : ''}${datum}` };
7194
+ return { description: `Use the value proposed for this member end${datum}` };
7195
+ }
7196
+ const heightNoProposalText = (row) => (row.noProposal ? `No height proposed: ${row.noProposal}` : 'The read proposed no height and gave no reason.');
7197
+
6539
7198
  function paintHeightRow(entry, row, open) {
6540
7199
  const key = heightEndKey(row);
6541
7200
  const item = document.createElement('li'); item.className = 'ai-chat-height-row';
@@ -6547,6 +7206,8 @@
6547
7206
  const label = document.createElement('div'); label.className = 'ai-chat-height-label'; label.textContent = row.label;
6548
7207
  label.dataset.tip = row.label;
6549
7208
  labelLine.append(label);
7209
+ const chip = heightPlaceChip(entry, row);
7210
+ if (chip) labelLine.append(chip);
6550
7211
  const meta = document.createElement('div'); meta.className = 'ai-chat-height-meta';
6551
7212
  // #1903: an existing member's PROFILE comes from the model, not from the read's label, so a label that
6552
7213
  // names the wrong member is visibly at odds with what the id really is.
@@ -7253,6 +7914,10 @@
7253
7914
  ? '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
7915
  : 'Only you can answer these heights. What you confirm or type goes straight into the model.';
7255
7916
  card.append(note);
7917
+ // #2774: the person asked for a height on every end; any end without one says why, and the card counts them.
7918
+ const bare = entry.view.proposeAll ? live.filter((row) => !row.proposed && !row.answer).length : 0;
7919
+ if (bare) card.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-height-unproposed',
7920
+ textContent: `You asked for a height on every end. The read could not propose ${bare === 1 ? 'one end' : `${bare} ends`}; each says why.` }));
7256
7921
  }
7257
7922
  if (entry.view.open && allAnswered) {
7258
7923
  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);
@@ -7266,6 +7931,13 @@
7266
7931
  card.append(next);
7267
7932
  }
7268
7933
  const list = document.createElement('ol'); list.className = 'ai-chat-height-rows';
7934
+ // Every repaint builds a new list (Answer, Back, a saved answer, a feed repaint of a changed card), and a new list
7935
+ // starts at its top. The list carries where the person left it, and keepRowsScroll or paintEvents puts it back once
7936
+ // 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)
7937
+ // reads 0 and forgets its place, so only a shown list records it, and it goes back there when it shows again.
7938
+ list.addEventListener('scroll', () => { if (list.clientHeight) entry.rowsScroll = list.scrollTop; }, { passive: true });
7939
+ list.keptScrollTop = entry.rowsScroll || 0;
7940
+ if (typeof ResizeObserver === 'function') new ResizeObserver(() => { if (list.clientHeight) list.scrollTop = entry.rowsScroll || 0; }).observe(list);
7269
7941
  for (const row of rows) {
7270
7942
  const key = drawingRowKey(kind, row);
7271
7943
  let item;
@@ -7277,6 +7949,9 @@
7277
7949
  } else {
7278
7950
  item = document.createElement('li'); item.className = 'ai-chat-height-row'; item.dataset.status = row.status; item.dataset.key = key;
7279
7951
  const label = document.createElement('span'); label.textContent = row.label || (row.kind === 'origin' ? 'Model origin' : viewName(row)); item.append(label);
7952
+ const firstPlace = kind === 'setup' && row.kind === 'level' ? setupPlaceItems(row)[0] : null;
7953
+ const chip = kind === 'height' ? heightPlaceChip(entry, row) : firstPlace ? setupPlaceChip(entry, row, firstPlace) : null;
7954
+ if (chip) item.append(chip);
7280
7955
  if (entry.view.open) {
7281
7956
  const answer = heightActionButton('Answer', `shell.chat-${kind}-change#${entry.questionId} ${key}`, label.textContent, 'ai-chat-height-change', null);
7282
7957
  answer.addEventListener('click', () => reopenDrawingItem(kind, entry, key)); item.append(answer);
@@ -7343,7 +8018,9 @@
7343
8018
  );
7344
8019
  }
7345
8020
  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; }
8021
+ 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; }
8022
+ else q.context.push(heightNoProposalText(row));
8023
+ q.figure = () => heightPlaceFigure(entry, row);
7347
8024
  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
8025
  } else if (row.kind === 'origin') {
7349
8026
  q.question = 'Which grid crossing is the model’s origin (0, 0)?'; q.layout = 'grid'; q.confirmSelection = true;
@@ -7354,6 +8031,9 @@
7354
8031
  } else {
7355
8032
  if (row.clue) q.context.push(row.clue);
7356
8033
  if (row.noSingleLevel) q.context.push(`No single level on the drawings: ${row.noSingleLevel.why}`);
8034
+ // Options follow row.proposals in order, so the selected option's index names its proposal.
8035
+ // A choice past the proposals ("No single level") has no place of its own, so it gets no picture.
8036
+ if (row.kind === 'level') q.figure = (choice) => setupPlaceFigure(entry, row, Number.isInteger(choice) ? (row.proposals[choice] ?? SETUP_NO_PROPOSAL) : null);
7357
8037
  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
8038
  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
8039
  }
@@ -7364,7 +8044,7 @@
7364
8044
  const previous = live.slice(0, live.indexOf(row)).filter((item) => !item.frozen).at(-1);
7365
8045
  const backToMode = kind === 'height' && !previous && open.length > 1;
7366
8046
  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,
8047
+ back: previous ? () => reopenDrawingItem(kind, entry, drawingRowKey(kind, previous)) : backToMode ? () => { entry.slotPhase = null; entry.activeItem = null; entry.slotSig = null; engageDrawingEntry(entry); drawingSlotRepaint(); } : null,
7368
8048
  source: (_index, onDraftChange) => drawingSource(kind, entry, scope, label, idFor, row, onDraftChange),
7369
8049
  validate: (_step, draft) => {
7370
8050
  const answer = draft.rows[0]; if (answer.choices.length) return '';
@@ -7394,9 +8074,9 @@
7394
8074
  source: confirmable ? (_index, onDraftChange) => drawingSource('height', entry, scope, label, idFor, { inherited }, onDraftChange) : null,
7395
8075
  question: { ...base, question: 'How would you like to answer these heights?', options, recommended: confirmable ? 0 : null,
7396
8076
  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) => {
8077
+ context: [...rows.map((row) => `${row.label} · ${row.inModel?.profile ? `${row.inModel.profile} · ` : ''}${row.memberId} · ${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.` : ''}`), ...(confirmable ? [`Optional source for all ${rows.length} heights. Each end keeps its own proposed value.`] : [])] }, commit: async (answer) => {
7398
8078
  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;
8079
+ entry.slotPhase = answer.choices[0] === options.length - 1 ? 'row' : 'select'; engageDrawingEntry(entry); return true;
7400
8080
  } };
7401
8081
  }
7402
8082
  if (entry.slotPhase === 'select') {
@@ -7406,7 +8086,7 @@
7406
8086
  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)}` })) },
7407
8087
  initial: ordered.map((row, index) => entry.selected.size ? entry.selected.has(heightEndKey(row)) ? index : -1 : index).filter((index) => index >= 0),
7408
8088
  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; } };
8089
+ commit: async (answer) => { entry.selected = new Set(answer.choices.map((index) => heightEndKey(ordered[index]))); entry.slotPhase = 'value'; engageDrawingEntry(entry); return true; } };
7410
8090
  }
7411
8091
  const chosen = rows.filter((row) => entry.selected.has(heightEndKey(row)));
7412
8092
  if (!chosen.length) { entry.slotPhase = 'select'; return drawingHeightBatch(entry, rows); }
@@ -7424,6 +8104,16 @@
7424
8104
  if (saved) { entry.slotPhase = null; entry.slotDrafts?.delete('batch-value'); entry.slotDrafts?.delete('batch-select'); }
7425
8105
  return saved; } };
7426
8106
  }
8107
+ /*
8108
+ * #2793: the card the person last acted in keeps the tray, until they act in another. Going Back to a card's own
8109
+ * "How would you like to answer…" step is acting in it: without this, the tray fell back to the OLDEST open card.
8110
+ */
8111
+ function engageDrawingEntry(entry) {
8112
+ // Another card's "Tell the read" step was shown because the person last acted there; acting here moves on from it.
8113
+ for (const other of [...setupCards.values(), ...heightCards.values()]) if (other !== entry) other.finishActive = false;
8114
+ entry.engaged = true; entry.reopenedAt = (state.drawingActivationOrder = (state.drawingActivationOrder || 0) + 1);
8115
+ }
8116
+ const drawingEntryHeld = (entry) => Boolean(entry.finishActive || entry.engaged || entry.changing.has(entry.activeItem));
7427
8117
  function paintDrawingQuestionSlot() {
7428
8118
  const tray = ui.approvalTray; if (!tray || !window.FlolessQuestionCard) return false;
7429
8119
  const showing = tray.querySelector('.ai-chat-drawing-step');
@@ -7432,13 +8122,14 @@
7432
8122
  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
8123
  const entries = [...setupCards.values()].map((entry) => ({ kind: 'setup', entry })).concat([...heightCards.values()].map((entry) => ({ kind: 'height', entry })))
7434
8124
  .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);
8125
+ .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
8126
  const waiting = entries.map(({ kind, entry }) => ({ kind, entry, step: drawingStep(kind, entry) })).filter(({ step }) => step);
7438
8127
  const hidden = waiting.filter(({ entry }) => drawingCardHidden(entry));
7439
8128
  const candidates = waiting.filter((candidate) => !hidden.includes(candidate));
7440
8129
  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];
8130
+ // A card's "Tell the read" step wins only while that card is the one the person acted in last (#2793): candidates
8131
+ // are sorted newest action first, so a finish step further down was left behind when they moved to another card.
8132
+ let chosen = candidates.find(({ entry, step }, index) => entry.finishActive && step.key === 'finish' && index === 0) || candidates.find(({ step }) => step.key !== 'finish') || candidates[0];
7442
8133
  if (heldFocus && personIsTyping()) {
7443
8134
  const current = candidates.find(({ entry, step }) => `${entry.chatId}/${entry.key}/${step.key}` === showing.dataset.drawingStep);
7444
8135
  const activated = chosen?.entry.finishActive || (chosen?.entry.reopenedAt || 0) > (current?.entry.reopenedAt || 0);
@@ -7555,6 +8246,98 @@
7555
8246
  return entry;
7556
8247
  }
7557
8248
 
8249
+
8250
+ /*
8251
+ * #2777 slice B: a level on the setup card shows where the read took it from. Each proposal carries the places of the
8252
+ * readings it stands for (`places`: `{ place, digest }` FloLess resolved, or `{ unplaced }` with the reason); a place with
8253
+ * no `region` is a whole sheet (a level read from the picture of a sheet, not from its text). The answer step shows the
8254
+ * first place as a picture labelled with its level, and every other place as a chip labelled with its level and sheet,
8255
+ * so no picture ever stands unlabelled for a choice it is not.
8256
+ */
8257
+ /** The answer step's "No single level" (or any choice that is not a proposal): it has no place to show. */
8258
+ const SETUP_NO_PROPOSAL = Object.freeze({ none: true });
8259
+ const setupPlaceUrl = (entry, row, item) => `/api/chat/setup-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}/place?${new URLSearchParams({
8260
+ key: row.key, proposal: item.proposal.id, ix: String(item.ix), digest: item.digest, chatId: entry.chatId || '' })}`;
8261
+ function setupPlaceItems(row, only) {
8262
+ const items = [];
8263
+ for (const proposal of row.proposals || []) {
8264
+ if (only && proposal !== only) continue;
8265
+ (Array.isArray(proposal.places) ? proposal.places : []).forEach((entry, ix) => {
8266
+ if (entry && entry.place && entry.digest) items.push({ proposal, ix, place: entry.place, digest: entry.digest });
8267
+ });
8268
+ }
8269
+ return items;
8270
+ }
8271
+ const setupUnplaced = (row) => (row.proposals || []).flatMap((proposal) => (proposal.places || []).filter((entry) => entry && entry.unplaced)
8272
+ .map((entry) => `${proposal.asRead}: ${entry.unplaced}`));
8273
+ const setupPlaceInstance = (item) => `${item.proposal.asRead} on ${item.place.sheet}`;
8274
+ function openSetupPlace(entry, row, item, opener) {
8275
+ const marked = Array.isArray(item.place.region);
8276
+ return openDrawingPlace(item.place, {
8277
+ title: `Level ${item.proposal.asRead} on ${item.place.sheet}`, opener, url: setupPlaceUrl(entry, row, item),
8278
+ 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.`
8279
+ : `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.`,
8280
+ commands: { close: 'shell.chat-setup-place-close', view: 'shell.chat-setup-place-view' },
8281
+ again: { label: 'Reload the setup card', commandId: 'shell.chat-setup-place-again', run: () => loadSetupQuestion(entry) },
8282
+ filter: { projectId: chatProjectId(), commandId: 'shell.chat-place-open-filter' },
8283
+ });
8284
+ }
8285
+ function setupPlaceChip(entry, row, item) {
8286
+ 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');
8287
+ chip.dataset.commandInstanceLabel = setupPlaceInstance(item);
8288
+ chip.setAttribute('aria-label', `Open sheet ${item.place.sheet} where the read took level ${item.proposal.asRead}`);
8289
+ 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`;
8290
+ chip.addEventListener('click', () => openSetupPlace(entry, row, item, chip));
8291
+ return chip;
8292
+ }
8293
+ /**
8294
+ * The setup answer step's picture for a level row: the selected level's first place (or, with nothing selected, the first
8295
+ * level's), labelled with its level; every other place as a chip labelled with its level and sheet; or why there is none.
8296
+ */
8297
+ function setupPlaceFigure(entry, row, chosen) {
8298
+ if (chosen === SETUP_NO_PROPOSAL) return null;
8299
+ const all = setupPlaceItems(row);
8300
+ // The selected level with no place of its own says so; it never borrows another level's picture.
8301
+ if (chosen && !all.some((item) => item.proposal === chosen)) {
8302
+ const why = (chosen.places || []).filter((entry) => entry && entry.unplaced).map((entry) => entry.unplaced);
8303
+ return Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-ask-context ai-chat-height-unplaced',
8304
+ textContent: why.length ? `Not placed on the drawings: ${why.join(' ')}` : `The read did not say where on the drawings it took ${chosen.asRead}.` });
8305
+ }
8306
+ const items = chosen ? [...all.filter((item) => item.proposal === chosen), ...all.filter((item) => item.proposal !== chosen)] : all;
8307
+ const unplaced = setupUnplaced(row);
8308
+ if (!items.length) {
8309
+ if (!unplaced.length) return null;
8310
+ return Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-ask-context ai-chat-height-unplaced', textContent: `Not placed on the drawings: ${unplaced.join(' ')}` });
8311
+ }
8312
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-setup-places';
8313
+ const first = items[0];
8314
+ const marked = Array.isArray(first.place.region);
8315
+ const open = button('', `shell.chat-setup-open-place#${entry.questionId} ${row.key} ${first.proposal.id} ${first.ix}`, 'ai-chat-height-place');
8316
+ open.dataset.commandInstanceLabel = setupPlaceInstance(first);
8317
+ open.setAttribute('aria-label', `Open sheet ${first.place.sheet} where the read took level ${first.proposal.asRead}`);
8318
+ open.dataset.tip = marked ? `Opens sheet ${first.place.sheet} with this place outlined` : `Opens sheet ${first.place.sheet}; no area is marked`;
8319
+ const crop = evidenceCrop(first.place);
8320
+ const frame = document.createElement('span'); frame.className = 'ai-chat-height-place-frame';
8321
+ frame.style.aspectRatio = `${crop.w} / ${crop.h}`;
8322
+ frame.style.width = `min(100%, calc(110px * ${crop.w / crop.h}))`;
8323
+ const caption = document.createElement('span'); caption.className = 'ai-chat-height-place-caption';
8324
+ caption.append(Object.assign(document.createElement('strong'), { textContent: 'Open on sheet' }),
8325
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-sheet', textContent: `${first.place.sheet} · page ${first.place.page}` }),
8326
+ 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)'}` }));
8327
+ open.append(frame, caption);
8328
+ open.addEventListener('click', () => openSetupPlace(entry, row, first, open));
8329
+ paintPlacePicture({ digest: first.digest, url: setupPlaceUrl(entry, row, first), place: first.place }, frame);
8330
+ wrap.append(open);
8331
+ if (items.length > 1) {
8332
+ const more = document.createElement('div'); more.className = 'ai-chat-setup-place-chips';
8333
+ more.setAttribute('role', 'group'); more.setAttribute('aria-label', 'Other places the read took these levels from');
8334
+ for (const item of items.slice(1)) more.append(setupPlaceChip(entry, row, item));
8335
+ wrap.append(more);
8336
+ }
8337
+ 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(' ')}` }));
8338
+ return wrap;
8339
+ }
8340
+
7558
8341
  function loadSetupQuestion(entry) {
7559
8342
  if (entry.loading) return;
7560
8343
  entry.loading = true;
@@ -7574,6 +8357,7 @@
7574
8357
  const caret = focused ? textCaret(document.activeElement) : null;
7575
8358
  const next = rememberCard(entry, paintSetupCard(entry, old.dataset.eventId, old.dataset.eventSequence), old.dataset.eventId, old.dataset.eventSequence);
7576
8359
  old.replaceWith(next);
8360
+ keepRowsScroll(next);
7577
8361
  if (focused) focusHeightControl(next, focused, caret);
7578
8362
  }
7579
8363
 
@@ -7590,7 +8374,7 @@
7590
8374
 
7591
8375
  const setupSettled = (row) => row.status === 'settled';
7592
8376
  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' };
8377
+ 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
8378
  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
8379
  const originText = (o) => `${o.xLabel}/${o.yLabel}`;
7596
8380
  const viewName = (row) => `${row.view.sheet}${row.view.title ? ` · ${row.view.title}` : ''}`;
@@ -7656,6 +8440,12 @@
7656
8440
  const text = document.createElement('span');
7657
8441
  text.textContent = row.status === 'needs-new-choices' ? `${setupAnswerText(row)}. Waiting for the read to offer other points.` : setupAnswerText(row);
7658
8442
  done.append(glyph, text);
8443
+ // #2777: the place of the level the person confirmed, the same chip the list shows.
8444
+ // By the proposal the person confirmed; an answer recorded before that was kept counts only when its value is unique.
8445
+ const sameValue = row.kind === 'level' && row.answer?.how === 'confirmed' ? (row.proposals || []).filter((proposal) => proposal.value === row.answer.value) : [];
8446
+ const chosen = row.answer?.proposalId ? (row.proposals || []).find((proposal) => proposal.id === row.answer.proposalId) : sameValue.length === 1 ? sameValue[0] : null;
8447
+ const chosenPlace = chosen ? setupPlaceItems(row, chosen)[0] : null;
8448
+ if (chosenPlace) done.append(setupPlaceChip(entry, row, chosenPlace));
7659
8449
  if (open && !row.frozen) {
7660
8450
  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
8451
  change.setAttribute('aria-label', `Change your answer for ${instance}`);
@@ -8389,6 +9179,8 @@
8389
9179
  if (node) links.push({ turnId: event.turnId, node });
8390
9180
  continue;
8391
9181
  }
9182
+ // #2777: the places an answer showed on the drawings, held under it like its sources.
9183
+ if (event.type === 'place') { const node = renderPlaceStrip(event); if (node) links.push({ turnId: event.turnId, node }); continue; }
8392
9184
  if (['tool', 'usage', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
8393
9185
  // FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
8394
9186
  // held and shown under the answer, so they never cut one answer into fragments.
@@ -8409,6 +9201,11 @@
8409
9201
  // never looks like a failed response. Recovery deliberately has no live indicator.
8410
9202
  if (turnIsVisiblyActive()) ui.feed.append(renderLiveStatus());
8411
9203
  }
9204
+ // Lists first, so a card that takes the keyboard below lands on a control the person can see (focusFeedCard).
9205
+ for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table')) {
9206
+ if (typeof list.keptScrollTop === 'number' && list.scrollTop !== list.keptScrollTop) list.scrollTop = list.keptScrollTop;
9207
+ if (typeof list.keptScrollLeft === 'number' && list.scrollLeft !== list.keptScrollLeft) list.scrollLeft = list.keptScrollLeft;
9208
+ }
8412
9209
  let refocused = null;
8413
9210
  if (focusedNode?.isConnected && ui.feed.contains(focusedNode)) {
8414
9211
  if (document.activeElement !== focusedNode) focusedNode.focus({ preventScroll: true });
@@ -8438,10 +9235,6 @@
8438
9235
  if (refocused && caret) {
8439
9236
  try { refocused.setSelectionRange(caret.start, caret.end, caret.direction); } catch { /* no caret on this control */ }
8440
9237
  }
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
9238
  // Removing a focused control makes the browser lay out the half-built feed, which clamps its scroll near the top.
8446
9239
  // Scrolled up, the reader stays where they were. At the end, they are put back there now, before any scroll event
8447
9240
  // can read that clamp as the reader moving up (keepFeedFollowing); the frame below settles late layout.
@@ -8453,7 +9246,11 @@
8453
9246
  if (state.feedLeftEnd || state.answerJump) return; // the reader moved up, or another conversation jumped to an answer
8454
9247
  ui.feed.scrollTop = ui.feed.scrollHeight;
8455
9248
  // 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' });
9249
+ // In a card's own list it is the list that is brought into sight: scrolling to the control would pull a list the
9250
+ // person scrolled away from back to it, under their pointer, on every 5 s poll.
9251
+ if (ui.feed.contains(document.activeElement)) {
9252
+ (document.activeElement.closest('.ai-chat-height-rows') || document.activeElement).scrollIntoView({ block: 'nearest' });
9253
+ }
8457
9254
  updateOffscreenActivity();
8458
9255
  });
8459
9256
  }