@floless/app 0.140.0 → 0.141.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/web/chat.js CHANGED
@@ -11,27 +11,51 @@
11
11
  settings: el('chat-settings'), provider: el('chat-provider'), switchAccount: el('chat-switch-account'), model: el('chat-model'),
12
12
  effort: el('chat-effort'), permission: el('chat-permission'), integrations: el('chat-integrations'),
13
13
  desktopValue: el('chat-desktop-value'), desktopReason: el('chat-desktop-reason'), picker: el('chat-picker'),
14
- feed: el('chat-feed'), recovery: el('chat-recovery'), recoveryCopy: el('chat-recovery-copy'),
14
+ feed: el('chat-feed'), offscreenActivity: el('chat-offscreen-activity'), recovery: el('chat-recovery'),
15
+ approvalTray: el('chat-approval-tray'), recoveryCopy: el('chat-recovery-copy'),
15
16
  reconcile: el('chat-reconcile'), recoveryStop: el('chat-recovery-stop'), attachments: el('chat-attachments'), skills: el('chat-skills'),
16
17
  composer: el('chat-composer'), input: el('chat-input'), file: el('chat-file'), attach: el('chat-attach'),
17
18
  hint: el('chat-compose-hint'), contextNote: el('chat-compose-context'), stop: el('chat-stop'), send: el('chat-send'), status: el('chat-status'),
19
+ disclosure: el('chat-composer-disclosure'),
18
20
  unread: el('chat-unread'), tab: el('narrative-tab'),
19
21
  context: el('left-chat-context'),
22
+ teklaChip: el('chat-tekla-context'),
20
23
  };
21
24
 
22
25
  const state = {
23
26
  // signInPending is keyed by provider: a wait started in one conversation must not paint an
24
27
  // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
25
28
  sessionReady: false, scope: null, chats: [], archivedChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
26
- source: null, eventReconnectTimer: null, eventReconnectAttempt: 0, eventReconnectChatId: null, attachments: [], integrations: null, historyOpen: false, historyFilter: 'all', archivedHistoryOpen: false,
29
+ 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, historyFilter: 'all', archivedHistoryOpen: false,
27
30
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
28
- draftTimer: null, refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, choosingProvider: false,
31
+ draftTimer: null, localDraft: null, backgroundDrafts: new Map(), draftWrites: new Map(), draftVersions: new Map(), unknownFollowups: new Map(), refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, choosingProvider: false,
29
32
  answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
30
33
  stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(), revokingApprovalTurns: new Set(), uploadingChatIds: new Set(),
31
34
  // Latched so the 5 s account poll logs an outage once instead of twelve times a minute; cleared
32
35
  // on the next successful read, so a later, separate outage is logged too.
33
36
  accountReadWarned: false,
37
+ // Drawing Filter requests sent from this composer: those still waiting for an answer (each checked
38
+ // on its own timer), failure notices and the last card refusal, keyed by request.
39
+ filterPending: new Map(), filterNotices: new Map(), filterCardMessages: new Map(),
40
+ filterSending: false,
41
+ // A Tekla model library carried over from a Graft receipt but not yet bound to its chat. It is
42
+ // browser-only until Send: opening, editing or removing it never calls the binding route.
43
+ // pendingTeklaLibrary waits for the provider chooser to create the chat it belongs to.
44
+ teklaDraft: null, pendingTeklaLibrary: null, teklaRemoveError: null,
34
45
  };
46
+ // A short-window resize can shrink the bounded tray after a decision card was painted.
47
+ // Keep its actions in view only while the reader was already at the bottom; preserve a
48
+ // deliberate scroll up to inspect the request-wide grant notice.
49
+ function keepApprovalTrayDecisionVisible(tray) {
50
+ let atBottom = true;
51
+ tray.addEventListener('scroll', () => {
52
+ atBottom = tray.scrollTop + tray.clientHeight >= tray.scrollHeight - 2;
53
+ });
54
+ new ResizeObserver(() => {
55
+ if (atBottom) tray.scrollTop = tray.scrollHeight;
56
+ }).observe(tray);
57
+ }
58
+ keepApprovalTrayDecisionVisible(ui.approvalTray);
35
59
  const permissionLabels = {
36
60
  'read-only': 'Read only', 'workspace-write': 'Working folder write', 'full-access': 'Full access',
37
61
  };
@@ -49,6 +73,7 @@
49
73
  const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question' };
50
74
  const requestStatusLabels = { pending: 'Queued', queued: 'Queued', running: 'Running', ready: 'Ready', completed: 'Complete', failed: 'Failed', stopped: 'Stopped' };
51
75
  const allowedTypes = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
76
+ const MAX_IMAGES_PER_MESSAGE = 5;
52
77
  const MB = 1024 * 1024;
53
78
 
54
79
  function ownerQuery(owner = state.scope?.owner) {
@@ -84,6 +109,8 @@
84
109
  if (!response.ok) {
85
110
  const error = new Error(body?.error || body || `Chat request failed (${response.status})`);
86
111
  error.code = body?.code || null;
112
+ error.reason = body?.reason || null;
113
+ error.status = response.status;
87
114
  throw error;
88
115
  }
89
116
  return body;
@@ -112,16 +139,37 @@
112
139
  ui.send.disabled = busy || uploading || !state.chat || blocked
113
140
  || (!ui.input.value.trim() && state.attachments.length === 0) || Boolean(state.chat?.activeTurn);
114
141
  ui.attach.disabled = busy || uploading || !state.chat || blocked || Boolean(state.chat?.activeTurn);
142
+ if (!busy) updateSendState();
115
143
  }
116
144
 
