@floless/app 0.148.1 → 0.149.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/bin/floless.mjs +1 -1
  2. package/dist/floless-server.cjs +29115 -18888
  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 +189 -12
  16. package/dist/web/chat.js +2203 -772
  17. package/dist/web/commands-drawing-check.js +53 -0
  18. package/dist/web/commands-shell.js +299 -6
  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 +29 -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,16 +6,20 @@
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'),
17
21
  settings: el('chat-settings'), provider: el('chat-provider'), switchAccount: el('chat-switch-account'), model: el('chat-model'),
18
- effort: el('chat-effort'), permission: el('chat-permission'), integrations: el('chat-integrations'),
22
+ effort: el('chat-effort'), permission: el('chat-permission'), integrations: el('chat-integrations'), ownConnectors: el('chat-own-connectors'),
19
23
  desktopValue: el('chat-desktop-value'), desktopReason: el('chat-desktop-reason'), picker: el('chat-picker'),
20
24
  feed: el('chat-feed'), offscreenActivity: el('chat-offscreen-activity'), recovery: el('chat-recovery'),
21
25
  approvalTray: el('chat-approval-tray'), recoveryCopy: el('chat-recovery-copy'),
@@ -26,29 +30,31 @@
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
+ connectors: el('chat-connectors'),
34
+ workspaceUnits: el('chat-units'),
29
35
  };
30
36
 
31
37
  const state = {
32
38
  // signInPending is keyed by provider: a wait started in one conversation must not paint an
33
39
  // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
40
+ // #1798: the chat owner's display units as the server last answered them (null = not known yet), and the
41
+ // generation that answer belongs to. Receipts show recorded kilograms until they are known.
42
+ displayUnits: null, displayUnitsGeneration: 0,
34
43
  sessionReady: false, scope: null, chats: [], archivedChats: [], unreadableChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
35
44
  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
45
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
37
46
  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
47
  answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, historyRename: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
39
48
  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,
49
+ // #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.
50
+ teklaLinks: { ownerKey: '', state: 'idle', links: [], partial: false, inflight: false, again: false }, teklaHistoryUi: {}, teklaHistoryHost: null,
42
51
  // Latched so the 5 s account poll logs an outage once instead of twelve times a minute; cleared
43
52
  // on the next successful read, so a later, separate outage is logged too.
44
53
  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,
54
+ // The last sentence a suggestion card's action reported, keyed by the card's request id.
55
+ filterCardMessages: new Map(),
56
+ // #1859: per message (client submission id), why the open Drawing Filter's selection did not go with it.
57
+ filterNotShared: new Map(),
52
58
  // The last sentence report() put under the box, held there until the person acts on it (#1683):
53
59
  // { message, scope, chatId, draft, attachments, blocked }. See heldReport().
54
60
  reportHold: null,
@@ -88,13 +94,21 @@
88
94
  const SERVER_WORDED_SIGN_IN_CODES = new Set(['runtime-unavailable', 'launch-failed', 'launch-unsafe', 'sign-in-active', 'sign-out-failed']);
89
95
  const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question' };
90
96
  const requestStatusLabels = { pending: 'Queued', queued: 'Queued', running: 'Running', ready: 'Ready', completed: 'Complete', failed: 'Failed', stopped: 'Stopped' };
97
+ // Pictures and PDFs upload as the browser names them. Any other file is a DATA file (#1853): its
98
+ // bytes decide whether FloLess can read it (sniffDataFile), never its name or declared type.
91
99
  const allowedTypes = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
92
100
  const MAX_IMAGES_PER_MESSAGE = 5;
101
+ const MAX_DATA_FILES_PER_MESSAGE = 4;
102
+ // What reaches the AI from one data file (server/attachment-text.ts MAX_TEXT_CHARS).
103
+ const MAX_DATA_TEXT_CHARS = 16000;
104
+ // The stored type of each data-file kind (server/attachment-text.ts DATA_MEDIA_TYPES).
105
+ const DATA_TYPES = new Set(['application/x-step', 'application/dxf', 'text/plain']);
106
+ const ATTACHMENT_KIND_LABELS = { 'application/pdf': 'PDF', 'application/x-step': 'IFC', 'application/dxf': 'DXF', 'text/plain': 'Data' };
93
107
  const MB = 1024 * 1024;
94
108
 
95
109
  function ownerQuery(owner = state.scope?.owner) {
96
110
  if (!owner) return '';
97
- const ownerId = owner.kind === 'project' ? owner.projectId : owner.workflowId;
111
+ const ownerId = owner.kind === 'project' ? owner.projectId : owner.kind === 'workflow' ? owner.workflowId : 'workspace';
98
112
  return new URLSearchParams({ ownerKind: owner.kind, ownerId }).toString();
99
113
  }
100
114
 
@@ -131,6 +145,7 @@
131
145
  const error = new Error(body?.error || body || `Chat request failed (${response.status})`);
132
146
  error.code = body?.code || null;
133
147
  error.reason = body?.reason || null;
148
+ error.recovery = Array.isArray(body?.recovery) ? body.recovery : null;
134
149
  error.status = response.status;
135
150
  throw error;
136
151
  }
@@ -164,9 +179,12 @@
164
179
  }
165
180
 
166
181
  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;
182
+ // A sentence written by plainError (an attachment refused in the browser) is already the whole
183
+ // plain-English explanation for this moment.
184
+ if (error?.plainSentence) return error.message;
169
185
  const raw = error instanceof Error ? error.message : String(error);
186
+ // Declared here, not beside the other constants: several test harnesses lift this function alone.
187
+ 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
188
  if (raw === 'This message was not sent because its queued response was cancelled') {
171
189
  return 'You stopped the response before AI could take this queued message. Use Retry sending if you still want to send it.';
172
190
  }
@@ -177,6 +195,8 @@
177
195
  // request() writes the timeout's sentence itself. Without this it fell through to the generic "could
178
196
  // not complete this chat action", which hid the one fact the user could act on (#1604).
179
197
  if (code === 'local-timeout' && raw) return raw;
198
+ // #1907: the server marks a not-sent reason it already wrote for the person; it is shown as is.
199
+ if (code === 'chat-send-refused-plain' && raw) return raw;
180
200
  const codeMessages = {
181
201
  'chat-origin-refused': 'This chat can only be used from the FloLess app. Reload the page and try again.',
182
202
  'chat-owner-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
@@ -210,6 +230,11 @@
210
230
  'chat-archived': 'This conversation is archived. Start a new conversation to continue.',
211
231
  'chat-turn-active': 'Stop the active response before changing this conversation.',
212
232
  'chat-message-image-limit': 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.',
233
+ 'chat-message-data-limit': 'You can attach up to four data files to one message. Remove one or choose fewer, then try again.',
234
+ // The server names the file and says what to attach instead (attachment-text.ts unreadableSentence).
235
+ 'chat-attachment-unreadable': raw,
236
+ // A file missing, or changed on disk since it was attached (#1853); the provider never received it.
237
+ 'chat-attachment-unavailable': ATTACHMENT_UNAVAILABLE,
213
238
  'chat-send-refused': 'The AI service did not accept this message. Check your sign-in and conversation settings, then try again.',
214
239
  'chat-approval-stale': 'This approval is no longer active. Refresh the conversation.',
215
240
  'chat-provider-identity-changed': 'The connected AI account changed while this response was running. Refresh the conversation and try again.',
@@ -235,8 +260,9 @@
235
260
  'chat-knowledge-unscoped': 'Knowledge is available only inside a project conversation. Open a project and try again.',
236
261
  'chat-knowledge-page-missing': 'That Knowledge page is no longer available in this project. Refresh the conversation.',
237
262
  'approval-explicit-only': 'This read needs its own approval. Choose Approve once or Deny.',
238
- 'approval-not-chat-allowable': 'Only Tekla reads can be allowed for the whole chat. Choose Approve once or Deny.',
263
+ 'approval-not-chat-allowable': 'This can only be approved once. Choose Approve once or Deny.',
239
264
  'tekla-allowance-changed': 'The Tekla read permission for this chat changed. Choose again.',
265
+ 'connector-allowance-changed': 'The connectors allowed for this chat changed. Choose again.',
240
266
  };
241
267
  if (code === 'chat-followup-refused' && error?.reason === 'chat-session-required') {
242
268
  return 'Your FloLess session expired before this message was sent. Copy the draft, reload, then paste and send it again.';
@@ -298,6 +324,8 @@
298
324
  }
299
325
  if (/chat model .*invalid|model .*not offered/i.test(raw)) return 'That model is no longer available. Choose another model.';
300
326
  if (/chat effort .*invalid|effort .*not offered/i.test(raw)) return 'That effort level is no longer available. Choose another option.';
327
+ // The stored "Not sent" row of a turn refused for the same reason carries the server's own words.
328
+ if (/^chat attachment (?:is unavailable|disappeared) before dispatch$/.test(raw.trim())) return ATTACHMENT_UNAVAILABLE;
301
329
  if (/\b(?:EPERM|EACCES|EBUSY|ENOENT|ENOTDIR)\b|operation not permitted|permission denied/i.test(raw)) {
302
330
  return 'FloLess could not access that file or folder. Check that it is available and try again.';
303
331
  }
@@ -366,11 +394,10 @@
366
394
  * Every repaint of the composer (a poll, a status change, the setup card's tick) rewrites the hint,
367
395
  * which used to wipe a reported sentence within seconds (#1683). It is the only visible reason nothing
368
396
  * 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.
397
+ * on it (heldReport).
371
398
  */
372
399
  function holdReport(message) {
373
- state.reportHold = message === state.filterSetupNote?.sentence ? null : {
400
+ state.reportHold = {
374
401
  message, scope: scopeKey(state.scope), chatId: state.chat?.chatId ?? null,
375
402
  draft: ui.input.value, attachments: attachmentKey(), blocked: sendBlocker(),
376
403
  };
@@ -419,20 +446,6 @@
419
446
  }
420
447
  }
421
448
 
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
449
  function clearReport() {
437
450
  ui.hint.classList.remove('error');
438
451
  const held = heldReport();
@@ -443,7 +456,6 @@
443
456
  ui.hint.classList.add('error');
444
457
  return;
445
458
  }
446
- const filterNote = filterSetupHint();
447
459
  const message = requestExecutionBlocked()
448
460
  ? 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.'
449
461
  : state.followupUnknownId || hasUnknownFollowup()
@@ -452,14 +464,14 @@
452
464
  && state.attachments.filter(attachment => attachment.mediaType.startsWith('image/')).length >= MAX_IMAGES_PER_MESSAGE
453
465
  ? 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.'
454
466
  : state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
455
- ? filterNote || runtimeNotice(state.chat.provider, state.capability.runtime).body
467
+ ? runtimeNotice(state.chat.provider, state.capability.runtime).body
456
468
  : state.chat && !providerReady()
457
469
  ? `${capabilityMessage(state.chat.provider, state.capability?.reason)} You can still write a message; Send will retry the connection.`
458
470
  : state.chat?.state === 'recovery'
459
471
  ? 'Check the last AI response before continuing.'
460
472
  : !state.scope?.owner
461
473
  ? '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.
474
+ // #1776/#1859: a drawing read running in this conversation is where a message goes, on any screen.
463
475
  : paintFilterComposer().replyToRead
464
476
  ? READ_REPLY_HINT
465
477
  : 'Enter to send · Shift+Enter for a new line';
@@ -472,8 +484,6 @@
472
484
  ui.hint.classList.remove('working');
473
485
  ui.hint.removeAttribute('aria-label');
474
486
  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
487
  }
478
488
  // The refusal no longer describes the composer. Only remove that exact announcement:
479
489
  // a response may have since claimed the same live region (#1704).
@@ -492,7 +502,7 @@
492
502
  if (!owner) return '';
493
503
  // Events and the bridge can construct the same owner with different property order; JSON
494
504
  // serialization made those equal scopes look different and reset the provider chooser.
495
- const ownerId = owner.kind === 'project' ? owner.projectId : owner.workflowId;
505
+ const ownerId = owner.kind === 'project' ? owner.projectId : owner.kind === 'workflow' ? owner.workflowId : 'workspace';
496
506
  return typeof ownerId === 'string' ? `${owner.kind}:${ownerId}` : '';
497
507
  }
498
508
 
@@ -524,10 +534,12 @@
524
534
  }[selectedStep || ''] || 'project-list';
525
535
  const workspaceProjectOpen = document.getElementById('ws-project')?.hidden === false;
526
536
  const dashboardVisible = document.getElementById('dashboard')?.hidden === false;
537
+ // #1890: the Workflows landing (the list of workflows), not the canvas of the workflow loaded underneath.
538
+ const workflowLanding = document.getElementById('wf-landing')?.hidden === false;
527
539
  const surface = reportOpen ? (threeDimensionalReport ? '3d-report' : 'report')
528
540
  : editorOpen ? 'model-editor'
529
541
  : workspaceMode ? (workspaceProjectOpen ? workspaceSurface : 'project-list')
530
- : dashboardVisible ? 'dashboard' : 'workflow-canvas';
542
+ : workflowLanding ? 'workflow-list' : dashboardVisible ? 'dashboard' : 'workflow-canvas';
531
543
  if (options.surfaceOnly) return { surface };
532
544
  return {
533
545
  mode: workspaceMode ? 'workspaces' : workflowMode ? 'workflows' : 'canvas',
@@ -562,6 +574,7 @@
562
574
  case 'project-history': return shellText('ws-history');
563
575
  case 'project-knowledge': return shellText('ws-knowledge');
564
576
  case 'project-list': return shellText('ws-landing');
577
+ case 'workflow-list': return shellText('wf-landing');
565
578
  case 'workflow-canvas': return shellText('canvas-main', 'inspect');
566
579
  case 'dashboard': return shellText('dashboard');
567
580
  case 'report': return boundedVisibleText(readVisibleFrameText('report-frame'), shellText('report-title', 'report-sub', 'report-overlay'));
@@ -576,7 +589,7 @@
576
589
  'drawing-filter': 'Drawing Filter', 'project-model': 'project model', 'project-exports': 'project exports',
577
590
  'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-list': 'project list',
578
591
  'workflow-canvas': 'workflow canvas', dashboard: 'dashboard', report: 'report', '3d-report': '3D report',
579
- 'model-editor': 'model editor',
592
+ 'model-editor': 'model editor', 'workflow-list': 'workflow list',
580
593
  };
581
594
  return `${labels[context.surface] || 'FloLess'} · visible state${context.activity === 'workflow-running' ? ' · workflow running' : ''}`;
582
595
  }
@@ -589,10 +602,10 @@
589
602
  // the composer's only mention of which sheet a Drawing Filter message is about.
590
603
  const shared = filter.state === 'off'
591
604
  ? floLessContextLabel(currentFloLessContext())
592
- : filter.state === 'ready' ? `Drawing Filter · partial view of ${filter.summary.sheet || 'this sheet'} and its selection`
593
- : 'Drawing Filter · loading…';
605
+ : filter.state === 'ready' ? `Drawing Filter · sheet ${filter.summary.sheet || 'on screen'} and its selection`
606
+ : 'Drawing Filter · still loading, its selection is not shared yet';
594
607
  // #1776: where the message goes, when that is not where this surface would send it.
595
- const destination = filter.replyToRead ? `${READ_REPLY_HINT} ` : '';
608
+ const destination = filter.replyToRead ? `${filter.readWorking ? READ_FOLLOWUP_HINT : READ_REPLY_HINT} ` : '';
596
609
  // A live region: rewritten only when the text changes, or every keystroke would re-announce it.
