@floless/app 0.148.1 → 0.149.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/bin/floless.mjs +1 -1
  2. package/dist/floless-server.cjs +28663 -18914
  3. package/dist/schemas/drawing-check.profile.v1.schema.json +156 -0
  4. package/dist/schemas/steel.model.v2.schema.json +43 -1
  5. package/dist/schemas/tekla.model.v2.schema.json +6 -2
  6. package/dist/skills/floless-app-steel-model/SKILL.md +54 -11
  7. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +9 -5
  8. package/dist/skills/floless-app-steel-takeoff/SKILL.md +128 -15
  9. package/dist/skills/floless-app-vectorize/SKILL.md +7 -4
  10. package/dist/templates/check-drawings.flo +46 -0
  11. package/dist/templates/drawing-check.flo +55 -0
  12. package/dist/templates/tekla-parser.flo +6 -2
  13. package/dist/web/app.css +143 -8
  14. package/dist/web/aware.js +444 -39
  15. package/dist/web/chat.css +171 -9
  16. package/dist/web/chat.js +2005 -759
  17. package/dist/web/commands-drawing-check.js +53 -0
  18. package/dist/web/commands-shell.js +275 -3
  19. package/dist/web/commands-steel.js +1 -0
  20. package/dist/web/commands-tekla-parser.js +3 -0
  21. package/dist/web/commands.js +1 -1
  22. package/dist/web/connections.js +382 -0
  23. package/dist/web/display-units.js +15 -1
  24. package/dist/web/drawing-check-editor.html +289 -0
  25. package/dist/web/drawing-check-editor.js +1242 -0
  26. package/dist/web/drawing-check-overlay.js +36 -0
  27. package/dist/web/filter-ai-proposal.js +32 -13
  28. package/dist/web/index.html +25 -3
  29. package/dist/web/instructor.js +2 -2
  30. package/dist/web/local-discovery.js +144 -2
  31. package/dist/web/model-display-units.js +23 -9
  32. package/dist/web/model-viewport-revit-adapter.js +12 -2
  33. package/dist/web/revit-editor.css +5 -0
  34. package/dist/web/revit-editor.js +141 -20
  35. package/dist/web/steel-editor.html +166 -27
  36. package/dist/web/steel-filter.html +60 -166
  37. package/dist/web/steel-model-v2-commands.js +13 -3
  38. package/dist/web/steel-model-v2-projection.js +20 -0
  39. package/dist/web/steel-units.js +3 -1
  40. package/dist/web/workspaces.js +306 -22
  41. package/launch.mjs +5 -5
  42. package/package.json +3 -1
  43. package/dist/web/filter-ai-context.js +0 -92
package/dist/web/chat.js CHANGED
@@ -6,11 +6,15 @@
6
6
 
7
7
  const el = (id) => document.getElementById(id);
8
8
  /**
9
- * What the composer says when a message typed on the Drawing Filter will go to a waiting read (#1776).
9
+ * What the composer says when a message typed on the Drawing Filter will go to the drawing read in
10
+ * this conversation (#1776) — once its turn has stopped, and while it is still working (#1857).
10
11
  * Painted BEFORE Send, over a draft, so it says where the message WILL go — never "Sent to …", which
11
- * claimed delivery of something not yet sent.
12
+ * claimed delivery of something not yet sent. The stopped wording no longer says the read is
13
+ * "waiting on your answer": it also holds while the read waits for the Drawing Filter to be saved
14
+ * (#1855), when there may be no question at all.
12
15
  */
13
- const READ_REPLY_HINT = 'Your reply will go to the drawing read, which is waiting on your answer.';
16
+ const READ_REPLY_HINT = 'Your message will go to the drawing read in this conversation.';
17
+ const READ_FOLLOWUP_HINT = 'Your message will go to the drawing read as a follow-up, without stopping it.';
14
18
  const ui = {
15
19
  historyToggle: el('chat-history-toggle'), newChat: el('chat-new'), refresh: el('chat-refresh'), history: el('chat-history'),
16
20
  title: el('chat-title'), rename: el('chat-rename'), scope: el('chat-scope'), settingsToggle: el('chat-settings-toggle'),
@@ -26,29 +30,30 @@
26
30
  unread: el('chat-unread'), tab: el('narrative-tab'),
27
31
  context: el('left-chat-context'),
28
32
  teklaChip: el('chat-tekla-context'),
33
+ workspaceUnits: el('chat-units'),
29
34
  };
30
35
 
31
36
  const state = {
32
37
  // signInPending is keyed by provider: a wait started in one conversation must not paint an
33
38
  // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
39
+ // #1798: the chat owner's display units as the server last answered them (null = not known yet), and the
40
+ // generation that answer belongs to. Receipts show recorded kilograms until they are known.
41
+ displayUnits: null, displayUnitsGeneration: 0,
34
42
  sessionReady: false, scope: null, chats: [], archivedChats: [], unreadableChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
35
43
  source: null, eventReconnectTimer: null, eventReconnectAttempt: 0, eventReconnectChatId: null, attachments: [], imageLimitChatId: null, followupSubmitting: false, followupUnknownId: null, resolvingFollowupIds: new Set(), retryingFollowupIds: new Set(), integrations: null, historyOpen: false, historyOpenings: 0, historyFilter: 'all', archivedHistoryOpen: false,
36
44
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
37
45
  draftTimer: null, localDraft: null, backgroundDrafts: new Map(), draftWrites: new Map(), draftVersions: new Map(), unknownFollowups: new Map(), refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, choosingProvider: false,
38
46
  answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, historyRename: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
39
47
  stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(), revokingApprovalTurns: new Set(), uploadingChatIds: new Set(),
40
- // #1653 stage 4: the project's questions linked to live Tekla parts, the card's open lists, and the receipt showing it.
41
- teklaLinks: { projectId: null, state: 'idle', links: [], partial: false, inflight: false, again: false }, teklaHistoryUi: {}, teklaHistoryHost: null,
48
+ // #1653 stage 4: this chat owner's (project or workflow, #1890) questions linked to live Tekla parts, the card's open lists, and the receipt showing it.
49
+ teklaLinks: { ownerKey: '', state: 'idle', links: [], partial: false, inflight: false, again: false }, teklaHistoryUi: {}, teklaHistoryHost: null,
42
50
  // Latched so the 5 s account poll logs an outage once instead of twelve times a minute; cleared
43
51
  // on the next successful read, so a later, separate outage is logged too.
44
52
  accountReadWarned: false,
45
- // Drawing Filter requests sent from this composer: those still waiting for an answer (each checked
46
- // on its own timer), failure notices and the last card refusal, keyed by request.
47
- filterPending: new Map(), filterNotices: new Map(), filterCardMessages: new Map(),
48
- filterSending: false,
49
- // The "not sent" sentence of a Drawing Filter message refused while FloLess sets its AI up, kept in
50
- // the hint while the setup card still shows the setup it was refused for (#1650): { key, sentence }.
51
- filterSetupNote: null,
53
+ // The last sentence a suggestion card's action reported, keyed by the card's request id.
54
+ filterCardMessages: new Map(),
55
+ // #1859: per message (client submission id), why the open Drawing Filter's selection did not go with it.
56
+ filterNotShared: new Map(),
52
57
  // The last sentence report() put under the box, held there until the person acts on it (#1683):
53
58
  // { message, scope, chatId, draft, attachments, blocked }. See heldReport().
54
59
  reportHold: null,
@@ -88,13 +93,21 @@
88
93
  const SERVER_WORDED_SIGN_IN_CODES = new Set(['runtime-unavailable', 'launch-failed', 'launch-unsafe', 'sign-in-active', 'sign-out-failed']);
89
94
  const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question' };
90
95
  const requestStatusLabels = { pending: 'Queued', queued: 'Queued', running: 'Running', ready: 'Ready', completed: 'Complete', failed: 'Failed', stopped: 'Stopped' };
96
+ // Pictures and PDFs upload as the browser names them. Any other file is a DATA file (#1853): its
97
+ // bytes decide whether FloLess can read it (sniffDataFile), never its name or declared type.
91
98
  const allowedTypes = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
92
99
  const MAX_IMAGES_PER_MESSAGE = 5;
100
+ const MAX_DATA_FILES_PER_MESSAGE = 4;
101
+ // What reaches the AI from one data file (server/attachment-text.ts MAX_TEXT_CHARS).
102
+ const MAX_DATA_TEXT_CHARS = 16000;
103
+ // The stored type of each data-file kind (server/attachment-text.ts DATA_MEDIA_TYPES).
104
+ const DATA_TYPES = new Set(['application/x-step', 'application/dxf', 'text/plain']);
105
+ const ATTACHMENT_KIND_LABELS = { 'application/pdf': 'PDF', 'application/x-step': 'IFC', 'application/dxf': 'DXF', 'text/plain': 'Data' };
93
106
  const MB = 1024 * 1024;
94
107
 
95
108
  function ownerQuery(owner = state.scope?.owner) {
96
109
  if (!owner) return '';
97
- const ownerId = owner.kind === 'project' ? owner.projectId : owner.workflowId;
110
+ const ownerId = owner.kind === 'project' ? owner.projectId : owner.kind === 'workflow' ? owner.workflowId : 'workspace';
98
111
  return new URLSearchParams({ ownerKind: owner.kind, ownerId }).toString();
99
112
  }
100
113
 
@@ -131,6 +144,7 @@
131
144
  const error = new Error(body?.error || body || `Chat request failed (${response.status})`);
132
145
  error.code = body?.code || null;
133
146
  error.reason = body?.reason || null;
147
+ error.recovery = Array.isArray(body?.recovery) ? body.recovery : null;
134
148
  error.status = response.status;
135
149
  throw error;
136
150
  }
@@ -164,9 +178,12 @@
164
178
  }
165
179
 
166
180
  function errorMessage(error) {
167
- // A Drawing Filter refusal is already a complete plain-English sentence written for this moment.
168
- if (error?.filterRefusal) return error.message;
181
+ // A sentence written by plainError (an attachment refused in the browser) is already the whole
182
+ // plain-English explanation for this moment.
183
+ if (error?.plainSentence) return error.message;
169
184
  const raw = error instanceof Error ? error.message : String(error);
185
+ // Declared here, not beside the other constants: several test harnesses lift this function alone.
186
+ const ATTACHMENT_UNAVAILABLE = 'An attached file is missing, or changed since you attached it, so nothing was sent. Remove it, attach it again, then send.';
170
187
  if (raw === 'This message was not sent because its queued response was cancelled') {
171
188
  return 'You stopped the response before AI could take this queued message. Use Retry sending if you still want to send it.';
172
189
  }
@@ -210,6 +227,11 @@
210
227
  'chat-archived': 'This conversation is archived. Start a new conversation to continue.',
211
228
  'chat-turn-active': 'Stop the active response before changing this conversation.',
212
229
  'chat-message-image-limit': 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.',
230
+ 'chat-message-data-limit': 'You can attach up to four data files to one message. Remove one or choose fewer, then try again.',
231
+ // The server names the file and says what to attach instead (attachment-text.ts unreadableSentence).
232
+ 'chat-attachment-unreadable': raw,
233
+ // A file missing, or changed on disk since it was attached (#1853); the provider never received it.
234
+ 'chat-attachment-unavailable': ATTACHMENT_UNAVAILABLE,
213
235
  'chat-send-refused': 'The AI service did not accept this message. Check your sign-in and conversation settings, then try again.',
214
236
  'chat-approval-stale': 'This approval is no longer active. Refresh the conversation.',
215
237
  'chat-provider-identity-changed': 'The connected AI account changed while this response was running. Refresh the conversation and try again.',
@@ -298,6 +320,8 @@
298
320
  }
299
321
  if (/chat model .*invalid|model .*not offered/i.test(raw)) return 'That model is no longer available. Choose another model.';
300
322
  if (/chat effort .*invalid|effort .*not offered/i.test(raw)) return 'That effort level is no longer available. Choose another option.';
323
+ // The stored "Not sent" row of a turn refused for the same reason carries the server's own words.
324
+ if (/^chat attachment (?:is unavailable|disappeared) before dispatch$/.test(raw.trim())) return ATTACHMENT_UNAVAILABLE;
301
325
  if (/\b(?:EPERM|EACCES|EBUSY|ENOENT|ENOTDIR)\b|operation not permitted|permission denied/i.test(raw)) {
302
326
  return 'FloLess could not access that file or folder. Check that it is available and try again.';
303
327
  }
@@ -366,11 +390,10 @@
366
390
  * Every repaint of the composer (a poll, a status change, the setup card's tick) rewrites the hint,
367
391
  * which used to wipe a reported sentence within seconds (#1683). It is the only visible reason nothing
368
392
  * happened, so it is held, with what the composer looked like when it was said, until the person acts
369
- * on it (heldReport). The Drawing Filter setup sentence is not: filterSetupHint gives it its own,
370
- * longer lifetime, tied to the setup card.
393
+ * on it (heldReport).
371
394
  */
372
395
  function holdReport(message) {
373
- state.reportHold = message === state.filterSetupNote?.sentence ? null : {
396
+ state.reportHold = {
374
397
  message, scope: scopeKey(state.scope), chatId: state.chat?.chatId ?? null,
375
398
  draft: ui.input.value, attachments: attachmentKey(), blocked: sendBlocker(),
376
399
  };
@@ -419,20 +442,6 @@
419
442
  }
420
443
  }
421
444
 
422
- // A Drawing Filter message refused while FloLess sets its AI up (#1650) keeps its sentence in the hint
423
- // while the card still shows that very setup and the refused words are still in the draft, which the
424
- // sentence says they are. Every repaint asks again, so the sentence ends with the first of those to
425
- // change (the setup finished, was cancelled or failed another way, another conversation, the words
426
- // removed) and the card speaks for itself.
427
- function filterSetupHint() {
428
- const note = state.filterSetupNote;
429
- if (!note) return null;
430
- const status = state.chat ? state.capability?.runtime : null;
431
- if (status && runtimeCardKey(state.chat.chatId, status) === note.key && ui.input.value.includes(note.text)) return note.sentence;
432
- state.filterSetupNote = null;
433
- return null;
434
- }
435
-
436
445
  function clearReport() {
437
446
  ui.hint.classList.remove('error');
438
447
  const held = heldReport();
@@ -443,7 +452,6 @@
443
452
  ui.hint.classList.add('error');
444
453
  return;
445
454
  }
446
- const filterNote = filterSetupHint();
447
455
  const message = requestExecutionBlocked()
448
456
  ? 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.'
449
457
  : state.followupUnknownId || hasUnknownFollowup()
@@ -452,14 +460,14 @@
452
460
  && state.attachments.filter(attachment => attachment.mediaType.startsWith('image/')).length >= MAX_IMAGES_PER_MESSAGE
453
461
  ? 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.'
454
462
  : state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
455
- ? filterNote || runtimeNotice(state.chat.provider, state.capability.runtime).body
463
+ ? runtimeNotice(state.chat.provider, state.capability.runtime).body
456
464
  : state.chat && !providerReady()
457
465
  ? `${capabilityMessage(state.chat.provider, state.capability?.reason)} You can still write a message; Send will retry the connection.`
458
466
  : state.chat?.state === 'recovery'
459
467
  ? 'Check the last AI response before continuing.'
460
468
  : !state.scope?.owner
461
469
  ? 'Open a project or workflow to start chatting.'
462
- // #1776: on the Drawing Filter, the one place a message would otherwise go to its own AI.
470
+ // #1776/#1859: a drawing read running in this conversation is where a message goes, on any screen.
463
471
  : paintFilterComposer().replyToRead
464
472
  ? READ_REPLY_HINT
465
473
  : 'Enter to send · Shift+Enter for a new line';
@@ -472,8 +480,6 @@
472
480
  ui.hint.classList.remove('working');
473
481
  ui.hint.removeAttribute('aria-label');
474
482
  ui.hint.textContent = message;
475
- // Painted as it was reported, so the poll does not restyle it.
476
- if (filterNote && message === filterNote) ui.hint.classList.add('error');
477
483
  }
478
484
  // The refusal no longer describes the composer. Only remove that exact announcement:
479
485
  // a response may have since claimed the same live region (#1704).
@@ -492,7 +498,7 @@
492
498
  if (!owner) return '';
493
499
  // Events and the bridge can construct the same owner with different property order; JSON
494
500
  // serialization made those equal scopes look different and reset the provider chooser.
495
- const ownerId = owner.kind === 'project' ? owner.projectId : owner.workflowId;
501
+ const ownerId = owner.kind === 'project' ? owner.projectId : owner.kind === 'workflow' ? owner.workflowId : 'workspace';
496
502
  return typeof ownerId === 'string' ? `${owner.kind}:${ownerId}` : '';
497
503
  }
498
504
 
@@ -524,10 +530,12 @@
524
530
  }[selectedStep || ''] || 'project-list';
525
531
  const workspaceProjectOpen = document.getElementById('ws-project')?.hidden === false;
526
532
  const dashboardVisible = document.getElementById('dashboard')?.hidden === false;
533
+ // #1890: the Workflows landing (the list of workflows), not the canvas of the workflow loaded underneath.
534
+ const workflowLanding = document.getElementById('wf-landing')?.hidden === false;
527
535
  const surface = reportOpen ? (threeDimensionalReport ? '3d-report' : 'report')
528
536
  : editorOpen ? 'model-editor'
529
537
  : workspaceMode ? (workspaceProjectOpen ? workspaceSurface : 'project-list')
530
- : dashboardVisible ? 'dashboard' : 'workflow-canvas';
538
+ : workflowLanding ? 'workflow-list' : dashboardVisible ? 'dashboard' : 'workflow-canvas';
531
539
  if (options.surfaceOnly) return { surface };
532
540
  return {
533
541
  mode: workspaceMode ? 'workspaces' : workflowMode ? 'workflows' : 'canvas',
@@ -562,6 +570,7 @@
562
570
  case 'project-history': return shellText('ws-history');
563
571
  case 'project-knowledge': return shellText('ws-knowledge');
564
572
  case 'project-list': return shellText('ws-landing');
573
+ case 'workflow-list': return shellText('wf-landing');
565
574
  case 'workflow-canvas': return shellText('canvas-main', 'inspect');
566
575
  case 'dashboard': return shellText('dashboard');
567
576
  case 'report': return boundedVisibleText(readVisibleFrameText('report-frame'), shellText('report-title', 'report-sub', 'report-overlay'));
@@ -576,7 +585,7 @@
576
585
  'drawing-filter': 'Drawing Filter', 'project-model': 'project model', 'project-exports': 'project exports',
577
586
  'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-list': 'project list',
578
587
  'workflow-canvas': 'workflow canvas', dashboard: 'dashboard', report: 'report', '3d-report': '3D report',
579
- 'model-editor': 'model editor',
588
+ 'model-editor': 'model editor', 'workflow-list': 'workflow list',
580
589
  };
581
590
  return `${labels[context.surface] || 'FloLess'} · visible state${context.activity === 'workflow-running' ? ' · workflow running' : ''}`;
582
591
  }
@@ -589,10 +598,10 @@
589
598
  // the composer's only mention of which sheet a Drawing Filter message is about.
590
599
  const shared = filter.state === 'off'
591
600
  ? floLessContextLabel(currentFloLessContext())
592
- : filter.state === 'ready' ? `Drawing Filter · partial view of ${filter.summary.sheet || 'this sheet'} and its selection`
593
- : 'Drawing Filter · loading…';
601
+ : filter.state === 'ready' ? `Drawing Filter · sheet ${filter.summary.sheet || 'on screen'} and its selection`
602
+ : 'Drawing Filter · still loading, its selection is not shared yet';
594
603
  // #1776: where the message goes, when that is not where this surface would send it.
595
- const destination = filter.replyToRead ? `${READ_REPLY_HINT} ` : '';
604
+ const destination = filter.replyToRead ? `${filter.readWorking ? READ_FOLLOWUP_HINT : READ_REPLY_HINT} ` : '';
596
605
  // A live region: rewritten only when the text changes, or every keystroke would re-announce it.
