@floless/app 0.161.0 → 0.162.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/web/chat.js CHANGED
@@ -2622,13 +2622,14 @@
2622
2622
  chip.append(cited, why, sourceActions(ask, choose, assume));
2623
2623
  return chip;
2624
2624
  }
2625
- if (entry.kind === 'sheet') {
2625
+ if (entry.kind === 'sheet' && entry.ref?.representation === 'sheet') {
2626
2626
  const thumb = document.createElement('img'); thumb.alt = ''; thumb.loading = 'lazy';
2627
2627
  // A preview is only the picture the AI was shown (never a render): a tiles look or a changed picture has none.
2628
2628
  const preview = citationUrl(row, 'image', '&thumb=1');
2629
2629
  if (preview) {
2630
2630
  thumb.src = preview;
2631
- thumb.addEventListener('error', () => thumb.remove(), { once: true });
2631
+ // Keep the preview's space if the stored picture is gone: removing it shrinks this row after every repaint.
2632
+ thumb.addEventListener('error', () => { thumb.style.visibility = 'hidden'; }, { once: true });
2632
2633
  chip.append(thumb);
2633
2634
  }
2634
2635
  }
@@ -2675,7 +2676,8 @@
2675
2676
  const preview = citationUrl(view, 'image', '&thumb=1');
2676
2677
  if (preview) {
2677
2678
  thumb.src = preview;
2678
- thumb.addEventListener('error', () => thumb.remove(), { once: true });
2679
+ // A missing picture must not change the source row's height or wrapping while the answer streams.
2680
+ thumb.addEventListener('error', () => { thumb.style.visibility = 'hidden'; }, { once: true });
2679
2681
  chip.append(thumb);
2680
2682
  }
2681
2683
  }
@@ -3254,6 +3256,143 @@
3254
3256
  return chip?.querySelector('.ai-chat-source-open') ?? null;
3255
3257
  }
3256
3258
 
3259
+ /** One drawing viewport for cited sheets, attached images and outlined drawing places. No source lookup lives here. */
3260
+ function drawingViewport(place, viewCommand = 'shell.chat-drawing-fit') {
3261
+ const commands = { view: viewCommand };
3262
+ const views = document.createElement('div'); views.className = 'ai-chat-evidence-views'; views.setAttribute('role', 'group'); views.setAttribute('aria-label', 'How much of the sheet to show');
3263
+ const area = button('This area', commands.view, 'ai-chat-evidence-view');
3264
+ const whole = button('Whole sheet', commands.view, 'ai-chat-evidence-view');
3265
+ area.dataset.commandInstanceLabel = 'this area'; whole.dataset.commandInstanceLabel = 'the whole sheet';
3266
+ const marked = Array.isArray(place.region);
3267
+ views.append(...(marked ? [area, whole] : [whole]));
3268
+ // Not one of the views: it leaves this viewer for another screen, so it sits beside the group, never in it.
3269
+ const bar = document.createElement('div'); bar.className = 'ai-chat-evidence-bar';
3270
+ bar.append(views);
3271
+ let crop = evidenceCrop(place);
3272
+ const frame = document.createElement('div'); frame.className = 'ai-chat-evidence-frame';
3273
+ /*
3274
+ * What the frame shows, in page units, always shaped like the frame so the drawing is never stretched. "This area" and
3275
+ * "Whole sheet" set it; zoom (the buttons, the wheel, a double-click, + and -) and pan (a drag, the arrow keys) move
3276
+ * it. It may zoom out until the whole sheet fits and in to a fiftieth of the sheet's width, and never pans the page
3277
+ * out of the frame.
3278
+ */
3279
+ let view = null;
3280
+ const paintView = () => {
3281
+ const image = frame.querySelector('img');
3282
+ if (image && view) Object.assign(image.style, { width: `${(crop.pageW / view.w) * 100}%`, left: `${(-(view.x0 - crop.px0) / view.w) * 100}%`, top: `${(-(view.y0 - crop.py0) / view.h) * 100}%` });
3283
+ if (!view) return;
3284
+ const ratio = view.h / view.w;
3285
+ zoomIn.disabled = view.w <= crop.pageW / 50 + 1e-9;
3286
+ zoomOut.disabled = view.w >= Math.max(crop.pageW, crop.pageH / ratio) - 1e-9;
3287
+ };
3288
+ const clampView = (v) => {
3289
+ const ratio = v.h / v.w;
3290
+ const w = Math.min(Math.max(v.w, crop.pageW / 50), Math.max(crop.pageW, crop.pageH / ratio));
3291
+ const h = w * ratio;
3292
+ // Smaller than the page on an axis: kept on the page. Larger: the page centred, so nothing drifts off.
3293
+ const fit = (lo, size, min, extent) => (size >= extent ? min + (extent - size) / 2 : Math.min(Math.max(lo, min), min + extent - size));
3294
+ return { x0: fit(v.x0, w, crop.px0, crop.pageW), y0: fit(v.y0, h, crop.py0, crop.pageH), w, h };
3295
+ };
3296
+ const moved = () => { area.setAttribute('aria-pressed', 'false'); whole.setAttribute('aria-pressed', 'false'); frame.dataset.view = 'zoomed'; };
3297
+ /** Zoom by `factor` (above 1 is in) about a point of the frame, given as fractions of its width and height. */
3298
+ const zoomAt = (factor, fx = 0.5, fy = 0.5) => {
3299
+ if (!view) return;
3300
+ const px = view.x0 + fx * view.w, py = view.y0 + fy * view.h;
3301
+ const next = clampView({ x0: 0, y0: 0, w: view.w / factor, h: view.h / factor });
3302
+ view = clampView({ x0: px - fx * next.w, y0: py - fy * next.h, w: next.w, h: next.h });
3303
+ moved(); paintView();
3304
+ };
3305
+ const panBy = (dx, dy) => { if (!view) return; view = clampView({ ...view, x0: view.x0 + dx, y0: view.y0 + dy }); moved(); paintView(); };
3306
+ // The view "0" goes back to: the last one chosen with This area or Whole sheet.
3307
+ let shownAll = !marked;
3308
+ const show = (all) => {
3309
+ shownAll = all;
3310
+ area.setAttribute('aria-pressed', String(!all)); whole.setAttribute('aria-pressed', String(all));
3311
+ frame.dataset.view = all ? 'sheet' : 'area';
3312
+ const c = all ? { x0: crop.px0, y0: crop.py0, w: crop.pageW, h: crop.pageH } : crop;
3313
+ // Shaped like the crop and never taller than most of the window: narrowed, not squashed, so the picture stays true.
3314
+ frame.style.aspectRatio = `${c.w} / ${c.h}`;
3315
+ frame.style.width = `min(100%, calc(62vh * ${c.w / c.h}))`;
3316
+ view = { x0: c.x0, y0: c.y0, w: c.w, h: c.h };
3317
+ paintView();
3318
+ };
3319
+ const zoom = document.createElement('div'); zoom.className = 'ai-chat-evidence-zoom'; zoom.setAttribute('role', 'group'); zoom.setAttribute('aria-label', 'Zoom the drawing');
3320
+ const zoomOut = button('−', 'shell.chat-drawing-zoom-out', 'ai-chat-evidence-zoom-out');
3321
+ const zoomIn = button('+', 'shell.chat-drawing-zoom-in', 'ai-chat-evidence-zoom-in');
3322
+ zoomOut.setAttribute('aria-label', 'Zoom out'); zoomOut.dataset.tip = 'Zoom out (or scroll down on the drawing, or press -)';
3323
+ zoomIn.setAttribute('aria-label', 'Zoom in'); zoomIn.dataset.tip = 'Zoom in (or scroll up on the drawing, or press +)';
3324
+ zoomOut.addEventListener('click', () => zoomAt(1 / 1.5));
3325
+ zoomIn.addEventListener('click', () => zoomAt(1.5));
3326
+ zoom.append(zoomOut, zoomIn);
3327
+ bar.insertBefore(zoom, views.nextSibling);
3328
+ // The drawing itself: scroll to zoom where the pointer is, drag to move it, double-click to zoom in there.
3329
+ frame.tabIndex = 0;
3330
+ frame.setAttribute('role', 'group');
3331
+ frame.setAttribute('aria-label', 'Drawing. Drag or use the arrow keys to move it; scroll, or press + and -, to zoom; 0 goes back.');
3332
+ frame.dataset.commandId = 'shell.chat-drawing-pan';
3333
+ const fraction = (event) => { const r = frame.getBoundingClientRect(); return [Math.min(1, Math.max(0, (event.clientX - r.left) / r.width)), Math.min(1, Math.max(0, (event.clientY - r.top) / r.height))]; };
3334
+ frame.addEventListener('wheel', (event) => {
3335
+ // Wheel and touchpad zoom belong to this drawing, including at its zoom limits.
3336
+ if (!view || !event.deltaY) return;
3337
+ const zoomingIn = event.deltaY < 0;
3338
+ event.preventDefault();
3339
+ if (zoomingIn ? zoomIn.disabled : zoomOut.disabled) return;
3340
+ zoomAt(zoomingIn ? 1.2 : 1 / 1.2, ...fraction(event));
3341
+ }, { passive: false });
3342
+ frame.addEventListener('dblclick', (event) => { event.preventDefault(); zoomAt(1.5, ...fraction(event)); });
3343
+ let drag = null;
3344
+ frame.addEventListener('pointerdown', (event) => {
3345
+ if (!view || event.button !== 0) return;
3346
+ event.preventDefault();
3347
+ // preventDefault (no text selection, no image drag) also stops the click focusing the drawing, so it is focused here:
3348
+ // after a click the arrow keys, + / - and 0 act on it.
3349
+ frame.focus({ preventScroll: true });
3350
+ frame.setPointerCapture?.(event.pointerId);
3351
+ drag = { id: event.pointerId, x: event.clientX, y: event.clientY, from: { ...view } };
3352
+ frame.classList.add('dragging');
3353
+ });
3354
+ frame.addEventListener('pointermove', (event) => {
3355
+ if (!drag || event.pointerId !== drag.id) return;
3356
+ const r = frame.getBoundingClientRect();
3357
+ view = clampView({ ...drag.from, x0: drag.from.x0 - ((event.clientX - drag.x) / r.width) * drag.from.w, y0: drag.from.y0 - ((event.clientY - drag.y) / r.height) * drag.from.h });
3358
+ moved(); paintView();
3359
+ });
3360
+ const endDrag = (event) => { if (!drag || event.pointerId !== drag.id) return; drag = null; frame.classList.remove('dragging'); };
3361
+ frame.addEventListener('pointerup', endDrag);
3362
+ frame.addEventListener('pointercancel', endDrag);
3363
+ frame.addEventListener('keydown', (event) => {
3364
+ if (!view || event.ctrlKey || event.metaKey || event.altKey) return;
3365
+ const step = 0.1;
3366
+ const keys = { ArrowLeft: () => panBy(-view.w * step, 0), ArrowRight: () => panBy(view.w * step, 0), ArrowUp: () => panBy(0, -view.h * step), ArrowDown: () => panBy(0, view.h * step),
3367
+ '+': () => zoomAt(1.5), '=': () => zoomAt(1.5), '-': () => zoomAt(1 / 1.5), '0': () => show(shownAll) };
3368
+ // The numpad's keys, and a layout whose + needs Shift, still zoom.
3369
+ const byCode = { NumpadAdd: '+', NumpadSubtract: '-', Equal: '+', Minus: '-' };
3370
+ const run = keys[event.key] || keys[byCode[event.code]];
3371
+ if (!run) return;
3372
+ event.preventDefault();
3373
+ run();
3374
+ });
3375
+ area.addEventListener('click', () => show(false));
3376
+ whole.addEventListener('click', () => show(true));
3377
+ show(!marked);
3378
+ frame.setAttribute('aria-busy', 'true');
3379
+ const setImage = async (image, current = () => true, useImageSize = false) => {
3380
+ // Blob receipt is not a visible drawing: finish loading only once the browser can decode its pixels.
3381
+ if (typeof image.decode === 'function') await image.decode();
3382
+ if (!current()) return false;
3383
+ if (useImageSize && image.naturalWidth > 0 && image.naturalHeight > 0) {
3384
+ place = { pageBounds: [0, 0, image.naturalWidth, image.naturalHeight] };
3385
+ crop = evidenceCrop(place);
3386
+ }
3387
+ image.draggable = false;
3388
+ frame.replaceChildren(image);
3389
+ frame.removeAttribute('aria-busy');
3390
+ show(!marked);
3391
+ return true;
3392
+ };
3393
+ return { bar, frame, setImage };
3394
+ }
3395
+
3257
3396
  const CHOSEN_NOT_AS_ATTACHED = 'This file is no longer the plain file that was attached: it was changed, or something else now stands in its place. FloLess does not open it as the file you chose. Attach the file again if you still need it.';
3258
3397
 