597
610
  if (ui.contextNote.textContent !== `${destination}Sharing with AI: ${shared}`) {
598
611
  const prefix = document.createElement('strong');
@@ -711,7 +724,7 @@
711
724
  // receive later events. This prevents a migrated chat history from showing hundreds of old events.
712
725
  function seedReadCursors(chats, owner = state.scope?.owner) {
713
726
  if (!owner) return;
714
- const ownerId = owner.kind === 'project' ? owner.projectId : owner.workflowId;
727
+ const ownerId = owner.kind === 'project' ? owner.projectId : owner.kind === 'workflow' ? owner.workflowId : 'workspace';
715
728
  const key = `floless:chat-read-seeded:${owner.kind}:${ownerId}`;
716
729
  try {
717
730
  if (localStorage.getItem(key)) return;
@@ -768,11 +781,12 @@
768
781
 
769
782
  function providerChooser() {
770
783
  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.
784
+ // Without a conversation owner there is no provider, history, or refresh to offer: none of those
785
+ // actions has a chat to operate on (#1890 gives every landing an owner, so this is a fallback).
773
786
  // No provider is chosen here (nor on the unscoped landing), so a setup card left from the previous
774
- // conversation must go with it.
787
+ // conversation must go with it — and so must the previous conversation's units line.
775
788
  shell.querySelector('.ai-chat-runtime')?.remove(); stopRuntimePoll();
789
+ if (ui.workspaceUnits) { ui.workspaceUnits.hidden = true; ui.workspaceUnits.replaceChildren(); delete ui.workspaceUnits.dataset.painted; }
776
790
  if (!state.scope?.owner) { showUnscoped(); return; }
777
791
  ui.feed.replaceChildren();
778
792
  updateOffscreenActivity();
@@ -781,7 +795,9 @@
781
795
  const strong = document.createElement('strong');
782
796
  strong.textContent = state.chats.length ? 'Start a new conversation' : 'Start this conversation';
783
797
  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.';
798
+ const home = state.scope.owner.kind === 'workspace' ? 'in your workspace'
799
+ : state.scope.owner.kind === 'workflow' ? 'with the workflow' : 'with the project';
800
+ copy.textContent = `FloLess keeps this chat ${home} on this computer. Messages and attachments are sent to Claude or Codex through your account.`;
785
801
  const row = document.createElement('div');
786
802
  row.className = 'ai-chat-provider-row';
787
803
  for (const provider of ['claude', 'codex']) {
@@ -1599,44 +1615,104 @@
1599
1615
  return html.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noreferrer">$1</a>');
1600
1616
  }
1601
1617
 
1602
- function markdownHtml(value) {
1618
+ function markdownHtml(value, depth = 0) {
1603
1619
  const source = String(value ?? '').replace(/\r\n?/g, '\n');
1604
- const lines = source.split('\n');
1620
+ // A quote or a list item re-enters this renderer for its own content, one level down. Past a
1621
+ // sane depth the remainder is shown as escaped text instead of recursing further.
1622
+ if (depth > 8) return `<p>${markdownInline(source).replace(/\n/g, '<br>')}</p>`;
1623
+ // Leading tabs count as four columns wherever they sit in the indent (" \t- x" is still a bullet).
1624
+ const lines = source.split('\n').map((line) => line.replace(/^[ \t]+/, (indent) => indent.replace(/\t/g, ' ')));
1605
1625
  const output = [];
1606
1626
  let paragraph = [];
1607
1627
  let list = null;
1628
+ let quote = null;
1608
1629
  let code = null;
1630
+ const isFence = (line) => /^\s*```(?:[\w-]+)?\s*$/.test(line);
1631
+ const isQuote = (line) => /^ {0,3}>/.test(line);
1632
+ const heading = (line) => line.match(/^\s{0,3}(#{1,3})\s+(.+?)\s*#*$/);
1633
+ const indentOf = (line) => line.length - line.trimStart().length;
1634
+ const listMarker = (line) => {
1635
+ const match = line.match(/^( *)(?:([-*])|(\d{1,9})[.)])([ \t]+)(\S.*)$/);
1636
+ if (!match) return null;
1637
+ const marker = match[2] || `${match[3]}.`;
1638
+ return { indent: match[1].length, type: match[2] ? 'ul' : 'ol', number: match[3] ? Number(match[3]) : 1,
1639
+ contentIndent: match[1].length + marker.length + Math.min(match[4].length, 4), text: match[5] };
1640
+ };
1609
1641
  const flushParagraph = () => {
1610
1642
  if (paragraph.length) { output.push(`<p>${markdownInline(paragraph.join('\n')).replace(/\n/g, '<br>')}</p>`); paragraph = []; }
1611
1643
  };
1644
+ const flushQuote = () => {
1645
+ if (!quote) return;
1646
+ output.push(`<blockquote>${markdownHtml(quote.join('\n'), depth + 1)}</blockquote>`);
1647
+ quote = null;
1648
+ };
1649
+ // An item is its own text plus any block content written under it — an indented continuation, a
1650
+ // quote, a nested list — rendered by this same escaping renderer, one level down.
1651
+ const renderItem = (item) => {
1652
+ const text = markdownInline(item.text.join('\n')).replace(/\n/g, '<br>');
1653
+ const children = item.children.join('\n').trim() ? markdownHtml(item.children.join('\n'), depth + 1) : '';
1654
+ return `<li>${text}${children}</li>`;
1655
+ };
1612
1656
  const flushList = () => {
1613
1657
  if (!list) return;
1614
- output.push(`<${list.type}>${list.items.map((item) => `<li>${markdownInline(item)}</li>`).join('')}</${list.type}>`);
1658
+ // The written first number is kept (a list the AI started at 4 reads 4, 5, 6 — not 1, 2, 3).
1659
+ const start = list.type === 'ol' && list.start !== 1 ? ` start="${list.start}"` : '';
1660
+ output.push(`<${list.type}${start}>${list.items.map(renderItem).join('')}</${list.type}>`);
1615
1661
  list = null;
1616
1662
  };
1663
+ const startList = (marker) => {
1664
+ list = { type: marker.type, start: marker.number, indent: marker.indent, items: [], blanks: 0, fence: false };
1665
+ addItem(marker);
1666
+ };
1667
+ const addItem = (marker) => {
1668
+ list.items.push({ text: [marker.text], children: [], contentIndent: marker.contentIndent });
1669
+ list.blanks = 0;
1670
+ };
1671
+ const addChild = (line) => {
1672
+ const item = list.items[list.items.length - 1];
1673
+ for (; list.blanks > 0; list.blanks -= 1) item.children.push('');
1674
+ item.children.push(line);
1675
+ if (isFence(line)) list.fence = !list.fence;
1676
+ };
1677
+ // Returns true when the line belongs to the open list; false means the list has ended here.
1678
+ const continueList = (line) => {
1679
+ const item = list.items[list.items.length - 1];
1680
+ if (list.fence) { addChild(line.slice(Math.min(indentOf(line), item.contentIndent))); return true; }
1681
+ if (!line.trim()) { list.blanks += 1; return true; }
1682
+ const marker = listMarker(line);
1683
+ if (marker && marker.indent < list.indent + 2) {
1684
+ // A blank line between items is a "loose" list, not the end of it — how both Claude and
1685
+ // Codex write long numbered questions.
1686
+ if (marker.type === list.type) { addItem(marker); return true; }
1687
+ return false;
1688
+ }
1689
+ if (indentOf(line) >= list.indent + 2) { addChild(line.slice(Math.min(indentOf(line), item.contentIndent))); return true; }
1690
+ // A quote written under an item belongs to it even unindented, so the numbering carries on.
1691
+ if (isQuote(line)) { addChild(line.trimStart()); return true; }
1692
+ if (list.blanks === 0 && !heading(line) && !isFence(line)) {
1693
+ if (item.children.length) addChild(line); else item.text.push(line.trim());
1694
+ return true;
1695
+ }
1696
+ return false;
1697
+ };
1617
1698
  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; }
1699
+ if (code !== null) {
1700
+ if (isFence(line)) { output.push(`<pre><code>${escapeMarkdownHtml(code.join('\n'))}</code></pre>`); code = null; } else code.push(line);
1622
1701
  continue;
1623
1702
  }
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; }
1703
+ if (list) { if (continueList(line)) continue; flushList(); }
1704
+ if (isQuote(line)) { flushParagraph(); if (!quote) quote = []; quote.push(line.replace(/^ {0,3}> ?/, '')); continue; }
1705
+ flushQuote();
1706
+ if (isFence(line)) { flushParagraph(); code = []; continue; }
1707
+ const title = heading(line);
1708
+ if (title) { flushParagraph(); const level = title[1].length; output.push(`<h${level}>${markdownInline(title[2])}</h${level}>`); continue; }
1709
+ const marker = listMarker(line);
1710
+ if (marker) { flushParagraph(); startList(marker); continue; }
1711
+ if (!line.trim()) { flushParagraph(); continue; }
1636
1712
  paragraph.push(line);
1637
1713
  }
1638
1714
  if (code !== null) output.push(`<pre><code>${escapeMarkdownHtml(code.join('\n'))}</code></pre>`);
1639
- flushParagraph(); flushList();
1715
+ flushParagraph(); flushQuote(); flushList();
1640
1716
  return output.join('') || '<p></p>';
1641
1717
  }
1642
1718
 
@@ -1676,8 +1752,14 @@
1676
1752
  target.append(image);
1677
1753
  } else {
1678
1754
  const file = document.createElement('span');
1679
- file.textContent = `${attachment.mediaType === 'application/pdf' ? 'PDF' : 'File'} · ${attachment.fileName}`;
1755
+ file.textContent = attachmentLabel(attachment);
1680
1756
  target.append(file);
1757
+ const cut = dataCutTip(attachment);
1758
+ if (cut) {
1759
+ target.dataset.tip = `${cut} Double-click to open in your default app.`;
1760
+ // The tile is focusable and named by its aria-label, so the cut is said there too, not only on hover.
1761
+ target.setAttribute('aria-label', `Open ${attachment.fileName} in its default app. ${cut}`);
1762
+ }
1681
1763
  }
1682
1764
  return target;
1683
1765
  }
@@ -1827,14 +1909,44 @@
1827
1909
  return item;
1828
1910
  }
1829
1911
 
1912
+ // #1907: the plain name of one of the person's connectors — the same rule the server words its cards with.
1913
+ function connectorLabel(connector) {
1914
+ // A Claude.ai connector is named "claude.ai <Name>"; the prefix names the channel, not the connector.
1915
+ const raw = String(connector?.app || connector?.server || 'A connector').replace(/^claude[._ ]ai[_ ]/i, '');
1916
+ return raw.replace(/[_-]+/g, ' ').replace(/\b\w/g, (letter) => letter.toUpperCase()).slice(0, 80);
1917
+ }
1918
+
1919
+ function connectorKey(connector) {
1920
+ return `${connector.provider}:${connector.server}:${connector.app || ''}`;
1921
+ }
1922
+
1923
+ function renderConnectorReceipt(event) {
1924
+ const item = document.createElement('div');
1925
+ item.className = 'ai-chat-event connector';
1926
+ item.dataset.eventSequence = String(event.sequence);
1927
+ item.dataset.eventId = event.eventId;
1928
+ const label = document.createElement('strong');
1929
+ label.textContent = 'Allowed for this chat';
1930
+ const connector = event.payload.connector;
1931
+ const tool = typeof connector.tool === 'string' ? connector.tool : 'a tool';
1932
+ item.append(label, document.createTextNode(` · ${connectorLabel(connector)} ran ${tool}`));
1933
+ return item;
1934
+ }
1935
+
1830
1936
  function renderEvent(event) {
1831
1937
  if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
1832
1938
  if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
1833
1939
  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));
1940
+ if (event.type === 'user-message') return withFilterNotShared(renderMessage(event, 'user', payloadText(event)), event);
1941
+ if (event.type === 'filter-proposal') return renderServerProposal(event);
1942
+ if (event.type === 'filter-proposal-update') return null;
1835
1943
  if (event.type === 'assistant-message') return renderMessage(event, 'assistant', payloadText(event), Boolean(event.payload?.delta));
1944
+ // #1907: a connector call that ran under "Allow for this chat" leaves a visible receipt; every other decision is audit only.
1945
+ if (event.type === 'approval-decided' && event.payload?.automatic === true && event.payload?.connector) return renderConnectorReceipt(event);
1836
1946
  if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state' || event.type === 'followup-status') return null;
1837
1947
  if (event.type === 'tekla-read') return renderTeklaReadEvent(event);
1948
+ if (event.type === 'height-question') return renderHeightQuestion(event);
1949
+ if (event.type === 'setup-question') return renderSetupQuestion(event);
1838
1950
  const item = document.createElement('div');
1839
1951
  item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}${event.type === 'knowledge-citation' ? ' knowledge' : ''}`;
1840
1952
  item.dataset.eventSequence = String(event.sequence);
@@ -1854,8 +1966,23 @@
1854
1966
  item.append(label, document.createTextNode(` · ${count} object${count === 1 ? '' : 's'}${note ? ` · AI note: ${note}` : ''}`));
1855
1967
  return item;
1856
1968
  }
1969
+ if (event.type === 'evidence-read') {
1970
+ // FloLess's own record of one look at a sheet or attachment (#1859) — written by the server, never by the
1971
+ // model, so a look that failed shows here whatever the answer says. Every string is FloLess's.
1972
+ const looked = payload.outcome === 'read';
1973
+ item.classList.add('evidence');
1974
+ if (!looked) item.classList.add('error');
1975
+ label.textContent = looked ? 'Looked at' : 'Could not look at';
1976
+ const what = typeof payload.label === 'string' && payload.label ? payload.label : 'a file';
1977
+ const reason = !looked && typeof payload.reason === 'string' && payload.reason ? ` · ${payload.reason}` : '';
1978
+ item.append(label, document.createTextNode(` ${what}${reason}`));
1979
+ return item;
1980
+ }
1857
1981
  label.textContent = event.type === 'error' && payload.outcome === 'not-sent' ? 'Not sent' : labels[event.type] || event.type;
1858
- let detail = event.type === 'error' ? errorMessage(payloadText(event)) : payloadText(event);
1982
+ // #1907: a not-sent reason the server wrote for the person (`plain`) is shown as is.
1983
+ let detail = event.type === 'error'
1984
+ ? (payload.plain === true && typeof payload.message === 'string' && payload.message ? payload.message : errorMessage(payloadText(event)))
1985
+ : payloadText(event);
1859
1986
  if (!detail && event.type === 'tool') {
1860
1987
  const toolLabels = { provider: 'AI provider', integration: 'Connected service', attachment: 'Attachment', knowledge: 'Knowledge', filesystem: 'Project files' };
1861
1988
  const statusLabels = { started: 'started', completed: 'completed', failed: 'failed', denied: 'not allowed' };
@@ -1870,6 +1997,1275 @@
1870
1997
  return item;
1871
1998
  }
1872
1999
 
2000
+ /*
2001
+ * #1882 — a HEIGHT QUESTION the drawing read asked the person, as a card in the transcript.
2002
+ *
2003
+ * The read cannot answer it: the card is painted from the server's own record of the question (never from
2004
+ * the chat event, which carries only ids), and Confirm/Use post to a route only this window can reach. What
2005
+ * the person confirms or types is what lands in the model. The feed repaints on every streamed word, so
2006
+ * everything the person has in hand — a half-typed height, a row being changed, an error — lives in
2007
+ * `heightCards`, keyed by question, and is painted back each time.
2008
+ */
2009
+ const heightCards = new Map();
2010
+
2011
+ /*
2012
+ * A NEW card for a read asks some rows again, which supersedes them on that read's earlier cards. Those
2013
+ * cards were loaded before it existed, so reload them now: otherwise they keep offering answers the
2014
+ * server will refuse (E2E #1906 — the first Take 5 setup card still showed its re-asked rows as open).
2015
+ */
2016
+ function refreshEarlierCards(cards, entry, load) {
2017
+ for (const other of cards.values()) {
2018
+ if (other === entry || other.requestId !== entry.requestId || (!other.view && !other.loading)) continue;
2019
+ // Mid-load or mid-save, what comes back may predate the new card: read it again once that settles
2020
+ // (Codex review #1906, round 2).
2021
+ if (other.loading || other.busy) other.reloadPending = true;
2022
+ else load(other);
2023
+ }
2024
+ }
2025
+ /**
2026
+ * After a card's own load or save settles, honour a reload a newer card asked for meanwhile.
2027
+ * Deliberately runs even when the card is no longer on screen (the person switched chats): a repaint
2028
+ * reuses the cached copy without fetching, so this reload is what keeps the card current for when they
2029
+ * come back. Its cost is one background request; nothing is painted (#1906 review r3, rejected finding).
2030
+ */
2031
+ function settlePendingReload(entry, load) {
2032
+ if (!entry.reloadPending || entry.loading || entry.busy) return;
2033
+ entry.reloadPending = false;
2034
+ load(entry);
2035
+ }
2036
+
2037
+ function heightCardState(requestId, questionId, chatId) {
2038
+ const key = `${requestId}/${questionId}`;
2039
+ let entry = heightCards.get(key);
2040
+ if (!entry) {
2041
+ entry = { key, requestId, questionId, chatId, view: null, loading: false, loadError: '', drafts: new Map(),
2042
+ changing: new Set(), rowErrors: new Map(), cardError: '', busy: false, selected: new Set(), bulkDraft: '' };
2043
+ heightCards.set(key, entry);
2044
+ }
2045
+ return entry;
2046
+ }
2047
+
2048
+ const heightEndKey = (row) => `${row.memberId}\u0000${row.end}`;
2049
+ const heightEndWord = (row) => (row.endWord === 'from' ? 'start' : 'end');
2050
+ const heightAnswerText = (answer) => (answer?.how === 'typed' ? `You typed ${answer.typed}` : `Confirmed ${answer?.shownAs || ''}`);
2051
+ // The server's sentence, then what to do next when it names a step (a damaged record says to discard the read).
2052
+ const heightErrorText = (error, fallback) => {
2053
+ const next = (error?.recovery || []).map((step) => step && typeof step.action === 'string' ? step.action : '').filter(Boolean);
2054
+ return [error?.message || fallback, ...next].join(' ');
2055
+ };
2056
+ // Refusals that mean the card is out of date: reload it from the server's record so it shows the truth.
2057
+ const HEIGHT_STALE = new Set(['height-question-changed', 'height-question-closed', 'height-question-superseded']);
2058
+ // A card whose read is gone: FloLess removes a read once it publishes or is discarded, so the card can no
2059
+ // longer load or change. The words hold either way (Codex review: not every removed read published).
2060
+ // Said as a final state, never as a load failure with Try again (E2E #1906: every card of a published
2061
+ // read showed "LOADING · there is no drawing read with this id · Try again").
2062
+ const CARD_READ_FINISHED = new Set(['height-question-unknown-read', 'setup-question-unknown-read']);
2063
+ 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.';
2064
+
2065
+ function loadHeightQuestion(entry) {
2066
+ if (entry.loading) return;
2067
+ entry.loading = true;
2068
+ request(`/api/chat/height-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}?${new URLSearchParams({ chatId: entry.chatId || '' })}`)
2069
+ .then((result) => { if (result?.readClosed) { entry.finished = true; entry.view = null; } else entry.view = result.question; entry.loadError = ''; })
2070
+ .catch((error) => {
2071
+ if (CARD_READ_FINISHED.has(error?.code)) { entry.finished = true; entry.loadError = ''; return; }
2072
+ entry.loadError = heightErrorText(error, 'FloLess could not load this height question.');
2073
+ })
2074
+ .finally(() => { entry.loading = false; repaintHeightCard(entry); settlePendingReload(entry, loadHeightQuestion); });
2075
+ }
2076
+
2077
+ function repaintHeightCard(entry) {
2078
+ const old = ui.feed?.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
2079
+ if (!old) return;
2080
+ const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
2081
+ const next = paintHeightCard(entry, old.dataset.eventId, old.dataset.eventSequence);
2082
+ old.replaceWith(next);
2083
+ if (focused) focusHeightControl(next, focused);
2084
+ }
2085
+
2086
+ function focusHeightControl(card, commandId) {
2087
+ const control = [...card.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === commandId);
2088
+ if (!control) return false;
2089
+ control.focus({ preventScroll: true });
2090
+ // Text fields only: a radio or checkbox has no caret, and setSelectionRange on one throws (#1906).
2091
+ if (control.tagName === 'INPUT' && (control.type === 'text' || !control.type)) control.setSelectionRange?.(control.value.length, control.value.length);
2092
+ return true;
2093
+ }
2094
+
2095
+ function renderHeightQuestion(event) {
2096
+ const payload = event.payload || {};
2097
+ const entry = heightCardState(String(payload.requestId || ''), String(payload.questionId || ''), String(event.chatId || state.chat?.chatId || ''));
2098
+ if (!entry.view && !entry.loadError && !entry.finished) {
2099
+ if (!entry.loading) refreshEarlierCards(heightCards, entry, loadHeightQuestion);
2100
+ loadHeightQuestion(entry);
2101
+ }
2102
+ return paintHeightCard(entry, event.eventId, String(event.sequence));
2103
+ }
2104
+
2105
+ function heightActionButton(label, commandId, instanceLabel, className, blockedReason) {
2106
+ const control = button(label, commandId, className);
2107
+ control.dataset.commandInstanceLabel = instanceLabel;
2108
+ if (blockedReason) {
2109
+ control.setAttribute('aria-disabled', 'true');
2110
+ control.dataset.tip = blockedReason;
2111
+ control.dataset.blockedReason = blockedReason;
2112
+ }
2113
+ return control;
2114
+ }
2115
+
2116
+ function paintHeightCard(entry, eventId, sequence) {
2117
+ const view = entry.view;
2118
+ const card = document.createElement('section');
2119
+ card.className = 'ai-chat-filter-card ai-chat-height-card';
2120
+ card.dataset.heightQuestion = entry.key;
2121
+ card.dataset.eventId = eventId || '';
2122
+ card.dataset.eventSequence = sequence || '';
2123
+ card.setAttribute('aria-label', view?.n ? `Confirm member heights, question ${view.n}` : 'Confirm member heights');
2124
+ const rows = view ? view.ends : [];
2125
+ const live = rows.filter((row) => row.status !== 'superseded');
2126
+ // A picture-only answer ("see snap") is answered by the person but waits on the READ, which only looks
2127
+ // once told; it counts here so Tell the read is offered (E2E #1906).
2128
+ const answered = live.filter((row) => row.answer && (row.status === 'confirmed' || row.status === 'typed' || row.status === 'evidence'));
2129
+ const open = Boolean(view?.open);
2130
+ const allAnswered = live.length > 0 && answered.length === live.length;
2131
+ card.dataset.state = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allAnswered ? 'answered' : 'open';
2132
+
2133
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
2134
+ const title = document.createElement('strong'); title.textContent = 'Confirm member heights';
2135
+ const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state';
2136
+ chip.textContent = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allAnswered ? 'answered' : 'needs you';
2137
+ head.append(title, chip);
2138
+ card.append(head);
2139
+
2140
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
2141
+ note.textContent = !view
2142
+ ? (entry.finished ? CARD_FINISHED_TEXT : entry.loadError || 'Loading the heights this read is asking about…')
2143
+ : open
2144
+ ? '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.'
2145
+ : 'This read is no longer waiting for an answer.';
2146
+ card.append(note);
2147
+ if (!view) {
2148
+ if (entry.loadError) {
2149
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2150
+ const retry = heightActionButton('Try again', `shell.chat-height-retry#${entry.questionId}`, 'this height question', '');
2151
+ retry.addEventListener('click', () => { entry.loadError = ''; repaintHeightCard(entry); loadHeightQuestion(entry); });
2152
+ actions.append(retry); card.append(actions);
2153
+ }
2154
+ return card;
2155
+ }
2156
+
2157
+ const questionLabel = `height question ${view.n}`;
2158
+ const count = document.createElement('p'); count.className = 'ai-chat-height-count'; count.setAttribute('aria-live', 'polite');
2159
+ count.textContent = `${answered.length} of ${live.length} answered`;
2160
+ card.append(count);
2161
+
2162
+ // #1906: rows the read grouped ("W10x33 column bases") sit under a header that selects them together.
2163
+ const selectable = (row) => open && row.status !== 'superseded' && !(row.answer && (row.status === 'confirmed' || row.status === 'typed') && !entry.changing.has(heightEndKey(row)));
2164
+ for (const key of [...entry.selected]) if (!rows.some((row) => heightEndKey(row) === key && selectable(row))) entry.selected.delete(key);
2165
+ const list = document.createElement('ol'); list.className = 'ai-chat-height-rows';
2166
+ list.setAttribute('role', 'region'); list.setAttribute('aria-label', 'Heights to confirm'); list.tabIndex = 0;
2167
+ list.dataset.commandId = `shell.chat-height-rows#${entry.questionId}`;
2168
+ list.dataset.commandInstanceLabel = questionLabel;
2169
+ const groups = [];
2170
+ for (const row of rows) {
2171
+ const name = row.group || '';
2172
+ let group = groups.find((g) => g.name === name);
2173
+ if (!group) { group = { name, rows: [] }; groups.push(group); }
2174
+ group.rows.push(row);
2175
+ }
2176
+ for (const group of groups) {
2177
+ if (group.name) list.append(paintHeightGroup(entry, group, selectable));
2178
+ for (const row of group.rows) list.append(paintHeightRow(entry, row, open, selectable(row)));
2179
+ }
2180
+ card.append(list);
2181
+ // The feed repaints on every streamed word; a person scrolled halfway down a long card stays there.
2182
+ list.addEventListener('scroll', () => { entry.rowsScroll = list.scrollTop; }, { passive: true });
2183
+ if (entry.rowsScroll) requestAnimationFrame(() => { if (list.isConnected) list.scrollTop = entry.rowsScroll; });
2184
+
2185
+ if (open && entry.selected.size) card.append(paintHeightBulk(entry, rows, questionLabel));
2186
+
2187
+ const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert');
2188
+ error.textContent = entry.cardError || '';
2189
+ card.append(error);
2190
+
2191
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2192
+ const confirmable = live.filter((row) => !row.answer && row.proposed);
2193
+ if (open && !allAnswered && !entry.selected.size && confirmable.length >= 2 && confirmable.length === live.filter((row) => !row.answer).length) {
2194
+ const all = heightActionButton(`Confirm all ${confirmable.length}`, `shell.chat-height-confirm-all#${entry.questionId}`, questionLabel, '',
2195
+ entry.busy ? 'A height is still being saved — wait for it to finish' : null);
2196
+ all.addEventListener('click', () => {
2197
+ if (all.getAttribute('aria-disabled') === 'true') return;
2198
+ submitHeightAnswers(entry, confirmable.map((row) => ({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value })), null);
2199
+ });
2200
+ actions.append(all);
2201
+ }
2202
+ if (open && allAnswered) {
2203
+ const done = document.createElement('p'); done.className = 'ai-chat-height-done';
2204
+ // No paint-time state about the composer: it changes without this card repainting, so anything
2205
+ // painted here about it would go stale. The click decides (owner ruling 2026-10-02).
2206
+ done.textContent = 'All answered. Press Tell the read, then Send, so the AI can carry on.';
2207
+ card.append(done);
2208
+ const tell = heightActionButton('Tell the read', `shell.chat-height-tell-read#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', null);
2209
+ tell.addEventListener('click', () => tellReadHeightsAnswered(entry));
2210
+ actions.append(tell);
2211
+ }
2212
+ actions.hidden = !actions.childNodes.length;
2213
+ card.append(actions);
2214
+ return card;
2215
+ }
2216
+
2217
+ /** A themed checkbox (the native box never shows, in either theme). */
2218
+ function themedCheck(commandId, instance, checked, ariaLabel, disabledReason, onChange) {
2219
+ const box = document.createElement('input');
2220
+ box.type = 'checkbox'; box.className = 'ai-chat-check';
2221
+ box.dataset.commandId = commandId; box.dataset.commandInstanceLabel = instance;
2222
+ box.checked = checked;
2223
+ box.setAttribute('aria-label', ariaLabel);
2224
+ if (disabledReason) { box.disabled = true; box.dataset.blockedReason = disabledReason; }
2225
+ box.addEventListener('change', () => onChange(box.checked));
2226
+ return box;
2227
+ }
2228
+
2229
+ function paintHeightGroup(entry, group, selectable) {
2230
+ const header = document.createElement('li'); header.className = 'ai-chat-height-group';
2231
+ const name = document.createElement('span'); name.className = 'ai-chat-height-group-name'; name.textContent = group.name; name.dataset.tip = group.name;
2232
+ const tally = document.createElement('span'); tally.className = 'ai-chat-height-meta'; tally.textContent = `${group.rows.length} ${group.rows.length === 1 ? 'end' : 'ends'}`;
2233
+ header.append(name, tally);
2234
+ const open = group.rows.filter(selectable);
2235
+ if (open.length) {
2236
+ const all = open.every((row) => entry.selected.has(heightEndKey(row)));
2237
+ const toggle = heightActionButton(all ? 'Clear group' : 'Select group', `shell.chat-height-select-group#${entry.questionId} ${group.name}`, group.name, 'ai-chat-height-change',
2238
+ entry.busy ? 'A height is still being saved — wait for it to finish' : null);
2239
+ toggle.setAttribute('aria-label', `${all ? 'Clear' : 'Select'} every open end in ${group.name}`);
2240
+ toggle.addEventListener('click', () => {
2241
+ if (toggle.getAttribute('aria-disabled') === 'true') return;
2242
+ for (const row of open) { if (all) entry.selected.delete(heightEndKey(row)); else entry.selected.add(heightEndKey(row)); }
2243
+ repaintHeightCard(entry);
2244
+ });
2245
+ header.append(toggle);
2246
+ }
2247
+ return header;
2248
+ }
2249
+
2250
+ /** The bulk bar (#1906): one height and one source for every ticked end, pinned under the rows. */
2251
+ function paintHeightBulk(entry, rows, questionLabel) {
2252
+ const chosen = rows.filter((row) => entry.selected.has(heightEndKey(row)));
2253
+ const n = chosen.length;
2254
+ const busyReason = entry.busy ? 'A height is still being saved — wait for it to finish' : null;
2255
+ const bar = document.createElement('div'); bar.className = 'ai-chat-height-bulk';
2256
+ const top = document.createElement('div'); top.className = 'ai-chat-height-bulk-top';
2257
+ const tally = document.createElement('span'); tally.setAttribute('aria-live', 'polite'); tally.setAttribute('aria-atomic', 'true');
2258
+ tally.textContent = `${n} selected`;
2259
+ const clear = heightActionButton('Clear', `shell.chat-height-bulk-clear#${entry.questionId}`, questionLabel, 'ai-chat-height-change', null);
2260
+ clear.setAttribute('aria-label', 'Clear the selection');
2261
+ clear.addEventListener('click', () => { entry.selected.clear(); repaintHeightCard(entry); });
2262
+ top.append(tally, clear);
2263
+ bar.append(top);
2264
+ const shared = chosen.every((row) => row.proposed && chosen[0].proposed && row.proposed.value === chosen[0].proposed.value);
2265
+ if (shared && chosen[0]?.proposed) {
2266
+ // Offered only when every ticked end has the SAME proposal — never shown disabled (design review).
2267
+ const line = document.createElement('div'); line.className = 'ai-chat-height-proposal';
2268
+ const value = document.createElement('span'); value.textContent = `Proposed ${chosen[0].proposed.asRead}`;
2269
+ const confirm = heightActionButton(`Confirm proposed for ${n}`, `shell.chat-height-bulk-confirm#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', busyReason);
2270
+ confirm.addEventListener('click', () => {
2271
+ if (confirm.getAttribute('aria-disabled') === 'true') return;
2272
+ submitHeightAnswers(entry, chosen.map((row) => ({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value })), null, `hb:${entry.questionId}`);
2273
+ });
2274
+ line.append(value, confirm);
2275
+ bar.append(line);
2276
+ }
2277
+ const field = document.createElement('div'); field.className = 'ai-chat-height-field';
2278
+ const input = document.createElement('input');
2279
+ input.type = 'text'; input.className = 'ai-chat-height-input'; input.autocomplete = 'off'; input.spellcheck = false;
2280
+ input.dataset.commandId = `shell.chat-height-bulk-input#${entry.questionId}`; input.dataset.commandInstanceLabel = questionLabel;
2281
+ input.placeholder = entry.view?.units === 'mm' ? 'one height for all, e.g. 4870 mm' : 'one height for all, e.g. 16\'-6"';
2282
+ input.setAttribute('aria-label', `One height for the ${n} selected ends`);
2283
+ input.value = entry.bulkDraft || '';
2284
+ input.addEventListener('input', () => { entry.bulkDraft = input.value; entry.cardError = ''; });
2285
+ if (busyReason) { input.readOnly = true; input.setAttribute('aria-disabled', 'true'); input.dataset.blockedReason = busyReason; }
2286
+ const use = heightActionButton(`Use for ${n}`, `shell.chat-height-bulk-use#${entry.questionId}`, questionLabel, shared ? '' : 'ai-chat-filter-apply', busyReason);
2287
+ use.setAttribute('aria-label', `Use the typed height for the ${n} selected ends`);
2288
+ const submit = () => {
2289
+ if (use.getAttribute('aria-disabled') === 'true') return;
2290
+ const typed = input.value.trim();
2291
+ if (!typed) { entry.cardError = 'Type a height first.'; repaintHeightCard(entry); return; }
2292
+ submitHeightAnswers(entry, chosen.map((row) => ({ memberId: row.memberId, end: row.end, action: 'type', typed })), null, `hb:${entry.questionId}`);
2293
+ };
2294
+ input.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } });
2295
+ use.addEventListener('click', submit);
2296
+ field.append(input, use);
2297
+ bar.append(field);
2298
+ bar.append(paintAnswerSource(`hb:${entry.questionId}`, {
2299
+ requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintHeightCard(entry), label: `the ${n} selected ends`, instance: questionLabel,
2300
+ idFor: (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra ? ` ${extra}` : ''}`, busyReason, allowPictureOnly: false,
2301
+ }));
2302
+ return bar;
2303
+ }
2304
+
2305
+ function paintHeightRow(entry, row, open, selectable) {
2306
+ const key = heightEndKey(row);
2307
+ const item = document.createElement('li'); item.className = 'ai-chat-height-row';
2308
+ item.dataset.status = row.status;
2309
+ const instance = `${row.memberId} ${heightEndWord(row)}`;
2310
+ const idFor = (what) => `shell.chat-height-${what}#${entry.questionId} ${row.memberId} ${row.endWord}`;
2311
+ const sourceIdFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} ${row.memberId} ${row.endWord}${extra ? ` ${extra}` : ''}`;
2312
+ const labelLine = document.createElement('div'); labelLine.className = 'ai-chat-height-labelline';
2313
+ if (selectable) {
2314
+ labelLine.append(themedCheck(idFor('select'), instance, entry.selected.has(key), `Select ${row.label} to answer several ends at once`,
2315
+ entry.busy ? 'A height is still being saved — wait for it to finish' : null,
2316
+ (checked) => { if (checked) entry.selected.add(key); else entry.selected.delete(key); repaintHeightCard(entry); }));
2317
+ }
2318
+ const label = document.createElement('div'); label.className = 'ai-chat-height-label'; label.textContent = row.label;
2319
+ label.dataset.tip = row.label;
2320
+ labelLine.append(label);
2321
+ const meta = document.createElement('div'); meta.className = 'ai-chat-height-meta';
2322
+ meta.textContent = `${row.memberId} · ${heightEndWord(row)}`;
2323
+ item.append(labelLine, meta);
2324
+
2325
+ if (row.status === 'superseded') {
2326
+ const gone = document.createElement('div'); gone.className = 'ai-chat-height-answered';
2327
+ gone.textContent = 'Asked again in a newer question. This one no longer counts.';
2328
+ item.append(gone);
2329
+ return item;
2330
+ }
2331
+ const changing = entry.changing.has(key);
2332
+ if (row.answer && !changing) {
2333
+ const done = document.createElement('div'); done.className = 'ai-chat-height-answered';
2334
+ const picture = row.status === 'evidence';
2335
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-height-glyph'; glyph.textContent = picture ? '…' : '✓'; glyph.setAttribute('aria-hidden', 'true');
2336
+ const text = document.createElement('span'); text.textContent = picture ? 'Waiting for the read to read your picture' : heightAnswerText(row.answer);
2337
+ done.append(glyph, text);
2338
+ if (open) {
2339
+ 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);
2340
+ change.setAttribute('aria-label', picture ? `Answer the height for ${row.label} yourself instead` : `Change the height for ${row.label}`);
2341
+ change.addEventListener('click', () => {
2342
+ if (change.getAttribute('aria-disabled') === 'true') return;
2343
+ entry.changing.add(key);
2344
+ if (!entry.drafts.has(key) && row.answer.how === 'typed') entry.drafts.set(key, row.answer.typed);
2345
+ repaintHeightCard(entry);
2346
+ const card = ui.feed.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
2347
+ if (card) focusHeightControl(card, idFor('input'));
2348
+ });
2349
+ done.append(change);
2350
+ }
2351
+ item.append(done);
2352
+ const source = paintAnsweredSource(entry.requestId, row.answer, sourceIdFor, instance);
2353
+ if (source) item.append(source);
2354
+ return item;
2355
+ }
2356
+ if (!open) {
2357
+ const none = document.createElement('div'); none.className = 'ai-chat-height-answered'; none.textContent = 'No answer';
2358
+ item.append(none);
2359
+ return item;
2360
+ }
2361
+ const busyReason = entry.busy ? 'A height is still being saved — wait for it to finish' : null;
2362
+ if (row.proposed) {
2363
+ const proposal = document.createElement('div'); proposal.className = 'ai-chat-height-proposal';
2364
+ const value = document.createElement('span'); value.textContent = `Proposed ${row.proposed.asRead}`;
2365
+ const confirm = heightActionButton('Confirm', idFor('confirm'), instance, 'ai-chat-filter-apply', busyReason);
2366
+ confirm.setAttribute('aria-label', `Confirm ${row.proposed.asRead} for ${row.label}`);
2367
+ confirm.addEventListener('click', () => {
2368
+ if (confirm.getAttribute('aria-disabled') === 'true') return;
2369
+ submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value }], key);
2370
+ });
2371
+ proposal.append(value, confirm);
2372
+ item.append(proposal);
2373
+ if (row.fromEvidence) {
2374
+ // #1906 "see snap": the proposal is the READ's reading of the person's picture, said as such.
2375
+ const tag = document.createElement('div'); tag.className = 'ai-chat-setup-evidence';
2376
+ const t = document.createElement('span'); t.className = 'ai-chat-setup-tag'; t.textContent = 'THE READ’S READING OF YOUR PICTURE';
2377
+ tag.append(t, document.createTextNode(' Check it before you confirm.'));
2378
+ item.append(tag);
2379
+ }
2380
+ }
2381
+ const field = document.createElement('div'); field.className = 'ai-chat-height-field';
2382
+ const input = document.createElement('input');
2383
+ input.type = 'text'; input.className = 'ai-chat-height-input'; input.autocomplete = 'off'; input.spellcheck = false;
2384
+ input.dataset.commandId = idFor('input');
2385
+ input.dataset.commandInstanceLabel = instance;
2386
+ input.placeholder = entry.view?.units === 'mm' ? 'e.g. 4870 mm' : 'e.g. 15\'-11 3/4"';
2387
+ input.setAttribute('aria-label', `${row.proposed ? 'Or type the height' : 'Type the height'} for ${row.label}`);
2388
+ input.value = entry.drafts.get(key) || '';
2389
+ input.addEventListener('input', () => { entry.drafts.set(key, input.value); entry.rowErrors.delete(key); });
2390
+ if (busyReason) { input.readOnly = true; input.setAttribute('aria-disabled', 'true'); input.dataset.blockedReason = busyReason; }
2391
+ const use = heightActionButton('Use', idFor('use'), instance, row.proposed ? '' : 'ai-chat-filter-apply', busyReason);
2392
+ use.setAttribute('aria-label', `Use the typed height for ${row.label}`);
2393
+ const submitTyped = () => {
2394
+ if (use.getAttribute('aria-disabled') === 'true') return;
2395
+ const typed = input.value.trim();
2396
+ if (!typed) { entry.rowErrors.set(key, 'Type a height first.'); repaintHeightCard(entry); return; }
2397
+ submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'type', typed }], key);
2398
+ };
2399
+ input.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submitTyped(); } });
2400
+ use.addEventListener('click', submitTyped);
2401
+ field.append(input, use);
2402
+ item.append(field);
2403
+ item.append(paintAnswerSource(`h:${entry.questionId}:${key}`, {
2404
+ requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintHeightCard(entry), label: row.label, instance,
2405
+ idFor: sourceIdFor, inherited: row.inherited, busyReason, allowPictureOnly: true,
2406
+ onPictureOnly: () => submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'evidence' }], key),
2407
+ }));
2408
+ const rowError = document.createElement('p'); rowError.className = 'ai-chat-height-error'; rowError.setAttribute('role', 'alert');
2409
+ rowError.textContent = entry.rowErrors.get(key) || '';
2410
+ item.append(rowError);
2411
+ return item;
2412
+ }
2413
+
2414
+ /**
2415
+ * Answers carry the person's source note and pictures from the row's box, or from the bulk bar's when
2416
+ * several ends are answered at once (`sharedScope`).
2417
+ */
2418
+ async function submitHeightAnswers(entry, answers, rowKey, sharedScope) {
2419
+ if (entry.busy) return;
2420
+ const scopeOf = (answer) => sharedScope || `h:${entry.questionId}:${heightEndKey(answer)}`;
2421
+ const withSource = answers.map((answer) => ({ ...answer, ...answerSourcePayload(scopeOf(answer)) }));
2422
+ entry.busy = true; entry.cardError = ''; if (rowKey) entry.rowErrors.delete(rowKey);
2423
+ repaintHeightCard(entry);
2424
+ try {
2425
+ const result = await request(`/api/chat/height-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}/answers`, {
2426
+ method: 'POST', body: JSON.stringify({ chatId: entry.chatId, answers: withSource }),
2427
+ });
2428
+ entry.view = result.question;
2429
+ for (const answer of answers) {
2430
+ const key = heightEndKey(answer);
2431
+ entry.changing.delete(key); entry.drafts.delete(key); entry.selected.delete(key);
2432
+ clearAnswerSource(scopeOf(answer));
2433
+ }
2434
+ if (sharedScope) entry.bulkDraft = '';
2435
+ } catch (error) {
2436
+ let message = heightErrorText(error, 'FloLess could not save this height. Try again.');
2437
+ if (error?.code === 'answer-evidence-unknown') message = dropStaleAnswerFiles([...new Set(answers.map(scopeOf))], entry);
2438
+ // Dropped, not kept: a reload that fails must show its own error and Try again, which only an
2439
+ // empty card does — an old view would hide both behind rows that are out of date.
2440
+ if (HEIGHT_STALE.has(error?.code)) { entry.cardError = message; entry.view = null; loadHeightQuestion(entry); }
2441
+ else if (rowKey) entry.rowErrors.set(rowKey, message);
2442
+ else entry.cardError = message;
2443
+ } finally {
2444
+ entry.busy = false;
2445
+ repaintHeightCard(entry);
2446
+ settlePendingReload(entry, loadHeightQuestion);
2447
+ focusNextHeightControl(entry);
2448
+ }
2449
+ }
2450
+
2451
+ // After an answer, keyboard focus moves to the next row still waiting, or to Tell the read.
2452
+ function focusNextHeightControl(entry) {
2453
+ const card = ui.feed?.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
2454
+ if (!card || (document.activeElement && card.contains(document.activeElement) && document.activeElement.tagName === 'INPUT')) return;
2455
+ const target = card.querySelector('.ai-chat-height-row[data-status="open"] button, .ai-chat-height-row[data-status="open"] input')
2456
+ || card.querySelector('[data-command-id^="shell.chat-height-tell-read"]');
2457
+ target?.focus({ preventScroll: true });
2458
+ }
2459
+
2460
+ const heightTellText = (entry) => `I've answered height question ${entry.view?.n ?? ''}.`.replace(' .', '.');
2461
+
2462
+ /*
2463
+ * TELL THE READ puts one short message in the composer and moves focus to Send; the PERSON sends it
2464
+ * (owner ruling 2026-10-02). The card never claims a delivery: the chat's own send, its delivery states
2465
+ * and its Retry are the truth about that. Two review rounds found that every way of inferring delivery
2466
+ * from here could still say "Sent" for a message that was not.
2467
+ */
2468
+ function tellReadHeightsAnswered(entry) {
2469
+ tellReadAnswered(entry, heightTellText(entry), repaintHeightCard);
2470
+ }
2471
+
2472
+ /*
2473
+ * #1906 — WHERE AN ANSWER CAME FROM: the person's source note and pictures, on any question card.
2474
+ *
2475
+ * Owner rulings 2026-10-02: "would still be beneficial to attach pictures etc like in chat" and "so i
2476
+ * still can answer see snap?". Each answerable row (and the height card's bulk bar) has one source box,
2477
+ * keyed by `scope`, kept across repaints like everything else on a card. A picture is uploaded at once
2478
+ * through the person-only route, so the server can tell it is the person's; it counts only when the
2479
+ * answer it rides on is recorded, and it can be removed until then.
2480
+ */
2481
+ const answerSources = new Map();
2482
+ const MAX_ANSWER_FILES = 3;
2483
+ const ANSWER_FILE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
2484
+ 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';
2485
+
2486
+ function answerSource(scope) {
2487
+ let source = answerSources.get(scope);
2488
+ if (!source) { source = { open: false, note: '', files: [], uploading: 0, error: '' }; answerSources.set(scope, source); }
2489
+ return source;
2490
+ }
2491
+ /** What an answer carries from its source box: the note and the uploaded files' ids. */
2492
+ function answerSourcePayload(scope) {
2493
+ const source = answerSources.get(scope);
2494
+ if (!source) return {};
2495
+ const note = source.note.trim();
2496
+ return { ...(note ? { note } : {}), ...(source.files.length ? { evidence: source.files.map((file) => file.attachmentId) } : {}) };
2497
+ }
2498
+ const MAX_ANSWER_NOTE = 160;
2499
+ /**
2500
+ * An answer plus its source box. A "No single level" / "None of these" answer carries the person's
2501
+ * REQUIRED reason in `note`; a source note never replaces it (Codex review #1906) — both are kept, the
2502
+ * reason first, so the record says what the person typed in each place.
2503
+ */
2504
+ function withAnswerSource(answer, source) {
2505
+ if (!answer.note || !source.note) return { ...answer, ...source };
2506
+ return { ...answer, ...source, note: `${answer.note} (source: ${source.note})` };
2507
+ }
2508
+
2509
+ /** After the answer is recorded the files belong to it: forget the box, keep nothing to remove. */
2510
+ function clearAnswerSource(scope) {
2511
+ const source = answerSources.get(scope);
2512
+ if (!source) return;
2513
+ for (const file of source.files) if (file.url) URL.revokeObjectURL(file.url);
2514
+ answerSources.delete(scope);
2515
+ }
2516
+ const evidenceUrl = (requestId, attachmentId) => `/api/chat/answer-evidence/${encodeURIComponent(requestId)}/${encodeURIComponent(attachmentId)}`;
2517
+
2518
+ async function attachAnswerFiles(scope, ctx, files) {
2519
+ const source = answerSource(scope);
2520
+ const incoming = [...files];
2521
+ if (!incoming.length) return;
2522
+ source.error = '';
2523
+ if (source.files.length + incoming.length > MAX_ANSWER_FILES) {
2524
+ source.error = `An answer can carry at most ${MAX_ANSWER_FILES} files. Remove one first.`;
2525
+ ctx.repaint(); return;
2526
+ }
2527
+ const refused = incoming.find((file) => !ANSWER_FILE_TYPES.has(file.type));
2528
+ if (refused) {
2529
+ source.error = `“${refused.name}” can’t be attached to an answer. Attach a picture (PNG, JPEG or WebP) or a PDF.`;
2530
+ ctx.repaint(); return;
2531
+ }
2532
+ for (const file of incoming) {
2533
+ source.uploading += 1; ctx.repaint();
2534
+ try {
2535
+ const data = await fileBase64(file);
2536
+ const result = await request(`/api/chat/answer-evidence/${encodeURIComponent(ctx.requestId)}`, {
2537
+ method: 'POST', timeoutMs: 120000,
2538
+ body: JSON.stringify({ chatId: ctx.chatId, fileName: file.name || 'screenshot.png', mediaType: file.type, data }),
2539
+ });
2540
+ const ref = result.evidence;
2541
+ source.files.push({ ...ref, url: file.type.startsWith('image/') ? URL.createObjectURL(file) : '' });
2542
+ } catch (error) {
2543
+ source.error = error?.message || `FloLess could not attach “${file.name}”. Try again.`;
2544
+ } finally {
2545
+ source.uploading -= 1; ctx.repaint();
2546
+ }
2547
+ }
2548
+ }
2549
+
2550
+ async function removeAnswerFile(scope, ctx, file) {
2551
+ const source = answerSource(scope);
2552
+ const drop = () => {
2553
+ source.files = source.files.filter((row) => row.attachmentId !== file.attachmentId);
2554
+ if (file.url) URL.revokeObjectURL(file.url);
2555
+ source.error = '';
2556
+ };
2557
+ try {
2558
+ await request(evidenceUrl(ctx.requestId, file.attachmentId), { method: 'DELETE', body: JSON.stringify({ chatId: ctx.chatId }) });
2559
+ drop();
2560
+ } catch (error) {
2561
+ // Already gone on the server (review #1906): the chip goes too, or it would ride on every later
2562
+ // answer and be refused each time, with the paperclip stuck at the file limit.
2563
+ if (error?.code === 'answer-evidence-unknown') drop();
2564
+ else source.error = error?.message || 'FloLess could not remove that file. Try again.';
2565
+ }
2566
+ ctx.repaint();
2567
+ }
2568
+
2569
+ /**
2570
+ * An answer was refused because a picture on it is no longer waiting to be used (review #1906). Take
2571
+ * those pictures off the answer — asking the server to release each one, so none keeps holding the
2572
+ * conversation's file budget — and say in words that they must be attached again. Returns the sentence.
2573
+ */
2574
+ function dropStaleAnswerFiles(scopes, entry) {
2575
+ for (const scope of scopes) {
2576
+ const source = answerSources.get(scope);
2577
+ if (!source?.files.length) continue;
2578
+ for (const file of source.files) {
2579
+ request(evidenceUrl(entry.requestId, file.attachmentId), { method: 'DELETE', body: JSON.stringify({ chatId: entry.chatId }) })
2580
+ .catch((error) => { if (error?.code !== 'answer-evidence-unknown') console.warn('[chat] an unused answer picture could not be released', file.attachmentId, error?.message); });
2581
+ if (file.url) URL.revokeObjectURL(file.url);
2582
+ }
2583
+ source.files = [];
2584
+ source.open = true;
2585
+ }
2586
+ 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.';
2587
+ }
2588
+
2589
+ /**
2590
+ * A recorded picture the browser could not show: ask the server why, so the chip says the truth —
2591
+ * "no longer available" only when the file really is gone or changed (410), and the server's own
2592
+ * sentence for anything else (a signed-out session, a busy record, a stopped server) (review #1906).
2593
+ */
2594
+ async function explainMissingPicture(url, slot) {
2595
+ let text = 'could not be shown just now';
2596
+ try {
2597
+ const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store' });
2598
+ if (response.status === 410) text = 'no longer available';
2599
+ else if (!response.ok) {
2600
+ const body = (response.headers.get('content-type') || '').includes('application/json') ? await response.json().catch(() => null) : null;
2601
+ text = body?.error ? `could not be shown: ${body.error}` : `could not be shown (FloLess answered ${response.status})`;
2602
+ }
2603
+ } catch { text = 'could not be shown: FloLess did not answer. Make sure it is still running.'; }
2604
+ slot.textContent = text;
2605
+ slot.dataset.missing = text === 'no longer available' ? 'gone' : 'error';
2606
+ }
2607
+
2608
+ /** One recorded picture as a chip: thumbnail for a picture, its name, and a button that opens it. */
2609
+ function answerPictureChip(requestId, ref, commandId, instance) {
2610
+ const chip = document.createElement('span'); chip.className = 'ai-chat-attachment ai-chat-answer-picture';
2611
+ if (ref.mediaType.startsWith('image/')) {
2612
+ const preview = document.createElement('img'); preview.alt = ''; preview.loading = 'lazy';
2613
+ preview.src = evidenceUrl(requestId, ref.attachmentId);
2614
+ // A picture the browser cannot show becomes the server's reason, never a broken image (review #1906).
2615
+ preview.addEventListener('error', () => {
2616
+ const slot = Object.assign(document.createElement('span'), { className: 'ai-chat-answer-missing', textContent: 'checking…' });
2617
+ slot.setAttribute('role', 'status');
2618
+ preview.replaceWith(slot);
2619
+ explainMissingPicture(preview.src, slot);
2620
+ }, { once: true });
2621
+ chip.append(preview);
2622
+ }
2623
+ const open = button(ref.fileName, commandId, 'ai-chat-answer-open');
2624
+ open.dataset.commandInstanceLabel = instance;
2625
+ open.dataset.tip = `Open ${ref.fileName}`;
2626
+ open.setAttribute('aria-label', `Open ${ref.fileName}`);
2627
+ open.addEventListener('click', () => { window.open(evidenceUrl(requestId, ref.attachmentId), '_blank', 'noopener'); });
2628
+ chip.append(open);
2629
+ return chip;
2630
+ }
2631
+
2632
+ /**
2633
+ * The "+ Add source" disclosure: a one-line note, a paperclip that works like the composer's (pick,
2634
+ * paste or drop), and the files as removable chips. `ctx` is { requestId, chatId, repaint, label,
2635
+ * instance, idFor, inherited, allowPictureOnly, onPictureOnly, busyReason }.
2636
+ */
2637
+ function paintAnswerSource(scope, ctx) {
2638
+ const source = answerSource(scope);
2639
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-answer-source';
2640
+ if (ctx.inherited?.length) {
2641
+ const kept = document.createElement('div'); kept.className = 'ai-chat-answer-files';
2642
+ const lead = document.createElement('span'); lead.className = 'ai-chat-answer-lead'; lead.textContent = 'Your picture';
2643
+ kept.append(lead, ...ctx.inherited.map((ref) => answerPictureChip(ctx.requestId, ref, ctx.idFor('picture-open', ref.attachmentId), ctx.instance)));
2644
+ wrap.append(kept);
2645
+ }
2646
+ const hasDraft = source.open || source.note || source.files.length || source.uploading;
2647
+ if (!hasDraft) {
2648
+ const add = button('+ Add source', ctx.idFor('source'), 'ai-chat-answer-add');
2649
+ add.dataset.commandInstanceLabel = ctx.instance;
2650
+ add.setAttribute('aria-label', `Add a source note or picture for ${ctx.label}`);
2651
+ add.dataset.tip = 'Say where your answer comes from: a note like “per 7/S-502”, or a screenshot or PDF';
2652
+ add.addEventListener('click', () => {
2653
+ source.open = true; ctx.repaint();
2654
+ [...(ui.feed?.querySelectorAll('[data-command-id]') || [])].find((node) => node.dataset.commandId === ctx.idFor('note'))?.focus({ preventScroll: true });
2655
+ });
2656
+ wrap.append(add);
2657
+ return wrap;
2658
+ }
2659
+ const box = document.createElement('div'); box.className = 'ai-chat-answer-box';
2660
+ const line = document.createElement('div'); line.className = 'ai-chat-answer-line';
2661
+ const note = document.createElement('input');
2662
+ note.type = 'text'; note.className = 'ai-chat-height-input ai-chat-answer-note'; note.maxLength = 160; note.autocomplete = 'off';
2663
+ note.placeholder = 'Source, e.g. per 7/S-502 (optional)';
2664
+ note.dataset.commandId = ctx.idFor('note'); note.dataset.commandInstanceLabel = ctx.instance;
2665
+ note.setAttribute('aria-label', `Source note for ${ctx.label}`);
2666
+ note.value = source.note;
2667
+ note.addEventListener('input', () => { source.note = note.value; });
2668
+ const clip = document.createElement('button');
2669
+ clip.type = 'button'; clip.className = 'ai-chat-answer-clip';
2670
+ clip.dataset.commandId = ctx.idFor('attach'); clip.dataset.commandInstanceLabel = ctx.instance;
2671
+ clip.dataset.tip = 'Attach a screenshot or PDF (you can also paste or drop it here)';
2672
+ clip.setAttribute('aria-label', `Attach a screenshot or PDF to the answer for ${ctx.label}`);
2673
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
2674
+ svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true'); svg.setAttribute('focusable', 'false');
2675
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', PAPERCLIP);
2676
+ svg.append(path); clip.append(svg);
2677
+ const picker = document.createElement('input');
2678
+ picker.type = 'file'; picker.multiple = true; picker.hidden = true; picker.accept = 'image/png,image/jpeg,image/webp,application/pdf';
2679
+ picker.dataset.commandId = ctx.idFor('attach-input'); picker.dataset.commandInstanceLabel = ctx.instance;
2680
+ picker.addEventListener('change', () => { const files = [...picker.files]; picker.value = ''; attachAnswerFiles(scope, ctx, files); });
2681
+ clip.addEventListener('click', () => picker.click());
2682
+ if (ctx.busyReason || source.files.length >= MAX_ANSWER_FILES) {
2683
+ const why = ctx.busyReason || `An answer can carry at most ${MAX_ANSWER_FILES} files`;
2684
+ clip.setAttribute('aria-disabled', 'true'); clip.dataset.blockedReason = why; clip.dataset.tip = why;
2685
+ clip.onclick = (event) => event.stopImmediatePropagation();
2686
+ }
2687
+ line.append(note, clip, picker);
2688
+ box.append(line);
2689
+ // Paste and drop, like the composer: a screenshot pasted while this box has focus attaches to the answer.
2690
+ box.addEventListener('paste', (event) => {
2691
+ const files = [...(event.clipboardData?.files || [])];
2692
+ if (files.length) { event.preventDefault(); attachAnswerFiles(scope, ctx, files); }
2693
+ });
2694
+ box.addEventListener('dragover', (event) => { if (event.dataTransfer?.types?.includes('Files')) { event.preventDefault(); box.classList.add('drop'); } });
2695
+ box.addEventListener('dragleave', () => box.classList.remove('drop'));
2696
+ box.addEventListener('drop', (event) => {
2697
+ box.classList.remove('drop');
2698
+ const files = [...(event.dataTransfer?.files || [])];
2699
+ if (files.length) { event.preventDefault(); attachAnswerFiles(scope, ctx, files); }
2700
+ });
2701
+ if (source.files.length || source.uploading) {
2702
+ const chips = document.createElement('div'); chips.className = 'ai-chat-answer-files';
2703
+ for (const file of source.files) {
2704
+ const chip = document.createElement('span'); chip.className = 'ai-chat-attachment';
2705
+ if (file.url) { const img = document.createElement('img'); img.alt = ''; img.src = file.url; chip.append(img); }
2706
+ const name = document.createElement('span'); name.textContent = file.fileName;
2707
+ const remove = button('×', ctx.idFor('picture-remove', file.attachmentId));
2708
+ remove.dataset.commandInstanceLabel = file.fileName;
2709
+ remove.setAttribute('aria-label', `Remove ${file.fileName} from this answer`);
2710
+ remove.dataset.tip = 'Remove from this answer';
2711
+ remove.addEventListener('click', () => removeAnswerFile(scope, ctx, file));
2712
+ chip.append(name, remove); chips.append(chip);
2713
+ }
2714
+ if (source.uploading) {
2715
+ const busy = document.createElement('span'); busy.className = 'ai-chat-answer-lead'; busy.setAttribute('role', 'status');
2716
+ busy.textContent = 'Attaching…';
2717
+ chips.append(busy);
2718
+ }
2719
+ box.append(chips);
2720
+ }
2721
+ if (ctx.allowPictureOnly && source.files.length && !source.uploading) {
2722
+ const only = button('Answer with the picture', ctx.idFor('picture-only'), 'ai-chat-answer-picture-only');
2723
+ only.dataset.commandInstanceLabel = ctx.instance;
2724
+ only.setAttribute('aria-label', `Answer ${ctx.label} with the picture only, and let the read read it`);
2725
+ only.dataset.tip = 'The read looks at your picture and asks this row again with what it reads; you confirm the number';
2726
+ if (ctx.busyReason) { only.setAttribute('aria-disabled', 'true'); only.dataset.blockedReason = ctx.busyReason; }
2727
+ only.addEventListener('click', () => { if (only.getAttribute('aria-disabled') !== 'true') ctx.onPictureOnly(); });
2728
+ box.append(only);
2729
+ }
2730
+ const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert');
2731
+ error.textContent = source.error || '';
2732
+ box.append(error);
2733
+ wrap.append(box);
2734
+ return wrap;
2735
+ }
2736
+
2737
+ /** The person's note and pictures on a recorded answer, shown under it. */
2738
+ function paintAnsweredSource(requestId, answer, idFor, instance) {
2739
+ // A "none" answer's note is its reason, already the answer's own line: it is not repeated as a source.
2740
+ const note = answer?.how === 'none' ? '' : answer?.note;
2741
+ if (!note && !answer?.evidence?.length) return null;
2742
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-answer-files ai-chat-answered-source';
2743
+ if (note) { const line = document.createElement('span'); line.className = 'ai-chat-answer-lead'; line.textContent = note; wrap.append(line); }
2744
+ for (const ref of answer.evidence || []) wrap.append(answerPictureChip(requestId, ref, idFor('picture-open', ref.attachmentId), instance));
2745
+ return wrap;
2746
+ }
2747
+
2748
+ /*
2749
+ * TELL THE READ, shared by the height and setup cards (#1882's click-time rule, unchanged): it puts one
2750
+ * short message in the composer and moves focus to Send; the PERSON sends it.
2751
+ */
2752
+ function tellReadAnswered(entry, text, repaint) {
2753
+ if (!ui.input) return;
2754
+ const held = ui.input.value.trim();
2755
+ if (held === text && !state.attachments.length) {
2756
+ if (entry.cardError) { entry.cardError = ''; repaint(entry); }
2757
+ ui.send?.focus({ preventScroll: true });
2758
+ return;
2759
+ }
2760
+ if (held || state.attachments.length) {
2761
+ entry.cardError = 'Send or clear the message you are writing first, then press Tell the read again.';
2762
+ repaint(entry);
2763
+ return;
2764
+ }
2765
+ entry.cardError = '';
2766
+ ui.input.value = text;
2767
+ saveDraftSoon();
2768
+ updateSendState();
2769
+ repaint(entry);
2770
+ ui.send?.focus({ preventScroll: true });
2771
+ }
2772
+
2773
+ /*
2774
+ * #1906 — THE READ SETUP CARD: each plan view's scale, the model origin and each plan view's level,
2775
+ * answered by the person on one card. Painted from the server's own record (the chat event carries
2776
+ * only ids); Confirm, Use and the rest post to a route only this window can reach. The read must then
2777
+ * use exactly what is settled here, and asks again on a new card if anything conflicts.
2778
+ */
2779
+ const setupCards = new Map();
2780
+ const SETUP_STALE = new Set(['setup-question-changed', 'height-question-closed', 'setup-question-superseded', 'setup-answer-frozen']);
2781
+ const SETUP_SECTIONS = [['scale', 'Drawing scale'], ['origin', 'Model origin'], ['level', 'Plan levels']];
2782
+
2783
+ function setupCardState(requestId, questionId, chatId) {
2784
+ const key = `${requestId}/${questionId}`;
2785
+ let entry = setupCards.get(key);
2786
+ if (!entry) {
2787
+ entry = { key, requestId, questionId, chatId, view: null, loading: false, loadError: '', drafts: new Map(), changing: new Set(),
2788
+ rowErrors: new Map(), cardError: '', busy: false, expanded: new Map(), originPick: null, noneOpen: new Set(), bodyScroll: 0 };
2789
+ setupCards.set(key, entry);
2790
+ }
2791
+ return entry;
2792
+ }
2793
+
2794
+ function loadSetupQuestion(entry) {
2795
+ if (entry.loading) return;
2796
+ entry.loading = true;
2797
+ request(`/api/chat/setup-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}?${new URLSearchParams({ chatId: entry.chatId || '' })}`)
2798
+ .then((result) => { if (result?.readClosed) { entry.finished = true; entry.view = null; } else entry.view = result.question; entry.loadError = ''; })
2799
+ .catch((error) => {
2800
+ if (CARD_READ_FINISHED.has(error?.code)) { entry.finished = true; entry.loadError = ''; return; }
2801
+ entry.loadError = heightErrorText(error, 'FloLess could not load the read setup.');
2802
+ })
2803
+ .finally(() => { entry.loading = false; repaintSetupCard(entry); settlePendingReload(entry, loadSetupQuestion); });
2804
+ }
2805
+
2806
+ function repaintSetupCard(entry) {
2807
+ const old = ui.feed?.querySelector(`[data-setup-question="${CSS.escape(entry.key)}"]`);
2808
+ if (!old) return;
2809
+ const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
2810
+ const next = paintSetupCard(entry, old.dataset.eventId, old.dataset.eventSequence);
2811
+ old.replaceWith(next);
2812
+ if (focused) focusHeightControl(next, focused);
2813
+ }
2814
+
2815
+ function renderSetupQuestion(event) {
2816
+ const payload = event.payload || {};
2817
+ const entry = setupCardState(String(payload.requestId || ''), String(payload.questionId || ''), String(event.chatId || state.chat?.chatId || ''));
2818
+ if (!entry.view && !entry.loadError && !entry.finished) {
2819
+ if (!entry.loading) refreshEarlierCards(setupCards, entry, loadSetupQuestion);
2820
+ loadSetupQuestion(entry);
2821
+ }
2822
+ return paintSetupCard(entry, event.eventId, String(event.sequence));
2823
+ }
2824
+
2825
+ const setupSettled = (row) => row.status === 'settled';
2826
+ const setupLive = (row) => row.status !== 'superseded';
2827
+ const scaleTag = { floless: 'FLOLESS FIT', 'floless-candidate': 'FLOLESS CANDIDATE', read: 'THE READ’S MEASUREMENT', 'read-of-picture': 'THE READ’S READING OF YOUR PICTURE' };
2828
+ 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' };
2829
+ const originText = (o) => `${o.xLabel}/${o.yLabel}`;
2830
+ const viewName = (row) => `${row.view.sheet}${row.view.title ? ` · ${row.view.title}` : ''}`;
2831
+
2832
+ function setupAnswerText(row) {
2833
+ const a = row.answer;
2834
+ if (!a) return '';
2835
+ if (row.kind === 'origin') {
2836
+ if (a.how === 'none') return `None of these: ${a.note}`;
2837
+ return `${originText(a.origin)}${a.origin.pickedAs ? ` (you picked ${a.origin.pickedAs})` : ''}${a.how === 'typed' ? ', typed' : ''}`;
2838
+ }
2839
+ if (a.how === 'none') return `No single level: ${a.note}`;
2840
+ if (a.how === 'typed') return `You typed ${a.typed}`;
2841
+ return `Confirmed ${a.shownAs}${a.basis === 'read-of-your-picture' ? ', the read’s reading of your picture' : ''}`;
2842
+ }
2843
+
2844
+ function paintSetupCard(entry, eventId, sequence) {
2845
+ const view = entry.view;
2846
+ const card = document.createElement('section');
2847
+ card.className = 'ai-chat-filter-card ai-chat-height-card ai-chat-setup-card';
2848
+ card.dataset.setupQuestion = entry.key;
2849
+ card.dataset.eventId = eventId || '';
2850
+ card.dataset.eventSequence = sequence || '';
2851
+ card.setAttribute('aria-label', view?.n ? `Read setup, question ${view.n}` : 'Read setup');
2852
+ const rows = view ? view.items : [];
2853
+ const live = rows.filter(setupLive);
2854
+ const settled = live.filter(setupSettled);
2855
+ const open = Boolean(view?.open);
2856
+ const allSettled = live.length > 0 && settled.length === live.length;
2857
+ // Every row the person can answer is answered, but some wait on the READ (a picture to read, or new
2858
+ // choices to offer): the person still has to tell it, or the read never looks (E2E #1906).
2859
+ const waitsOnRead = (row) => row.status === 'picture' || row.status === 'needs-new-choices';
2860
+ const allAnswered = !allSettled && live.length > 0 && live.every((row) => setupSettled(row) || waitsOnRead(row));
2861
+ card.dataset.state = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allSettled ? 'answered' : allAnswered ? 'waiting-for-read' : 'open';
2862
+
2863
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
2864
+ const title = document.createElement('strong'); title.textContent = 'Read setup';
2865
+ const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state';
2866
+ chip.textContent = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allSettled ? 'settled' : allAnswered ? 'with the read' : 'needs you';
2867
+ head.append(title, chip);
2868
+ card.append(head);
2869
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
2870
+ note.textContent = !view
2871
+ ? (entry.finished ? CARD_FINISHED_TEXT : entry.loadError || 'Loading the read setup…')
2872
+ : open
2873
+ ? '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.'
2874
+ : 'This read is no longer waiting for an answer.';
2875
+ card.append(note);
2876
+ if (!view) {
2877
+ if (entry.loadError) {
2878
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2879
+ const retry = heightActionButton('Try again', `shell.chat-setup-retry#${entry.questionId}`, 'the read setup', '');
2880
+ retry.addEventListener('click', () => { entry.loadError = ''; repaintSetupCard(entry); loadSetupQuestion(entry); });
2881
+ actions.append(retry); card.append(actions);
2882
+ }
2883
+ return card;
2884
+ }
2885
+ const questionLabel = `setup question ${view.n}`;
2886
+ const count = document.createElement('p'); count.className = 'ai-chat-height-count'; count.setAttribute('aria-live', 'polite'); count.setAttribute('aria-atomic', 'true');
2887
+ count.textContent = `${settled.length} of ${live.length} settled`;
2888
+ card.append(count);
2889
+
2890
+ const body = document.createElement('div'); body.className = 'ai-chat-height-rows ai-chat-setup-body';
2891
+ body.setAttribute('role', 'region'); body.setAttribute('aria-label', 'Read setup questions'); body.tabIndex = 0;
2892
+ body.dataset.commandId = `shell.chat-setup-body#${entry.questionId}`;
2893
+ body.dataset.commandInstanceLabel = questionLabel;
2894
+ for (const [kind, name] of SETUP_SECTIONS) {
2895
+ const items = rows.filter((row) => row.kind === kind);
2896
+ if (!items.length) continue;
2897
+ body.append(paintSetupSection(entry, kind, name, items, open));
2898
+ }
2899
+ card.append(body);
2900
+ body.addEventListener('scroll', () => { entry.bodyScroll = body.scrollTop; }, { passive: true });
2901
+ if (entry.bodyScroll) requestAnimationFrame(() => { if (body.isConnected) body.scrollTop = entry.bodyScroll; });
2902
+
2903
+ const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert');
2904
+ error.textContent = entry.cardError || '';
2905
+ card.append(error);
2906
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2907
+ if (open && (allSettled || allAnswered)) {
2908
+ const done = document.createElement('p'); done.className = 'ai-chat-height-done';
2909
+ done.textContent = allSettled
2910
+ ? 'All settled. Press Tell the read, then Send, so the AI can carry on.'
2911
+ : 'All answered. Press Tell the read, then Send: the read looks at what you sent and asks you to confirm its reading here.';
2912
+ card.append(done);
2913
+ const tell = heightActionButton('Tell the read', `shell.chat-setup-tell-read#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', null);
2914
+ tell.addEventListener('click', () => tellReadAnswered(entry, `I've answered setup question ${view.n}.`, repaintSetupCard));
2915
+ actions.append(tell);
2916
+ }
2917
+ actions.hidden = !actions.childNodes.length;
2918
+ card.append(actions);
2919
+ return card;
2920
+ }
2921
+
2922
+ function paintSetupSection(entry, kind, name, items, open) {
2923
+ const section = document.createElement('div'); section.className = 'ai-chat-setup-section';
2924
+ const live = items.filter(setupLive);
2925
+ const settled = live.filter(setupSettled).length;
2926
+ // The first section with something open starts expanded; a settled one collapses to one line.
2927
+ const expanded = entry.expanded.has(kind) ? entry.expanded.get(kind) : (settled < live.length || !open);
2928
+ const toggle = document.createElement('button');
2929
+ toggle.type = 'button'; toggle.className = 'ai-chat-setup-section-head';
2930
+ toggle.dataset.commandId = `shell.chat-setup-section#${entry.questionId} ${kind}`;
2931
+ toggle.dataset.commandInstanceLabel = name;
2932
+ toggle.setAttribute('aria-expanded', String(expanded));
2933
+ const label = document.createElement('span'); label.textContent = name;
2934
+ const tally = document.createElement('span'); tally.className = 'ai-chat-filter-state';
2935
+ tally.textContent = settled === live.length ? '✓ settled' : `${settled}/${live.length}`;
2936
+ toggle.append(label, tally);
2937
+ toggle.addEventListener('click', () => { entry.expanded.set(kind, !expanded); repaintSetupCard(entry); });
2938
+ section.append(toggle);
2939
+ if (!expanded) {
2940
+ const summary = document.createElement('p'); summary.className = 'ai-chat-setup-summary';
2941
+ summary.textContent = live.map((row) => `${row.kind === 'origin' ? 'Origin' : row.view.sheet} ${setupAnswerText(row) || 'open'}`).join(' · ');
2942
+ section.append(summary);
2943
+ return section;
2944
+ }
2945
+ const list = document.createElement('ol'); list.className = 'ai-chat-setup-list';
2946
+ for (const row of items) list.append(paintSetupRow(entry, row, open));
2947
+ section.append(list);
2948
+ return section;
2949
+ }
2950
+
2951
+ function setupConflictBanner(row) {
2952
+ if (!row.conflict) return null;
2953
+ const box = document.createElement('div'); box.className = 'ai-chat-setup-conflict';
2954
+ if (row.earlier) {
2955
+ const earlier = document.createElement('div');
2956
+ earlier.textContent = `You answered ${setupAnswerText({ ...row, answer: row.earlier })}.`;
2957
+ box.append(earlier);
2958
+ }
2959
+ const why = document.createElement('div');
2960
+ const lead = document.createElement('span'); lead.className = 'ai-chat-setup-conflict-lead'; lead.textContent = 'The read says: ';
2961
+ why.append(lead, document.createTextNode(row.conflict));
2962
+ box.append(why);
2963
+ return box;
2964
+ }
2965
+
2966
+ function paintSetupRow(entry, row, open) {
2967
+ const item = document.createElement('li'); item.className = 'ai-chat-height-row ai-chat-setup-row';
2968
+ item.dataset.status = row.status;
2969
+ item.dataset.key = row.key;
2970
+ const name = row.kind === 'origin' ? 'Model origin' : viewName(row);
2971
+ const instance = row.kind === 'origin' ? 'the model origin' : `${row.kind === 'scale' ? 'the scale of' : 'the level of'} ${viewName(row)}`;
2972
+ const idFor = (what, extra) => `shell.chat-setup-${what}#${entry.questionId} ${row.key}${extra ? ` ${extra}` : ''}`;
2973
+ const sourceIdFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} ${row.key}${extra ? ` ${extra}` : ''}`;
2974
+ if (row.kind !== 'origin') {
2975
+ const label = document.createElement('div'); label.className = 'ai-chat-height-label'; label.textContent = name; label.dataset.tip = name;
2976
+ item.append(label);
2977
+ }
2978
+ const banner = setupConflictBanner(row);
2979
+ if (banner) item.append(banner);
2980
+
2981
+ if (row.status === 'superseded') {
2982
+ const gone = document.createElement('div'); gone.className = 'ai-chat-height-answered';
2983
+ gone.textContent = 'Asked again in a newer question. This one no longer counts.';
2984
+ item.append(gone);
2985
+ return item;
2986
+ }
2987
+ const changing = entry.changing.has(row.key);
2988
+ if (row.answer && !changing && row.status !== 'picture') {
2989
+ const done = document.createElement('div'); done.className = 'ai-chat-height-answered';
2990
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-height-glyph'; glyph.textContent = row.status === 'settled' ? '✓' : '…'; glyph.setAttribute('aria-hidden', 'true');
2991
+ const text = document.createElement('span');
2992
+ text.textContent = row.status === 'needs-new-choices' ? `${setupAnswerText(row)}. Waiting for the read to offer other points.` : setupAnswerText(row);
2993
+ done.append(glyph, text);
2994
+ if (open && !row.frozen) {
2995
+ 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);
2996
+ change.setAttribute('aria-label', `Change your answer for ${instance}`);
2997
+ change.addEventListener('click', () => {
2998
+ if (change.getAttribute('aria-disabled') === 'true') return;
2999
+ entry.changing.add(row.key);
3000
+ // A "none" answer's note is the person's REASON, not a source: it is not put in the source box.
3001
+ 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; }
3002
+ repaintSetupCard(entry);
3003
+ });
3004
+ done.append(change);
3005
+ }
3006
+ item.append(done);
3007
+ const source = paintAnsweredSource(entry.requestId, row.answer, sourceIdFor, instance);
3008
+ if (source) item.append(source);
3009
+ if (row.frozen) { const frozen = document.createElement('p'); frozen.className = 'ai-chat-setup-frozen'; frozen.textContent = row.frozen; item.append(frozen); }
3010
+ return item;
3011
+ }
3012
+ if (row.status === 'picture' && !changing) {
3013
+ const wait = document.createElement('div'); wait.className = 'ai-chat-height-answered';
3014
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-height-glyph'; glyph.textContent = '…'; glyph.setAttribute('aria-hidden', 'true');
3015
+ const text = document.createElement('span'); text.textContent = 'Waiting for the read to read your picture';
3016
+ wait.append(glyph, text);
3017
+ if (open) {
3018
+ const change = heightActionButton('Answer now', idFor('change'), instance, 'ai-chat-height-change', null);
3019
+ change.setAttribute('aria-label', `Answer ${instance} yourself instead`);
3020
+ change.addEventListener('click', () => { entry.changing.add(row.key); repaintSetupCard(entry); });
3021
+ wait.append(change);
3022
+ }
3023
+ item.append(wait);
3024
+ const source = paintAnsweredSource(entry.requestId, row.answer, sourceIdFor, instance);
3025
+ if (source) item.append(source);
3026
+ return item;
3027
+ }
3028
+ if (!open) {
3029
+ const none = document.createElement('div'); none.className = 'ai-chat-height-answered'; none.textContent = 'No answer';
3030
+ item.append(none);
3031
+ return item;
3032
+ }
3033
+ if (row.frozen) { const frozen = document.createElement('p'); frozen.className = 'ai-chat-setup-frozen'; frozen.textContent = row.frozen; item.append(frozen); return item; }
3034
+ const busyReason = entry.busy ? 'An answer is still being saved — wait for it to finish' : null;
3035
+ const scope = `s:${entry.questionId}:${row.key}`;
3036
+ if (row.kind === 'scale') paintScaleControls(entry, row, item, instance, idFor, busyReason, scope);
3037
+ else if (row.kind === 'level') paintLevelControls(entry, row, item, instance, idFor, busyReason, scope);
3038
+ else paintOriginControls(entry, row, item, instance, idFor, busyReason, scope);
3039
+ item.append(paintAnswerSource(scope, {
3040
+ requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintSetupCard(entry), label: instance, instance,
3041
+ idFor: sourceIdFor, inherited: row.inherited, busyReason, allowPictureOnly: true,
3042
+ onPictureOnly: () => submitSetupAnswers(entry, [{ key: row.key, action: 'evidence' }], row.key),
3043
+ }));
3044
+ const rowError = document.createElement('p'); rowError.className = 'ai-chat-height-error'; rowError.setAttribute('role', 'alert');
3045
+ rowError.textContent = entry.rowErrors.get(row.key) || '';
3046
+ item.append(rowError);
3047
+ return item;
3048
+ }
3049
+
3050
+ function setupProposal(valueText, tag, evidence, confirm) {
3051
+ const box = document.createElement('div'); box.className = 'ai-chat-setup-proposal';
3052
+ const line = document.createElement('div'); line.className = 'ai-chat-height-proposal';
3053
+ const value = document.createElement('span'); value.textContent = valueText;
3054
+ line.append(value, confirm);
3055
+ const source = document.createElement('div'); source.className = 'ai-chat-setup-evidence';
3056
+ const label = document.createElement('span'); label.className = 'ai-chat-setup-tag'; label.textContent = tag;
3057
+ source.append(label, document.createTextNode(` ${evidence}`));
3058
+ source.dataset.tip = `${tag}: ${evidence}`;
3059
+ box.append(line, source);
3060
+ return box;
3061
+ }
3062
+
3063
+ function setupTypedField(entry, row, item, instance, idFor, busyReason, placeholder, ariaWhat, primary) {
3064
+ const field = document.createElement('div'); field.className = 'ai-chat-height-field';
3065
+ const input = document.createElement('input');
3066
+ input.type = 'text'; input.className = 'ai-chat-height-input'; input.autocomplete = 'off'; input.spellcheck = false;
3067
+ input.dataset.commandId = idFor('input'); input.dataset.commandInstanceLabel = instance;
3068
+ input.placeholder = placeholder;
3069
+ input.setAttribute('aria-label', `${ariaWhat} for ${instance}`);
3070
+ input.value = entry.drafts.get(row.key) || '';
3071
+ input.addEventListener('input', () => { entry.drafts.set(row.key, input.value); entry.rowErrors.delete(row.key); if (row.kind === 'origin' && input.value) entry.originPick = null; });
3072
+ if (busyReason) { input.readOnly = true; input.setAttribute('aria-disabled', 'true'); input.dataset.blockedReason = busyReason; }
3073
+ const use = heightActionButton('Use', idFor('use'), instance, primary ? 'ai-chat-filter-apply' : '', busyReason);
3074
+ use.setAttribute('aria-label', `Use what you typed for ${instance}`);
3075
+ const submit = () => {
3076
+ if (use.getAttribute('aria-disabled') === 'true') return;
3077
+ const typed = input.value.trim();
3078
+ if (!typed) { entry.rowErrors.set(row.key, 'Type an answer first.'); repaintSetupCard(entry); return; }
3079
+ submitSetupAnswers(entry, [{ key: row.key, action: 'type', typed }], row.key);
3080
+ };
3081
+ input.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } });
3082
+ use.addEventListener('click', submit);
3083
+ field.append(input, use);
3084
+ item.append(field);
3085
+ }
3086
+
3087
+ function paintScaleControls(entry, row, item, instance, idFor, busyReason, scope) {
3088
+ if (row.clue) { const clue = document.createElement('p'); clue.className = 'ai-chat-setup-why'; clue.textContent = row.clue; item.append(clue); }
3089
+ for (const proposal of row.proposals) {
3090
+ const confirm = heightActionButton(proposal.pageFit ? 'Use for this plan' : 'Confirm', idFor('confirm', proposal.id), instance, 'ai-chat-filter-apply', busyReason);
3091
+ confirm.setAttribute('aria-label', `${proposal.pageFit ? 'Use' : 'Confirm'} ${proposal.standard} for ${instance}`);
3092
+ confirm.addEventListener('click', () => {
3093
+ if (confirm.getAttribute('aria-disabled') === 'true') return;
3094
+ submitSetupAnswers(entry, [{ key: row.key, action: 'confirm', choice: proposal.id, shown: proposal.mmPerPx }], row.key);
3095
+ });
3096
+ // The Confirm records mmPerPx, so the exact number is shown beside the standard (Codex review #1906).
3097
+ item.append(setupProposal(`${proposal.standard} · ${scaleNumber(proposal.mmPerPx)} mm per drawing point`, scaleTag[proposal.source] || 'PROPOSED', proposal.evidence, confirm));
3098
+ }
3099
+ 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);
3100
+ }
3101
+
3102
+ const scaleNumber = (mmPerPx) => String(Number(Number(mmPerPx).toFixed(6)));
3103
+
3104
+ function levelEvidence(p) {
3105
+ const more = p.alsoOn ? `, and ${p.alsoOn} more` : '';
3106
+ if (p.source === 'drawing-text') return `${p.sheet} shows “${p.quote || p.asRead}”${p.near ? ` near ${p.near}` : ''}${more}.`;
3107
+ 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}.`;
3108
+ return 'Read from the picture you sent. Check it before you confirm.';
3109
+ }
3110
+
3111
+ function paintLevelControls(entry, row, item, instance, idFor, busyReason, scope) {
3112
+ 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); }
3113
+ const units = entry.view?.units;
3114
+ for (const proposal of row.proposals) {
3115
+ const confirm = heightActionButton('Confirm', idFor('confirm', proposal.id), instance, 'ai-chat-filter-apply', busyReason);
3116
+ confirm.setAttribute('aria-label', `Confirm ${proposal.asRead} for ${instance}`);
3117
+ confirm.addEventListener('click', () => {
3118
+ if (confirm.getAttribute('aria-disabled') === 'true') return;
3119
+ submitSetupAnswers(entry, [{ key: row.key, action: 'confirm', choice: proposal.id, shown: proposal.value }], row.key);
3120
+ });
3121
+ item.append(setupProposal(proposal.asRead, levelTag[proposal.source] || 'PROPOSED', levelEvidence(proposal), confirm));
3122
+ }
3123
+ 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);
3124
+ 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');
3125
+ }
3126
+
3127
+ function paintNoneControl(entry, row, item, instance, idFor, busyReason, label, placeholder, saveLabel) {
3128
+ if (!entry.noneOpen.has(row.key)) {
3129
+ const none = heightActionButton(label, idFor('none'), instance, 'ai-chat-setup-secondary', busyReason);
3130
+ none.setAttribute('aria-label', `${label} for ${instance}`);
3131
+ none.addEventListener('click', () => {
3132
+ if (none.getAttribute('aria-disabled') === 'true') return;
3133
+ entry.noneOpen.add(row.key); repaintSetupCard(entry);
3134
+ const card = ui.feed.querySelector(`[data-setup-question="${CSS.escape(entry.key)}"]`);
3135
+ if (card) focusHeightControl(card, idFor('none-note'));
3136
+ });
3137
+ item.append(none);
3138
+ return;
3139
+ }
3140
+ const field = document.createElement('div'); field.className = 'ai-chat-height-field';
3141
+ const note = document.createElement('input');
3142
+ note.type = 'text'; note.className = 'ai-chat-height-input'; note.maxLength = 160; note.autocomplete = 'off';
3143
+ note.dataset.commandId = idFor('none-note'); note.dataset.commandInstanceLabel = instance;
3144
+ note.placeholder = placeholder;
3145
+ note.setAttribute('aria-label', `Why: ${label.toLowerCase()} for ${instance}`);
3146
+ note.required = true;
3147
+ const noteKey = `${row.key}\u0000none`;
3148
+ note.value = entry.drafts.get(noteKey) || '';
3149
+ note.addEventListener('input', () => { entry.drafts.set(noteKey, note.value); entry.rowErrors.delete(row.key); });
3150
+ const save = heightActionButton(saveLabel, idFor('none-save'), instance, '', busyReason);
3151
+ const submit = () => {
3152
+ if (save.getAttribute('aria-disabled') === 'true') return;
3153
+ const text = note.value.trim();
3154
+ if (!text) { entry.rowErrors.set(row.key, 'Add a short note first, so the read knows what to do instead.'); repaintSetupCard(entry); return; }
3155
+ submitSetupAnswers(entry, [{ key: row.key, action: 'none', note: text }], row.key);
3156
+ };
3157
+ note.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } });
3158
+ save.addEventListener('click', submit);
3159
+ field.append(note, save);
3160
+ item.append(field);
3161
+ }
3162
+
3163
+ function paintOriginControls(entry, row, item, instance, idFor, busyReason, scope) {
3164
+ const group = document.createElement('fieldset'); group.className = 'ai-chat-setup-origin';
3165
+ group.setAttribute('role', 'radiogroup');
3166
+ const legend = document.createElement('legend'); legend.textContent = 'Which grid crossing is the model’s origin (0, 0)?';
3167
+ group.append(legend);
3168
+ const radio = (choiceId, text, tag) => {
3169
+ const label = document.createElement('label'); label.className = 'ai-chat-setup-choice';
3170
+ const input = document.createElement('input');
3171
+ input.type = 'radio'; input.name = `origin-${entry.questionId}`; input.value = choiceId;
3172
+ input.dataset.commandId = idFor('origin-choice', choiceId); input.dataset.commandInstanceLabel = text;
3173
+ input.checked = entry.originPick === choiceId;
3174
+ if (busyReason) { input.disabled = true; }
3175
+ input.addEventListener('change', () => { entry.originPick = choiceId; entry.drafts.delete(row.key); entry.rowErrors.delete(row.key); repaintSetupCard(entry); });
3176
+ const name = document.createElement('span'); name.className = 'ai-chat-setup-choice-name'; name.textContent = text;
3177
+ label.append(input, name);
3178
+ if (tag) { const t = document.createElement('span'); t.className = 'ai-chat-setup-tag'; t.textContent = tag; label.append(t); }
3179
+ return label;
3180
+ };
3181
+ const straight = document.createElement('div'); straight.className = 'ai-chat-setup-choices';
3182
+ 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') : '')));
3183
+ group.append(straight);
3184
+ if (row.offGrid.length) {
3185
+ const also = document.createElement('fieldset'); also.className = 'ai-chat-setup-also';
3186
+ const legend2 = document.createElement('legend'); legend2.textContent = 'Also on the drawing (not straight grid lines)';
3187
+ also.append(legend2);
3188
+ row.offGrid.forEach((point, i) => also.append(radio(`o${i}`, point.as, '')));
3189
+ group.append(also);
3190
+ }
3191
+ item.append(group);
3192
+ const pick = entry.originPick;
3193
+ let target = null;
3194
+ if (pick && pick.startsWith('c')) target = row.choices[Number(pick.slice(1))] || null;
3195
+ let statement = null;
3196
+ if (pick && pick.startsWith('o')) {
3197
+ const point = row.offGrid[Number(pick.slice(1))];
3198
+ target = point ? row.choices[point.same] : null;
3199
+ if (point && target) {
3200
+ // Said BEFORE the confirm, and the confirm itself names the straight intersection that lands.
3201
+ statement = document.createElement('div'); statement.className = 'ai-chat-setup-statement';
3202
+ statement.setAttribute('role', 'status');
3203
+ statement.id = `setup-statement-${entry.questionId}`;
3204
+ 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.`;
3205
+ item.append(statement);
3206
+ }
3207
+ }
3208
+ const confirmLabel = target ? `Confirm ${originText(target)} as the model origin` : 'Confirm the model origin';
3209
+ const confirm = heightActionButton(confirmLabel, idFor('origin-confirm'), instance, 'ai-chat-filter-apply', busyReason || (target ? null : 'Pick a point first'));
3210
+ if (statement) confirm.setAttribute('aria-describedby', statement.id);
3211
+ confirm.addEventListener('click', () => {
3212
+ if (confirm.getAttribute('aria-disabled') === 'true' || !target) return;
3213
+ submitSetupAnswers(entry, [{ key: row.key, action: 'confirm', choice: pick, shown: originText(target) }], row.key);
3214
+ });
3215
+ const actions = document.createElement('div'); actions.className = 'ai-chat-height-proposal';
3216
+ actions.append(confirm);
3217
+ item.append(actions);
3218
+ setupTypedField(entry, row, item, instance, idFor, busyReason, 'or type a point, e.g. K/1.1', 'Type the grid point', false);
3219
+ 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');
3220
+ }
3221
+
3222
+ async function submitSetupAnswers(entry, answers, rowKey) {
3223
+ if (entry.busy) return;
3224
+ const withSource = answers.map((answer) => withAnswerSource(answer, answerSourcePayload(`s:${entry.questionId}:${answer.key}`)));
3225
+ const tooLong = withSource.find((answer) => answer.note && answer.note.length > MAX_ANSWER_NOTE);
3226
+ if (tooLong) {
3227
+ entry.rowErrors.set(rowKey, `Your reason and your source note together are longer than ${MAX_ANSWER_NOTE} characters. Shorten one of them.`);
3228
+ repaintSetupCard(entry); return;
3229
+ }
3230
+ if (withSource.some((answer) => answer.action === 'evidence' && !answer.evidence?.length)) {
3231
+ entry.rowErrors.set(rowKey, 'Attach a picture first.'); repaintSetupCard(entry); return;
3232
+ }
3233
+ entry.busy = true; entry.cardError = ''; if (rowKey) entry.rowErrors.delete(rowKey);
3234
+ repaintSetupCard(entry);
3235
+ try {
3236
+ const result = await request(`/api/chat/setup-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}/answers`, {
3237
+ method: 'POST', body: JSON.stringify({ chatId: entry.chatId, answers: withSource }),
3238
+ });
3239
+ entry.view = result.question;
3240
+ for (const answer of answers) {
3241
+ entry.changing.delete(answer.key); entry.drafts.delete(answer.key); entry.drafts.delete(`${answer.key}\u0000none`);
3242
+ entry.noneOpen.delete(answer.key);
3243
+ if (answer.key === 'origin') entry.originPick = null;
3244
+ clearAnswerSource(`s:${entry.questionId}:${answer.key}`);
3245
+ }
3246
+ } catch (error) {
3247
+ let message = heightErrorText(error, 'FloLess could not save this answer. Try again.');
3248
+ if (error?.code === 'answer-evidence-unknown') message = dropStaleAnswerFiles(answers.map((answer) => `s:${entry.questionId}:${answer.key}`), entry);
3249
+ if (SETUP_STALE.has(error?.code)) { entry.cardError = message; entry.view = null; loadSetupQuestion(entry); }
3250
+ else if (rowKey) entry.rowErrors.set(rowKey, message);
3251
+ else entry.cardError = message;
3252
+ } finally {
3253
+ entry.busy = false;
3254
+ repaintSetupCard(entry);
3255
+ settlePendingReload(entry, loadSetupQuestion);
3256
+ focusNextSetupControl(entry);
3257
+ }
3258
+ }
3259
+
3260
+ // After an answer, keyboard focus moves to the next row still open, or to Tell the read.
3261
+ function focusNextSetupControl(entry) {
3262
+ const card = ui.feed?.querySelector(`[data-setup-question="${CSS.escape(entry.key)}"]`);
3263
+ if (!card || (document.activeElement && card.contains(document.activeElement) && document.activeElement.tagName === 'INPUT')) return;
3264
+ const target = card.querySelector('.ai-chat-setup-row[data-status="open"] button:not([aria-disabled="true"]), .ai-chat-setup-row[data-status="open"] input')
3265
+ || card.querySelector('[data-command-id^="shell.chat-setup-tell-read"]');
3266
+ target?.focus({ preventScroll: true });
3267
+ }
3268
+
1873
3269
  // A server-authored receipt of one approved live Tekla read. Deterministic: it shows only what
1874
3270
  // the server recorded, and an unverified read never shows a model name or parts.
1875
3271
  function renderTeklaReadEvent(event) {
@@ -1915,8 +3311,70 @@
1915
3311
  return card;
1916
3312
  }
1917
3313
 
3314
+ /* #1798: a receipt's weights follow the chat's display units — lb for ft-in, kg for mm. The receipt records
3315
+ kilograms and keeps them; this converts only what is shown, through the one shared helper
3316
+ (web/display-units.js). Until the units and the helper are both known it shows the recorded kilograms. */
3317
+ let displayUnitsModule = null;
3318
+ let displayUnitsLoading = null;
3319
+ function loadDisplayUnitsModule() {
3320
+ displayUnitsLoading ??= import('./display-units.js').then(
3321
+ (module) => { displayUnitsModule = module; },
3322
+ (error) => { displayUnitsLoading = null; console.warn('[chat] the display-units helper could not be loaded', error); });
3323
+ return displayUnitsLoading;
3324
+ }
3325
+ function receiptWeightUnits() {
3326
+ return displayUnitsModule && state.displayUnits ? state.displayUnits : null;
3327
+ }
3328
+ function teklaWeightWord() {
3329
+ const units = receiptWeightUnits();
3330
+ return units ? displayUnitsModule.weightUnitWord(units) : 'kg';
3331
+ }
1918
3332
  function teklaKg(value) {
1919
- return new Intl.NumberFormat(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(value);
3333
+ const units = receiptWeightUnits();
3334
+ const shown = units ? displayUnitsModule.weightIn(value, units) : value;
3335
+ return new Intl.NumberFormat(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(shown);
3336
+ }
3337
+
3338
+ function displayUnitsUrl(owner) {
3339
+ return owner.kind === 'project'
3340
+ ? `/api/projects/${encodeURIComponent(owner.projectId)}/display-units`
3341
+ : `/api/workflows/owned/${encodeURIComponent(owner.workflowId)}/display-units`;
3342
+ }
3343
+
3344
+ // A workspace conversation has no owner setting (#1890): its units are the person's choice, else the suggestion.
3345
+ function workspaceUnitsOf(chat) {
3346
+ const units = chat?.workspaceUnits;
3347
+ const pick = (value) => (value === 'mm' || value === 'ft-in' ? value : null);
3348
+ return pick(units?.chosen) || pick(units?.suggested);
3349
+ }
3350
+
3351
+ // Asks the server for the open chat's units, then repaints so every receipt — old ones too — follows them.
3352
+ // A failed read keeps whatever was last confirmed (or the recorded kilograms) and says so in the console.
3353
+ async function refreshDisplayUnits(retries = 2) {
3354
+ const owner = state.scope?.owner;
3355
+ const generation = ++state.displayUnitsGeneration;
3356
+ if (!owner) { state.displayUnits = null; return; }
3357
+ const shownBefore = receiptWeightUnits();
3358
+ if (owner.kind === 'workspace') {
3359
+ await loadDisplayUnitsModule().catch(() => {});
3360
+ if (generation !== state.displayUnitsGeneration) return;
3361
+ state.displayUnits = workspaceUnitsOf(state.chat);
3362
+ if (receiptWeightUnits() !== shownBefore && state.chat) paintEvents();
3363
+ return;
3364
+ }
3365
+ try {
3366
+ const [body] = await Promise.all([request(displayUnitsUrl(owner)), loadDisplayUnitsModule()]);
3367
+ if (generation !== state.displayUnitsGeneration) return;
3368
+ const units = body?.displayUnits === 'mm' || body?.displayUnits === 'ft-in' ? body.displayUnits : null;
3369
+ state.displayUnits = units;
3370
+ // Repaint on what the receipts would SHOW: the units changing, or the helper arriving after a failed load.
3371
+ if (receiptWeightUnits() !== shownBefore && state.chat) paintEvents();
3372
+ } catch (error) {
3373
+ if (generation !== state.displayUnitsGeneration) return;
3374
+ console.warn('[chat] this conversation’s display units could not be read', error);
3375
+ // A brief outage should not leave the receipts in recorded kilograms for the rest of the conversation.
3376
+ if (retries > 0) setTimeout(() => { if (generation === state.displayUnitsGeneration) void refreshDisplayUnits(retries - 1); }, 1500);
3377
+ }
1920
3378
  }
1921
3379
  function teklaCount(value) { return new Intl.NumberFormat().format(value); }
1922
3380
  function partsWord(count) { return `${teklaCount(count)} ${count === 1 ? 'part' : 'parts'}`; }
@@ -1925,7 +3383,7 @@
1925
3383
  // list that was cut short says so before anyone scrolls.
1926
3384
  function teklaSelectionSummary(payload, listed) {
1927
3385
  const count = Number(payload.partCount) || 0;
1928
- const total = `${teklaKg(Number(payload.totalWeightKg) || 0)} kg`;
3386
+ const total = `${teklaKg(Number(payload.totalWeightKg) || 0)} ${teklaWeightWord()}`;
1929
3387
  const missing = Number(payload.weightMissing) || 0;
1930
3388
  const lines = [];
1931
3389
  if (payload.complete === false) {
@@ -2006,9 +3464,10 @@
2006
3464
  caption.textContent = `Parts selected in Tekla when checked (${parts.length} listed of ${count})`;
2007
3465
  const head = document.createElement('thead');
2008
3466
  const headRow = document.createElement('tr');
2009
- for (const [label, numeric] of [['Mark', false], ['Name', false], ['Profile', false], ['Material', false], ['kg', true]]) {
3467
+ const weightWord = teklaWeightWord();
3468
+ for (const [label, numeric] of [['Mark', false], ['Name', false], ['Profile', false], ['Material', false], [weightWord, true]]) {
2010
3469
  const th = document.createElement('th'); th.scope = 'col'; th.textContent = label;
2011
- if (numeric) { th.className = 'num'; th.setAttribute('aria-label', 'Weight in kilograms'); }
3470
+ if (numeric) { th.className = 'num'; th.setAttribute('aria-label', weightWord === 'lb' ? 'Weight in pounds' : 'Weight in kilograms'); }
2012
3471
  headRow.append(th);
2013
3472
  }
2014
3473
  head.append(headRow);
@@ -2087,8 +3546,8 @@
2087
3546
  const missing = new Set(Array.isArray(payload.missingLinkedParts) ? payload.missingLinkedParts : []);
2088
3547
  if (!parts.length && !missing.size) return null;
2089
3548
  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 };
3549
+ const ownerKey = scopeKey(state.scope);
3550
+ const loaded = ownerKey && state.teklaLinks.ownerKey === ownerKey ? state.teklaLinks : { state: 'idle', links: [], partial: false };
2092
3551
  const own = payload.linkedQuestion?.messageEventId;
2093
3552
  const chatLinks = loaded.state === 'ready' ? { ...loaded, links: loaded.links.filter((link) => link.messageEventId !== own) } : loaded;
2094
3553
  return module.renderChatQuestions({
@@ -2100,15 +3559,16 @@
2100
3559
  }
2101
3560
 
2102
3561
  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 }))
3562
+ // The links listed are this chat's owner's, so the conversation is in the scope already open (#1890: a workflow's too).
3563
+ const ownerKey = scopeKey(state.scope);
3564
+ if (!ownerKey) return false;
3565
+ Promise.resolve(openConversation(link.chatId, { messageEventId: link.messageEventId, ownerKey }))
2106
3566
  .catch((error) => { window.showToast?.(error?.message || 'That conversation could not be opened. Try Show in chat again.', 'info'); });
2107
3567
  return true;
2108
3568
  }
2109
3569
 
2110
3570
  function appendTeklaHistory(card, event) {
2111
- if (state.scope?.owner?.kind !== 'project' || event.eventId !== newestTeklaSelectionId(state.events)) return;
3571
+ if (!state.scope?.owner || event.eventId !== newestTeklaSelectionId(state.events)) return;
2112
3572
  const host = document.createElement('div');
2113
3573
  host.className = 'ai-chat-tekla-history';
2114
3574
  host.hidden = true;
@@ -2141,7 +3601,7 @@
2141
3601
  // The check fell short for another reason: the receipt must never look like "no linked part is missing".
2142
3602
  const shortfall = {
2143
3603
  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.',
3604
+ 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
3605
  }[payload.linkedPartsCheck];
2146
3606
  if (shortfall) {
2147
3607
  const line = document.createElement('p');
@@ -2154,19 +3614,19 @@
2154
3614
  }
2155
3615
 
2156
3616
  async function loadTeklaLinks(force = false) {
2157
- const projectId = state.scope?.owner?.kind === 'project' ? state.scope.owner.projectId : null;
2158
- if (!projectId) return;
3617
+ const ownerKey = scopeKey(state.scope);
3618
+ if (!ownerKey) return;
2159
3619
  const current = state.teklaLinks;
2160
- const same = current.projectId === projectId;
3620
+ const same = current.ownerKey === ownerKey;
2161
3621
  // Only a real change (a new receipt, a link written live, Retry) asks again; a repaint while an answer streams must
2162
3622
  // not queue one read after another.
2163
3623
  if (same && current.inflight) { if (force) current.again = true; return; }
2164
3624
  if (same && !force && current.state !== 'idle') return;
2165
- const next = { projectId, state: same ? current.state : 'idle', links: same ? current.links : [], partial: same && current.partial,
3625
+ const next = { ownerKey, state: same ? current.state : 'idle', links: same ? current.links : [], partial: same && current.partial,
2166
3626
  inflight: true, again: false };
2167
3627
  state.teklaLinks = next;
2168
3628
  try {
2169
- const result = await request(`/api/chat/subject-links?ownerKind=project&ownerId=${encodeURIComponent(projectId)}&source=tekla`);
3629
+ const result = await request(`/api/chat/subject-links?${ownerQuery()}&source=tekla`);
2170
3630
  if (state.teklaLinks === next) {
2171
3631
  Object.assign(next, { state: 'ready', links: Array.isArray(result?.links) ? result.links : [], partial: Boolean(result?.partial) });
2172
3632
  }
@@ -2274,7 +3734,9 @@
2274
3734
  // That button is `aria-disabled`, not `disabled`, so it passes the filter (#1514).
2275
3735
  function restoreFeedFocus(focusedCommand) {
2276
3736
  if (!focusedCommand?.startsWith('shell.chat-followup-') && !focusedCommand?.startsWith('shell.chat-filter-')
2277
- && !focusedCommand?.startsWith('shell.chat-question') && focusedCommand !== 'shell.chat-sign-in') return;
3737
+ && !focusedCommand?.startsWith('shell.chat-question') && !focusedCommand?.startsWith('shell.chat-height-')
3738
+ && !focusedCommand?.startsWith('shell.chat-setup-') && !focusedCommand?.startsWith('shell.chat-answer-')
3739
+ && focusedCommand !== 'shell.chat-sign-in') return;
2278
3740
  [...ui.feed.querySelectorAll('[data-command-id]')]
2279
3741
  .find(control => control.dataset.commandId === focusedCommand && !control.disabled)?.focus({ preventScroll: true });
2280
3742
  }
@@ -2318,7 +3780,9 @@
2318
3780
  // Provider tools commonly split one answer into before/after chunks. They are not prose,
2319
3781
  // so keep collecting same-turn deltas across them instead of rendering abandoned fragments.
2320
3782
  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; }
3783
+ // FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
3784
+ // held and shown under the answer, so they never cut one answer into fragments.
3785
+ if (event.type === 'chat-subjects' || event.type === 'evidence-read' || event.type === 'filter-proposal') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
2322
3786
  flushAssistant();
2323
3787
  const node = renderEvent(event);
2324
3788
  if (node) ui.feed.append(node);
@@ -2373,7 +3837,10 @@
2373
3837
  empty.append(strong, copy, emptySignInButton(label, true, copy.id));
2374
3838
  } else if (providerReady()) {
2375
3839
  strong.textContent = 'Ready when you are';
2376
- copy.textContent = `This ${label} conversation is stored with ${state.scope?.label || 'this work'}.`;
3840
+ // #1890: a workspace conversation is one shared history, reachable from every landing and installed workflow.
3841
+ copy.textContent = state.scope?.owner?.kind === 'workspace'
3842
+ ? `This ${label} conversation is kept in your workspace. Open it again from Workspaces, Workflows or any installed workflow.`
3843
+ : `This ${label} conversation is stored with ${state.scope?.label || 'this work'}.`;
2377
3844
  empty.append(strong, copy);
2378
3845
  } else if (state.capability?.runtime && state.capability.runtime.state !== 'installed') {
2379
3846
  const notice = runtimeNotice(provider, state.capability.runtime);
@@ -2431,7 +3898,10 @@
2431
3898
  // Keep the same buttons during polling so keyboard focus and pointer clicks survive. A Tekla card
2432
3899
  // also carries the permission view it offers "Allow for this chat" on, so a change repaints it.
2433
3900
  const teklaBinding = teklaAllowableApproval(approval) ? currentTeklaBinding(state.chat) : null;
2434
- const allowanceRevision = teklaBinding ? String(teklaAllowanceRevision(teklaBinding)) : '';
3901
+ // #1907: a call to one of the person's connectors FloLess could identify may be allowed for the whole chat.
3902
+ const connector = approval.connector?.verified ? approval.connector : null;
3903
+ const allowanceRevision = teklaBinding ? String(teklaAllowanceRevision(teklaBinding))
3904
+ : connector ? String(state.chat?.connectorAllowance?.revision ?? 0) : '';
2435
3905
  if (existing?.dataset.approvalId === approval.approvalId && (existing.dataset.allowanceRevision || '') === allowanceRevision) return;
2436
3906
  // A permission change repaints the same approval: keep keyboard focus on the same control.
2437
3907
  const refocus = existing?.dataset.approvalId === approval.approvalId && existing.contains(document.activeElement)
@@ -2439,7 +3909,7 @@
2439
3909
  existing?.remove();
2440
3910
  const card = document.createElement('section'); card.className = 'ai-chat-approval';
2441
3911
  card.dataset.approvalId = approval.approvalId;
2442
- if (teklaBinding) card.dataset.allowanceRevision = allowanceRevision;
3912
+ if (teklaBinding || connector) card.dataset.allowanceRevision = allowanceRevision;
2443
3913
  const heading = document.createElement('strong'); heading.textContent = 'Approval needed';
2444
3914
  const copy = document.createElement('p'); copy.textContent = approval.summary;
2445
3915
  const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
@@ -2459,6 +3929,27 @@
2459
3929
  allowRequest.setAttribute('aria-describedby', scope.id);
2460
3930
  allowRequest.addEventListener('click', () => decideApproval('allow-request'));
2461
3931
  actions.append(deny, allow, allowRequest); card.append(heading, copy, actions, scope);
3932
+ } else if (connector) {
3933
+ card.dataset.explicitOnly = 'true';
3934
+ // The warning is the part that decides it: on its own line, not at the end of the question.
3935
+ const split = approval.summary.indexOf(' FloLess cannot check');
3936
+ const warning = document.createElement('p');
3937
+ warning.className = 'ai-chat-approval-warning';
3938
+ if (split > 0) {
3939
+ copy.textContent = approval.summary.slice(0, split);
3940
+ warning.textContent = approval.summary.slice(split + 1);
3941
+ }
3942
+ const who = connectorLabel(connector);
3943
+ const allowChat = button(`Allow ${who} for this chat`, `shell.chat-connector-allow-chat#${connectorKey(connector)}`, 'allow');
3944
+ allowChat.dataset.commandInstanceLabel = who;
3945
+ const help = document.createElement('span');
3946
+ help.className = 'sr-only';
3947
+ help.id = `chat-approval-connector-scope-help-${approval.approvalId}`;
3948
+ help.textContent = `Let ${who} run whenever Chat asks in this conversation, without asking you each time. Each run is shown in the chat. Revoke it above the message box.`;
3949
+ allowChat.dataset.tip = help.textContent;
3950
+ allowChat.setAttribute('aria-describedby', help.id);
3951
+ allowChat.addEventListener('click', () => decideApproval('allow-chat', Number(allowanceRevision)));
3952
+ actions.append(deny, allow, allowChat); card.append(heading, copy, ...(warning.textContent ? [warning] : []), actions, help);
2462
3953
  } else if (teklaBinding) {
2463
3954
  // A Tekla read may instead be allowed for the whole chat, covering every read the chat is bound for.
2464
3955
  card.dataset.explicitOnly = 'true';
@@ -2570,8 +4061,7 @@
2570
4061
  };
2571
4062
  }