597
606
  if (ui.contextNote.textContent !== `${destination}Sharing with AI: ${shared}`) {
598
607
  const prefix = document.createElement('strong');
@@ -711,7 +720,7 @@
711
720
  // receive later events. This prevents a migrated chat history from showing hundreds of old events.
712
721
  function seedReadCursors(chats, owner = state.scope?.owner) {
713
722
  if (!owner) return;
714
- const ownerId = owner.kind === 'project' ? owner.projectId : owner.workflowId;
723
+ const ownerId = owner.kind === 'project' ? owner.projectId : owner.kind === 'workflow' ? owner.workflowId : 'workspace';
715
724
  const key = `floless:chat-read-seeded:${owner.kind}:${ownerId}`;
716
725
  try {
717
726
  if (localStorage.getItem(key)) return;
@@ -768,11 +777,12 @@
768
777
 
769
778
  function providerChooser() {
770
779
  paintComposerDisclosure();
771
- // The workspace landing page has no conversation owner. It must never offer a provider,
772
- // history, or refresh there: none of those actions has a chat to operate on.
780
+ // Without a conversation owner there is no provider, history, or refresh to offer: none of those
781
+ // actions has a chat to operate on (#1890 gives every landing an owner, so this is a fallback).
773
782
  // No provider is chosen here (nor on the unscoped landing), so a setup card left from the previous
774
- // conversation must go with it.
783
+ // conversation must go with it — and so must the previous conversation's units line.
775
784
  shell.querySelector('.ai-chat-runtime')?.remove(); stopRuntimePoll();
785
+ if (ui.workspaceUnits) { ui.workspaceUnits.hidden = true; ui.workspaceUnits.replaceChildren(); delete ui.workspaceUnits.dataset.painted; }
776
786
  if (!state.scope?.owner) { showUnscoped(); return; }
777
787
  ui.feed.replaceChildren();
778
788
  updateOffscreenActivity();
@@ -781,7 +791,9 @@
781
791
  const strong = document.createElement('strong');
782
792
  strong.textContent = state.chats.length ? 'Start a new conversation' : 'Start this conversation';
783
793
  const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
784
- copy.textContent = 'FloLess keeps this chat with the project on this computer. Messages and attachments are sent to Claude or Codex through your account.';
794
+ const home = state.scope.owner.kind === 'workspace' ? 'in your workspace'
795
+ : state.scope.owner.kind === 'workflow' ? 'with the workflow' : 'with the project';
796
+ copy.textContent = `FloLess keeps this chat ${home} on this computer. Messages and attachments are sent to Claude or Codex through your account.`;
785
797
  const row = document.createElement('div');
786
798
  row.className = 'ai-chat-provider-row';
787
799
  for (const provider of ['claude', 'codex']) {
@@ -1599,44 +1611,104 @@
1599
1611
  return html.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noreferrer">$1</a>');
1600
1612
  }
1601
1613
 
1602
- function markdownHtml(value) {
1614
+ function markdownHtml(value, depth = 0) {
1603
1615
  const source = String(value ?? '').replace(/\r\n?/g, '\n');
1604
- const lines = source.split('\n');
1616
+ // A quote or a list item re-enters this renderer for its own content, one level down. Past a
1617
+ // sane depth the remainder is shown as escaped text instead of recursing further.
1618
+ if (depth > 8) return `<p>${markdownInline(source).replace(/\n/g, '<br>')}</p>`;
1619
+ // Leading tabs count as four columns wherever they sit in the indent (" \t- x" is still a bullet).
1620
+ const lines = source.split('\n').map((line) => line.replace(/^[ \t]+/, (indent) => indent.replace(/\t/g, ' ')));
1605
1621
  const output = [];
1606
1622
  let paragraph = [];
1607
1623
  let list = null;
1624
+ let quote = null;
1608
1625
  let code = null;
1626
+ const isFence = (line) => /^\s*```(?:[\w-]+)?\s*$/.test(line);
1627
+ const isQuote = (line) => /^ {0,3}>/.test(line);
1628
+ const heading = (line) => line.match(/^\s{0,3}(#{1,3})\s+(.+?)\s*#*$/);
1629
+ const indentOf = (line) => line.length - line.trimStart().length;
1630
+ const listMarker = (line) => {
1631
+ const match = line.match(/^( *)(?:([-*])|(\d{1,9})[.)])([ \t]+)(\S.*)$/);
1632
+ if (!match) return null;
1633
+ const marker = match[2] || `${match[3]}.`;
1634
+ return { indent: match[1].length, type: match[2] ? 'ul' : 'ol', number: match[3] ? Number(match[3]) : 1,
1635
+ contentIndent: match[1].length + marker.length + Math.min(match[4].length, 4), text: match[5] };
1636
+ };
1609
1637
  const flushParagraph = () => {
1610
1638
  if (paragraph.length) { output.push(`<p>${markdownInline(paragraph.join('\n')).replace(/\n/g, '<br>')}</p>`); paragraph = []; }
1611
1639
  };
1640
+ const flushQuote = () => {
1641
+ if (!quote) return;
1642
+ output.push(`<blockquote>${markdownHtml(quote.join('\n'), depth + 1)}</blockquote>`);
1643
+ quote = null;
1644
+ };
1645
+ // An item is its own text plus any block content written under it — an indented continuation, a
1646
+ // quote, a nested list — rendered by this same escaping renderer, one level down.
1647
+ const renderItem = (item) => {
1648
+ const text = markdownInline(item.text.join('\n')).replace(/\n/g, '<br>');
1649
+ const children = item.children.join('\n').trim() ? markdownHtml(item.children.join('\n'), depth + 1) : '';
1650
+ return `<li>${text}${children}</li>`;
1651
+ };
1612
1652
  const flushList = () => {
1613
1653
  if (!list) return;
1614
- output.push(`<${list.type}>${list.items.map((item) => `<li>${markdownInline(item)}</li>`).join('')}</${list.type}>`);
1654
+ // The written first number is kept (a list the AI started at 4 reads 4, 5, 6 — not 1, 2, 3).
1655
+ const start = list.type === 'ol' && list.start !== 1 ? ` start="${list.start}"` : '';
1656
+ output.push(`<${list.type}${start}>${list.items.map(renderItem).join('')}</${list.type}>`);
1615
1657
  list = null;
1616
1658
  };
1659
+ const startList = (marker) => {
1660
+ list = { type: marker.type, start: marker.number, indent: marker.indent, items: [], blanks: 0, fence: false };
1661
+ addItem(marker);
1662
+ };
1663
+ const addItem = (marker) => {
1664
+ list.items.push({ text: [marker.text], children: [], contentIndent: marker.contentIndent });
1665
+ list.blanks = 0;
1666
+ };
1667
+ const addChild = (line) => {
1668
+ const item = list.items[list.items.length - 1];
1669
+ for (; list.blanks > 0; list.blanks -= 1) item.children.push('');
1670
+ item.children.push(line);
1671
+ if (isFence(line)) list.fence = !list.fence;
1672
+ };
1673
+ // Returns true when the line belongs to the open list; false means the list has ended here.
1674
+ const continueList = (line) => {
1675
+ const item = list.items[list.items.length - 1];
1676
+ if (list.fence) { addChild(line.slice(Math.min(indentOf(line), item.contentIndent))); return true; }
1677
+ if (!line.trim()) { list.blanks += 1; return true; }
1678
+ const marker = listMarker(line);
1679
+ if (marker && marker.indent < list.indent + 2) {
1680
+ // A blank line between items is a "loose" list, not the end of it — how both Claude and
1681
+ // Codex write long numbered questions.
1682
+ if (marker.type === list.type) { addItem(marker); return true; }
1683
+ return false;
1684
+ }
1685
+ if (indentOf(line) >= list.indent + 2) { addChild(line.slice(Math.min(indentOf(line), item.contentIndent))); return true; }
1686
+ // A quote written under an item belongs to it even unindented, so the numbering carries on.
1687
+ if (isQuote(line)) { addChild(line.trimStart()); return true; }
1688
+ if (list.blanks === 0 && !heading(line) && !isFence(line)) {
1689
+ if (item.children.length) addChild(line); else item.text.push(line.trim());
1690
+ return true;
1691
+ }
1692
+ return false;
1693
+ };
1617
1694
  for (const line of lines) {
1618
- const fence = line.match(/^\s*```(?:[\w-]+)?\s*$/);
1619
- if (fence) {
1620
- flushParagraph(); flushList();
1621
- if (code === null) code = []; else { output.push(`<pre><code>${escapeMarkdownHtml(code.join('\n'))}</code></pre>`); code = null; }
1695
+ if (code !== null) {
1696
+ if (isFence(line)) { output.push(`<pre><code>${escapeMarkdownHtml(code.join('\n'))}</code></pre>`); code = null; } else code.push(line);
1622
1697
  continue;
1623
1698
  }
1624
- if (code !== null) { code.push(line); continue; }
1625
- const heading = line.match(/^\s{0,3}(#{1,3})\s+(.+?)\s*#*$/);
1626
- if (heading) { flushParagraph(); flushList(); const level = heading[1].length; output.push(`<h${level}>${markdownInline(heading[2])}</h${level}>`); continue; }
1627
- const bullet = line.match(/^\s*[-*]\s+(.+)$/);
1628
- const numbered = line.match(/^\s*\d+[.)]\s+(.+)$/);
1629
- if (bullet || numbered) {
1630
- flushParagraph();
1631
- const type = bullet ? 'ul' : 'ol';
1632
- if (!list || list.type !== type) { flushList(); list = { type, items: [] }; }
1633
- list.items.push((bullet || numbered)[1]); continue;
1634
- }
1635
- if (!line.trim()) { flushParagraph(); flushList(); continue; }
1699
+ if (list) { if (continueList(line)) continue; flushList(); }
1700
+ if (isQuote(line)) { flushParagraph(); if (!quote) quote = []; quote.push(line.replace(/^ {0,3}> ?/, '')); continue; }
1701
+ flushQuote();
1702
+ if (isFence(line)) { flushParagraph(); code = []; continue; }
1703
+ const title = heading(line);
1704
+ if (title) { flushParagraph(); const level = title[1].length; output.push(`<h${level}>${markdownInline(title[2])}</h${level}>`); continue; }
1705
+ const marker = listMarker(line);
1706
+ if (marker) { flushParagraph(); startList(marker); continue; }
1707
+ if (!line.trim()) { flushParagraph(); continue; }
1636
1708
  paragraph.push(line);
1637
1709
  }
1638
1710
  if (code !== null) output.push(`<pre><code>${escapeMarkdownHtml(code.join('\n'))}</code></pre>`);
1639
- flushParagraph(); flushList();
1711
+ flushParagraph(); flushQuote(); flushList();
1640
1712
  return output.join('') || '<p></p>';
1641
1713
  }
1642
1714
 
@@ -1676,8 +1748,14 @@
1676
1748
  target.append(image);
1677
1749
  } else {
1678
1750
  const file = document.createElement('span');
1679
- file.textContent = `${attachment.mediaType === 'application/pdf' ? 'PDF' : 'File'} · ${attachment.fileName}`;
1751
+ file.textContent = attachmentLabel(attachment);
1680
1752
  target.append(file);
1753
+ const cut = dataCutTip(attachment);
1754
+ if (cut) {
1755
+ target.dataset.tip = `${cut} Double-click to open in your default app.`;
1756
+ // The tile is focusable and named by its aria-label, so the cut is said there too, not only on hover.
1757
+ target.setAttribute('aria-label', `Open ${attachment.fileName} in its default app. ${cut}`);
1758
+ }
1681
1759
  }
1682
1760
  return target;
1683
1761
  }
@@ -1831,10 +1909,14 @@
1831
1909
  if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
1832
1910
  if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
1833
1911
  if (event.type === 'assistant-message' && event.payload?.filterAi && !event.payload?.delta) return renderFilterAnswer(event);
1834
- if (event.type === 'user-message') return renderMessage(event, 'user', payloadText(event));
1912
+ if (event.type === 'user-message') return withFilterNotShared(renderMessage(event, 'user', payloadText(event)), event);
1913
+ if (event.type === 'filter-proposal') return renderServerProposal(event);
1914
+ if (event.type === 'filter-proposal-update') return null;
1835
1915
  if (event.type === 'assistant-message') return renderMessage(event, 'assistant', payloadText(event), Boolean(event.payload?.delta));
1836
1916
  if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state' || event.type === 'followup-status') return null;
1837
1917
  if (event.type === 'tekla-read') return renderTeklaReadEvent(event);
1918
+ if (event.type === 'height-question') return renderHeightQuestion(event);
1919
+ if (event.type === 'setup-question') return renderSetupQuestion(event);
1838
1920
  const item = document.createElement('div');
1839
1921
  item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}${event.type === 'knowledge-citation' ? ' knowledge' : ''}`;
1840
1922
  item.dataset.eventSequence = String(event.sequence);
@@ -1854,6 +1936,18 @@
1854
1936
  item.append(label, document.createTextNode(` · ${count} object${count === 1 ? '' : 's'}${note ? ` · AI note: ${note}` : ''}`));
1855
1937
  return item;
1856
1938
  }
1939
+ if (event.type === 'evidence-read') {
1940
+ // FloLess's own record of one look at a sheet or attachment (#1859) — written by the server, never by the
1941
+ // model, so a look that failed shows here whatever the answer says. Every string is FloLess's.
1942
+ const looked = payload.outcome === 'read';
1943
+ item.classList.add('evidence');
1944
+ if (!looked) item.classList.add('error');
1945
+ label.textContent = looked ? 'Looked at' : 'Could not look at';
1946
+ const what = typeof payload.label === 'string' && payload.label ? payload.label : 'a file';
1947
+ const reason = !looked && typeof payload.reason === 'string' && payload.reason ? ` · ${payload.reason}` : '';
1948
+ item.append(label, document.createTextNode(` ${what}${reason}`));
1949
+ return item;
1950
+ }
1857
1951
  label.textContent = event.type === 'error' && payload.outcome === 'not-sent' ? 'Not sent' : labels[event.type] || event.type;
1858
1952
  let detail = event.type === 'error' ? errorMessage(payloadText(event)) : payloadText(event);
1859
1953
  if (!detail && event.type === 'tool') {
@@ -1870,6 +1964,1275 @@
1870
1964
  return item;
1871
1965
  }
1872
1966
 
1967
+ /*
1968
+ * #1882 — a HEIGHT QUESTION the drawing read asked the person, as a card in the transcript.
1969
+ *
1970
+ * The read cannot answer it: the card is painted from the server's own record of the question (never from
1971
+ * the chat event, which carries only ids), and Confirm/Use post to a route only this window can reach. What
1972
+ * the person confirms or types is what lands in the model. The feed repaints on every streamed word, so
1973
+ * everything the person has in hand — a half-typed height, a row being changed, an error — lives in
1974
+ * `heightCards`, keyed by question, and is painted back each time.
1975
+ */
1976
+ const heightCards = new Map();
1977
+
1978
+ /*
1979
+ * A NEW card for a read asks some rows again, which supersedes them on that read's earlier cards. Those
1980
+ * cards were loaded before it existed, so reload them now: otherwise they keep offering answers the
1981
+ * server will refuse (E2E #1906 — the first Take 5 setup card still showed its re-asked rows as open).
1982
+ */
1983
+ function refreshEarlierCards(cards, entry, load) {
1984
+ for (const other of cards.values()) {
1985
+ if (other === entry || other.requestId !== entry.requestId || (!other.view && !other.loading)) continue;
1986
+ // Mid-load or mid-save, what comes back may predate the new card: read it again once that settles
1987
+ // (Codex review #1906, round 2).
1988
+ if (other.loading || other.busy) other.reloadPending = true;
1989
+ else load(other);
1990
+ }
1991
+ }
1992
+ /**
1993
+ * After a card's own load or save settles, honour a reload a newer card asked for meanwhile.
1994
+ * Deliberately runs even when the card is no longer on screen (the person switched chats): a repaint
1995
+ * reuses the cached copy without fetching, so this reload is what keeps the card current for when they
1996
+ * come back. Its cost is one background request; nothing is painted (#1906 review r3, rejected finding).
1997
+ */
1998
+ function settlePendingReload(entry, load) {
1999
+ if (!entry.reloadPending || entry.loading || entry.busy) return;
2000
+ entry.reloadPending = false;
2001
+ load(entry);
2002
+ }
2003
+
2004
+ function heightCardState(requestId, questionId, chatId) {
2005
+ const key = `${requestId}/${questionId}`;
2006
+ let entry = heightCards.get(key);
2007
+ if (!entry) {
2008
+ entry = { key, requestId, questionId, chatId, view: null, loading: false, loadError: '', drafts: new Map(),
2009
+ changing: new Set(), rowErrors: new Map(), cardError: '', busy: false, selected: new Set(), bulkDraft: '' };
2010
+ heightCards.set(key, entry);
2011
+ }
2012
+ return entry;
2013
+ }
2014
+
2015
+ const heightEndKey = (row) => `${row.memberId}\u0000${row.end}`;
2016
+ const heightEndWord = (row) => (row.endWord === 'from' ? 'start' : 'end');
2017
+ const heightAnswerText = (answer) => (answer?.how === 'typed' ? `You typed ${answer.typed}` : `Confirmed ${answer?.shownAs || ''}`);
2018
+ // The server's sentence, then what to do next when it names a step (a damaged record says to discard the read).
2019
+ const heightErrorText = (error, fallback) => {
2020
+ const next = (error?.recovery || []).map((step) => step && typeof step.action === 'string' ? step.action : '').filter(Boolean);
2021
+ return [error?.message || fallback, ...next].join(' ');
2022
+ };
2023
+ // Refusals that mean the card is out of date: reload it from the server's record so it shows the truth.
2024
+ const HEIGHT_STALE = new Set(['height-question-changed', 'height-question-closed', 'height-question-superseded']);
2025
+ // A card whose read is gone: FloLess removes a read once it publishes or is discarded, so the card can no
2026
+ // longer load or change. The words hold either way (Codex review: not every removed read published).
2027
+ // Said as a final state, never as a load failure with Try again (E2E #1906: every card of a published
2028
+ // read showed "LOADING · there is no drawing read with this id · Try again").
2029
+ const CARD_READ_FINISHED = new Set(['height-question-unknown-read', 'setup-question-unknown-read']);
2030
+ 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.';
2031
+
2032
+ function loadHeightQuestion(entry) {
2033
+ if (entry.loading) return;
2034
+ entry.loading = true;
2035
+ request(`/api/chat/height-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}?${new URLSearchParams({ chatId: entry.chatId || '' })}`)
2036
+ .then((result) => { if (result?.readClosed) { entry.finished = true; entry.view = null; } else entry.view = result.question; entry.loadError = ''; })
2037
+ .catch((error) => {
2038
+ if (CARD_READ_FINISHED.has(error?.code)) { entry.finished = true; entry.loadError = ''; return; }
2039
+ entry.loadError = heightErrorText(error, 'FloLess could not load this height question.');
2040
+ })
2041
+ .finally(() => { entry.loading = false; repaintHeightCard(entry); settlePendingReload(entry, loadHeightQuestion); });
2042
+ }
2043
+
2044
+ function repaintHeightCard(entry) {
2045
+ const old = ui.feed?.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
2046
+ if (!old) return;
2047
+ const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
2048
+ const next = paintHeightCard(entry, old.dataset.eventId, old.dataset.eventSequence);
2049
+ old.replaceWith(next);
2050
+ if (focused) focusHeightControl(next, focused);
2051
+ }
2052
+
2053
+ function focusHeightControl(card, commandId) {
2054
+ const control = [...card.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === commandId);
2055
+ if (!control) return false;
2056
+ control.focus({ preventScroll: true });
2057
+ // Text fields only: a radio or checkbox has no caret, and setSelectionRange on one throws (#1906).
2058
+ if (control.tagName === 'INPUT' && (control.type === 'text' || !control.type)) control.setSelectionRange?.(control.value.length, control.value.length);
2059
+ return true;
2060
+ }
2061
+
2062
+ function renderHeightQuestion(event) {
2063
+ const payload = event.payload || {};
2064
+ const entry = heightCardState(String(payload.requestId || ''), String(payload.questionId || ''), String(event.chatId || state.chat?.chatId || ''));
2065
+ if (!entry.view && !entry.loadError && !entry.finished) {
2066
+ if (!entry.loading) refreshEarlierCards(heightCards, entry, loadHeightQuestion);
2067
+ loadHeightQuestion(entry);
2068
+ }
2069
+ return paintHeightCard(entry, event.eventId, String(event.sequence));
2070
+ }
2071
+
2072
+ function heightActionButton(label, commandId, instanceLabel, className, blockedReason) {
2073
+ const control = button(label, commandId, className);
2074
+ control.dataset.commandInstanceLabel = instanceLabel;
2075
+ if (blockedReason) {
2076
+ control.setAttribute('aria-disabled', 'true');
2077
+ control.dataset.tip = blockedReason;
2078
+ control.dataset.blockedReason = blockedReason;
2079
+ }
2080
+ return control;
2081
+ }
2082
+
2083
+ function paintHeightCard(entry, eventId, sequence) {
2084
+ const view = entry.view;
2085
+ const card = document.createElement('section');
2086
+ card.className = 'ai-chat-filter-card ai-chat-height-card';
2087
+ card.dataset.heightQuestion = entry.key;
2088
+ card.dataset.eventId = eventId || '';
2089
+ card.dataset.eventSequence = sequence || '';
2090
+ card.setAttribute('aria-label', view?.n ? `Confirm member heights, question ${view.n}` : 'Confirm member heights');
2091
+ const rows = view ? view.ends : [];
2092
+ const live = rows.filter((row) => row.status !== 'superseded');
2093
+ // A picture-only answer ("see snap") is answered by the person but waits on the READ, which only looks
2094
+ // once told; it counts here so Tell the read is offered (E2E #1906).
2095
+ const answered = live.filter((row) => row.answer && (row.status === 'confirmed' || row.status === 'typed' || row.status === 'evidence'));
2096
+ const open = Boolean(view?.open);
2097
+ const allAnswered = live.length > 0 && answered.length === live.length;
2098
+ card.dataset.state = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allAnswered ? 'answered' : 'open';
2099
+
2100
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
2101
+ const title = document.createElement('strong'); title.textContent = 'Confirm member heights';
2102
+ const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state';
2103
+ chip.textContent = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allAnswered ? 'answered' : 'needs you';
2104
+ head.append(title, chip);
2105
+ card.append(head);
2106
+
2107
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
2108
+ note.textContent = !view
2109
+ ? (entry.finished ? CARD_FINISHED_TEXT : entry.loadError || 'Loading the heights this read is asking about…')
2110
+ : open
2111
+ ? 'The drawings don’t settle these heights. Only you can answer — the AI can’t fill this in. What you confirm or type goes straight into the model.'
2112
+ : 'This read is no longer waiting for an answer.';
2113
+ card.append(note);
2114
+ if (!view) {
2115
+ if (entry.loadError) {
2116
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2117
+ const retry = heightActionButton('Try again', `shell.chat-height-retry#${entry.questionId}`, 'this height question', '');
2118
+ retry.addEventListener('click', () => { entry.loadError = ''; repaintHeightCard(entry); loadHeightQuestion(entry); });
2119
+ actions.append(retry); card.append(actions);
2120
+ }
2121
+ return card;
2122
+ }
2123
+
2124
+ const questionLabel = `height question ${view.n}`;
2125
+ const count = document.createElement('p'); count.className = 'ai-chat-height-count'; count.setAttribute('aria-live', 'polite');
2126
+ count.textContent = `${answered.length} of ${live.length} answered`;
2127
+ card.append(count);
2128
+
2129
+ // #1906: rows the read grouped ("W10x33 column bases") sit under a header that selects them together.
2130
+ const selectable = (row) => open && row.status !== 'superseded' && !(row.answer && (row.status === 'confirmed' || row.status === 'typed') && !entry.changing.has(heightEndKey(row)));
2131
+ for (const key of [...entry.selected]) if (!rows.some((row) => heightEndKey(row) === key && selectable(row))) entry.selected.delete(key);
2132
+ const list = document.createElement('ol'); list.className = 'ai-chat-height-rows';
2133
+ list.setAttribute('role', 'region'); list.setAttribute('aria-label', 'Heights to confirm'); list.tabIndex = 0;
2134
+ list.dataset.commandId = `shell.chat-height-rows#${entry.questionId}`;
2135
+ list.dataset.commandInstanceLabel = questionLabel;
2136
+ const groups = [];
2137
+ for (const row of rows) {
2138
+ const name = row.group || '';
2139
+ let group = groups.find((g) => g.name === name);
2140
+ if (!group) { group = { name, rows: [] }; groups.push(group); }
2141
+ group.rows.push(row);
2142
+ }
2143
+ for (const group of groups) {
2144
+ if (group.name) list.append(paintHeightGroup(entry, group, selectable));
2145
+ for (const row of group.rows) list.append(paintHeightRow(entry, row, open, selectable(row)));
2146
+ }
2147
+ card.append(list);
2148
+ // The feed repaints on every streamed word; a person scrolled halfway down a long card stays there.
2149
+ list.addEventListener('scroll', () => { entry.rowsScroll = list.scrollTop; }, { passive: true });
2150
+ if (entry.rowsScroll) requestAnimationFrame(() => { if (list.isConnected) list.scrollTop = entry.rowsScroll; });
2151
+
2152
+ if (open && entry.selected.size) card.append(paintHeightBulk(entry, rows, questionLabel));
2153
+
2154
+ const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert');
2155
+ error.textContent = entry.cardError || '';
2156
+ card.append(error);
2157
+
2158
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2159
+ const confirmable = live.filter((row) => !row.answer && row.proposed);
2160
+ if (open && !allAnswered && !entry.selected.size && confirmable.length >= 2 && confirmable.length === live.filter((row) => !row.answer).length) {
2161
+ const all = heightActionButton(`Confirm all ${confirmable.length}`, `shell.chat-height-confirm-all#${entry.questionId}`, questionLabel, '',
2162
+ entry.busy ? 'A height is still being saved — wait for it to finish' : null);
2163
+ all.addEventListener('click', () => {
2164
+ if (all.getAttribute('aria-disabled') === 'true') return;
2165
+ submitHeightAnswers(entry, confirmable.map((row) => ({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value })), null);
2166
+ });
2167
+ actions.append(all);
2168
+ }
2169
+ if (open && allAnswered) {
2170
+ const done = document.createElement('p'); done.className = 'ai-chat-height-done';
2171
+ // No paint-time state about the composer: it changes without this card repainting, so anything
2172
+ // painted here about it would go stale. The click decides (owner ruling 2026-10-02).
2173
+ done.textContent = 'All answered. Press Tell the read, then Send, so the AI can carry on.';
2174
+ card.append(done);
2175
+ const tell = heightActionButton('Tell the read', `shell.chat-height-tell-read#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', null);
2176
+ tell.addEventListener('click', () => tellReadHeightsAnswered(entry));
2177
+ actions.append(tell);
2178
+ }
2179
+ actions.hidden = !actions.childNodes.length;
2180
+ card.append(actions);
2181
+ return card;
2182
+ }
2183
+
2184
+ /** A themed checkbox (the native box never shows, in either theme). */
2185
+ function themedCheck(commandId, instance, checked, ariaLabel, disabledReason, onChange) {
2186
+ const box = document.createElement('input');
2187
+ box.type = 'checkbox'; box.className = 'ai-chat-check';
2188
+ box.dataset.commandId = commandId; box.dataset.commandInstanceLabel = instance;
2189
+ box.checked = checked;
2190
+ box.setAttribute('aria-label', ariaLabel);
2191
+ if (disabledReason) { box.disabled = true; box.dataset.blockedReason = disabledReason; }
2192
+ box.addEventListener('change', () => onChange(box.checked));
2193
+ return box;
2194
+ }
2195
+
2196
+ function paintHeightGroup(entry, group, selectable) {
2197
+ const header = document.createElement('li'); header.className = 'ai-chat-height-group';
2198
+ const name = document.createElement('span'); name.className = 'ai-chat-height-group-name'; name.textContent = group.name; name.dataset.tip = group.name;
2199
+ const tally = document.createElement('span'); tally.className = 'ai-chat-height-meta'; tally.textContent = `${group.rows.length} ${group.rows.length === 1 ? 'end' : 'ends'}`;
2200
+ header.append(name, tally);
2201
+ const open = group.rows.filter(selectable);
2202
+ if (open.length) {
2203
+ const all = open.every((row) => entry.selected.has(heightEndKey(row)));
2204
+ const toggle = heightActionButton(all ? 'Clear group' : 'Select group', `shell.chat-height-select-group#${entry.questionId} ${group.name}`, group.name, 'ai-chat-height-change',
2205
+ entry.busy ? 'A height is still being saved — wait for it to finish' : null);
2206
+ toggle.setAttribute('aria-label', `${all ? 'Clear' : 'Select'} every open end in ${group.name}`);
2207
+ toggle.addEventListener('click', () => {
2208
+ if (toggle.getAttribute('aria-disabled') === 'true') return;
2209
+ for (const row of open) { if (all) entry.selected.delete(heightEndKey(row)); else entry.selected.add(heightEndKey(row)); }
2210
+ repaintHeightCard(entry);
2211
+ });
2212
+ header.append(toggle);
2213
+ }
2214
+ return header;
2215
+ }
2216
+
2217
+ /** The bulk bar (#1906): one height and one source for every ticked end, pinned under the rows. */
2218
+ function paintHeightBulk(entry, rows, questionLabel) {
2219
+ const chosen = rows.filter((row) => entry.selected.has(heightEndKey(row)));
2220
+ const n = chosen.length;
2221
+ const busyReason = entry.busy ? 'A height is still being saved — wait for it to finish' : null;
2222
+ const bar = document.createElement('div'); bar.className = 'ai-chat-height-bulk';
2223
+ const top = document.createElement('div'); top.className = 'ai-chat-height-bulk-top';
2224
+ const tally = document.createElement('span'); tally.setAttribute('aria-live', 'polite'); tally.setAttribute('aria-atomic', 'true');
2225
+ tally.textContent = `${n} selected`;
2226
+ const clear = heightActionButton('Clear', `shell.chat-height-bulk-clear#${entry.questionId}`, questionLabel, 'ai-chat-height-change', null);
2227
+ clear.setAttribute('aria-label', 'Clear the selection');
2228
+ clear.addEventListener('click', () => { entry.selected.clear(); repaintHeightCard(entry); });
2229
+ top.append(tally, clear);
2230
+ bar.append(top);
2231
+ const shared = chosen.every((row) => row.proposed && chosen[0].proposed && row.proposed.value === chosen[0].proposed.value);
2232
+ if (shared && chosen[0]?.proposed) {
2233
+ // Offered only when every ticked end has the SAME proposal — never shown disabled (design review).
2234
+ const line = document.createElement('div'); line.className = 'ai-chat-height-proposal';
2235
+ const value = document.createElement('span'); value.textContent = `Proposed ${chosen[0].proposed.asRead}`;
2236
+ const confirm = heightActionButton(`Confirm proposed for ${n}`, `shell.chat-height-bulk-confirm#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', busyReason);
2237
+ confirm.addEventListener('click', () => {
2238
+ if (confirm.getAttribute('aria-disabled') === 'true') return;
2239
+ submitHeightAnswers(entry, chosen.map((row) => ({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value })), null, `hb:${entry.questionId}`);
2240
+ });
2241
+ line.append(value, confirm);
2242
+ bar.append(line);
2243
+ }
2244
+ const field = document.createElement('div'); field.className = 'ai-chat-height-field';
2245
+ const input = document.createElement('input');
2246
+ input.type = 'text'; input.className = 'ai-chat-height-input'; input.autocomplete = 'off'; input.spellcheck = false;
2247
+ input.dataset.commandId = `shell.chat-height-bulk-input#${entry.questionId}`; input.dataset.commandInstanceLabel = questionLabel;
2248
+ input.placeholder = entry.view?.units === 'mm' ? 'one height for all, e.g. 4870 mm' : 'one height for all, e.g. 16\'-6"';
2249
+ input.setAttribute('aria-label', `One height for the ${n} selected ends`);
2250
+ input.value = entry.bulkDraft || '';
2251
+ input.addEventListener('input', () => { entry.bulkDraft = input.value; entry.cardError = ''; });
2252
+ if (busyReason) { input.readOnly = true; input.setAttribute('aria-disabled', 'true'); input.dataset.blockedReason = busyReason; }
2253
+ const use = heightActionButton(`Use for ${n}`, `shell.chat-height-bulk-use#${entry.questionId}`, questionLabel, shared ? '' : 'ai-chat-filter-apply', busyReason);
2254
+ use.setAttribute('aria-label', `Use the typed height for the ${n} selected ends`);
2255
+ const submit = () => {
2256
+ if (use.getAttribute('aria-disabled') === 'true') return;
2257
+ const typed = input.value.trim();
2258
+ if (!typed) { entry.cardError = 'Type a height first.'; repaintHeightCard(entry); return; }
2259
+ submitHeightAnswers(entry, chosen.map((row) => ({ memberId: row.memberId, end: row.end, action: 'type', typed })), null, `hb:${entry.questionId}`);
2260
+ };
2261
+ input.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } });
2262
+ use.addEventListener('click', submit);
2263
+ field.append(input, use);
2264
+ bar.append(field);
2265
+ bar.append(paintAnswerSource(`hb:${entry.questionId}`, {
2266
+ requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintHeightCard(entry), label: `the ${n} selected ends`, instance: questionLabel,
2267
+ idFor: (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra ? ` ${extra}` : ''}`, busyReason, allowPictureOnly: false,
2268
+ }));
2269
+ return bar;
2270
+ }
2271
+
2272
+ function paintHeightRow(entry, row, open, selectable) {
2273
+ const key = heightEndKey(row);
2274
+ const item = document.createElement('li'); item.className = 'ai-chat-height-row';
2275
+ item.dataset.status = row.status;
2276
+ const instance = `${row.memberId} ${heightEndWord(row)}`;
2277
+ const idFor = (what) => `shell.chat-height-${what}#${entry.questionId} ${row.memberId} ${row.endWord}`;
2278
+ const sourceIdFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} ${row.memberId} ${row.endWord}${extra ? ` ${extra}` : ''}`;
2279
+ const labelLine = document.createElement('div'); labelLine.className = 'ai-chat-height-labelline';
2280
+ if (selectable) {
2281
+ labelLine.append(themedCheck(idFor('select'), instance, entry.selected.has(key), `Select ${row.label} to answer several ends at once`,
2282
+ entry.busy ? 'A height is still being saved — wait for it to finish' : null,
2283
+ (checked) => { if (checked) entry.selected.add(key); else entry.selected.delete(key); repaintHeightCard(entry); }));
2284
+ }
2285
+ const label = document.createElement('div'); label.className = 'ai-chat-height-label'; label.textContent = row.label;
2286
+ label.dataset.tip = row.label;
2287
+ labelLine.append(label);
2288
+ const meta = document.createElement('div'); meta.className = 'ai-chat-height-meta';
2289
+ meta.textContent = `${row.memberId} · ${heightEndWord(row)}`;
2290
+ item.append(labelLine, meta);
2291
+
2292
+ if (row.status === 'superseded') {
2293
+ const gone = document.createElement('div'); gone.className = 'ai-chat-height-answered';
2294
+ gone.textContent = 'Asked again in a newer question. This one no longer counts.';
2295
+ item.append(gone);
2296
+ return item;
2297
+ }
2298
+ const changing = entry.changing.has(key);
2299
+ if (row.answer && !changing) {
2300
+ const done = document.createElement('div'); done.className = 'ai-chat-height-answered';
2301
+ const picture = row.status === 'evidence';
2302
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-height-glyph'; glyph.textContent = picture ? '…' : '✓'; glyph.setAttribute('aria-hidden', 'true');
2303
+ const text = document.createElement('span'); text.textContent = picture ? 'Waiting for the read to read your picture' : heightAnswerText(row.answer);
2304
+ done.append(glyph, text);
2305
+ if (open) {
2306
+ 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);
2307
+ change.setAttribute('aria-label', picture ? `Answer the height for ${row.label} yourself instead` : `Change the height for ${row.label}`);
2308
+ change.addEventListener('click', () => {
2309
+ if (change.getAttribute('aria-disabled') === 'true') return;
2310
+ entry.changing.add(key);
2311
+ if (!entry.drafts.has(key) && row.answer.how === 'typed') entry.drafts.set(key, row.answer.typed);
2312
+ repaintHeightCard(entry);
2313
+ const card = ui.feed.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
2314
+ if (card) focusHeightControl(card, idFor('input'));
2315
+ });
2316
+ done.append(change);
2317
+ }
2318
+ item.append(done);
2319
+ const source = paintAnsweredSource(entry.requestId, row.answer, sourceIdFor, instance);
2320
+ if (source) item.append(source);
2321
+ return item;
2322
+ }
2323
+ if (!open) {
2324
+ const none = document.createElement('div'); none.className = 'ai-chat-height-answered'; none.textContent = 'No answer';
2325
+ item.append(none);
2326
+ return item;
2327
+ }
2328
+ const busyReason = entry.busy ? 'A height is still being saved — wait for it to finish' : null;
2329
+ if (row.proposed) {
2330
+ const proposal = document.createElement('div'); proposal.className = 'ai-chat-height-proposal';
2331
+ const value = document.createElement('span'); value.textContent = `Proposed ${row.proposed.asRead}`;
2332
+ const confirm = heightActionButton('Confirm', idFor('confirm'), instance, 'ai-chat-filter-apply', busyReason);
2333
+ confirm.setAttribute('aria-label', `Confirm ${row.proposed.asRead} for ${row.label}`);
2334
+ confirm.addEventListener('click', () => {
2335
+ if (confirm.getAttribute('aria-disabled') === 'true') return;
2336
+ submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value }], key);
2337
+ });
2338
+ proposal.append(value, confirm);
2339
+ item.append(proposal);
2340
+ if (row.fromEvidence) {
2341
+ // #1906 "see snap": the proposal is the READ's reading of the person's picture, said as such.
2342
+ const tag = document.createElement('div'); tag.className = 'ai-chat-setup-evidence';
2343
+ const t = document.createElement('span'); t.className = 'ai-chat-setup-tag'; t.textContent = 'THE READ’S READING OF YOUR PICTURE';
2344
+ tag.append(t, document.createTextNode(' Check it before you confirm.'));
2345
+ item.append(tag);
2346
+ }
2347
+ }
2348
+ const field = document.createElement('div'); field.className = 'ai-chat-height-field';
2349
+ const input = document.createElement('input');
2350
+ input.type = 'text'; input.className = 'ai-chat-height-input'; input.autocomplete = 'off'; input.spellcheck = false;
2351
+ input.dataset.commandId = idFor('input');
2352
+ input.dataset.commandInstanceLabel = instance;
2353
+ input.placeholder = entry.view?.units === 'mm' ? 'e.g. 4870 mm' : 'e.g. 15\'-11 3/4"';
2354
+ input.setAttribute('aria-label', `${row.proposed ? 'Or type the height' : 'Type the height'} for ${row.label}`);
2355
+ input.value = entry.drafts.get(key) || '';
2356
+ input.addEventListener('input', () => { entry.drafts.set(key, input.value); entry.rowErrors.delete(key); });
2357
+ if (busyReason) { input.readOnly = true; input.setAttribute('aria-disabled', 'true'); input.dataset.blockedReason = busyReason; }
2358
+ const use = heightActionButton('Use', idFor('use'), instance, row.proposed ? '' : 'ai-chat-filter-apply', busyReason);
2359
+ use.setAttribute('aria-label', `Use the typed height for ${row.label}`);
2360
+ const submitTyped = () => {
2361
+ if (use.getAttribute('aria-disabled') === 'true') return;
2362
+ const typed = input.value.trim();
2363
+ if (!typed) { entry.rowErrors.set(key, 'Type a height first.'); repaintHeightCard(entry); return; }
2364
+ submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'type', typed }], key);
2365
+ };
2366
+ input.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submitTyped(); } });
2367
+ use.addEventListener('click', submitTyped);
2368
+ field.append(input, use);
2369
+ item.append(field);
2370
+ item.append(paintAnswerSource(`h:${entry.questionId}:${key}`, {
2371
+ requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintHeightCard(entry), label: row.label, instance,
2372
+ idFor: sourceIdFor, inherited: row.inherited, busyReason, allowPictureOnly: true,
2373
+ onPictureOnly: () => submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'evidence' }], key),
2374
+ }));
2375
+ const rowError = document.createElement('p'); rowError.className = 'ai-chat-height-error'; rowError.setAttribute('role', 'alert');
2376
+ rowError.textContent = entry.rowErrors.get(key) || '';
2377
+ item.append(rowError);
2378
+ return item;
2379
+ }
2380
+
2381
+ /**
2382
+ * Answers carry the person's source note and pictures from the row's box, or from the bulk bar's when
2383
+ * several ends are answered at once (`sharedScope`).
2384
+ */
2385
+ async function submitHeightAnswers(entry, answers, rowKey, sharedScope) {
2386
+ if (entry.busy) return;
2387
+ const scopeOf = (answer) => sharedScope || `h:${entry.questionId}:${heightEndKey(answer)}`;
2388
+ const withSource = answers.map((answer) => ({ ...answer, ...answerSourcePayload(scopeOf(answer)) }));
2389
+ entry.busy = true; entry.cardError = ''; if (rowKey) entry.rowErrors.delete(rowKey);
2390
+ repaintHeightCard(entry);
2391
+ try {
2392
+ const result = await request(`/api/chat/height-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}/answers`, {
2393
+ method: 'POST', body: JSON.stringify({ chatId: entry.chatId, answers: withSource }),
2394
+ });
2395
+ entry.view = result.question;
2396
+ for (const answer of answers) {
2397
+ const key = heightEndKey(answer);
2398
+ entry.changing.delete(key); entry.drafts.delete(key); entry.selected.delete(key);
2399
+ clearAnswerSource(scopeOf(answer));
2400
+ }
2401
+ if (sharedScope) entry.bulkDraft = '';
2402
+ } catch (error) {
2403
+ let message = heightErrorText(error, 'FloLess could not save this height. Try again.');
2404
+ if (error?.code === 'answer-evidence-unknown') message = dropStaleAnswerFiles([...new Set(answers.map(scopeOf))], entry);
2405
+ // Dropped, not kept: a reload that fails must show its own error and Try again, which only an
2406
+ // empty card does — an old view would hide both behind rows that are out of date.
2407
+ if (HEIGHT_STALE.has(error?.code)) { entry.cardError = message; entry.view = null; loadHeightQuestion(entry); }
2408
+ else if (rowKey) entry.rowErrors.set(rowKey, message);
2409
+ else entry.cardError = message;
2410
+ } finally {
2411
+ entry.busy = false;
2412
+ repaintHeightCard(entry);
2413
+ settlePendingReload(entry, loadHeightQuestion);
2414
+ focusNextHeightControl(entry);
2415
+ }
2416
+ }
2417
+
2418
+ // After an answer, keyboard focus moves to the next row still waiting, or to Tell the read.
2419
+ function focusNextHeightControl(entry) {
2420
+ const card = ui.feed?.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
2421
+ if (!card || (document.activeElement && card.contains(document.activeElement) && document.activeElement.tagName === 'INPUT')) return;
2422
+ const target = card.querySelector('.ai-chat-height-row[data-status="open"] button, .ai-chat-height-row[data-status="open"] input')
2423
+ || card.querySelector('[data-command-id^="shell.chat-height-tell-read"]');
2424
+ target?.focus({ preventScroll: true });
2425
+ }
2426
+
2427
+ const heightTellText = (entry) => `I've answered height question ${entry.view?.n ?? ''}.`.replace(' .', '.');
2428
+
2429
+ /*
2430
+ * TELL THE READ puts one short message in the composer and moves focus to Send; the PERSON sends it
2431
+ * (owner ruling 2026-10-02). The card never claims a delivery: the chat's own send, its delivery states
2432
+ * and its Retry are the truth about that. Two review rounds found that every way of inferring delivery
2433
+ * from here could still say "Sent" for a message that was not.
2434
+ */
2435
+ function tellReadHeightsAnswered(entry) {
2436
+ tellReadAnswered(entry, heightTellText(entry), repaintHeightCard);
2437
+ }
2438
+
2439
+ /*
2440
+ * #1906 — WHERE AN ANSWER CAME FROM: the person's source note and pictures, on any question card.
2441
+ *
2442
+ * Owner rulings 2026-10-02: "would still be beneficial to attach pictures etc like in chat" and "so i
2443
+ * still can answer see snap?". Each answerable row (and the height card's bulk bar) has one source box,
2444
+ * keyed by `scope`, kept across repaints like everything else on a card. A picture is uploaded at once
2445
+ * through the person-only route, so the server can tell it is the person's; it counts only when the
2446
+ * answer it rides on is recorded, and it can be removed until then.
2447
+ */
2448
+ const answerSources = new Map();
2449
+ const MAX_ANSWER_FILES = 3;
2450
+ const ANSWER_FILE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
2451
+ const PAPERCLIP = 'm16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551';
2452
+
2453
+ function answerSource(scope) {
2454
+ let source = answerSources.get(scope);
2455
+ if (!source) { source = { open: false, note: '', files: [], uploading: 0, error: '' }; answerSources.set(scope, source); }
2456
+ return source;
2457
+ }
2458
+ /** What an answer carries from its source box: the note and the uploaded files' ids. */
2459
+ function answerSourcePayload(scope) {
2460
+ const source = answerSources.get(scope);
2461
+ if (!source) return {};
2462
+ const note = source.note.trim();
2463
+ return { ...(note ? { note } : {}), ...(source.files.length ? { evidence: source.files.map((file) => file.attachmentId) } : {}) };
2464
+ }
2465
+ const MAX_ANSWER_NOTE = 160;
2466
+ /**
2467
+ * An answer plus its source box. A "No single level" / "None of these" answer carries the person's
2468
+ * REQUIRED reason in `note`; a source note never replaces it (Codex review #1906) — both are kept, the
2469
+ * reason first, so the record says what the person typed in each place.
2470
+ */
2471
+ function withAnswerSource(answer, source) {
2472
+ if (!answer.note || !source.note) return { ...answer, ...source };
2473
+ return { ...answer, ...source, note: `${answer.note} (source: ${source.note})` };
2474
+ }
2475
+
2476
+ /** After the answer is recorded the files belong to it: forget the box, keep nothing to remove. */
2477
+ function clearAnswerSource(scope) {
2478
+ const source = answerSources.get(scope);
2479
+ if (!source) return;
2480
+ for (const file of source.files) if (file.url) URL.revokeObjectURL(file.url);
2481
+ answerSources.delete(scope);
2482
+ }
2483
+ const evidenceUrl = (requestId, attachmentId) => `/api/chat/answer-evidence/${encodeURIComponent(requestId)}/${encodeURIComponent(attachmentId)}`;
2484
+
2485
+ async function attachAnswerFiles(scope, ctx, files) {
2486
+ const source = answerSource(scope);
2487
+ const incoming = [...files];
2488
+ if (!incoming.length) return;
2489
+ source.error = '';
2490
+ if (source.files.length + incoming.length > MAX_ANSWER_FILES) {
2491
+ source.error = `An answer can carry at most ${MAX_ANSWER_FILES} files. Remove one first.`;
2492
+ ctx.repaint(); return;
2493
+ }
2494
+ const refused = incoming.find((file) => !ANSWER_FILE_TYPES.has(file.type));
2495
+ if (refused) {
2496
+ source.error = `“${refused.name}” can’t be attached to an answer. Attach a picture (PNG, JPEG or WebP) or a PDF.`;
2497
+ ctx.repaint(); return;
2498
+ }
2499
+ for (const file of incoming) {
2500
+ source.uploading += 1; ctx.repaint();
2501
+ try {
2502
+ const data = await fileBase64(file);
2503
+ const result = await request(`/api/chat/answer-evidence/${encodeURIComponent(ctx.requestId)}`, {
2504
+ method: 'POST', timeoutMs: 120000,
2505
+ body: JSON.stringify({ chatId: ctx.chatId, fileName: file.name || 'screenshot.png', mediaType: file.type, data }),
2506
+ });
2507
+ const ref = result.evidence;
2508
+ source.files.push({ ...ref, url: file.type.startsWith('image/') ? URL.createObjectURL(file) : '' });
2509
+ } catch (error) {
2510
+ source.error = error?.message || `FloLess could not attach “${file.name}”. Try again.`;
2511
+ } finally {
2512
+ source.uploading -= 1; ctx.repaint();
2513
+ }
2514
+ }
2515
+ }
2516
+
2517
+ async function removeAnswerFile(scope, ctx, file) {
2518
+ const source = answerSource(scope);
2519
+ const drop = () => {
2520
+ source.files = source.files.filter((row) => row.attachmentId !== file.attachmentId);
2521
+ if (file.url) URL.revokeObjectURL(file.url);
2522
+ source.error = '';
2523
+ };
2524
+ try {
2525
+ await request(evidenceUrl(ctx.requestId, file.attachmentId), { method: 'DELETE', body: JSON.stringify({ chatId: ctx.chatId }) });
2526
+ drop();
2527
+ } catch (error) {
2528
+ // Already gone on the server (review #1906): the chip goes too, or it would ride on every later
2529
+ // answer and be refused each time, with the paperclip stuck at the file limit.
2530
+ if (error?.code === 'answer-evidence-unknown') drop();
2531
+ else source.error = error?.message || 'FloLess could not remove that file. Try again.';
2532
+ }
2533
+ ctx.repaint();
2534
+ }
2535
+
2536
+ /**
2537
+ * An answer was refused because a picture on it is no longer waiting to be used (review #1906). Take
2538
+ * those pictures off the answer — asking the server to release each one, so none keeps holding the
2539
+ * conversation's file budget — and say in words that they must be attached again. Returns the sentence.
2540
+ */
2541
+ function dropStaleAnswerFiles(scopes, entry) {
2542
+ for (const scope of scopes) {
2543
+ const source = answerSources.get(scope);
2544
+ if (!source?.files.length) continue;
2545
+ for (const file of source.files) {
2546
+ request(evidenceUrl(entry.requestId, file.attachmentId), { method: 'DELETE', body: JSON.stringify({ chatId: entry.chatId }) })
2547
+ .catch((error) => { if (error?.code !== 'answer-evidence-unknown') console.warn('[chat] an unused answer picture could not be released', file.attachmentId, error?.message); });
2548
+ if (file.url) URL.revokeObjectURL(file.url);
2549
+ }
2550
+ source.files = [];
2551
+ source.open = true;
2552
+ }
2553
+ return 'A picture on this answer was attached too long ago (or FloLess restarted), so it can no longer be used. It has been taken off: attach it again, then answer.';
2554
+ }
2555
+
2556
+ /**
2557
+ * A recorded picture the browser could not show: ask the server why, so the chip says the truth —
2558
+ * "no longer available" only when the file really is gone or changed (410), and the server's own
2559
+ * sentence for anything else (a signed-out session, a busy record, a stopped server) (review #1906).
2560
+ */
2561
+ async function explainMissingPicture(url, slot) {
2562
+ let text = 'could not be shown just now';
2563
+ try {
2564
+ const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store' });
2565
+ if (response.status === 410) text = 'no longer available';
2566
+ else if (!response.ok) {
2567
+ const body = (response.headers.get('content-type') || '').includes('application/json') ? await response.json().catch(() => null) : null;
2568
+ text = body?.error ? `could not be shown: ${body.error}` : `could not be shown (FloLess answered ${response.status})`;
2569
+ }
2570
+ } catch { text = 'could not be shown: FloLess did not answer. Make sure it is still running.'; }
2571
+ slot.textContent = text;
2572
+ slot.dataset.missing = text === 'no longer available' ? 'gone' : 'error';
2573
+ }
2574
+
2575
+ /** One recorded picture as a chip: thumbnail for a picture, its name, and a button that opens it. */
2576
+ function answerPictureChip(requestId, ref, commandId, instance) {
2577
+ const chip = document.createElement('span'); chip.className = 'ai-chat-attachment ai-chat-answer-picture';
2578
+ if (ref.mediaType.startsWith('image/')) {
2579
+ const preview = document.createElement('img'); preview.alt = ''; preview.loading = 'lazy';
2580
+ preview.src = evidenceUrl(requestId, ref.attachmentId);
2581
+ // A picture the browser cannot show becomes the server's reason, never a broken image (review #1906).
2582
+ preview.addEventListener('error', () => {
2583
+ const slot = Object.assign(document.createElement('span'), { className: 'ai-chat-answer-missing', textContent: 'checking…' });
2584
+ slot.setAttribute('role', 'status');
2585
+ preview.replaceWith(slot);
2586
+ explainMissingPicture(preview.src, slot);
2587
+ }, { once: true });
2588
+ chip.append(preview);
2589
+ }
2590
+ const open = button(ref.fileName, commandId, 'ai-chat-answer-open');
2591
+ open.dataset.commandInstanceLabel = instance;
2592
+ open.dataset.tip = `Open ${ref.fileName}`;
2593
+ open.setAttribute('aria-label', `Open ${ref.fileName}`);
2594
+ open.addEventListener('click', () => { window.open(evidenceUrl(requestId, ref.attachmentId), '_blank', 'noopener'); });
2595
+ chip.append(open);
2596
+ return chip;
2597
+ }
2598
+
2599
+ /**
2600
+ * The "+ Add source" disclosure: a one-line note, a paperclip that works like the composer's (pick,
2601
+ * paste or drop), and the files as removable chips. `ctx` is { requestId, chatId, repaint, label,
2602
+ * instance, idFor, inherited, allowPictureOnly, onPictureOnly, busyReason }.
2603
+ */
2604
+ function paintAnswerSource(scope, ctx) {
2605
+ const source = answerSource(scope);
2606
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-answer-source';
2607
+ if (ctx.inherited?.length) {
2608
+ const kept = document.createElement('div'); kept.className = 'ai-chat-answer-files';
2609
+ const lead = document.createElement('span'); lead.className = 'ai-chat-answer-lead'; lead.textContent = 'Your picture';
2610
+ kept.append(lead, ...ctx.inherited.map((ref) => answerPictureChip(ctx.requestId, ref, ctx.idFor('picture-open', ref.attachmentId), ctx.instance)));
2611
+ wrap.append(kept);
2612
+ }
2613
+ const hasDraft = source.open || source.note || source.files.length || source.uploading;
2614
+ if (!hasDraft) {
2615
+ const add = button('+ Add source', ctx.idFor('source'), 'ai-chat-answer-add');
2616
+ add.dataset.commandInstanceLabel = ctx.instance;
2617
+ add.setAttribute('aria-label', `Add a source note or picture for ${ctx.label}`);
2618
+ add.dataset.tip = 'Say where your answer comes from: a note like “per 7/S-502”, or a screenshot or PDF';
2619
+ add.addEventListener('click', () => {
2620
+ source.open = true; ctx.repaint();
2621
+ [...(ui.feed?.querySelectorAll('[data-command-id]') || [])].find((node) => node.dataset.commandId === ctx.idFor('note'))?.focus({ preventScroll: true });
2622
+ });
2623
+ wrap.append(add);
2624
+ return wrap;
2625
+ }
2626
+ const box = document.createElement('div'); box.className = 'ai-chat-answer-box';
2627
+ const line = document.createElement('div'); line.className = 'ai-chat-answer-line';
2628
+ const note = document.createElement('input');
2629
+ note.type = 'text'; note.className = 'ai-chat-height-input ai-chat-answer-note'; note.maxLength = 160; note.autocomplete = 'off';
2630
+ note.placeholder = 'Source, e.g. per 7/S-502 (optional)';
2631
+ note.dataset.commandId = ctx.idFor('note'); note.dataset.commandInstanceLabel = ctx.instance;
2632
+ note.setAttribute('aria-label', `Source note for ${ctx.label}`);
2633
+ note.value = source.note;
2634
+ note.addEventListener('input', () => { source.note = note.value; });
2635
+ const clip = document.createElement('button');
2636
+ clip.type = 'button'; clip.className = 'ai-chat-answer-clip';
2637
+ clip.dataset.commandId = ctx.idFor('attach'); clip.dataset.commandInstanceLabel = ctx.instance;
2638
+ clip.dataset.tip = 'Attach a screenshot or PDF (you can also paste or drop it here)';
2639
+ clip.setAttribute('aria-label', `Attach a screenshot or PDF to the answer for ${ctx.label}`);
2640
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2641
+ svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true'); svg.setAttribute('focusable', 'false');
2642
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', PAPERCLIP);
2643
+ svg.append(path); clip.append(svg);
2644
+ const picker = document.createElement('input');
2645
+ picker.type = 'file'; picker.multiple = true; picker.hidden = true; picker.accept = 'image/png,image/jpeg,image/webp,application/pdf';
2646
+ picker.dataset.commandId = ctx.idFor('attach-input'); picker.dataset.commandInstanceLabel = ctx.instance;
2647
+ picker.addEventListener('change', () => { const files = [...picker.files]; picker.value = ''; attachAnswerFiles(scope, ctx, files); });
2648
+ clip.addEventListener('click', () => picker.click());
2649
+ if (ctx.busyReason || source.files.length >= MAX_ANSWER_FILES) {
2650
+ const why = ctx.busyReason || `An answer can carry at most ${MAX_ANSWER_FILES} files`;
2651
+ clip.setAttribute('aria-disabled', 'true'); clip.dataset.blockedReason = why; clip.dataset.tip = why;
2652
+ clip.onclick = (event) => event.stopImmediatePropagation();
2653
+ }
2654
+ line.append(note, clip, picker);
2655
+ box.append(line);
2656
+ // Paste and drop, like the composer: a screenshot pasted while this box has focus attaches to the answer.
2657
+ box.addEventListener('paste', (event) => {
2658
+ const files = [...(event.clipboardData?.files || [])];
2659
+ if (files.length) { event.preventDefault(); attachAnswerFiles(scope, ctx, files); }
2660
+ });
2661
+ box.addEventListener('dragover', (event) => { if (event.dataTransfer?.types?.includes('Files')) { event.preventDefault(); box.classList.add('drop'); } });
2662
+ box.addEventListener('dragleave', () => box.classList.remove('drop'));
2663
+ box.addEventListener('drop', (event) => {
2664
+ box.classList.remove('drop');
2665
+ const files = [...(event.dataTransfer?.files || [])];
2666
+ if (files.length) { event.preventDefault(); attachAnswerFiles(scope, ctx, files); }
2667
+ });
2668
+ if (source.files.length || source.uploading) {
2669
+ const chips = document.createElement('div'); chips.className = 'ai-chat-answer-files';
2670
+ for (const file of source.files) {
2671
+ const chip = document.createElement('span'); chip.className = 'ai-chat-attachment';
2672
+ if (file.url) { const img = document.createElement('img'); img.alt = ''; img.src = file.url; chip.append(img); }
2673
+ const name = document.createElement('span'); name.textContent = file.fileName;
2674
+ const remove = button('×', ctx.idFor('picture-remove', file.attachmentId));
2675
+ remove.dataset.commandInstanceLabel = file.fileName;
2676
+ remove.setAttribute('aria-label', `Remove ${file.fileName} from this answer`);
2677
+ remove.dataset.tip = 'Remove from this answer';
2678
+ remove.addEventListener('click', () => removeAnswerFile(scope, ctx, file));
2679
+ chip.append(name, remove); chips.append(chip);
2680
+ }
2681
+ if (source.uploading) {
2682
+ const busy = document.createElement('span'); busy.className = 'ai-chat-answer-lead'; busy.setAttribute('role', 'status');
2683
+ busy.textContent = 'Attaching…';
2684
+ chips.append(busy);
2685
+ }
2686
+ box.append(chips);
2687
+ }
2688
+ if (ctx.allowPictureOnly && source.files.length && !source.uploading) {
2689
+ const only = button('Answer with the picture', ctx.idFor('picture-only'), 'ai-chat-answer-picture-only');
2690
+ only.dataset.commandInstanceLabel = ctx.instance;
2691
+ only.setAttribute('aria-label', `Answer ${ctx.label} with the picture only, and let the read read it`);
2692
+ only.dataset.tip = 'The read looks at your picture and asks this row again with what it reads; you confirm the number';
2693
+ if (ctx.busyReason) { only.setAttribute('aria-disabled', 'true'); only.dataset.blockedReason = ctx.busyReason; }
2694
+ only.addEventListener('click', () => { if (only.getAttribute('aria-disabled') !== 'true') ctx.onPictureOnly(); });
2695
+ box.append(only);
2696
+ }
2697
+ const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert');
2698
+ error.textContent = source.error || '';
2699
+ box.append(error);
2700
+ wrap.append(box);
2701
+ return wrap;
2702
+ }
2703
+
2704
+ /** The person's note and pictures on a recorded answer, shown under it. */
2705
+ function paintAnsweredSource(requestId, answer, idFor, instance) {
2706
+ // A "none" answer's note is its reason, already the answer's own line: it is not repeated as a source.
2707
+ const note = answer?.how === 'none' ? '' : answer?.note;
2708
+ if (!note && !answer?.evidence?.length) return null;
2709
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-answer-files ai-chat-answered-source';
2710
+ if (note) { const line = document.createElement('span'); line.className = 'ai-chat-answer-lead'; line.textContent = note; wrap.append(line); }
2711
+ for (const ref of answer.evidence || []) wrap.append(answerPictureChip(requestId, ref, idFor('picture-open', ref.attachmentId), instance));
2712
+ return wrap;
2713
+ }
2714
+
2715
+ /*
2716
+ * TELL THE READ, shared by the height and setup cards (#1882's click-time rule, unchanged): it puts one
2717
+ * short message in the composer and moves focus to Send; the PERSON sends it.
2718
+ */
2719
+ function tellReadAnswered(entry, text, repaint) {
2720
+ if (!ui.input) return;
2721
+ const held = ui.input.value.trim();
2722
+ if (held === text && !state.attachments.length) {
2723
+ if (entry.cardError) { entry.cardError = ''; repaint(entry); }
2724
+ ui.send?.focus({ preventScroll: true });
2725
+ return;
2726
+ }
2727
+ if (held || state.attachments.length) {
2728
+ entry.cardError = 'Send or clear the message you are writing first, then press Tell the read again.';
2729
+ repaint(entry);
2730
+ return;
2731
+ }
2732
+ entry.cardError = '';
2733
+ ui.input.value = text;
2734
+ saveDraftSoon();
2735
+ updateSendState();
2736
+ repaint(entry);
2737
+ ui.send?.focus({ preventScroll: true });
2738
+ }
2739
+
2740
+ /*
2741
+ * #1906 — THE READ SETUP CARD: each plan view's scale, the model origin and each plan view's level,
2742
+ * answered by the person on one card. Painted from the server's own record (the chat event carries
2743
+ * only ids); Confirm, Use and the rest post to a route only this window can reach. The read must then
2744
+ * use exactly what is settled here, and asks again on a new card if anything conflicts.
2745
+ */
2746
+ const setupCards = new Map();
2747
+ const SETUP_STALE = new Set(['setup-question-changed', 'height-question-closed', 'setup-question-superseded', 'setup-answer-frozen']);
2748
+ const SETUP_SECTIONS = [['scale', 'Drawing scale'], ['origin', 'Model origin'], ['level', 'Plan levels']];
2749
+
2750
+ function setupCardState(requestId, questionId, chatId) {
2751
+ const key = `${requestId}/${questionId}`;
2752
+ let entry = setupCards.get(key);
2753
+ if (!entry) {
2754
+ entry = { key, requestId, questionId, chatId, view: null, loading: false, loadError: '', drafts: new Map(), changing: new Set(),
2755
+ rowErrors: new Map(), cardError: '', busy: false, expanded: new Map(), originPick: null, noneOpen: new Set(), bodyScroll: 0 };
2756
+ setupCards.set(key, entry);
2757
+ }
2758
+ return entry;
2759
+ }
2760
+
2761
+ function loadSetupQuestion(entry) {
2762
+ if (entry.loading) return;
2763
+ entry.loading = true;
2764
+ request(`/api/chat/setup-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}?${new URLSearchParams({ chatId: entry.chatId || '' })}`)
2765
+ .then((result) => { if (result?.readClosed) { entry.finished = true; entry.view = null; } else entry.view = result.question; entry.loadError = ''; })
2766
+ .catch((error) => {
2767
+ if (CARD_READ_FINISHED.has(error?.code)) { entry.finished = true; entry.loadError = ''; return; }
2768
+ entry.loadError = heightErrorText(error, 'FloLess could not load the read setup.');
2769
+ })
2770
+ .finally(() => { entry.loading = false; repaintSetupCard(entry); settlePendingReload(entry, loadSetupQuestion); });
2771
+ }
2772
+
2773
+ function repaintSetupCard(entry) {
2774
+ const old = ui.feed?.querySelector(`[data-setup-question="${CSS.escape(entry.key)}"]`);
2775
+ if (!old) return;
2776
+ const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
2777
+ const next = paintSetupCard(entry, old.dataset.eventId, old.dataset.eventSequence);
2778
+ old.replaceWith(next);
2779
+ if (focused) focusHeightControl(next, focused);
2780
+ }
2781
+
2782
+ function renderSetupQuestion(event) {
2783
+ const payload = event.payload || {};
2784
+ const entry = setupCardState(String(payload.requestId || ''), String(payload.questionId || ''), String(event.chatId || state.chat?.chatId || ''));
2785
+ if (!entry.view && !entry.loadError && !entry.finished) {
2786
+ if (!entry.loading) refreshEarlierCards(setupCards, entry, loadSetupQuestion);
2787
+ loadSetupQuestion(entry);
2788
+ }
2789
+ return paintSetupCard(entry, event.eventId, String(event.sequence));
2790
+ }
2791
+
2792
+ const setupSettled = (row) => row.status === 'settled';
2793
+ const setupLive = (row) => row.status !== 'superseded';
2794
+ const scaleTag = { floless: 'FLOLESS FIT', 'floless-candidate': 'FLOLESS CANDIDATE', read: 'THE READ’S MEASUREMENT', 'read-of-picture': 'THE READ’S READING OF YOUR PICTURE' };
2795
+ const levelTag = { 'drawing-text': 'ON THE DRAWING', 'drawing-picture': 'READ OFF THE PICTURE · NOT CHECKED', 'read-of-picture': 'THE READ’S READING OF YOUR PICTURE' };
2796
+ const originText = (o) => `${o.xLabel}/${o.yLabel}`;
2797
+ const viewName = (row) => `${row.view.sheet}${row.view.title ? ` · ${row.view.title}` : ''}`;
2798
+
2799
+ function setupAnswerText(row) {
2800
+ const a = row.answer;
2801
+ if (!a) return '';
2802
+ if (row.kind === 'origin') {
2803
+ if (a.how === 'none') return `None of these: ${a.note}`;
2804
+ return `${originText(a.origin)}${a.origin.pickedAs ? ` (you picked ${a.origin.pickedAs})` : ''}${a.how === 'typed' ? ', typed' : ''}`;
2805
+ }
2806
+ if (a.how === 'none') return `No single level: ${a.note}`;
2807
+ if (a.how === 'typed') return `You typed ${a.typed}`;
2808
+ return `Confirmed ${a.shownAs}${a.basis === 'read-of-your-picture' ? ', the read’s reading of your picture' : ''}`;
2809
+ }
2810
+
2811
+ function paintSetupCard(entry, eventId, sequence) {
2812
+ const view = entry.view;
2813
+ const card = document.createElement('section');
2814
+ card.className = 'ai-chat-filter-card ai-chat-height-card ai-chat-setup-card';
2815
+ card.dataset.setupQuestion = entry.key;
2816
+ card.dataset.eventId = eventId || '';
2817
+ card.dataset.eventSequence = sequence || '';
2818
+ card.setAttribute('aria-label', view?.n ? `Read setup, question ${view.n}` : 'Read setup');
2819
+ const rows = view ? view.items : [];
2820
+ const live = rows.filter(setupLive);
2821
+ const settled = live.filter(setupSettled);
2822
+ const open = Boolean(view?.open);
2823
+ const allSettled = live.length > 0 && settled.length === live.length;
2824
+ // Every row the person can answer is answered, but some wait on the READ (a picture to read, or new
2825
+ // choices to offer): the person still has to tell it, or the read never looks (E2E #1906).
2826
+ const waitsOnRead = (row) => row.status === 'picture' || row.status === 'needs-new-choices';
2827
+ const allAnswered = !allSettled && live.length > 0 && live.every((row) => setupSettled(row) || waitsOnRead(row));
2828
+ card.dataset.state = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allSettled ? 'answered' : allAnswered ? 'waiting-for-read' : 'open';
2829
+
2830
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
2831
+ const title = document.createElement('strong'); title.textContent = 'Read setup';
2832
+ const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state';
2833
+ chip.textContent = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allSettled ? 'settled' : allAnswered ? 'with the read' : 'needs you';
2834
+ head.append(title, chip);
2835
+ card.append(head);
2836
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
2837
+ note.textContent = !view
2838
+ ? (entry.finished ? CARD_FINISHED_TEXT : entry.loadError || 'Loading the read setup…')
2839
+ : open
2840
+ ? 'These shape the whole model: each plan’s drawing scale, the model origin and each plan’s level. Only you can answer, and the read uses exactly what you settle here. If something conflicts, it asks you again here.'
2841
+ : 'This read is no longer waiting for an answer.';
2842
+ card.append(note);
2843
+ if (!view) {
2844
+ if (entry.loadError) {
2845
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2846
+ const retry = heightActionButton('Try again', `shell.chat-setup-retry#${entry.questionId}`, 'the read setup', '');
2847
+ retry.addEventListener('click', () => { entry.loadError = ''; repaintSetupCard(entry); loadSetupQuestion(entry); });
2848
+ actions.append(retry); card.append(actions);
2849
+ }
2850
+ return card;
2851
+ }
2852
+ const questionLabel = `setup question ${view.n}`;
2853
+ const count = document.createElement('p'); count.className = 'ai-chat-height-count'; count.setAttribute('aria-live', 'polite'); count.setAttribute('aria-atomic', 'true');
2854
+ count.textContent = `${settled.length} of ${live.length} settled`;
2855
+ card.append(count);
2856
+
2857
+ const body = document.createElement('div'); body.className = 'ai-chat-height-rows ai-chat-setup-body';
2858
+ body.setAttribute('role', 'region'); body.setAttribute('aria-label', 'Read setup questions'); body.tabIndex = 0;
2859
+ body.dataset.commandId = `shell.chat-setup-body#${entry.questionId}`;
2860
+ body.dataset.commandInstanceLabel = questionLabel;
2861
+ for (const [kind, name] of SETUP_SECTIONS) {
2862
+ const items = rows.filter((row) => row.kind === kind);
2863
+ if (!items.length) continue;
2864
+ body.append(paintSetupSection(entry, kind, name, items, open));
2865
+ }
2866
+ card.append(body);
2867
+ body.addEventListener('scroll', () => { entry.bodyScroll = body.scrollTop; }, { passive: true });
2868
+ if (entry.bodyScroll) requestAnimationFrame(() => { if (body.isConnected) body.scrollTop = entry.bodyScroll; });
2869
+
2870
+ const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert');
2871
+ error.textContent = entry.cardError || '';
2872
+ card.append(error);
2873
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2874
+ if (open && (allSettled || allAnswered)) {
2875
+ const done = document.createElement('p'); done.className = 'ai-chat-height-done';
2876
+ done.textContent = allSettled
2877
+ ? 'All settled. Press Tell the read, then Send, so the AI can carry on.'
2878
+ : 'All answered. Press Tell the read, then Send: the read looks at what you sent and asks you to confirm its reading here.';
2879
+ card.append(done);
2880
+ const tell = heightActionButton('Tell the read', `shell.chat-setup-tell-read#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', null);
2881
+ tell.addEventListener('click', () => tellReadAnswered(entry, `I've answered setup question ${view.n}.`, repaintSetupCard));
2882
+ actions.append(tell);
2883
+ }
2884
+ actions.hidden = !actions.childNodes.length;
2885
+ card.append(actions);
2886
+ return card;
2887
+ }
2888
+
2889
+ function paintSetupSection(entry, kind, name, items, open) {
2890
+ const section = document.createElement('div'); section.className = 'ai-chat-setup-section';
2891
+ const live = items.filter(setupLive);
2892
+ const settled = live.filter(setupSettled).length;
2893
+ // The first section with something open starts expanded; a settled one collapses to one line.
2894
+ const expanded = entry.expanded.has(kind) ? entry.expanded.get(kind) : (settled < live.length || !open);
2895
+ const toggle = document.createElement('button');
2896
+ toggle.type = 'button'; toggle.className = 'ai-chat-setup-section-head';
2897
+ toggle.dataset.commandId = `shell.chat-setup-section#${entry.questionId} ${kind}`;
2898
+ toggle.dataset.commandInstanceLabel = name;
2899
+ toggle.setAttribute('aria-expanded', String(expanded));
2900
+ const label = document.createElement('span'); label.textContent = name;
2901
+ const tally = document.createElement('span'); tally.className = 'ai-chat-filter-state';
2902
+ tally.textContent = settled === live.length ? '✓ settled' : `${settled}/${live.length}`;
2903
+ toggle.append(label, tally);
2904
+ toggle.addEventListener('click', () => { entry.expanded.set(kind, !expanded); repaintSetupCard(entry); });
2905
+ section.append(toggle);
2906
+ if (!expanded) {
2907
+ const summary = document.createElement('p'); summary.className = 'ai-chat-setup-summary';
2908
+ summary.textContent = live.map((row) => `${row.kind === 'origin' ? 'Origin' : row.view.sheet} ${setupAnswerText(row) || 'open'}`).join(' · ');
2909
+ section.append(summary);
2910
+ return section;
2911
+ }
2912
+ const list = document.createElement('ol'); list.className = 'ai-chat-setup-list';
2913
+ for (const row of items) list.append(paintSetupRow(entry, row, open));
2914
+ section.append(list);
2915
+ return section;
2916
+ }
2917
+
2918
+ function setupConflictBanner(row) {
2919
+ if (!row.conflict) return null;
2920
+ const box = document.createElement('div'); box.className = 'ai-chat-setup-conflict';
2921
+ if (row.earlier) {
2922
+ const earlier = document.createElement('div');
2923
+ earlier.textContent = `You answered ${setupAnswerText({ ...row, answer: row.earlier })}.`;
2924
+ box.append(earlier);
2925
+ }
2926
+ const why = document.createElement('div');
2927
+ const lead = document.createElement('span'); lead.className = 'ai-chat-setup-conflict-lead'; lead.textContent = 'The read says: ';
2928
+ why.append(lead, document.createTextNode(row.conflict));
2929
+ box.append(why);
2930
+ return box;
2931
+ }
2932
+
2933
+ function paintSetupRow(entry, row, open) {
2934
+ const item = document.createElement('li'); item.className = 'ai-chat-height-row ai-chat-setup-row';
2935
+ item.dataset.status = row.status;
2936
+ item.dataset.key = row.key;
2937
+ const name = row.kind === 'origin' ? 'Model origin' : viewName(row);
2938
+ const instance = row.kind === 'origin' ? 'the model origin' : `${row.kind === 'scale' ? 'the scale of' : 'the level of'} ${viewName(row)}`;
2939
+ const idFor = (what, extra) => `shell.chat-setup-${what}#${entry.questionId} ${row.key}${extra ? ` ${extra}` : ''}`;
2940
+ const sourceIdFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} ${row.key}${extra ? ` ${extra}` : ''}`;
2941
+ if (row.kind !== 'origin') {
2942
+ const label = document.createElement('div'); label.className = 'ai-chat-height-label'; label.textContent = name; label.dataset.tip = name;
2943
+ item.append(label);
2944
+ }
2945
+ const banner = setupConflictBanner(row);
2946
+ if (banner) item.append(banner);
2947
+
2948
+ if (row.status === 'superseded') {
2949
+ const gone = document.createElement('div'); gone.className = 'ai-chat-height-answered';
2950
+ gone.textContent = 'Asked again in a newer question. This one no longer counts.';
2951
+ item.append(gone);
2952
+ return item;
2953
+ }
2954
+ const changing = entry.changing.has(row.key);
2955
+ if (row.answer && !changing && row.status !== 'picture') {
2956
+ const done = document.createElement('div'); done.className = 'ai-chat-height-answered';
2957
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-height-glyph'; glyph.textContent = row.status === 'settled' ? '✓' : '…'; glyph.setAttribute('aria-hidden', 'true');
2958
+ const text = document.createElement('span');
2959
+ text.textContent = row.status === 'needs-new-choices' ? `${setupAnswerText(row)}. Waiting for the read to offer other points.` : setupAnswerText(row);
2960
+ done.append(glyph, text);
2961
+ if (open && !row.frozen) {
2962
+ const change = heightActionButton('Change', idFor('change'), instance, 'ai-chat-height-change', entry.busy ? 'An answer is still being saved — wait for it to finish' : null);
2963
+ change.setAttribute('aria-label', `Change your answer for ${instance}`);
2964
+ change.addEventListener('click', () => {
2965
+ if (change.getAttribute('aria-disabled') === 'true') return;
2966
+ entry.changing.add(row.key);
2967
+ // A "none" answer's note is the person's REASON, not a source: it is not put in the source box.
2968
+ if (row.answer.note && row.answer.how !== 'none') { const source = answerSource(`s:${entry.questionId}:${row.key}`); source.open = true; source.note = source.note || row.answer.note; }
2969
+ repaintSetupCard(entry);
2970
+ });
2971
+ done.append(change);
2972
+ }
2973
+ item.append(done);
2974
+ const source = paintAnsweredSource(entry.requestId, row.answer, sourceIdFor, instance);
2975
+ if (source) item.append(source);
2976
+ if (row.frozen) { const frozen = document.createElement('p'); frozen.className = 'ai-chat-setup-frozen'; frozen.textContent = row.frozen; item.append(frozen); }
2977
+ return item;
2978
+ }
2979
+ if (row.status === 'picture' && !changing) {
2980
+ const wait = document.createElement('div'); wait.className = 'ai-chat-height-answered';
2981
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-height-glyph'; glyph.textContent = '…'; glyph.setAttribute('aria-hidden', 'true');
2982
+ const text = document.createElement('span'); text.textContent = 'Waiting for the read to read your picture';
2983
+ wait.append(glyph, text);
2984
+ if (open) {
2985
+ const change = heightActionButton('Answer now', idFor('change'), instance, 'ai-chat-height-change', null);
2986
+ change.setAttribute('aria-label', `Answer ${instance} yourself instead`);
2987
+ change.addEventListener('click', () => { entry.changing.add(row.key); repaintSetupCard(entry); });
2988
+ wait.append(change);
2989
+ }
2990
+ item.append(wait);
2991
+ const source = paintAnsweredSource(entry.requestId, row.answer, sourceIdFor, instance);
2992
+ if (source) item.append(source);
2993
+ return item;
2994
+ }
2995
+ if (!open) {
2996
+ const none = document.createElement('div'); none.className = 'ai-chat-height-answered'; none.textContent = 'No answer';
2997
+ item.append(none);
2998
+ return item;
2999
+ }
3000
+ if (row.frozen) { const frozen = document.createElement('p'); frozen.className = 'ai-chat-setup-frozen'; frozen.textContent = row.frozen; item.append(frozen); return item; }
3001
+ const busyReason = entry.busy ? 'An answer is still being saved — wait for it to finish' : null;
3002
+ const scope = `s:${entry.questionId}:${row.key}`;
3003
+ if (row.kind === 'scale') paintScaleControls(entry, row, item, instance, idFor, busyReason, scope);
3004
+ else if (row.kind === 'level') paintLevelControls(entry, row, item, instance, idFor, busyReason, scope);
3005
+ else paintOriginControls(entry, row, item, instance, idFor, busyReason, scope);
3006
+ item.append(paintAnswerSource(scope, {
3007
+ requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintSetupCard(entry), label: instance, instance,
3008
+ idFor: sourceIdFor, inherited: row.inherited, busyReason, allowPictureOnly: true,
3009
+ onPictureOnly: () => submitSetupAnswers(entry, [{ key: row.key, action: 'evidence' }], row.key),
3010
+ }));
3011
+ const rowError = document.createElement('p'); rowError.className = 'ai-chat-height-error'; rowError.setAttribute('role', 'alert');
3012
+ rowError.textContent = entry.rowErrors.get(row.key) || '';
3013
+ item.append(rowError);
3014
+ return item;
3015
+ }
3016
+
3017
+ function setupProposal(valueText, tag, evidence, confirm) {
3018
+ const box = document.createElement('div'); box.className = 'ai-chat-setup-proposal';
3019
+ const line = document.createElement('div'); line.className = 'ai-chat-height-proposal';
3020
+ const value = document.createElement('span'); value.textContent = valueText;
3021
+ line.append(value, confirm);
3022
+ const source = document.createElement('div'); source.className = 'ai-chat-setup-evidence';
3023
+ const label = document.createElement('span'); label.className = 'ai-chat-setup-tag'; label.textContent = tag;
3024
+ source.append(label, document.createTextNode(` ${evidence}`));
3025
+ source.dataset.tip = `${tag}: ${evidence}`;
3026
+ box.append(line, source);
3027
+ return box;
3028
+ }
3029
+
3030
+ function setupTypedField(entry, row, item, instance, idFor, busyReason, placeholder, ariaWhat, primary) {
3031
+ const field = document.createElement('div'); field.className = 'ai-chat-height-field';
3032
+ const input = document.createElement('input');
3033
+ input.type = 'text'; input.className = 'ai-chat-height-input'; input.autocomplete = 'off'; input.spellcheck = false;
3034
+ input.dataset.commandId = idFor('input'); input.dataset.commandInstanceLabel = instance;
3035
+ input.placeholder = placeholder;
3036
+ input.setAttribute('aria-label', `${ariaWhat} for ${instance}`);
3037
+ input.value = entry.drafts.get(row.key) || '';
3038
+ input.addEventListener('input', () => { entry.drafts.set(row.key, input.value); entry.rowErrors.delete(row.key); if (row.kind === 'origin' && input.value) entry.originPick = null; });
3039
+ if (busyReason) { input.readOnly = true; input.setAttribute('aria-disabled', 'true'); input.dataset.blockedReason = busyReason; }
3040
+ const use = heightActionButton('Use', idFor('use'), instance, primary ? 'ai-chat-filter-apply' : '', busyReason);
3041
+ use.setAttribute('aria-label', `Use what you typed for ${instance}`);
3042
+ const submit = () => {
3043
+ if (use.getAttribute('aria-disabled') === 'true') return;
3044
+ const typed = input.value.trim();
3045
+ if (!typed) { entry.rowErrors.set(row.key, 'Type an answer first.'); repaintSetupCard(entry); return; }
3046
+ submitSetupAnswers(entry, [{ key: row.key, action: 'type', typed }], row.key);
3047
+ };
3048
+ input.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } });
3049
+ use.addEventListener('click', submit);
3050
+ field.append(input, use);
3051
+ item.append(field);
3052
+ }
3053
+
3054
+ function paintScaleControls(entry, row, item, instance, idFor, busyReason, scope) {
3055
+ if (row.clue) { const clue = document.createElement('p'); clue.className = 'ai-chat-setup-why'; clue.textContent = row.clue; item.append(clue); }
3056
+ for (const proposal of row.proposals) {
3057
+ const confirm = heightActionButton(proposal.pageFit ? 'Use for this plan' : 'Confirm', idFor('confirm', proposal.id), instance, 'ai-chat-filter-apply', busyReason);
3058
+ confirm.setAttribute('aria-label', `${proposal.pageFit ? 'Use' : 'Confirm'} ${proposal.standard} for ${instance}`);
3059
+ confirm.addEventListener('click', () => {
3060
+ if (confirm.getAttribute('aria-disabled') === 'true') return;
3061
+ submitSetupAnswers(entry, [{ key: row.key, action: 'confirm', choice: proposal.id, shown: proposal.mmPerPx }], row.key);
3062
+ });
3063
+ // The Confirm records mmPerPx, so the exact number is shown beside the standard (Codex review #1906).
3064
+ item.append(setupProposal(`${proposal.standard} · ${scaleNumber(proposal.mmPerPx)} mm per drawing point`, scaleTag[proposal.source] || 'PROPOSED', proposal.evidence, confirm));
3065
+ }
3066
+ setupTypedField(entry, row, item, instance, idFor, busyReason, 'or type a scale, e.g. 1/4" = 1\'-0" or 1:100', 'Type the scale', !row.proposals.length);
3067
+ }
3068
+
3069
+ const scaleNumber = (mmPerPx) => String(Number(Number(mmPerPx).toFixed(6)));
3070
+
3071
+ function levelEvidence(p) {
3072
+ const more = p.alsoOn ? `, and ${p.alsoOn} more` : '';
3073
+ if (p.source === 'drawing-text') return `${p.sheet} shows “${p.quote || p.asRead}”${p.near ? ` near ${p.near}` : ''}${more}.`;
3074
+ if (p.source === 'drawing-picture') return `Read off the picture of ${p.sheet}${p.near ? ` near ${p.near}` : ''}: “${p.quote || p.asRead}”. FloLess has not checked this reading${more}.`;
3075
+ return 'Read from the picture you sent. Check it before you confirm.';
3076
+ }
3077
+
3078
+ function paintLevelControls(entry, row, item, instance, idFor, busyReason, scope) {
3079
+ if (row.noSingleLevel) { const why = document.createElement('p'); why.className = 'ai-chat-setup-why'; why.textContent = `No single level on the drawings: ${row.noSingleLevel.why}`; item.append(why); }
3080
+ const units = entry.view?.units;
3081
+ for (const proposal of row.proposals) {
3082
+ const confirm = heightActionButton('Confirm', idFor('confirm', proposal.id), instance, 'ai-chat-filter-apply', busyReason);
3083
+ confirm.setAttribute('aria-label', `Confirm ${proposal.asRead} for ${instance}`);
3084
+ confirm.addEventListener('click', () => {
3085
+ if (confirm.getAttribute('aria-disabled') === 'true') return;
3086
+ submitSetupAnswers(entry, [{ key: row.key, action: 'confirm', choice: proposal.id, shown: proposal.value }], row.key);
3087
+ });
3088
+ item.append(setupProposal(proposal.asRead, levelTag[proposal.source] || 'PROPOSED', levelEvidence(proposal), confirm));
3089
+ }
3090
+ setupTypedField(entry, row, item, instance, idFor, busyReason, units === 'mm' ? 'or type a level, e.g. 4870 mm' : 'or type a level, e.g. 16\'-6"', 'Type the level', !row.proposals.length);
3091
+ paintNoneControl(entry, row, item, instance, idFor, busyReason, 'No single level', 'Short note (required), e.g. 1\'-6" TOF west, 0\'-0" east', 'Save: no single level');
3092
+ }
3093
+
3094
+ function paintNoneControl(entry, row, item, instance, idFor, busyReason, label, placeholder, saveLabel) {
3095
+ if (!entry.noneOpen.has(row.key)) {
3096
+ const none = heightActionButton(label, idFor('none'), instance, 'ai-chat-setup-secondary', busyReason);
3097
+ none.setAttribute('aria-label', `${label} for ${instance}`);
3098
+ none.addEventListener('click', () => {
3099
+ if (none.getAttribute('aria-disabled') === 'true') return;
3100
+ entry.noneOpen.add(row.key); repaintSetupCard(entry);
3101
+ const card = ui.feed.querySelector(`[data-setup-question="${CSS.escape(entry.key)}"]`);
3102
+ if (card) focusHeightControl(card, idFor('none-note'));
3103
+ });
3104
+ item.append(none);
3105
+ return;
3106
+ }
3107
+ const field = document.createElement('div'); field.className = 'ai-chat-height-field';
3108
+ const note = document.createElement('input');
3109
+ note.type = 'text'; note.className = 'ai-chat-height-input'; note.maxLength = 160; note.autocomplete = 'off';
3110
+ note.dataset.commandId = idFor('none-note'); note.dataset.commandInstanceLabel = instance;
3111
+ note.placeholder = placeholder;
3112
+ note.setAttribute('aria-label', `Why: ${label.toLowerCase()} for ${instance}`);
3113
+ note.required = true;
3114
+ const noteKey = `${row.key}\u0000none`;
3115
+ note.value = entry.drafts.get(noteKey) || '';
3116
+ note.addEventListener('input', () => { entry.drafts.set(noteKey, note.value); entry.rowErrors.delete(row.key); });
3117
+ const save = heightActionButton(saveLabel, idFor('none-save'), instance, '', busyReason);
3118
+ const submit = () => {
3119
+ if (save.getAttribute('aria-disabled') === 'true') return;
3120
+ const text = note.value.trim();
3121
+ if (!text) { entry.rowErrors.set(row.key, 'Add a short note first, so the read knows what to do instead.'); repaintSetupCard(entry); return; }
3122
+ submitSetupAnswers(entry, [{ key: row.key, action: 'none', note: text }], row.key);
3123
+ };
3124
+ note.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } });
3125
+ save.addEventListener('click', submit);
3126
+ field.append(note, save);
3127
+ item.append(field);
3128
+ }
3129
+
3130
+ function paintOriginControls(entry, row, item, instance, idFor, busyReason, scope) {
3131
+ const group = document.createElement('fieldset'); group.className = 'ai-chat-setup-origin';
3132
+ group.setAttribute('role', 'radiogroup');
3133
+ const legend = document.createElement('legend'); legend.textContent = 'Which grid crossing is the model’s origin (0, 0)?';
3134
+ group.append(legend);
3135
+ const radio = (choiceId, text, tag) => {
3136
+ const label = document.createElement('label'); label.className = 'ai-chat-setup-choice';
3137
+ const input = document.createElement('input');
3138
+ input.type = 'radio'; input.name = `origin-${entry.questionId}`; input.value = choiceId;
3139
+ input.dataset.commandId = idFor('origin-choice', choiceId); input.dataset.commandInstanceLabel = text;
3140
+ input.checked = entry.originPick === choiceId;
3141
+ if (busyReason) { input.disabled = true; }
3142
+ input.addEventListener('change', () => { entry.originPick = choiceId; entry.drafts.delete(row.key); entry.rowErrors.delete(row.key); repaintSetupCard(entry); });
3143
+ const name = document.createElement('span'); name.className = 'ai-chat-setup-choice-name'; name.textContent = text;
3144
+ label.append(input, name);
3145
+ if (tag) { const t = document.createElement('span'); t.className = 'ai-chat-setup-tag'; t.textContent = tag; label.append(t); }
3146
+ return label;
3147
+ };
3148
+ const straight = document.createElement('div'); straight.className = 'ai-chat-setup-choices';
3149
+ row.choices.forEach((choice, i) => straight.append(radio(`c${i}`, originText(choice), row.proposed === i ? (row.fromEvidence ? 'THE READ’S READING OF YOUR PICTURE' : 'THE READ SUGGESTS') : '')));
3150
+ group.append(straight);
3151
+ if (row.offGrid.length) {
3152
+ const also = document.createElement('fieldset'); also.className = 'ai-chat-setup-also';
3153
+ const legend2 = document.createElement('legend'); legend2.textContent = 'Also on the drawing (not straight grid lines)';
3154
+ also.append(legend2);
3155
+ row.offGrid.forEach((point, i) => also.append(radio(`o${i}`, point.as, '')));
3156
+ group.append(also);
3157
+ }
3158
+ item.append(group);
3159
+ const pick = entry.originPick;
3160
+ let target = null;
3161
+ if (pick && pick.startsWith('c')) target = row.choices[Number(pick.slice(1))] || null;
3162
+ let statement = null;
3163
+ if (pick && pick.startsWith('o')) {
3164
+ const point = row.offGrid[Number(pick.slice(1))];
3165
+ target = point ? row.choices[point.same] : null;
3166
+ if (point && target) {
3167
+ // Said BEFORE the confirm, and the confirm itself names the straight intersection that lands.
3168
+ statement = document.createElement('div'); statement.className = 'ai-chat-setup-statement';
3169
+ statement.setAttribute('role', 'status');
3170
+ statement.id = `setup-statement-${entry.questionId}`;
3171
+ statement.textContent = `${point.as} is not a straight grid line in the model, so it cannot be the origin. The read says it is the same point as ${originText(target)} (${point.why}). This is the read’s claim; FloLess has not checked it.`;
3172
+ item.append(statement);
3173
+ }
3174
+ }
3175
+ const confirmLabel = target ? `Confirm ${originText(target)} as the model origin` : 'Confirm the model origin';
3176
+ const confirm = heightActionButton(confirmLabel, idFor('origin-confirm'), instance, 'ai-chat-filter-apply', busyReason || (target ? null : 'Pick a point first'));
3177
+ if (statement) confirm.setAttribute('aria-describedby', statement.id);
3178
+ confirm.addEventListener('click', () => {
3179
+ if (confirm.getAttribute('aria-disabled') === 'true' || !target) return;
3180
+ submitSetupAnswers(entry, [{ key: row.key, action: 'confirm', choice: pick, shown: originText(target) }], row.key);
3181
+ });
3182
+ const actions = document.createElement('div'); actions.className = 'ai-chat-height-proposal';
3183
+ actions.append(confirm);
3184
+ item.append(actions);
3185
+ setupTypedField(entry, row, item, instance, idFor, busyReason, 'or type a point, e.g. K/1.1', 'Type the grid point', false);
3186
+ paintNoneControl(entry, row, item, instance, idFor, busyReason, 'None of these', 'Short note (required), e.g. use the corner at C/0.5', 'Save: none of these');
3187
+ }
3188
+
3189
+ async function submitSetupAnswers(entry, answers, rowKey) {
3190
+ if (entry.busy) return;
3191
+ const withSource = answers.map((answer) => withAnswerSource(answer, answerSourcePayload(`s:${entry.questionId}:${answer.key}`)));
3192
+ const tooLong = withSource.find((answer) => answer.note && answer.note.length > MAX_ANSWER_NOTE);
3193
+ if (tooLong) {
3194
+ entry.rowErrors.set(rowKey, `Your reason and your source note together are longer than ${MAX_ANSWER_NOTE} characters. Shorten one of them.`);
3195
+ repaintSetupCard(entry); return;
3196
+ }
3197
+ if (withSource.some((answer) => answer.action === 'evidence' && !answer.evidence?.length)) {
3198
+ entry.rowErrors.set(rowKey, 'Attach a picture first.'); repaintSetupCard(entry); return;
3199
+ }
3200
+ entry.busy = true; entry.cardError = ''; if (rowKey) entry.rowErrors.delete(rowKey);
3201
+ repaintSetupCard(entry);
3202
+ try {
3203
+ const result = await request(`/api/chat/setup-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}/answers`, {
3204
+ method: 'POST', body: JSON.stringify({ chatId: entry.chatId, answers: withSource }),
3205
+ });
3206
+ entry.view = result.question;
3207
+ for (const answer of answers) {
3208
+ entry.changing.delete(answer.key); entry.drafts.delete(answer.key); entry.drafts.delete(`${answer.key}\u0000none`);
3209
+ entry.noneOpen.delete(answer.key);
3210
+ if (answer.key === 'origin') entry.originPick = null;
3211
+ clearAnswerSource(`s:${entry.questionId}:${answer.key}`);
3212
+ }
3213
+ } catch (error) {
3214
+ let message = heightErrorText(error, 'FloLess could not save this answer. Try again.');
3215
+ if (error?.code === 'answer-evidence-unknown') message = dropStaleAnswerFiles(answers.map((answer) => `s:${entry.questionId}:${answer.key}`), entry);
3216
+ if (SETUP_STALE.has(error?.code)) { entry.cardError = message; entry.view = null; loadSetupQuestion(entry); }
3217
+ else if (rowKey) entry.rowErrors.set(rowKey, message);
3218
+ else entry.cardError = message;
3219
+ } finally {
3220
+ entry.busy = false;
3221
+ repaintSetupCard(entry);
3222
+ settlePendingReload(entry, loadSetupQuestion);
3223
+ focusNextSetupControl(entry);
3224
+ }
3225
+ }
3226
+
3227
+ // After an answer, keyboard focus moves to the next row still open, or to Tell the read.
3228
+ function focusNextSetupControl(entry) {
3229
+ const card = ui.feed?.querySelector(`[data-setup-question="${CSS.escape(entry.key)}"]`);
3230
+ if (!card || (document.activeElement && card.contains(document.activeElement) && document.activeElement.tagName === 'INPUT')) return;
3231
+ const target = card.querySelector('.ai-chat-setup-row[data-status="open"] button:not([aria-disabled="true"]), .ai-chat-setup-row[data-status="open"] input')
3232
+ || card.querySelector('[data-command-id^="shell.chat-setup-tell-read"]');
3233
+ target?.focus({ preventScroll: true });
3234
+ }
3235
+
1873
3236
  // A server-authored receipt of one approved live Tekla read. Deterministic: it shows only what
1874
3237
  // the server recorded, and an unverified read never shows a model name or parts.
1875
3238
  function renderTeklaReadEvent(event) {
@@ -1915,8 +3278,70 @@
1915
3278
  return card;
1916
3279
  }
1917
3280
 
3281
+ /* #1798: a receipt's weights follow the chat's display units — lb for ft-in, kg for mm. The receipt records
3282
+ kilograms and keeps them; this converts only what is shown, through the one shared helper
3283
+ (web/display-units.js). Until the units and the helper are both known it shows the recorded kilograms. */
3284
+ let displayUnitsModule = null;
3285
+ let displayUnitsLoading = null;
3286
+ function loadDisplayUnitsModule() {
3287
+ displayUnitsLoading ??= import('./display-units.js').then(
3288
+ (module) => { displayUnitsModule = module; },
3289
+ (error) => { displayUnitsLoading = null; console.warn('[chat] the display-units helper could not be loaded', error); });
3290
+ return displayUnitsLoading;
3291
+ }
3292
+ function receiptWeightUnits() {
3293
+ return displayUnitsModule && state.displayUnits ? state.displayUnits : null;
3294
+ }
3295
+ function teklaWeightWord() {
3296
+ const units = receiptWeightUnits();
3297
+ return units ? displayUnitsModule.weightUnitWord(units) : 'kg';
3298
+ }
1918
3299
  function teklaKg(value) {
1919
- return new Intl.NumberFormat(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(value);
3300
+ const units = receiptWeightUnits();
3301
+ const shown = units ? displayUnitsModule.weightIn(value, units) : value;
3302
+ return new Intl.NumberFormat(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(shown);
3303
+ }
3304
+
3305
+ function displayUnitsUrl(owner) {
3306
+ return owner.kind === 'project'
3307
+ ? `/api/projects/${encodeURIComponent(owner.projectId)}/display-units`
3308
+ : `/api/workflows/owned/${encodeURIComponent(owner.workflowId)}/display-units`;
3309
+ }
3310
+
3311
+ // A workspace conversation has no owner setting (#1890): its units are the person's choice, else the suggestion.
3312
+ function workspaceUnitsOf(chat) {
3313
+ const units = chat?.workspaceUnits;
3314
+ const pick = (value) => (value === 'mm' || value === 'ft-in' ? value : null);
3315
+ return pick(units?.chosen) || pick(units?.suggested);
3316
+ }
3317
+
3318
+ // Asks the server for the open chat's units, then repaints so every receipt — old ones too — follows them.
3319
+ // A failed read keeps whatever was last confirmed (or the recorded kilograms) and says so in the console.
3320
+ async function refreshDisplayUnits(retries = 2) {
3321
+ const owner = state.scope?.owner;
3322
+ const generation = ++state.displayUnitsGeneration;
3323
+ if (!owner) { state.displayUnits = null; return; }
3324
+ const shownBefore = receiptWeightUnits();
3325
+ if (owner.kind === 'workspace') {
3326
+ await loadDisplayUnitsModule().catch(() => {});
3327
+ if (generation !== state.displayUnitsGeneration) return;
3328
+ state.displayUnits = workspaceUnitsOf(state.chat);
3329
+ if (receiptWeightUnits() !== shownBefore && state.chat) paintEvents();
3330
+ return;
3331
+ }
3332
+ try {
3333
+ const [body] = await Promise.all([request(displayUnitsUrl(owner)), loadDisplayUnitsModule()]);
3334
+ if (generation !== state.displayUnitsGeneration) return;
3335
+ const units = body?.displayUnits === 'mm' || body?.displayUnits === 'ft-in' ? body.displayUnits : null;
3336
+ state.displayUnits = units;
3337
+ // Repaint on what the receipts would SHOW: the units changing, or the helper arriving after a failed load.
3338
+ if (receiptWeightUnits() !== shownBefore && state.chat) paintEvents();
3339
+ } catch (error) {
3340
+ if (generation !== state.displayUnitsGeneration) return;
3341
+ console.warn('[chat] this conversation’s display units could not be read', error);
3342
+ // A brief outage should not leave the receipts in recorded kilograms for the rest of the conversation.
3343
+ if (retries > 0) setTimeout(() => { if (generation === state.displayUnitsGeneration) void refreshDisplayUnits(retries - 1); }, 1500);
3344
+ }
1920
3345
  }
1921
3346
  function teklaCount(value) { return new Intl.NumberFormat().format(value); }
1922
3347
  function partsWord(count) { return `${teklaCount(count)} ${count === 1 ? 'part' : 'parts'}`; }
@@ -1925,7 +3350,7 @@
1925
3350
  // list that was cut short says so before anyone scrolls.
1926
3351
  function teklaSelectionSummary(payload, listed) {
1927
3352
  const count = Number(payload.partCount) || 0;
1928
- const total = `${teklaKg(Number(payload.totalWeightKg) || 0)} kg`;
3353
+ const total = `${teklaKg(Number(payload.totalWeightKg) || 0)} ${teklaWeightWord()}`;
1929
3354
  const missing = Number(payload.weightMissing) || 0;
1930
3355
  const lines = [];
1931
3356
  if (payload.complete === false) {
@@ -2006,9 +3431,10 @@
2006
3431
  caption.textContent = `Parts selected in Tekla when checked (${parts.length} listed of ${count})`;
2007
3432
  const head = document.createElement('thead');
2008
3433
  const headRow = document.createElement('tr');
2009
- for (const [label, numeric] of [['Mark', false], ['Name', false], ['Profile', false], ['Material', false], ['kg', true]]) {
3434
+ const weightWord = teklaWeightWord();
3435
+ for (const [label, numeric] of [['Mark', false], ['Name', false], ['Profile', false], ['Material', false], [weightWord, true]]) {
2010
3436
  const th = document.createElement('th'); th.scope = 'col'; th.textContent = label;
2011
- if (numeric) { th.className = 'num'; th.setAttribute('aria-label', 'Weight in kilograms'); }
3437
+ if (numeric) { th.className = 'num'; th.setAttribute('aria-label', weightWord === 'lb' ? 'Weight in pounds' : 'Weight in kilograms'); }
2012
3438
  headRow.append(th);
2013
3439
  }
2014
3440
  head.append(headRow);
@@ -2087,8 +3513,8 @@
2087
3513
  const missing = new Set(Array.isArray(payload.missingLinkedParts) ? payload.missingLinkedParts : []);
2088
3514
  if (!parts.length && !missing.size) return null;
2089
3515
  const labels = new Map(parts.map((part) => [part.guid, module.subjectLabelText(module.modelSubjectLabel('tekla', part))]));
2090
- const projectId = state.scope?.owner?.kind === 'project' ? state.scope.owner.projectId : null;
2091
- const loaded = state.teklaLinks.projectId === projectId ? state.teklaLinks : { state: 'idle', links: [], partial: false };
3516
+ const ownerKey = scopeKey(state.scope);
3517
+ const loaded = ownerKey && state.teklaLinks.ownerKey === ownerKey ? state.teklaLinks : { state: 'idle', links: [], partial: false };
2092
3518
  const own = payload.linkedQuestion?.messageEventId;
2093
3519
  const chatLinks = loaded.state === 'ready' ? { ...loaded, links: loaded.links.filter((link) => link.messageEventId !== own) } : loaded;
2094
3520
  return module.renderChatQuestions({
@@ -2100,15 +3526,16 @@
2100
3526
  }
2101
3527
 
2102
3528
  function showTeklaQuestion(link) {
2103
- const projectId = state.scope?.owner?.kind === 'project' ? state.scope.owner.projectId : null;
2104
- if (!projectId) return false;
2105
- Promise.resolve(openConversation(link.chatId, { messageEventId: link.messageEventId, projectId }))
3529
+ // The links listed are this chat's owner's, so the conversation is in the scope already open (#1890: a workflow's too).
3530
+ const ownerKey = scopeKey(state.scope);
3531
+ if (!ownerKey) return false;
3532
+ Promise.resolve(openConversation(link.chatId, { messageEventId: link.messageEventId, ownerKey }))
2106
3533
  .catch((error) => { window.showToast?.(error?.message || 'That conversation could not be opened. Try Show in chat again.', 'info'); });
2107
3534
  return true;
2108
3535
  }
2109
3536
 
2110
3537
  function appendTeklaHistory(card, event) {
2111
- if (state.scope?.owner?.kind !== 'project' || event.eventId !== newestTeklaSelectionId(state.events)) return;
3538
+ if (!state.scope?.owner || event.eventId !== newestTeklaSelectionId(state.events)) return;
2112
3539
  const host = document.createElement('div');
2113
3540
  host.className = 'ai-chat-tekla-history';
2114
3541
  host.hidden = true;
@@ -2141,7 +3568,7 @@
2141
3568
  // The check fell short for another reason: the receipt must never look like "no linked part is missing".
2142
3569
  const shortfall = {
2143
3570
  unavailable: 'FloLess could not check this time whether the parts linked to earlier questions are still in the model, so questions about removed parts are not listed here. Ask again to check them.',
2144
- partial: 'Some conversations in this project can’t be opened, so the parts linked to questions in them were not checked, and questions about removed parts may be missing here. History lists those conversations.',
3571
+ partial: `Some conversations in this ${state.scope?.owner?.kind === 'workflow' ? 'workflow' : 'project'} can’t be opened, so the parts linked to questions in them were not checked, and questions about removed parts may be missing here. History lists those conversations.`,
2145
3572
  }[payload.linkedPartsCheck];
2146
3573
  if (shortfall) {
2147
3574
  const line = document.createElement('p');
@@ -2154,19 +3581,19 @@
2154
3581
  }
2155
3582
 
2156
3583
  async function loadTeklaLinks(force = false) {
2157
- const projectId = state.scope?.owner?.kind === 'project' ? state.scope.owner.projectId : null;
2158
- if (!projectId) return;
3584
+ const ownerKey = scopeKey(state.scope);
3585
+ if (!ownerKey) return;
2159
3586
  const current = state.teklaLinks;
2160
- const same = current.projectId === projectId;
3587
+ const same = current.ownerKey === ownerKey;
2161
3588
  // Only a real change (a new receipt, a link written live, Retry) asks again; a repaint while an answer streams must
2162
3589
  // not queue one read after another.
2163
3590
  if (same && current.inflight) { if (force) current.again = true; return; }
2164
3591
  if (same && !force && current.state !== 'idle') return;
2165
- const next = { projectId, state: same ? current.state : 'idle', links: same ? current.links : [], partial: same && current.partial,
3592
+ const next = { ownerKey, state: same ? current.state : 'idle', links: same ? current.links : [], partial: same && current.partial,
2166
3593
  inflight: true, again: false };
2167
3594
  state.teklaLinks = next;
2168
3595
  try {
2169
- const result = await request(`/api/chat/subject-links?ownerKind=project&ownerId=${encodeURIComponent(projectId)}&source=tekla`);
3596
+ const result = await request(`/api/chat/subject-links?${ownerQuery()}&source=tekla`);
2170
3597
  if (state.teklaLinks === next) {
2171
3598
  Object.assign(next, { state: 'ready', links: Array.isArray(result?.links) ? result.links : [], partial: Boolean(result?.partial) });
2172
3599
  }
@@ -2274,7 +3701,9 @@
2274
3701
  // That button is `aria-disabled`, not `disabled`, so it passes the filter (#1514).
2275
3702
  function restoreFeedFocus(focusedCommand) {
2276
3703
  if (!focusedCommand?.startsWith('shell.chat-followup-') && !focusedCommand?.startsWith('shell.chat-filter-')
2277
- && !focusedCommand?.startsWith('shell.chat-question') && focusedCommand !== 'shell.chat-sign-in') return;
3704
+ && !focusedCommand?.startsWith('shell.chat-question') && !focusedCommand?.startsWith('shell.chat-height-')
3705
+ && !focusedCommand?.startsWith('shell.chat-setup-') && !focusedCommand?.startsWith('shell.chat-answer-')
3706
+ && focusedCommand !== 'shell.chat-sign-in') return;
2278
3707
  [...ui.feed.querySelectorAll('[data-command-id]')]
2279
3708
  .find(control => control.dataset.commandId === focusedCommand && !control.disabled)?.focus({ preventScroll: true });
2280
3709
  }
@@ -2318,7 +3747,9 @@
2318
3747
  // Provider tools commonly split one answer into before/after chunks. They are not prose,
2319
3748
  // so keep collecting same-turn deltas across them instead of rendering abandoned fragments.
2320
3749
  if (['tool', 'usage', 'knowledge-citation', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
2321
- if (event.type === 'chat-subjects') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
3750
+ // FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
3751
+ // held and shown under the answer, so they never cut one answer into fragments.
3752
+ if (event.type === 'chat-subjects' || event.type === 'evidence-read' || event.type === 'filter-proposal') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
2322
3753
  flushAssistant();
2323
3754
  const node = renderEvent(event);
2324
3755
  if (node) ui.feed.append(node);
@@ -2373,7 +3804,10 @@
2373
3804
  empty.append(strong, copy, emptySignInButton(label, true, copy.id));
2374
3805
  } else if (providerReady()) {
2375
3806
  strong.textContent = 'Ready when you are';
2376
- copy.textContent = `This ${label} conversation is stored with ${state.scope?.label || 'this work'}.`;
3807
+ // #1890: a workspace conversation is one shared history, reachable from every landing and installed workflow.
3808
+ copy.textContent = state.scope?.owner?.kind === 'workspace'
3809
+ ? `This ${label} conversation is kept in your workspace. Open it again from Workspaces, Workflows or any installed workflow.`
3810
+ : `This ${label} conversation is stored with ${state.scope?.label || 'this work'}.`;
2377
3811
  empty.append(strong, copy);
2378
3812
  } else if (state.capability?.runtime && state.capability.runtime.state !== 'installed') {
2379
3813
  const notice = runtimeNotice(provider, state.capability.runtime);
@@ -2570,8 +4004,7 @@
2570
4004
  };
2571
4005
  }
2572
4006
 
2573
- // What the setup card shows for one conversation: the card is rebuilt, and a Drawing Filter "not sent"
2574
- // sentence dropped from the hint, only when this changes.
4007
+ // What the setup card shows for one conversation: the card is rebuilt only when this changes.
2575
4008
  function runtimeCardKey(chatId, status) {
2576
4009
  return `${chatId}:${status.state}:${status.owner || ''}:${status.code || ''}:${status.retryable ? 1 : 0}`;
2577
4010
  }
@@ -2688,9 +4121,10 @@
2688
4121
  */
2689
4122
  function paintAttachControl() {
2690
4123
  const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length;
2691
- // A reply to a drawing read waiting on the person is a normal turn, and takes what any message takes (#1776).
2692
- const kinds = filterSurface().state === 'off' || paintFilterComposer().replyToRead ? 'image or PDF' : 'a picture';
2693
- ui.attach.dataset.tip = `Attach ${kinds} · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images in this message`;
4124
+ // Every message takes what any message takes, the Drawing Filter open or not (#1859), and that
4125
+ // includes data files (#1853); the tooltip lists the common ones, the spoken label stays short.
4126
+ const kinds = 'a picture, PDF, or data file';
4127
+ ui.attach.dataset.tip = `Attach ${kinds} (IFC, DXF, CSV, text) · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images in this message`;
2694
4128
  ui.attach.setAttribute('aria-label', `Attach ${kinds} · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images`);
2695
4129
  }
2696
4130
 
@@ -2791,7 +4225,15 @@
2791
4225
  preview.src = `/api/chat/conversations/${encodeURIComponent(state.chat.chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}?${ownerQuery()}`;
2792
4226
  chip.append(preview);
2793
4227
  }
2794
- const name = document.createElement('span'); name.textContent = attachment.fileName;
4228
+ const name = document.createElement('span');
4229
+ name.textContent = attachment.mediaType.startsWith('image/') ? attachment.fileName : attachmentLabel(attachment);
4230
+ const cut = dataCutTip(attachment);
4231
+ if (cut) {
4232
+ // Hover shows the tip; the hidden sentence says the same to a keyboard or screen-reader user.
4233
+ chip.dataset.tip = cut;
4234
+ const note = document.createElement('span'); note.className = 'sr-only'; note.textContent = ` ${cut}`;
4235
+ name.append(note);
4236
+ }
2795
4237
  const remove = button('×', `shell.chat-attachment-remove#${attachment.attachmentId}`);
2796
4238
  remove.dataset.commandInstanceLabel = attachment.fileName;
2797
4239
  remove.setAttribute('aria-label', `Remove ${attachment.fileName} from the next message`);
@@ -2980,6 +4422,9 @@
2980
4422
  const medium = (model?.efforts || []).find((effort) => effort.toLowerCase() === 'medium');
2981
4423
  ui.effort.querySelector('strong').textContent = effortLabel(chat?.settings.effort || medium || model?.efforts?.[0]) || 'Choose effort';
2982
4424
  ui.permission.querySelector('strong').textContent = permissionLabels[chat?.settings.permissionProfile] || 'Read only';
4425
+ if (state.scope?.owner?.kind === 'workspace') ui.permission.dataset.tip = 'From the workspace, AI Chat reads and answers. Open a project or workflow to let it change files there.';
4426
+ else delete ui.permission.dataset.tip;
4427
+ paintWorkspaceUnits();
2983
4428
  const bindings = chat?.integrationBindings || [];
2984
4429
  ui.integrations.querySelector('strong').textContent = bindings.length
2985
4430
  ? `${bindings.length} FloLess account${bindings.length === 1 ? '' : 's'}`
@@ -3186,6 +4631,15 @@
3186
4631
  };
3187
4632
  }