117
145
  function errorMessage(error) {
146
+ // A Drawing Filter refusal is already a complete plain-English sentence written for this moment.
147
+ if (error?.filterRefusal) return error.message;
118
148
  const raw = error instanceof Error ? error.message : String(error);
149
+ if (raw === 'This message was not sent because its queued response was cancelled') {
150
+ return 'You stopped the response before AI could take this queued message. Use Retry sending if you still want to send it.';
151
+ }
152
+ if (raw === 'This message was not sent because FloLess could not start its AI response') {
153
+ return 'FloLess could not start this queued AI response, so the message was not sent. Wait a moment, then use Retry sending.';
154
+ }
119
155
  const code = String(error && error.code || '');
120
156
  const codeMessages = {
121
157
  'chat-origin-refused': 'This chat can only be used from the FloLess app. Reload the page and try again.',
122
158
  'chat-owner-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
123
159
  'chat-cwd-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
124
- 'chat-turn-stale': 'This response is no longer active. Refresh the conversation before trying again.',
160
+ 'chat-turn-stale': 'This AI response just finished. Your draft is still here; press Send again to start a new response.',
161
+ 'chat-followup-refused': 'FloLess could not save or start this message, so AI did not receive it. Your draft is still here; try sending again.',
162
+ 'chat-followup-save-failed': 'FloLess could not save this message, so AI did not receive it. Your draft is still here; check that the project folder is available, then try sending again.',
163
+ 'chat-followup-queued': 'An earlier message is waiting for AI. Wait for it to send before starting another response.',
164
+ 'chat-followup-unconfirmed': 'Waiting to confirm your earlier message before starting another response. Review its delivery status in this conversation.',
165
+ 'chat-message-too-long': 'This message is too long. Shorten it, then send it again.',
166
+ 'chat-followup-too-large': 'This message is too long. Shorten it, then send it again.',
167
+ 'chat-followup-unknown': 'FloLess could not confirm delivery of this message. Check the AI response, then use Continue without resending if you want to proceed.',
168
+ 'chat-followup-retry-wait': 'This message can be retried after the current AI response finishes.',
169
+ 'chat-followup-retry-unavailable': 'FloLess can only retry a message confirmed as not sent. Review the conversation and write a new message if needed.',
170
+ 'chat-followup-not-unknown': 'This message’s delivery status changed while you were reviewing it. Refresh the conversation before deciding what to do.',
171
+ 'chat-followup-not-found': 'This message is no longer in this conversation. Refresh the conversation.',
172
+ 'chat-attachment-scope': 'An attached file is no longer available to this message. Add the file again in a new message.',
125
173
  'chat-initiator-unknown': 'FloLess could not identify what started this conversation. Reload the conversation and try again.',
126
174
  'chat-record-unsafe': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
127
175
  'chat-record-invalid': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
@@ -132,6 +180,7 @@
132
180
  'chat-owner-archived': 'This project or workflow is archived. Restore it before continuing the conversation.',
133
181
  'chat-archived': 'This conversation is archived. Start a new conversation to continue.',
134
182
  'chat-turn-active': 'Stop the active response before changing this conversation.',
183
+ 'chat-message-image-limit': 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.',
135
184
  'chat-send-refused': 'The AI service did not accept this message. Check your sign-in and conversation settings, then try again.',
136
185
  'chat-approval-stale': 'This approval is no longer active. Refresh the conversation.',
137
186
  'chat-provider-identity-changed': 'The connected AI account changed while this response was running. Refresh the conversation and try again.',
@@ -156,8 +205,16 @@
156
205
  'request-chat-not-ready': 'This request is still being prepared. Wait a moment, then try again.',
157
206
  'chat-knowledge-unscoped': 'Knowledge is available only inside a project conversation. Open a project and try again.',
158
207
  'chat-knowledge-page-missing': 'That Knowledge page is no longer available in this project. Refresh the conversation.',
208
+ 'approval-explicit-only': 'This read needs its own approval. Choose Approve once or Deny.',
159
209
  };
210
+ if (code === 'chat-followup-refused' && error?.reason === 'chat-session-required') {
211
+ return 'Your FloLess session expired before this message was sent. Copy the draft, reload, then paste and send it again.';
212
+ }
213
+ if (code === 'chat-followup-refused' && codeMessages[String(error?.reason || '')]) {
214
+ return codeMessages[String(error.reason)];
215
+ }
160
216
  if (codeMessages[code]) return codeMessages[code];
217
+ if (error?.status === 413) return 'This message is too large to send. Shorten it, then try again.';
161
218
  if (code === 'request-chat-owner-mismatch' || /request chat link belongs to another owner/i.test(raw)) {
162
219
  return 'This request is linked to another project or workflow. Open the project or workflow shown on the request, then try again.';
163
220
  }
@@ -265,6 +322,11 @@
265
322
  ui.hint.classList.remove('error');
266
323
  const message = requestExecutionBlocked()
267
324
  ? 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.'
325
+ : state.followupUnknownId || hasUnknownFollowup()
326
+ ? 'FloLess could not confirm this message. Check its status and use the action beside it before sending again.'
327
+ : state.imageLimitChatId === state.chat?.chatId
328
+ && state.attachments.filter(attachment => attachment.mediaType.startsWith('image/')).length >= MAX_IMAGES_PER_MESSAGE
329
+ ? 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.'
268
330
  : state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
269
331
  ? runtimeNotice(state.chat.provider, state.capability.runtime).body
270
332
  : state.chat && !providerReady()
@@ -274,10 +336,11 @@
274
336
  : !state.scope?.owner
275
337
  ? 'Open a project or workflow to start chatting.'
276
338
  : 'Enter to send · Shift+Enter for a new line';
277
- if (turnIsVisiblyActive()) {
278
- ui.hint.replaceChildren();
339
+ if (turnIsVisiblyActive() && !state.followupUnknownId && !hasUnknownFollowup()
340
+ && state.imageLimitChatId !== state.chat?.chatId) {
341
+ ui.hint.textContent = 'AI is working · send a follow-up without stopping';
279
342
  ui.hint.classList.remove('working');
280
- ui.hint.setAttribute('aria-label', 'AI is working');
343
+ ui.hint.removeAttribute('aria-label');
281
344
  } else {
282
345
  ui.hint.classList.remove('working');
283
346
  ui.hint.removeAttribute('aria-label');
@@ -303,7 +366,11 @@
303
366
  && capabilityAnswer(state.capability).state !== 'signed-out');
304
367
  }
305
368
 
306
- function currentFloLessContext() {
369
+ function currentSurface() {
370
+ return currentFloLessContext({ surfaceOnly: true }).surface;
371
+ }
372
+
373
+ function currentFloLessContext(options = {}) {
307
374
  const workspaceMode = document.querySelector('#mode-switch [data-mode="workspaces"]')?.getAttribute('aria-selected') === 'true';
308
375
  const workflowMode = document.querySelector('#mode-switch [data-mode="workflows"]')?.getAttribute('aria-selected') === 'true';
309
376
  const reportOpen = document.getElementById('report-modal')?.classList.contains('show') === true;
@@ -322,6 +389,7 @@
322
389
  : editorOpen ? 'model-editor'
323
390
  : workspaceMode ? (workspaceProjectOpen ? workspaceSurface : 'project-list')
324
391
  : dashboardVisible ? 'dashboard' : 'workflow-canvas';
392
+ if (options.surfaceOnly) return { surface };
325
393
  return {
326
394
  mode: workspaceMode ? 'workspaces' : workflowMode ? 'workflows' : 'canvas',
327
395
  surface,
@@ -376,11 +444,23 @@
376
444
 
377
445
  function paintFloLessContext() {
378
446
  if (!ui.contextNote) return;
379
- const context = currentFloLessContext();
380
- ui.contextNote.replaceChildren();
381
- const prefix = document.createElement('strong');
382
- prefix.textContent = 'Sharing with AI: ';
383
- ui.contextNote.append(prefix, document.createTextNode(floLessContextLabel(context)));
447
+ const filter = paintFilterComposer();
448
+ // A Drawing Filter message sends a bounded description of this sheet's controls and text, not
449
+ // the visible page, and says so rather than implying AI sees the whole drawing. This note is also
450
+ // the composer's only mention of which sheet a Drawing Filter message is about.
451
+ const shared = filter.state === 'off'
452
+ ? floLessContextLabel(currentFloLessContext())
453
+ : filter.state === 'ready' ? `Drawing Filter · partial view of ${filter.summary.sheet || 'this sheet'} and its selection`
454
+ : 'Drawing Filter · loading…';
455
+ // A live region: rewritten only when the text changes, or every keystroke would re-announce it.
456
+ if (ui.contextNote.textContent !== `Sharing with AI: ${shared}`) {
457
+ const prefix = document.createElement('strong');
458
+ prefix.textContent = 'Sharing with AI: ';
459
+ ui.contextNote.replaceChildren(prefix, document.createTextNode(shared));
460
+ }
461
+ ui.send.dataset.tip = ui.contextNote.textContent;
462
+ // Leaving or returning to the Drawing Filter changes whether a suggestion can be applied.
463
+ refreshFilterCards();
384
464
  }
385
465
 
386
466
  function commandInstance(value) {
@@ -530,7 +610,22 @@
530
610
  return node;
531
611
  }
532
612
 
613
+ // The composer's disclosure line. Derived from state in ONE place and called from every render
614
+ // entry point, rather than switched on where the chooser is built and off in each of the paths
615
+ // that leave it: a guarantee assembled from N call sites is only as good as the one someone
616
+ // forgets. It shows exactly where the card's own copy would say it — a scoped conversation that
617
+ // has not been started yet — so the sentence is on screen before the first message either way,
618
+ // at every panel height, including the ones where the card itself cannot fit (#1501).
619
+ // `opening` is passed by showConversationLoading, which nulls state.chat while it fetches a
620
+ // conversation the user has already picked. Without it the transient null reads as "no chat
621
+ // chosen yet" and the disclosure flashes on over a conversation that is merely loading — the
622
+ // predicate would be answering a question about state rather than about what the user is doing.
623
+ function paintComposerDisclosure(options = {}) {
624
+ ui.disclosure.hidden = options.opening === true || Boolean(state.chat) || !state.scope?.owner;
625
+ }
626
+
533
627
  function providerChooser() {
628
+ paintComposerDisclosure();
534
629
  // The workspace landing page has no conversation owner. It must never offer a provider,
535
630
  // history, or refresh there: none of those actions has a chat to operate on.
536
631
  // No provider is chosen here (nor on the unscoped landing), so a setup card left from the previous
@@ -538,11 +633,12 @@
538
633
  shell.querySelector('.ai-chat-runtime')?.remove(); stopRuntimePoll();
539
634
  if (!state.scope?.owner) { showUnscoped(); return; }
540
635
  ui.feed.replaceChildren();
636
+ updateOffscreenActivity();
541
637
  const empty = document.createElement('div');
542
638
  empty.className = 'ai-chat-empty';
543
639
  const strong = document.createElement('strong');
544
640
  strong.textContent = state.chats.length ? 'Start a new conversation' : 'Start this conversation';
545
- const copy = document.createElement('div');
641
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
546
642
  copy.textContent = 'FloLess keeps this chat with the project on this computer. Messages and attachments are sent to Claude or Codex through your account.';
547
643
  const row = document.createElement('div');
548
644
  row.className = 'ai-chat-provider-row';
@@ -588,6 +684,12 @@
588
684
  ui.historyToggle.disabled = false;
589
685
  ui.refresh.disabled = true;
590
686
  ui.settingsToggle.disabled = true;
687
+ // The ⚙ toggle is disabled here, so a strip left open from the previous conversation (+ New
688
+ // conversation pressed with it open) could no longer be closed, and it would take its height from
689
+ // the conversation area the Claude / Codex choice needs (#1554). There is no conversation for its
690
+ // settings to act on, so it closes, as it does on the unscoped landing.
691
+ ui.settings.hidden = true; ui.settingsToggle.setAttribute('aria-expanded', 'false');
692
+ closePicker();
591
693
  }
592
694
 
593
695
  function clearProviderChoice() {
@@ -595,16 +697,18 @@
595
697
  }
596
698
 
597
699
  function showUnscoped() {
700
+ paintComposerDisclosure();
598
701
  clearProviderChoice();
599
702
  closeSource();
600
703
  clearLiveStream(true);
601
- state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = [];
704
+ state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = []; state.followupUnknownId = null;
602
705
  ui.feed.replaceChildren();
706
+ updateOffscreenActivity();
603
707
  const empty = document.createElement('div');
604
708
  empty.className = 'ai-chat-empty';
605
709
  const strong = document.createElement('strong');
606
710
  strong.textContent = 'Open a project or workflow';
607
- const copy = document.createElement('div');
711
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
608
712
  copy.textContent = 'Each project or workflow keeps its own chat history in its folder.';
609
713
  empty.append(strong, copy);
610
714
  ui.feed.append(empty);
@@ -920,7 +1024,8 @@
920
1024
  paintHistory(); paintUnread();
921
1025
  if (state.chat?.chatId !== chatId) { announce(announcement); return; }
922
1026
  closeSource(); clearLiveStream(true);
923
- state.chat = null; state.events = []; state.attachments = []; state.integrations = null;
1027
+ state.chat = null; state.events = []; state.attachments = []; state.followupUnknownId = null; state.integrations = null;
1028
+ updateOffscreenActivity();
924
1029
  if (state.chats.length) await selectConversation(state.chats[0].chatId, { focus: true, replaceProviderChoice: true });
925
1030
  else providerChooser();
926
1031
  if (sameScope(snapshot.scope, snapshot.generation)) announce(announcement);
@@ -1132,7 +1237,10 @@
1132
1237
  if (event.providerItemId) item.dataset.providerItemId = event.providerItemId;
1133
1238
  if (event.turnId) item.dataset.turnId = event.turnId;
1134
1239
  const head = document.createElement('div'); head.className = 'ai-chat-message-head';
1135
- const who = document.createElement('span'); who.textContent = role === 'user' ? 'You' : providerLabels[state.chat?.provider] || 'AI';
1240
+ // A background answer records the runtime that produced it; name that one, not the conversation's.
1241
+ const who = document.createElement('span'); who.textContent = event.payload?.source === 'filter-save'
1242
+ ? 'FloLess' : role === 'user' ? 'You'
1243
+ : providerLabels[event.payload?.provider] || providerLabels[state.chat?.provider] || 'AI';
1136
1244
  const time = document.createElement('time'); time.dateTime = event.createdAt; time.textContent = eventTime(event);
1137
1245
  const visibleText = role === 'assistant' ? visibleAssistantText(text) : visibleUserText(text);
1138
1246
  head.append(who, time); item.append(head);
@@ -1153,9 +1261,81 @@
1153
1261
  item.append(gallery);
1154
1262
  }
1155
1263
  }
1264
+ if (role === 'user' && (event.payload?.followup || event.payload?.deliveryState)) {
1265
+ const delivery = followupDelivery(event);
1266
+ const deliveryReceipt = [...state.events].reverse().find((candidate) => candidate.type === 'followup-status'
1267
+ && candidate.clientSubmissionId === event.clientSubmissionId)?.payload;
1268
+ const labels = {
1269
+ pending: 'Waiting to send', sending: 'Sending to AI', accepted: 'Sent to AI',
1270
+ 'queued-next': 'Queued for the next response', 'not-sent': 'Not sent', unknown: 'Delivery unconfirmed',
1271
+ dismissed: 'Continued without resending',
1272
+ };
1273
+ // A later message stays durably pending so it can join the first queued message's
1274
+ // promoted turn. Show why it is waiting while that earlier message is being promoted.
1275
+ const queuedAhead = delivery === 'pending' && state.events.some((candidate) =>
1276
+ candidate.type === 'user-message' && candidate.turnId === event.turnId
1277
+ && candidate.sequence < event.sequence && candidate.payload?.followup
1278
+ && state.events.some((statusEvent) => statusEvent.type === 'followup-status'
1279
+ && statusEvent.clientSubmissionId === candidate.clientSubmissionId
1280
+ && statusEvent.payload?.deliveryState === 'queued-next'));
1281
+ const status = document.createElement('span'); status.className = 'ai-chat-message-delivery';
1282
+ status.textContent = labels[queuedAhead ? 'queued-next' : delivery] || 'Waiting for AI';
1283
+ item.append(status);
1284
+ if (delivery === 'not-sent' && deliveryReceipt?.reason) {
1285
+ const help = document.createElement('span'); help.className = 'ai-chat-message-delivery ai-chat-message-delivery-detail';
1286
+ help.textContent = deliveryReceipt.reason;
1287
+ item.append(help);
1288
+ }
1289
+ if (delivery === 'unknown' && event.clientSubmissionId) {
1290
+ const help = document.createElement('span'); help.className = 'ai-chat-message-delivery ai-chat-message-delivery-detail';
1291
+ help.textContent = 'AI may have received this. Check the conversation before continuing.';
1292
+ const resolve = button(event.optimistic ? 'Review draft and continue' : 'Continue without resending',
1293
+ `shell.chat-followup-resolve-${event.optimistic ? 'local' : 'durable'}#${event.clientSubmissionId}`, 'ai-chat-followup-resolve');
1294
+ resolve.dataset.commandInstanceLabel = visibleText.slice(0, 80) || 'Follow-up';
1295
+ resolve.setAttribute('aria-label', `${resolve.textContent}: ${visibleText.slice(0, 80) || 'follow-up with attachments'}`);
1296
+ resolve.dataset.tip = event.optimistic
1297
+ ? 'Review the draft; sending it again may duplicate a message AI received'
1298
+ : 'Continue despite uncertain delivery; this message will not be resent';
1299
+ resolve.disabled = Boolean(state.resolvingFollowupIds?.has(event.clientSubmissionId));
1300
+ resolve.setAttribute('aria-busy', String(resolve.disabled));
1301
+ if (resolve.disabled) resolve.dataset.blockedReason = 'FloLess is updating this message';
1302
+ resolve.addEventListener('click', () => { void resolveUnknownFollowup(event.clientSubmissionId); });
1303
+ item.append(help, resolve);
1304
+ }
1305
+ if (delivery === 'not-sent' && deliveryReceipt?.retryable !== false
1306
+ && event.clientSubmissionId && !state.chat?.archivedAt
1307
+ && state.chat?.state !== 'recovery'
1308
+ && !state.followupUnknownId && !hasUnknownFollowup()
1309
+ && (!state.chat?.activeTurn || state.chat.activeTurn.turnId === event.turnId)
1310
+ && !state.events.some(candidate => candidate.type === 'user-message'
1311
+ && candidate.payload?.retryOfSubmissionId === event.clientSubmissionId)) {
1312
+ const retry = button(state.retryingFollowupIds?.has(event.clientSubmissionId) ? 'Retrying…' : 'Retry sending',
1313
+ `shell.chat-followup-retry#${event.clientSubmissionId}`, 'ai-chat-followup-resolve');
1314
+ retry.dataset.commandInstanceLabel = visibleText.slice(0, 80) || 'Follow-up with attachments';
1315
+ retry.setAttribute('aria-label', `${retry.textContent}: ${visibleText.slice(0, 80) || 'follow-up with attachments'}`);
1316
+ retry.dataset.tip = 'Send this message and its attached files again; your draft stays as it is';
1317
+ retry.disabled = Boolean(state.retryingFollowupIds?.has(event.clientSubmissionId));
1318
+ retry.setAttribute('aria-busy', String(retry.disabled));
1319
+ if (retry.disabled) retry.dataset.blockedReason = 'FloLess is retrying this message';
1320
+ retry.addEventListener('click', () => { void retryNotSentFollowup(event.clientSubmissionId); });
1321
+ item.append(retry);
1322
+ }
1323
+ }
1156
1324
  return item;
1157
1325
  }
1158
1326
 
1327
+ function followupDelivery(event) {
1328
+ const receipt = [...state.events].reverse().find((candidate) => candidate.type === 'followup-status'
1329
+ && candidate.clientSubmissionId === event.clientSubmissionId);
1330
+ return receipt?.payload?.deliveryState || event.payload?.deliveryState || 'pending';
1331
+ }
1332
+
1333
+ function hasUnknownFollowup() {
1334
+ return state.events.some((event) => event.type === 'user-message'
1335
+ && (event.payload?.followup || event.payload?.deliveryState)
1336
+ && followupDelivery(event) === 'unknown');
1337
+ }
1338
+
1159
1339
  function renderRequestCard(event) {
1160
1340
  const payload = event.payload || {};
1161
1341
  const item = document.createElement('article');
@@ -1188,10 +1368,13 @@
1188
1368
  }
1189
1369
 
1190
1370
  function renderEvent(event) {
1371
+ if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
1191
1372
  if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
1373
+ if (event.type === 'assistant-message' && event.payload?.filterAi && !event.payload?.delta) return renderFilterAnswer(event);
1192
1374
  if (event.type === 'user-message') return renderMessage(event, 'user', payloadText(event));
1193
1375
  if (event.type === 'assistant-message') return renderMessage(event, 'assistant', payloadText(event), Boolean(event.payload?.delta));
1194
- if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state') return null;
1376
+ if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state' || event.type === 'followup-status') return null;
1377
+ if (event.type === 'tekla-read') return renderTeklaReadEvent(event);
1195
1378
  const item = document.createElement('div');
1196
1379
  item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}${event.type === 'knowledge-citation' ? ' knowledge' : ''}`;
1197
1380
  item.dataset.eventSequence = String(event.sequence);
@@ -1201,8 +1384,8 @@
1201
1384
  attachment: 'Attachment', tool: 'AI action', error: 'Error', interrupted: 'Stopped', usage: 'AI usage',
1202
1385
  compaction: 'Conversation summary updated', 'knowledge-citation': 'Knowledge cited', state: 'Status', request: 'Request',
1203
1386
  };
1204
- label.textContent = labels[event.type] || event.type;
1205
1387
  const payload = event.payload || {};
1388
+ label.textContent = event.type === 'error' && payload.outcome === 'not-sent' ? 'Not sent' : labels[event.type] || event.type;
1206
1389
  let detail = event.type === 'error' ? errorMessage(payloadText(event)) : payloadText(event);
1207
1390
  if (!detail && event.type === 'tool') {
1208
1391
  const toolLabels = { provider: 'AI provider', integration: 'Connected service', attachment: 'Attachment', knowledge: 'Knowledge', filesystem: 'Project files' };
@@ -1218,6 +1401,60 @@
1218
1401
  return item;
1219
1402
  }
1220
1403
 
1404
+ // A server-authored receipt of one approved live Tekla read. Deterministic: it shows only what
1405
+ // the server recorded, and an unverified read never shows a model name.
1406
+ function renderTeklaReadEvent(event) {
1407
+ const payload = event.payload || {};
1408
+ const verified = payload.status === 'verified-for-model-name-read';
1409
+ const card = document.createElement('section');
1410
+ card.className = `ai-chat-tekla-read ${verified ? 'verified' : 'unverified'}`;
1411
+ card.setAttribute('role', 'status');
1412
+ card.dataset.eventSequence = String(event.sequence);
1413
+ card.dataset.eventId = event.eventId;
1414
+ const heading = document.createElement('strong');
1415
+ heading.textContent = verified ? 'Verified for model-name read' : 'Could not verify this read';
1416
+ card.setAttribute('aria-label', heading.textContent);
1417
+ card.append(heading);
1418
+ const facts = document.createElement('dl');
1419
+ const fact = (name, value) => {
1420
+ if (value === undefined || value === null || value === '') return;
1421
+ const dt = document.createElement('dt'); dt.textContent = name;
1422
+ const dd = document.createElement('dd');
1423
+ if (value instanceof Node) dd.append(value); else dd.textContent = String(value);
1424
+ facts.append(dt, dd);
1425
+ };
1426
+ if (verified) {
1427
+ fact('Operation', payload.operation);
1428
+ // A replayed receipt is history: the name is what was open at the check, not what is open now.
1429
+ fact('Model when checked', payload.modelName);
1430
+ fact('Tekla host', `${payload.hostVersion || ''}${Number.isFinite(payload.hostPid) ? ` · PID ${payload.hostPid}` : ''}`);
1431
+ fact('Library', payload.library);
1432
+ fact('Checked', checkedTime(payload.checkedAt));
1433
+ card.append(facts);
1434
+ const note = document.createElement('p'); note.textContent = 'The generated agent\'s commands remain unverified.';
1435
+ card.append(note);
1436
+ } else {
1437
+ const message = document.createElement('p');
1438
+ message.textContent = typeof payload.message === 'string' && payload.message.trim()
1439
+ ? payload.message : 'FloLess could not complete this read.';
1440
+ card.append(message);
1441
+ fact('Library', payload.library);
1442
+ fact('Checked', checkedTime(payload.checkedAt));
1443
+ if (facts.childElementCount) card.append(facts);
1444
+ }
1445
+ return card;
1446
+ }
1447
+
1448
+ function checkedTime(value) {
1449
+ if (typeof value !== 'string' || !value) return '';
1450
+ const date = new Date(value);
1451
+ if (Number.isNaN(date.getTime())) return value;
1452
+ const time = document.createElement('time');
1453
+ time.dateTime = value;
1454
+ time.textContent = date.toLocaleString([], { dateStyle: 'medium', timeStyle: 'medium' });
1455
+ return time;
1456
+ }
1457
+
1221
1458
  function animatedDots() {
1222
1459
  const dots = document.createElement('span'); dots.className = 'ai-chat-live-dots'; dots.setAttribute('aria-hidden', 'true');
1223
1460
  dots.append(document.createElement('i'), document.createElement('i'), document.createElement('i'));
@@ -1235,11 +1472,15 @@
1235
1472
 
1236
1473
  function announceLiveResponseOnce() {
1237
1474
  const turnId = turnIsVisiblyActive() ? state.chat.activeTurn.turnId : null;
1475
+ const wasResponding = state.liveStatusTurnId !== null;
1238
1476
  if (!turnId) {
1239
1477
  state.liveStatusTurnId = null;
1240
1478
  // The screen-reader announcement is a transient status. Once the durable turn ends,
1241
1479
  // leaving its text behind makes the finished chat sound as though it is still working.
1242
- ui.status.textContent = '';
1480
+ // Cleared once, when that turn ends — not on every idle repaint: the 5 s poll repaints the
1481
+ // feed, and wiping the live region there erased other announcements, such as the pending
1482
+ // sign-in's, before a screen reader had read them (#1514).
1483
+ if (wasResponding) ui.status.textContent = '';
1243
1484
  return;
1244
1485
  }
1245
1486
  if (state.liveStatusTurnId === turnId) return;
@@ -1279,8 +1520,31 @@
1279
1520
  target.scrollIntoView({ block: 'center' });
1280
1521
  }
1281
1522
 
1523
+ function updateOffscreenActivity() {
1524
+ const liveDots = ui.feed.querySelector('.ai-chat-live-status .ai-chat-live-dots');
1525
+ // Showing the badge claims a row below the feed. Require enough room for that row before
1526
+ // showing it, otherwise ResizeObserver could alternate between show and hide in a short pane.
1527
+ const minimumFeedHeight = ui.offscreenActivity.hidden ? 88 : 48;
1528
+ ui.offscreenActivity.hidden = !turnIsVisiblyActive() || state.historyOpen || !liveDots
1529
+ || ui.feed.clientHeight < minimumFeedHeight
1530
+ || liveDots.getBoundingClientRect().bottom <= ui.feed.getBoundingClientRect().bottom;
1531
+ }
1532
+
1533
+ // paintEvents rebuilds every control in the feed, so a control that held keyboard focus is put
1534
+ // back on its replacement. The empty state's sign-in is one of them: the repaint that follows its
1535
+ // own click would otherwise drop focus to the page just as it turns to "Sign-in window open".
1536
+ // That button is `aria-disabled`, not `disabled`, so it passes the filter (#1514).
1537
+ function restoreFeedFocus(focusedCommand) {
1538
+ if (!focusedCommand?.startsWith('shell.chat-followup-') && !focusedCommand?.startsWith('shell.chat-filter-')
1539
+ && focusedCommand !== 'shell.chat-sign-in') return;
1540
+ [...ui.feed.querySelectorAll('[data-command-id]')]
1541
+ .find(control => control.dataset.commandId === focusedCommand && !control.disabled)?.focus({ preventScroll: true });
1542
+ }
1543
+
1282
1544
  function paintEvents(options = {}) {
1283
1545
  announceLiveResponseOnce();
1546
+ const focusedCommand = ui.feed.contains(document.activeElement)
1547
+ ? document.activeElement?.dataset?.commandId : null;
1284
1548
  const nearBottom = ui.feed.scrollHeight - ui.feed.scrollTop - ui.feed.clientHeight < 56;
1285
1549
  ui.feed.replaceChildren();
1286
1550
  if (!state.events.length) {
@@ -1320,8 +1584,13 @@
1320
1584
  // never looks like a failed response. Recovery deliberately has no live indicator.
1321
1585
  if (turnIsVisiblyActive()) ui.feed.append(renderLiveStatus());
1322
1586
  }
1587
+ restoreFeedFocus(focusedCommand);
1323
1588
  restoreAnswerJump();
1324
- if (!state.answerJump && (nearBottom || options.forceBottom)) requestAnimationFrame(() => { ui.feed.scrollTop = ui.feed.scrollHeight; });
1589
+ updateOffscreenActivity();
1590
+ if (!state.answerJump && (nearBottom || options.forceBottom)) requestAnimationFrame(() => {
1591
+ ui.feed.scrollTop = ui.feed.scrollHeight;
1592
+ updateOffscreenActivity();
1593
+ });
1325
1594
  }
1326
1595
 
1327
1596
  // The feed's empty state. Four cases, in the order they must win: a sign-in window FloLess
@@ -1333,18 +1602,24 @@
1333
1602
  function emptyFeedNotice() {
1334
1603
  const empty = document.createElement('div'); empty.className = 'ai-chat-empty';
1335
1604
  const strong = document.createElement('strong');
1336
- const copy = document.createElement('div');
1605
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
1337
1606
  const provider = state.chat?.provider;
1338
1607
  const label = providerLabels[provider] || 'AI';
1339
1608
  const pendingSignIn = Boolean(provider && state.signInPending.has(provider));
1340
1609
  if (pendingSignIn) {
1610
+ // The title names the STATE and the button names the OBJECT (the open window), so the card
1611
+ // never says the same phrase twice (#1516).
1341
1612
  strong.textContent = 'Waiting for sign-in…';
1342
1613
  // The claude.ai page in the browser keeps its OWN session: it may still show the previous
1343
1614
  // account with an "Switch account" link of its own, and no CLI verb can clear that. Said
1344
1615
  // at the one moment it matters, for the one provider it applies to.
1345
1616
  copy.textContent = `Finish signing in using the window FloLess opened.${provider === 'claude'
1346
1617
  ? ' If the Claude page in your browser still shows the previous account, use its own Switch account link.' : ''}`;
1347
- empty.append(strong, copy, emptySignInButton(label, true));
1618
+ // The button's accessible description. A short panel hides this prose (chat.css), but a node
1619
+ // referenced by aria-describedby still describes even when it is not painted, so the reason
1620
+ // the button is inert reaches a screen reader at every height (#1514).
1621
+ copy.id = 'chat-empty-signin-help';
1622
+ empty.append(strong, copy, emptySignInButton(label, true, copy.id));
1348
1623
  } else if (providerReady()) {
1349
1624
  strong.textContent = 'Ready when you are';
1350
1625
  copy.textContent = `This ${label} conversation is stored with ${state.scope?.label || 'this work'}.`;
@@ -1369,16 +1644,28 @@
1369
1644
  // pending set. Only ever a sign-in — the reason that shows it guarantees that — so it never needs
1370
1645
  // the strip's "Switch account…" label. Its own command id because it is its own carrier, in its
1371
1646
  // own place.
1372
- function emptySignInButton(label, pending) {
1647
+ //
1648
+ // While the window is open the button is inert but NOT `disabled` (#1514): a disabled button
1649
+ // cannot take focus, and in a short panel it is the only thing left in the card, so keyboard and
1650
+ // screen-reader users found nothing at all. It is `aria-disabled` instead — reachable, named for
1651
+ // the window it is waiting on, described by the card's prose, and refusing its own click.
1652
+ function emptySignInButton(label, pending, describedBy) {
1373
1653
  const signIn = document.createElement('button');
1374
1654
  signIn.type = 'button';
1375
1655
  signIn.className = 'ai-chat-provider-switch ai-chat-empty-signin';
1376
1656
  signIn.dataset.commandId = 'shell.chat-sign-in';
1377
- signIn.setAttribute('aria-label', `Sign in to ${label}`);
1378
- signIn.textContent = pending ? 'Waiting for sign-in…' : 'Sign in…';
1379
- signIn.disabled = pending;
1380
- if (pending) signIn.dataset.blockedReason = 'Waiting for the sign-in window.';
1381
- signIn.addEventListener('click', () => { void switchAccount(); });
1657
+ // The accessible name contains the visible label word for word (WCAG 2.5.3, label in name).
1658
+ signIn.setAttribute('aria-label', pending ? `${label} sign-in window open` : `Sign in to ${label}`);
1659
+ signIn.textContent = pending ? 'Sign-in window open' : 'Sign in…';
1660
+ if (pending) {
1661
+ signIn.setAttribute('aria-disabled', 'true');
1662
+ signIn.dataset.blockedReason = 'Finish signing in using the window FloLess opened.';
1663
+ if (describedBy) signIn.setAttribute('aria-describedby', describedBy);
1664
+ }
1665
+ signIn.addEventListener('click', (event) => {
1666
+ if (signIn.getAttribute('aria-disabled') === 'true') { event.preventDefault(); return; }
1667
+ void switchAccount();
1668
+ });
1382
1669
  return signIn;
1383
1670
  }
1384
1671
 
@@ -1400,15 +1687,34 @@
1400
1687
  const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
1401
1688
  const deny = button('Deny', 'shell.chat-approval-deny');
1402
1689
  const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
1403
- const allowRequest = button('Approve for this request', 'shell.chat-approval-request', 'allow');
1404
- allowRequest.dataset.tip = 'Approve access actions until this response finishes. Your permission setting stays unchanged.';
1405
- const scope = document.createElement('p');
1406
- scope.textContent = 'Request approval lasts until this response finishes. Review checkpoints still need your decision.';
1690
+ // A Tekla model read needs its own decision every time, so a request-wide grant is not offered.
1691
+ const explicitOnly = approvalIsExplicitOnly(approval);
1692
+ const allowRequest = explicitOnly ? null : button('Approve for this request', 'shell.chat-approval-request', 'allow');
1693
+ const scope = document.createElement('span');
1694
+ scope.className = 'sr-only';
1695
+ scope.id = `chat-approval-request-help-${approval.approvalId}`;
1407
1696
  deny.addEventListener('click', () => decideApproval('deny'));
1408
1697
  allow.addEventListener('click', () => decideApproval('allow'));
1409
- allowRequest.addEventListener('click', () => decideApproval('allow-request'));
1410
- actions.append(deny, allow, allowRequest); card.append(heading, copy, scope, actions);
1411
- shell.insertBefore(card, ui.recovery);
1698
+ if (allowRequest) {
1699
+ scope.textContent = 'Approve access actions until this response finishes. Your permission setting stays unchanged. Review checkpoints and Tekla model reads still ask every time.';
1700
+ allowRequest.dataset.tip = scope.textContent;
1701
+ allowRequest.setAttribute('aria-describedby', scope.id);
1702
+ allowRequest.addEventListener('click', () => decideApproval('allow-request'));
1703
+ actions.append(deny, allow, allowRequest); card.append(heading, copy, actions, scope);
1704
+ } else {
1705
+ card.dataset.explicitOnly = 'true';
1706
+ actions.append(deny, allow); card.append(heading, copy, actions);
1707
+ }
1708
+ ui.approvalTray.append(card);
1709
+ // When a request-wide grant notice is also present, keep the decision nearest the composer.
1710
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
1711
+ }
1712
+
1713
+ function approvalIsExplicitOnly(approval) {
1714
+ if (!approval) return false;
1715
+ if (approval.explicitOnly === true) return true;
1716
+ return state.events.some((event) => event.type === 'approval-requested'
1717
+ && event.payload?.approvalId === approval.approvalId && event.payload?.explicitOnly === true);
1412
1718
  }
1413
1719
 
1414
1720
  function paintApprovalScope() {
@@ -1429,19 +1735,19 @@
1429
1735
  card.className = 'ai-chat-approval ai-chat-approval-scope';
1430
1736
  card.dataset.turnId = turn.turnId;
1431
1737
  const heading = document.createElement('strong');
1432
- heading.textContent = 'Access auto-approval on for this request';
1433
- const copy = document.createElement('p');
1434
- copy.textContent = 'Your permission setting is unchanged. Review checkpoints still need your decision.';
1435
- const note = document.createElement('p');
1436
- note.textContent = 'Actions already approved may finish.';
1437
- const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
1738
+ heading.textContent = 'Auto-approval on · this request';
1739
+ const explanation = document.createElement('span');
1740
+ explanation.className = 'sr-only';
1741
+ explanation.id = `chat-approval-scope-help-${turn.turnId}`;
1742
+ explanation.textContent = 'Your permission setting is unchanged. Review checkpoints and Tekla model reads still ask every time. Revoke asks before future access actions in this request; actions already approved may finish.';
1438
1743
  const revoke = button('Revoke', 'shell.chat-approval-revoke');
1439
- revoke.dataset.tip = 'Ask before future access actions in this request.';
1744
+ revoke.dataset.tip = explanation.textContent;
1745
+ revoke.setAttribute('aria-describedby', explanation.id);
1440
1746
  revoke.disabled = busy;
1441
1747
  revoke.setAttribute('aria-busy', String(busy));
1442
1748
  revoke.addEventListener('click', revokeApprovalScope);
1443
- actions.append(revoke); card.append(heading, copy, note, actions);
1444
- shell.insertBefore(card, ui.recovery);
1749
+ card.append(heading, revoke, explanation);
1750
+ ui.approvalTray.prepend(card);
1445
1751
  }
1446
1752
 
1447
1753
  // FloLess installs its own tested copy of Claude Code / Codex. While that copy is being set up (or
@@ -1592,6 +1898,9 @@
1592
1898
 
1593
1899
  function paintAttachments() {
1594
1900
  ui.attachments.replaceChildren();
1901
+ const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length;
1902
+ ui.attach.dataset.tip = `Attach image or PDF · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images in this message`;
1903
+ ui.attach.setAttribute('aria-label', `Attach image or PDF · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images`);
1595
1904
  for (const attachment of state.attachments) {
1596
1905
  const chip = document.createElement('span'); chip.className = 'ai-chat-attachment';
1597
1906
  if (attachment.mediaType.startsWith('image/')) {
@@ -1624,13 +1933,20 @@
1624
1933
  if (!state.capability) return null;
1625
1934
  return state.capability.models.find((model) => model.id === state.chat?.settings.model)
1626
1935
  || preferredModel(state.chat?.provider, state.capability.models)
1936
+ || state.capability.models.find((model) => model.isDefault)
1627
1937
  || state.capability.models[0] || null;
1628
1938
  }
1629
1939
 
1940
+ // In order of preference; keep in step with PREFERRED_MODELS in server/chat-routes.ts. Without
1941
+ // GPT-6-Sol nothing is preferred, so the provider's own default row is shown and used.
1630
1942
  function preferredModel(provider, models) {
1631
1943
  if (!provider || !Array.isArray(models)) return null;
1632
- const pattern = provider === 'codex' ? /gpt[- .]?5\.6[- .]?terra/i : /opus/i;
1633
- return models.find((model) => pattern.test(`${model.id} ${model.label}`)) || null;
1944
+ const patterns = provider === 'codex' ? [/gpt[- .]?6[- .]?sol/i] : [/opus[- .]?5\.5/i, /opus/i];
1945
+ for (const pattern of patterns) {
1946
+ const found = models.find((model) => pattern.test(`${model.id} ${model.label}`));
1947
+ if (found) return found;
1948
+ }
1949
+ return null;
1634
1950
  }
1635
1951
 
1636
1952
  function preferredSettings(provider, capability) {
@@ -1695,11 +2011,16 @@
1695
2011
  const snapshot = captureChat();
1696
2012
  const before = answerKey(state.capability?.account);
1697
2013
  state.signInPending.add(chat.provider);
1698
- // Both carriers of this action flip to "Waiting for sign-in…" at the click, not at the next
1699
- // 5 s poll: the empty state's button is the one a new user just pressed.
2014
+ // Both carriers of this action flip to waiting at the click, not at the next 5 s poll — the
2015
+ // settings strip to "Waiting for sign-in…", the empty state to its "Waiting for sign-in…" title
2016
+ // over a "Sign-in window open" button: that button is the one a new user just pressed.
1700
2017
  paintSettings(); paintEvents();
1701
2018
  try {
1702
2019
  await request(`/api/terminal-runtimes/${encodeURIComponent(chat.provider)}/sign-in`, { method: 'POST' });
2020
+ // Announced once, through the panel's live region, so it reaches a screen reader however
2021
+ // much of the empty state a short panel still paints (#1514). Only now: before this await
2022
+ // resolves there is no window to point at.
2023
+ if (sameChat(snapshot)) announce(`Waiting for sign-in. Finish signing in to ${providerLabels[chat.provider] || 'AI'} using the window FloLess opened.`);
1703
2024
  await waitForSignIn(chat.provider, before);
1704
2025
  if (sameChat(snapshot)) await loadCapability();
1705
2026
  } catch (error) {
@@ -1834,6 +2155,8 @@
1834
2155
  }
1835
2156
 
1836
2157
  function paintConversation() {
2158
+ paintComposerDisclosure();
2159
+ paintTeklaChip();
1837
2160
  const chat = state.chat;
1838
2161
  if (!chat) { providerChooser(); paintHistory(); return; }
1839
2162
  ui.historyToggle.disabled = false;
@@ -1842,13 +2165,26 @@
1842
2165
  ui.scope.textContent = `${state.scope.label} · ${providerLabels[chat.provider]}`;
1843
2166
  ui.rename.hidden = Boolean(chat.activeTurn) || Boolean(chat.archivedAt);
1844
2167
  ui.input.disabled = Boolean(chat.archivedAt) || chat.state === 'recovery' || requestExecutionBlocked();
1845
- if (ui.input.value !== chat.draft && document.activeElement !== ui.input) ui.input.value = chat.draft || '';
2168
+ const draft = draftForChat(chat);
2169
+ if (ui.input.value !== draft && document.activeElement !== ui.input) ui.input.value = draft;
1846
2170
  const active = turnIsVisiblyActive(chat);
1847
2171
  ui.stop.hidden = !active || Boolean(chat.activeTurn?.local);
1848
- ui.send.hidden = active;
2172
+ ui.send.hidden = false;
1849
2173
  paintSettings(); paintRecovery(); paintApproval(); paintRuntime(); paintAttachments(); paintEvents(); paintHistory(); updateSendState();
1850
2174
  }
1851
2175
 
2176
+ function draftForChat(chat) {
2177
+ if (state.backgroundDrafts.has(chat.chatId)) {
2178
+ const recovered = state.backgroundDrafts.get(chat.chatId);
2179
+ if (chat.draft === recovered) state.backgroundDrafts.delete(chat.chatId);
2180
+ return recovered;
2181
+ }
2182
+ const local = state.localDraft;
2183
+ // A refresh can arrive after typing but before the debounced draft write commits.
2184
+ // Keep the local edit through older in-flight refreshes when focus leaves the composer.
2185
+ return local?.chatId === chat.chatId ? local.text : chat.draft || '';
2186
+ }
2187
+
1852
2188
  function closeSource() {
1853
2189
  if (state.eventReconnectTimer) { clearTimeout(state.eventReconnectTimer); state.eventReconnectTimer = null; }
1854
2190
  if (state.source) { state.source.close(); state.source = null; }
@@ -1901,13 +2237,24 @@
1901
2237
  state.eventReconnectChatId = chatId;
1902
2238
  state.eventReconnectAttempt = 0;
1903
2239
  }
1904
- const after = state.events.reduce((max, event) => Math.max(max, event.sequence || 0), 0);
2240
+ const after = Math.floor(state.events.reduce((max, event) => Math.max(max, event.sequence || 0), 0));
1905
2241
  const source = new EventSource(`/api/chat/conversations/${encodeURIComponent(chatId)}/events?${ownerQuery(scope.owner)}&after=${after}`);
1906
2242
  state.source = source;
1907
2243
  source.addEventListener('chat-event', (message) => {
1908
2244
  if (state.chat?.chatId !== chatId) return;
1909
2245
  const event = JSON.parse(message.data);
1910
- if (event.clientSubmissionId) {
2246
+ if (state.followupUnknownId === event.clientSubmissionId
2247
+ && event.type === 'user-message'
2248
+ && event.payload?.deliveryState !== 'unknown') {
2249
+ state.followupUnknownId = null;
2250
+ state.unknownFollowups.delete(chatId);
2251
+ clearConfirmedUnknownDraft(event, chatId);
2252
+ updateSendState();
2253
+ }
2254
+ // A status can precede the durable user message. Keep the uncertain row and
2255
+ // draft blocked until that message confirms which submission the server saved.
2256
+ if (event.clientSubmissionId && !(event.type === 'followup-status'
2257
+ && state.followupUnknownId === event.clientSubmissionId)) {
1911
2258
  state.events = state.events.filter((item) => !(item.optimistic && item.clientSubmissionId === event.clientSubmissionId));
1912
2259
  }
1913
2260
  if (state.events.some((item) => item.eventId === event.eventId)) return;
@@ -1924,9 +2271,21 @@
1924
2271
  state.chat = { ...state.chat, state: 'completed', activeTurn: null };
1925
2272
  paintConversation();
1926
2273
  }
2274
+ if (event.type === 'followup-status') {
2275
+ const notices = {
2276
+ accepted: 'Follow-up sent to AI.',
2277
+ 'queued-next': 'Follow-up queued for the next AI response.',
2278
+ 'not-sent': event.payload?.reason || (event.payload?.retryable === false
2279
+ ? 'This message was not sent. Review the conversation before writing a new message.'
2280
+ : 'This message was not sent. Use Retry sending if you still want to send it.'),
2281
+ unknown: 'FloLess could not confirm whether AI received the follow-up. Check the AI response here, then choose Continue without resending if you want to proceed.',
2282
+ };
2283
+ if (notices[event.payload?.deliveryState]) announce(notices[event.payload.deliveryState]);
2284
+ }
1927
2285
  paintEvents(); paintUnread();
1928
2286
  if (!document.hidden && !ui.feed.closest('[hidden]')) markRead();
1929
- if (['approval-requested', 'approval-decided', 'error', 'interrupted', 'state'].includes(event.type)) refreshConversation(chatId, false);
2287
+ if (['approval-requested', 'approval-decided', 'error', 'interrupted', 'state', 'followup-status'].includes(event.type)
2288
+ || (event.type === 'user-message' && event.payload?.followup)) refreshConversation(chatId, false);
1930
2289
  });
1931
2290
  source.addEventListener('ready', () => {
1932
2291
  if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
@@ -1940,6 +2299,21 @@
1940
2299
  };
1941
2300
  }
1942
2301
 
2302
+ function clearConfirmedUnknownDraft(event, chatId) {
2303
+ const confirmed = String(event.payload?.text || '').trim();
2304
+ if (state.backgroundDrafts.get(chatId)?.trim() === confirmed) state.backgroundDrafts.delete(chatId);
2305
+ const used = new Set(event.payload?.attachmentIds || []);
2306
+ state.attachments = state.attachments.filter(item => !used.has(item.attachmentId));
2307
+ paintAttachments(); updateSendState();
2308
+ if (ui.input.value.trim() !== confirmed) return;
2309
+ clearTimeout(state.draftTimer);
2310
+ ui.input.value = '';
2311
+ state.localDraft = { chatId, text: '' };
2312
+ if (state.chat?.chatId === chatId) state.chat.draft = '';
2313
+ autosize(); paintAttachments(); updateSendState();
2314
+ void writeChatDraft(chatId, state.scope.owner, '').catch(error => report(error, 'Draft was not saved'));
2315
+ }
2316
+
1943
2317
  async function ensureSession() {
1944
2318
  if (state.sessionReady) return;
1945
2319
  await request('/api/chat/session');
@@ -2007,10 +2381,14 @@
2007
2381
  closeSource();
2008
2382
  clearLiveStream(true);
2009
2383
  state.chat = null; state.events = []; state.capability = null; state.desktop = null;
2010
- state.attachments = []; state.integrations = null;
2384
+ state.attachments = []; state.followupUnknownId = null; state.integrations = null;
2385
+ updateOffscreenActivity();
2011
2386
  // The header switches to the next conversation now; the previous provider's setup card and composer
2012
2387
  // hint must not stay under it while that conversation opens.
2013
2388
  paintRuntime(); clearReport();
2389
+ // The user picked a conversation; they are not choosing a provider. state.chat is null only
2390
+ // because this function cleared it, so the predicate has to be told rather than left to infer.
2391
+ paintComposerDisclosure({ opening: true });
2014
2392
  ui.title.textContent = listed?.title || 'Opening conversation';
2015
2393
  ui.scope.textContent = listed ? `${state.scope?.label || ''} · ${providerLabels[listed.provider]}` : 'Opening conversation';
2016
2394
  ui.rename.hidden = true;
@@ -2018,12 +2396,12 @@
2018
2396
  ui.stop.hidden = true; ui.send.hidden = false;
2019
2397
  ui.settings.hidden = true; ui.settingsToggle.setAttribute('aria-expanded', 'false');
2020
2398
  ui.recovery.hidden = true;
2021
- shell.querySelector('.ai-chat-approval')?.remove();
2399
+ ui.approvalTray.replaceChildren();
2022
2400
  ui.attachments.replaceChildren();
2023
2401
  ui.feed.replaceChildren();
2024
2402
  const loading = document.createElement('div'); loading.className = 'ai-chat-empty';
2025
2403
  const strong = document.createElement('strong'); strong.textContent = 'Opening conversation';
2026
- const copy = document.createElement('div'); copy.textContent = listed
2404
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy'; copy.textContent = listed
2027
2405
  ? `Loading “${listed.title}”…`
2028
2406
  : 'Loading the selected conversation…';
2029
2407
  loading.append(strong, copy); ui.feed.append(loading);
@@ -2041,7 +2419,7 @@
2041
2419
  if (state.choosingProvider && options.replaceProviderChoice !== true) return;
2042
2420
  // Opening an existing conversation abandons an unsent discovery handoff. Only the
2043
2421
  // conversation created from that chooser should inherit its draft.
2044
- if (!options.preserveDiscoveryDraft) state.discoveryDraft = null;
2422
+ if (!options.preserveDiscoveryDraft) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; }
2045
2423
  clearProviderChoice();
2046
2424
  const selection = ++state.selectionGeneration;
2047
2425
  const exactAnswer = typeof options.answerEventId === 'string' ? options.answerEventId : null;
@@ -2073,10 +2451,14 @@
2073
2451
  state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
2074
2452
  state.chat = chat;
2075
2453
  state.events = snapshot.events || [];
2454
+ reconcileUnknownFollowupOnSelection(chat);
2076
2455
  state.capability = capability;
2077
2456
  state.desktop = desktop;
2078
2457
  state.attachments = (chat.attachments || []).filter((attachment) => !attachment.turnId);
2079
- ui.input.value = chat.draft || '';
2458
+ ui.input.value = draftForChat(chat);
2459
+ // A cached draft may be newer than the server draft after a fast switch.
2460
+ // Save it now, even if the user does not type again after reopening.
2461
+ if (state.backgroundDrafts.has(chatId) && draftFitsStorage(state.scope.owner, ui.input.value)) saveDraftSoon();
2080
2462
  if (answerTarget) {
2081
2463
  state.answerJump = { chatId, eventId: answerTarget.eventId, expiresAt: Date.now() + 2600 };
2082
2464
  state.answerJumpTimer = setTimeout(() => {
@@ -2084,6 +2466,7 @@
2084
2466
  }, 2600);
2085
2467
  }
2086
2468
  paintConversation(); connectEvents();
2469
+ resumeFilterRequests();
2087
2470
  if (options.applyProviderDefaults || !chat.nativeSessionId) await applyProviderDefaults(chatId);
2088
2471
  // Let the server prepare the provider for the next message while the user types, after the
2089
2472
  // default model and effort are saved so the prepared runtime matches the first message. Best-effort:
@@ -2106,6 +2489,28 @@
2106
2489
  finally { if (selection === state.selectionGeneration) setBusy(false); }
2107
2490
  }
2108
2491
 
2492
+ function reconcileUnknownFollowupOnSelection(chat) {
2493
+ const chatId = chat.chatId;
2494
+ const uncertain = state.unknownFollowups.get(chatId);
2495
+ if (!uncertain) return;
2496
+ const confirmed = state.events.some(event => event.type === 'user-message'
2497
+ && event.clientSubmissionId === uncertain.submissionId);
2498
+ if (confirmed) {
2499
+ state.unknownFollowups.delete(chatId);
2500
+ if (state.backgroundDrafts.get(chatId)?.trim() === uncertain.text.trim()) state.backgroundDrafts.delete(chatId);
2501
+ if ((state.localDraft?.chatId === chatId && state.localDraft.text.trim() === uncertain.text.trim())
2502
+ || chat.draft?.trim() === uncertain.text.trim()) {
2503
+ state.localDraft = { chatId, text: '' };
2504
+ chat.draft = '';
2505
+ void writeChatDraft(chatId, state.scope.owner, '').catch(error => report(error, 'Draft was not saved'));
2506
+ }
2507
+ } else {
2508
+ state.followupUnknownId = uncertain.submissionId;
2509
+ if (!state.events.some(event => event.type === 'user-message'
2510
+ && event.clientSubmissionId === uncertain.submissionId)) state.events.push(uncertain.event);
2511
+ }
2512
+ }
2513
+
2109
2514
  async function applyProviderDefaults(chatId) {
2110
2515
  if (!state.chat || state.chat.chatId !== chatId || state.chat.nativeSessionId || !state.capability?.available) return;
2111
2516
  const defaults = preferredSettings(state.chat.provider, state.capability);
@@ -2126,7 +2531,7 @@
2126
2531
  return;
2127
2532
  }
2128
2533
  const generation = ++state.scopeGeneration;
2129
- if (scopeKey(scope) !== scopeKey(state.scope)) state.discoveryDraft = null;
2534
+ if (scopeKey(scope) !== scopeKey(state.scope)) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; state.teklaDraft = null; }
2130
2535
  state.selectionGeneration += 1;
2131
2536
  clearAnswerJump();
2132
2537
  clearLiveStream(true);
@@ -2135,6 +2540,10 @@
2135
2540
  state.scope = scope;
2136
2541
  state.scopeInitialized = true;
2137
2542
  state.chat = null; state.chats = []; state.archivedChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
2543
+ // A published filter answer still lands in its own project's conversation; reopening it resumes.
2544
+ for (const entry of state.filterPending.values()) clearTimeout(entry.timer);
2545
+ state.filterPending.clear(); state.filterNotices.clear(); state.filterCardMessages.clear();
2546
+ updateOffscreenActivity();
2138
2547
  state.historyFilter = 'all'; state.instructorAnswers = []; state.historyLoading = false; state.historyRequestGeneration += 1;
2139
2548
  state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
2140
2549
  if (!scope?.owner) { showUnscoped(); return; }
@@ -2156,6 +2565,7 @@
2156
2565
  // older, stale conversation is being recovered). Do not erase the scope and disable the
2157
2566
  // whole panel: the user can still start a new conversation in the project that is open.
2158
2567
  state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null;
2568
+ updateOffscreenActivity();
2159
2569
  ui.scope.textContent = scope.label;
2160
2570
  ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
2161
2571
  paintHistory(); paintUnread(); providerChooser();
@@ -2194,6 +2604,11 @@
2194
2604
  state.discoveryDraft = null;
2195
2605
  ui.input.dispatchEvent(new Event('input', { bubbles: true }));
2196
2606
  }
2607
+ if (state.pendingTeklaLibrary && state.chat?.chatId === chat.chatId) {
2608
+ state.teklaDraft = { chatId: chat.chatId, library: state.pendingTeklaLibrary, status: 'draft', error: null };
2609
+ state.pendingTeklaLibrary = null;
2610
+ paintTeklaChip();
2611
+ }
2197
2612
  announce(`${providerLabels[provider]} conversation created.`);
2198
2613
  } catch (error) { report(error, 'Could not start conversation'); }
2199
2614
  finally { setBusy(false); }
@@ -2273,6 +2688,7 @@
2273
2688
  state.historyOpen = open;
2274
2689
  shell.classList.toggle('history-open', open);
2275
2690
  ui.history.hidden = !open;
2691
+ updateOffscreenActivity();
2276
2692
  ui.historyToggle.setAttribute('aria-expanded', String(open));
2277
2693
  if (open) {
2278
2694
  ui.settings.hidden = true;
@@ -2281,7 +2697,7 @@
2281
2697
  if (state.historyFilter === 'instructor-answers') refreshInstructorAnswers(true);
2282
2698
  else refreshArchivedChats();
2283
2699
  } else if (options.focusToggle) ui.historyToggle.focus();
2284
- else ui.input.focus();
2700
+ else if (!options.keepFocus) ui.input.focus();
2285
2701
  }
2286
2702
 
2287
2703
  function closePicker() {
@@ -2327,7 +2743,7 @@
2327
2743
  function modelChoices() {
2328
2744
  const models = state.capability?.models || [];
2329
2745
  return models.map((model) => ({
2330
- id: `model:${model.id}`, label: model.label, meta: '',
2746
+ id: `model:${model.id}`, label: model.label, meta: model.detail || '',
2331
2747
  selected: (state.chat.settings.model || selectedModel()?.id) === model.id, patch: { model: model.id },
2332
2748
  }));
2333
2749
  }
@@ -2442,17 +2858,30 @@
2442
2858
  function updateSendState() {
2443
2859
  const active = turnIsVisiblyActive();
2444
2860
  const recovery = state.chat?.state === 'recovery';
2445
- const frozen = recovery || Boolean(state.chat?.activeTurn) || Boolean(state.chat?.archivedAt);
2861
+ const frozen = recovery || Boolean(state.chat?.activeTurn?.local) || Boolean(state.chat?.archivedAt);
2446
2862
  const blocked = requestExecutionBlocked();
2447
2863
  // A provider FloLess is still setting up cannot take a message; the runtime card explains why.
2448
2864
  const settingUp = Boolean(state.capability?.runtime && state.capability.runtime.state !== 'installed');
2449
2865
  const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
2450
- ui.input.disabled = !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
2451
- ui.send.disabled = state.loading || uploading || !state.chat || blocked || frozen
2866
+ ui.input.disabled = state.followupSubmitting || !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
2867
+ const filterMode = paintFilterComposer().state !== 'off';
2868
+ ui.send.disabled = state.loading || state.followupSubmitting || state.filterSending || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
2452
2869
  || (!ui.input.value.trim() && state.attachments.length === 0) || settingUp;
2453
- ui.attach.disabled = state.loading || uploading || !state.chat || blocked || frozen;
2870
+ // Drawing Filter messages carry the filter's own context, never attached files.
2871
+ ui.attach.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
2872
+ || filterMode;
2873
+ const unknownReason = state.followupUnknownId || hasUnknownFollowup()
2874
+ ? 'FloLess could not confirm a follow-up. Review that message before sending or attaching another file.' : null;
2875
+ const sendingReason = state.followupSubmitting
2876
+ ? 'FloLess is saving this message. Wait for its delivery status before sending another.'
2877
+ : state.filterSending ? 'FloLess is sending this message to the Drawing Filter. Wait for it to appear before sending another.' : null;
2878
+ for (const control of [ui.send, ui.attach]) {
2879
+ if (unknownReason || sendingReason) control.dataset.blockedReason = unknownReason || sendingReason;
2880
+ else delete control.dataset.blockedReason;
2881
+ }
2882
+ if (filterMode && !unknownReason && !sendingReason) ui.attach.dataset.blockedReason = 'Drawing Filter messages do not include attachments. Attach files from another tab.';
2454
2883
  ui.stop.hidden = !active || Boolean(state.chat?.activeTurn?.local);
2455
- ui.send.hidden = active;
2884
+ ui.send.hidden = false;
2456
2885
  // Session recovery must remain available even while provider capability discovery is loading
2457
2886
  // or has failed; it is the escape hatch for that exact state.
2458
2887
  ui.refresh.disabled = !state.chat;
@@ -2465,22 +2894,100 @@
2465
2894
  ui.input.style.height = `${Math.min(132, ui.input.scrollHeight)}px`;
2466
2895
  }
2467
2896
 
2897
+ function draftFitsStorage(owner, draft) {
2898
+ const encoder = new TextEncoder();
2899
+ // Match CHAT_STORE_LIMITS.maxDraftBytes and the draft route's bodyLimit.
2900
+ return !draft.includes('\u0000') && encoder.encode(draft).length <= 128 * 1024
2901
+ && encoder.encode(JSON.stringify({ owner, draft })).length <= 129 * 1024;
2902
+ }
2903
+
2468
2904
  function saveDraftSoon() {
2469
2905
  clearTimeout(state.draftTimer);
2470
2906
  if (!state.chat) return;
2471
2907
  const chatId = state.chat.chatId;
2472
2908
  const draft = ui.input.value;
2473
- state.chat.draft = draft;
2909
+ state.localDraft = { chatId, text: draft };
2910
+ state.draftVersions.set(chatId, (state.draftVersions.get(chatId) || 0) + 1);
2911
+ // Keep the newest local text until the matching server write succeeds.
2912
+ // This also preserves an unsavable draft when the user switches chats.
2913
+ state.backgroundDrafts.set(chatId, draft);
2914
+ if (!draftFitsStorage(state.scope.owner, draft)) return;
2474
2915
  state.draftTimer = setTimeout(async () => {
2475
2916
  if (state.chat?.chatId !== chatId) return;
2476
2917
  try {
2477
- await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/draft`, {
2478
- method: 'PUT', body: JSON.stringify({ owner: state.scope.owner, draft }),
2479
- });
2918
+ await writeChatDraft(chatId, state.scope.owner, draft);
2480
2919
  } catch (error) { report(error, 'Draft was not saved'); }