2572
4063
 
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.
4064
+ // What the setup card shows for one conversation: the card is rebuilt only when this changes.
2575
4065
  function runtimeCardKey(chatId, status) {
2576
4066
  return `${chatId}:${status.state}:${status.owner || ''}:${status.code || ''}:${status.retryable ? 1 : 0}`;
2577
4067
  }
@@ -2688,9 +4178,10 @@
2688
4178
  */
2689
4179
  function paintAttachControl() {
2690
4180
  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`;
4181
+ // Every message takes what any message takes, the Drawing Filter open or not (#1859), and that
4182
+ // includes data files (#1853); the tooltip lists the common ones, the spoken label stays short.
4183
+ const kinds = 'a picture, PDF, or data file';
4184
+ ui.attach.dataset.tip = `Attach ${kinds} (IFC, DXF, CSV, text) · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images in this message`;
2694
4185
  ui.attach.setAttribute('aria-label', `Attach ${kinds} · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images`);
2695
4186
  }
2696
4187
 
@@ -2791,7 +4282,15 @@
2791
4282
  preview.src = `/api/chat/conversations/${encodeURIComponent(state.chat.chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}?${ownerQuery()}`;
2792
4283
  chip.append(preview);
2793
4284
  }
2794
- const name = document.createElement('span'); name.textContent = attachment.fileName;
4285
+ const name = document.createElement('span');
4286
+ name.textContent = attachment.mediaType.startsWith('image/') ? attachment.fileName : attachmentLabel(attachment);
4287
+ const cut = dataCutTip(attachment);
4288
+ if (cut) {
4289
+ // Hover shows the tip; the hidden sentence says the same to a keyboard or screen-reader user.
4290
+ chip.dataset.tip = cut;
4291
+ const note = document.createElement('span'); note.className = 'sr-only'; note.textContent = ` ${cut}`;
4292
+ name.append(note);
4293
+ }
2795
4294
  const remove = button('×', `shell.chat-attachment-remove#${attachment.attachmentId}`);
2796
4295
  remove.dataset.commandInstanceLabel = attachment.fileName;
2797
4296
  remove.setAttribute('aria-label', `Remove ${attachment.fileName} from the next message`);
@@ -2980,10 +4479,13 @@
2980
4479
  const medium = (model?.efforts || []).find((effort) => effort.toLowerCase() === 'medium');
2981
4480
  ui.effort.querySelector('strong').textContent = effortLabel(chat?.settings.effort || medium || model?.efforts?.[0]) || 'Choose effort';
2982
4481
  ui.permission.querySelector('strong').textContent = permissionLabels[chat?.settings.permissionProfile] || 'Read only';
4482
+ 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.';
4483
+ else delete ui.permission.dataset.tip;
4484
+ paintWorkspaceUnits();
2983
4485
  const bindings = chat?.integrationBindings || [];
2984
4486
  ui.integrations.querySelector('strong').textContent = bindings.length
2985
4487
  ? `${bindings.length} FloLess account${bindings.length === 1 ? '' : 's'}`
2986
- : `Using ${providerLabels[chat?.provider] || 'provider'} connections`;
4488
+ : 'Not using one';
2987
4489
  const frozen = !chat || Boolean(chat.activeTurn) || !state.capability?.available;
2988
4490
  ui.model.disabled = frozen; ui.effort.disabled = frozen; ui.permission.disabled = frozen;
2989
4491
  ui.integrations.disabled = frozen || Boolean(chat?.nativeSessionId);
@@ -2996,14 +4498,44 @@
2996
4498
  ui.integrations.dataset.tip = integrationBlocked || 'Choose which connected account this chat can use';
2997
4499
  if (integrationBlocked) ui.integrations.dataset.blockedReason = integrationBlocked;
2998
4500
  else delete ui.integrations.dataset.blockedReason;
4501
+ paintOwnConnectorsSetting(chat, frozen);
2999
4502
  paintDesktopStatus();
3000
4503
  }
3001
4504
 
3002
- function paintDesktopStatus() {
3003
- const desktop = state.desktop;
3004
- if (!state.chat) {
3005
- ui.desktopValue.textContent = '—';
3006
- ui.desktopReason.textContent = 'Open a conversation to check whether the desktop app can continue it.';
4505
+ /** #1907: the per-conversation switch for the AI's own connectors (off for every new conversation). */
4506
+ function paintOwnConnectorsSetting(chat, frozen) {
4507
+ const control = ui.ownConnectors;
4508
+ if (!control) return;
4509
+ const provider = providerLabels[chat?.provider] || 'Claude or Codex';
4510
+ const usesAccount = Boolean(chat?.integrationBindings?.length);
4511
+ const on = chat?.settings?.useOwnConnectors === true && !usesAccount;
4512
+ control.querySelector('span').textContent = `Use my ${provider} connectors in this chat`;
4513
+ control.querySelector('strong').textContent = on ? 'On' : 'Off';
4514
+ control.setAttribute('aria-checked', String(on));
4515
+ const blocked = !chat ? 'Open a conversation first.'
4516
+ : usesAccount ? 'This chat uses a FloLess connected account, so your own connectors stay off.'
4517
+ : chat.activeTurn ? 'Wait for the current AI reply to finish before changing this.'
4518
+ : !state.capability?.available ? capabilityMessage(chat.provider, state.capability?.reason)
4519
+ : frozen ? 'This setting cannot change right now.' : '';
4520
+ control.disabled = Boolean(blocked);
4521
+ control.dataset.tip = blocked || `Lets the AI use the connectors you added to ${provider}, such as Google Drive. Each call still asks you first. Off in every new chat.`;
4522
+ if (blocked) control.dataset.blockedReason = blocked; else delete control.dataset.blockedReason;
4523
+ }
4524
+
4525
+ async function setOwnConnectors(on, options = {}) {
4526
+ if (!state.chat) return;
4527
+ const provider = providerLabels[state.chat.provider] || 'Claude or Codex';
4528
+ await saveSettings({ useOwnConnectors: on }, { announce: false });
4529
+ if (state.chat?.settings?.useOwnConnectors === true !== on) return;
4530
+ announce(on ? `Your ${provider} connectors are on for this chat. Each call asks you first.` : `Your ${provider} connectors are off for this chat.`);
4531
+ if (options.focusInput) ui.input?.focus();
4532
+ }
4533
+
4534
+ function paintDesktopStatus() {
4535
+ const desktop = state.desktop;
4536
+ if (!state.chat) {
4537
+ ui.desktopValue.textContent = '—';
4538
+ ui.desktopReason.textContent = 'Open a conversation to check whether the desktop app can continue it.';
3007
4539
  return;
3008
4540
  }
3009
4541
  if (!desktop) {
@@ -3040,6 +4572,7 @@
3040
4572
  function paintConversation() {
3041
4573
  paintComposerDisclosure();
3042
4574
  paintTeklaChip();
4575
+ paintConnectorAllowance();
3043
4576
  const chat = state.chat;
3044
4577
  if (!chat) { providerChooser(); paintHistory(); return; }
3045
4578
  ui.historyToggle.disabled = false;
@@ -3186,6 +4719,15 @@
3186
4719
  };
3187
4720
  }
3188
4721
 
4722
+ /*
4723
+ * The composer's draft files: stored, not yet sent. A picture the person attached to an ANSWER (#1906)
4724
+ * is stored the same way but belongs to its card, never to the next message — the server refuses it
4725
+ * on a send, so listing it here would block every message (found in the Take 5 E2E).
4726
+ */
4727
+ function composerDrafts(chat) {
4728
+ return (chat.attachments || []).filter((attachment) => !attachment.turnId && attachment.purpose !== 'answer-evidence');
4729
+ }
4730
+
3189
4731
  function clearConfirmedUnknownDraft(event, chatId) {
3190
4732
  const confirmed = String(event.payload?.text || '').trim();
3191
4733
  if (state.backgroundDrafts.get(chatId)?.trim() === confirmed) state.backgroundDrafts.delete(chatId);
@@ -3255,7 +4797,7 @@
3255
4797
  }
3256
4798
  if (!sameChat(snapshot)) return;
3257
4799
  state.chat = chat;
3258
- state.attachments = (chat.attachments || []).filter((attachment) => !attachment.turnId);
4800
+ state.attachments = composerDrafts(chat);
3259
4801
  const index = state.chats.findIndex((item) => item.chatId === chatId);
3260
4802
  if (index >= 0) state.chats[index] = chat;
3261
4803
  paintConversation();
@@ -3357,7 +4899,7 @@
3357
4899
  reconcileUnknownFollowupOnSelection(chat);
3358
4900
  state.capability = capability;
3359
4901
  state.desktop = desktop;
3360
- state.attachments = (chat.attachments || []).filter((attachment) => !attachment.turnId);
4902
+ state.attachments = composerDrafts(chat);
3361
4903
  ui.input.value = draftForChat(chat);
3362
4904
  // A cached draft may be newer than the server draft after a fast switch.
3363
4905
  // Save it now, even if the user does not type again after reopening.
@@ -3369,7 +4911,6 @@
3369
4911
  }, 2600);
3370
4912
  }
3371
4913
  paintConversation(); connectEvents();
3372
- resumeFilterRequests();
3373
4914
  if (options.applyProviderDefaults || !chat.nativeSessionId) await applyProviderDefaults(chatId);
3374
4915
  // Let the server prepare the provider for the next message while the user types, after the
3375
4916
  // default model and effort are saved so the prepared runtime matches the first message. Best-effort:
@@ -3463,15 +5004,15 @@
3463
5004
  if (scopeChanged) { try { window.flolessLeftPane?.chatLinksChanged?.(); } catch { /* the card refreshes on its next read */ } }
3464
5005
  state.chat = null; state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
3465
5006
  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();
5007
+ state.filterCardMessages.clear();
3469
5008
  updateOffscreenActivity();
3470
5009
  state.historyFilter = 'all'; state.instructorAnswers = []; state.historyLoading = false; state.historyRequestGeneration += 1;
3471
5010
  closeHistoryPanel();
3472
- if (!scope?.owner) { showUnscoped(); return; }
5011
+ if (scopeChanged) state.displayUnits = null;
5012
+ if (!scope?.owner) { state.displayUnitsGeneration += 1; showUnscoped(); return; }
5013
+ void refreshDisplayUnits();
3473
5014
  ui.scope.textContent = scope.label;
3474
- ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
5015
+ ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : scope.owner.kind === 'workflow' ? 'Workflow conversation' : 'Workspace conversation';
3475
5016
  setBusy(true);
3476
5017
  try {
3477
5018
  await ensureSession();
@@ -3491,7 +5032,7 @@
3491
5032
  state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null;
3492
5033
  updateOffscreenActivity();
3493
5034
  ui.scope.textContent = scope.label;
3494
- ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
5035
+ ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : scope.owner.kind === 'workflow' ? 'Workflow conversation' : 'Workspace conversation';
3495
5036
  paintHistory(); paintUnread(); providerChooser();
3496
5037
  report(error, 'Could not load this conversation history');
3497
5038
  }
@@ -3509,18 +5050,131 @@
3509
5050
  await loadScope(next);
3510
5051
  }