3188
4633
 
4634
+ /*
4635
+ * The composer's draft files: stored, not yet sent. A picture the person attached to an ANSWER (#1906)
4636
+ * is stored the same way but belongs to its card, never to the next message — the server refuses it
4637
+ * on a send, so listing it here would block every message (found in the Take 5 E2E).
4638
+ */
4639
+ function composerDrafts(chat) {
4640
+ return (chat.attachments || []).filter((attachment) => !attachment.turnId && attachment.purpose !== 'answer-evidence');
4641
+ }
4642
+
3189
4643
  function clearConfirmedUnknownDraft(event, chatId) {
3190
4644
  const confirmed = String(event.payload?.text || '').trim();
3191
4645
  if (state.backgroundDrafts.get(chatId)?.trim() === confirmed) state.backgroundDrafts.delete(chatId);
@@ -3255,7 +4709,7 @@
3255
4709
  }
3256
4710
  if (!sameChat(snapshot)) return;
3257
4711
  state.chat = chat;
3258
- state.attachments = (chat.attachments || []).filter((attachment) => !attachment.turnId);
4712
+ state.attachments = composerDrafts(chat);
3259
4713
  const index = state.chats.findIndex((item) => item.chatId === chatId);
3260
4714
  if (index >= 0) state.chats[index] = chat;