2481
2920
  }, 350);
2482
2921
  }
2483
2922
 
2923
+ async function writeChatDraft(chatId, owner, draft) {
2924
+ if (!draftFitsStorage(owner, draft)) return;
2925
+ const version = state.draftVersions.get(chatId) || 0;
2926
+ const previous = state.draftWrites.get(chatId) || Promise.resolve();
2927
+ const write = previous.catch(() => {}).then(() => request(`/api/chat/conversations/${encodeURIComponent(chatId)}/draft`, {
2928
+ method: 'PUT', body: JSON.stringify({ owner, draft }),
2929
+ }));
2930
+ state.draftWrites.set(chatId, write);
2931
+ try {
2932
+ await write;
2933
+ if (state.draftVersions.get(chatId) === version && state.backgroundDrafts.get(chatId) === draft) state.backgroundDrafts.delete(chatId);
2934
+ }
2935
+ finally { if (state.draftWrites.get(chatId) === write) state.draftWrites.delete(chatId); }
2936
+ }
2937
+
2938
+ async function restoreBackgroundDraft(snapshot, text, submissionId) {
2939
+ let existing = '';
2940
+ if (state.chat?.chatId === snapshot.chatId) {
2941
+ if (state.events.some(event => event.type === 'user-message' && event.clientSubmissionId === submissionId)) return;
2942
+ existing = ui.input.value;
2943
+ } else {
2944
+ // The user can type and save a newer draft in A, leave A again, and only
2945
+ // then receive A's refusal. Read A's latest saved draft before restoring.
2946
+ try {
2947
+ await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
2948
+ const latest = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}?${ownerQuery(snapshot.scope.owner)}`);
2949
+ existing = latest.draft || '';
2950
+ } catch (error) { console.error('[chat] could not read the newer draft before restoration:', error); }
2951
+ // A pending local draft is the full composer value and is newer than a
2952
+ // server draft from before the debounce. Use it once, never append it to
2953
+ // an older prefix or append the same local value a second time.
2954
+ if (state.backgroundDrafts.has(snapshot.chatId)) existing = state.backgroundDrafts.get(snapshot.chatId);
2955
+ if (state.localDraft?.chatId === snapshot.chatId) existing = state.localDraft.text;
2956
+ }
2957
+ // A can become selected again, or receive newer typing, while the draft
2958
+ // read above is in flight. Recheck the live composer after the await.
2959
+ if (state.chat?.chatId === snapshot.chatId) {
2960
+ if (state.events.some(event => event.type === 'user-message' && event.clientSubmissionId === submissionId)) return;
2961
+ existing = ui.input.value;
2962
+ } else if (state.localDraft?.chatId === snapshot.chatId) {
2963
+ existing = state.localDraft.text;
2964
+ }
2965
+ const merged = Boolean(existing.trim() && existing.trim() !== text.trim());
2966
+ if (merged) text = `${existing}\n\nEarlier unsent message:\n${text}`;
2967
+ if (state.chat?.chatId === snapshot.chatId) {
2968
+ clearTimeout(state.draftTimer);
2969
+ if (ui.input.value !== text) {
2970
+ ui.input.value = text;
2971
+ autosize(); updateSendState();
2972
+ }
2973
+ announce(merged ? 'An earlier unsent message was added to your draft. Review it before sending.'
2974
+ : 'The message was not sent. Its text is back in your draft.');
2975
+ state.localDraft = { chatId: snapshot.chatId, text };
2976
+ }
2977
+ state.draftVersions.set(snapshot.chatId, (state.draftVersions.get(snapshot.chatId) || 0) + 1);
2978
+ state.backgroundDrafts.set(snapshot.chatId, text);
2979
+ try {
2980
+ await writeChatDraft(snapshot.chatId, snapshot.scope.owner, text);
2981
+ } catch (error) { console.error('[chat] could not save a refused message as a draft:', error); }
2982
+ }
2983
+
2984
+ function initialTurnDefinitelyRefused(error) {
2985
+ return sessionNeedsRenewal(error) || error?.status === 413 || error?.status === 400
2986
+ || ['chat-provider-unavailable', 'chat-turn-active', 'chat-turn-settling', 'chat-followup-queued', 'chat-followup-unconfirmed',
2987
+ 'chat-owner-busy', 'chat-host-busy', 'chat-attachment-scope',
2988
+ 'chat-root-stale', 'chat-archived'].includes(String(error?.code || ''));
2989
+ }
2990
+
2484
2991
  function paintSkills() {
2485
2992
  ui.skills.replaceChildren();
2486
2993
  const match = ui.input.value.slice(0, ui.input.selectionStart).match(/(?:^|\s)\/([A-Za-z0-9:_-]*)$/u);
@@ -2505,10 +3012,578 @@
2505
3012
  ui.skills.hidden = false;
2506
3013
  }
2507
3014
 
3015
+ // ── Drawing Filter help ────────────────────────────────────────────────────────────────────────
3016
+ // While the Drawing Filter is the visible surface, this composer sends a read-only guide request
3017
+ // about the filter instead of a normal turn, and its answer is published into this conversation.
3018
+ // The filter page (its iframe) owns the drawing, the selection and every Apply / Undo / Keep guard;
3019
+ // for anything about the drawing this chat only relays through `window.__floFilterAi`. The chat owns
3020
+ // linking, starting and polling the request itself.
3021
+ // There is no mode to choose: the person just asks or says what to change. Every message is sent as
3022
+ // a request that may suggest ticks, and a review card appears only when the answer does.
3023
+ const FILTER_PLACEHOLDER = 'Ask about this filter, or say what to change…';
3024
+ const FILTER_PENDING = 'AI is reading the filter…';
3025
+ const DEFAULT_PLACEHOLDER = ui.input.placeholder;
3026
+ const FILTER_NOT_OPEN = 'Open Drawing Filter to use this suggestion.';
3027
+ // Mirrors the filter page's own FILTER_AI_UNKNOWN: with no page at all, its records are gone too.
3028
+ 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.';
3029
+ // Codes the start route (/api/chat/requests/:id/start) returns before it writes a link; a 400 counts
3030
+ // too, and an expired chat session is renewed and retried. Only when every attempt was definitely
3031
+ // refused does sendFilterAi clean the request up. After any other failure the request is never
3032
+ // deleted: it continues only if Requests shows the link, and otherwise stays in Requests.
3033
+ const FILTER_LINK_REFUSALS = new Set(['request-chat-unavailable', 'request-chat-owner-changed']);
3034
+ const FILTER_LINK_REFUSAL_COPY = {
3035
+ // One code for several causes (a reply started, archived, another provider), so no cause is named.
3036
+ '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.',
3037
+ 'request-chat-owner-changed': 'The project changed while FloLess was sending this. Open the project again, then send it once more. Nothing was sent.',
3038
+ };
3039
+ const FILTER_CREATE_TIMEOUT = 'FloLess did not answer in time, so this request may not have started. Check Requests before sending it again.';
3040
+ // One cause-free pair for every failed answer check: a slow server, a dropped connection and a bug
3041
+ // look the same from here.
3042
+ const FILTER_CHECK_RETRY = 'FloLess could not check the answer yet. Trying again.';
3043
+ 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.';
3044
+ let filterBridgeWarned = false;
3045
+
3046
+ function filterRefusal(message) {
3047
+ return Object.assign(new Error(message), { filterRefusal: true });
3048
+ }
3049
+
3050
+ /** A broken filter page is a bug worth one console line, not a silent "still loading" forever. */
3051
+ function warnFilterBridge(error) {
3052
+ if (filterBridgeWarned) return;
3053
+ filterBridgeWarned = true;
3054
+ console.error('[chat] the Drawing Filter page did not answer AI Chat:', error);
3055
+ }
3056
+
3057
+ /**
3058
+ * Whether the composer is in Drawing Filter mode depends on the visible surface. A filter page that
3059
+ * has not finished loading means 'loading' (Send refuses, never a normal turn); only the page's own
3060
+ * empty screen ('unavailable') drops back to a normal chat.
3061
+ */
3062
+ function filterSurface() {
3063
+ if (currentSurface() !== 'drawing-filter') return { state: 'off' };
3064
+ const frame = document.getElementById('ws-frame-drawings');
3065
+ if (!frame || !String(frame.dataset.want || '').startsWith('/steel-filter.html')) return { state: 'off' };
3066
+ let bridge = null;
3067
+ let summary = null;
3068
+ try {
3069
+ bridge = frame.contentWindow?.__floFilterAi || null;
3070
+ summary = bridge ? bridge.summary() : null;
3071
+ } catch (error) { warnFilterBridge(error); bridge = null; summary = null; }
3072
+ if (!bridge || !summary || summary.state === 'loading') return { state: 'loading' };
3073
+ if (summary.state !== 'ready') return { state: 'off' };
3074
+ return { state: 'ready', bridge, summary };
3075
+ }
3076
+
3077
+ /** The composer's only Drawing Filter cue is its placeholder; returns the surface for the caller. */
3078
+ function paintFilterComposer() {
3079
+ const surface = filterSurface();
3080
+ ui.input.placeholder = surface.state === 'off' ? DEFAULT_PLACEHOLDER : FILTER_PLACEHOLDER;
3081
+ return surface;
3082
+ }
3083
+
3084
+ function filterPendingIn(chatId) {
3085
+ return [...state.filterPending.values()].some((entry) => entry.chatId === chatId);
3086
+ }
3087
+
3088
+ function filterAnswered(requestId) {
3089
+ return state.events.some((event) => event.type === 'assistant-message' && event.payload?.requestId === requestId);
3090
+ }
3091
+
3092
+ /** Why a filter message cannot be sent right now, or null. Checked before the draft is touched. */
3093
+ function filterSendRefusal(surface, text) {
3094
+ const chat = state.chat;
3095
+ if (surface.state !== 'ready') return 'The Drawing Filter is still loading. Wait until its layers appear, then send again. Nothing was sent.';
3096
+ if (turnIsVisiblyActive(chat) || chat.activeTurn) return 'Wait for the current AI reply to finish before asking about the filter. Your message was not sent.';
3097
+ if (filterPendingIn(chat.chatId)) return 'Wait for the current Drawing Filter answer before sending another. Your message was not sent.';
3098
+ if (state.attachments.length) return 'Attachments are not sent with Drawing Filter messages. Remove them to send this message, or send them from another tab.';
3099
+ // Counted exactly as the filter page counts it, so the two limits can never disagree.
3100
+ if (text.length > 300) return 'Shorten your message to 300 characters, then send it again. Nothing was sent.';
3101
+ return null;
3102
+ }
3103
+
3104
+ function filterAccessFailure(status, detail) {
3105
+ if (status === 401 || detail?.reason === 'session-expired') return 'Your FloLess sign-in expired. Sign in again, then send your message again. Nothing changed.';
3106
+ if (detail?.reason === 'signed-out') return 'You are signed out of FloLess. Sign in, then send your message again. Nothing changed.';
3107
+ 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.';
3108
+ if (detail?.reason === 'no-subscription') return 'Your FloLess subscription is not active. Restore access, then send your message again. Nothing changed.';
3109
+ return 'FloLess could not access this answer. Check your sign-in and project access, then send your message again. Nothing changed.';
3110
+ }
3111
+
3112
+ /** Start the read-only guide run. Resolves 'started', 'unconfirmed' (checking), or { refused: message }. */
3113
+ async function startFilterRun(requestId, runtime) {
3114
+ const controller = new AbortController();
3115
+ const deadline = setTimeout(() => controller.abort(), 15000);
3116
+ let started;
3117
+ try {
3118
+ started = await fetch(`/api/requests/${encodeURIComponent(requestId)}/run`, {
3119
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ runtime }), signal: controller.signal,
3120
+ });
3121
+ } catch { clearTimeout(deadline); return 'unconfirmed'; } // the server may have accepted it before the reply was lost
3122
+ if (started.ok) { clearTimeout(deadline); return 'started'; }
3123
+ const detail = await started.json().catch(() => null);
3124
+ clearTimeout(deadline);
3125
+ if (started.status === 409 && detail?.code === 'running') return 'started';
3126
+ if (detail?.code === 'filter-ai-provider-mismatch' && typeof detail.error === 'string') return { refused: detail.error };
3127
+ if ((started.status === 409 && !detail) || started.status >= 500) return 'unconfirmed';
3128
+ if ([401, 402, 403].includes(started.status)) return { refused: filterAccessFailure(started.status, detail) };
3129
+ // Several refusals land here, each with a different cause, so the sentence names none of them.
3130
+ return { refused: 'FloLess could not start AI for this request. Nothing changed. Send it again from AI Chat.' };
3131
+ }
3132
+
3133
+ /**
3134
+ * Request events (the linked question and the published answer) are written straight to the
3135
+ * conversation store and never reach the live event stream, so read them back explicitly.
3136
+ * Resolves true once the conversation was read.
3137
+ */
3138
+ async function mergeFilterEvents(chatId) {
3139
+ if (state.chat?.chatId !== chatId || !state.scope?.owner) return false;
3140
+ const snapshot = captureChat();
3141
+ const path = `/api/chat/conversations/${encodeURIComponent(chatId)}/events-snapshot?${ownerQuery(snapshot.scope.owner)}`;
3142
+ let listed;
3143
+ try {
3144
+ try { listed = await request(path); }
3145
+ catch (error) {
3146
+ // The chat session is short-lived; renew it once, as refreshConversation does.
3147
+ if (!sessionNeedsRenewal(error)) throw error;
3148
+ state.sessionReady = false;
3149
+ await ensureSession();
3150
+ listed = await request(path);
3151
+ }
3152
+ } catch (error) {
3153
+ console.error('[chat] could not read back the Drawing Filter messages:', error);
3154
+ return false;
3155
+ }
3156
+ if (!sameChat(snapshot)) return false;
3157
+ let added = false;
3158
+ for (const event of listed.events || []) {
3159
+ if (state.events.some((item) => item.eventId === event.eventId)) continue;
3160
+ state.events.push(event); added = true;
3161
+ }
3162
+ if (added) {
3163
+ state.events.sort((a, b) => a.sequence - b.sequence);
3164
+ state.chat.lastEventSequence = Math.max(state.chat.lastEventSequence || 0, ...state.events.map((event) => event.sequence || 0));
3165
+ paintEvents({ forceBottom: true });
3166
+ }
3167
+ return true;
3168
+ }
3169
+
3170
+ /** After an uncertain link: true only when Requests records this request linked to this conversation. */
3171
+ async function filterRequestLinked(requestId, chatId) {
3172
+ // Send stays blocked meanwhile, so this read is bounded; a slow list simply proves nothing.
3173
+ const listed = await fetch('/api/requests', { signal: AbortSignal.timeout(30000) })
3174
+ .then((response) => (response.ok ? response.json() : null)).catch(() => null);
3175
+ const row = Array.isArray(listed?.requests) ? listed.requests.find((candidate) => candidate?.id === requestId) : null;
3176
+ return row?.chatConversation?.chatId === chatId;
3177
+ }
3178
+
3179
+ function finishFilterPending(entry, notice) {
3180
+ if (state.filterPending.get(entry.requestId) !== entry) return false;
3181
+ state.filterPending.delete(entry.requestId);
3182
+ if (notice) { state.filterNotices.set(entry.requestId, notice); announce(notice); }
3183
+ if (state.chat?.chatId === entry.chatId) { paintEvents(); updateSendState(); }
3184
+ return true;
3185
+ }
3186
+
3187
+ function filterPollRecovered(entry) {
3188
+ entry.failures = 0;
3189
+ if (entry.retryNote) { entry.retryNote = ''; if (state.chat?.chatId === entry.chatId) paintEvents(); }
3190
+ }
3191
+
3192
+ function filterPollFailure(entry, stopped = FILTER_CHECK_STOPPED, retrying = FILTER_CHECK_RETRY) {
3193
+ entry.failures += 1;
3194
+ if (entry.failures >= 3) { finishFilterPending(entry, stopped); return; }
3195
+ entry.retryNote = retrying;
3196
+ if (state.chat?.chatId === entry.chatId) paintEvents();
3197
+ }
3198
+
3199
+ /**
3200
+ * Check one pending request again after `delay`. Each request runs its own chain of checks, started
3201
+ * once by sendFilterAi or resumeFilterRequests, so a slow or broken request never holds up another.
3202
+ */
3203
+ function scheduleFilterPoll(entry, delay = 2000) {
3204
+ clearTimeout(entry.timer);
3205
+ entry.timer = setTimeout(() => { void pollFilterRequest(entry); }, delay);
3206
+ }
3207
+
3208
+ /** One bounded check of one request. While the request is still pending, the next check is scheduled. */
3209
+ async function pollFilterRequest(entry) {
3210
+ const current = () => state.filterPending.get(entry.requestId) === entry;
3211
+ try {
3212
+ const query = new URLSearchParams({ app: entry.appId || '', ...(entry.project ? { project: entry.project } : {}) });
3213
+ const response = await fetch(`/api/filter-ai-answer/${encodeURIComponent(entry.requestId)}?${query}`,
3214
+ { signal: AbortSignal.timeout(15000) }).catch(() => null);
3215
+ if (!current()) return;
3216
+ if (!response) { filterPollFailure(entry); return; }
3217
+ if (response.status === 401 || response.status === 403) { finishFilterPending(entry, filterAccessFailure(response.status)); return; }
3218
+ if (response.status === 402) {
3219
+ const detail = await response.json().catch(() => null);
3220
+ if (current()) finishFilterPending(entry, filterAccessFailure(402, detail));
3221
+ return;
3222
+ }
3223
+ const result = response.ok ? await response.json().catch(() => null) : null;
3224
+ if (!current()) return;
3225
+ 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; }
3226
+ if (!result) { filterPollFailure(entry); return; }
3227
+ if (result.state === 'waiting') { filterPollRecovered(entry); return; }
3228
+ if (result.state === 'failed') { finishFilterPending(entry, result.error || 'AI could not answer this. Send it again. The filter has not changed.'); return; }
3229
+ // Reading Requests is what publishes a validated answer into its linked conversation. It lists
3230
+ // every request and can be slow on a busy machine, so its bound is generous.
3231
+ const listed = await fetch('/api/requests', { signal: AbortSignal.timeout(90000) })
3232
+ .then((res) => (res.ok ? res.json() : null)).catch(() => null);
3233
+ if (!current()) return;
3234
+ if (!Array.isArray(listed?.chatPublications)) {
3235
+ filterPollFailure(entry,
3236
+ '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.',
3237
+ 'The answer is ready. FloLess could not confirm whether it was added yet. Trying again.');
3238
+ return;
3239
+ }
3240
+ filterPollRecovered(entry);
3241
+ const published = listed.chatPublications.some((publication) => publication?.requestId === entry.requestId);
3242
+ const here = state.chat?.chatId === entry.chatId;
3243
+ if (here) await mergeFilterEvents(entry.chatId);
3244
+ if (!current()) return;
3245
+ // Done once the answer is on screen, or published into a conversation that is not open here.
3246
+ if ((here && filterAnswered(entry.requestId)) || (!here && published)) { finishFilterPending(entry, null); return; }
3247
+ // Publication and the read-back can lag the answer; the next checks try again before saying so.
3248
+ entry.readBack = (entry.readBack || 0) + 1;
3249
+ if (entry.readBack < 5) return;
3250
+ finishFilterPending(entry, published
3251
+ ? 'The answer was added to this conversation but could not be shown here. Reopen the conversation to see it.'
3252
+ : 'The answer is ready but FloLess could not add it to this conversation. Open Requests to read it.');
3253
+ } catch (error) {
3254
+ // A bug in this check counts as a failed check, so it still stops after three instead of looping.
3255
+ console.error('[chat] checking a Drawing Filter answer failed:', error);
3256
+ if (current()) filterPollFailure(entry);
3257
+ } finally {
3258
+ if (current()) scheduleFilterPoll(entry);
3259
+ }
3260
+ }
3261
+
3262
+ /**
3263
+ * After a reload or reopening a project conversation, keep watching its unanswered filter requests:
3264
+ * the newest five that show neither an answer nor a failure notice from this page session.
3265
+ */
3266
+ function resumeFilterRequests() {
3267
+ const chat = state.chat;
3268
+ if (!chat || state.scope?.owner?.kind !== 'project') return;
3269
+ const unanswered = state.events.filter((event) => event.type === 'user-message' && event.payload?.filterAi
3270
+ && event.payload.requestId && !filterAnswered(event.payload.requestId)
3271
+ && !state.filterPending.has(event.payload.requestId) && !state.filterNotices.has(event.payload.requestId)).slice(-5);
3272
+ for (const event of unanswered) {
3273
+ const entry = {
3274
+ requestId: event.payload.requestId, chatId: chat.chatId, kind: event.payload.filterAi.kind,
3275
+ appId: event.payload.filterAi.appId || '', project: state.scope.owner.projectId, failures: 0, note: '',
3276
+ };
3277
+ state.filterPending.set(entry.requestId, entry);
3278
+ scheduleFilterPoll(entry, 0);
3279
+ }
3280
+ }
3281
+
3282
+ async function sendFilterAi(surface) {
3283
+ const snapshot = captureChat();
3284
+ if (!snapshot || state.filterSending) return;
3285
+ const chat = state.chat;
3286
+ const kind = 'change';
3287
+ const text = ui.input.value.trim();
3288
+ if (!text) return;
3289
+ const refusal = filterSendRefusal(surface, text);
3290
+ if (refusal) { report(filterRefusal(refusal)); return; }
3291
+ // The draft is set aside before the first await, as a normal Send does: anything typed from here
3292
+ // on is newer than the submitted message and must survive whatever happens to it.
3293
+ // restoreBackgroundDraft skips a message the conversation already shows under this id; a Drawing
3294
+ // Filter message carries none, so a fresh id means the refused text is always given back.
3295
+ const submissionId = crypto.randomUUID();
3296
+ clearTimeout(state.draftTimer);
3297
+ state.localDraft = { chatId: snapshot.chatId, text: '' };
3298
+ state.backgroundDrafts.delete(snapshot.chatId);
3299
+ ui.input.value = ''; autosize();
3300
+ state.filterSending = true; updateSendState();
3301
+ let requestId = null;
3302
+ let failure = null;
3303
+ try {
3304
+ await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
3305
+ const options = await window.flolessBridge?.readOnlyRequestOptions?.().catch(() => null);
3306
+ if (!Array.isArray(options?.found)) {
3307
+ throw filterRefusal('FloLess could not check which AI can answer Drawing Filter messages. Try again in a moment. Nothing was sent.');
3308
+ }
3309
+ // Answer only with this conversation's own provider, never a silently substituted one.
3310
+ if (!options.found.some((runtime) => runtime?.id === chat.provider)) {
3311
+ 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.`);
3312
+ }
3313
+ // The promise belongs to the filter page. A page thrown away mid-request never settles it, so
3314
+ // the chat keeps its own deadline rather than leaving Send blocked in every conversation.
3315
+ const created = await Promise.race([
3316
+ surface.bridge.createRequest(kind, text),
3317
+ new Promise((resolve) => { setTimeout(resolve, 20000, { ok: false, message: FILTER_CREATE_TIMEOUT }); }),
3318
+ ]);
3319
+ if (!created?.ok) {
3320
+ throw filterRefusal([401, 402, 403].includes(created?.status)
3321
+ ? filterAccessFailure(created.status, { reason: created.reason })
3322
+ : created?.message || 'FloLess could not start this request. Nothing was sent.');
3323
+ }
3324
+ requestId = created.request.id;
3325
+ let linked = false;
3326
+ let uncertain = false;
3327
+ let linkError = null;
3328
+ for (let attempt = 0; attempt < 2 && !linked; attempt++) {
3329
+ try {
3330
+ await request(`/api/chat/requests/${encodeURIComponent(requestId)}/start`, {
3331
+ method: 'POST', timeoutMs: 10000,
3332
+ body: JSON.stringify({ provider: chat.provider, mode: 'discuss', chatId: snapshot.chatId, expectedOwner: snapshot.scope.owner }),
3333
+ });
3334
+ linked = true;
3335
+ } catch (error) {
3336
+ linkError = error;
3337
+ if (sessionNeedsRenewal(error)) { state.sessionReady = false; await ensureSession().catch(() => {}); continue; }
3338
+ // A definite refusal stops retrying. It only proves nothing was linked when no earlier attempt
3339
+ // was uncertain: a retry's refusal can follow a first attempt that did persist the link
3340
+ // (another tab started a turn). `uncertain` never resets.
3341
+ if (FILTER_LINK_REFUSALS.has(String(error?.code || '')) || error?.status === 400) break;
3342
+ uncertain = true;
3343
+ }
3344
+ }
3345
+ if (!linked && uncertain) {
3346
+ // Only proof of the link lets it continue. No link yet proves nothing: the lost attempt may still
3347
+ // be writing it, so nothing is deleted and the request stays in Requests.
3348
+ if (!(await filterRequestLinked(requestId, snapshot.chatId))) {
3349
+ throw filterRefusal('FloLess could not confirm whether this message reached AI Chat. Check Requests before sending it again.');
3350
+ }
3351
+ linked = true;
3352
+ }
3353
+ if (!linked) {
3354
+ try { surface.bridge.forget(requestId); } catch { /* the filter reloaded; it has no record */ }
3355
+ const cleared = await fetch(`/api/requests/${encodeURIComponent(requestId)}`, { method: 'DELETE', signal: AbortSignal.timeout(10000) })
3356
+ .then((response) => response.ok).catch(() => false);
3357
+ const why = FILTER_LINK_REFUSAL_COPY[String(linkError?.code || '')]
3358
+ || 'FloLess could not add this message to the conversation. Nothing was sent. Send it again.';
3359
+ throw filterRefusal(cleared ? why : `${why} The unsent request is still listed in Requests; you can clear it there.`);
3360
+ }
3361
+ // Linked durably, but the saved draft still holds the sent words. Rewrite it now rather than on
3362
+ // saveDraftSoon's debounce, so a reload cannot bring the sent message back; the composer's current
3363
+ // text (empty, or typed during creation or linking) is what survives.
3364
+ const draft = sameChat(snapshot) ? ui.input.value : state.backgroundDrafts.get(snapshot.chatId) ?? '';
3365
+ if (sameChat(snapshot)) {
3366
+ clearTimeout(state.draftTimer);
3367
+ state.localDraft = { chatId: snapshot.chatId, text: draft };
3368
+ }
3369
+ state.draftVersions.set(snapshot.chatId, (state.draftVersions.get(snapshot.chatId) || 0) + 1);
3370
+ state.backgroundDrafts.set(snapshot.chatId, draft);
3371
+ if (draftFitsStorage(snapshot.scope.owner, draft)) {
3372
+ void writeChatDraft(snapshot.chatId, snapshot.scope.owner, draft)
3373
+ .catch((error) => { if (sameChat(snapshot)) report(error, 'Draft was not saved'); });
3374
+ }
3375
+ const entry = { requestId, chatId: snapshot.chatId, kind, appId: created.request.appId || '', project: created.request.project || '', failures: 0, note: '' };
3376
+ state.filterPending.set(requestId, entry);
3377
+ state.filterNotices.delete(requestId);
3378
+ // Start AI first, so nothing between the link and the run can leave a linked request unstarted.
3379
+ const started = await startFilterRun(requestId, chat.provider);
3380
+ await mergeFilterEvents(snapshot.chatId);
3381
+ if (started?.refused) { finishFilterPending(entry, started.refused); return; }
3382
+ if (started === 'unconfirmed') entry.note = 'Checking whether AI started…';
3383
+ announce(FILTER_PENDING);
3384
+ if (sameChat(snapshot)) paintEvents({ forceBottom: true });
3385
+ scheduleFilterPoll(entry, 0);
3386
+ } catch (error) {
3387
+ failure = error;
3388
+ await restoreBackgroundDraft(snapshot, text, submissionId);
3389
+ } finally {
3390
+ state.filterSending = false;
3391
+ // updateSendState() repaints the hint, so the refusal is reported after it, not before.
3392
+ if (sameChat(snapshot)) {
3393
+ updateSendState();
3394
+ if (failure) report(failure, failure.filterRefusal ? '' : 'Message was not sent');
3395
+ }
3396
+ }
3397
+ }
3398
+
3399
+ function filterChangeLabel(item) {
3400
+ if (item.dimension === 'thickness') return `line weight ${item.value} pt`;
3401
+ return `${item.dimension} ${item.value}`;
3402
+ }
3403
+
3404
+ function filterModeLabel(value) {
3405
+ return String(value).split('+').map((dim) => ({ thickness: 'line weight', layer: 'layer', color: 'color' }[dim] || dim)).join(', ');
3406
+ }
3407
+
3408
+ /**
3409
+ * Ask the filter page about one suggestion. Its record is read even while another tab is showing,
3410
+ * so the card shows what this page did with it; acting on it needs the Drawing Filter visible (`open`).
3411
+ * No page at all (not opened since this window loaded, or reloading) means the page that recorded
3412
+ * the suggestion is gone, exactly like an unknown record.
3413
+ */
3414
+ function inspectFilterSuggestion(requestId, proposal) {
3415
+ let bridge = null;
3416
+ try { bridge = document.getElementById('ws-frame-drawings')?.contentWindow?.__floFilterAi || null; }
3417
+ catch (error) { warnFilterBridge(error); }
3418
+ let info = null;
3419
+ try { info = bridge ? bridge.inspect(requestId, proposal) : null; } catch (error) { warnFilterBridge(error); }
3420
+ if (!info) return { known: false, applicable: false, reason: FILTER_PAGE_GONE, open: false };
3421
+ const open = filterSurface().state === 'ready';
3422
+ // An unknown record keeps its own reason: opening the Drawing Filter would not bring it back.
3423
+ if (open || !info.known) return { ...info, open };
3424
+ return { ...info, open, applicable: false, reason: FILTER_NOT_OPEN };
3425
+ }
3426
+
3427
+ function filterActionButton(label, action, requestId, className, blockedReason) {
3428
+ const control = button(label, `shell.chat-filter-${action}#${requestId}`, className);
3429
+ control.dataset.commandInstanceLabel = 'Drawing Filter suggestion';
3430
+ if (blockedReason) {
3431
+ control.setAttribute('aria-disabled', 'true');
3432
+ control.dataset.tip = blockedReason;
3433
+ control.dataset.blockedReason = blockedReason;
3434
+ }
3435
+ return control;
3436
+ }
3437
+
3438
+ function paintFilterSuggestion(card, event) {
3439
+ const requestId = String(event.payload.requestId || '');
3440
+ const proposal = event.payload.filterAi.proposal;
3441
+ const hasChanges = proposal.changes.length > 0 || proposal.mode !== null;
3442
+ const info = inspectFilterSuggestion(requestId, proposal);
3443
+ const disposition = info.known ? info.disposition : 'pending';
3444
+ // An unknown record (reload, another window) claims no outcome, only that it predates this view.
3445
+ // "not saved" only while this suggestion's own Undo is live: Save and later edits retire it.
3446
+ const chip = card.querySelector('.ai-chat-filter-state');
3447
+ chip.textContent = !info.known ? 'from an earlier view' : {
3448
+ applied: info.undo ? 'applied, not saved' : 'applied', kept: 'not applied', undone: 'undone',
3449
+ }[disposition] || 'not applied';
3450
+ const status = card.querySelector('.ai-chat-filter-note');
3451
+ const override = state.filterCardMessages.get(requestId);
3452
+ // Why Apply is unavailable is visible text, not only the button's tooltip. The exception is a card
3453
+ // from an earlier view, which offers nothing at all: its chip says so, the tooltip says why, and
3454
+ // the reason stays readable to a screen reader instead of repeating on every old card.
3455
+ const earlier = !info.known && hasChanges && !override;
3456
+ if (earlier) chip.dataset.tip = info.reason || FILTER_PAGE_GONE; else delete chip.dataset.tip;
3457
+ status.classList.toggle('sr-only', earlier);
3458
+ status.textContent = override || (disposition !== 'pending' ? info.note : '')
3459
+ || (!hasChanges ? 'No selection changes suggested.' : info.applicable ? '' : info.reason || FILTER_NOT_OPEN);
3460
+ const actions = card.querySelector('.ai-chat-filter-actions');
3461
+ // Repaints run on every filter change; keep keyboard focus on the same control when it survives.
3462
+ const focused = actions.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
3463
+ actions.replaceChildren();
3464
+ if (!info.known) {
3465
+ // Nothing here can act on a suggestion this page never recorded; the note says why.
3466
+ } else if (disposition === 'pending' && hasChanges) {
3467
+ const unavailable = info.applicable ? null : info.reason || FILTER_NOT_OPEN;
3468
+ const keep = filterActionButton('Keep current', 'keep', requestId, 'ai-chat-filter-keep', info.known && info.open ? null : unavailable);
3469
+ const apply = filterActionButton('Apply selection', 'apply', requestId, 'ai-chat-filter-apply', unavailable);
3470
+ keep.addEventListener('click', () => runFilterSuggestionAction('keep', event));
3471
+ apply.addEventListener('click', () => runFilterSuggestionAction('apply', event));
3472
+ actions.append(keep, apply);
3473
+ } else if (disposition === 'applied' && info.undo) {
3474
+ const undo = filterActionButton('Undo', 'undo', requestId, 'ai-chat-filter-keep', info.open ? null : FILTER_NOT_OPEN);
3475
+ undo.addEventListener('click', () => runFilterSuggestionAction('undo', event));
3476
+ actions.append(undo);
3477
+ }
3478
+ actions.hidden = !actions.childNodes.length;
3479
+ if (focused) [...actions.children].find((control) => control.dataset.commandId === focused)?.focus({ preventScroll: true });
3480
+ }
3481
+
3482
+ function runFilterSuggestionAction(action, event) {
3483
+ const requestId = String(event.payload.requestId || '');
3484
+ // Re-resolve the page at click time: the frame may have reloaded since this card was painted.
3485
+ const surface = filterSurface();
3486
+ let result;
3487
+ if (surface.state !== 'ready') result = { ok: false, message: FILTER_NOT_OPEN };
3488
+ else {
3489
+ try {
3490
+ result = action === 'apply' ? surface.bridge.apply(requestId, event.payload.filterAi.proposal)
3491
+ : action === 'undo' ? surface.bridge.undo(requestId) : surface.bridge.keep(requestId);
3492
+ } catch (error) {
3493
+ console.error('[chat] the Drawing Filter could not finish a suggestion action:', error);
3494
+ result = { ok: false, message: 'FloLess could not finish this in the Drawing Filter. Check its ticks before you save, and reload the Drawing Filter if they look wrong.' };
3495
+ }
3496
+ }
3497
+ if (result?.ok) state.filterCardMessages.delete(requestId);
3498
+ else state.filterCardMessages.set(requestId, result?.message || FILTER_NOT_OPEN);
3499
+ announce(result?.message || FILTER_NOT_OPEN);
3500
+ refreshFilterCards();
3501
+ const card = ui.feed.querySelector(`.ai-chat-filter-card[data-request-id="${CSS.escape(requestId)}"]`);
3502
+ (card?.querySelector('.ai-chat-filter-actions button') || card?.querySelector('.ai-chat-filter-note'))?.focus({ preventScroll: true });
3503
+ }
3504
+
3505
+ function renderFilterSuggestion(event) {
3506
+ const proposal = event.payload.filterAi.proposal;
3507
+ const card = document.createElement('section');
3508
+ card.className = 'ai-chat-filter-card';
3509
+ card.dataset.requestId = String(event.payload.requestId || '');
3510
+ card.dataset.eventId = event.eventId;
3511
+ card.setAttribute('aria-label', 'Suggested filter changes');
3512
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
3513
+ const title = document.createElement('strong'); title.textContent = 'Suggested filter changes';
3514
+ const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state';
3515
+ head.append(title, chip);
3516
+ const list = document.createElement('ul'); list.className = 'ai-chat-filter-changes';
3517
+ for (const item of proposal.changes) {
3518
+ const row = document.createElement('li'); row.className = `ai-chat-filter-change ${item.on ? 'include' : 'exclude'}`;
3519
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-filter-change-glyph'; glyph.setAttribute('aria-hidden', 'true');
3520
+ row.append(glyph, document.createTextNode(`${item.on ? 'Include' : 'Exclude'} ${filterChangeLabel(item)}`));
3521
+ list.append(row);
3522
+ }
3523
+ if (proposal.mode !== null) {
3524
+ const row = document.createElement('li'); row.className = 'ai-chat-filter-change match';
3525
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-filter-change-glyph'; glyph.setAttribute('aria-hidden', 'true');
3526
+ row.append(glyph, document.createTextNode(`Match on ${filterModeLabel(proposal.mode)}`));
3527
+ list.append(row);
3528
+ }
3529
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-note'; note.tabIndex = -1;
3530
+ note.setAttribute('role', 'status');
3531
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
3532
+ card.append(head);
3533
+ if (list.childNodes.length) card.append(list);
3534
+ card.append(note, actions);
3535
+ paintFilterSuggestion(card, event);
3536
+ return card;
3537
+ }
3538
+
3539
+ function renderFilterAnswer(event) {
3540
+ const filterAi = event.payload.filterAi;
3541
+ const proposal = filterAi.kind === 'change' ? filterAi.proposal : null;
3542
+ const item = renderMessage(event, 'assistant', proposal ? proposal.explanation : payloadText(event));
3543
+ // An answer is just the message; the review card appears only when it suggests ticks.
3544
+ if (proposal && (proposal.changes.length || proposal.mode !== null)) item.append(renderFilterSuggestion(event));
3545
+ return item;
3546
+ }
3547
+
3548
+ function renderFilterQuestion(event) {
3549
+ // The person's own words, like any message; only a wait or a failure adds a line under them.
3550
+ const item = renderMessage(event, 'user', payloadText(event));
3551
+ const requestId = String(event.payload.requestId || '');
3552
+ const pending = state.filterPending.get(requestId);
3553
+ const notice = state.filterNotices.get(requestId);
3554
+ if (pending && !filterAnswered(requestId)) {
3555
+ const live = document.createElement('div'); live.className = 'ai-chat-live-status ai-chat-filter-pending';
3556
+ const label = document.createElement('span'); label.className = 'ai-chat-live-label';
3557
+ label.textContent = pending.retryNote || pending.note || FILTER_PENDING;
3558
+ live.append(animatedDots(), label);
3559
+ item.append(live);
3560
+ } else if (notice && !filterAnswered(requestId)) {
3561
+ const failed = document.createElement('p'); failed.className = 'ai-chat-filter-notice'; failed.setAttribute('role', 'status');
3562
+ failed.textContent = notice;
3563
+ item.append(failed);
3564
+ }
3565
+ return item;
3566
+ }
3567
+
3568
+ /** Re-read the live filter state for every visible suggestion card, in place. */
3569
+ function refreshFilterCards() {
3570
+ for (const card of ui.feed.querySelectorAll('.ai-chat-filter-card')) {
3571
+ const event = state.events.find((candidate) => candidate.eventId === card.dataset.eventId);
3572
+ if (event?.payload?.filterAi?.proposal) paintFilterSuggestion(card, event);
3573
+ }
3574
+ }
3575
+
2508
3576
  async function sendTurn() {
2509
3577
  if (!state.chat || ui.send.disabled) return;
3578
+ // On the Drawing Filter, Send asks about the filter; a filter-intended message is never sent as a
3579
+ // normal turn, not even while the filter page is still loading.
3580
+ const filter = filterSurface();
3581
+ if (filter.state !== 'off') { await sendFilterAi(filter); return; }
3582
+ if (turnIsVisiblyActive() && !state.chat.activeTurn?.local) { await sendFollowup(); return; }
2510
3583
  const snapshot = captureChat();
2511
3584
  if (!snapshot) return;
3585
+ // Bind a carried-over Tekla library first; a refused binding keeps the message unsent.
3586
+ if (!(await bindPendingTeklaRead(snapshot))) return;
2512
3587
  const text = ui.input.value.trim();
2513
3588
  const uiContext = currentFloLessContext();
2514
3589
  const chatId = snapshot.chatId;
@@ -2522,12 +3597,17 @@
2522
3597
  payload: { text, attachmentIds }, createdAt: new Date().toISOString(), optimistic: true,
2523
3598
  };