3511
5052
 
5053
+ // The units of the project the person opened last (#1890), suggested to a new workspace conversation. Null when no
5054
+ // project was opened in this browser, or its units cannot be read: then the conversation suggests nothing.
5055
+ async function lastProjectUnits() {
5056
+ let projectId = null;
5057
+ try { projectId = localStorage.getItem('floless:last-project'); } catch { /* private mode: no suggestion */ }
5058
+ if (!projectId) return null;
5059
+ try {
5060
+ const body = await request(`/api/projects/${encodeURIComponent(projectId)}/display-units`);
5061
+ return body?.displayUnits === 'mm' || body?.displayUnits === 'ft-in' ? body.displayUnits : null;
5062
+ } catch { return null; }
5063
+ }
5064
+
5065
+ // The units question of a workspace conversation (#1890): asked until the person answers, then a quiet line to change
5066
+ // it. Never blocks Send — an unanswered question tells the AI the units are not chosen yet, and it asks.
5067
+ function paintWorkspaceUnits() {
5068
+ const host = ui.workspaceUnits;
5069
+ if (!host) return;
5070
+ const chat = state.chat;
5071
+ if (state.scope?.owner?.kind !== 'workspace' || !chat || chat.archivedAt) { host.hidden = true; host.replaceChildren(); delete host.dataset.painted; return; }
5072
+ // The receipts' units follow the conversation's own (chosen, else suggested) — set here, where the chat is known.
5073
+ state.displayUnits = workspaceUnitsOf(chat);
5074
+ const units = chat.workspaceUnits || {};
5075
+ const chosen = units.chosen === 'mm' || units.chosen === 'ft-in' ? units.chosen : null;
5076
+ const label = (value) => (value === 'mm' ? 'Metric (mm)' : 'ft-in');
5077
+ // Settings repaint on every chat event; rebuilding unchanged buttons would swap them out from under a click.
5078
+ const painted = `${chat.chatId}|${chosen}|${units.suggested ?? null}|${Boolean(state.workspaceUnitsEditing)}`;
5079
+ if (!host.hidden && host.dataset.painted === painted) return;
5080
+ host.dataset.painted = painted;
5081
+ host.hidden = false;
5082
+ host.replaceChildren();
5083
+ if (chosen && !state.workspaceUnitsEditing) {
5084
+ const text = document.createElement('span');
5085
+ text.className = 'ai-chat-units-current';
5086
+ text.textContent = `Units: ${label(chosen)}`;
5087
+ const change = document.createElement('button');
5088
+ change.type = 'button';
5089
+ change.className = 'ai-chat-units-change';
5090
+ change.textContent = 'Change';
5091
+ change.setAttribute('aria-label', 'Change units');
5092
+ change.dataset.commandId = 'shell.chat-units-change';
5093
+ change.dataset.tip = 'Choose the units AI answers in, in this conversation';
5094
+ change.addEventListener('click', () => { state.workspaceUnitsEditing = true; paintWorkspaceUnits(); host.querySelector('[role="radio"][aria-checked="true"], [role="radio"]')?.focus(); });
5095
+ host.append(text, change);
5096
+ return;
5097
+ }
5098
+ const question = document.createElement('span');
5099
+ question.className = 'ai-chat-units-question';
5100
+ question.id = 'chat-units-question';
5101
+ question.textContent = 'Which units should AI use here?';
5102
+ const group = document.createElement('div');
5103
+ group.className = 'ai-chat-units-options';
5104
+ group.setAttribute('role', 'radiogroup');
5105
+ group.setAttribute('aria-labelledby', 'chat-units-question');
5106
+ const suggested = units.suggested === 'mm' || units.suggested === 'ft-in' ? units.suggested : null;
5107
+ const options = ['ft-in', 'mm'];
5108
+ for (const value of options) {
5109
+ const option = document.createElement('button');
5110
+ option.type = 'button';
5111
+ option.className = 'ai-chat-units-option';
5112
+ option.setAttribute('role', 'radio');
5113
+ const checked = chosen ? chosen === value : suggested === value;
5114
+ option.setAttribute('aria-checked', String(Boolean(chosen && chosen === value)));
5115
+ option.tabIndex = checked || (!chosen && !suggested && value === 'ft-in') ? 0 : -1;
5116
+ option.dataset.commandId = `shell.chat-units-choose#${value}`;
5117
+ option.dataset.commandInstanceLabel = label(value);
5118
+ if (suggested === value && !chosen) option.classList.add('is-suggested');
5119
+ option.textContent = label(value);
5120
+ if (suggested === value && !chosen) {
5121
+ const hint = document.createElement('span');
5122
+ hint.className = 'ai-chat-units-hint';
5123
+ hint.textContent = ' · last project';
5124
+ option.append(hint);
5125
+ }
5126
+ option.addEventListener('click', () => { void chooseWorkspaceUnits(value); });
5127
+ option.addEventListener('keydown', (event) => {
5128
+ if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft' && event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
5129
+ event.preventDefault();
5130
+ const next = group.querySelectorAll('[role="radio"]')[value === 'ft-in' ? 1 : 0];
5131
+ next?.focus();
5132
+ });
5133
+ group.append(option);
5134
+ }
5135
+ host.append(question, group);
5136
+ }
5137
+
5138
+ async function chooseWorkspaceUnits(value) {
5139
+ const snapshot = captureChat();
5140
+ if (!snapshot) return;
5141
+ try {
5142
+ const updated = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/workspace-units`, {
5143
+ method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, units: value }),
5144
+ });
5145
+ if (!sameChat(snapshot)) return;
5146
+ state.chat = { ...state.chat, workspaceUnits: updated.workspaceUnits };
5147
+ state.workspaceUnitsEditing = false;
5148
+ paintWorkspaceUnits();
5149
+ void refreshDisplayUnits();
5150
+ announce(`Units set to ${value === 'mm' ? 'metric (millimetres)' : 'feet and inches'}.`);
5151
+ ui.workspaceUnits?.querySelector('.ai-chat-units-change')?.focus();
5152
+ } catch (error) {
5153
+ report(error, 'Could not save the units for this conversation');
5154
+ }
5155
+ }
5156
+
3512
5157
  async function createConversation(provider) {
3513
5158
  if (!state.scope || state.loading) return;
3514
5159
  clearProviderChoice();
3515
5160
  setBusy(true);
5161
+ // The owner is the one shown when the person chose a provider: a scope change while this runs must neither create
5162
+ // the conversation somewhere else nor paint it into, or unlock, the scope the person moved to.
5163
+ const owner = state.scope.owner;
5164
+ const generation = state.scopeGeneration;
3516
5165
  try {
5166
+ const displayUnitsSuggestion = owner.kind === 'workspace' ? await lastProjectUnits() : undefined;
5167
+ if (generation !== state.scopeGeneration) return;
3517
5168
  const chat = await request('/api/chat/conversations', {
3518
5169
  method: 'POST', body: JSON.stringify({
3519
- owner: state.scope.owner, provider, title: 'New chat',
5170
+ owner, provider, title: 'New chat',
3520
5171
  settings: { model: null, effort: null, permissionProfile: 'read-only' },
3521
5172
  initiator: { kind: 'user' },
5173
+ ...(displayUnitsSuggestion ? { displayUnitsSuggestion } : {}),
3522
5174
  }),
3523
5175
  });
5176
+ // Created where it was asked for; it is listed when that place is opened again.
5177
+ if (generation !== state.scopeGeneration) return;
3524
5178
  state.chats.unshift(chat);
3525
5179
  await selectConversation(chat.chatId, { focus: true, applyProviderDefaults: true, replaceProviderChoice: true, preserveDiscoveryDraft: true });
3526
5180
  if (state.discoveryDraft && state.chat?.chatId === chat.chatId) {
@@ -3533,9 +5187,10 @@
3533
5187
  state.pendingTeklaLibrary = null;
3534
5188
  paintTeklaChip();
3535
5189
  }
3536
- announce(`${providerLabels[provider]} conversation created.`);
5190
+ // A late announcement would name a conversation from the place the person already left.
5191
+ if (generation === state.scopeGeneration) announce(`${providerLabels[provider]} conversation created.`);
3537
5192
  } catch (error) { report(error, 'Could not start conversation'); }
3538
- finally { setBusy(false); }
5193
+ finally { if (generation === state.scopeGeneration) setBusy(false); }
3539
5194
  }
3540
5195
 
3541
5196
  async function refreshInstructorAnswers(focusFilter = false) {
@@ -3694,7 +5349,11 @@
3694
5349
  }
3695
5350
 
3696
5351
  function permissionChoices() {
3697
- return Object.entries(permissionLabels).map(([value, label]) => ({
5352
+ // #1890: from the workspace, AI Chat reads and answers; it changes files only from a project or workflow.
5353
+ const offered = state.scope?.owner?.kind === 'workspace'
5354
+ ? Object.entries(permissionLabels).filter(([value]) => value === 'read-only')
5355
+ : Object.entries(permissionLabels);
5356
+ return offered.map(([value, label]) => ({
3698
5357
  id: `permission:${value}`, label, meta: value === 'full-access' ? 'all local files' : value === 'workspace-write' ? 'project or workflow folder' : 'no file changes',
3699
5358
  selected: state.chat.settings.permissionProfile === value, patch: { permissionProfile: value },
3700
5359
  }));
@@ -3736,7 +5395,9 @@
3736
5395
  const lead = document.createElement('strong');
3737
5396
  const detail = document.createTextNode(state.chat?.integrationBindings?.length
3738
5397
  ? ' When you select a FloLess account, this chat uses it for that service instead of the account connected in Claude or Codex.'
3739
- : ' Claude or Codex uses its own connected accounts until you select a FloLess account here.');
5398
+ : state.chat?.settings?.useOwnConnectors === true
5399
+ ? ` Until you select a FloLess account here, ${providerLabels[state.chat.provider] || 'the AI'} uses your own connectors, and each call asks you first.`
5400
+ : ` Your own ${providerLabels[state.chat?.provider] || 'Claude or Codex'} connectors are off in this chat, so select a FloLess account to use a service.`);
3740
5401
  lead.textContent = state.chat?.integrationBindings?.length ? 'This chat will use the FloLess account you selected.' : 'Choose a connected account for this chat.';
3741
5402
  note.append(lead, detail); ui.picker.append(note);
3742
5403
  const rows = data?.rows || [];
@@ -3790,7 +5451,7 @@
3790
5451
  state.chat = chat;
3791
5452
  const index = state.chats.findIndex((item) => item.chatId === chatId); if (index >= 0) state.chats[index] = state.chat;
3792
5453
  await loadIntegrations(); paintSettings(); paintIntegrationPicker();
3793
- announce(row.selected ? `${row.label} now uses the account connected in Claude or Codex.` : `${integrationAccountLabel(row)} selected in FloLess.`);
5454
+ announce(row.selected ? `${row.label} is no longer selected for this chat.` : `${integrationAccountLabel(row)} selected in FloLess.`);
3794
5455
  } catch (error) { if (sameChat(snapshot)) { report(error, 'Could not change the connected account'); paintIntegrationPicker(); } }
3795
5456
  }
3796
5457
 
@@ -3803,24 +5464,18 @@
3803
5464
  const settingUp = Boolean(state.capability?.runtime && state.capability.runtime.state !== 'installed');
3804
5465
  const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
3805
5466
  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
5467
+ ui.send.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
3807
5468
  || (!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;
5469
+ // The paperclip is the same on every surface, the Drawing Filter included (#1681, #1859): a message
5470
+ // there carries the filter's context AND whatever the person attached, under the general rules only.
5471
+ ui.attach.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen;
3816
5472
  // Repainted here too: this runs on a surface switch, which changes what may be attached without
3817
5473
  // changing the attachments themselves.
3818
5474
  paintAttachControl();
3819
5475
  const unknownReason = state.followupUnknownId || hasUnknownFollowup()
3820
5476
  ? 'FloLess could not confirm a follow-up. Review that message before sending or attaching another file.' : null;
3821
5477
  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;
5478
+ ? 'FloLess is saving this message. Wait for its delivery status before sending another.' : null;
3824
5479
  for (const control of [ui.send, ui.attach]) {
3825
5480
  if (unknownReason || sendingReason) control.dataset.blockedReason = unknownReason || sendingReason;
3826
5481
  else delete control.dataset.blockedReason;
@@ -3970,40 +5625,19 @@
3970
5625
  ui.skills.hidden = false;
3971
5626
  }
3972
5627
 
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…';
5628
+ // ── Drawing Filter context and suggestions ─────────────────────────────────────────────────────
5629
+ // ONE AI CHAT (#1859). With the Drawing Filter open, a message is an ordinary turn or follow-up; the
5630
+ // open filter only adds a snapshot of the sheet and its selection (`filterContextForSend`), and the AI
5631
+ // may answer with a suggestion card (`floless_filter_propose`). The filter page (its iframe) owns the
5632
+ // drawing, the selection and every Apply / Undo / Keep guard; this chat only relays through
5633
+ // `window.__floFilterAi`. Drawing Filter questions and answers from before #1859 still render from
5634
+ // their events, read-only: the page that recorded their suggestions is gone, so they offer nothing.
3982
5635
  const FILTER_NOT_OPEN = 'Open Drawing Filter to use this suggestion.';
3983
5636
  // Mirrors the filter page's own FILTER_AI_UNKNOWN: with no page at all, its records are gone too.
3984
5637
  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
5638
  let filterBridgeWarned = false;
4001
5639
  let readCheckWarned = false;
4002
5640
 
4003
- function filterRefusal(message) {
4004
- return Object.assign(new Error(message), { filterRefusal: true });
4005
- }
4006
-
4007
5641
  /** A broken filter page is a bug worth one console line, not a silent "still loading" forever. */
4008
5642
  function warnFilterBridge(error) {
4009
5643
  if (filterBridgeWarned) return;
@@ -4012,9 +5646,8 @@
4012
5646
  }
4013
5647
 
4014
5648
  /**
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.
5649
+ * The Drawing Filter as the visible surface: 'off', 'loading' (the message goes without its context,
5650
+ * and says so), or 'ready' with the page's bridge. The page's own empty screen ('unavailable') is 'off'.
4018
5651
  */
4019
5652
  function filterSurface() {
4020
5653
  if (currentSurface() !== 'drawing-filter') return { state: 'off' };
@@ -4038,31 +5671,26 @@
4038
5671
  * a second wording here made the same box look like a different box on one screen, for a mode the
4039
5672
  * person did not choose and cannot see the edges of.
4040
5673
  *
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.)
5674
+ * There is no mode (#1859): Send never routes on this. What says the filter's selection goes with a
5675
+ * message is `paintFloLessContext`'s "Sharing with AI: Drawing Filter · sheet <sheet> and its
5676
+ * selection", directly under the box.
4051
5677
  *
4052
5678
  * 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.
5679
+ * bridge, summary }` — except when a drawing read is running in this conversation (#1776, #1857):
5680
+ * then `{ state: 'off', replyToRead: true, readWorking }`, even though the Drawing Filter IS open,
5681
+ * where `readWorking` says whether its turn is still running (the message is then a follow-up).
5682
+ * Callers that route or label a message must ask this, never `filterSurface()` directly.
4056
5683
  */
4057
5684
  function paintFilterComposer() {
4058
5685
  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 };
5686
+ // #1859: the read hints below say where a message goes on EVERY surface; the filter no longer routes.
5687
+ // #1776, #1857: a drawing read in THIS conversation is who the person is talking to, so the
5688
+ // composer says where a message goes — to the read, or to it as a follow-up while it is working:
5689
+ // the hint beside Send (`clearReport`, when no higher-priority notice holds it) and the context note
5690
+ // under the box (`paintFloLessContext`), which also feeds Send's tooltip.
5691
+ if (readAwaitingReply()) {
5692
+ return { ...surface, replyToRead: true, readWorking: turnIsVisiblyActive() };
5693
+ }
4066
5694
  return surface;
4067
5695
  }
4068
5696
 
@@ -4078,533 +5706,6 @@
4078
5706
  }
4079
5707
  }