3261
4715
  paintConversation();
@@ -3357,7 +4811,7 @@
3357
4811
  reconcileUnknownFollowupOnSelection(chat);
3358
4812
  state.capability = capability;
3359
4813
  state.desktop = desktop;
3360
- state.attachments = (chat.attachments || []).filter((attachment) => !attachment.turnId);
4814
+ state.attachments = composerDrafts(chat);
3361
4815
  ui.input.value = draftForChat(chat);
3362
4816
  // A cached draft may be newer than the server draft after a fast switch.
3363
4817
  // Save it now, even if the user does not type again after reopening.
@@ -3369,7 +4823,6 @@
3369
4823
  }, 2600);
3370
4824
  }
3371
4825
  paintConversation(); connectEvents();
3372
- resumeFilterRequests();
3373
4826
  if (options.applyProviderDefaults || !chat.nativeSessionId) await applyProviderDefaults(chatId);
3374
4827
  // Let the server prepare the provider for the next message while the user types, after the
3375
4828
  // default model and effort are saved so the prepared runtime matches the first message. Best-effort:
@@ -3463,15 +4916,15 @@
3463
4916
  if (scopeChanged) { try { window.flolessLeftPane?.chatLinksChanged?.(); } catch { /* the card refreshes on its next read */ } }
3464
4917
  state.chat = null; state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