3259
3398
  async function openCitedSource(row, turnId) {
@@ -3267,9 +3406,14 @@
3267
3406
  // viewer is removed, its picture released and focus handed back to the chip, once, whichever way it closes.
3268
3407
  let picture = null;
3269
3408
  let finished = false;
3409
+ const controller = new AbortController();
3410
+ let loadingTimer = null;
3411
+ let viewport = null;
3270
3412
  const finish = () => {
3271
3413
  if (finished) return;
3272
3414
  finished = true;
3415
+ controller.abort();
3416
+ clearTimeout(loadingTimer);
3273
3417
  if (dialog.open) dialog.close();
3274
3418
  hide();
3275
3419
  if (picture) URL.revokeObjectURL(picture);
@@ -3286,6 +3430,26 @@
3286
3430
  dialog.append(head, note, body);
3287
3431
  const hide = showChatViewer(dialog, finish);
3288
3432
  close.focus({ preventScroll: true });
3433
+ const drawing = entry.kind === 'sheet' || (entry.kind === 'attachment' && entry.ref?.mediaType?.startsWith('image/'));
3434
+ const mountDrawing = () => {
3435
+ if (viewport) return viewport;
3436
+ dialog.classList.add('ai-chat-evidence-viewer');
3437
+ viewport = drawingViewport({ pageBounds: [0, 0, 1, 1] });
3438
+ dialog.insertBefore(viewport.bar, body);
3439
+ body.append(viewport.frame);
3440
+ return viewport;
3441
+ };
3442
+ if (drawing) mountDrawing();
3443
+ loadingTimer = setTimeout(() => { if (!finished && !body.querySelector('img')) status.textContent = `Still loading ${citationLabel(entry)}. You can close this window while it loads.`; }, 4000);
3444
+ const loaded = () => clearTimeout(loadingTimer);
3445
+ const retry = () => {
3446
+ if (finished || dialog.querySelector('.ai-chat-drawing-retry')) return;
3447
+ loaded();
3448
+ viewport?.frame.remove(); viewport?.bar.remove();
3449
+ const again = button('Try again', 'shell.chat-drawing-retry', 'ai-chat-source-viewer-knowledge ai-chat-drawing-retry');
3450
+ again.addEventListener('click', () => { finish(); void openCitedSource(row, turnId); });
3451
+ dialog.append(again);
3452
+ };
3289
3453
  const refused = async (response) => {
3290
3454
  if (response.status === 404) return 'FloLess no longer holds this source, or its project is no longer part of this conversation.';
3291
3455
  if (response.status === 410) {
@@ -3323,23 +3487,24 @@
3323
3487
  return;
3324
3488
  }
3325
3489
  if (entry.kind === 'sheet') {
3326
- const response = await fetch(citationUrl(row, 'image'), { credentials: 'same-origin', cache: 'no-store' });
3327
- if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3490
+ const response = await fetch(citationUrl(row, 'image'), { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
3491
+ if (!response.ok) { const why = await refused(response); if (!finished) { status.textContent = why; retry(); } return; }
3328
3492
  const shown = response.headers.get('X-FloLess-Shown') || 'as-seen';
3329
3493
  const bytes = await response.blob();
3330
3494
  // Checked after every wait: a viewer closed meanwhile creates nothing it would never release.
3331
3495
  if (finished) return;
3332
3496
  picture = URL.createObjectURL(bytes);
3333
3497
  const image = Object.assign(document.createElement('img'), { src: picture, alt: `${entry.label}${shown === 'as-seen' ? '' : ', rendered from the source drawing'}` });
3498
+ if (!await mountDrawing().setImage(image, () => !finished, true)) return;
3499
+ loaded();
3334
3500
  status.textContent = SHOWN[shown] || SHOWN['as-seen'];
3335
- body.append(image);
3336
3501
  return;
3337
3502
  }
3338
3503
  if (entry.kind === 'member') { await showCitedMember(row, { dialog, body, status, finish, refused, done: () => finished }); return; }
3339
3504
  if (entry.kind === 'project-file') {
3340
3505
  // #2701: a file of the project's folder, checked now against the size and digest it was cited with.
3341
- const response = await fetch(citationUrl(row, 'project-file'), { credentials: 'same-origin', cache: 'no-store' });
3342
- if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3506
+ const response = await fetch(citationUrl(row, 'project-file'), { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
3507
+ if (!response.ok) { const why = await refused(response); if (!finished) { status.textContent = why; retry(); } return; }
3343
3508
  const { file } = await response.json();
3344
3509
  if (finished) return;
3345
3510
  if (!file) { status.textContent = 'FloLess could not open this source right now. Try again in a moment.'; return; }
@@ -3355,15 +3520,17 @@
3355
3520
  return;
3356
3521
  }
3357
3522
  if (entry.kind === 'attachment') {
3358
- const response = await fetch(citationUrl(row, 'attachment'), { credentials: 'same-origin', cache: 'no-store' });
3359
- if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3523
+ const response = await fetch(citationUrl(row, 'attachment'), { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
3524
+ if (!response.ok) { const why = await refused(response); if (!finished) { status.textContent = why; retry(); } return; }
3360
3525
  const type = (response.headers.get('Content-Type') || '').split(';')[0].trim().toLowerCase();
3361
3526
  if (type.startsWith('image/')) {
3362
3527
  const bytes = await response.blob();
3363
3528
  if (finished) return;
3364
3529
  picture = URL.createObjectURL(bytes);
3530
+ const image = Object.assign(document.createElement('img'), { src: picture, alt: entry.label });
3531
+ if (!await mountDrawing().setImage(image, () => !finished, true)) return;
3532
+ loaded();
3365
3533
  status.textContent = 'The file as it was attached.';
3366
- body.append(Object.assign(document.createElement('img'), { src: picture, alt: entry.label }));
3367
3534
  } else if (type === 'text/plain') {
3368
3535
  const text = await response.text();
3369
3536
  if (finished) return;
@@ -3407,8 +3574,8 @@
3407
3574
  dialog.append(external);
3408
3575
  return;
3409
3576
  }
3410
- const response = await fetch(citationUrl(row, 'page'), { credentials: 'same-origin', cache: 'no-store' });
3411
- if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3577
+ const response = await fetch(citationUrl(row, 'page'), { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
3578
+ if (!response.ok) { const why = await refused(response); if (!finished) { status.textContent = why; retry(); } return; }
3412
3579
  const { page } = await response.json();
3413
3580
  if (finished) return;
3414
3581
  status.textContent = entry.chosen ? 'The Knowledge page as it was when you chose it.' : 'The Knowledge page as it was when the answer cited it.';
@@ -3423,9 +3590,11 @@
3423
3590
  body.append(article);
3424
3591
  dialog.append(knowledge);
3425
3592
  } catch (error) {
3593
+ if (finished) return;
3426
3594
  console.error('[chat] a cited source could not be opened', error);
3427
- if (!finished) status.textContent = 'FloLess could not open this source right now. Try again in a moment.';
3428
- }
3595
+ status.textContent = 'FloLess could not open this source right now. Try again to check and open the same source.';
3596
+ retry();
3597
+ } finally { loaded(); }
3429
3598
  }
3430
3599
 
3431
3600
  /**
@@ -3998,8 +4167,47 @@
3998
4167
  return item;
3999
4168
  }
4000
4169
 
4170
+ /** One completed auto-review record, using the same disclosure and per-chat state as answer receipts. */
4171
+ function renderAutoReviewReceipt(event) {
4172
+ const chatId = state.chat?.chatId || '';
4173
+ if (receiptFoldsChat !== chatId) { receiptFolds.clear(); receiptFoldsChat = chatId; }
4174
+ const key = `auto-review:${event.eventId}`;
4175
+ let fold = receiptFolds.get(key);
4176
+ if (!fold) {
4177
+ fold = newReceiptFold(key);
4178
+ fold.root.classList.add('auto-review', 'ai-chat-auto-review-receipt');
4179
+ fold.toggle.dataset.commandId = `shell.chat-auto-review-details#${event.eventId}`;
4180
+ fold.toggle.dataset.commandInstanceLabel = 'this auto-approved action';
4181
+ fold.text.textContent = 'Auto-approved · Details';
4182
+ fold.body.setAttribute('aria-label', 'Auto-approval details');
4183
+ const record = document.createElement('pre');
4184
+ record.className = 'ai-chat-auto-review-record';
4185
+ record.tabIndex = 0;
4186
+ record.dataset.commandId = `shell.chat-auto-review-record#${event.eventId}`;
4187
+ record.dataset.commandInstanceLabel = 'this auto-approved action';
4188
+ record.setAttribute('aria-label', 'Auto-approval record');
4189
+ fold.body.append(record);
4190
+ fold.root.addEventListener('keydown', (keyEvent) => {
4191
+ if (keyEvent.key !== 'Escape' || !fold.open || keyEvent.defaultPrevented) return;
4192
+ keyEvent.preventDefault(); keyEvent.stopPropagation();
4193
+ fold.toggle.click(); fold.toggle.focus({ preventScroll: true });
4194
+ });
4195
+ }
4196
+ fold.root.dataset.eventId = event.eventId;
4197
+ fold.root.dataset.eventSequence = String(event.sequence);
4198
+ const record = fold.body.firstElementChild;
4199
+ const payload = event.payload || {};
4200
+ const message = [String(payload.message ?? ''),
4201
+ typeof payload.command === 'string' ? `Command\n${payload.command}` : '',
4202
+ typeof payload.reviewExplanation === 'string' ? `Review explanation\n${payload.reviewExplanation}` : '',
4203
+ ].filter(Boolean).join('\n\n');
4204
+ if (record.textContent !== message) record.textContent = message;
4205
+ return fold.root;
4206
+ }
4207
+
4001
4208
  /** A refusal FloLess wrote for the person (`plain`), shown as is: what happened, why, and what to do next. */
4002
4209
  function renderPlainNotice(event) {
4210
+ if (event.payload?.tool === 'auto-review' && event.payload.decision === 'approved') return renderAutoReviewReceipt(event);
4003
4211
  const item = document.createElement('div');
4004
4212
  // #2037: a Codex auto-review decision is a receipt, not a failure: approved is information, held back is a notice.
4005
4213
  const review = event.payload?.tool === 'auto-review' ? event.payload.decision : null;
@@ -5336,13 +5544,19 @@
5336
5544
  const close = button('Close', commands.close, 'ai-chat-source-viewer-close');
5337
5545
  let picture = null;
5338
5546
  let finished = false;
5547
+ const controller = new AbortController();
5548
+ let loadingTimer = null;
5339
5549
  const finish = () => {
5340
5550
  if (finished) return;
5341
5551
  finished = true;
5552
+ controller.abort();
5553
+ clearTimeout(loadingTimer);
5342
5554
  if (dialog.open) dialog.close();
5343
5555
  hide();
5344
5556
  if (picture) URL.revokeObjectURL(picture);
5345
- if (opener?.isConnected) opener.focus({ preventScroll: true });
5557
+ const returnTo = opener?.isConnected ? opener : opener?.dataset.commandId
5558
+ ? [...document.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === opener.dataset.commandId) : null;
5559
+ returnTo?.focus({ preventScroll: true });
5346
5560
  };
5347
5561
  close.addEventListener('click', finish);
5348
5562
  dialog.addEventListener('close', finish);
@@ -5350,15 +5564,9 @@
5350
5564
  const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: noteText });
5351
5565
  const filterNote = Object.assign(document.createElement('p'), { className: 'ai-chat-evidence-filter-note', hidden: true });
5352
5566
  filterNote.setAttribute('role', 'status');
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');
5354
- const area = button('This area', commands.view, 'ai-chat-evidence-view');
5355
- const whole = button('Whole sheet', commands.view, 'ai-chat-evidence-view');
5356
- area.dataset.commandInstanceLabel = 'this area'; whole.dataset.commandInstanceLabel = 'the whole sheet';
5357
5567
  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);
5568
+ const viewport = drawingViewport(place, commands.view);
5569
+ const { bar, frame } = viewport;
5362
5570
  if (filter?.projectId && filter.commandId) {
5363
5571
  bar.append(drawingFilterButton(place, filter, {
5364
5572
  shown: () => finish(),
@@ -5369,129 +5577,26 @@
5369
5577
  const body = document.createElement('div'); body.className = 'ai-chat-source-viewer-body';
5370
5578
  const status = Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-status', textContent: 'Loading the drawing…' });
5371
5579
  status.setAttribute('role', 'status');
5372
- const crop = evidenceCrop(place);
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;
5409
- const show = (all) => {
5410
- shownAll = all;
5411
- area.setAttribute('aria-pressed', String(!all)); whole.setAttribute('aria-pressed', String(all));
5412
- frame.dataset.view = all ? 'sheet' : 'area';
5413
- const c = all ? { x0: crop.px0, y0: crop.py0, w: crop.pageW, h: crop.pageH } : crop;
5414
- // Shaped like the crop and never taller than most of the window: narrowed, not squashed, so the picture stays true.
5415
- frame.style.aspectRatio = `${c.w} / ${c.h}`;
5416
- frame.style.width = `min(100%, calc(62vh * ${c.w / c.h}))`;
5417
- view = { x0: c.x0, y0: c.y0, w: c.w, h: c.h };
5418
- paintView();
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
- });
5476
- area.addEventListener('click', () => show(false));
5477
- whole.addEventListener('click', () => show(true));
5478
- show(!marked);
5479
5580
  body.append(status, frame);
5480
5581
  dialog.append(head, note, bar, filterNote, body);
5481
5582
  const hide = showChatViewer(dialog, finish);
5482
5583
  close.focus({ preventScroll: true });
5584
+ loadingTimer = setTimeout(() => { if (!finished && !frame.querySelector('img')) status.textContent = `Still loading ${place.sheet}. You can close this window while it loads.`; }, 4000);
5483
5585
  // A place that changed or is gone says so and offers the way on: the card asked for again, never sent for the person.
5484
5586
  const offerAgain = (why) => {
5485
5587
  if (finished) return;
5588
+ clearTimeout(loadingTimer);
5486
5589
  status.textContent = why;
5487
5590
  frame.remove(); bar.remove(); filterNote.remove();
5488
5591
  const way = button(again.label, again.commandId, 'ai-chat-source-viewer-knowledge');
5489
5592
  if (again.tip) way.dataset.tip = again.tip;
5490
5593
  way.addEventListener('click', () => { finish(); again.run(); });
5491
- dialog.append(way);
5594
+ const retry = button('Try again', 'shell.chat-drawing-retry', 'ai-chat-source-viewer-knowledge ai-chat-drawing-retry');
5595
+ retry.addEventListener('click', () => { finish(); void openDrawingPlace(place, { title, note: noteText, url, opener, commands, again, filter }); });
5596
+ dialog.append(retry, way);
5492
5597
  };
5493
5598
  try {
5494
- const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store' });
5599
+ const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
5495
5600
  if (finished) return;
5496
5601
  if (!response.ok) {
5497
5602
  const said = await response.json().catch(() => null);
@@ -5502,14 +5607,13 @@
5502
5607
  if (finished) return;
5503
5608
  picture = URL.createObjectURL(bytes);
5504
5609
  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;
5506
- frame.append(image);
5507
- paintView();
5610
+ if (!await viewport.setImage(image, () => !finished)) return;
5508
5611
  status.textContent = `${place.sheet} · page ${place.page}`;
5509
5612
  } catch (error) {
5613
+ if (finished) return;
5510
5614
  console.error('[chat] a drawing place could not be opened', error);
5511
5615
  offerAgain('FloLess could not open this drawing just now. Try again in a moment.');
5512
- }
5616
+ } finally { clearTimeout(loadingTimer); }
5513
5617
  }
5514
5618
 
5515
5619
  /*
@@ -6689,7 +6793,7 @@
6689
6793
  // follows); a message refused or not sent stops counting, and the card is back.
6690
6794
  const movedPast = (waits === 'you' || movedPastFeedCards.has(id)) && feedCardAnsweredInChat(event, id);
6691
6795
  if (movedPast) movedPastFeedCards.add(id);
6692
- const byItself = !feedCardFolded(node) && ((waits === 'done' && !openedFeedCards.has(id)) || movedPast);
6796
+ const byItself = !feedCardFolded(node) && (((waits === 'done' || mark?.dataset.autoFold === 'true') && !openedFeedCards.has(id)) || movedPast);
6693
6797
  if (hiddenFeedCards.has(id) || byItself) {
6694
6798
  const { sentence, full } = feedCardSentence(node, kind, mark);
6695
6799
  // Amber while the person's choice waits, blue while the AI or the read still works, quiet once it is finished.
@@ -6765,6 +6869,7 @@
6765
6869
  }
6766
6870
 
6767
6871
  function renderEvent(event) {
6872
+ if (event.type === 'height-question-state') { applyHeightQuestionState(event); return null; }
6768
6873
  if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
6769
6874
  if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
6770
6875
  if (event.type === 'assistant-message' && event.payload?.filterAi && !event.payload?.delta) return renderFilterAnswer(event);
@@ -6915,15 +7020,17 @@
6915
7020
  * Typed text is not in the signature on purpose: it lives in the field and in `drafts`, and a keystroke is not a
6916
7021
  * reason to rebuild. Everything else a card paints from belongs in it.
6917
7022
  */
6918
- const CARD_SIGNATURE_SKIP = new Set(['node', 'nodeSig', 'drafts', 'bulkDraft', 'rowsScroll', 'bodyScroll', 'reloadPending', 'loading', 'slotNode', 'slotDrafts', 'slotSig']);
7023
+ const CARD_SIGNATURE_SKIP = new Set(['node', 'nodeSig', 'drafts', 'bulkDraft', 'rowsScroll', 'bodyScroll', 'reloadPending', 'loading', 'checkedAt', 'slotNode', 'slotDrafts', 'slotSig']);
6919
7024
  function cardSignature(entry, eventId, sequence) {
6920
7025
  settleNotSent(entry);
6921
7026
  const sources = [];
6922
7027
  for (const [scope, source] of answerSources) {
6923
- if (scope.split(':')[1] !== entry.questionId) continue;
7028
+ if (scope.startsWith('h:')) {
7029
+ if (!heightSourceBelongs(entry, scope)) continue;
7030
+ } else if (scope.split(':')[1] !== entry.questionId) continue;
6924
7031
  sources.push([scope, source.open, Boolean(source.note), source.files.map((file) => file.attachmentId), source.uploading, source.error]);
6925
7032
  }
6926
- return JSON.stringify([eventId, sequence, sources, entry], (key, value) => {
7033
+ return JSON.stringify([eventId, sequence, sources, entry, Boolean(entry.view?.ends && heightClarificationPending(entry))], (key, value) => {
6927
7034
  if (CARD_SIGNATURE_SKIP.has(key)) return undefined;
6928
7035
  if (value instanceof Map) return [...value];
6929
7036
  if (value instanceof Set) return [...value];
@@ -6946,10 +7053,81 @@
6946
7053
  entry = { key, requestId, questionId, chatId, view: null, loading: false, loadError: '', drafts: new Map(),
6947
7054
  changing: new Set(), rowErrors: new Map(), cardError: '', busy: false, selected: new Set(), bulkDraft: '' };
6948
7055
  heightCards.set(key, entry);
7056
+ restoreHeightDraft(entry);
6949
7057
  }
6950
7058
  return entry;
6951
7059
  }
6952
7060
 
7061
+ // Synchronous per-conversation storage: an older asynchronous response cannot restore an earlier draft.
7062
+ const heightDraftKey = (entry) => `floless-height-draft/v1/${encodeURIComponent(entry.chatId)}/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}`;
7063
+ function saveHeightDraft(entry) {
7064
+ try {
7065
+ const sources = [...answerSources].filter(([scope]) => heightSourceBelongs(entry, scope))
7066
+ .map(([scope, source]) => {
7067
+ if (scope === heightSourceScope(entry) && !source.scopeEnds && (source.note?.trim() || source.files.length)) source.scopeEnds = entry.slotQuestionKey === 'batch-value' ? [...entry.selected] : drawingRows('height', entry).filter((row) => row.status !== 'superseded').map(heightEndKey);
7068
+ return [scope, { open: source.open, note: source.note, scopeEnds: source.scopeEnds, files: source.files.map(({ url, ...file }) => file) }];
7069
+ });
7070
+ const slots = [...(entry.slotDrafts || [])].filter(([key]) => key !== 'finish');
7071
+ const value = { slots, sources, retiredDrafts: [...(entry.retiredDrafts || [])], projectId: entry.projectId, activeItem: entry.activeItem, slotPhase: entry.slotPhase, selected: [...entry.selected] };
7072
+ if (!window.sessionStorage) return; // Older embedded browsers keep the live draft only.
7073
+ window.sessionStorage.setItem(heightDraftKey(entry), JSON.stringify(value));
7074
+ entry.draftStorageError = '';
7075
+ } catch { entry.draftStorageError = 'Your draft is kept in this window, but FloLess could not keep it for a reload. Copy your text before refreshing; keep this window open to finish the answer.'; }
7076
+ }
7077
+ function restoreHeightDraft(entry) {
7078
+ try {
7079
+ const value = JSON.parse(window.sessionStorage?.getItem(heightDraftKey(entry)) || 'null');
7080
+ if (!value || !Array.isArray(value.slots) || !Array.isArray(value.sources)) return;
7081
+ entry.slotDrafts = new Map(value.slots.filter(([key, draft]) => typeof key === 'string' && Array.isArray(draft?.rows)).map(([key, draft]) => [key, { ...draft, pending: false }]));
7082
+ if (Array.isArray(value.retiredDrafts)) entry.retiredDrafts = new Map(value.retiredDrafts);
7083
+ if (typeof value.projectId === 'string') entry.projectId = value.projectId;
7084
+ entry.activeItem = value.activeItem; entry.slotPhase = value.slotPhase; entry.selected = new Set(value.selected || []);
7085
+ for (const [savedScope, source] of value.sources) {
7086
+ const scope = restoredHeightSourceScope(entry, savedScope);
7087
+ if (!scope || !Array.isArray(source.files)) continue;
7088
+ const recovered = { ...source, restored: true, uploading: 0, error: '', files: source.files.map((file) => ({ ...file, url: '' })) };
7089
+ answerSources.set(scope, recovered);
7090
+ }
7091
+ } catch { /* Invalid stored drafts never affect authoritative questions or answers. */ }
7092
+ }
7093
+ function checkHeightDraftPictures(entry) {
7094
+ if (entry.view?.readRemoved) return;
7095
+ for (const [scope, source] of answerSources) {
7096
+ if (!source.restored || !(heightSourceBelongs(entry, scope))) continue;
7097
+ source.restored = false;
7098
+ for (const file of source.files) {
7099
+ const url = heightDraftEvidenceUrl(entry, file.attachmentId);
7100
+ if (!url) { source.error = 'Open this question in its original project to check the saved picture; your text is kept.'; continue; }
7101
+ file.url = url;
7102
+ fetch(url, { credentials: 'same-origin' }).then((response) => {
7103
+ if (!response.ok && source.files.includes(file)) { source.error = response.status === 404 || response.status === 410
7104
+ ? `The saved picture ${file.fileName} is no longer available. Remove it and attach it again; your text is kept.`
7105
+ : 'FloLess could not check your saved pictures just now. Try again before submitting; your text is kept.'; repaintHeightCard(entry); }
7106
+ }).catch(() => { source.error = 'FloLess could not check your saved pictures. Try again before submitting; your text is kept.'; repaintHeightCard(entry); });
7107
+ }
7108
+ }
7109
+ }
7110
+ const heightStateEvents = new Set();
7111
+ function applyHeightQuestionState(event) {
7112
+ if (heightStateEvents.has(event.eventId)) return;
7113
+ heightStateEvents.add(event.eventId);
7114
+ const payload = event.payload || {}, entry = heightCards.get(`${payload.requestId}/${payload.questionId}`);
7115
+ if (!entry || entry.chatId !== event.chatId) return;
7116
+ if (entry.loading || entry.busy) entry.reloadPending = true; else loadHeightQuestion(entry);
7117
+ }
7118
+ function heightResponsibility(row) {
7119
+ return row.responsibility || (row.status === 'superseded' ? 'replaced' : row.answer && row.answer.how !== 'evidence' ? 'answered' : row.answer ? 'investigating' : row.proposed ? 'proposal' : 'needs-answer');
7120
+ }
7121
+ function heightStateText(row) {
7122
+ const state = heightResponsibility(row);
7123
+ const label = { investigating: 'AI investigating', 'needs-answer': 'Needs your answer', proposal: 'Proposed height — needs your confirmation', answered: 'Answered', replaced: 'Replaced by a newer question', 'resolved-from-drawings': 'Resolved from drawings', 'no-longer-needed': 'No longer needed' }[state];
7124
+ return `${label}${row.lifecycle?.reason ? ` · ${row.lifecycle.reason}` : state === 'needs-answer' && row.noProposal ? ` · ${row.noProposal}` : ''}`;
7125
+ }
7126
+ function heightStudyText(row) {
7127
+ const study = row.lifecycle?.investigation;
7128
+ return study ? [`Reader-reported study (${study.provenance})${study.datum ? ` · datum ${study.datum}` : ''}.`, ...study.checked.map((check) => `${check.sheet}${check.detail ? ` · ${check.detail}` : ''}: ${check.finding}`), !study.checked.length ? 'No source checks recorded.' : '', ...(study.conflicts || []), study.derivation ? `${study.derivation.inputs.join('; ')}. ${study.derivation.basis}` : '', study.limitations].filter(Boolean).join(' ') : !row.proposed && ['needs-answer', 'investigating'].includes(heightResponsibility(row)) ? 'No source checks recorded.' : '';
7129
+ }
7130
+
6953
7131
  const heightEndKey = (row) => `${row.memberId}\u0000${row.end}`;
6954
7132
  const heightEndWord = (row) => (row.endWord === 'from' ? 'start' : 'end');
6955
7133
  // #2788: a confirmed proposal keeps where it came from, so a derived height never reads as one taken off a drawing.
@@ -6978,7 +7156,8 @@
6978
7156
  // The server's sentence, then what to do next when it names a step (a damaged record says to discard the read).
6979
7157
  const heightErrorText = (error, fallback) => {
6980
7158
  const next = (error?.recovery || []).map((step) => step && typeof step.action === 'string' ? step.action : '').filter(Boolean);
6981
- return [error?.message || fallback, ...next].join(' ');
7159
+ const message = /failed to fetch|fetch failed|networkerror|load failed/i.test(error?.message || '') ? fallback : (error?.message || fallback);
7160
+ return [message, ...next].join(' ');
6982
7161
  };
6983
7162
  // Refusals that mean the card is out of date: reload it from the server's record so it shows the truth.
6984
7163
  const HEIGHT_STALE = new Set(['height-question-changed', 'height-question-closed', 'height-question-superseded']);
@@ -6989,13 +7168,74 @@
6989
7168
  const CARD_READ_FINISHED = new Set(['height-question-unknown-read', 'setup-question-unknown-read']);
6990
7169
  const CARD_FINISHED_TEXT = 'This drawing read is closed, so this card can no longer change. If the read published a model, your answers are in it: open Model to see them.';
6991
7170
 
7171
+ const heightSourceScope = (entry, key = 'bulk') => `h:${JSON.stringify([entry.chatId, entry.requestId, entry.questionId, key])}`;
7172
+ function heightSourceBelongs(entry, scope) {
7173
+ try {
7174
+ if (typeof scope !== 'string' || !scope.startsWith('h:[')) return false;
7175
+ const identity = JSON.parse(scope.slice(2));
7176
+ return Array.isArray(identity) && identity.length === 4 && identity[0] === entry.chatId && identity[1] === entry.requestId
7177
+ && identity[2] === entry.questionId && typeof identity[3] === 'string';
7178
+ } catch { return false; }
7179
+ }
7180
+ // Legacy scopes carry no chat/read identity. Translate them ONLY from this entry's already-scoped storage envelope.
7181
+ function restoredHeightSourceScope(entry, scope) {
7182
+ if (heightSourceBelongs(entry, scope)) return scope;
7183
+ if (scope === `hb:${entry.questionId}`) return heightSourceScope(entry);
7184
+ const prefix = `h:${entry.questionId}:`;
7185
+ return typeof scope === 'string' && scope.startsWith(prefix) ? heightSourceScope(entry, scope.slice(prefix.length)) : null;
7186
+ }
7187
+ const mergeHeightClarification = (origin, addition) => origin && addition && (origin === addition || origin.endsWith(`\n\n${addition}`)) ? origin : origin && addition ? `${origin}\n\n${addition}` : (addition || origin || '');
7188
+ const heightDraftFileIds = new WeakMap(); let heightDraftFileN = 0;
7189
+ const heightDraftFileId = (file) => { if (!heightDraftFileIds.has(file)) heightDraftFileIds.set(file, ++heightDraftFileN); return heightDraftFileIds.get(file); };
7190
+ function heightDraftSnapshot(entry, scope, draftKey) {
7191
+ const source = answerSources.get(scope);
7192
+ const draft = entry.slotDrafts?.get(draftKey)?.rows[0];
7193
+ return JSON.stringify([source?.note || '', (source?.files || []).map((file) => file.attachmentId).sort(), draft ? [draft.other, draft.choices, draft.reason, draft.otherOpen] : null, (source?.failedUploads || []).map(heightDraftFileId), source?.uploading || 0]);
7194
+ }
7195
+ function reconcileHeightSubmission(entry) {
7196
+ if (!entry.failedSubmission || !entry.view) return;
7197
+ const same = entry.failedSubmission.every((input) => {
7198
+ const row = entry.view.ends.find((item) => heightEndKey(item) === heightEndKey(input));
7199
+ const answer = row?.answer;
7200
+ return answer && answer.how === (input.action === 'type' ? 'typed' : input.action === 'confirm' ? 'confirmed' : 'evidence')
7201
+ && (input.action !== 'type' || answer.typed === input.typed.trim())
7202
+ && (input.action !== 'confirm' || answer.value === input.shown)
7203
+ && (answer.note || '') === input.expectedNote
7204
+ && JSON.stringify((answer.evidence || []).map((file) => file.attachmentId).sort()) === JSON.stringify(input.expectedFiles);
7205
+ });
7206
+ if (!same) {
7207
+ for (const input of entry.failedSubmission) entry.changing.add(heightEndKey(input));
7208
+ return;
7209
+ }
7210
+ let newer = false;
7211
+ const unchanged = new Map(entry.failedSubmission.map((input) => [input, heightDraftSnapshot(entry, input.scope, input.draftKey) === input.draftSnapshot]));
7212
+ for (const input of entry.failedSubmission) {
7213
+ const key = heightEndKey(input);
7214
+ if (!unchanged.get(input)) {
7215
+ newer = true; entry.changing.add(key);
7216
+ continue;
7217
+ }
7218
+ entry.changing.delete(key); entry.drafts.delete(key); entry.slotDrafts?.delete(input.draftKey); clearAnswerSource(input.scope);
7219
+ }
7220
+ entry.failedSubmission = null; entry.saveFailed = false; entry.rowErrors.clear();
7221
+ entry.cardError = newer ? 'Your earlier answer was saved. Your newer edits and files are kept here; submit them when ready.' : '';
7222
+ if (!newer) entry.activeItem = null;
7223
+ }
6992
7224
  function loadHeightQuestion(entry) {
6993
7225
  if (entry.loading) return;
7226
+ entry.checkedAt = Date.now();
6994
7227
  entry.loading = true;
6995
7228
  request(`/api/chat/height-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}?${new URLSearchParams({ chatId: entry.chatId || '' })}`)
6996
7229
  .then((result) => {
6997
- if (result?.readClosed) { entry.finished = true; entry.view = null; } else entry.view = result.question;
7230
+ if (result.question && (result.question.revision || 0) < (entry.view?.revision || 0)) return;
7231
+ for (const row of result.question?.ends || []) {
7232
+ const prior = entry.view?.ends?.find((old) => heightEndKey(old) === heightEndKey(row));
7233
+ if (row.lifecycleRevision !== prior?.lifecycleRevision) entry.changing.delete(heightEndKey(row));
7234
+ }
7235
+ if (result?.readClosed) { entry.finished = true; if (entry.view) entry.view = { ...entry.view, open: false, readRemoved: true }; } else entry.view = result.question;
7236
+ if (entry.view) checkHeightDraftPictures(entry);
6998
7237
  entry.loadError = '';
7238
+ reconcileHeightSubmission(entry);
6999
7239
  // #1903: an existing member's "in the model" height is shown in the question's units, which needs
7000
7240
  // the shared helper; repaint once it has loaded.
7001
7241
  if (entry.view?.ends?.some((row) => row.inModel) && !displayUnitsModule) loadDisplayUnitsModule().then(() => repaintHeightCard(entry));
@@ -7008,6 +7248,7 @@
7008
7248
  }
7009
7249
 
7010
7250
  function repaintHeightCard(entry) {
7251
+ saveHeightDraft(entry);
7011
7252
  const old = ui.feed?.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
7012
7253
  if (!old) { drawingSlotRepaint(); return; }
7013
7254
  const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
@@ -7027,7 +7268,7 @@
7027
7268
  /** The caret of a focused text field, or null (a radio or checkbox has none, and reading it can throw). */
7028
7269
  function textCaret(control) {
7029
7270
  try {
7030
- if (control?.tagName === 'INPUT' && (control.type === 'text' || !control.type) && typeof control.selectionStart === 'number') {
7271
+ if ((control?.tagName === 'TEXTAREA' || control?.tagName === 'INPUT' && (control.type === 'text' || !control.type)) && typeof control.selectionStart === 'number') {
7031
7272
  return { start: control.selectionStart, end: control.selectionEnd, direction: control.selectionDirection || 'none' };
7032
7273
  }
7033
7274
  } catch { /* no caret */ }
@@ -7039,7 +7280,7 @@
7039
7280
  if (!control) return false;
7040
7281
  control.focus({ preventScroll: true });
7041
7282
  // Text fields only: a radio or checkbox has no caret, and setSelectionRange on one throws (#1906).
7042
- if (control.tagName === 'INPUT' && (control.type === 'text' || !control.type)) {
7283
+ if (control.tagName === 'TEXTAREA' || control.tagName === 'INPUT' && (control.type === 'text' || !control.type)) {
7043
7284
  // Where the person's caret was, not the end: a repaint mid-word must not move it (#2163).
7044
7285
  if (caret) control.setSelectionRange?.(Math.min(caret.start, control.value.length), Math.min(caret.end, control.value.length), caret.direction);
7045
7286
  else control.setSelectionRange?.(control.value.length, control.value.length);
@@ -7050,10 +7291,13 @@
7050
7291
  function renderHeightQuestion(event) {
7051
7292
  const payload = event.payload || {};
7052
7293
  const entry = heightCardState(String(payload.requestId || ''), String(payload.questionId || ''), String(event.chatId || state.chat?.chatId || ''));
7294
+ const projectId = drawingEntryCurrent(entry) && state.scope?.owner?.kind === 'project' ? state.scope.owner.projectId : payload.projectId || (typeof chatProjectId === 'function' ? chatProjectId() : '');
7295
+ if (projectId) entry.projectId = String(projectId);
7053
7296
  if (!entry.view && !entry.loadError && !entry.finished) {
7054
7297
  if (!entry.loading) refreshEarlierCards(heightCards, entry, loadHeightQuestion);
7055
7298
  loadHeightQuestion(entry);
7056
7299
  }
7300
+ else if (entry.view?.open && !entry.busy && Date.now() - (entry.checkedAt || 0) > 5000) loadHeightQuestion(entry);
7057
7301
  return reusableCard(entry, event.eventId, String(event.sequence))
7058
7302
  || rememberCard(entry, paintHeightCard(entry, event.eventId, String(event.sequence)), event.eventId, String(event.sequence));
7059
7303
  }
@@ -7175,15 +7419,34 @@
7175
7419
  return open;
7176
7420
  }
7177
7421
  /** A row's sheet, as a small button in the card's list: the same place, no picture, so a long list stays short. */
7178
- function heightPlaceChip(entry, row) {
7422
+ function heightPlaceChip(entry, row, phase = null) {
7179
7423
  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}`);
7424
+ const command = phase ? `shell.chat-height-batch-place#${entry.questionId} ${phase} ${row.memberId} ${row.endWord}` : `shell.chat-height-row-place#${entry.questionId} ${row.memberId} ${row.endWord}`;
7425
+ const chip = button(phase ? 'Show on drawing' : row.place.sheet, command, 'ai-chat-height-sheet');
7426
+ chip.dataset.commandInstanceLabel = `${row.label}${phase ? ` · ${heightEndWord(row)}` : ''} on ${row.place.sheet}`;
7427
+ chip.setAttribute('aria-label', phase ? `Show ${row.label} · ${heightEndWord(row)} on sheet ${row.place.sheet}` : `Open sheet ${row.place.sheet} at ${row.label}`);
7183
7428
  chip.dataset.tip = `Opens sheet ${row.place.sheet} with this place outlined`;
7184
7429
  chip.addEventListener('click', () => openHeightPlace(entry, row, chip));
7185
7430
  return chip;
7186
7431
  }
7432
+ /** Grouped answers keep every end's own place beside its label; drawing bytes load only when its button is pressed. */
7433
+ function heightBatchPlaces(entry, rows, phase, descriptions = []) {
7434
+ const list = document.createElement('ol'); list.className = 'ai-chat-height-rows ai-chat-height-batch-places';
7435
+ list.setAttribute('aria-label', 'Member ends on the drawings');
7436
+ rows.forEach((row, index) => {
7437
+ const item = document.createElement('li'); item.className = 'ai-chat-height-row';
7438
+ const line = document.createElement('div'); line.className = 'ai-chat-height-labelline';
7439
+ line.append(Object.assign(document.createElement('span'), { className: 'ai-chat-height-label', textContent: `${row.label} · ${heightEndWord(row)}` }));
7440
+ const chip = heightPlaceChip(entry, row, phase); if (chip) line.append(chip);
7441
+ item.append(line);
7442
+ if (descriptions[index]) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-ask-context', textContent: descriptions[index] }));
7443
+ const context = row.place ? `${row.place.sheet} · page ${row.place.page}` : '';
7444
+ item.append(Object.assign(document.createElement('span'), { className: 'ai-chat-height-meta',
7445
+ textContent: heightPlaced(row) ? context : [context, heightUnplacedText(row)].filter(Boolean).join(' · ') }));
7446
+ list.append(item);
7447
+ });
7448
+ return list;
7449
+ }
7187
7450
  /** #2774: where a proposed height came from, in the option's own words. A derived one is an assumption and says how. */
7188
7451
  function heightProposalWords(proposed) {
7189
7452
  // #2802: an elevation printed on the sheet and measured from a datum shows the conversion, so the person confirms it.
@@ -7193,7 +7456,7 @@
7193
7456
  if (proposed.how === 'read') return { description: `Read off the drawings${proposed.basis ? `: ${proposed.basis}` : ''}${datum}` };
7194
7457
  return { description: `Use the value proposed for this member end${datum}` };
7195
7458
  }
7196
- const heightNoProposalText = (row) => (row.noProposal ? `No height proposed: ${row.noProposal}` : 'The read proposed no height and gave no reason.');
7459
+ const heightNoProposalText = (row) => `${row.noProposal ? `No height proposed: ${row.noProposal}` : 'The read proposed no height and gave no reason.'}${!row.lifecycle?.investigation ? ' No source checks recorded.' : ''}`;
7197
7460
 
7198
7461
  function paintHeightRow(entry, row, open) {
7199
7462
  const key = heightEndKey(row);
@@ -7213,6 +7476,7 @@
7213
7476
  // names the wrong member is visibly at odds with what the id really is.
7214
7477
  meta.textContent = [row.inModel?.profile, row.memberId, heightEndWord(row)].filter(Boolean).join(' · ');
7215
7478
  item.append(labelLine, meta);
7479
+ if (row.answer?.how === 'evidence' && row.lifecycle) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `${heightStateText(row)}. ${heightStudyText(row)}` }));
7216
7480
  if (row.inModel) {
7217
7481
  const inModel = document.createElement('div'); inModel.className = 'ai-chat-height-inmodel';
7218
7482
  inModel.textContent = `${heightInModelText(row.inModel, entry.view?.units)} ${HEIGHT_PROPOSED_TEXT}`;
@@ -7233,9 +7497,11 @@
7233
7497
  // #2167: a note with no picture and no height is honest about it: no height is claimed, the AI is asked to find it.
7234
7498
  const noteOnly = picture && !row.answer.evidence?.length;
7235
7499
  const text = document.createElement('span');
7236
- text.textContent = noteOnly ? 'Note sent. The read will look for the height.' : picture ? 'Waiting for the read to read your picture' : heightAnswerText(row.answer);
7500
+ text.textContent = picture && heightResponsibility(row) === 'needs-answer' ? 'Your earlier note or picture is kept. The read needs your answer now.'
7501
+ : picture && ['resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row)) ? 'Your earlier note or picture is kept as evidence. The status above explains how the question ended.'
7502
+ : picture ? 'Clarification saved. Height still unresolved; tell the read to work out a proposal.' : heightAnswerText(row.answer);
7237
7503
  done.append(glyph, text);
7238
- if (open) {
7504
+ if (open && !['resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row))) {
7239
7505
  const change = heightActionButton(picture ? 'Answer now' : 'Change', idFor('change'), instance, 'ai-chat-height-change', entry.busy ? 'A height is still being saved — wait for it to finish' : null);
7240
7506
  change.setAttribute('aria-label', picture ? `Answer the height for ${row.label} yourself instead` : `Change the height for ${row.label}`);
7241
7507
  change.addEventListener('click', () => {
@@ -7246,8 +7512,9 @@
7246
7512
  done.append(change);
7247
7513
  }
7248
7514
  item.append(done);
7249
- const source = paintAnsweredSource(entry.requestId, row.answer, sourceIdFor, instance);
7515
+ const source = paintAnsweredSource(entry.requestId, entry.view?.readRemoved ? { ...row.answer, evidence: [] } : row.answer, sourceIdFor, instance);
7250
7516
  if (source) item.append(source);
7517
+ if (entry.view?.readRemoved && row.answer.evidence?.length) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Pictures recorded with this answer: ${row.answer.evidence.map((file) => file.fileName).join(', ')}. This read is closed, so these pictures cannot be opened here. Review the saved model's answer evidence or your original files.` }));
7251
7518
  return item;
7252
7519
  }
7253
7520
  if (!open) {
@@ -7269,11 +7536,24 @@
7269
7536
  const ownedSlot = drawingEntryCurrent(entry) && ui.approvalTray?.querySelector('.ai-chat-drawing-step')?.dataset.drawingStep;
7270
7537
  const ownedNode = ownedSlot ? ui.approvalTray.querySelector('.ai-chat-drawing-step') : null;
7271
7538
  const pendingFocusId = ownedNode?.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
7272
- const failedField = ownedNode && ([...ownedNode.querySelectorAll('input')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
7539
+ const failedField = ownedNode && ([...ownedNode.querySelectorAll('input, textarea')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
7273
7540
  const failedFieldId = failedField?.dataset.commandId, failedCaret = failedField ? textCaret(failedField) : null;
7274
7541
  let saved = false;
7275
- const scopeOf = (answer) => sharedScope || `h:${entry.questionId}:${heightEndKey(answer)}`;
7542
+ const scopeOf = (answer) => sharedScope || heightSourceScope(entry, heightEndKey(answer));
7276
7543
  const withSource = answers.map((answer) => ({ ...answer, ...answerSourcePayload(scopeOf(answer)) }));
7544
+ const unfinished = answers.map((answer) => answerSources.get(scopeOf(answer))).find((source) => source?.uploading || source?.failedUploads?.length);
7545
+ if (unfinished) {
7546
+ const message = unfinished.uploading ? 'A file is still uploading. Your answer is kept; wait for it to finish, then Submit.' : 'A selected file was not uploaded. Retry its upload or choose Leave out next to that file, then Submit. Your answer and file are kept until you decide.';
7547
+ if (rowKey) entry.rowErrors.set(rowKey, message); else entry.cardError = message; repaintHeightCard(entry); return false;
7548
+ }
7549
+ if (withSource.some((answer) => answer.note?.length > MAX_HEIGHT_CLARIFICATION)) {
7550
+ const message = 'Your clarification is longer than 8,000 characters. Your full draft and files are kept. Keep a copy and shorten it, or send additional context in chat; chat context does not confirm a height.';
7551
+ if (rowKey) entry.rowErrors.set(rowKey, message); else entry.cardError = message; repaintHeightCard(entry); return false;
7552
+ }
7553
+ const submissionDrafts = new Map(withSource.map((input) => {
7554
+ const scope = scopeOf(input), draftKey = sharedScope ? 'batch-value' : heightEndKey(input);
7555
+ return [heightEndKey(input), { draftKey, draftSnapshot: heightDraftSnapshot(entry, scope, draftKey) }];
7556
+ }));
7277
7557
  entry.busy = true; entry.cardError = ''; if (rowKey) entry.rowErrors.delete(rowKey);
7278
7558
  repaintHeightCard(entry);
7279
7559
  try {
@@ -7284,16 +7564,17 @@
7284
7564
  ...withSource.flatMap((answer) => answer.evidence || []),
7285
7565
  ...[entry.view, result.question].flatMap((view) => (view?.ends || []).flatMap((row) => [...row.answer?.evidence || [], ...row.inherited || []])).map((ref) => ref.attachmentId),
7286
7566
  ]);
7287
- entry.view = result.question;
7567
+ if ((result.question?.revision || 0) >= (entry.view?.revision || 0)) entry.view = result.question;
7288
7568
  // Answering on the card means the person is on it: a message sent while its save kept failing does not fold it now.
7289
- saved = true; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
7569
+ saved = true; entry.failedSubmission = null; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
7290
7570
  for (const answer of answers) {
7291
7571
  const key = heightEndKey(answer);
7572
+ if (result.question?.ends?.find((row) => heightEndKey(row) === key)?.answer) entry.slotDrafts?.delete(key);
7292
7573
  entry.changing.delete(key); entry.drafts.delete(key); entry.selected.delete(key);
7293
7574
  if (entry.activeItem === key) { entry.activeItem = null; entry.reopenedAt = 0; }
7294
7575
  clearAnswerSource(scopeOf(answer));
7295
7576
  if (sharedScope) {
7296
- const rowScope = `h:${entry.questionId}:${key}`, source = answerSources.get(rowScope);
7577
+ const rowScope = heightSourceScope(entry, key), source = answerSources.get(rowScope);
7297
7578
  if (source) {
7298
7579
  source.note = '';
7299
7580
  for (const file of [...source.files]) {
@@ -7318,10 +7599,16 @@
7318
7599
  }
7319
7600
  if (sharedScope) entry.bulkDraft = '';
7320
7601
  } catch (error) {
7321
- let message = heightErrorText(error, 'FloLess could not save this height. Try again.');
7602
+ let message = heightErrorText(error, 'FloLess could not confirm that this answer was saved because the connection was interrupted. Your draft and files are kept. Submit again to check and retry.');
7322
7603
  if (error?.code === 'answer-evidence-unknown') message = dropStaleAnswerFiles([...new Set(answers.map(scopeOf))], entry);
7323
7604
  // A failed save, apart from the card's other notices: the hidden line says so and the card never hides by itself.
7324
7605
  entry.saveFailed = true;
7606
+ entry.failedSubmission = withSource.map((input) => {
7607
+ const row = entry.view?.ends.find((item) => heightEndKey(item) === heightEndKey(input));
7608
+ const origin = row?.answer?.note || row?.inheritedNote, addition = input.note;
7609
+ return { ...input, ...submissionDrafts.get(heightEndKey(input)), scope: scopeOf(input), expectedNote: mergeHeightClarification(origin, addition),
7610
+ expectedFiles: [...new Set([...(input.evidence || []), ...(row?.inherited || []).map((file) => file.attachmentId)])].sort() };
7611
+ });
7325
7612
  // Dropped, not kept: a reload that fails must show its own error and Try again, which only an
7326
7613
  // empty card does — an old view would hide both behind rows that are out of date.
7327
7614
  if (HEIGHT_STALE.has(error?.code)) { entry.cardError = message; entry.view = null; loadHeightQuestion(entry); }
@@ -7364,6 +7651,7 @@
7364
7651
  return at < CARD_ORDINALS.length ? `the ${CARD_ORDINALS[at]} ${noun}` : `${noun} ${at + 1} of ${keys.length}`;
7365
7652
  }
7366
7653
  const heightTellText = (entry) => `I've answered ${cardPlace(entry, 'data-height-question', 'height card')}.`;
7654
+ const heightClarificationText = (entry) => `I saved clarification on ${cardPlace(entry, 'data-height-question', 'height card')}. Please read the saved explanation and attachments and work out a proposal; the height is still unresolved.`;
7367
7655
  const setupTellText = (entry) => `I've answered ${cardPlace(entry, 'data-setup-question', 'read setup card')}.`;
7368
7656
 
7369
7657
  /*
@@ -7392,17 +7680,18 @@
7392
7680
 
7393
7681
  function answerSource(scope) {
7394
7682
  let source = answerSources.get(scope);
7395
- if (!source) { source = { open: false, note: '', files: [], uploading: 0, error: '' }; answerSources.set(scope, source); }
7683
+ if (!source) { source = { open: false, note: '', files: [], failedUploads: [], uploading: 0, error: '' }; answerSources.set(scope, source); }
7396
7684
  return source;
7397
7685
  }
7398
7686
  /** What an answer carries from its source box: the note and the uploaded files' ids. */
7399
7687
  function answerSourcePayload(scope) {
7400
7688
  const source = answerSources.get(scope);
7401
7689
  if (!source) return {};
7402
- const note = source.note.trim();
7690
+ const note = scope.startsWith('h:') ? (source.note.trim() ? source.note : '') : source.note.trim();
7403
7691
  return { ...(note ? { note } : {}), ...(source.files.length ? { evidence: source.files.map((file) => file.attachmentId) } : {}) };
7404
7692
  }
7405
7693
  const MAX_ANSWER_NOTE = 160;
7694
+ const MAX_HEIGHT_CLARIFICATION = 8000;
7406
7695
  // #2167: asked for nothing at all. Said plainly, with the three things that would count.
7407
7696
  const NO_HEIGHT_NO_SOURCE = 'Type a height, or add a note or a picture and the AI will work it out.';
7408
7697
  /** True when the source box holds a note or an attached picture the person could send instead of a height. */
@@ -7445,6 +7734,7 @@
7445
7734
  }
7446
7735
  for (const file of incoming) {
7447
7736
  if (answerSources.get(scope) !== source) break;
7737
+ source.failedUploads = (source.failedUploads || []).filter((held) => held !== file);
7448
7738
  source.uploading += 1; ctx.repaint();
7449
7739
  try {
7450
7740
  const data = await fileBase64(file);
@@ -7465,9 +7755,12 @@
7465
7755
  }
7466
7756
  source.files.push({ ...ref, url: file.type.startsWith('image/') ? URL.createObjectURL(file) : '' });
7467
7757
  } catch (error) {
7468
- source.error = error?.message || `FloLess could not attach “${file.name}”. Try again.`;
7758
+ if (!(source.failedUploads || []).includes(file)) (source.failedUploads ??= []).push(file);
7759
+ source.error = heightErrorText(error, `FloLess could not upload “${file.name}” because the connection was interrupted. Your answer and file are kept here. Retry the upload.`);
7469
7760
  } finally {
7470
- source.uploading -= 1; ctx.repaint();
7761
+ source.uploading -= 1;
7762
+ if (source.failedUploads?.length) source.error = 'A selected file was not uploaded. Retry its upload or choose Leave out next to it, then Submit. Your answer and file are kept until you decide.';
7763
+ ctx.repaint();
7471
7764
  }
7472
7765
  }
7473
7766
  }
@@ -7533,11 +7826,11 @@
7533
7826
  }
7534
7827
 
7535
7828
  /** One recorded picture as a chip: thumbnail for a picture, its name, and a button that opens it. */
7536
- function answerPictureChip(requestId, ref, commandId, instance) {
7829
+ function answerPictureChip(requestId, ref, commandId, instance, pictureUrl = evidenceUrl(requestId, ref.attachmentId)) {
7537
7830
  const chip = document.createElement('span'); chip.className = 'ai-chat-attachment ai-chat-answer-picture';
7538
7831
  if (ref.mediaType.startsWith('image/')) {
7539
7832
  const preview = document.createElement('img'); preview.alt = ''; preview.loading = 'lazy';
7540
- preview.src = evidenceUrl(requestId, ref.attachmentId);
7833
+ preview.src = pictureUrl;
7541
7834
  // A picture the browser cannot show becomes the server's reason, never a broken image (review #1906).
7542
7835
  preview.addEventListener('error', () => {
7543
7836
  const slot = Object.assign(document.createElement('span'), { className: 'ai-chat-answer-missing', textContent: 'checking…' });
@@ -7551,7 +7844,7 @@
7551
7844
  open.dataset.commandInstanceLabel = instance;
7552
7845
  open.dataset.tip = `Open ${ref.fileName}`;
7553
7846
  open.setAttribute('aria-label', `Open ${ref.fileName}`);
7554
- open.addEventListener('click', () => { window.open(evidenceUrl(requestId, ref.attachmentId), '_blank', 'noopener'); });
7847
+ open.addEventListener('click', () => { window.open(pictureUrl, '_blank', 'noopener'); });
7555
7848
  chip.append(open);
7556
7849
  return chip;
7557
7850
  }
@@ -7564,12 +7857,24 @@
7564
7857
  function paintAnswerSource(scope, ctx) {
7565
7858
  const source = answerSource(scope);
7566
7859
  const wrap = document.createElement('div'); wrap.className = 'ai-chat-answer-source';
7860
+ if (ctx.inheritedNote) wrap.append(Object.assign(document.createElement('p'), { className: 'ai-chat-answer-lead ai-chat-inherited-clarification', textContent: `Your earlier clarification: ${ctx.inheritedNote}` }));
7567
7861
  if (ctx.inherited?.length) {
7568
7862
  const kept = document.createElement('div'); kept.className = 'ai-chat-answer-files';
7569
7863
  const lead = document.createElement('span'); lead.className = 'ai-chat-answer-lead'; lead.textContent = 'Your picture';
7570
7864
  kept.append(lead, ...ctx.inherited.map((ref) => answerPictureChip(ctx.requestId, ref, ctx.idFor('picture-open', ref.attachmentId), ctx.instance)));
7571
7865
  wrap.append(kept);
7572
7866
  }
7867
+ for (const file of source.failedUploads || []) {
7868
+ const retry = button(`Retry upload: ${file.name}`, ctx.idFor('attach', `retry ${file.name}`), 'ai-chat-answer-add');
7869
+ retry.dataset.commandInstanceLabel = ctx.instance;
7870
+ if (ctx.busyReason || source.uploading) { const why = ctx.busyReason || 'Wait for the current upload to finish'; retry.setAttribute('aria-disabled', 'true'); retry.dataset.blockedReason = why; retry.dataset.tip = why; }
7871
+ retry.addEventListener('click', () => { if (retry.getAttribute('aria-disabled') !== 'true') attachAnswerFiles(scope, ctx, [file]); });
7872
+ const omit = button(`Leave out ${file.name}`, ctx.idFor('picture-remove', `failed ${file.name}`), 'ai-chat-answer-add');
7873
+ omit.dataset.commandInstanceLabel = ctx.instance; omit.setAttribute('aria-label', `Leave out the file ${file.name} that was not uploaded`);
7874
+ if (ctx.busyReason || source.uploading) { const why = ctx.busyReason || 'Wait for the current upload to finish'; omit.setAttribute('aria-disabled', 'true'); omit.dataset.blockedReason = why; omit.dataset.tip = why; }
7875
+ omit.addEventListener('click', () => { if (omit.getAttribute('aria-disabled') === 'true') return; source.failedUploads = source.failedUploads.filter((held) => held !== file); if (!source.failedUploads.length) source.error = ''; ctx.repaint(); });
7876
+ wrap.append(retry, omit);
7877
+ }
7573
7878
  const hasDraft = ctx.alwaysOpen || source.open || source.note || source.files.length || source.uploading;
7574
7879
  if (!hasDraft) {
7575
7880
  const add = button('+ Add source', ctx.idFor('source'), 'ai-chat-answer-add');
@@ -7585,13 +7890,24 @@
7585
7890
  }
7586
7891
  const box = document.createElement('div'); box.className = 'ai-chat-answer-box';
7587
7892
  const line = document.createElement('div'); line.className = 'ai-chat-answer-line';
7588
- const note = document.createElement('input');
7589
- note.type = 'text'; note.className = 'ai-chat-height-input ai-chat-answer-note'; note.maxLength = 160; note.autocomplete = 'off';
7590
- note.placeholder = 'Source, e.g. per 7/S-502 (optional)';
7893
+ const note = document.createElement(ctx.clarification ? 'textarea' : 'input');
7894
+ if (ctx.clarification) { note.rows = 4; wrap.classList.add('ai-chat-answer-clarification'); }
7895
+ else { note.type = 'text'; note.maxLength = 160; }
7896
+ note.className = `ai-chat-height-input ai-chat-answer-note${ctx.clarification ? ' ai-chat-answer-clarification' : ''}`; note.autocomplete = 'off';
7897
+ note.placeholder = ctx.clarification ? 'Use the stair landing level shown in this detail; the hanger sits on it.' : 'Source, e.g. per 7/S-502 (optional)';
7591
7898
  note.dataset.commandId = ctx.idFor('note'); note.dataset.commandInstanceLabel = ctx.instance;
7592
- note.setAttribute('aria-label', `Source note for ${ctx.label}`);
7899
+ note.setAttribute('aria-label', `${ctx.clarification ? 'Explain what to use' : 'Source note'} for ${ctx.label}`);
7593
7900
  note.value = source.note;
7594
7901
  if (ctx.busyReason) { note.readOnly = true; note.setAttribute('aria-disabled', 'true'); note.dataset.blockedReason = ctx.busyReason; note.dataset.tip = ctx.busyReason; }
7902
+ let counter;
7903
+ if (ctx.clarification) {
7904
+ const heading = Object.assign(document.createElement('label'), { className: 'ai-chat-answer-lead', textContent: 'Explain what to use (optional)' });
7905
+ note.id = `clarification-${encodeURIComponent(scope)}`; heading.htmlFor = note.id; box.append(heading);
7906
+ counter = Object.assign(document.createElement('p'), { className: 'ai-chat-answer-lead' });
7907
+ note.setAttribute('aria-describedby', `${note.id}-limit`); counter.id = `${note.id}-limit`;
7908
+ const count = () => { counter.textContent = `${note.value.length.toLocaleString()} / 8,000 characters. Without a Height, this saves clarification for the read; the height stays unresolved.`; note.setAttribute('aria-invalid', String(note.value.length > MAX_HEIGHT_CLARIFICATION)); };
7909
+ note.addEventListener('input', count); count();
7910
+ }
7595
7911
  note.addEventListener('input', () => { source.note = note.value; ctx.onDraftChange?.(); });
7596
7912
  const clip = document.createElement('button');
7597
7913
  clip.type = 'button'; clip.className = 'ai-chat-answer-clip';
@@ -7613,6 +7929,7 @@
7613
7929
  }
7614
7930
  line.append(note, clip, picker);
7615
7931
  box.append(line);
7932
+ if (counter) box.append(counter);
7616
7933
  // Paste and drop, like the composer: a screenshot pasted while this box has focus attaches to the answer.
7617
7934
  box.addEventListener('paste', (event) => {
7618
7935
  if (ctx.busyReason) return;
@@ -7753,11 +8070,14 @@
7753
8070
  function drawingRowOpen(kind, entry, row) {
7754
8071
  if (!entry.view?.open || row.status === 'superseded' || row.frozen) return false;
7755
8072
  const key = drawingRowKey(kind, row);
8073
+ if (kind === 'height' && ['resolved-from-drawings', 'no-longer-needed', 'replaced'].includes(heightResponsibility(row))) return false;
7756
8074
  if (entry.changing.has(key)) return true;
7757
- return kind === 'setup' ? row.status === 'open' : !row.answer;
8075
+ if (kind === 'height' && heightResponsibility(row) === 'investigating') return false;
8076
+ return kind === 'setup' ? row.status === 'open' : !row.answer || ['needs-answer', 'proposal'].includes(heightResponsibility(row));
7758
8077
  }
7759
8078
  function drawingEntryCurrent(entry) { return entry.chatId === state.chat?.chatId; }
7760
8079
  function drawingSlotRepaint() {
8080
+ for (const entry of heightCards.values()) saveHeightDraft(entry);
7761
8081
  paintDrawingQuestionSlot();
7762
8082
  }
7763
8083
  /*
@@ -7869,9 +8189,10 @@
7869
8189
  function reopenDrawingItem(kind, entry, key) {
7870
8190
  const row = drawingRows(kind, entry).find((row) => drawingRowKey(kind, row) === key);
7871
8191
  if (entry.busy || !entry.view?.open || !row || row.frozen || row.status === 'superseded') return;
8192
+ if (kind === 'height' && ['resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row))) return;
7872
8193
  showDrawingSlot(entry.chatId);
7873
8194
  entry.changing.add(key); entry.activeItem = key; entry.finishActive = false; entry.reopenedAt = (state.drawingActivationOrder = (state.drawingActivationOrder || 0) + 1);
7874
- if (row.answer?.note && row.answer.how !== 'none') { const source = answerSource(`${kind === 'setup' ? 's' : 'h'}:${entry.questionId}:${key}`); source.open = true; source.note ||= row.answer.note; }
8195
+ if (kind === 'setup' && row.answer?.note && row.answer.how !== 'none') { const source = answerSource((kind === 'setup' ? `s:${entry.questionId}:${key}` : heightSourceScope(entry, key))); source.open = true; source.note ||= row.answer.note; }
7875
8196
  entry.slotPhase = 'row';
7876
8197
  (kind === 'setup' ? repaintSetupCard : repaintHeightCard)(entry);
7877
8198
  drawingSlotRepaint();
@@ -7888,14 +8209,24 @@
7888
8209
  const answered = live.filter((row) => row.answer);
7889
8210
  const settled = kind === 'setup' ? live.filter(setupSettled).length : live.filter((row) => row.status === 'confirmed' || row.status === 'typed').length;
7890
8211
  const allAnswered = live.length > 0 && answered.length === live.length;
8212
+ const heightStates = kind === 'height' ? live.map(heightResponsibility) : [];
8213
+ const unresolved = heightStates.filter((s) => ['needs-answer', 'proposal', 'investigating'].includes(s));
7891
8214
  card.dataset.state = !entry.view ? (entry.finished ? 'closed' : 'loading') : !entry.view.open ? 'closed'
7892
8215
  : allAnswered ? (settled === live.length ? 'answered' : 'waiting-for-read') : 'open';
8216
+ if (kind === 'height' && entry.view) card.dataset.state = !live.length ? 'replaced' : settled === live.length ? 'answered'
8217
+ : !entry.view.open && unresolved.length ? 'closed-unresolved' : !unresolved.length ? 'resolved'
8218
+ : heightStates.includes('needs-answer') ? 'needs-answer' : heightStates.includes('proposal') ? 'proposal' : 'investigating';
7893
8219
  // #2678: a hidden card's line says what still waits: the person's answers, or the read.
7894
- const waits = { open: 'you', 'waiting-for-read': 'ai', answered: 'done', closed: 'done' }[card.dataset.state];
8220
+ const waits = { open: 'you', 'waiting-for-read': 'ai', answered: 'done', closed: 'done', replaced: 'done', resolved: 'done', investigating: 'ai', 'needs-answer': 'you', proposal: 'you', 'closed-unresolved': 'ai' }[card.dataset.state];
7895
8221
  if (waits) card.dataset.waits = waits;
8222
+ if (kind === 'height' && entry.view) {
8223
+ card.dataset.waitsSays = card.dataset.state === 'closed-unresolved' ? 'Read closed with unresolved heights. Open the model or start a new read to review them.'
8224
+ : live.length === 1 ? heightStateText(live[0]) : `${settled} answered · ${heightStates.filter((s) => s === 'investigating').length} AI investigating · ${heightStates.filter((s) => s === 'needs-answer' || s === 'proposal').length} need you${!live.length ? ' · Replaced by newer questions' : ''}`;
8225
+ if (['investigating', 'resolved', 'replaced', 'closed-unresolved'].includes(card.dataset.state)) card.dataset.autoFold = 'true';
8226
+ }
7896
8227
  const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
7897
8228
  const heading = document.createElement('strong'); heading.textContent = title;
7898
- const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state'; chip.textContent = card.dataset.state;
8229
+ const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state'; chip.textContent = ({ investigating: 'AI investigating', 'needs-answer': 'Needs your answer', proposal: 'Needs your confirmation', 'closed-unresolved': 'Closed · unresolved heights' })[card.dataset.state] || card.dataset.state;
7899
8230
  head.append(heading, chip); card.append(head);
7900
8231
  if (!entry.view) {
7901
8232
  const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
@@ -7907,20 +8238,21 @@
7907
8238
  }
7908
8239
  } else {
7909
8240
  const count = document.createElement('p'); count.className = 'ai-chat-height-count'; count.setAttribute('aria-live', 'polite');
7910
- count.textContent = `${kind === 'setup' ? settled : answered.length} of ${live.length} ${kind === 'setup' ? 'settled' : 'answered'}`; card.append(count);
8241
+ count.textContent = kind === 'setup' ? `${settled} of ${live.length} settled` : `${settled} of ${live.length} heights answered${answered.length > settled ? ` · ${answered.length - settled} clarification${answered.length - settled === 1 ? '' : 's'} saved` : ''}`; card.append(count);
7911
8242
  if (kind === 'height' && entry.view.open) {
7912
8243
  const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
7913
8244
  note.textContent = rows.some((row) => row.inModel)
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.'
7915
- : 'Only you can answer these heights. What you confirm or type goes straight into the model.';
8245
+ ? 'Only you can confirm or type a height. It goes into a new member or becomes a proposal in the review for an existing member. An explanation stays unresolved; save it, then use Tell the read for a proposal.'
8246
+ : 'Only you can confirm or type a height for the model. Explanations stay unresolved; save one, then use Tell the read for a proposal.';
7916
8247
  card.append(note);
7917
8248
  // #2774: the person asked for a height on every end; any end without one says why, and the card counts them.
7918
8249
  const bare = entry.view.proposeAll ? live.filter((row) => !row.proposed && !row.answer).length : 0;
7919
8250
  if (bare) card.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-height-unproposed',
7920
8251
  textContent: `You asked for a height on every end. The read could not propose ${bare === 1 ? 'one end' : `${bare} ends`}; each says why.` }));
7921
8252
  }
7922
- if (entry.view.open && allAnswered) {
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);
8253
+ const clarificationReady = kind === 'height' && heightClarificationPending(entry);
8254
+ if (entry.view.open && (clarificationReady || allAnswered && !(kind === 'height' && live.some((row) => heightResponsibility(row) !== 'answered')))) {
8255
+ const next = heightActionButton(clarificationReady ? 'Tell / send clarification to the read' : 'Tell / send to the read', `shell.chat-${kind}-next-step#${entry.questionId}`, clarificationReady ? 'saved clarification; height unresolved' : `${kind === 'setup' ? 'setup' : 'height'} question ${entry.view.n}`, 'ai-chat-height-change', entry.busy ? 'An answer is still being saved — wait for it to finish' : null);
7924
8256
  next.dataset.tip = 'Choose whether to put the message in the box or send it now';
7925
8257
  next.addEventListener('click', () => {
7926
8258
  if (entry.busy) return;
@@ -7949,30 +8281,81 @@
7949
8281
  } else {
7950
8282
  item = document.createElement('li'); item.className = 'ai-chat-height-row'; item.dataset.status = row.status; item.dataset.key = key;
7951
8283
  const label = document.createElement('span'); label.textContent = row.label || (row.kind === 'origin' ? 'Model origin' : viewName(row)); item.append(label);
8284
+ if (kind === 'height') {
8285
+ const status = document.createElement('p'); status.className = 'ai-chat-filter-note'; status.textContent = heightStateText(row); item.append(status);
8286
+ if (heightStudyText(row)) {
8287
+ const details = document.createElement('p'); details.className = 'ai-chat-filter-note';
8288
+ details.textContent = heightStudyText(row); item.append(details);
8289
+ }
8290
+ }
7952
8291
  const firstPlace = kind === 'setup' && row.kind === 'level' ? setupPlaceItems(row)[0] : null;
7953
8292
  const chip = kind === 'height' ? heightPlaceChip(entry, row) : firstPlace ? setupPlaceChip(entry, row, firstPlace) : null;
7954
8293
  if (chip) item.append(chip);
7955
- if (entry.view.open) {
7956
- const answer = heightActionButton('Answer', `shell.chat-${kind}-change#${entry.questionId} ${key}`, label.textContent, 'ai-chat-height-change', null);
8294
+ if (entry.view.open && !(kind === 'height' && ['resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row)))) {
8295
+ const answer = heightActionButton(kind === 'height' && heightResponsibility(row) === 'investigating' ? 'Answer yourself' : 'Answer', `shell.chat-${kind}-change#${entry.questionId} ${key}`, label.textContent, 'ai-chat-height-change', null);
7957
8296
  answer.addEventListener('click', () => reopenDrawingItem(kind, entry, key)); item.append(answer);
7958
8297
  }
7959
8298
  }
8299
+ if (kind === 'height' && ['replaced', 'resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row))) {
8300
+ const draft = entry.slotDrafts?.get(key), source = answerSources.get(heightSourceScope(entry, key));
8301
+ const text = draft?.rows?.map((r) => r.other || r.reason || '').filter(Boolean).join(' ');
8302
+ if (text || source?.note) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Unsent draft kept here: ${[text, source?.note].filter(Boolean).join(' · ')}. Nothing from this draft was submitted or transferred to another question.` }));
8303
+ for (const file of source?.files || []) item.append(retainedHeightPicture(entry, file, `shell.chat-answer-picture-open#${entry.questionId} ${key} ${file.attachmentId}`, `unsent picture for ${row.label}`));
8304
+ const batch = entry.slotDrafts?.get('batch-value'), shared = answerSources.get(heightSourceScope(entry));
8305
+ const batchEnds = batch?.scopeEnds || [], sharedEnds = shared?.scopeEnds || batchEnds;
8306
+ entry.retiredDrafts ??= new Map();
8307
+ if (!entry.retiredDrafts.has(key)) entry.retiredDrafts.set(key, {
8308
+ text: batchEnds.includes(key) ? batch.rows?.map((r) => r.other || r.reason || '').filter(Boolean).join(' ') || '' : '',
8309
+ note: sharedEnds.includes(key) ? shared?.note || '' : '',
8310
+ files: sharedEnds.includes(key) ? (shared?.files || []).map(({ url, ...file }) => ({ ...file })) : [],
8311
+ scopeEnds: [...new Set([...batchEnds, ...sharedEnds])],
8312
+ });
8313
+ // A later save for the still-open siblings clears their live batch, never this retired end's original recovery.
8314
+ const recovery = entry.retiredDrafts.get(key), sharedText = recovery.text, sharedNote = recovery.note;
8315
+ const scope = recovery.scopeEnds.map((end) => rows.find((r) => heightEndKey(r) === end)?.label || end).join('; ');
8316
+ if (sharedText || sharedNote) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Shared unsent draft kept for its original ends (${scope}): ${[sharedText, sharedNote].filter(Boolean).join(' · ')}. It has not been applied to this end or moved to another question.` }));
8317
+ for (const file of recovery.files) item.append(retainedHeightPicture(entry, file, `shell.chat-answer-picture-open#${entry.questionId} bulk ${file.attachmentId}`, `shared unsent picture for ${scope}`));
8318
+ }
8319
+ if (kind === 'height' && row.place && !row.placeDigest && row.unplaced) item.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: row.unplaced }));
7960
8320
  list.append(item);
7961
8321
  }
7962
8322
  card.append(list);
7963
8323
  }
7964
- const unused = kind === 'height' ? drawingRows(kind, entry).filter((row) => answerSources.get(`h:${entry.questionId}:${heightEndKey(row)}`)?.files.some((file) => file.cleanupPending)) : [];
8324
+ const unused = kind === 'height' ? drawingRows(kind, entry).filter((row) => answerSources.get(heightSourceScope(entry, heightEndKey(row)))?.files.some((file) => file.cleanupPending)) : [];
7965
8325
  const cleanup = unused.length ? `Your heights were saved. Some unused pictures could not be removed. Choose Change for each listed end, then Remove on its unused pictures: ${unused.map((row) => `${row.label} · ${row.memberId} · ${heightEndWord(row)}`).join('; ')}. You do not need to submit the heights again.` : '';
7966
8326
  const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert'); error.textContent = [entry.cardError, cleanup].filter(Boolean).join(' '); card.append(error);
8327
+ if (kind === 'height' && entry.draftStorageError) card.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: entry.draftStorageError }));
8328
+ if (kind === 'height' && entry.cardError && card.dataset.state === 'investigating') error.textContent = `Previous answer was not saved; draft retained. ${entry.cardError}`;
8329
+ if (kind === 'height') {
8330
+ const kept = [...(entry.slotDrafts || [])].filter(([key, draft]) => !rows.some((row) => ['replaced', 'resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row)) && heightEndKey(row) === key) && draft.rows?.some((row) => row.other?.trim() || row.reason?.trim()));
8331
+ if (kept.length && ['replaced', 'resolved', 'closed-unresolved'].includes(card.dataset.state)) {
8332
+ const draft = document.createElement('p'); draft.className = 'ai-chat-filter-note'; draft.textContent = `Unsent draft kept on this original question: ${kept.map(([, item]) => item.rows.map((r) => r.other || r.reason || '').join(' ')).join('; ')}. It was not transferred to the newer question.`; card.append(draft);
8333
+ }
8334
+ if (['replaced', 'resolved', 'closed-unresolved'].includes(card.dataset.state)) for (const [scope, source] of answerSources) {
8335
+ if (!heightSourceBelongs(entry, scope)) continue;
8336
+ if (rows.some((row) => ['replaced', 'resolved-from-drawings', 'no-longer-needed'].includes(heightResponsibility(row)) && scope === heightSourceScope(entry, heightEndKey(row)))) continue;
8337
+ if (source.note) card.append(Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Unsent source note kept on this question: ${source.note}` }));
8338
+ for (const file of source.files) {
8339
+ card.append(retainedHeightPicture(entry, file, `shell.chat-answer-picture-open#${entry.questionId} draft ${file.attachmentId}`, `unsent picture on height question ${entry.view.n}`));
8340
+ }
8341
+ }
8342
+ }
7967
8343
  drawingSlotRepaint();
7968
8344
  return card;
7969
8345
  }
7970
8346
  function drawingSource(kind, entry, scope, label, idFor, row, onDraftChange) {
7971
8347
  return paintAnswerSource(scope, { requestId: entry.requestId, chatId: entry.chatId, repaint: () => { (kind === 'setup' ? repaintSetupCard : repaintHeightCard)(entry); drawingSlotRepaint(); },
7972
8348
  removeFile: (file) => request(`/api/chat/answer-evidence/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(file.attachmentId)}`, { method: 'DELETE', body: JSON.stringify({ chatId: entry.chatId }) }),
7973
- label, instance: label, idFor, inherited: row?.inherited, busyReason: entry.busy ? 'An answer is still being saved — wait for it to finish' : null,
8349
+ label, instance: label, idFor, inherited: row?.inherited, inheritedNote: (kind === 'height' ? row?.answer?.note : null) || row?.inheritedNote, clarification: kind === 'height', busyReason: entry.busy ? 'An answer is still being saved — wait for it to finish' : null,
7974
8350
  allowPictureOnly: false, onDraftChange, alwaysOpen: Boolean(entry.slotDrafts?.get(entry.slotQuestionKey)?.rows[0]?.otherOpen) });
7975
8351
  }
8352
+ function retainedHeightPicture(entry, file, commandId, instance) {
8353
+ const url = heightDraftEvidenceUrl(entry, file.attachmentId);
8354
+ return entry.view?.readRemoved || !url ? Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note', textContent: `Retained unsent picture: ${file.fileName}. This read is closed or its original project is unavailable here, so the picture cannot be opened here. Your draft reference is kept; attach the original file to a new question if needed.` }) : answerPictureChip(entry.requestId, file, commandId, instance, url);
8355
+ }
8356
+ function heightDraftEvidenceUrl(entry, attachmentId) {
8357
+ return entry.projectId ? `/api/chat/conversations/${encodeURIComponent(entry.chatId)}/attachments/${encodeURIComponent(attachmentId)}?${new URLSearchParams({ ownerKind: 'project', ownerId: entry.projectId })}` : '';
8358
+ }
7976
8359
  /**
7977
8360
  * The card's last step ("Tell the read what to look at next") has nothing left to do once a message saying so went to
7978
8361
  * the read after the card's last answer (owner, 2026-10-23: the card stayed while the AI was already working on it).
@@ -7991,11 +8374,38 @@
7991
8374
  && String(event.payload?.text || '').includes(told));
7992
8375
  }
7993
8376
 
8377
+ function heightClarificationPending(entry) {
8378
+ if (!entry.view?.open) return false;
8379
+ const rows = drawingRows('height', entry).filter((row) => row.status !== 'superseded'
8380
+ && ['investigating', 'needs-answer', 'proposal'].includes(heightResponsibility(row))
8381
+ && row.answer?.how === 'evidence' && (row.answer.note?.trim() || row.answer.evidence?.length));
8382
+ if (!rows.length) return false;
8383
+ const lastEvidence = Math.max(0, ...rows.map((row) => Date.parse(row.answer.answeredAt || '') || 0));
8384
+ const text = heightClarificationText(entry);
8385
+ return !state.events.some((event) => event.type === 'user-message' && !event.optimistic && event.eventId
8386
+ && event.chatId === entry.chatId && !event.payload?.source
8387
+ && (Date.parse(event.createdAt || '') || 0) > lastEvidence
8388
+ && (!(event.payload?.followup || event.payload?.deliveryState) || ['accepted', 'queued-next'].includes(followupDelivery(event)))
8389
+ && String(event.payload?.text || '').includes(text));
8390
+ }
8391
+ function drawingClarificationStep(entry) {
8392
+ return { key: 'clarification', label: 'saved clarification; height unresolved', question: { id: 'clarification', header: 'Heights',
8393
+ question: 'Clarification saved — height unresolved', allowOther: false,
8394
+ context: ['Your explanation and attachments are saved. Send a message to ask the read to work out a proposal. The height remains unresolved.'],
8395
+ hint: 'Tell the read puts a message in the box. Send to the read sends it now.',
8396
+ options: [{ shown: 'Tell the read', description: 'Put the clarification notice in the box so you can add to it' }, { shown: 'Send to the read', description: 'Send the notice now, keeping your words and files' }] },
8397
+ commit: async (answer) => { const text = heightClarificationText(entry);
8398
+ if (answer.choices[0] === 0) tellReadAnswered(entry, text, repaintHeightCard); else await sendToReadAnswered(entry, text, repaintHeightCard); return false; } };
8399
+ }
8400
+
7994
8401
  function drawingStep(kind, entry) {
7995
8402
  const open = drawingRows(kind, entry).filter((row) => drawingRowOpen(kind, entry, row));
7996
8403
  const row = open.find((row) => drawingRowKey(kind, row) === entry.activeItem) || open[0];
8404
+ const clarificationReady = kind === 'height' && heightClarificationPending(entry);
8405
+ if (clarificationReady && (entry.finishActive || !row)) return drawingClarificationStep(entry);
7997
8406
  if (!row) {
7998
8407
  const live = drawingRows(kind, entry).filter((row) => row.status !== 'superseded');
8408
+ if (kind === 'height' && live.some((item) => heightResponsibility(item) !== 'answered')) return null;
7999
8409
  if (!entry.view?.open || !live.length || !live.every((row) => row.answer)) return null;
8000
8410
  if (drawingFinishTold(kind, entry, live)) return null;
8001
8411
  return { key: 'finish', question: { id: 'finish', header: kind === 'setup' ? 'Read setup' : 'Heights', question: 'Your answers are recorded. Tell the read what to look at next.', allowOther: false,
@@ -8005,19 +8415,22 @@
8005
8415
  if (answer.choices[0] === 0) tellReadAnswered(entry, text, repaint); else await sendToReadAnswered(entry, text, repaint); return false; } };
8006
8416
  }
8007
8417
  if (kind === 'height' && open.length > 1 && entry.slotPhase !== 'row') return drawingHeightBatch(entry, open);
8008
- const key = drawingRowKey(kind, row), scope = `${kind === 'setup' ? 's' : 'h'}:${entry.questionId}:${key}`;
8418
+ const key = drawingRowKey(kind, row), scope = (kind === 'setup' ? `s:${entry.questionId}:${key}` : heightSourceScope(entry, key));
8009
8419
  const label = row.label || (row.kind === 'origin' ? 'the model origin' : viewName(row));
8010
8420
  const q = { id: key, header: kind === 'setup' ? 'Read setup' : 'Height', question: label, options: [], recommended: null, context: [] };
8011
8421
  const live = drawingRows(kind, entry).filter((item) => item.status !== 'superseded');
8012
8422
  q.progress = { index: live.indexOf(row), total: live.length };
8013
8423
  const choices = [];
8014
8424
  if (kind === 'height') {
8425
+ q.otherInputLabel = 'Height (optional)';
8426
+ q.otherPlaceholder = entry.view.units === 'mm' ? '4870 mm, or 4.87 for metres' : `15'-11 3/4"; a bare number is inches`;
8015
8427
  if (row.inModel) {
8016
8428
  q.context.push(
8017
8429
  `${row.inModel.profile || ''} · ${row.memberId} · ${heightEndWord(row)}. ${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}`
8018
8430
  );
8019
8431
  }
8020
- else q.context.push(`${row.memberId} · ${heightEndWord(row)}. Only you can answer. What you confirm or type goes straight into the model.`);
8432
+ else q.context.push(`${row.memberId} · ${heightEndWord(row)}. Only you can confirm or enter a numeric height. An explanation or attachment leaves the height unresolved until you confirm a proposal.`);
8433
+ q.context.push(heightStateText(row));
8021
8434
  if (row.proposed) { q.options.push({ shown: `Confirm ${row.proposed.asRead}`, ...heightProposalWords(row.proposed) }); choices.push({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value }); q.recommended = 0; }
8022
8435
  else q.context.push(heightNoProposalText(row));
8023
8436
  q.figure = () => heightPlaceFigure(entry, row);
@@ -8037,6 +8450,7 @@
8037
8450
  row.proposals.forEach((proposal) => { q.options.push({ shown: row.kind === 'scale' ? `${proposal.pageFit ? 'Use for this plan' : 'Confirm'}: ${proposal.standard} · ${proposal.mmPerPx} mm per drawing point` : `Confirm ${proposal.asRead}`,
8038
8451
  description: row.kind === 'scale' ? proposal.evidence : levelEvidence(proposal), tag: (row.kind === 'scale' ? scaleTag : levelTag)[proposal.source] || 'PROPOSED' }); choices.push({ key, action: 'confirm', choice: proposal.id, shown: row.kind === 'scale' ? proposal.mmPerPx : proposal.value }); });
8039
8452
  }
8453
+ if (kind === 'setup' && (row.kind === 'origin' || row.kind === 'scale')) q.context.push('This setup question has no saved drawing location. Inspect the drawing set in Drawing Filter, or ask the read to point out the context.');
8040
8454
  if (kind === 'setup' && row.kind !== 'scale') { q.options.push({ shown: row.kind === 'origin' ? 'None of these' : 'No single level', description: 'Tell the read what to use instead', requiresNote: { placeholder: 'Add a short reason', max: MAX_ANSWER_NOTE } }); choices.push({ key, action: 'none' }); }
8041
8455
  if (kind === 'setup') { const banner = setupConflictBanner(row); if (banner) q.context.push(banner.textContent); }
8042
8456
  const controlKey = kind === 'height' ? `${row.memberId} ${row.endWord}` : key;
@@ -8064,7 +8478,7 @@
8064
8478
  const base = { header: 'Heights', allowOther: false, id: 'batch', recommended: null };
8065
8479
  if (!entry.slotPhase) {
8066
8480
  const confirmable = rows.every((row) => !row.answer && row.proposed);
8067
- const scope = `hb:${entry.questionId}`, label = `all ${rows.length} proposed member ends`;
8481
+ const scope = heightSourceScope(entry), label = `all ${rows.length} proposed member ends`;
8068
8482
  const idFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra === undefined ? '' : ` ${extra}`}`;
8069
8483
  const inherited = [...new Map(rows.flatMap((row) => row.inherited || []).map((ref) => [ref.attachmentId, ref])).values()];
8070
8484
  const options = [];
@@ -8074,7 +8488,8 @@
8074
8488
  source: confirmable ? (_index, onDraftChange) => drawingSource('height', entry, scope, label, idFor, { inherited }, onDraftChange) : null,
8075
8489
  question: { ...base, question: 'How would you like to answer these heights?', options, recommended: confirmable ? 0 : null,
8076
8490
  hint: confirmable ? 'Confirm all saves these values. The other choices only choose how to answer.' : 'Choose how to answer; no heights are saved yet.',
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) => {
8491
+ figure: () => heightBatchPlaces(entry, rows, 'batch-intro', rows.map((row) => `${row.label} · ${row.inModel?.profile ? `${row.inModel.profile} · ` : ''}${heightEndWord(row)}.${heightPlaced(row) ? ` On ${row.place.sheet}.` : ''}${row.proposed ? ` Proposed: ${row.proposed.asRead} (${row.proposed.value} mm)${row.proposed.how === 'derived' ? `, derived, an assumption: ${row.proposed.basis}` : ''}.` : ` ${heightNoProposalText(row).replace(/[^.!?]$/, '$&.')}`} ${row.inModel ? `${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}` : 'What you confirm or type goes straight into the model.'}${row.fromEvidence ? ` The read’s reading of your ${row.inherited?.length ? 'picture' : 'note'}. Check it before you confirm.` : ''}`)),
8492
+ context: [...(confirmable ? [`Optional source for all ${rows.length} heights. Each end keeps its own proposed value.`] : [])] }, commit: async (answer) => {
8078
8493
  if (confirmable && answer.choices[0] === 0) return submitHeightAnswers(entry, rows.map((row) => ({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value })), null, hasAnswerSource(scope) ? scope : null);
8079
8494
  entry.slotPhase = answer.choices[0] === options.length - 1 ? 'row' : 'select'; engageDrawingEntry(entry); return true;
8080
8495
  } };
@@ -8083,7 +8498,7 @@
8083
8498
  const groups = new Map();
8084
8499
  for (const row of rows) { const members = groups.get(row.group) || []; members.push(row); groups.set(row.group, members); }
8085
8500
  const ordered = [...groups.values()].flat();
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)}` })) },
8501
+ return { key: 'batch-select', rows: ordered, question: { ...base, figure: () => heightBatchPlaces(entry, ordered, 'batch-select'), allowClear: true, hint: 'Select ends, then Submit. No heights are saved yet.', question: 'Which member ends should share one answer?', multiSelect: true, options: ordered.map((row) => ({ shown: row.label, group: row.group, description: [row.inModel?.profile, heightEndWord(row)].filter(Boolean).join(' · ') })) },
8087
8502
  initial: ordered.map((row, index) => entry.selected.size ? entry.selected.has(heightEndKey(row)) ? index : -1 : index).filter((index) => index >= 0),
8088
8503
  back: () => { entry.slotPhase = null; entry.slotSig = null; drawingSlotRepaint(); },
8089
8504
  commit: async (answer) => { entry.selected = new Set(answer.choices.map((index) => heightEndKey(ordered[index]))); entry.slotPhase = 'value'; engageDrawingEntry(entry); return true; } };
@@ -8091,12 +8506,12 @@
8091
8506
  const chosen = rows.filter((row) => entry.selected.has(heightEndKey(row)));
8092
8507
  if (!chosen.length) { entry.slotPhase = 'select'; return drawingHeightBatch(entry, rows); }
8093
8508
  const shared = chosen.every((row) => row.proposed && row.proposed.value === chosen[0].proposed?.value);
8094
- const scope = `hb:${entry.questionId}`, label = `${chosen.length} selected member ends`, idFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra === undefined ? '' : ` ${extra}`}`;
8509
+ const scope = heightSourceScope(entry), label = `${chosen.length} selected member ends`, idFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra === undefined ? '' : ` ${extra}`}`;
8095
8510
  const inherited = [...new Map(chosen.flatMap((row) => row.inherited || []).map((ref) => [ref.attachmentId, ref])).values()];
8096
8511
  const context = chosen.filter((row) => row.inModel).map((row) => `${row.label}: ${row.inModel.profile || ''}. ${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}`);
8097
8512
  if (chosen.some((row) => row.fromEvidence)) context.push(inherited.length ? 'The read’s reading of your picture. Check it before you confirm.' : 'The read’s reading of your note. Check it before you confirm.');
8098
8513
  return { key: 'batch-value', scope, label, back: () => { entry.slotPhase = 'select'; entry.slotSig = null; drawingSlotRepaint(); },
8099
- question: { ...base, allowOther: true, context, question: `What height should the ${chosen.length} selected ends use?`,
8514
+ question: { ...base, figure: () => heightBatchPlaces(entry, chosen, 'batch-value'), allowOther: true, otherInputLabel: 'Height (optional)', otherPlaceholder: entry.view.units === 'mm' ? '4870 mm, or 4.87 for metres' : `15'-11 3/4"; a bare number is inches`, context, question: `What height should the ${chosen.length} selected ends use?`,
8100
8515
  options: shared ? [{ shown: `Confirm ${chosen[0].proposed.asRead} for ${chosen.length}`, description: 'Every selected end has this same proposed value' }] : [], recommended: shared ? 0 : null },
8101
8516
  source: (_index, onDraftChange) => drawingSource('height', entry, scope, label, idFor, { inherited }, onDraftChange), validate: (_step, draft) => draft.rows[0].choices.length || draft.rows[0].other.trim() || hasAnswerSource(scope) ? '' : NO_HEIGHT_NO_SOURCE,
8102
8517
  commit: async (answer) => { const answers = chosen.map((row) => ({ memberId: row.memberId, end: row.end, ...(answer.choices.length ? { action: 'confirm', shown: row.proposed.value } : answer.other ? { action: 'type', typed: answer.other } : { action: 'evidence' }) }));
@@ -8129,14 +8544,25 @@
8129
8544
  const units = drawingUnitsCandidate(); if (units) (drawingCardHidden(units.entry) ? hidden : candidates).push(units);
8130
8545
  // A card's "Tell the read" step wins only while that card is the one the person acted in last (#2793): candidates
8131
8546
  // 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];
8547
+ let chosen = candidates.find(({ entry, step }, index) => entry.finishActive && ['finish', 'clarification'].includes(step.key) && index === 0) || candidates.find(({ step }) => !['finish', 'clarification'].includes(step.key)) || candidates[0];
8133
8548
  if (heldFocus && personIsTyping()) {
8134
8549
  const current = candidates.find(({ entry, step }) => `${entry.chatId}/${entry.key}/${step.key}` === showing.dataset.drawingStep);
8135
8550
  const activated = chosen?.entry.finishActive || (chosen?.entry.reopenedAt || 0) > (current?.entry.reopenedAt || 0);
8136
8551
  if (current && !activated) chosen = current;
8137
8552
  }
8138
8553
  if (!chosen && hidden.length) return paintDrawingHiddenLine(tray, showing, hidden);
8139
- if (!chosen) { showing?.remove(); return false; }
8554
+ if (!chosen) {
8555
+ const parked = entries.flatMap(({ kind, entry }) => kind === 'height' ? drawingRows(kind, entry).filter((row) => heightResponsibility(row) === 'investigating' && !entry.changing.has(heightEndKey(row))).map((row) => ({ entry, row })) : []);
8556
+ if (parked.length) {
8557
+ const { entry, row } = parked[0];
8558
+ if (showing && showing !== drawingHiddenLine) showing.remove();
8559
+ drawingHiddenLine = paintHiddenLine(drawingHiddenLine, tray, { className: 'ai-chat-drawing-step', label: 'Heights',
8560
+ sentence: `AI investigating · ${row.label} · ${row.lifecycle?.reason || 'The read is looking for this height.'}${parked.length > 1 ? ` · ${parked.length} ends` : ''}${entry.saveFailed ? ' Previous answer was not saved; draft retained.' : ''} · Answer yourself`,
8561
+ commandId: `shell.chat-height-change#${entry.questionId} ${heightEndKey(row)}`, instance: row.label, show: () => reopenDrawingItem('height', entry, heightEndKey(row)) });
8562
+ drawingHiddenLine.dataset.drawingStep = `investigating/${entry.key}`; return true;
8563
+ }
8564
+ showing?.remove(); return false;
8565
+ }
8140
8566
  const { kind, entry, step } = chosen, key = `${entry.chatId}/${entry.key}/${step.key}`;
8141
8567
  if (showing && showing.dataset.drawingStep !== key) showing.remove();
8142
8568
  entry.slotDrafts ??= new Map();
@@ -8147,6 +8573,7 @@
8147
8573
  if (step.row?.answer?.how === 'typed' && entry.changing.has(step.key)) { draft.rows[0].otherOpen = true; draft.rows[0].other = step.row.answer.typed; }
8148
8574
  entry.slotDrafts.set(step.key, draft);
8149
8575
  }
8576
+ if (kind === 'height' && step.key === 'batch-value' && !draft.scopeEnds) draft.scopeEnds = [...entry.selected];
8150
8577
  const choiceSignature = JSON.stringify(step.question.options);
8151
8578
  if (draft.choiceSignature && draft.choiceSignature !== choiceSignature) draft.rows[0].choices = [];
8152
8579
  draft.choiceSignature = choiceSignature;
@@ -8154,18 +8581,20 @@
8154
8581
  entry.slotQuestionKey = step.key;
8155
8582
  const sig = JSON.stringify([key, entry.view, entry.busy, entry.cardError, [...entry.rowErrors], [...entry.changing], [...entry.selected || []], entry.slotPhase,
8156
8583
  // Typing refreshes Submit availability/carrier in place; note text must not invalidate the live field on a poll.
8157
- source && [source.open, source.files.map((file) => file.attachmentId), source.uploading, source.error], draft.pending, draft.rows[0].choices, draft.rows[0].otherOpen]);
8584
+ source && [source.open, source.files.map((file) => file.attachmentId), (source.failedUploads || []).map(heightDraftFileId), source.uploading, source.error], draft.pending, draft.rows[0].choices, draft.rows[0].otherOpen]);
8158
8585
  const node = entry.slotNode || document.createElement('section'); entry.slotNode = node;
8159
8586
  if (node.isConnected && entry.slotSig === sig) return true;
8160
- const editingSelections = [...node.querySelectorAll('input[data-command-id]')].map((field) => ({ id: field.dataset.commandId, caret: textCaret(field) })).filter(({ caret }) => caret);
8587
+ const editingSelections = [...node.querySelectorAll('input[data-command-id], textarea[data-command-id]')].map((field) => ({ id: field.dataset.commandId, caret: textCaret(field) })).filter(({ caret }) => caret);
8161
8588
  const focused = node.contains(document.activeElement) ? document.activeElement : heldFocus;
8162
8589
  const focusId = focused?.dataset.commandId, caret = focused ? textCaret(focused) : null;
8163
8590
  const freshStep = node.dataset.drawingStep !== key;
8164
8591
  const sameStepScroll = freshStep ? null : tray.scrollTop;
8165
8592
  if (freshStep) { delete node.dataset.armedAt; node.lastDrawingField = null; }
8166
8593
  if (!node.drawingFieldFocus) {
8167
- node.drawingFieldFocus = (event) => { if (event.target.tagName === 'INPUT' && (event.target.type === 'text' || !event.target.type)) node.lastDrawingField = event.target.dataset.commandId; };
8594
+ node.drawingFieldFocus = (event) => { if ((event.target.tagName === 'TEXTAREA' || event.target.tagName === 'INPUT' && (event.target.type === 'text' || !event.target.type))) node.lastDrawingField = event.target.dataset.commandId; };
8168
8595
  node.addEventListener('focusin', node.drawingFieldFocus);
8596
+ node.addEventListener('input', () => { if (kind === 'height') saveHeightDraft(entry); });
8597
+ node.addEventListener('change', () => { if (kind === 'height') saveHeightDraft(entry); });
8169
8598
  }
8170
8599
  node.className = 'ai-chat-approval ai-chat-ask-card ai-chat-drawing-step'; node.dataset.drawingStep = key;
8171
8600
  if (!node.isConnected) tray.append(node);
@@ -8184,7 +8613,7 @@
8184
8613
  // Rebuilding the same question temporarily shrinks the tray and clamps its scroll position.
8185
8614
  if (sameStepScroll !== null) tray.scrollTop = sameStepScroll;
8186
8615
  for (const { id, caret } of editingSelections) {
8187
- const field = [...node.querySelectorAll('input[data-command-id]')].find((control) => control.dataset.commandId === id);
8616
+ const field = [...node.querySelectorAll('input[data-command-id], textarea[data-command-id]')].find((control) => control.dataset.commandId === id);
8188
8617
  field?.setSelectionRange?.(Math.min(caret.start, field.value.length), Math.min(caret.end, field.value.length), caret.direction);
8189
8618
  }
8190
8619
  if (focusId) {
@@ -8198,7 +8627,7 @@
8198
8627
  const rowKey = step.row && kind === 'height' ? `${step.row.memberId} ${step.row.endWord}` : step.key;
8199
8628
  let name = what, suffix = rowKey, instance = step.label || step.question.header;
8200
8629
  if (kind === 'units') return { id: `shell.chat-units-choose#${extra === 0 ? 'ft-in' : 'mm'}`, instance: extra === 0 ? 'feet and inches' : 'metric (mm)' };
8201
- if (step.key === 'finish') name = extra === 0 ? 'tell-read' : 'send-read';
8630
+ if (step.key === 'finish' || step.key === 'clarification') name = extra === 0 ? 'tell-read' : 'send-read';
8202
8631
  else if (what === 'option') {
8203
8632
  if (step.key === 'batch-intro') { name = extra === 0 && step.question.recommended === 0 ? 'confirm-all' : 'mode'; if (name === 'mode') suffix += ` ${extra}`; }
8204
8633
  else if (step.key === 'batch-select') { name = 'select'; const row = step.rows[extra]; suffix = `${row.memberId} ${row.endWord}`; instance = row.label; }
@@ -8306,8 +8735,9 @@
8306
8735
  const items = chosen ? [...all.filter((item) => item.proposal === chosen), ...all.filter((item) => item.proposal !== chosen)] : all;
8307
8736
  const unplaced = setupUnplaced(row);
8308
8737
  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(' ')}` });
8738
+ return Object.assign(document.createElement('p'), { className: 'ai-chat-filter-note ai-chat-ask-context ai-chat-height-unplaced', textContent: unplaced.length
8739
+ ? `Not placed on the drawings: ${unplaced.join(' ')}`
8740
+ : 'The read supplied no drawing location for this level. Ask it to locate the level, or inspect the drawing set in Drawing Filter.' });
8311
8741
  }
8312
8742
  const wrap = document.createElement('div'); wrap.className = 'ai-chat-setup-places';
8313
8743
  const first = items[0];
@@ -8513,7 +8943,7 @@
8513
8943
  const ownedSlot = drawingEntryCurrent(entry) && ui.approvalTray?.querySelector('.ai-chat-drawing-step')?.dataset.drawingStep;
8514
8944
  const ownedNode = ownedSlot ? ui.approvalTray.querySelector('.ai-chat-drawing-step') : null;
8515
8945
  const pendingFocusId = ownedNode?.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
8516
- const failedField = ownedNode && ([...ownedNode.querySelectorAll('input')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
8946
+ const failedField = ownedNode && ([...ownedNode.querySelectorAll('input, textarea')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
8517
8947
  const failedFieldId = failedField?.dataset.commandId, failedCaret = failedField ? textCaret(failedField) : null;
8518
8948
  let saved = false;
8519
8949
  const withSource = answers.map((answer) => withAnswerSource(answer, answerSourcePayload(`s:${entry.questionId}:${answer.key}`)));
@@ -8532,7 +8962,7 @@
8532
8962
  method: 'POST', body: JSON.stringify({ chatId: entry.chatId, answers: withSource }),
8533
8963
  });
8534
8964
  entry.view = result.question;
8535
- saved = true; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
8965
+ saved = true; entry.failedSubmission = null; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
8536
8966
  for (const answer of answers) {
8537
8967
  entry.changing.delete(answer.key); entry.drafts.delete(answer.key); entry.drafts.delete(`${answer.key}\u0000none`);
8538
8968
  if (entry.activeItem === answer.key) { entry.activeItem = null; entry.reopenedAt = 0; }
@@ -8964,6 +9394,31 @@
8964
9394
  // writing again ends it, and so does a declined approval (it never will run). Codex ends each tool by its own item
8965
9395
  // id (#2102), so one finishing does not end another running beside it.
8966
9396
  const TOOL_ENDED = new Set(['completed', 'failed', 'denied', 'declined', 'error']);
9397
+ // #2848: describe only work whose lifetime the provider actually reports. Claude's starts have no
9398
+ // matching ends, so its label stays generic (its existing avatar heuristic is separate). Never lift
9399
+ // commands, inputs, reasoning or earlier assistant narration into a claim about current work.
9400
+ function liveActivityText() {
9401
+ if (!turnIsVisiblyActive()) return '';
9402
+ if (state.source && state.source.readyState !== 1) return 'Reconnecting to this conversation…';
9403
+ if (state.chat?.state === 'awaiting-approval' || state.chat?.pendingApproval) {
9404
+ return state.chat?.pendingApproval?.kind === 'question' ? 'Waiting for your answer…' : 'Waiting for your approval…';
9405
+ }
9406
+ if (state.chat?.provider !== 'codex') return 'Processing your request…';
9407
+ const running = new Map();
9408
+ for (const event of state.events || []) {
9409
+ if (event.turnId !== state.chat?.activeTurn?.turnId || event.type !== 'tool' || event.payload?.plain === true) continue;
9410
+ const key = event.providerItemId;
9411
+ // An unmatched/historical receipt is not evidence that a tool is running now.
9412
+ if (!key) continue;
9413
+ if (TOOL_ENDED.has(event.payload?.status)) running.delete(key);
9414
+ else if (event.payload?.status === 'inProgress') running.set(key, event.payload);
9415
+ }
9416
+ const tool = [...running.values()].at(-1);
9417
+ if (tool?.tool === 'webSearch') return 'Searching the web…';
9418
+ if (tool?.tool === 'file-change') return 'Updating files…';
9419
+ return 'Processing your request…';
9420
+ }
9421
+
8967
9422
  function liveFloMood() {
8968
9423
  if (state.chat?.state === 'awaiting-approval' || state.chat?.pendingApproval) return 'idle';
8969
9424
  const turnId = state.chat?.activeTurn?.turnId;
@@ -8984,18 +9439,21 @@
8984
9439
  }
8985
9440
 
8986
9441
  // The feed is rebuilt on every event, so the live row is one kept node: Flo carries on instead of restarting
8987
- // on every streamed word. The row is decoration; announceLiveResponseOnce speaks for it.
9442
+ // on every streamed word. Only the avatar is decoration; the full label remains readable even
9443
+ // when CSS truncates it. The separate live region announces coalesced changes.
8988
9444
  function renderLiveStatus() {
8989
9445
  if (!state.liveFlo) {
8990
9446
  const item = document.createElement('div'); item.className = 'ai-chat-live-status';
8991
- item.setAttribute('aria-hidden', 'true');
8992
9447
  const label = document.createElement('span'); label.className = 'ai-chat-live-label';
9448
+ const flo = typeof floAvatar === 'function' ? floAvatar(item, { size: 22, mood: 'thinking', hatRoom: true }) : null;
8993
9449
  item.append(label);
8994
- state.liveFlo = { item, flo: typeof floAvatar === 'function' ? floAvatar(item, { size: 22, mood: 'thinking', hatRoom: true }) : null };
9450
+ state.liveFlo = { item, label, flo };
8995
9451
  }
8996
9452
  const mood = liveFloMood();
8997
9453
  state.liveFlo.item.dataset.mood = mood;
8998
9454
  state.liveFlo.flo?.setMood(mood, mood === 'working');
9455
+ const text = liveActivityText();
9456
+ if (state.liveFlo.label.textContent !== text) state.liveFlo.label.textContent = text;
8999
9457
  return state.liveFlo.item;
9000
9458
  }
9001
9459
 
@@ -9004,6 +9462,10 @@
9004
9462
  const wasResponding = state.liveStatusTurnId !== null;
9005
9463
  if (!turnId) {
9006
9464
  state.liveStatusTurnId = null;
9465
+ state.liveActivityAnnouncement = null;
9466
+ if (state.liveActivityTimer) clearTimeout(state.liveActivityTimer);
9467
+ state.liveActivityTimer = null;
9468
+ if (state.liveFlo) state.liveFlo.label.textContent = '';
9007
9469
  // The screen-reader announcement is a transient status. Once the durable turn ends,
9008
9470
  // leaving its text behind makes the finished chat sound as though it is still working.
9009
9471
  // Cleared once, when that turn ends — not on every idle repaint: the 5 s poll repaints the
@@ -9012,15 +9474,25 @@
9012
9474
  if (wasResponding) ui.status.textContent = '';
9013
9475
  return;
9014
9476
  }
9015
- if (state.liveStatusTurnId === turnId) return;
9477
+ const chatId = state.chat?.chatId;
9478
+ const text = liveActivityText();
9479
+ const key = JSON.stringify([chatId, turnId, text]);
9480
+ if (state.liveActivityAnnouncement === key) return;
9481
+ if (state.liveActivityTimer) clearTimeout(state.liveActivityTimer);
9482
+ const first = state.liveStatusTurnId !== turnId || state.liveStatusChatId !== chatId;
9016
9483
  state.liveStatusTurnId = turnId;
9017
- const provider = providerLabels[state.chat?.provider] || 'AI';
9018
- ui.status.textContent = '';
9019
- requestAnimationFrame(() => {
9484
+ state.liveStatusChatId = chatId;
9485
+ state.liveActivityAnnouncement = key;
9486
+ if (first) ui.status.textContent = '';
9487
+ const announce = () => {
9020
9488
  // Recovery or completion may land between scheduling and painting this transient sentence.
9021
- if (!turnIsVisiblyActive() || state.chat?.activeTurn?.turnId !== turnId || state.liveStatusTurnId !== turnId) return;
9022
- ui.status.textContent = `${provider} is responding.`;
9023
- });
9489
+ if (!turnIsVisiblyActive() || state.chat?.chatId !== chatId || state.chat?.activeTurn?.turnId !== turnId
9490
+ || state.liveActivityAnnouncement !== key || liveActivityText() !== text) return;
9491
+ state.liveActivityTimer = null;
9492
+ if (ui.status.textContent !== text) ui.status.textContent = text;
9493
+ };
9494
+ if (first) requestAnimationFrame(announce);
9495
+ else state.liveActivityTimer = setTimeout(announce, 750);
9024
9496
  }
9025
9497
 
9026
9498
  function renderedAnswerTarget(events, eventId, turnId, type = 'assistant-message') {
@@ -9100,7 +9572,7 @@
9100
9572
  } catch { caret = null; } // a checkbox or radio has no caret, and some engines throw on reading it
9101
9573
  // A reused card node is detached and re-attached here, and a detached element forgets its scroll: the height
9102
9574
  // card's lists, and the readiness card's own scroll area and table (#2439), are noted and put back below.
9103
- for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table')) {
9575
+ for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table, .ai-chat-auto-review-record')) {
9104
9576
  list.keptScrollTop = list.scrollTop; list.keptScrollLeft = list.scrollLeft;
9105
9577
  }
9106
9578
  ui.feed.replaceChildren();
@@ -9202,7 +9674,7 @@
9202
9674
  if (turnIsVisiblyActive()) ui.feed.append(renderLiveStatus());
9203
9675
  }
9204
9676
  // 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')) {
9677
+ for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table, .ai-chat-auto-review-record')) {
9206
9678
  if (typeof list.keptScrollTop === 'number' && list.scrollTop !== list.keptScrollTop) list.scrollTop = list.keptScrollTop;
9207
9679
  if (typeof list.keptScrollLeft === 'number' && list.scrollLeft !== list.keptScrollLeft) list.scrollLeft = list.keptScrollLeft;
9208
9680
  }
@@ -11368,6 +11840,7 @@
11368
11840
  source.onerror = () => {
11369
11841
  if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
11370
11842
  ui.hint.textContent = 'Reconnecting to this conversation…';
11843
+ paintEvents();
11371
11844
  if (source.readyState === EventSource.CLOSED) scheduleEventReconnect(chatId, scope, generation);
11372
11845
  };
11373
11846
  }