4080
5708
 
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
5709
  function filterChangeLabel(item) {
4609
5710
  if (item.dimension === 'thickness') return `line weight ${item.value} pt`;
4610
5711
  return `${item.dimension} ${item.value}`;
@@ -4620,12 +5721,17 @@
4620
5721
  * No page at all (not opened since this window loaded, or reloading) means the page that recorded
4621
5722
  * the suggestion is gone, exactly like an unknown record.
4622
5723
  */
4623
- function inspectFilterSuggestion(requestId, proposal) {
5724
+ function inspectFilterSuggestion(requestId, proposal, base = null) {
4624
5725
  let bridge = null;
4625
5726
  try { bridge = document.getElementById('ws-frame-drawings')?.contentWindow?.__floFilterAi || null; }
4626
5727
  catch (error) { warnFilterBridge(error); }
4627
5728
  let info = null;
4628
- try { info = bridge ? bridge.inspect(requestId, proposal) : null; } catch (error) { warnFilterBridge(error); }
5729
+ try {
5730
+ // A suggestion the AI made through floless_filter_propose (#1859) carries its base in the server record, so
5731
+ // ANY page instance can check it — the page adopts that base rather than needing to have sent the message.
5732
+ if (bridge && base) bridge.adopt?.(requestId, base);
5733
+ info = bridge ? bridge.inspect(requestId, proposal) : null;
5734
+ } catch (error) { warnFilterBridge(error); }
4629
5735
  if (!info) return { known: false, applicable: false, reason: FILTER_PAGE_GONE, open: false };
4630
5736
  const open = filterSurface().state === 'ready';
4631
5737
  // An unknown record keeps its own reason: opening the Drawing Filter would not bring it back.
@@ -4648,13 +5754,24 @@
4648
5754
  const requestId = String(event.payload.requestId || '');
4649
5755
  const proposal = event.payload.filterAi.proposal;
4650
5756
  const hasChanges = proposal.changes.length > 0 || proposal.mode !== null;
4651
- const info = inspectFilterSuggestion(requestId, proposal);
5757
+ const server = event.payload.serverProposal ? serverProposalState(event.payload.serverProposal) : null;
5758
+ let info = inspectFilterSuggestion(requestId, proposal, server ? server.base : null);
5759
+ // The server record is the truth about what happened to a suggestion; the page only knows its own session.
5760
+ // An unsettled claim ('applying') wins even over the page's own "applied": the ticks may have changed, but the
5761
+ // outcome was never recorded, so the card must not say it was confirmed.
5762
+ if (server && server.disposition !== 'pending'
5763
+ && (server.disposition === 'applying' || !info.known || info.disposition === 'pending')) {
5764
+ info = { ...info, known: true, applicable: false, undo: false, disposition: server.disposition === 'applying' ? 'applying' : server.disposition,
5765
+ note: SERVER_PROPOSAL_NOTES[server.disposition] || server.reason || '' };
5766
+ if (server.disposition === 'stale') info.note = server.reason || SERVER_PROPOSAL_NOTES.stale;
5767
+ }
4652
5768
  const disposition = info.known ? info.disposition : 'pending';
4653
5769
  // An unknown record (reload, another window) claims no outcome, only that it predates this view.
4654
5770
  // "not saved" only while this suggestion's own Undo is live: Save and later edits retire it.
4655
5771
  const chip = card.querySelector('.ai-chat-filter-state');
4656
5772
  chip.textContent = !info.known ? 'from an earlier view' : {
4657
5773
  applied: info.undo ? 'applied, not saved' : 'applied', kept: 'not applied', undone: 'undone',
5774
+ applying: 'could not confirm', stale: 'no longer applies',
4658
5775
  }[disposition] || 'not applied';
4659
5776
  const status = card.querySelector('.ai-chat-filter-note');
4660
5777
  const override = state.filterCardMessages.get(requestId);
@@ -4689,6 +5806,7 @@
4689
5806
  }
4690
5807
 
4691
5808
  function runFilterSuggestionAction(action, event) {
5809
+ if (event.payload.serverProposal && action !== 'undo') { void runServerProposalAction(action, event); return; }
4692
5810
  const requestId = String(event.payload.requestId || '');
4693
5811
  // Re-resolve the page at click time: the frame may have reloaded since this card was painted.
4694
5812
  const surface = filterSurface();
@@ -4755,44 +5873,175 @@
4755
5873
  }
4756
5874
 
4757
5875
  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;
5876
+ // A Drawing Filter question from before #1859: the person's own words, like any message. Nothing
5877
+ // waits on it any more; its answer, if one was published, is its own event.
5878
+ return renderMessage(event, 'user', payloadText(event));
4775
5879
  }
4776
5880
 
4777
5881
  /** Re-read the live filter state for every visible suggestion card, in place. */
4778
5882
  function refreshFilterCards() {
4779
5883
  for (const card of ui.feed.querySelectorAll('.ai-chat-filter-card')) {
4780
5884
  const event = state.events.find((candidate) => candidate.eventId === card.dataset.eventId);
4781
- if (event?.payload?.filterAi?.proposal) paintFilterSuggestion(card, event);
5885
+ if (event?.type === 'filter-proposal') paintFilterSuggestion(card, serverProposalCardEvent(event));
5886
+ else if (event?.payload?.filterAi?.proposal) paintFilterSuggestion(card, event);
4782
5887
  }
4783
5888
  }
4784
5889
 
5890
+ /** What became of each suggestion, from the server's own record of it (#1859): later updates win. */
5891
+ const SERVER_PROPOSAL_NOTES = {
5892
+ applied: 'Applied. Undo is no longer available here. Change the ticks by hand if needed, and press Save filter to keep them.',
5893
+ applying: 'FloLess could not confirm whether this suggestion reached the Drawing Filter. Check the ticks on the drawing before you save.',
5894
+ kept: 'Kept your current selection. No changes were made.',
5895
+ stale: 'The Drawing Filter changed after this suggestion, so it was not applied. Ask again for a current one.',
5896
+ };
5897
+
5898
+ function serverProposalState(payload) {
5899
+ let disposition = payload.disposition || 'pending';
5900
+ let reason = payload.reason || null;
5901
+ for (const event of state.events) {
5902
+ if (event.type !== 'filter-proposal-update' || event.payload?.proposalId !== payload.proposalId) continue;
5903
+ disposition = event.payload.disposition || disposition;
5904
+ reason = event.payload.reason || null;
5905
+ }
5906
+ return { disposition, reason, base: payload.base };
5907
+ }
5908
+
5909
+ /** A `filter-proposal` event in the shape the suggestion card already paints. */
5910
+ function serverProposalCardEvent(event) {
5911
+ const payload = event.payload || {};
5912
+ return { ...event, payload: { requestId: `proposal:${payload.proposalId}`, serverProposal: payload,
5913
+ filterAi: { kind: 'change', proposal: { explanation: String(payload.explanation || ''), changes: Array.isArray(payload.changes) ? payload.changes : [],
5914
+ mode: payload.mode ?? null } } } };
5915
+ }
5916
+
5917
+ function renderServerProposal(event) {
5918
+ const shaped = serverProposalCardEvent(event);
5919
+ const card = renderFilterSuggestion(shaped);
5920
+ card.dataset.eventId = event.eventId;
5921
+ card.dataset.eventSequence = String(event.sequence);
5922
+ // The AI's own words go on the card as plain text, under its title.
5923
+ const why = document.createElement('p'); why.className = 'ai-chat-filter-why';
5924
+ why.textContent = shaped.payload.filterAi.proposal.explanation;
5925
+ card.querySelector('.ai-chat-filter-card-head')?.after(why);
5926
+ return card;
5927
+ }
5928
+
5929
+ /**
5930
+ * Apply or Keep a suggestion the AI made through floless_filter_propose (#1859). Apply CLAIMS it on the server
5931
+ * first, so a second click or another window can never apply it twice; the page then applies it to the
5932
+ * on-screen selection, and the outcome is settled. A claim that is never settled is never reopened.
5933
+ */
5934
+ async function runServerProposalAction(action, event) {
5935
+ const payload = event.payload.serverProposal;
5936
+ const requestId = String(event.payload.requestId || '');
5937
+ const snapshot = captureChat();
5938
+ if (!snapshot) return;
5939
+ const path = `/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/filter-proposals/${encodeURIComponent(payload.proposalId)}`;
5940
+ // Each step's update event comes back with it, so the card repaints from the server's record at once.
5941
+ const post = async (verb, body = {}) => {
5942
+ const result = await request(`${path}/${verb}`, { method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, ...body }) });
5943
+ if (sameChat(snapshot)) for (const item of result?.events || []) if (!state.events.some((known) => known.eventId === item.eventId)) state.events.push(item);
5944
+ return result;
5945
+ };
5946
+ let message;
5947
+ try {
5948
+ if (action === 'keep') {
5949
+ await post('keep');
5950
+ try { filterSurface().bridge?.keep?.(requestId); } catch (error) { warnFilterBridge(error); }
5951
+ message = SERVER_PROPOSAL_NOTES.kept;
5952
+ } else {
5953
+ const surface = filterSurface();
5954
+ if (surface.state !== 'ready') throw Object.assign(new Error(FILTER_NOT_OPEN), { plain: true });
5955
+ // Checked on the page BEFORE the claim, so a suggestion that no longer fits is never claimed.
5956
+ const check = surface.bridge.inspect(requestId, event.payload.filterAi.proposal);
5957
+ if (!check?.applicable) throw Object.assign(new Error(check?.reason || FILTER_NOT_OPEN), { plain: true });
5958
+ const opId = crypto.randomUUID();
5959
+ await post('claim', { opId });
5960
+ let result;
5961
+ try { result = surface.bridge.apply(requestId, event.payload.filterAi.proposal); }
5962
+ catch (error) {
5963
+ console.error('[chat] the Drawing Filter could not apply a suggestion:', error);
5964
+ result = null;
5965
+ }
5966
+ if (result?.ok) {
5967
+ await post('settle', { opId, outcome: 'applied' });
5968
+ message = result.message;
5969
+ } else {
5970
+ const reason = result?.message || 'The Drawing Filter could not apply this suggestion.';
5971
+ // Released only because the page refused at that instant; a thrown apply stays unconfirmed.
5972
+ if (result) await post('settle', { opId, outcome: 'released', reason });
5973
+ message = result ? reason : SERVER_PROPOSAL_NOTES.applying;
5974
+ }
5975
+ }
5976
+ state.filterCardMessages.delete(requestId);
5977
+ } catch (error) {
5978
+ message = error?.plain ? error.message
5979
+ : error?.code === 'chat-filter-proposal-used' || error?.status === 409 ? 'This suggestion was already used, so it was not applied again.'
5980
+ : 'FloLess could not record what happened to this suggestion. Check the Drawing Filter ticks before you save.';
5981
+ state.filterCardMessages.set(requestId, message);
5982
+ }
5983
+ if (!sameChat(snapshot)) return;
5984
+ announce(message);
5985
+ refreshFilterCards();
5986
+ const card = ui.feed.querySelector(`.ai-chat-filter-card[data-event-id="${CSS.escape(event.eventId)}"]`);
5987
+ (card?.querySelector('.ai-chat-filter-actions button') || card?.querySelector('.ai-chat-filter-note'))?.focus({ preventScroll: true });
5988
+ }
5989
+
5990
+ /** A message sent with the Drawing Filter open whose selection did not go with it says so under it (#1859). */
5991
+ function withFilterNotShared(item, event) {
5992
+ const reason = item ? state.filterNotShared?.get(event.clientSubmissionId) : null;
5993
+ if (!reason) return item;
5994
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-notice'; note.setAttribute('role', 'status');
5995
+ note.textContent = reason;
5996
+ item.append(note);
5997
+ return item;
5998
+ }
5999
+
6000
+ /**
6001
+ * What the open Drawing Filter adds to a message (#1859): a snapshot of the sheet on screen and its selection,
6002
+ * sent beside the message for the server to store and append. Never a reason not to send. While the filter is
6003
+ * still loading the message goes without it, and says so under the message (owner ruling 2026-10-02).
6004
+ */
6005
+ /** The most a filter snapshot may weigh on the wire: under the routes' 4 MiB allowance with room to spare. */
6006
+ const FILTER_SNAPSHOT_MAX_BYTES = 3 * 1024 * 1024;
6007
+
6008
+ function filterContextForSend() {
6009
+ const surface = filterSurface();
6010
+ if (surface.state === 'off') return { open: false, field: {} };
6011
+ if (surface.state !== 'ready') return { open: true, loading: true, field: {} };
6012
+ let snapshot = null;
6013
+ try { snapshot = surface.bridge.chatSnapshot?.() || null; } catch (error) { warnFilterBridge(error); snapshot = null; }
6014
+ if (!snapshot) return { open: true, loading: false, failed: true, field: {} };
6015
+ // Bounded on the wire, in bytes, so the message can never be refused for its size (#1859 review): a filter too
6016
+ // big to describe goes without its selection, and the message says so.
6017
+ let bytes = Infinity;
6018
+ try { bytes = new TextEncoder().encode(JSON.stringify(snapshot)).length; } catch { bytes = Infinity; }
6019
+ if (bytes > FILTER_SNAPSHOT_MAX_BYTES) return { open: true, tooLarge: true, field: {} };
6020
+ return { open: true, field: { filterSnapshot: snapshot } };
6021
+ }
6022
+
6023
+ /** Remember, per message, that the filter was open but its selection did not go with it — shown under the message. */
6024
+ function noteFilterContext(clientSubmissionId, sent, outcome) {
6025
+ if (!sent.open) return;
6026
+ // What happened, then what it means for the answer, then what to do — never an error: the message went.
6027
+ 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.'
6028
+ : sent.failed ? 'FloLess could not read the Drawing Filter, so the AI did not see its selection.'
6029
+ : sent.tooLarge ? 'The Drawing Filter has more than FloLess can send with one message, so the AI did not see its selection.'
6030
+ : outcome === 'not-shared' ? 'This message was too long to include the Drawing Filter selection. Shorten it and send again if the AI needs it.'
6031
+ : null;
6032
+ if (reason) state.filterNotShared.set(clientSubmissionId, reason);
6033
+ }
6034
+
4785
6035
  async function sendTurn() {
4786
6036
  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; }