3465
4918
  if (scopeChanged) clearReport();
3466
- // A published filter answer still lands in its own project's conversation; reopening it resumes.
3467
- for (const entry of state.filterPending.values()) clearTimeout(entry.timer);
3468
- state.filterPending.clear(); state.filterNotices.clear(); state.filterCardMessages.clear();
4919
+ state.filterCardMessages.clear();
3469
4920
  updateOffscreenActivity();
3470
4921
  state.historyFilter = 'all'; state.instructorAnswers = []; state.historyLoading = false; state.historyRequestGeneration += 1;
3471
4922
  closeHistoryPanel();
3472
- if (!scope?.owner) { showUnscoped(); return; }
4923
+ if (scopeChanged) state.displayUnits = null;
4924
+ if (!scope?.owner) { state.displayUnitsGeneration += 1; showUnscoped(); return; }
4925
+ void refreshDisplayUnits();
3473
4926
  ui.scope.textContent = scope.label;
3474
- ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
4927
+ ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : scope.owner.kind === 'workflow' ? 'Workflow conversation' : 'Workspace conversation';
3475
4928
  setBusy(true);
3476
4929
  try {
3477
4930
  await ensureSession();
@@ -3491,7 +4944,7 @@
3491
4944
  state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null;
3492
4945
  updateOffscreenActivity();
3493
4946
  ui.scope.textContent = scope.label;
3494
- ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
4947
+ ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : scope.owner.kind === 'workflow' ? 'Workflow conversation' : 'Workspace conversation';
3495
4948
  paintHistory(); paintUnread(); providerChooser();
3496
4949
  report(error, 'Could not load this conversation history');
3497
4950
  }
@@ -3509,18 +4962,131 @@
3509
4962
  await loadScope(next);
3510
4963
  }
3511
4964
 