2524
3599
  clearTimeout(state.draftTimer);
3600
+ state.localDraft = { chatId, text: '' };
3601
+ state.backgroundDrafts.delete(chatId);
2525
3602
  state.pendingSubmissionId = clientSubmissionId;
2526
3603
  state.events.push(optimisticEvent);
2527
- state.chat = { ...previousChat, state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
3604
+ state.chat = { ...previousChat, draft: '', state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
2528
3605
  ui.input.value = ''; autosize(); state.attachments = []; paintAttachments();
2529
3606
  setBusy(true); paintConversation(); announce('Message sent.');
2530
3607
  try {
3608
+ // A debounced save already in flight must finish before the server clears
3609
+ // the draft while admitting this message.
3610
+ await state.draftWrites.get(chatId)?.catch(() => {});
2531
3611
  const result = await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/turns`, {
2532
3612
  method: 'POST', body: JSON.stringify({
2533
3613
  // The server alone appends this context to the provider copy. The submitted text and
@@ -2545,16 +3625,215 @@
2545
3625
  // The server accepts a turn only from a ready provider, so a warning from an earlier check is stale.
2546
3626
  if (!providerReady()) void loadCapability().then(() => { if (sameChat(snapshot)) { paintSettings(); updateSendState(); } });
2547
3627
  } catch (error) {
2548
- if (!sameChat(snapshot)) return;
3628
+ if (!sameChat(snapshot)) {
3629
+ if (initialTurnDefinitelyRefused(error)) await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
3630
+ return;
3631
+ }
2549
3632
  state.pendingSubmissionId = null;
2550
3633
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
2551
3634
  state.chat = previousChat;
2552
3635
  state.attachments = previousAttachments;
2553
- ui.input.value = text; autosize(); paintAttachments(); paintConversation();
3636
+ ui.input.value = text; autosize(); paintAttachments(); saveDraftSoon(); paintConversation();
2554
3637
  report(error, 'Message was not sent');
2555
3638
  } finally { if (sameChat(snapshot)) { setBusy(false); updateSendState(); } }
2556
3639
  }
2557
3640
 
3641
+ function followupDefinitelyRefused(error) {
3642
+ // Session rejection and body-size rejection happen before the route can save a row.
3643
+ return ['chat-followup-refused', 'chat-followup-save-failed'].includes(String(error?.code || ''))
3644
+ || sessionNeedsRenewal(error) || error?.status === 413;
3645
+ }
3646
+
3647
+ async function sendFollowup() {
3648
+ if (!state.chat || !turnIsVisiblyActive() || state.followupSubmitting) return;
3649
+ const snapshot = captureChat();
3650
+ if (!snapshot) return;
3651
+ const text = ui.input.value.trim();
3652
+ const attachmentIds = state.attachments.map((item) => item.attachmentId);
3653
+ if (!text && !attachmentIds.length) return;
3654
+ if (new TextEncoder().encode(text).length > 128 * 1024) {
3655
+ report({ code: 'chat-message-too-long' }, 'Message was not sent');
3656
+ return;
3657
+ }
3658
+ const clientSubmissionId = crypto.randomUUID();
3659
+ const previousAttachments = state.attachments;
3660
+ let failedDelivery = null;
3661
+ const optimisticEvent = {
3662
+ eventId: `local:${clientSubmissionId}`,
3663
+ sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
3664
+ chatId: snapshot.chatId, turnId: state.chat.activeTurn.turnId, clientSubmissionId,
3665
+ providerItemId: null, type: 'user-message',
3666
+ payload: { text, attachmentIds, followup: true, deliveryState: 'pending' },
3667
+ createdAt: new Date().toISOString(), optimistic: true,
3668
+ };
3669
+ clearTimeout(state.draftTimer);
3670
+ state.localDraft = { chatId: snapshot.chatId, text: '' };
3671
+ state.backgroundDrafts.delete(snapshot.chatId);
3672
+ state.followupSubmitting = true;
3673
+ state.chat.draft = '';
3674
+ state.events.push(optimisticEvent);
3675
+ ui.input.value = ''; autosize(); state.attachments = []; paintAttachments();
3676
+ paintEvents({ forceBottom: true }); updateSendState();
3677
+ try {
3678
+ await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
3679
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups`, {
3680
+ method: 'POST', body: JSON.stringify({
3681
+ owner: snapshot.scope.owner, clientSubmissionId, text,
3682
+ uiContext: currentFloLessContext(), attachmentIds,
3683
+ }),
3684
+ });
3685
+ if (!sameChat(snapshot)) return;
3686
+ state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
3687
+ for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
3688
+ state.events.sort((a, b) => a.sequence - b.sequence);
3689
+ state.chat = result.chat;
3690
+ announce(result.followup?.deliveryState === 'queued-next'
3691
+ ? 'Message queued for the next AI response.'
3692
+ : result.followup?.deliveryState === 'accepted'
3693
+ ? 'Follow-up sent to AI.'
3694
+ : result.followup?.deliveryState === 'not-sent'
3695
+ ? (result.followup?.deliveryFailure?.reason || 'FloLess could not finish saving this message. Use Retry sending if you still want to send it.')
3696
+ : 'Follow-up saved. Waiting for AI.');
3697
+ paintConversation();
3698
+ } catch (error) {
3699
+ if (!sameChat(snapshot)) {
3700
+ if (followupDefinitelyRefused(error)) await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
3701
+ else {
3702
+ optimisticEvent.payload.deliveryState = 'unknown';
3703
+ state.unknownFollowups.set(snapshot.chatId, { submissionId: clientSubmissionId, text, event: optimisticEvent });
3704
+ // The user may have selected A → B → A while this request was in flight.
3705
+ // The second A snapshot ran before the uncertain result existed, so reconcile it now.
3706
+ if (sameScope(snapshot.scope, snapshot.generation) && state.chat?.chatId === snapshot.chatId) {
3707
+ reconcileUnknownFollowupOnSelection(state.chat);
3708
+ paintEvents(); updateSendState();
3709
+ }
3710
+ }
3711
+ return;
3712
+ }
3713
+ if (state.events.some((event) => !event.optimistic && event.clientSubmissionId === clientSubmissionId
3714
+ && event.type === 'user-message')) {
3715
+ state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
3716
+ announce('Follow-up saved. Waiting for AI.'); paintEvents();
3717
+ return;
3718
+ }
3719
+ const definitiveRefusal = followupDefinitelyRefused(error);
3720
+ // A lost HTTP reply does not prove the provider missed the message. Keep the submission
3721
+ // visible and block another send until the saved receipt or a deliberate user action resolves it.
3722
+ if (definitiveRefusal) state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
3723
+ else {
3724
+ optimisticEvent.payload.deliveryState = 'unknown';
3725
+ state.followupUnknownId = clientSubmissionId;
3726
+ state.unknownFollowups.set(snapshot.chatId, { submissionId: clientSubmissionId, text, event: optimisticEvent });
3727
+ }
3728
+ // An uncertain request may already own these files. Keep them on its
3729
+ // message, and restore chips only when the server definitely refused it.
3730
+ state.attachments = definitiveRefusal ? previousAttachments : [];
3731
+ ui.input.value = text; autosize(); paintAttachments(); paintEvents();
3732
+ if (definitiveRefusal) saveDraftSoon();
3733
+ else state.localDraft = { chatId: snapshot.chatId, text };
3734
+ failedDelivery = { error, prefix: definitiveRefusal ? '' : 'Could not confirm the follow-up' };
3735
+ } finally {
3736
+ state.followupSubmitting = false;
3737
+ if (sameChat(snapshot)) {
3738
+ updateSendState();
3739
+ if (failedDelivery) report(failedDelivery.error, failedDelivery.prefix);
3740
+ if (document.activeElement === document.body || document.activeElement === ui.send) ui.input.focus();
3741
+ }
3742
+ }
3743
+ }
3744
+
3745
+ async function resolveUnknownFollowup(clientSubmissionId) {
3746
+ if (!state.chat || !clientSubmissionId) return;
3747
+ if (state.resolvingFollowupIds.has(clientSubmissionId)) return;
3748
+ const optimistic = state.events.find((event) => event.optimistic && event.clientSubmissionId === clientSubmissionId);
3749
+ if (optimistic) {
3750
+ optimistic.payload.deliveryState = 'dismissed';
3751
+ state.followupUnknownId = null;
3752
+ state.unknownFollowups.delete(state.chat.chatId);
3753
+ announce('Delivery is still unconfirmed. Review the draft before sending; sending it again may duplicate a message AI received.'
3754
+ + (optimistic.payload.attachmentIds?.length ? ' Attached files were not restored to the draft. Refresh the conversation to check whether they are still available before attaching them again.' : ''));
3755
+ paintEvents(); updateSendState();
3756
+ if (!ui.input.disabled) ui.input.focus();
3757
+ return;
3758
+ }
3759
+ const snapshot = captureChat();
3760
+ if (!snapshot) return;
3761
+ state.resolvingFollowupIds.add(clientSubmissionId);
3762
+ const button = [...ui.feed.querySelectorAll('.ai-chat-followup-resolve')]
3763
+ .find((candidate) => candidate.closest('[data-event-id]')?.dataset.eventId
3764
+ === state.events.find((event) => event.clientSubmissionId === clientSubmissionId && event.type === 'user-message')?.eventId);
3765
+ const focusAfterSuccess = document.activeElement === button;
3766
+ let resolved = false;
3767
+ if (button) button.disabled = true;
3768
+ try {
3769
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups/${encodeURIComponent(clientSubmissionId)}/resolve`, {
3770
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, resolution: 'continue-without-resending' }),
3771
+ });
3772
+ if (!sameChat(snapshot)) return;
3773
+ state.followupUnknownId = null;
3774
+ state.chat = result.chat;
3775
+ for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
3776
+ state.events.sort((a, b) => a.sequence - b.sequence);
3777
+ announce(result.followup?.deliveryState === 'accepted'
3778
+ ? 'AI had received this follow-up. You can continue.'
3779
+ : 'Delivery remains unconfirmed. FloLess will not resend this follow-up. You can continue.');
3780
+ paintConversation();
3781
+ resolved = true;
3782
+ } catch (error) {
3783
+ if (sameChat(snapshot)) { if (button) button.disabled = false; report(error, 'Could not continue without resending'); }
3784
+ } finally {
3785
+ state.resolvingFollowupIds.delete(clientSubmissionId);
3786
+ if (sameChat(snapshot)) {
3787
+ paintEvents();
3788
+ if (resolved && focusAfterSuccess && document.activeElement === document.body && !ui.input.disabled) ui.input.focus();
3789
+ }
3790
+ }
3791
+ }
3792
+
3793
+ async function retryNotSentFollowup(clientSubmissionId) {
3794
+ if (!state.chat || !clientSubmissionId || state.retryingFollowupIds.has(clientSubmissionId)) return;
3795
+ const snapshot = captureChat();
3796
+ if (!snapshot) return;
3797
+ const commandId = `shell.chat-followup-retry#${clientSubmissionId}`;
3798
+ const restoreFocusOnFailure = document.activeElement?.dataset?.commandId === commandId;
3799
+ let failed = false;
3800
+ let succeeded = false;
3801
+ state.retryingFollowupIds.add(clientSubmissionId);
3802
+ paintEvents();
3803
+ announce('Retrying this message. Your draft stays here.');
3804
+ try {
3805
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups/${encodeURIComponent(clientSubmissionId)}/retry`, {
3806
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner }),
3807
+ });
3808
+ if (!sameChat(snapshot)) return;
3809
+ state.chat = result.chat;
3810
+ for (const event of result.events || []) if (!state.events.some(item => item.eventId === event.eventId)) state.events.push(event);
3811
+ state.events.sort((a, b) => a.sequence - b.sequence);
3812
+ announce(result.followup?.deliveryState === 'accepted' ? 'Retry sent to AI.'
3813
+ : result.followup?.deliveryState === 'not-sent'
3814
+ ? (result.followup?.deliveryFailure?.reason || 'FloLess could not start this retry. Check the conversation, then use Retry sending if you still want to send it.')
3815
+ : 'Retry queued for AI. Your draft is unchanged.');
3816
+ paintConversation();
3817
+ succeeded = true;
3818
+ } catch (error) {
3819
+ failed = true;
3820
+ if (sameChat(snapshot)) report(error,
3821
+ followupDefinitelyRefused(error)
3822
+ || ['chat-followup-queued', 'chat-followup-retry-wait', 'chat-followup-retry-unavailable', 'chat-attachment-scope'].includes(String(error?.code || ''))
3823
+ ? '' : 'Could not confirm the retry. Check the conversation before retrying again');
3824
+ } finally {
3825
+ state.retryingFollowupIds.delete(clientSubmissionId);
3826
+ if (sameChat(snapshot)) {
3827
+ paintEvents();
3828
+ if (failed && restoreFocusOnFailure) {
3829
+ [...ui.feed.querySelectorAll('.ai-chat-followup-resolve')]
3830
+ .find(button => button.dataset.commandId === commandId)?.focus();
3831
+ }
3832
+ if (succeeded && restoreFocusOnFailure && document.activeElement === document.body && !ui.input.disabled) ui.input.focus();
3833
+ }
3834
+ }
3835
+ }
3836
+
2558
3837
  async function stopTurn() {
2559
3838
  if (!state.chat?.activeTurn) return;
2560
3839
  const snapshot = captureChat();
@@ -2751,16 +4030,27 @@
2751
4030
  }
2752
4031
 
2753
4032
  async function attachFiles(files) {
2754
- if (!state.chat || state.chat.activeTurn) return;
4033
+ if (!state.chat || state.chat.activeTurn?.local || state.chat.state === 'recovery' || state.followupSubmitting || state.followupUnknownId || hasUnknownFollowup()) return;
2755
4034
  const snapshot = captureChat();
2756
4035
  if (!snapshot) return;
2757
4036
  if (state.uploadingChatIds.has(snapshot.chatId)) return;
2758
4037
  const incoming = [...files];
4038
+ // Reset the native chooser even when validation rejects this batch. After the user removes
4039
+ // an image, selecting that same file again must fire a fresh change event.
4040
+ ui.file.value = '';
4041
+ if (incoming.some((file) => !allowedTypes.has(file.type))) { report(new Error('Attach a PNG, JPEG, WebP, or PDF')); return; }
4042
+ const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length
4043
+ + incoming.filter((file) => file.type.startsWith('image/')).length;
4044
+ if (imageCount > MAX_IMAGES_PER_MESSAGE) {
4045
+ state.imageLimitChatId = snapshot.chatId;
4046
+ report({ code: 'chat-message-image-limit' });
4047
+ return;
4048
+ }
4049
+ state.imageLimitChatId = null;
2759
4050
  const known = [...new Map([...(state.chat.attachments || []), ...state.attachments]
2760
4051
  .map((attachment) => [attachment.attachmentId, attachment])).values()];
2761
4052
  const existingBytes = known.reduce((sum, item) => sum + (item.bytes || 0), 0);
2762
4053
  if (known.length + incoming.length > 10) { report(new Error('You can attach up to 10 files to this conversation.')); return; }
2763
- if (incoming.some((file) => !allowedTypes.has(file.type))) { report(new Error('Attach a PNG, JPEG, WebP, or PDF')); return; }
2764
4054
  if (incoming.some((file) => file.size > 20 * MB)) { report(new Error('Each attachment must be 20 MB or smaller')); return; }
2765
4055
  if (existingBytes + incoming.reduce((sum, file) => sum + file.size, 0) > 50 * MB) { report(new Error('Attachments must stay within 50 MB per conversation')); return; }
2766
4056
  state.uploadingChatIds.add(snapshot.chatId);
@@ -2931,6 +4221,211 @@
2931
4221
  await selectConversation(chatId, { focus: true, replaceProviderChoice: true });
2932
4222
  }
2933
4223
 
4224
+ const TEKLA_OPERATION = 'Tekla.Structures.Model.Model.GetInfo().ModelName';
4225
+
4226
+ function teklaDraftForChat(chat = state.chat) {
4227
+ const draft = state.teklaDraft;
4228
+ return draft && chat && draft.chatId === chat.chatId ? draft : null;
4229
+ }
4230
+
4231
+ function teklaBindingFrozen(chat) {
4232
+ return Boolean(chat?.nativeSessionId || chat?.activeTurn || chat?.archivedAt);
4233
+ }
4234
+
4235
+ // The chip states what the binding permits — never that anything is verified. The live check
4236
+ // happens on each approved read, and its own receipt card says whether it verified.
4237
+ function paintTeklaChip() {
4238
+ const node = ui.teklaChip;
4239
+ if (!node) return;
4240
+ const chat = state.chat;
4241
+ const draft = teklaDraftForChat(chat);
4242
+ const bound = chat?.teklaModelRead || null;
4243
+ const library = draft?.library || bound;
4244
+ if (!chat || !library) {
4245
+ if (!node.hidden || node.childElementCount) { node.replaceChildren(); node.hidden = true; delete node.dataset.key; }
4246
+ return;
4247
+ }
4248
+ const status = draft ? draft.status : 'bound';
4249
+ const frozen = !draft && teklaBindingFrozen(chat);
4250
+ const error = draft?.error || (state.teklaRemoveError?.chatId === chat.chatId ? state.teklaRemoveError.message : null);
4251
+ const key = [chat.chatId, library.sourcePath, library.hostVersion, status, frozen, error || ''].join('|');
4252
+ // Keep the same Remove button across polls so keyboard focus survives a repaint.
4253
+ if (node.dataset.key === key && !node.hidden) return;
4254
+ node.dataset.key = key;
4255
+ node.replaceChildren();
4256
+ node.hidden = false;
4257
+ node.dataset.state = error ? 'error' : status;
4258
+ const chip = document.createElement('div'); chip.className = 'ai-chat-tekla-chip';
4259
+ const copy = document.createElement('span'); copy.className = 'ai-chat-tekla-chip-copy';
4260
+ copy.id = `chat-tekla-context-copy-${chat.chatId}`;
4261
+ const lead = document.createElement('strong'); lead.textContent = `Tekla ${library.hostVersion} model library`;
4262
+ copy.append(lead, document.createTextNode(' · Chat may ask to read the open model name — FloLess asks you first and checks live each time'));
4263
+ if (status === 'bound') {
4264
+ const suffix = document.createElement('span'); suffix.className = 'ai-chat-tekla-chip-state';
4265
+ suffix.textContent = ' · added to this chat';
4266
+ copy.append(suffix);
4267
+ } else if (status === 'binding') {
4268
+ const suffix = document.createElement('span'); suffix.className = 'ai-chat-tekla-chip-state';
4269
+ suffix.textContent = ' · adding…';
4270
+ copy.append(suffix);
4271
+ }
4272
+ chip.dataset.tip = library.sourcePath;
4273
+ chip.append(copy);
4274
+ if (!frozen) {
4275
+ const remove = button(status === 'removing' ? 'Removing…' : 'Remove', 'shell.chat-tekla-remove', 'ai-chat-tekla-remove');
4276
+ remove.setAttribute('aria-label', `Remove Tekla ${library.hostVersion} model library from this chat`);
4277
+ remove.setAttribute('aria-describedby', copy.id);
4278
+ const busy = status === 'binding' || status === 'removing';
4279
+ remove.disabled = busy;
4280
+ remove.setAttribute('aria-busy', String(busy));
4281
+ if (busy) remove.dataset.blockedReason = status === 'binding' ? 'FloLess is adding this library to the chat. Wait for it to finish.' : 'FloLess is removing this library from the chat.';
4282
+ remove.addEventListener('click', () => { void removeTeklaChip(); });
4283
+ chip.append(remove);
4284
+ }
4285
+ node.append(chip);
4286
+ if (error) {
4287
+ const reason = document.createElement('p'); reason.className = 'ai-chat-tekla-error';
4288
+ reason.setAttribute('role', 'alert');
4289
+ reason.textContent = error;
4290
+ node.append(reason);
4291
+ }
4292
+ }
4293
+
4294
+ async function removeTeklaChip() {
4295
+ const chat = state.chat;
4296
+ if (!chat) return;
4297
+ state.teklaRemoveError = null;
4298
+ const draft = teklaDraftForChat(chat);
4299
+ if (draft && draft.status !== 'binding') {
4300
+ // Not bound yet: forgetting it is purely local. Nothing is sent and no route is called.
4301
+ state.teklaDraft = null;
4302
+ paintTeklaChip(); ui.input.focus(); announce('Tekla model library removed from this draft.');
4303
+ return;
4304
+ }
4305
+ if (!chat.teklaModelRead || teklaBindingFrozen(chat)) { paintTeklaChip(); return; }
4306
+ const snapshot = captureChat();
4307
+ if (!snapshot) return;
4308
+ state.teklaDraft = { chatId: chat.chatId, library: chat.teklaModelRead, status: 'removing', error: null };
4309
+ paintTeklaChip();
4310
+ try {
4311
+ const updated = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/tekla-model-read`, {
4312
+ method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, library: null }),
4313
+ });
4314
+ if (!sameChat(snapshot)) return;
4315
+ state.teklaDraft = null;
4316
+ // Only the server's own chat record, with no library left, may say it is gone; anything else is a failure.
4317
+ if (!updated || updated.chatId !== snapshot.chatId || updated.teklaModelRead != null) {
4318
+ state.teklaRemoveError = { chatId: snapshot.chatId, message: 'FloLess could not confirm the library was removed. Try again.' };
4319
+ paintTeklaChip();
4320
+ return;
4321
+ }
4322
+ state.chat = { ...state.chat, ...updated };
4323
+ paintTeklaChip(); ui.input.focus(); announce('Tekla model library removed from this chat.');
4324
+ } catch (error) {
4325
+ if (!sameChat(snapshot)) return;
4326
+ state.teklaDraft = null;
4327
+ state.teklaRemoveError = { chatId: snapshot.chatId, message: errorMessage(error) };
4328
+ paintTeklaChip();
4329
+ }
4330
+ }
4331
+
4332
+ // Returns true when the message may be sent: nothing pending, or the binding was stored.
4333
+ async function bindPendingTeklaRead(snapshot) {
4334
+ const draft = teklaDraftForChat();
4335
+ if (draft && (draft.status === 'binding' || draft.status === 'removing')) {
4336
+ announce('Wait for the Tekla library change to finish, then send.');
4337
+ return false;
4338
+ }
4339
+ if (!draft || draft.status !== 'draft') return !draft || draft.status === 'bound';
4340
+ const bound = state.chat?.teklaModelRead;
4341
+ if (bound && bound.sourcePath === draft.library.sourcePath && bound.hostVersion === draft.library.hostVersion) {
4342
+ state.teklaDraft = null; paintTeklaChip(); return true;
4343
+ }
4344
+ draft.status = 'binding'; draft.error = null;
4345
+ paintTeklaChip(); setBusy(true);
4346
+ try {
4347
+ const updated = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/tekla-model-read`, {
4348
+ method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, library: draft.library }),
4349
+ });
4350
+ if (!sameChat(snapshot)) return false;
4351
+ // Never invent the binding locally: only the server's own record of THIS library for this chat counts.
4352
+ const stored = updated && updated.chatId === snapshot.chatId ? updated.teklaModelRead : null;
4353
+ if (!stored || stored.sourcePath !== draft.library.sourcePath || stored.hostVersion !== draft.library.hostVersion) {
4354
+ draft.status = 'draft';
4355
+ draft.error = 'Message not sent. FloLess could not confirm the Tekla library was added to this chat. Try again.';
4356
+ paintTeklaChip();
4357
+ return false;
4358
+ }
4359
+ if (state.teklaDraft === draft) state.teklaDraft = null;
4360
+ state.teklaRemoveError = null;
4361
+ state.chat = { ...state.chat, ...updated };
4362
+ paintTeklaChip();
4363
+ return true;
4364
+ } catch (error) {
4365
+ if (!sameChat(snapshot)) return false;
4366
+ draft.status = 'draft';
4367
+ draft.error = `Message not sent. ${errorMessage(error)}`;
4368
+ paintTeklaChip();
4369
+ return false;
4370
+ } finally { if (sameChat(snapshot)) setBusy(false); }
4371
+ }
4372
+
4373
+ function teklaDraftText(receipt) {
4374
+ const when = typeof receipt.verifiedAt === 'string' ? new Date(receipt.verifiedAt) : null;
4375
+ // The same readable form the transcript's receipt card uses, not a raw ISO timestamp.
4376
+ const checked = when && !Number.isNaN(when.getTime())
4377
+ ? `, checked ${when.toLocaleString([], { dateStyle: 'medium', timeStyle: 'medium' })}` : '';
4378
+ // The earlier model name is deliberately left out: the open model may have changed since, and
4379
+ // the AI would repeat a stale name as current. A fresh read shows the name at that moment.
4380
+ return `Earlier FloLess check: reading the open model name through the Tekla model library at ${receipt.sourcePath} `
4381
+ + `worked (Tekla ${receipt.hostVersion}${checked}). The generated agent's commands remain unverified. `
4382
+ + 'Help me use this read in this project.';
4383
+ }
4384
+
4385
+ // Leave the selected conversation for the Claude/Codex choice. A prior async select can still be
4386
+ // waiting for capability discovery, and the poll repaints whatever `state.chat` holds: invalidate
4387
+ // the one and clear the other, or the old conversation is painted back over the chooser.
4388
+ function beginProviderChoice() {
4389
+ state.selectionGeneration += 1;
4390
+ state.choosingProvider = true;
4391
+ closeSource(); clearLiveStream(true);
4392
+ state.chat = null; state.events = []; state.attachments = []; state.integrations = null; state.capability = null;
4393
+ updateOffscreenActivity();
4394
+ }
4395
+
4396
+ // Graft receipt → unsent Chat draft. Opening performs no binding, sends nothing and never
4397
+ // touches Tekla: the binding is stored only when the user presses Send.
4398
+ async function openVerifiedTeklaDraft(receipt) {
4399
+ // `plainEnglish` marks errors written for the user, so the Graft dialog can show them as-is.
4400
+ if (!receipt || typeof receipt.sourcePath !== 'string' || !receipt.sourcePath
4401
+ || typeof receipt.hostVersion !== 'string' || !receipt.hostVersion) {
4402
+ throw Object.assign(new Error('FloLess could not read the result of the model check. Check the model read again, then continue in AI Chat.'), { plainEnglish: true });
4403
+ }
4404
+ const library = { sourcePath: receipt.sourcePath, hostVersion: receipt.hostVersion };
4405
+ const draft = teklaDraftText(receipt);
4406
+ await refreshScope();
4407
+ if (!state.scope?.owner) throw Object.assign(new Error('Open a project or workflow before continuing in AI Chat.'), { plainEnglish: true });
4408
+ window.flolessBridge?.revealAiChat?.();
4409
+ ui.tab.click();
4410
+ const chat = state.chat;
4411
+ // The binding is frozen once a provider session exists, so only a chat that has never
4412
+ // started a provider session, and is not busy, can take it. Otherwise start a new chat.
4413
+ if (!chat || chat.nativeSessionId || chat.activeTurn || chat.archivedAt || chat.state === 'recovery') {
4414
+ state.discoveryDraft = draft;
4415
+ state.pendingTeklaLibrary = library;
4416
+ beginProviderChoice();
4417
+ providerChooser(); clearReport();
4418
+ return;
4419
+ }
4420
+ state.teklaRemoveError = null;
4421
+ state.teklaDraft = { chatId: chat.chatId, library, status: 'draft', error: null };
4422
+ const existing = ui.input.value.trim();
4423
+ ui.input.value = existing ? `${existing}\n\n${draft}` : draft;
4424
+ ui.input.dispatchEvent(new Event('input', { bubbles: true }));
4425
+ paintTeklaChip();
4426
+ ui.input.focus();
4427
+ }
4428
+
2934
4429
  async function openDraft(draft) {
2935
4430
  if (typeof draft !== 'string' || !draft.trim()) return;
2936
4431
  await refreshScope();
@@ -2939,8 +4434,8 @@
2939
4434
  ui.tab.click();
2940
4435
  if (!state.chat || state.chat.activeTurn || state.chat.archivedAt || state.chat.state === 'recovery') {
2941
4436
  state.discoveryDraft = draft;
2942
- state.choosingProvider = true;
2943
- providerChooser();
4437
+ beginProviderChoice();
4438
+ providerChooser(); clearReport();
2944
4439
  return;
2945
4440
  }
2946
4441
  const existing = ui.input.value.trim();
@@ -2964,17 +4459,15 @@
2964
4459
  }
2965
4460
 
2966
4461
  ui.historyToggle.addEventListener('click', () => toggleHistory());
4462
+ ui.feed.addEventListener('scroll', updateOffscreenActivity, { passive: true });
4463
+ const activityResizeObserver = new ResizeObserver(updateOffscreenActivity);
4464
+ activityResizeObserver.observe(ui.feed);
2967
4465
  ui.refresh.addEventListener('click', refreshChatSession);
2968
4466
  ui.history.addEventListener('keydown', (event) => {
2969
4467
  if (event.key === 'Escape') { event.preventDefault(); toggleHistory(false, { focusToggle: true }); }
2970
4468
  });
2971
4469
  ui.newChat.addEventListener('click', () => {
2972
- // A prior async select can still be waiting for capability discovery. Invalidate it before
2973
- // showing the provider choice, otherwise it can put the old conversation back over this view.
2974
- state.selectionGeneration += 1;
2975
- state.choosingProvider = true;
2976
- closeSource(); clearLiveStream(true);
2977
- state.chat = null; state.events = []; state.attachments = []; state.integrations = null; state.capability = null;
4470
+ beginProviderChoice();
2978
4471
  toggleHistory(false); setBusy(false); providerChooser(); clearReport();
2979
4472
  });
2980
4473
  ui.rename.addEventListener('click', beginRename);
@@ -2986,7 +4479,8 @@
2986
4479
  ui.title.addEventListener('blur', () => finishRename(ui.title.textContent?.trim() !== ''));
2987
4480
  ui.settingsToggle.addEventListener('click', () => {
2988
4481
  const open = ui.settings.hidden;
2989
- if (open) toggleHistory(false);
4482
+ // Switching from History to Settings: the composer is about to be hidden, so focus stays here.
4483
+ if (open) toggleHistory(false, { keepFocus: true });
2990
4484
  ui.settings.hidden = !open;
2991
4485
  ui.settingsToggle.setAttribute('aria-expanded', String(open));
2992
4486
  closePicker();
@@ -2997,6 +4491,12 @@
2997
4491
  ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
2998
4492
  ui.integrations.addEventListener('click', openIntegrations);
2999
4493
  ui.send.addEventListener('click', sendTurn);
4494
+ // The Drawing Filter page reports every change that can alter what the chat shows about it.
4495
+ window.addEventListener('floless:filter-ai-changed', () => {
4496
+ state.filterCardMessages.clear();
4497
+ paintFloLessContext(); refreshFilterCards(); updateSendState();
4498
+ });
4499
+ document.getElementById('ws-frame-drawings')?.addEventListener('load', () => { paintFloLessContext(); refreshFilterCards(); updateSendState(); });
3000
4500
  ui.stop.addEventListener('click', stopTurn);
3001
4501
  ui.recoveryStop.addEventListener('click', () => { void (state.recoveryCanEnd ? endRecovery() : stopTurn()); });
3002
4502
  ui.reconcile.addEventListener('click', reconcile);
@@ -3036,9 +4536,9 @@
3036
4536
  }
3037
4537
 
3038
4538
  state.refreshTimer = setInterval(pollChats, 5000);
3039
- window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
4539
+ window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); activityResizeObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
3040
4540
  window.flolessChat = {
3041
- refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openDraft,
4541
+ refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openDraft, openVerifiedTeklaDraft,
3042
4542
  startProjectIntake, resumeProjectIntake,
3043
4543
  currentProvider: () => state.chat?.provider ?? null,
3044
4544
  };