6037
+ // ONE AI CHAT (#1859, owner ruling 2026-10-01/02): the open Drawing Filter never changes where a message goes.
6038
+ // It is a turn, or a follow-up to a running reply (a drawing read included), exactly as anywhere else; the
6039
+ // filter only adds its context (`filterContextForSend`) and the AI may answer with a suggestion card.
4792
6040
  // Decided once, at the click, from what the pill showed: a follow-up that falls back to a new turn below
4793
6041
  // must not attach objects the person was never shown (#1653).
4794
6042
  const subjects = subjectsPayload(composerSelection());
4795
6043
  const subjectsField = subjects ? { subjects } : {};
6044
+ const filterContext = filterContextForSend();
4796
6045
  if (turnIsVisiblyActive() && !state.chat.activeTurn?.local) {
4797
6046
  const followup = await sendFollowup();
4798
6047
  if (followup?.outcome !== 'turn-ended') return;
@@ -4834,10 +6083,14 @@
4834
6083
  // The server alone appends this context to the provider copy. The submitted text and
4835
6084
  // durable transcript must remain exactly what the user typed.
4836
6085
  owner: snapshot.scope.owner, clientSubmissionId, text, displayText: text, uiContext, attachmentIds,
4837
- modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField,
6086
+ modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField, ...filterContext.field,
4838
6087
  }),