4965
+ // The units of the project the person opened last (#1890), suggested to a new workspace conversation. Null when no
4966
+ // project was opened in this browser, or its units cannot be read: then the conversation suggests nothing.
4967
+ async function lastProjectUnits() {
4968
+ let projectId = null;
4969
+ try { projectId = localStorage.getItem('floless:last-project'); } catch { /* private mode: no suggestion */ }
4970
+ if (!projectId) return null;
4971
+ try {
4972
+ const body = await request(`/api/projects/${encodeURIComponent(projectId)}/display-units`);
4973
+ return body?.displayUnits === 'mm' || body?.displayUnits === 'ft-in' ? body.displayUnits : null;
4974
+ } catch { return null; }
4975
+ }
4976
+
4977
+ // The units question of a workspace conversation (#1890): asked until the person answers, then a quiet line to change
4978
+ // it. Never blocks Send — an unanswered question tells the AI the units are not chosen yet, and it asks.
4979
+ function paintWorkspaceUnits() {
4980
+ const host = ui.workspaceUnits;
4981
+ if (!host) return;
4982
+ const chat = state.chat;
4983
+ if (state.scope?.owner?.kind !== 'workspace' || !chat || chat.archivedAt) { host.hidden = true; host.replaceChildren(); delete host.dataset.painted; return; }
4984
+ // The receipts' units follow the conversation's own (chosen, else suggested) — set here, where the chat is known.
4985
+ state.displayUnits = workspaceUnitsOf(chat);
4986
+ const units = chat.workspaceUnits || {};
4987
+ const chosen = units.chosen === 'mm' || units.chosen === 'ft-in' ? units.chosen : null;
4988
+ const label = (value) => (value === 'mm' ? 'Metric (mm)' : 'ft-in');
4989
+ // Settings repaint on every chat event; rebuilding unchanged buttons would swap them out from under a click.
4990
+ const painted = `${chat.chatId}|${chosen}|${units.suggested ?? null}|${Boolean(state.workspaceUnitsEditing)}`;
4991
+ if (!host.hidden && host.dataset.painted === painted) return;
4992
+ host.dataset.painted = painted;
4993
+ host.hidden = false;
4994
+ host.replaceChildren();
4995
+ if (chosen && !state.workspaceUnitsEditing) {
4996
+ const text = document.createElement('span');
4997
+ text.className = 'ai-chat-units-current';
4998
+ text.textContent = `Units: ${label(chosen)}`;
4999
+ const change = document.createElement('button');
5000
+ change.type = 'button';
5001
+ change.className = 'ai-chat-units-change';
5002
+ change.textContent = 'Change';
5003
+ change.setAttribute('aria-label', 'Change units');
5004
+ change.dataset.commandId = 'shell.chat-units-change';
5005
+ change.dataset.tip = 'Choose the units AI answers in, in this conversation';
5006
+ change.addEventListener('click', () => { state.workspaceUnitsEditing = true; paintWorkspaceUnits(); host.querySelector('[role="radio"][aria-checked="true"], [role="radio"]')?.focus(); });
5007
+ host.append(text, change);
5008
+ return;
5009
+ }
5010
+ const question = document.createElement('span');
5011
+ question.className = 'ai-chat-units-question';
5012
+ question.id = 'chat-units-question';
5013
+ question.textContent = 'Which units should AI use here?';
5014
+ const group = document.createElement('div');
5015
+ group.className = 'ai-chat-units-options';
5016
+ group.setAttribute('role', 'radiogroup');
5017
+ group.setAttribute('aria-labelledby', 'chat-units-question');
5018
+ const suggested = units.suggested === 'mm' || units.suggested === 'ft-in' ? units.suggested : null;
5019
+ const options = ['ft-in', 'mm'];
5020
+ for (const value of options) {
5021
+ const option = document.createElement('button');
5022
+ option.type = 'button';
5023
+ option.className = 'ai-chat-units-option';
5024
+ option.setAttribute('role', 'radio');
5025
+ const checked = chosen ? chosen === value : suggested === value;
5026
+ option.setAttribute('aria-checked', String(Boolean(chosen && chosen === value)));
5027
+ option.tabIndex = checked || (!chosen && !suggested && value === 'ft-in') ? 0 : -1;
5028
+ option.dataset.commandId = `shell.chat-units-choose#${value}`;
5029
+ option.dataset.commandInstanceLabel = label(value);
5030
+ if (suggested === value && !chosen) option.classList.add('is-suggested');
5031
+ option.textContent = label(value);
5032
+ if (suggested === value && !chosen) {
5033
+ const hint = document.createElement('span');
5034
+ hint.className = 'ai-chat-units-hint';
5035
+ hint.textContent = ' · last project';
5036
+ option.append(hint);
5037
+ }
5038
+ option.addEventListener('click', () => { void chooseWorkspaceUnits(value); });
5039
+ option.addEventListener('keydown', (event) => {
5040
+ if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft' && event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
5041
+ event.preventDefault();
5042
+ const next = group.querySelectorAll('[role="radio"]')[value === 'ft-in' ? 1 : 0];
5043
+ next?.focus();
5044
+ });
5045
+ group.append(option);
5046
+ }
5047
+ host.append(question, group);
5048
+ }
5049
+
5050
+ async function chooseWorkspaceUnits(value) {
5051
+ const snapshot = captureChat();
5052
+ if (!snapshot) return;
5053
+ try {
5054
+ const updated = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/workspace-units`, {
5055
+ method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, units: value }),
5056
+ });
5057
+ if (!sameChat(snapshot)) return;
5058
+ state.chat = { ...state.chat, workspaceUnits: updated.workspaceUnits };
5059
+ state.workspaceUnitsEditing = false;
5060
+ paintWorkspaceUnits();
5061
+ void refreshDisplayUnits();
5062
+ announce(`Units set to ${value === 'mm' ? 'metric (millimetres)' : 'feet and inches'}.`);
5063
+ ui.workspaceUnits?.querySelector('.ai-chat-units-change')?.focus();
5064
+ } catch (error) {
5065
+ report(error, 'Could not save the units for this conversation');
5066
+ }
5067
+ }
5068
+
3512
5069
  async function createConversation(provider) {
3513
5070
  if (!state.scope || state.loading) return;
3514
5071
  clearProviderChoice();
3515
5072
  setBusy(true);
5073
+ // The owner is the one shown when the person chose a provider: a scope change while this runs must neither create
5074
+ // the conversation somewhere else nor paint it into, or unlock, the scope the person moved to.
5075
+ const owner = state.scope.owner;
5076
+ const generation = state.scopeGeneration;
3516
5077
  try {
5078
+ const displayUnitsSuggestion = owner.kind === 'workspace' ? await lastProjectUnits() : undefined;
5079
+ if (generation !== state.scopeGeneration) return;
3517
5080
  const chat = await request('/api/chat/conversations', {
3518
5081
  method: 'POST', body: JSON.stringify({
3519
- owner: state.scope.owner, provider, title: 'New chat',
5082
+ owner, provider, title: 'New chat',
3520
5083
  settings: { model: null, effort: null, permissionProfile: 'read-only' },
3521
5084
  initiator: { kind: 'user' },
5085
+ ...(displayUnitsSuggestion ? { displayUnitsSuggestion } : {}),
3522
5086
  }),
3523
5087
  });
5088
+ // Created where it was asked for; it is listed when that place is opened again.
5089
+ if (generation !== state.scopeGeneration) return;
3524
5090
  state.chats.unshift(chat);
3525
5091
  await selectConversation(chat.chatId, { focus: true, applyProviderDefaults: true, replaceProviderChoice: true, preserveDiscoveryDraft: true });
3526
5092
  if (state.discoveryDraft && state.chat?.chatId === chat.chatId) {
@@ -3533,9 +5099,10 @@
3533
5099
  state.pendingTeklaLibrary = null;
3534
5100
  paintTeklaChip();
3535
5101
  }
3536
- announce(`${providerLabels[provider]} conversation created.`);
5102
+ // A late announcement would name a conversation from the place the person already left.
5103
+ if (generation === state.scopeGeneration) announce(`${providerLabels[provider]} conversation created.`);
3537
5104
  } catch (error) { report(error, 'Could not start conversation'); }
3538
- finally { setBusy(false); }
5105
+ finally { if (generation === state.scopeGeneration) setBusy(false); }
3539
5106
  }
3540
5107
 
3541
5108
  async function refreshInstructorAnswers(focusFilter = false) {
@@ -3694,7 +5261,11 @@
3694
5261
  }
3695
5262
 
3696
5263
  function permissionChoices() {
3697
- return Object.entries(permissionLabels).map(([value, label]) => ({
5264
+ // #1890: from the workspace, AI Chat reads and answers; it changes files only from a project or workflow.
5265
+ const offered = state.scope?.owner?.kind === 'workspace'
5266
+ ? Object.entries(permissionLabels).filter(([value]) => value === 'read-only')
5267
+ : Object.entries(permissionLabels);
5268
+ return offered.map(([value, label]) => ({
3698
5269
  id: `permission:${value}`, label, meta: value === 'full-access' ? 'all local files' : value === 'workspace-write' ? 'project or workflow folder' : 'no file changes',
3699
5270
  selected: state.chat.settings.permissionProfile === value, patch: { permissionProfile: value },
3700
5271
  }));
@@ -3803,24 +5374,18 @@
3803
5374
  const settingUp = Boolean(state.capability?.runtime && state.capability.runtime.state !== 'installed');
3804
5375
  const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
3805
5376
  ui.input.disabled = state.followupSubmitting || !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
3806
- ui.send.disabled = state.loading || state.followupSubmitting || state.filterSending || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
5377
+ ui.send.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
3807
5378
  || (!ui.input.value.trim() && state.attachments.length === 0) || settingUp;
3808
- // A Drawing Filter message carries the filter's own context AND whatever pictures the person
3809
- // attached (#1681). The paperclip used to be disabled here, which is the "I can't add
3810
- // attachments" in that issue; the only attachment rule left is the one in `filterSendRefusal`,
3811
- // and it is about the file type, not about the surface.
3812
- // `state.filterSending` belongs here BECAUSE the shared tooltip below already stamps "wait for it
3813
- // to appear" on this control: without it the paperclip says blocked and stays clickable, and a
3814
- // picture attached mid-send is not in the set `sendFilterAi` puts back if the send fails.
3815
- ui.attach.disabled = state.loading || state.followupSubmitting || state.filterSending || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen;
5379
+ // The paperclip is the same on every surface, the Drawing Filter included (#1681, #1859): a message
5380
+ // there carries the filter's context AND whatever the person attached, under the general rules only.
5381
+ ui.attach.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen;
3816
5382
  // Repainted here too: this runs on a surface switch, which changes what may be attached without
3817
5383
  // changing the attachments themselves.
3818
5384
  paintAttachControl();
3819
5385
  const unknownReason = state.followupUnknownId || hasUnknownFollowup()
3820
5386
  ? 'FloLess could not confirm a follow-up. Review that message before sending or attaching another file.' : null;
3821
5387
  const sendingReason = state.followupSubmitting
3822
- ? 'FloLess is saving this message. Wait for its delivery status before sending another.'
3823
- : state.filterSending ? 'FloLess is sending this message to the Drawing Filter. Wait for it to appear before sending another.' : null;
5388
+ ? 'FloLess is saving this message. Wait for its delivery status before sending another.' : null;
3824
5389
  for (const control of [ui.send, ui.attach]) {
3825
5390
  if (unknownReason || sendingReason) control.dataset.blockedReason = unknownReason || sendingReason;
3826
5391
  else delete control.dataset.blockedReason;
@@ -3970,40 +5535,19 @@
3970
5535
  ui.skills.hidden = false;
3971
5536
  }
3972
5537
 
3973
- // ── Drawing Filter help ────────────────────────────────────────────────────────────────────────
3974
- // While the Drawing Filter is the visible surface, this composer sends a read-only guide request
3975
- // about the filter instead of a normal turn, and its answer is published into this conversation.
3976
- // The filter page (its iframe) owns the drawing, the selection and every Apply / Undo / Keep guard;
3977
- // for anything about the drawing this chat only relays through `window.__floFilterAi`. The chat owns
3978
- // linking, starting and polling the request itself.
3979
- // There is no mode to choose: the person just asks or says what to change. Every message is sent as
3980
- // a request that may suggest ticks, and a review card appears only when the answer does.
3981
- const FILTER_PENDING = 'AI is reading the filter…';
5538
+ // ── Drawing Filter context and suggestions ─────────────────────────────────────────────────────
5539
+ // ONE AI CHAT (#1859). With the Drawing Filter open, a message is an ordinary turn or follow-up; the
5540
+ // open filter only adds a snapshot of the sheet and its selection (`filterContextForSend`), and the AI
5541
+ // may answer with a suggestion card (`floless_filter_propose`). The filter page (its iframe) owns the
5542
+ // drawing, the selection and every Apply / Undo / Keep guard; this chat only relays through
5543
+ // `window.__floFilterAi`. Drawing Filter questions and answers from before #1859 still render from
5544
+ // their events, read-only: the page that recorded their suggestions is gone, so they offer nothing.
3982
5545
  const FILTER_NOT_OPEN = 'Open Drawing Filter to use this suggestion.';
3983
5546
  // Mirrors the filter page's own FILTER_AI_UNKNOWN: with no page at all, its records are gone too.
3984
5547
  const FILTER_PAGE_GONE = 'This suggestion was made before the Drawing Filter was last opened or reloaded. Ask again from the current filter to apply it.';
3985
- // Codes the start route (/api/chat/requests/:id/start) returns before it writes a link; a 400 counts
3986
- // too, and an expired chat session is renewed and retried. Only when every attempt was definitely
3987
- // refused does sendFilterAi clean the request up. After any other failure the request is never
3988
- // deleted: it continues only if Requests shows the link, and otherwise stays in Requests.
3989
- const FILTER_LINK_REFUSALS = new Set(['request-chat-unavailable', 'request-chat-owner-changed']);
3990
- const FILTER_LINK_REFUSAL_COPY = {
3991
- // One code for several causes (a reply started, archived, another provider), so no cause is named.
3992
- 'request-chat-unavailable': 'This conversation could not take the message, so nothing was sent. Send it again, or start a new conversation and send it there.',
3993
- 'request-chat-owner-changed': 'The project changed while FloLess was sending this. Open the project again, then send it once more. Nothing was sent.',
3994
- };
3995
- const FILTER_CREATE_TIMEOUT = 'FloLess did not answer in time, so this request may not have started. Check Requests before sending it again.';
3996
- // One cause-free pair for every failed answer check: a slow server, a dropped connection and a bug
3997
- // look the same from here.
3998
- const FILTER_CHECK_RETRY = 'FloLess could not check the answer yet. Trying again.';
3999
- const FILTER_CHECK_STOPPED = 'FloLess stopped checking this answer after several tries. A late answer may still appear here or in Requests. Check those before sending it again. Nothing changed.';
4000
5548
  let filterBridgeWarned = false;
4001
5549
  let readCheckWarned = false;
4002
5550
 
4003
- function filterRefusal(message) {
4004
- return Object.assign(new Error(message), { filterRefusal: true });
4005
- }
4006
-
4007
5551
  /** A broken filter page is a bug worth one console line, not a silent "still loading" forever. */
4008
5552
  function warnFilterBridge(error) {
4009
5553
  if (filterBridgeWarned) return;
@@ -4012,9 +5556,8 @@
4012
5556
  }
4013
5557
 
4014
5558
  /**
4015
- * Whether the composer is in Drawing Filter mode depends on the visible surface. A filter page that
4016
- * has not finished loading means 'loading' (Send refuses, never a normal turn); only the page's own
4017
- * empty screen ('unavailable') drops back to a normal chat.
5559
+ * The Drawing Filter as the visible surface: 'off', 'loading' (the message goes without its context,
5560
+ * and says so), or 'ready' with the page's bridge. The page's own empty screen ('unavailable') is 'off'.
4018
5561
  */
4019
5562
  function filterSurface() {
4020
5563
  if (currentSurface() !== 'drawing-filter') return { state: 'off' };
@@ -4038,31 +5581,26 @@
4038
5581
  * a second wording here made the same box look like a different box on one screen, for a mode the
4039
5582
  * person did not choose and cannot see the edges of.
4040
5583
  *
4041
- * The mode is still real: Send routes a filter message through the Drawing Filter's own request
4042
- * path rather than as a normal chat turn — a change request whose answer proposes ticks for the
4043
- * person to review, run with read-only runtime options. (Not "a read-only question": `sendFilterAi`
4044
- * hard-codes `kind = 'change'`, and a comment on this screen saying otherwise is how the next
4045
- * reader gets it backwards.) What still announces it is `paintFloLessContext`'s "Sharing with AI:
4046
- * Drawing Filter · partial view of <sheet> and its selection" — which is the better cue anyway,
4047
- * because it NAMES THE SHEET, and it sits directly under the box. (The compose hint does not
4048
- * announce the filter mode: the only branch of its chain in `clearReport` that depends on this
4049
- * function is the #1776 read-reply hint below, which names where a message goes when it is NOT the
4050
- * filter mode; and the attach control's blocked reason only speaks once someone tries to attach.)
5584
+ * There is no mode (#1859): Send never routes on this. What says the filter's selection goes with a
5585
+ * message is `paintFloLessContext`'s "Sharing with AI: Drawing Filter · sheet <sheet> and its
5586
+ * selection", directly under the box.
4051
5587
  *
4052
5588
  * RETURNS the raw `filterSurface()` result — `{ state: 'off' | 'loading' }` or `{ state: 'ready',
4053
- * bridge, summary }` — except when a drawing read in this conversation is waiting on the person's
4054
- * answer (#1776): then `{ state: 'off', replyToRead: true }`, even though the Drawing Filter IS
4055
- * open. Callers that route or label a message must ask this, never `filterSurface()` directly.
5589
+ * bridge, summary }` — except when a drawing read is running in this conversation (#1776, #1857):
5590
+ * then `{ state: 'off', replyToRead: true, readWorking }`, even though the Drawing Filter IS open,
5591
+ * where `readWorking` says whether its turn is still running (the message is then a follow-up).
5592
+ * Callers that route or label a message must ask this, never `filterSurface()` directly.
4056
5593
  */
4057
5594
  function paintFilterComposer() {
4058
5595
  const surface = filterSurface();
4059
- // #1776: a drawing read in THIS conversation whose turn has stopped is waiting on the person, so
4060
- // what they type is its answer. Sent to the Drawing Filter's AI instead, the answer reached a
4061
- // listener that never asked, and the read sat idle with nothing on screen saying why. The read
4062
- // wins, and the composer says so while it does: the hint beside Send (`clearReport`, when no
4063
- // higher-priority notice holds it) and the context note under the box (`paintFloLessContext`),
4064
- // which also feeds Send's tooltip. With no read waiting, nothing changes.
4065
- if (surface.state !== 'off' && !turnIsVisiblyActive() && readAwaitingReply()) return { state: 'off', replyToRead: true };
5596
+ // #1859: the read hints below say where a message goes on EVERY surface; the filter no longer routes.
5597
+ // #1776, #1857: a drawing read in THIS conversation is who the person is talking to, so the
5598
+ // composer says where a message goes — to the read, or to it as a follow-up while it is working:
5599
+ // the hint beside Send (`clearReport`, when no higher-priority notice holds it) and the context note
5600
+ // under the box (`paintFloLessContext`), which also feeds Send's tooltip.
5601
+ if (readAwaitingReply()) {
5602
+ return { ...surface, replyToRead: true, readWorking: turnIsVisiblyActive() };
5603
+ }
4066
5604
  return surface;
4067
5605
  }
4068
5606
 
@@ -4078,533 +5616,6 @@
4078
5616
  }
4079
5617
  }
4080
5618
 
4081
- function filterPendingIn(chatId) {
4082
- return [...state.filterPending.values()].some((entry) => entry.chatId === chatId);
4083
- }
4084
-
4085
- function filterAnswered(requestId) {
4086
- return state.events.some((event) => event.type === 'assistant-message' && event.payload?.requestId === requestId);
4087
- }
4088
-
4089
- /**
4090
- * The only length limit on a Drawing Filter message, and the same number the server enforces
4091
- * (`MAX_SUBJECT_CHARS` in `server/instructor-request.ts`).
4092
- *
4093
- * It was 300 — short enough that an ordinary question naming two layers was refused, which is the
4094
- * complaint #1681 opens with. It is deliberately still A limit: the message becomes the request's
4095
- * subject, and an unbounded field there is its own failure.
4096
- */
4097
- const FILTER_MESSAGE_LIMIT = 4000;
4098
-
4099
- /** Why a filter message cannot be sent right now, or null. Checked before the draft is touched. */
4100
- function filterSendRefusal(surface, text) {
4101
- const chat = state.chat;
4102
- if (surface.state !== 'ready') return 'The Drawing Filter is still loading. Wait until its layers appear, then send again. Nothing was sent.';
4103
- if (turnIsVisiblyActive(chat) || chat.activeTurn) return 'Wait for the current AI reply to finish before asking about the filter. Your message was not sent.';
4104
- if (filterPendingIn(chat.chatId)) return 'Wait for the current Drawing Filter answer before sending another. Your message was not sent.';
4105
- // Pictures ride along (#1681). A PDF cannot: the AI answering a Drawing Filter message looks at
4106
- // images handed to it on the command line and has no file access of its own, so a PDF here would
4107
- // be stored and never opened. Say that plainly rather than accept it and answer around it.
4108
- const nonImage = state.attachments.find((item) => !String(item.mediaType || '').startsWith('image/'));
4109
- if (nonImage) {
4110
- return `“${nonImage.fileName}” can’t be sent with a Drawing Filter message — the AI answering here can only look at pictures. `
4111
- + 'Attach a screenshot of the page you mean, or ask about it in the main conversation instead. Nothing was sent.';
4112
- }
4113
- // A PICTURE ONLY REACHES CODEX. It travels on the command line of the headless run, and a
4114
- // read-only Claude run has no tool that could open one and a relay that returns text only — so
4115
- // on a Claude conversation the answer would be written having seen nothing. The run route
4116
- // refuses this too, but by then a request exists and has to be unwound; the independent QA saw
4117
- // exactly that, with a queued request and an "attachment ready" composer. Refuse here, before
4118
- // anything is created.
4119
- if (state.attachments.length && chat.provider !== 'codex') {
4120
- return `${providerLabels[chat.provider] || 'This AI'} can’t be shown a picture in a Drawing Filter message. `
4121
- + 'Remove the picture to send the question on its own, or ask in a conversation with the other AI. Nothing was sent.';
4122
- }
4123
- // Counted exactly as the filter page counts it, so the two limits can never disagree.
4124
- if (text.length > FILTER_MESSAGE_LIMIT) return `Shorten your message to ${FILTER_MESSAGE_LIMIT} characters, then send it again. Nothing was sent.`;
4125
- return null;
4126
- }
4127
-
4128
- function filterAccessFailure(status, detail) {
4129
- if (status === 401 || detail?.reason === 'session-expired') return 'Your FloLess sign-in expired. Sign in again, then send your message again. Nothing changed.';
4130
- if (detail?.reason === 'signed-out') return 'You are signed out of FloLess. Sign in, then send your message again. Nothing changed.';
4131
- if (detail?.reason === 'seat-taken') return 'This FloLess session lost its licence seat. Sign in again or close the other active session, then send your message again. Nothing changed.';
4132
- if (detail?.reason === 'no-subscription') return 'Your FloLess subscription is not active. Restore access, then send your message again. Nothing changed.';
4133
- return 'FloLess could not access this answer. Check your sign-in and project access, then send your message again. Nothing changed.';
4134
- }
4135
-
4136
- /**
4137
- * Start the read-only guide run. Resolves 'started', 'unconfirmed' (checking), or { refused: message }.
4138
- * `notStarted: true` on a refusal means no AI can have started on it, so its words can be given back;
4139
- * `runtime` is then the setup status when FloLess setting its AI up was the cause (#1650, #1643).
4140
- */
4141
- async function startFilterRun(requestId, runtime) {
4142
- const controller = new AbortController();
4143
- const deadline = setTimeout(() => controller.abort(), 15000);
4144
- let started;
4145
- try {
4146
- started = await fetch(`/api/requests/${encodeURIComponent(requestId)}/run`, {
4147
- method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ runtime }), signal: controller.signal,
4148
- });
4149
- } catch { clearTimeout(deadline); return 'unconfirmed'; } // the server may have accepted it before the reply was lost
4150
- if (started.ok) { clearTimeout(deadline); return 'started'; }
4151
- const detail = await started.json().catch(() => null);
4152
- clearTimeout(deadline);
4153
- if (started.status === 409 && detail?.code === 'running') return 'started';
4154
- // The run route flags a refusal it made before anything started (#1650, #1643). Definite even as a
4155
- // 5xx; one without its notice is not trusted, and falls through to the rules below.
4156
- if (detail?.notStarted === true && typeof detail.notice === 'string' && detail.notice) {
4157
- return { refused: detail.notice, notStarted: true, runtime: detail.runtime ?? null };
4158
- }
4159
- if (detail?.code === 'filter-ai-provider-mismatch' && typeof detail.error === 'string') return { refused: detail.error };
4160
- if ((started.status === 409 && !detail) || started.status >= 500) return 'unconfirmed';
4161
- // The sign-in and licence check refuses before the route runs, so nothing started either.
4162
- if ([401, 402, 403].includes(started.status)) return { refused: filterAccessFailure(started.status, detail), notStarted: true };
4163
- // Several refusals land here, each with a different cause, so the sentence names none of them.
4164
- return { refused: 'FloLess could not start AI for this request. Nothing changed. Send it again from AI Chat.' };
4165
- }
4166
-
4167
- /**
4168
- * Request events (the linked question and the published answer) are written straight to the
4169
- * conversation store and never reach the live event stream, so read them back explicitly.
4170
- * Resolves true once the conversation was read.
4171
- */
4172
- async function mergeFilterEvents(chatId) {
4173
- if (state.chat?.chatId !== chatId || !state.scope?.owner) return false;
4174
- const snapshot = captureChat();
4175
- const path = `/api/chat/conversations/${encodeURIComponent(chatId)}/events-snapshot?${ownerQuery(snapshot.scope.owner)}`;
4176
- let listed;
4177
- try {
4178
- try { listed = await request(path); }
4179
- catch (error) {
4180
- // The chat session is short-lived; renew it once, as refreshConversation does.
4181
- if (!sessionNeedsRenewal(error)) throw error;
4182
- state.sessionReady = false;
4183
- await ensureSession();
4184
- listed = await request(path);
4185
- }
4186
- } catch (error) {
4187
- console.error('[chat] could not read back the Drawing Filter messages:', error);
4188
- return false;
4189
- }
4190
- if (!sameChat(snapshot)) return false;
4191
- let added = false;
4192
- for (const event of listed.events || []) {
4193
- if (state.events.some((item) => item.eventId === event.eventId)) continue;
4194
- state.events.push(event); added = true;
4195
- }
4196
- if (added) {
4197
- state.events.sort((a, b) => a.sequence - b.sequence);
4198
- state.chat.lastEventSequence = Math.max(state.chat.lastEventSequence || 0, ...state.events.map((event) => event.sequence || 0));
4199
- paintEvents({ forceBottom: true });
4200
- }
4201
- return true;
4202
- }
4203
-
4204
- /** After an uncertain link: true only when Requests records this request linked to this conversation. */
4205
- async function filterRequestLinked(requestId, chatId) {
4206
- // Send stays blocked meanwhile, so this read is bounded; a slow list simply proves nothing.
4207
- const listed = await fetch('/api/requests', { signal: AbortSignal.timeout(30000) })
4208
- .then((response) => (response.ok ? response.json() : null)).catch(() => null);
4209
- const row = Array.isArray(listed?.requests) ? listed.requests.find((candidate) => candidate?.id === requestId) : null;
4210
- return row?.chatConversation?.chatId === chatId;
4211
- }
4212
-
4213
- function finishFilterPending(entry, notice) {
4214
- if (state.filterPending.get(entry.requestId) !== entry) return false;
4215
- state.filterPending.delete(entry.requestId);
4216
- if (notice) { state.filterNotices.set(entry.requestId, notice); announce(notice); }
4217
- if (state.chat?.chatId === entry.chatId) { paintEvents(); updateSendState(); }
4218
- return true;
4219
- }
4220
-
4221
- function filterPollRecovered(entry) {
4222
- entry.failures = 0;
4223
- if (entry.retryNote) { entry.retryNote = ''; if (state.chat?.chatId === entry.chatId) paintEvents(); }
4224
- }
4225
-
4226
- function filterPollFailure(entry, stopped = FILTER_CHECK_STOPPED, retrying = FILTER_CHECK_RETRY) {
4227
- entry.failures += 1;
4228
- if (entry.failures >= 3) { finishFilterPending(entry, stopped); return; }
4229
- entry.retryNote = retrying;
4230
- if (state.chat?.chatId === entry.chatId) paintEvents();
4231
- }
4232
-
4233
- /**
4234
- * Check one pending request again after `delay`. Each request runs its own chain of checks, started
4235
- * once by sendFilterAi or resumeFilterRequests, so a slow or broken request never holds up another.
4236
- */
4237
- function scheduleFilterPoll(entry, delay = 2000) {
4238
- clearTimeout(entry.timer);
4239
- entry.timer = setTimeout(() => { void pollFilterRequest(entry); }, delay);
4240
- }
4241
-
4242
- /** One bounded check of one request. While the request is still pending, the next check is scheduled. */
4243
- async function pollFilterRequest(entry) {
4244
- const current = () => state.filterPending.get(entry.requestId) === entry;
4245
- try {
4246
- const query = new URLSearchParams({ app: entry.appId || '', ...(entry.project ? { project: entry.project } : {}) });
4247
- const response = await fetch(`/api/filter-ai-answer/${encodeURIComponent(entry.requestId)}?${query}`,
4248
- { signal: AbortSignal.timeout(15000) }).catch(() => null);
4249
- if (!current()) return;
4250
- if (!response) { filterPollFailure(entry); return; }
4251
- if (response.status === 401 || response.status === 403) { finishFilterPending(entry, filterAccessFailure(response.status)); return; }
4252
- if (response.status === 402) {
4253
- const detail = await response.json().catch(() => null);
4254
- if (current()) finishFilterPending(entry, filterAccessFailure(402, detail));
4255
- return;
4256
- }
4257
- const result = response.ok ? await response.json().catch(() => null) : null;
4258
- if (!current()) return;
4259
- if (response.status === 404 || result?.state === 'gone') { finishFilterPending(entry, 'This request is no longer available. Send it again from the current filter. Nothing changed.'); return; }
4260
- if (!result) { filterPollFailure(entry); return; }
4261
- if (result.state === 'waiting') { filterPollRecovered(entry); return; }
4262
- if (result.state === 'failed') { finishFilterPending(entry, result.error || 'AI could not answer this. Send it again. The filter has not changed.'); return; }
4263
- // Reading Requests is what publishes a validated answer into its linked conversation. It lists
4264
- // every request and can be slow on a busy machine, so its bound is generous.
4265
- const listed = await fetch('/api/requests', { signal: AbortSignal.timeout(90000) })
4266
- .then((res) => (res.ok ? res.json() : null)).catch(() => null);
4267
- if (!current()) return;
4268
- if (!Array.isArray(listed?.chatPublications)) {
4269
- filterPollFailure(entry,
4270
- 'FloLess could not confirm whether this answer was added to the conversation. Reopen the conversation to check; if it is not there, open Requests. Nothing changed.',
4271
- 'The answer is ready. FloLess could not confirm whether it was added yet. Trying again.');
4272
- return;
4273
- }
4274
- filterPollRecovered(entry);
4275
- const published = listed.chatPublications.some((publication) => publication?.requestId === entry.requestId);
4276
- const here = state.chat?.chatId === entry.chatId;
4277
- if (here) await mergeFilterEvents(entry.chatId);
4278
- if (!current()) return;
4279
- // Done once the answer is on screen, or published into a conversation that is not open here.
4280
- if ((here && filterAnswered(entry.requestId)) || (!here && published)) { finishFilterPending(entry, null); return; }
4281
- // Publication and the read-back can lag the answer; the next checks try again before saying so.
4282
- entry.readBack = (entry.readBack || 0) + 1;
4283
- if (entry.readBack < 5) return;
4284
- finishFilterPending(entry, published
4285
- ? 'The answer was added to this conversation but could not be shown here. Reopen the conversation to see it.'
4286
- : 'The answer is ready but FloLess could not add it to this conversation. Open Requests to read it.');
4287
- } catch (error) {
4288
- // A bug in this check counts as a failed check, so it still stops after three instead of looping.
4289
- console.error('[chat] checking a Drawing Filter answer failed:', error);
4290
- if (current()) filterPollFailure(entry);
4291
- } finally {
4292
- if (current()) scheduleFilterPoll(entry);
4293
- }
4294
- }
4295
-
4296
- /**
4297
- * After a reload or reopening a project conversation, keep watching its unanswered filter requests:
4298
- * the newest five that show neither an answer nor a failure notice from this page session.
4299
- */
4300
- function resumeFilterRequests() {
4301
- const chat = state.chat;
4302
- if (!chat || state.scope?.owner?.kind !== 'project') return;
4303
- const unanswered = state.events.filter((event) => event.type === 'user-message' && event.payload?.filterAi
4304
- && event.payload.requestId && !filterAnswered(event.payload.requestId)
4305
- && !state.filterPending.has(event.payload.requestId) && !state.filterNotices.has(event.payload.requestId)).slice(-5);
4306
- for (const event of unanswered) {
4307
- const entry = {
4308
- requestId: event.payload.requestId, chatId: chat.chatId, kind: event.payload.filterAi.kind,
4309
- appId: event.payload.filterAi.appId || '', project: state.scope.owner.projectId, failures: 0, note: '',
4310
- };
4311
- state.filterPending.set(entry.requestId, entry);
4312
- scheduleFilterPoll(entry, 0);
4313
- }
4314
- }
4315
-
4316
- /**
4317
- * Hand a setup status to this conversation's own setup card (#1650): the card polls it, explains it,
4318
- * offers Cancel or Try again, and keeps Send locked until the AI is set up. Only for the conversation
4319
- * that sent the message, while it is still that AI's, and only for a status the card can show.
4320
- */
4321
- function adoptRuntimeStatus(snapshot, provider, status) {
4322
- if (!status || typeof status !== 'object' || !['preparing', 'not-installed', 'failed'].includes(status.state)
4323
- || !sameChat(snapshot) || !state.capability || state.chat?.provider !== provider) return false;
4324
- state.capability = { ...state.capability, runtime: status };
4325
- paintRuntime();
4326
- return true;
4327
- }
4328
-
4329
- /** Why a Drawing Filter message was not sent while its AI is set up. The status decides; without one, no cause is claimed. */
4330
- function filterSetupSentence(provider, status) {
4331
- const name = providerLabels[provider] || 'the AI';
4332
- if (status?.state === 'preparing' || status?.state === 'not-installed') {
4333
- return `FloLess is setting up ${name}, so this message was not sent. It is back in your draft; send it once setup finishes.`;
4334
- }
4335
- if (status?.state === 'failed') return `${providerLabels[provider] || 'The AI'} could not be set up, so this message was not sent. It is back in your draft.`;
4336
- // No status, a failed call (one that timed out may still have started the setup), or a state this
4337
- // build cannot name.
4338
- return `FloLess could not confirm that it is setting up ${name}, so this message was not sent. It is back in your draft; try again.`;
4339
- }
4340
-
4341
- /**
4342
- * Ask FloLess to set up the conversation's own AI, through the setup card's Retry route (idempotent).
4343
- * Resolves `{ installed: true }` when it already is, else the sentence to refuse the message with,
4344
- * having handed the status to the card. It never waits for the setup: the card carries that wait.
4345
- * `text` is the refused message, which the refusal puts back in the draft.
4346
- */
4347
- async function prepareFilterRuntime(snapshot, provider, text) {
4348
- let status = null;
4349
- try {
4350
- status = (await request(`/api/managed-runtimes/${encodeURIComponent(provider)}/prepare`, { method: 'POST', body: '{}', timeoutMs: 10000 }))?.runtime || null;
4351
- } catch (error) { console.warn('[chat] could not ask FloLess to set up the Drawing Filter AI:', error); }
4352
- if (status?.state === 'installed') return { installed: true };
4353
- const sentence = filterSetupSentence(provider, status);
4354
- // The card's status check repaints the hint every two seconds; the sentence stays there while the
4355
- // card shows the setup it was refused for and the words are in the draft (filterSetupHint), not only
4356
- // until the first repaint.
4357
- if (adoptRuntimeStatus(snapshot, provider, status)) {
4358
- state.filterSetupNote = { key: runtimeCardKey(snapshot.chatId, status), sentence, text };
4359
- }
4360
- return { installed: false, sentence };
4361
- }
4362
-
4363
- /**
4364
- * Read the pictures on the composer into the data URLs `/api/guide` stores beside the request.
4365
- *
4366
- * A COPY, ON PURPOSE. The headless run gets its own leased file under the requests directory —
4367
- * it never reaches into the conversation's attachment store — so the picture the AI was shown
4368
- * stays exactly the picture that was attached, whatever happens to the chat afterwards.
4369
- *
4370
- * Throws a refusal on the first unreadable one rather than sending a shorter list: a message that
4371
- * quietly carries two of three pictures is answered as if the third never existed.
4372
- */
4373
- async function filterAiPictures(attachments, chatId, owner) {
4374
- const pictures = [];
4375
- for (const attachment of attachments) {
4376
- let dataUrl;
4377
- try {
4378
- const response = await fetch(
4379
- `/api/chat/conversations/${encodeURIComponent(chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}?${ownerQuery(owner)}`,
4380
- { signal: AbortSignal.timeout(20000) });
4381
- if (!response.ok) throw new Error(`attachment read failed (${response.status})`);
4382
- const blob = await response.blob();
4383
- dataUrl = await new Promise((resolve, reject) => {
4384
- const reader = new FileReader();
4385
- reader.onerror = () => reject(reader.error || new Error('attachment could not be read'));
4386
- reader.onload = () => resolve(String(reader.result || ''));
4387
- reader.readAsDataURL(blob);
4388
- });
4389
- } catch (error) {
4390
- console.error('[chat] a Drawing Filter attachment could not be read:', error);
4391
- throw filterRefusal(`FloLess could not read “${attachment.fileName}”, so nothing was sent. Attach it again, then send the message.`);
4392
- }
4393
- pictures.push({ name: attachment.fileName, dataUrl, role: 'reference' });
4394
- }
4395
- return pictures;
4396
- }
4397
-
4398
- /**
4399
- * Drop the composer rows whose bytes are now copied onto the request.
4400
- *
4401
- * Local state alone is not enough: reopening the conversation repaints the composer from the
4402
- * chat's own pending attachments, so a row left behind would come back and be sent twice.
4403
- */
4404
- async function discardSentFilterAttachments(attachments, chatId, owner) {
4405
- const cleared = new Set();
4406
- const stranded = [];
4407
- for (const attachment of attachments) {
4408
- try {
4409
- await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}`, {
4410
- method: 'DELETE', timeoutMs: 10000, body: JSON.stringify({ owner }),
4411
- });
4412
- cleared.add(attachment.attachmentId);
4413
- } catch (error) {
4414
- console.warn('[chat] a sent Drawing Filter attachment was not cleared:', error);
4415
- stranded.push(attachment.fileName);
4416
- }
4417
- }
4418
- // BOTH LISTS, as the chip's own remove handler does. `state.chat.attachments` is what the
4419
- // conversation-wide budget counts (ten files, fifty megabytes), so pruning only the composer
4420
- // would spend that budget on pictures that no longer exist and refuse the next real one.
4421
- if (state.chat?.chatId === chatId) {
4422
- state.chat.attachments = (state.chat.attachments || []).filter((item) => !cleared.has(item.attachmentId));
4423
- }
4424
- // A row that would not delete is still on the server, and the composer is repainted from the
4425
- // server on the next refresh — so it comes back and rides the person's NEXT, unrelated message.
4426
- // They are the only one who can clear it, so say so rather than leaving it in the console.
4427
- if (stranded.length) {
4428
- report(filterRefusal(`Your message was sent, but ${stranded.map((name) => `“${name}”`).join(' and ')} `
4429
- + `${stranded.length > 1 ? 'are' : 'is'} still attached to this conversation. Remove `
4430
- + `${stranded.length > 1 ? 'them' : 'it'} from the box below so ${stranded.length > 1 ? 'they do' : 'it does'} not go with your next message.`));
4431
- }
4432
- }
4433
-
4434
- async function sendFilterAi(surface) {
4435
- const snapshot = captureChat();
4436
- if (!snapshot || state.filterSending) return;
4437
- const chat = state.chat;
4438
- const kind = 'change';
4439
- const text = ui.input.value.trim();
4440
- if (!text) return;
4441
- const refusal = filterSendRefusal(surface, text);
4442
- if (refusal) { report(filterRefusal(refusal)); return; }
4443
- // The draft is set aside before the first await, as a normal Send does: anything typed from here
4444
- // on is newer than the submitted message and must survive whatever happens to it.
4445
- // restoreBackgroundDraft skips a message the conversation already shows under this id; a Drawing
4446
- // Filter message carries none, so a fresh id means the refused text is always given back.
4447
- const submissionId = crypto.randomUUID();
4448
- clearTimeout(state.draftTimer);
4449
- state.localDraft = { chatId: snapshot.chatId, text: '' };
4450
- state.backgroundDrafts.delete(snapshot.chatId);
4451
- // Captured before the composer is cleared, and put back by the catch below if nothing was sent —
4452
- // the same contract the words get.
4453
- const attached = state.attachments.slice();
4454
- // Set the moment the rows are handed to the server for deletion, so the catch below never offers
4455
- // back a chip whose record is gone — its preview would 404 and every later send would refuse.
4456
- let discarded = false;
4457
- ui.input.value = ''; autosize();
4458
- state.attachments = []; paintAttachments();
4459
- state.filterSending = true; updateSendState();
4460
- let requestId = null;
4461
- let failure = null;
4462
- try {
4463
- await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
4464
- // Decided from what launching this conversation's own AI would see NOW, a read of its own (#1650):
4465
- // the rows AI Chat was painted from can say "set up" for a copy of FloLess's that has gone since.
4466
- // It answers only with this conversation's own provider, never a silently substituted one.
4467
- // The read logs its own network and shape failures; a rejection here is a fault in the bridge.
4468
- const launch = await window.flolessBridge?.filterRuntimeLaunch?.(chat.provider).catch((error) => {
4469
- console.error('[chat] the Drawing Filter could not read which AI can start:', error);
4470
- return null;
4471
- });
4472
- if (!launch || launch.readiness === 'unchecked') {
4473
- throw filterRefusal('FloLess could not check which AI can answer Drawing Filter messages. Try again in a moment. Nothing was sent.');
4474
- }
4475
- if (launch.readiness === 'setup') {
4476
- // FloLess has to set its own copy up first. Nothing is created: the setup starts, this
4477
- // conversation's setup card shows it and keeps Send locked until it lands, and the words go back.
4478
- const setup = await prepareFilterRuntime(snapshot, chat.provider, text);
4479
- if (!setup.installed) throw filterRefusal(setup.sentence);
4480
- // It finished between the read and the prepare: send as usual.
4481
- } else if (launch.readiness !== 'ready') {
4482
- throw filterRefusal(`${providerLabels[chat.provider] || 'This AI'} cannot answer Drawing Filter messages on this computer yet. Check it in Integrations, or start a conversation with the other provider. Nothing was sent.`);
4483
- }
4484
- // The promise belongs to the filter page. A page thrown away mid-request never settles it, so
4485
- // the chat keeps its own deadline rather than leaving Send blocked in every conversation.
4486
- const pictures = attached.length ? await filterAiPictures(attached, snapshot.chatId, snapshot.scope.owner) : [];
4487
- const created = await Promise.race([
4488
- surface.bridge.createRequest(kind, text, pictures),
4489
- // ONE DEADLINE, and it must not be shorter than the filter page's own: that page waits 60s
4490
- // when pictures ride in the body (they are megabytes, not a few hundred bytes of narration).
4491
- // Racing it at 20s declared failure while the request was still being written, leaving a real
4492
- // request in Requests while the composer invited a retry that would duplicate it.
4493
- new Promise((resolve) => { setTimeout(resolve, pictures.length ? 60000 : 20000, { ok: false, message: FILTER_CREATE_TIMEOUT }); }),
4494
- ]);
4495
- if (!created?.ok) {
4496
- throw filterRefusal([401, 402, 403].includes(created?.status)
4497
- ? filterAccessFailure(created.status, { reason: created.reason })
4498
- : created?.message || 'FloLess could not start this request. Nothing was sent.');
4499
- }
4500
- requestId = created.request.id;
4501
- let linked = false;
4502
- let uncertain = false;
4503
- let linkError = null;
4504
- for (let attempt = 0; attempt < 2 && !linked; attempt++) {
4505
- try {
4506
- await request(`/api/chat/requests/${encodeURIComponent(requestId)}/start`, {
4507
- method: 'POST', timeoutMs: 10000,
4508
- body: JSON.stringify({ provider: chat.provider, mode: 'discuss', chatId: snapshot.chatId, expectedOwner: snapshot.scope.owner }),
4509
- });
4510
- linked = true;
4511
- } catch (error) {
4512
- linkError = error;
4513
- if (sessionNeedsRenewal(error)) { state.sessionReady = false; await ensureSession().catch(() => {}); continue; }
4514
- // A definite refusal stops retrying. It only proves nothing was linked when no earlier attempt
4515
- // was uncertain: a retry's refusal can follow a first attempt that did persist the link
4516
- // (another tab started a turn). `uncertain` never resets.
4517
- if (FILTER_LINK_REFUSALS.has(String(error?.code || '')) || error?.status === 400) break;
4518
- uncertain = true;
4519
- }
4520
- }
4521
- if (!linked && uncertain) {
4522
- // Only proof of the link lets it continue. No link yet proves nothing: the lost attempt may still
4523
- // be writing it, so nothing is deleted and the request stays in Requests.
4524
- if (!(await filterRequestLinked(requestId, snapshot.chatId))) {
4525
- throw filterRefusal('FloLess could not confirm whether this message reached AI Chat. Check Requests before sending it again.');
4526
- }
4527
- linked = true;
4528
- }
4529
- if (!linked) {
4530
- try { surface.bridge.forget(requestId); } catch { /* the filter reloaded; it has no record */ }
4531
- const cleared = await fetch(`/api/requests/${encodeURIComponent(requestId)}`, { method: 'DELETE', signal: AbortSignal.timeout(10000) })
4532
- .then((response) => response.ok).catch(() => false);
4533
- const why = FILTER_LINK_REFUSAL_COPY[String(linkError?.code || '')]
4534
- || 'FloLess could not add this message to the conversation. Nothing was sent. Send it again.';
4535
- throw filterRefusal(cleared ? why : `${why} The unsent request is still listed in Requests; you can clear it there.`);
4536
- }
4537
- // Linked durably, but the saved draft still holds the sent words. Rewrite it now rather than on
4538
- // saveDraftSoon's debounce, so a reload cannot bring the sent message back; the composer's current
4539
- // text (empty, or typed during creation or linking) is what survives.
4540
- const draft = sameChat(snapshot) ? ui.input.value : state.backgroundDrafts.get(snapshot.chatId) ?? '';
4541
- if (sameChat(snapshot)) {
4542
- clearTimeout(state.draftTimer);
4543
- state.localDraft = { chatId: snapshot.chatId, text: draft };
4544
- }
4545
- state.draftVersions.set(snapshot.chatId, (state.draftVersions.get(snapshot.chatId) || 0) + 1);
4546
- state.backgroundDrafts.set(snapshot.chatId, draft);
4547
- if (draftFitsStorage(snapshot.scope.owner, draft)) {
4548
- void writeChatDraft(snapshot.chatId, snapshot.scope.owner, draft)
4549
- .catch((error) => { if (sameChat(snapshot)) report(error, 'Draft was not saved'); });
4550
- }
4551
- // The bytes are on the request now, so the composer rows have done their job.
4552
- const entry = { requestId, chatId: snapshot.chatId, kind, appId: created.request.appId || '', project: created.request.project || '', failures: 0, note: '' };
4553
- state.filterPending.set(requestId, entry);
4554
- state.filterNotices.delete(requestId);
4555
- // Start AI first, so nothing between the link and the run can leave a linked request unstarted.
4556
- const started = await startFilterRun(requestId, chat.provider);
4557
- await mergeFilterEvents(snapshot.chatId);
4558
- if (started?.refused) {
4559
- finishFilterPending(entry, started.refused);
4560
- if (started.notStarted) {
4561
- // Nothing started, so the words come back to the draft; the conversation also keeps them, with
4562
- // the notice under them. The setup card shows when FloLess setting its AI up was the cause,
4563
- // first: it announces itself, and the live region keeps only its last line, so that line is the
4564
- // whole notice (what happened, why, what next) and then where the words are. The message is in
4565
- // the conversation, so a merge never calls it unsent. A refusal that is not flagged (another
4566
- // owner's message) or a lost reply gives nothing back.
4567
- adoptRuntimeStatus(snapshot, chat.provider, started.runtime);
4568
- await restoreBackgroundDraft(snapshot, text, submissionId, {
4569
- announcement: `${started.refused} Its text is back in your draft.`,
4570
- mergeLabel: 'Earlier message AI did not start on:',
4571
- mergedAnnouncement: `${started.refused} Its text was added to your draft. Review it before sending.`,
4572
- });
4573
- }
4574
- return;
4575
- }
4576
- // The bytes are on the request AND the run is under way, so the composer rows have done their
4577
- // job. Deliberately after `startFilterRun`: a refusal above gives the pictures back with the
4578
- // words, which it could not do once these rows are gone.
4579
- if (attached.length) { discarded = true; await discardSentFilterAttachments(attached, snapshot.chatId, snapshot.scope.owner); }
4580
- if (started === 'unconfirmed') entry.note = 'Checking whether AI started…';
4581
- announce(FILTER_PENDING);
4582
- if (sameChat(snapshot)) paintEvents({ forceBottom: true });
4583
- scheduleFilterPoll(entry, 0);
4584
- } catch (error) {
4585
- failure = error;
4586
- // Nothing was sent, so the pictures go back to the composer with the words — but ONLY while
4587
- // their server records still exist. Several awaits run after the discard (the run start, the
4588
- // event merge, a refusal's own restore), and a throw in any of them lands here; handing back
4589
- // deleted rows would render chips whose previews 404 and make every later send refuse.
4590
- // MERGED, not assigned: a second tab's row can reach this state, and overwriting would make it
4591
- // disappear from the composer with nothing said.
4592
- if (attached.length && !discarded && sameChat(snapshot)) {
4593
- const returning = new Set(attached.map((item) => item.attachmentId));
4594
- state.attachments = [...attached, ...state.attachments.filter((item) => !returning.has(item.attachmentId))];
4595
- paintAttachments();
4596
- }
4597
- await restoreBackgroundDraft(snapshot, text, submissionId);
4598
- } finally {
4599
- state.filterSending = false;
4600
- // updateSendState() repaints the hint, so the refusal is reported after it, not before.
4601
- if (sameChat(snapshot)) {
4602
- updateSendState();
4603
- if (failure) report(failure, failure.filterRefusal ? '' : 'Message was not sent');
4604
- }
4605
- }
4606
- }
4607
-
4608
5619
  function filterChangeLabel(item) {
4609
5620
  if (item.dimension === 'thickness') return `line weight ${item.value} pt`;
4610
5621
  return `${item.dimension} ${item.value}`;
@@ -4620,12 +5631,17 @@
4620
5631
  * No page at all (not opened since this window loaded, or reloading) means the page that recorded
4621
5632
  * the suggestion is gone, exactly like an unknown record.
4622
5633
  */
4623
- function inspectFilterSuggestion(requestId, proposal) {
5634
+ function inspectFilterSuggestion(requestId, proposal, base = null) {
4624
5635
  let bridge = null;
4625
5636
  try { bridge = document.getElementById('ws-frame-drawings')?.contentWindow?.__floFilterAi || null; }
4626
5637
  catch (error) { warnFilterBridge(error); }
4627
5638
  let info = null;
4628
- try { info = bridge ? bridge.inspect(requestId, proposal) : null; } catch (error) { warnFilterBridge(error); }
5639
+ try {
5640
+ // A suggestion the AI made through floless_filter_propose (#1859) carries its base in the server record, so
5641
+ // ANY page instance can check it — the page adopts that base rather than needing to have sent the message.
5642
+ if (bridge && base) bridge.adopt?.(requestId, base);
5643
+ info = bridge ? bridge.inspect(requestId, proposal) : null;
5644
+ } catch (error) { warnFilterBridge(error); }
4629
5645
  if (!info) return { known: false, applicable: false, reason: FILTER_PAGE_GONE, open: false };
4630
5646
  const open = filterSurface().state === 'ready';
4631
5647
  // An unknown record keeps its own reason: opening the Drawing Filter would not bring it back.
@@ -4648,13 +5664,24 @@
4648
5664
  const requestId = String(event.payload.requestId || '');
4649
5665
  const proposal = event.payload.filterAi.proposal;
4650
5666
  const hasChanges = proposal.changes.length > 0 || proposal.mode !== null;
4651
- const info = inspectFilterSuggestion(requestId, proposal);
5667
+ const server = event.payload.serverProposal ? serverProposalState(event.payload.serverProposal) : null;
5668
+ let info = inspectFilterSuggestion(requestId, proposal, server ? server.base : null);
5669
+ // The server record is the truth about what happened to a suggestion; the page only knows its own session.
5670
+ // An unsettled claim ('applying') wins even over the page's own "applied": the ticks may have changed, but the
5671
+ // outcome was never recorded, so the card must not say it was confirmed.
5672
+ if (server && server.disposition !== 'pending'
5673
+ && (server.disposition === 'applying' || !info.known || info.disposition === 'pending')) {
5674
+ info = { ...info, known: true, applicable: false, undo: false, disposition: server.disposition === 'applying' ? 'applying' : server.disposition,
5675
+ note: SERVER_PROPOSAL_NOTES[server.disposition] || server.reason || '' };
5676
+ if (server.disposition === 'stale') info.note = server.reason || SERVER_PROPOSAL_NOTES.stale;
5677
+ }
4652
5678
  const disposition = info.known ? info.disposition : 'pending';
4653
5679
  // An unknown record (reload, another window) claims no outcome, only that it predates this view.
4654
5680
  // "not saved" only while this suggestion's own Undo is live: Save and later edits retire it.
4655
5681
  const chip = card.querySelector('.ai-chat-filter-state');
4656
5682
  chip.textContent = !info.known ? 'from an earlier view' : {
4657
5683
  applied: info.undo ? 'applied, not saved' : 'applied', kept: 'not applied', undone: 'undone',
5684
+ applying: 'could not confirm', stale: 'no longer applies',
4658
5685
  }[disposition] || 'not applied';
4659
5686
  const status = card.querySelector('.ai-chat-filter-note');
4660
5687
  const override = state.filterCardMessages.get(requestId);
@@ -4689,6 +5716,7 @@
4689
5716
  }
4690
5717
 
4691
5718
  function runFilterSuggestionAction(action, event) {
5719
+ if (event.payload.serverProposal && action !== 'undo') { void runServerProposalAction(action, event); return; }
4692
5720
  const requestId = String(event.payload.requestId || '');
4693
5721
  // Re-resolve the page at click time: the frame may have reloaded since this card was painted.
4694
5722
  const surface = filterSurface();
@@ -4755,44 +5783,175 @@
4755
5783
  }
4756
5784
 
4757
5785
  function renderFilterQuestion(event) {
4758
- // The person's own words, like any message; only a wait or a failure adds a line under them.
4759
- const item = renderMessage(event, 'user', payloadText(event));
4760
- const requestId = String(event.payload.requestId || '');
4761
- const pending = state.filterPending.get(requestId);
4762
- const notice = state.filterNotices.get(requestId);
4763
- if (pending && !filterAnswered(requestId)) {
4764
- const live = document.createElement('div'); live.className = 'ai-chat-live-status ai-chat-filter-pending';
4765
- const label = document.createElement('span'); label.className = 'ai-chat-live-label';
4766
- label.textContent = pending.retryNote || pending.note || FILTER_PENDING;
4767
- live.append(animatedDots(), label);
4768
- item.append(live);
4769
- } else if (notice && !filterAnswered(requestId)) {
4770
- const failed = document.createElement('p'); failed.className = 'ai-chat-filter-notice'; failed.setAttribute('role', 'status');
4771
- failed.textContent = notice;
4772
- item.append(failed);
4773
- }
4774
- return item;
5786
+ // A Drawing Filter question from before #1859: the person's own words, like any message. Nothing
5787
+ // waits on it any more; its answer, if one was published, is its own event.
5788
+ return renderMessage(event, 'user', payloadText(event));
4775
5789
  }
4776
5790
 
4777
5791
  /** Re-read the live filter state for every visible suggestion card, in place. */
4778
5792
  function refreshFilterCards() {
4779
5793
  for (const card of ui.feed.querySelectorAll('.ai-chat-filter-card')) {
4780
5794
  const event = state.events.find((candidate) => candidate.eventId === card.dataset.eventId);
4781
- if (event?.payload?.filterAi?.proposal) paintFilterSuggestion(card, event);
5795
+ if (event?.type === 'filter-proposal') paintFilterSuggestion(card, serverProposalCardEvent(event));
5796
+ else if (event?.payload?.filterAi?.proposal) paintFilterSuggestion(card, event);
5797
+ }
5798
+ }
5799
+
5800
+ /** What became of each suggestion, from the server's own record of it (#1859): later updates win. */
5801
+ const SERVER_PROPOSAL_NOTES = {
5802
+ applied: 'Applied. Undo is no longer available here. Change the ticks by hand if needed, and press Save filter to keep them.',
5803
+ applying: 'FloLess could not confirm whether this suggestion reached the Drawing Filter. Check the ticks on the drawing before you save.',
5804
+ kept: 'Kept your current selection. No changes were made.',
5805
+ stale: 'The Drawing Filter changed after this suggestion, so it was not applied. Ask again for a current one.',
5806
+ };
5807
+
5808
+ function serverProposalState(payload) {
5809
+ let disposition = payload.disposition || 'pending';
5810
+ let reason = payload.reason || null;
5811
+ for (const event of state.events) {
5812
+ if (event.type !== 'filter-proposal-update' || event.payload?.proposalId !== payload.proposalId) continue;
5813
+ disposition = event.payload.disposition || disposition;
5814
+ reason = event.payload.reason || null;
5815
+ }
5816
+ return { disposition, reason, base: payload.base };
5817
+ }
5818
+
5819
+ /** A `filter-proposal` event in the shape the suggestion card already paints. */
5820
+ function serverProposalCardEvent(event) {
5821
+ const payload = event.payload || {};
5822
+ return { ...event, payload: { requestId: `proposal:${payload.proposalId}`, serverProposal: payload,
5823
+ filterAi: { kind: 'change', proposal: { explanation: String(payload.explanation || ''), changes: Array.isArray(payload.changes) ? payload.changes : [],
5824
+ mode: payload.mode ?? null } } } };
5825
+ }
5826
+
5827
+ function renderServerProposal(event) {
5828
+ const shaped = serverProposalCardEvent(event);
5829
+ const card = renderFilterSuggestion(shaped);
5830
+ card.dataset.eventId = event.eventId;
5831
+ card.dataset.eventSequence = String(event.sequence);
5832
+ // The AI's own words go on the card as plain text, under its title.
5833
+ const why = document.createElement('p'); why.className = 'ai-chat-filter-why';
5834
+ why.textContent = shaped.payload.filterAi.proposal.explanation;
5835
+ card.querySelector('.ai-chat-filter-card-head')?.after(why);
5836
+ return card;
5837
+ }
5838
+
5839
+ /**
5840
+ * Apply or Keep a suggestion the AI made through floless_filter_propose (#1859). Apply CLAIMS it on the server
5841
+ * first, so a second click or another window can never apply it twice; the page then applies it to the
5842
+ * on-screen selection, and the outcome is settled. A claim that is never settled is never reopened.
5843
+ */
5844
+ async function runServerProposalAction(action, event) {
5845
+ const payload = event.payload.serverProposal;
5846
+ const requestId = String(event.payload.requestId || '');
5847
+ const snapshot = captureChat();
5848
+ if (!snapshot) return;
5849
+ const path = `/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/filter-proposals/${encodeURIComponent(payload.proposalId)}`;
5850
+ // Each step's update event comes back with it, so the card repaints from the server's record at once.
5851
+ const post = async (verb, body = {}) => {
5852
+ const result = await request(`${path}/${verb}`, { method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, ...body }) });
5853
+ if (sameChat(snapshot)) for (const item of result?.events || []) if (!state.events.some((known) => known.eventId === item.eventId)) state.events.push(item);
5854
+ return result;
5855
+ };
5856
+ let message;
5857
+ try {
5858
+ if (action === 'keep') {
5859
+ await post('keep');
5860
+ try { filterSurface().bridge?.keep?.(requestId); } catch (error) { warnFilterBridge(error); }
5861
+ message = SERVER_PROPOSAL_NOTES.kept;
5862
+ } else {
5863
+ const surface = filterSurface();
5864
+ if (surface.state !== 'ready') throw Object.assign(new Error(FILTER_NOT_OPEN), { plain: true });
5865
+ // Checked on the page BEFORE the claim, so a suggestion that no longer fits is never claimed.
5866
+ const check = surface.bridge.inspect(requestId, event.payload.filterAi.proposal);
5867
+ if (!check?.applicable) throw Object.assign(new Error(check?.reason || FILTER_NOT_OPEN), { plain: true });
5868
+ const opId = crypto.randomUUID();
5869
+ await post('claim', { opId });
5870
+ let result;
5871
+ try { result = surface.bridge.apply(requestId, event.payload.filterAi.proposal); }
5872
+ catch (error) {
5873
+ console.error('[chat] the Drawing Filter could not apply a suggestion:', error);
5874
+ result = null;
5875
+ }
5876
+ if (result?.ok) {
5877
+ await post('settle', { opId, outcome: 'applied' });
5878
+ message = result.message;
5879
+ } else {
5880
+ const reason = result?.message || 'The Drawing Filter could not apply this suggestion.';
5881
+ // Released only because the page refused at that instant; a thrown apply stays unconfirmed.
5882
+ if (result) await post('settle', { opId, outcome: 'released', reason });
5883
+ message = result ? reason : SERVER_PROPOSAL_NOTES.applying;
5884
+ }
5885
+ }
5886
+ state.filterCardMessages.delete(requestId);
5887
+ } catch (error) {
5888
+ message = error?.plain ? error.message
5889
+ : error?.code === 'chat-filter-proposal-used' || error?.status === 409 ? 'This suggestion was already used, so it was not applied again.'
5890
+ : 'FloLess could not record what happened to this suggestion. Check the Drawing Filter ticks before you save.';
5891
+ state.filterCardMessages.set(requestId, message);
4782
5892
  }
5893
+ if (!sameChat(snapshot)) return;
5894
+ announce(message);
5895
+ refreshFilterCards();
5896
+ const card = ui.feed.querySelector(`.ai-chat-filter-card[data-event-id="${CSS.escape(event.eventId)}"]`);
5897
+ (card?.querySelector('.ai-chat-filter-actions button') || card?.querySelector('.ai-chat-filter-note'))?.focus({ preventScroll: true });
5898
+ }
5899
+
5900
+ /** A message sent with the Drawing Filter open whose selection did not go with it says so under it (#1859). */
5901
+ function withFilterNotShared(item, event) {
5902
+ const reason = item ? state.filterNotShared?.get(event.clientSubmissionId) : null;
5903
+ if (!reason) return item;
5904
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-notice'; note.setAttribute('role', 'status');
5905
+ note.textContent = reason;
5906
+ item.append(note);
5907
+ return item;
5908
+ }
5909
+
5910
+ /**
5911
+ * What the open Drawing Filter adds to a message (#1859): a snapshot of the sheet on screen and its selection,
5912
+ * sent beside the message for the server to store and append. Never a reason not to send. While the filter is
5913
+ * still loading the message goes without it, and says so under the message (owner ruling 2026-10-02).
5914
+ */
5915
+ /** The most a filter snapshot may weigh on the wire: under the routes' 4 MiB allowance with room to spare. */
5916
+ const FILTER_SNAPSHOT_MAX_BYTES = 3 * 1024 * 1024;
5917
+
5918
+ function filterContextForSend() {
5919
+ const surface = filterSurface();
5920
+ if (surface.state === 'off') return { open: false, field: {} };
5921
+ if (surface.state !== 'ready') return { open: true, loading: true, field: {} };
5922
+ let snapshot = null;
5923
+ try { snapshot = surface.bridge.chatSnapshot?.() || null; } catch (error) { warnFilterBridge(error); snapshot = null; }
5924
+ if (!snapshot) return { open: true, loading: false, failed: true, field: {} };
5925
+ // Bounded on the wire, in bytes, so the message can never be refused for its size (#1859 review): a filter too
5926
+ // big to describe goes without its selection, and the message says so.
5927
+ let bytes = Infinity;
5928
+ try { bytes = new TextEncoder().encode(JSON.stringify(snapshot)).length; } catch { bytes = Infinity; }
5929
+ if (bytes > FILTER_SNAPSHOT_MAX_BYTES) return { open: true, tooLarge: true, field: {} };
5930
+ return { open: true, field: { filterSnapshot: snapshot } };
5931
+ }
5932
+
5933
+ /** Remember, per message, that the filter was open but its selection did not go with it — shown under the message. */
5934
+ function noteFilterContext(clientSubmissionId, sent, outcome) {
5935
+ if (!sent.open) return;
5936
+ // What happened, then what it means for the answer, then what to do — never an error: the message went.
5937
+ const reason = sent.loading ? 'The Drawing Filter was still loading, so the AI did not see its selection. Send again once it has loaded if the AI needs it.'
5938
+ : sent.failed ? 'FloLess could not read the Drawing Filter, so the AI did not see its selection.'
5939
+ : sent.tooLarge ? 'The Drawing Filter has more than FloLess can send with one message, so the AI did not see its selection.'
5940
+ : outcome === 'not-shared' ? 'This message was too long to include the Drawing Filter selection. Shorten it and send again if the AI needs it.'
5941
+ : null;
5942
+ if (reason) state.filterNotShared.set(clientSubmissionId, reason);
4783
5943
  }
4784
5944
 
4785
5945
  async function sendTurn() {
4786
5946
  if (!state.chat || ui.send.disabled) return;
4787
- // On the Drawing Filter, Send asks about the filter; a filter-intended message is never sent as a
4788
- // normal turn, not even while the filter page is still loading.
4789
- // Unless a drawing read here is waiting on the person's answer: then the message is that answer (#1776).
4790
- const filter = filterSurface();
4791
- if (filter.state !== 'off' && !paintFilterComposer().replyToRead) { await sendFilterAi(filter); return; }
5947
+ // ONE AI CHAT (#1859, owner ruling 2026-10-01/02): the open Drawing Filter never changes where a message goes.
5948
+ // It is a turn, or a follow-up to a running reply (a drawing read included), exactly as anywhere else; the
5949
+ // filter only adds its context (`filterContextForSend`) and the AI may answer with a suggestion card.
4792
5950
  // Decided once, at the click, from what the pill showed: a follow-up that falls back to a new turn below
4793
5951
  // must not attach objects the person was never shown (#1653).
4794
5952
  const subjects = subjectsPayload(composerSelection());
4795
5953
  const subjectsField = subjects ? { subjects } : {};
5954
+ const filterContext = filterContextForSend();
4796
5955
  if (turnIsVisiblyActive() && !state.chat.activeTurn?.local) {
4797
5956
  const followup = await sendFollowup();
4798
5957
  if (followup?.outcome !== 'turn-ended') return;
@@ -4834,10 +5993,14 @@
4834
5993
  // The server alone appends this context to the provider copy. The submitted text and
4835
5994
  // durable transcript must remain exactly what the user typed.
4836
5995
  owner: snapshot.scope.owner, clientSubmissionId, text, displayText: text, uiContext, attachmentIds,
4837
- modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField,
5996
+ modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField, ...filterContext.field,
4838
5997
  }),
4839
5998
  });
4840
- if (!sameChat(snapshot)) return void subjectLinksSaved(subjects);
5999
+ if (!sameChat(snapshot)) {
6000
+ noteFilterContext(clientSubmissionId, filterContext, result?.filterContext);
6001
+ return void subjectLinksSaved(subjects);
6002
+ }
6003
+ noteFilterContext(clientSubmissionId, filterContext, result?.filterContext);
4841
6004
  subjectLinksSaved(subjects);
4842
6005
  state.pendingSubmissionId = null;
4843
6006
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
@@ -4901,6 +6064,8 @@
4901
6064
  return;
4902
6065
  }
4903
6066
  const clientSubmissionId = crypto.randomUUID();
6067
+ // A steer to a running reply — a drawing read included — carries the open filter's context too (#1859).
6068
+ const filterContext = filterContextForSend();
4904
6069
  const previousAttachments = state.attachments;
4905
6070
  let failedDelivery = null;
4906
6071
  let outcome = null;
@@ -4925,9 +6090,10 @@
4925
6090
  const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups`, {
4926
6091
  method: 'POST', body: JSON.stringify({
4927
6092
  owner: snapshot.scope.owner, clientSubmissionId, text,
4928
- uiContext: currentFloLessContext(), attachmentIds,
6093
+ uiContext: currentFloLessContext(), attachmentIds, ...filterContext.field,
4929
6094
  }),
4930
6095
  });
6096
+ noteFilterContext(clientSubmissionId, filterContext, result?.filterContext);
4931
6097
  if (!sameChat(snapshot)) return;
4932
6098
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
4933
6099
  for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
@@ -5276,6 +6442,83 @@
5276
6442
  }