4839
6088
  });
4840
- if (!sameChat(snapshot)) return void subjectLinksSaved(subjects);
6089
+ if (!sameChat(snapshot)) {
6090
+ noteFilterContext(clientSubmissionId, filterContext, result?.filterContext);
6091
+ return void subjectLinksSaved(subjects);
6092
+ }
6093
+ noteFilterContext(clientSubmissionId, filterContext, result?.filterContext);
4841
6094
  subjectLinksSaved(subjects);
4842
6095
  state.pendingSubmissionId = null;
4843
6096
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
@@ -4901,6 +6154,8 @@
4901
6154
  return;
4902
6155
  }
4903
6156
  const clientSubmissionId = crypto.randomUUID();
6157
+ // A steer to a running reply — a drawing read included — carries the open filter's context too (#1859).
6158
+ const filterContext = filterContextForSend();
4904
6159
  const previousAttachments = state.attachments;
4905
6160
  let failedDelivery = null;
4906
6161
  let outcome = null;
@@ -4925,9 +6180,10 @@
4925
6180
  const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups`, {
4926
6181
  method: 'POST', body: JSON.stringify({
4927
6182
  owner: snapshot.scope.owner, clientSubmissionId, text,
4928
- uiContext: currentFloLessContext(), attachmentIds,
6183
+ uiContext: currentFloLessContext(), attachmentIds, ...filterContext.field,
4929
6184
  }),
4930
6185
  });
6186
+ noteFilterContext(clientSubmissionId, filterContext, result?.filterContext);
4931
6187
  if (!sameChat(snapshot)) return;
4932
6188
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
4933
6189
  for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
@@ -5276,6 +6532,83 @@
5276
6532
  }
5277
6533
  }
5278
6534
 
6535
+ /** "IFC · tower.ifc", "Data · loads.csv", "PDF · notes.pdf" — the same words on the composer chip and the sent tile. */
6536
+ function attachmentLabel(attachment) {
6537
+ return `${ATTACHMENT_KIND_LABELS[attachment.mediaType] || 'File'} · ${attachment.fileName}`;
6538
+ }
6539
+
6540
+ /**
6541
+ * The cut a large data file gets, said on its chip, or ''. Measured in bytes because that is what a
6542
+ * stored attachment records; a UTF-8 file never has more characters than bytes, so a file at or under
6543
+ * the limit is always read whole, and "up to" keeps the sentence true for one just over it.
6544
+ */
6545
+ function dataCutTip(attachment) {
6546
+ if (!DATA_TYPES.has(attachment.mediaType) || (attachment.bytes || 0) <= MAX_DATA_TEXT_CHARS) return '';
6547
+ return 'Large file. The AI reads up to its first 16,000 characters.';
6548
+ }
6549
+
6550
+ /**
6551
+ * Can FloLess read this data file, and what is it? The browser-side twin of server/attachment-text.ts
6552
+ * (isDwg + sniffTextKind), run on the WHOLE file before anything in the batch uploads, so a refused
6553
+ * file never reaches the server (#1853). A parity test runs both over the same fixtures.
6554
+ * Returns 'dwg', 'ifc', 'dxf', 'text', or null for a file that is not readable text.
6555
+ */
6556
+ function sniffDataFile(bytes) {
6557
+ // A DWG is named only when the file is not text: a CSV may begin "AC1234,…" (isDwg).
6558
+ const dwg = bytes.length >= 6 && bytes[0] === 0x41 && bytes[1] === 0x43
6559
+ && [2, 3, 4, 5].every((i) => bytes[i] >= 0x30 && bytes[i] <= 0x39);
6560
+ const kind = sniffTextBytes(bytes);
6561
+ return kind || (dwg ? 'dwg' : null);
6562
+ }
6563
+
6564
+ /** The text half of sniffDataFile: 'ifc', 'dxf', 'text', or null (server/attachment-text.ts sniffTextKind). */
6565
+ function sniffTextBytes(bytes) {
6566
+ if (!bytes.length || bytes.includes(0)) return null;
6567
+ let printable = 0;
6568
+ for (const byte of bytes) {
6569
+ if (byte === 0x09 || byte === 0x0a || byte === 0x0d || (byte >= 0x20 && byte !== 0x7f)) printable++;
6570
+ }
6571
+ if (printable / bytes.length <= 0.9) return null;
6572
+ let utf8 = true;
6573
+ try { new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { utf8 = false; }
6574
+ if (!utf8 && bytes.filter((byte) => byte >= 0x80).length / bytes.length > 0.3) return null;
6575
+ let head = '';
6576
+ for (const byte of bytes.subarray(0, 512)) head += String.fromCharCode(byte);
6577
+ if (head.startsWith('ISO-10303-21')) return 'ifc';
6578
+ if (/^\s*0\s*[\r\n]+\s*SECTION/.test(head)) return 'dxf';
6579
+ return 'text';
6580
+ }
6581
+
6582
+ /**
6583
+ * Why a file chosen for AI Chat cannot be attached, in the server's own words (unreadableSentence), or
6584
+ * null. `attachFiles` asks this of every data file in a batch before the first upload, so a refused
6585
+ * file leaves nothing behind (#1853). The whole file is read here; one that can no longer be read
6586
+ * (moved or locked since it was chosen) is refused plainly too.
6587
+ */
6588
+ async function dataFileRefusal(file) {
6589
+ let kind;
6590
+ try { kind = sniffDataFile(new Uint8Array(await file.arrayBuffer())); }
6591
+ catch (error) {
6592
+ console.warn('[ai-chat] a chosen file could not be read', error);
6593
+ return `“${file.name}” could not be read. Check that the file is still there, then attach it again. Nothing was attached.`;
6594
+ }
6595
+ 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.`;
6596
+ if (kind) return null;
6597
+ if (String(file.type || '').startsWith('image/')) {
6598
+ 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.`;
6599
+ }
6600
+ 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.`;
6601
+ }
6602
+
6603
+ /**
6604
+ * An error whose message is already the whole plain sentence the person should read. Without the mark
6605
+ * errorMessage() replaces an unrecognised message with "FloLess could not complete this chat action",
6606
+ * which is how the attachment limits below used to say nothing useful.
6607
+ */
6608
+ function plainError(sentence) {
6609
+ return Object.assign(new Error(sentence), { plainSentence: true });
6610
+ }
6611
+
5279
6612
  function fileBase64(file) {
5280
6613
  return new Promise((resolve, reject) => {
5281
6614
  const reader = new FileReader();
@@ -5285,30 +6618,6 @@
5285
6618
  });
5286
6619
  }