5277
6443
  }
5278
6444
 
6445
+ /** "IFC · tower.ifc", "Data · loads.csv", "PDF · notes.pdf" — the same words on the composer chip and the sent tile. */
6446
+ function attachmentLabel(attachment) {
6447
+ return `${ATTACHMENT_KIND_LABELS[attachment.mediaType] || 'File'} · ${attachment.fileName}`;
6448
+ }
6449
+
6450
+ /**
6451
+ * The cut a large data file gets, said on its chip, or ''. Measured in bytes because that is what a
6452
+ * stored attachment records; a UTF-8 file never has more characters than bytes, so a file at or under
6453
+ * the limit is always read whole, and "up to" keeps the sentence true for one just over it.
6454
+ */
6455
+ function dataCutTip(attachment) {
6456
+ if (!DATA_TYPES.has(attachment.mediaType) || (attachment.bytes || 0) <= MAX_DATA_TEXT_CHARS) return '';
6457
+ return 'Large file. The AI reads up to its first 16,000 characters.';
6458
+ }
6459
+
6460
+ /**
6461
+ * Can FloLess read this data file, and what is it? The browser-side twin of server/attachment-text.ts
6462
+ * (isDwg + sniffTextKind), run on the WHOLE file before anything in the batch uploads, so a refused
6463
+ * file never reaches the server (#1853). A parity test runs both over the same fixtures.
6464
+ * Returns 'dwg', 'ifc', 'dxf', 'text', or null for a file that is not readable text.
6465
+ */
6466
+ function sniffDataFile(bytes) {
6467
+ // A DWG is named only when the file is not text: a CSV may begin "AC1234,…" (isDwg).
6468
+ const dwg = bytes.length >= 6 && bytes[0] === 0x41 && bytes[1] === 0x43
6469
+ && [2, 3, 4, 5].every((i) => bytes[i] >= 0x30 && bytes[i] <= 0x39);
6470
+ const kind = sniffTextBytes(bytes);
6471
+ return kind || (dwg ? 'dwg' : null);
6472
+ }
6473
+
6474
+ /** The text half of sniffDataFile: 'ifc', 'dxf', 'text', or null (server/attachment-text.ts sniffTextKind). */
6475
+ function sniffTextBytes(bytes) {
6476
+ if (!bytes.length || bytes.includes(0)) return null;
6477
+ let printable = 0;
6478
+ for (const byte of bytes) {
6479
+ if (byte === 0x09 || byte === 0x0a || byte === 0x0d || (byte >= 0x20 && byte !== 0x7f)) printable++;
6480
+ }
6481
+ if (printable / bytes.length <= 0.9) return null;
6482
+ let utf8 = true;
6483
+ try { new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { utf8 = false; }
6484
+ if (!utf8 && bytes.filter((byte) => byte >= 0x80).length / bytes.length > 0.3) return null;
6485
+ let head = '';
6486
+ for (const byte of bytes.subarray(0, 512)) head += String.fromCharCode(byte);
6487
+ if (head.startsWith('ISO-10303-21')) return 'ifc';
6488
+ if (/^\s*0\s*[\r\n]+\s*SECTION/.test(head)) return 'dxf';
6489
+ return 'text';
6490
+ }
6491
+
6492
+ /**
6493
+ * Why a file chosen for AI Chat cannot be attached, in the server's own words (unreadableSentence), or
6494
+ * null. `attachFiles` asks this of every data file in a batch before the first upload, so a refused
6495
+ * file leaves nothing behind (#1853). The whole file is read here; one that can no longer be read
6496
+ * (moved or locked since it was chosen) is refused plainly too.
6497
+ */
6498
+ async function dataFileRefusal(file) {
6499
+ let kind;
6500
+ try { kind = sniffDataFile(new Uint8Array(await file.arrayBuffer())); }
6501
+ catch (error) {
6502
+ console.warn('[ai-chat] a chosen file could not be read', error);
6503
+ return `“${file.name}” could not be read. Check that the file is still there, then attach it again. Nothing was attached.`;
6504
+ }
6505
+ if (kind === 'dwg') return `“${file.name}” is a DWG, which FloLess can’t read. Export it as IFC or PDF and attach that instead. Nothing was sent.`;
6506
+ if (kind) return null;
6507
+ if (String(file.type || '').startsWith('image/')) {
6508
+ return `“${file.name}” is a picture format FloLess can’t send. Save it as PNG, JPEG or WebP and attach that instead. Nothing was sent.`;
6509
+ }
6510
+ return `“${file.name}” isn’t a file type FloLess can read. Attach a picture, PDF, IFC, DXF, or a text file such as CSV. Nothing was sent.`;
6511
+ }
6512
+
6513
+ /**
6514
+ * An error whose message is already the whole plain sentence the person should read. Without the mark
6515
+ * errorMessage() replaces an unrecognised message with "FloLess could not complete this chat action",
6516
+ * which is how the attachment limits below used to say nothing useful.
6517
+ */
6518
+ function plainError(sentence) {
6519
+ return Object.assign(new Error(sentence), { plainSentence: true });
6520
+ }
6521
+
5279
6522
  function fileBase64(file) {
5280
6523
  return new Promise((resolve, reject) => {
5281
6524
  const reader = new FileReader();
@@ -5285,30 +6528,6 @@
5285
6528
  });
5286
6529
  }
5287
6530
 
5288
- /**
5289
- * Why these files cannot be attached on the surface the person is on, or null.
5290
- *
5291
- * REFUSED AT THE CHOOSER, not at Send. The AI answering a Drawing Filter message is handed
5292
- * pictures on a command line and has no way to open a document, so a PDF attached there could
5293
- * only be uploaded, counted against the conversation's budget, and then refused after the whole
5294
- * message had been written around it. `paintAttachControl` already says "Attach a picture" on that
5295
- * surface; this is the half that makes the control's word good. (Except while a drawing read in
5296
- * this chat is waiting on your answer, #1776: the message then goes to that read as a normal turn,
5297
- * so nothing is refused here and the control offers PDFs too.)
5298
- *
5299
- * A NAMED FUNCTION rather than an inline block, because `attachFiles` is held to a guard that
5300
- * requires its `captureChat()` and `sameChat(snapshot)` to stay within reach of each other — the
5301
- * ownership pattern every in-flight action follows. Inlining this pushed them apart and turned
5302
- * that guard red, which is the guard doing its job.
5303
- */
5304
- function filterAttachRefusal(incoming) {
5305
- if (filterSurface().state === 'off' || paintFilterComposer().replyToRead) return null;
5306
- const document = incoming.find((file) => !String(file.type || '').startsWith('image/'));
5307
- if (!document) return null;
5308
- return `“${document.name}” can’t be sent with a Drawing Filter message — the AI answering here can only look at pictures. `
5309
- + 'Attach a screenshot of the page you mean, or ask about it in the main conversation instead. Nothing was attached.';
5310
- }
5311
-
5312
6531
  async function attachFiles(files) {
5313
6532
  if (!state.chat || state.chat.activeTurn?.local || state.chat.state === 'recovery' || state.followupSubmitting || state.followupUnknownId || hasUnknownFollowup()) return;
5314
6533
  const snapshot = captureChat();
@@ -5318,31 +6537,38 @@
5318
6537
  // Reset the native chooser even when validation rejects this batch. After the user removes
5319
6538
  // an image, selecting that same file again must fire a fresh change event.
5320
6539
  ui.file.value = '';
5321
- if (incoming.some((file) => !allowedTypes.has(file.type))) { report(new Error('Attach a PNG, JPEG, WebP, or PDF')); return; }
5322
- const filterRefused = filterAttachRefusal(incoming);
5323
- if (filterRefused) { report(filterRefusal(filterRefused)); return; }
6540
+ const isData = (file) => !allowedTypes.has(file.type);
5324
6541
  const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length
5325
- + incoming.filter((file) => file.type.startsWith('image/')).length;
6542
+ + incoming.filter((file) => !isData(file) && file.type.startsWith('image/')).length;
5326
6543
  if (imageCount > MAX_IMAGES_PER_MESSAGE) {
5327
6544
  state.imageLimitChatId = snapshot.chatId;
5328
6545
  report({ code: 'chat-message-image-limit' });
5329
6546
  return;
5330
6547
  }
5331
6548
  state.imageLimitChatId = null;
6549
+ if (state.attachments.filter((attachment) => DATA_TYPES.has(attachment.mediaType)).length
6550
+ + incoming.filter(isData).length > MAX_DATA_FILES_PER_MESSAGE) { report({ code: 'chat-message-data-limit' }); return; }
5332
6551
  const known = [...new Map([...(state.chat.attachments || []), ...state.attachments]
5333
6552
  .map((attachment) => [attachment.attachmentId, attachment])).values()];
5334
6553
  const existingBytes = known.reduce((sum, item) => sum + (item.bytes || 0), 0);
5335
- if (known.length + incoming.length > 10) { report(new Error('You can attach up to 10 files to this conversation.')); return; }
5336
- if (incoming.some((file) => file.size > 20 * MB)) { report(new Error('Each attachment must be 20 MB or smaller')); return; }
5337
- if (existingBytes + incoming.reduce((sum, file) => sum + file.size, 0) > 50 * MB) { report(new Error('Attachments must stay within 50 MB per conversation')); return; }
6554
+ if (known.length + incoming.length > 10) { report(plainError('You can attach up to 10 files to this conversation. Remove one, then try again.')); return; }
6555
+ if (incoming.some((file) => file.size > 20 * MB)) { report(plainError('Each attachment must be 20 MB or smaller. Nothing was attached.')); return; }
6556
+ if (existingBytes + incoming.reduce((sum, file) => sum + file.size, 0) > 50 * MB) { report(plainError('Attachments must stay within 50 MB per conversation. Nothing was attached.')); return; }
5338
6557
  state.uploadingChatIds.add(snapshot.chatId);
5339
6558
  updateSendState();
5340
6559
  try {
6560
+ for (const file of incoming.filter(isData)) {
6561
+ const refusal = await dataFileRefusal(file);
6562
+ if (!sameChat(snapshot)) return;
6563
+ if (refusal) { report(plainError(refusal)); return; }
6564
+ }
5341
6565
  for (const file of incoming) {
5342
6566
  const data = await fileBase64(file);
5343
6567
  if (!sameChat(snapshot)) return;
6568
+ // A data file goes up as text/plain; the server reads its bytes again and decides what it is.
6569
+ const mediaType = isData(file) ? 'text/plain' : file.type;
5344
6570
  const attachment = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/attachments`, {
5345
- method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, fileName: file.name, mediaType: file.type, data }),
6571
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, fileName: file.name, mediaType, data }),
5346
6572
  });
5347
6573
  if (!sameChat(snapshot)) return;
5348
6574
  state.attachments.push(attachment);
@@ -5544,6 +6770,9 @@
5544
6770
  if (typeof options.projectId === 'string' && (state.scope.owner.kind !== 'project' || state.scope.owner.projectId !== options.projectId)) {
5545
6771
  throw new Error('Open this project in Workspaces to see that conversation.');
5546
6772
  }
6773
+ if (typeof options.ownerKey === 'string' && scopeKey(state.scope) !== options.ownerKey) {
6774
+ throw new Error('Open the project or workflow this conversation belongs to, then choose Show in chat again.');
6775
+ }
5547
6776
  window.flolessBridge?.revealAiChat?.();
5548
6777
  ui.tab.click();
5549
6778
  const listed = await request(`/api/chat/conversations?${ownerQuery()}`);
@@ -5974,11 +7203,28 @@
5974
7203
  if (!ui.picker.hidden && !ui.picker.contains(event.target)
5975
7204
  && (!event.target.closest('.ai-chat-setting') || event.target.closest('.ai-chat-provider-switch'))) closePicker();
5976
7205
  });
7206
+ // A units change — in a model view, a workflow's Units control, another tab or the terminal AI — repaints the receipts
7207
+ // and is what the next message is answered in. The event only says something changed; the server says what.
7208
+ window.addEventListener('floless:display-units-changed', () => { void refreshDisplayUnits(); });
7209
+ // #1890: every workspace has the same owner name, so a change of Workspace directory is what moves a workspace
7210
+ // conversation's history; reload it, or the open chat would keep pointing at the previous directory.
7211
+ let workspaceRootKey = null;
7212
+ window.addEventListener('floless:workspace-root-state', (event) => {
7213
+ const root = event.detail?.root || null;
7214
+ const key = root ? `${root.rootId ?? ''}|${root.generation ?? ''}|${root.path ?? ''}` : '';
7215
+ const changed = workspaceRootKey !== null && key !== workspaceRootKey;
7216
+ workspaceRootKey = key;
7217
+ if (changed && state.scope?.owner?.kind === 'workspace') { state.choosingProvider = false; void loadScope({ ...state.scope }); }
7218
+ });
5977
7219
  window.addEventListener('floless:chat-scope-changed', (event) => {
5978
7220
  const next = event.detail || null;
5979
7221
  // The workspace emits repeated scope notifications while its iframe finishes loading. A
5980
7222
  // same-scope notification must not reselect the first stored chat over a provider picker.
5981
- if (scopeKey(next) === scopeKey(state.scope)) { refreshActivity(); return; }
7223
+ if (scopeKey(next) === scopeKey(state.scope)) {
7224
+ // #1890: one workspace conversation spans the landings and every installed workflow; only its label moves.
7225
+ if (next?.label && state.scope && next.label !== state.scope.label) { state.scope = { ...state.scope, label: next.label }; ui.scope.textContent = next.label; }
7226
+ refreshActivity(); return;
7227
+ }
5982
7228
  loadScope(next);
5983
7229
  });
5984
7230
  document.addEventListener('click', () => queueMicrotask(paintFloLessContext));