5287
6620
 
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
6621
  async function attachFiles(files) {
5313
6622
  if (!state.chat || state.chat.activeTurn?.local || state.chat.state === 'recovery' || state.followupSubmitting || state.followupUnknownId || hasUnknownFollowup()) return;
5314
6623
  const snapshot = captureChat();
@@ -5318,31 +6627,38 @@
5318
6627
  // Reset the native chooser even when validation rejects this batch. After the user removes
5319
6628
  // an image, selecting that same file again must fire a fresh change event.
5320
6629
  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; }
6630
+ const isData = (file) => !allowedTypes.has(file.type);
5324
6631
  const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length
5325
- + incoming.filter((file) => file.type.startsWith('image/')).length;
6632
+ + incoming.filter((file) => !isData(file) && file.type.startsWith('image/')).length;
5326
6633
  if (imageCount > MAX_IMAGES_PER_MESSAGE) {
5327
6634
  state.imageLimitChatId = snapshot.chatId;
5328
6635
  report({ code: 'chat-message-image-limit' });
5329
6636
  return;
5330
6637
  }
5331
6638
  state.imageLimitChatId = null;
6639
+ if (state.attachments.filter((attachment) => DATA_TYPES.has(attachment.mediaType)).length
6640
+ + incoming.filter(isData).length > MAX_DATA_FILES_PER_MESSAGE) { report({ code: 'chat-message-data-limit' }); return; }
5332
6641
  const known = [...new Map([...(state.chat.attachments || []), ...state.attachments]
5333
6642
  .map((attachment) => [attachment.attachmentId, attachment])).values()];
5334
6643
  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; }
6644
+ if (known.length + incoming.length > 10) { report(plainError('You can attach up to 10 files to this conversation. Remove one, then try again.')); return; }
6645
+ if (incoming.some((file) => file.size > 20 * MB)) { report(plainError('Each attachment must be 20 MB or smaller. Nothing was attached.')); return; }
6646
+ 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
6647
  state.uploadingChatIds.add(snapshot.chatId);
5339
6648
  updateSendState();
5340
6649
  try {
6650
+ for (const file of incoming.filter(isData)) {
6651
+ const refusal = await dataFileRefusal(file);
6652
+ if (!sameChat(snapshot)) return;
6653
+ if (refusal) { report(plainError(refusal)); return; }
6654
+ }
5341
6655
  for (const file of incoming) {
5342
6656
  const data = await fileBase64(file);
5343
6657
  if (!sameChat(snapshot)) return;
6658
+ // A data file goes up as text/plain; the server reads its bytes again and decides what it is.
6659
+ const mediaType = isData(file) ? 'text/plain' : file.type;
5344
6660
  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 }),
6661
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, fileName: file.name, mediaType, data }),
5346
6662
  });
5347
6663
  if (!sameChat(snapshot)) return;
5348
6664
  state.attachments.push(attachment);
@@ -5544,6 +6860,9 @@
5544
6860
  if (typeof options.projectId === 'string' && (state.scope.owner.kind !== 'project' || state.scope.owner.projectId !== options.projectId)) {
5545
6861
  throw new Error('Open this project in Workspaces to see that conversation.');
5546
6862
  }
6863
+ if (typeof options.ownerKey === 'string' && scopeKey(state.scope) !== options.ownerKey) {
6864
+ throw new Error('Open the project or workflow this conversation belongs to, then choose Show in chat again.');
6865
+ }
5547
6866
  window.flolessBridge?.revealAiChat?.();
5548
6867
  ui.tab.click();
5549
6868
  const listed = await request(`/api/chat/conversations?${ownerQuery()}`);
@@ -5684,6 +7003,94 @@
5684
7003
  }
5685
7004
 
5686
7005
  // Ends this chat's standing Tekla read allowance. Nothing to confirm: it only removes permission.
7006
+ // #1907: the connectors allowed for this conversation, each with its own Revoke. Repainted only when the list changes,
7007
+ // so a click is never swapped out from under the pointer.
7008
+ function paintConnectorAllowance() {
7009
+ const host = ui.connectors;
7010
+ if (!host) return;
7011
+ const chat = state.chat;
7012
+ // #1907: the line exists only while this chat's own connectors are on; with them off, nothing can call.
7013
+ const on = Boolean(chat && !chat.archivedAt && chat.settings?.useOwnConnectors === true && !chat.integrationBindings?.length);
7014
+ const allowed = on && Array.isArray(chat.connectorAllowance?.allowed) ? chat.connectorAllowance.allowed : [];
7015
+ const busy = Boolean(chat?.activeTurn) || state.ownConnectorsSaving === true;
7016
+ const painted = `${chat?.chatId || ''}|${on}|${busy}|${chat?.provider || ''}|${allowed.map(connectorKey).join(',')}|${state.connectorRevoking || ''}`;
7017
+ if (host.dataset.painted === painted) return;
7018
+ host.dataset.painted = painted;
7019
+ host.replaceChildren();
7020
+ host.hidden = !on;
7021
+ if (!on) return;
7022
+ const provider = providerLabels[chat.provider] || 'Claude or Codex';
7023
+ const status = document.createElement('span');
7024
+ status.className = 'ai-chat-connectors-status';
7025
+ status.textContent = `Your ${provider} connectors are on`;
7026
+ const off = button('Turn off', 'shell.chat-own-connectors-off', 'ai-chat-units-change');
7027
+ off.setAttribute('aria-label', `Turn off your ${provider} connectors for this chat`);
7028
+ off.disabled = busy;
7029
+ const offBlocked = busy ? 'Wait for the current AI reply to finish before changing this.' : '';
7030
+ off.dataset.tip = offBlocked || 'The AI stops using your own connectors in this chat. You can turn them on again in chat settings.';
7031
+ if (offBlocked) off.dataset.blockedReason = offBlocked;
7032
+ off.addEventListener('click', () => { void turnOffOwnConnectors(); });
7033
+ host.append(status, off);
7034
+ if (!allowed.length) return;
7035
+ const title = document.createElement('span');
7036
+ title.className = 'ai-chat-connectors-title';
7037
+ title.textContent = 'Allowed for this chat:';
7038
+ host.append(title);
7039
+ for (const entry of allowed) {
7040
+ const pill = document.createElement('span');
7041
+ pill.className = 'ai-chat-connector-pill';
7042
+ const name = document.createElement('span');
7043
+ name.textContent = connectorLabel(entry);
7044
+ const key = connectorKey(entry);
7045
+ const revoke = button('Revoke', `shell.chat-connector-allowance-revoke#${key}`, 'ai-chat-connector-revoke');
7046
+ revoke.dataset.commandInstanceLabel = connectorLabel(entry);
7047
+ revoke.setAttribute('aria-label', `Revoke ${connectorLabel(entry)} for this chat`);
7048
+ revoke.dataset.tip = `${connectorLabel(entry)} will ask you again before it runs in this chat.`;
7049
+ revoke.disabled = state.connectorRevoking === key;
7050
+ revoke.addEventListener('click', () => { void revokeConnectorAllowance(entry); });
7051
+ pill.append(name, revoke);
7052
+ host.append(pill);
7053
+ }
7054
+ }
7055
+
7056
+ async function turnOffOwnConnectors() {
7057
+ state.ownConnectorsSaving = true;
7058
+ paintConnectorAllowance();
7059
+ try { await setOwnConnectors(false, { focusInput: true }); }
7060
+ finally { state.ownConnectorsSaving = false; paintConnectorAllowance(); }
7061
+ }
7062
+
7063
+ async function revokeConnectorAllowance(entry) {
7064
+ const snapshot = captureChat();
7065
+ if (!snapshot) return;
7066
+ const key = connectorKey(entry);
7067
+ state.connectorRevoking = key;
7068
+ paintConnectorAllowance();
7069
+ try {
7070
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/connector-allowance/revoke`, {
7071
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, connector: { provider: entry.provider, server: entry.server, app: entry.app ?? null } }),
7072
+ });
7073
+ if (!sameChat(snapshot)) return;
7074
+ // Only the server's own record, without that connector, may say it ended.
7075
+ const updated = result?.chat;
7076
+ if (!updated || updated.chatId !== snapshot.chatId || (updated.connectorAllowance?.allowed || []).some((row) => connectorKey(row) === key)) {
7077
+ report(new Error('FloLess could not confirm that this connector will ask again. Choose Revoke again.'), 'Could not revoke');
7078
+ return;
7079
+ }
7080
+ state.chat = { ...state.chat, connectorAllowance: updated.connectorAllowance };
7081
+ announce(`${connectorLabel(entry)} will ask you again in this chat.`);
7082
+ state.connectorRevoking = null;
7083
+ paintConnectorAllowance();
7084
+ // The pressed Revoke is gone with its pill: keep keyboard focus on the next one, or on the message box.
7085
+ (ui.connectors?.querySelector('.ai-chat-connector-revoke') || ui.input)?.focus();
7086
+ } catch (error) {
7087
+ if (sameChat(snapshot)) report(error, 'Could not revoke');
7088
+ } finally {
7089
+ if (state.connectorRevoking === key) state.connectorRevoking = null;
7090
+ paintConnectorAllowance();
7091
+ }
7092
+ }
7093
+
5687
7094
  async function revokeTeklaAllowance() {
5688
7095
  const chat = state.chat;
5689
7096
  const snapshot = captureChat();
@@ -5837,6 +7244,8 @@
5837
7244
  updateOffscreenActivity();
5838
7245
  // The left chat's library chip ("added to this chat") must not linger over the chooser.
5839
7246
  paintTeklaChip();
7247
+ // Nor the left chat's "connectors are on" line and its allowances (#1907).
7248
+ paintConnectorAllowance();
5840
7249
  }
5841
7250
 
5842
7251
  // Graft receipt → unsent Chat draft. Opening performs no binding, sends nothing and never
@@ -5937,6 +7346,11 @@
5937
7346
  ui.switchAccount.addEventListener('click', () => { void switchAccount(); });
5938
7347
  ui.effort.addEventListener('click', () => openPicker('effort', ui.effort, effortChoices()));
5939
7348
  ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
7349
+ ui.ownConnectors?.addEventListener('click', () => {
7350
+ if (ui.ownConnectors.disabled || !state.chat) return;
7351
+ closePicker();
7352
+ void setOwnConnectors(state.chat.settings?.useOwnConnectors !== true);
7353
+ });
5940
7354
  ui.integrations.addEventListener('click', openIntegrations);
5941
7355
  ui.send.addEventListener('click', sendTurn);
5942
7356
  // The Drawing Filter page reports every change that can alter what the chat shows about it.
@@ -5974,11 +7388,28 @@
5974
7388
  if (!ui.picker.hidden && !ui.picker.contains(event.target)
5975
7389
  && (!event.target.closest('.ai-chat-setting') || event.target.closest('.ai-chat-provider-switch'))) closePicker();
5976
7390
  });
7391
+ // A units change — in a model view, a workflow's Units control, another tab or the terminal AI — repaints the receipts
7392
+ // and is what the next message is answered in. The event only says something changed; the server says what.
7393
+ window.addEventListener('floless:display-units-changed', () => { void refreshDisplayUnits(); });
7394
+ // #1890: every workspace has the same owner name, so a change of Workspace directory is what moves a workspace
7395
+ // conversation's history; reload it, or the open chat would keep pointing at the previous directory.
7396
+ let workspaceRootKey = null;
7397
+ window.addEventListener('floless:workspace-root-state', (event) => {
7398
+ const root = event.detail?.root || null;
7399
+ const key = root ? `${root.rootId ?? ''}|${root.generation ?? ''}|${root.path ?? ''}` : '';
7400
+ const changed = workspaceRootKey !== null && key !== workspaceRootKey;
7401
+ workspaceRootKey = key;
7402
+ if (changed && state.scope?.owner?.kind === 'workspace') { state.choosingProvider = false; void loadScope({ ...state.scope }); }
7403
+ });
5977
7404
  window.addEventListener('floless:chat-scope-changed', (event) => {
5978
7405
  const next = event.detail || null;
5979
7406
  // The workspace emits repeated scope notifications while its iframe finishes loading. A
5980
7407
  // same-scope notification must not reselect the first stored chat over a provider picker.
5981
- if (scopeKey(next) === scopeKey(state.scope)) { refreshActivity(); return; }
7408
+ if (scopeKey(next) === scopeKey(state.scope)) {
7409
+ // #1890: one workspace conversation spans the landings and every installed workflow; only its label moves.
7410
+ if (next?.label && state.scope && next.label !== state.scope.label) { state.scope = { ...state.scope, label: next.label }; ui.scope.textContent = next.label; }
7411
+ refreshActivity(); return;
7412
+ }
5982
7413
  loadScope(next);
5983
7414
  });
5984
7415
  document.addEventListener('click', () => queueMicrotask(paintFloLessContext));