@floless/app 0.139.1 → 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.
Files changed (41) hide show
  1. package/dist/floless-server.cjs +32765 -36490
  2. package/dist/skills/floless-app-steel-takeoff/SKILL.md +8 -3
  3. package/dist/skills/floless-app-vectorize/SKILL.md +1 -1
  4. package/dist/skills/floless-app-vectorize/scripts/extract_pdf.py +7 -1
  5. package/dist/skills/floless-app-vectorize/scripts/vision_to_contract.py +7 -1
  6. package/dist/web/app.css +163 -3
  7. package/dist/web/aware.js +657 -66
  8. package/dist/web/chat.css +387 -25
  9. package/dist/web/chat.js +2005 -108
  10. package/dist/web/commands-filter.js +86 -8
  11. package/dist/web/commands-revit.js +2 -1
  12. package/dist/web/commands-shell.js +249 -13
  13. package/dist/web/commands-steel.js +34 -24
  14. package/dist/web/commands.js +19 -0
  15. package/dist/web/filter-ai-context.js +57 -0
  16. package/dist/web/filter-ai-proposal.js +87 -0
  17. package/dist/web/filter-guidance.js +8 -0
  18. package/dist/web/index.html +72 -11
  19. package/dist/web/instructor.js +231 -33
  20. package/dist/web/left-pane.js +185 -18
  21. package/dist/web/local-discovery.js +297 -0
  22. package/dist/web/model-editor-revit-adapter.js +3 -1
  23. package/dist/web/model-editor-steel-adapter.js +3 -1
  24. package/dist/web/model-editor.css +4 -4
  25. package/dist/web/model-revit-module.js +63 -0
  26. package/dist/web/model-viewport-toolbar.js +13 -1
  27. package/dist/web/model-viewport.js +16 -1
  28. package/dist/web/overlay-escape.js +79 -0
  29. package/dist/web/revit-editor.css +7 -0
  30. package/dist/web/revit-editor.html +5 -5
  31. package/dist/web/revit-editor.js +20 -10
  32. package/dist/web/steel-detail-refs.js +0 -69
  33. package/dist/web/steel-editor.html +103 -264
  34. package/dist/web/steel-filter-core.js +298 -12
  35. package/dist/web/steel-filter-hit.js +526 -0
  36. package/dist/web/steel-filter.html +1647 -75
  37. package/dist/web/steel-split-view.js +1 -1
  38. package/dist/web/vector-3d.html +3 -0
  39. package/dist/web/vector-editor.html +9 -1
  40. package/dist/web/workspaces.js +198 -25
  41. package/package.json +5 -2
package/dist/web/chat.js CHANGED
@@ -8,32 +8,72 @@
8
8
  const ui = {
9
9
  historyToggle: el('chat-history-toggle'), newChat: el('chat-new'), refresh: el('chat-refresh'), history: el('chat-history'),
10
10
  title: el('chat-title'), rename: el('chat-rename'), scope: el('chat-scope'), settingsToggle: el('chat-settings-toggle'),
11
- settings: el('chat-settings'), provider: el('chat-provider'), model: el('chat-model'),
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
- sessionReady: false, scope: null, chats: [], archivedChats: [], chat: null, events: [], capability: null, desktop: null,
24
- source: null, eventReconnectTimer: null, eventReconnectAttempt: 0, eventReconnectChatId: null, attachments: [], integrations: null, historyOpen: false, historyFilter: 'all', archivedHistoryOpen: false,
26
+ // signInPending is keyed by provider: a wait started in one conversation must not paint an
27
+ // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
28
+ sessionReady: false, scope: null, chats: [], archivedChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
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,
25
30
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
26
- 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,
27
32
  answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
28
- stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(),
33
+ stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(), revokingApprovalTurns: new Set(), uploadingChatIds: new Set(),
34
+ // Latched so the 5 s account poll logs an outage once instead of twelve times a minute; cleared
35
+ // on the next successful read, so a later, separate outage is logged too.
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,
29
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);
30
59
  const permissionLabels = {
31
60
  'read-only': 'Read only', 'workspace-write': 'Working folder write', 'full-access': 'Full access',
32
61
  };
33
62
  const providerLabels = { claude: 'Claude', codex: 'Codex' };
63
+ // The one sign-in refusal FloLess re-words. 'chat-turn-active' is the same code every other chat
64
+ // action returns, whose shared sentence (stop the response before changing the conversation) would
65
+ // be wrong here: the user is not changing the conversation, only waiting to switch who answers it.
66
+ // Every other sign-in refusal keeps the server's own sentence — see SERVER_WORDED_SIGN_IN_CODES.
67
+ const signInMessages = {
68
+ 'chat-turn-active': 'Wait for the current AI reply to finish before switching accounts.',
69
+ };
70
+ // The server's own sentence is more accurate than anything we can substitute: it names WHICH
71
+ // runtime problem happened and WHICH command to run by hand. errorMessage() would flatten it.
72
+ const SERVER_WORDED_SIGN_IN_CODES = new Set(['runtime-unavailable', 'launch-failed', 'launch-unsafe', 'sign-in-active', 'sign-out-failed']);
34
73
  const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question' };
35
74
  const requestStatusLabels = { pending: 'Queued', queued: 'Queued', running: 'Running', ready: 'Ready', completed: 'Complete', failed: 'Failed', stopped: 'Stopped' };
36
75
  const allowedTypes = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
76
+ const MAX_IMAGES_PER_MESSAGE = 5;
37
77
  const MB = 1024 * 1024;
38
78
 
39
79
  function ownerQuery(owner = state.scope?.owner) {
@@ -69,6 +109,8 @@
69
109
  if (!response.ok) {
70
110
  const error = new Error(body?.error || body || `Chat request failed (${response.status})`);
71
111
  error.code = body?.code || null;
112
+ error.reason = body?.reason || null;
113
+ error.status = response.status;
72
114
  throw error;
73
115
  }
74
116
  return body;
@@ -88,23 +130,46 @@
88
130
  choice.setAttribute('aria-busy', String(busy));
89
131
  }
90
132
  const blocked = requestExecutionBlocked();
133
+ const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
91
134
  // Freeze the draft while the server is accepting it. The acceptance transaction clears the
92
135
  // durable draft; allowing typing in this short window can race a new autosave over that clear
93
136
  // and make the submitted message reappear after the turn finishes.
94
137
  ui.input.disabled = busy || !state.chat || Boolean(state.chat?.archivedAt)
95
138
  || state.chat?.state === 'recovery' || blocked;
96
- ui.send.disabled = busy || !state.chat || blocked || !ui.input.value.trim() || Boolean(state.chat?.activeTurn);
97
- ui.attach.disabled = busy || !state.chat || blocked || Boolean(state.chat?.activeTurn);
139
+ ui.send.disabled = busy || uploading || !state.chat || blocked
140
+ || (!ui.input.value.trim() && state.attachments.length === 0) || Boolean(state.chat?.activeTurn);
141
+ ui.attach.disabled = busy || uploading || !state.chat || blocked || Boolean(state.chat?.activeTurn);
142
+ if (!busy) updateSendState();
98
143
  }
99
144
 
100
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;
101
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
+ }
102
155
  const code = String(error && error.code || '');
103
156
  const codeMessages = {
104
157
  'chat-origin-refused': 'This chat can only be used from the FloLess app. Reload the page and try again.',
105
158
  'chat-owner-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
106
159
  'chat-cwd-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
107
- '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.',
108
173
  'chat-initiator-unknown': 'FloLess could not identify what started this conversation. Reload the conversation and try again.',
109
174
  'chat-record-unsafe': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
110
175
  'chat-record-invalid': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
@@ -115,6 +180,7 @@
115
180
  'chat-owner-archived': 'This project or workflow is archived. Restore it before continuing the conversation.',
116
181
  'chat-archived': 'This conversation is archived. Start a new conversation to continue.',
117
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.',
118
184
  'chat-send-refused': 'The AI service did not accept this message. Check your sign-in and conversation settings, then try again.',
119
185
  'chat-approval-stale': 'This approval is no longer active. Refresh the conversation.',
120
186
  'chat-provider-identity-changed': 'The connected AI account changed while this response was running. Refresh the conversation and try again.',
@@ -139,8 +205,16 @@
139
205
  'request-chat-not-ready': 'This request is still being prepared. Wait a moment, then try again.',
140
206
  'chat-knowledge-unscoped': 'Knowledge is available only inside a project conversation. Open a project and try again.',
141
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.',
142
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
+ }
143
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.';
144
218
  if (code === 'request-chat-owner-mismatch' || /request chat link belongs to another owner/i.test(raw)) {
145
219
  return 'This request is linked to another project or workflow. Open the project or workflow shown on the request, then try again.';
146
220
  }
@@ -213,11 +287,17 @@
213
287
  return 'FloLess could not complete this chat action. Reload the conversation and try again.';
214
288
  }
215
289
 
290
+ // The one reason the empty state can act on itself: a sign-in. Every other reason names a problem
291
+ // a sign-in button would not fix, so the button follows THIS rule, not the reason's wording.
292
+ function signInNeeded(reason) {
293
+ const raw = String(reason || '');
294
+ return !raw || /sign in|auth|account/i.test(raw);
295
+ }
296
+
216
297
  function capabilityMessage(provider, reason) {
217
298
  const label = providerLabels[provider] || 'AI service';
218
299
  const raw = String(reason || '');
219
- if (!raw) return `Sign in to ${label} first.`;
220
- if (/sign in|auth|account/i.test(raw)) return `Sign in to ${label} first.`;
300
+ if (signInNeeded(raw)) return `Sign in to ${label} first.`;
221
301
  if (/EPERM|EACCES|ENOENT|ENOTDIR|operation not permitted|permission denied|watch ['"]/i.test(raw)) {
222
302
  return 'FloLess cannot open this conversation’s project or workflow folder. Restore or reconnect that folder, then try again.';
223
303
  }
@@ -230,8 +310,9 @@
230
310
  return `The ${label} chat is not ready on this computer. Reload FloLess and try again.`;
231
311
  }
232
312
 
233
- function report(error, prefix = '') {
234
- const message = `${prefix}${prefix ? ': ' : ''}${errorMessage(error)}`;
313
+ function report(error, prefix = '', messages = null) {
314
+ const code = String(error && error.code || '');
315
+ const message = `${prefix}${prefix ? ': ' : ''}${messages?.[code] || errorMessage(error)}`;
235
316
  announce(message);
236
317
  ui.hint.textContent = message;
237
318
  ui.hint.classList.add('error');
@@ -241,6 +322,11 @@
241
322
  ui.hint.classList.remove('error');
242
323
  const message = requestExecutionBlocked()
243
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.'
244
330
  : state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
245
331
  ? runtimeNotice(state.chat.provider, state.capability.runtime).body
246
332
  : state.chat && !providerReady()
@@ -250,10 +336,11 @@
250
336
  : !state.scope?.owner
251
337
  ? 'Open a project or workflow to start chatting.'
252
338
  : 'Enter to send · Shift+Enter for a new line';
253
- if (turnIsVisiblyActive()) {
254
- 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';
255
342
  ui.hint.classList.remove('working');
256
- ui.hint.setAttribute('aria-label', 'AI is working');
343
+ ui.hint.removeAttribute('aria-label');
257
344
  } else {
258
345
  ui.hint.classList.remove('working');
259
346
  ui.hint.removeAttribute('aria-label');
@@ -270,11 +357,20 @@
270
357
  return typeof ownerId === 'string' ? `${owner.kind}:${ownerId}` : '';
271
358
  }
272
359
 
360
+ // The probe's `authenticated` is read once per capability load; the CLI's own answer is merged
361
+ // in by the 5 s poll. A parsed sign-OUT from the CLI overrides the probe here exactly as the
362
+ // server's registry does on a fresh read: a chat is not ready on a CLI that says "not logged in",
363
+ // however recently the probe said otherwise — the feed and the Provider row must not disagree.
273
364
  function providerReady() {
274
- return Boolean(state.capability?.available && state.capability?.authenticated === true);
365
+ return Boolean(state.capability?.available && state.capability?.authenticated === true
366
+ && capabilityAnswer(state.capability).state !== 'signed-out');
275
367
  }
276
368
 
277
- function currentFloLessContext() {
369
+ function currentSurface() {
370
+ return currentFloLessContext({ surfaceOnly: true }).surface;
371
+ }
372
+
373
+ function currentFloLessContext(options = {}) {
278
374
  const workspaceMode = document.querySelector('#mode-switch [data-mode="workspaces"]')?.getAttribute('aria-selected') === 'true';
279
375
  const workflowMode = document.querySelector('#mode-switch [data-mode="workflows"]')?.getAttribute('aria-selected') === 'true';
280
376
  const reportOpen = document.getElementById('report-modal')?.classList.contains('show') === true;
@@ -293,6 +389,7 @@
293
389
  : editorOpen ? 'model-editor'
294
390
  : workspaceMode ? (workspaceProjectOpen ? workspaceSurface : 'project-list')
295
391
  : dashboardVisible ? 'dashboard' : 'workflow-canvas';
392
+ if (options.surfaceOnly) return { surface };
296
393
  return {
297
394
  mode: workspaceMode ? 'workspaces' : workflowMode ? 'workflows' : 'canvas',
298
395
  surface,
@@ -347,11 +444,23 @@
347
444
 
348
445
  function paintFloLessContext() {
349
446
  if (!ui.contextNote) return;
350
- const context = currentFloLessContext();
351
- ui.contextNote.replaceChildren();
352
- const prefix = document.createElement('strong');
353
- prefix.textContent = 'Sharing with AI: ';
354
- 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();
355
464
  }
356
465
 
357
466
  function commandInstance(value) {
@@ -405,10 +514,35 @@
405
514
  function renderedLiveAssistantText(event, text) {
406
515
  if (!event?.payload?.delta || !event.turnId || !state.chat) return { text, streaming: false };
407
516
  const key = `${state.chat.chatId}:${event.turnId}`;
517
+ const isActiveTurn = state.chat.activeTurn?.turnId === event.turnId;
518
+ // One animator can own only the final prose block. Earlier blocks must not
519
+ // reset its target on every repaint (even when they belong to the same turn).
520
+ if (state.chat.state === 'recovery') {
521
+ // Recovery may reconcile back to this same running turn. Preserve the fully revealed target so
522
+ // that return does not restart an already-read answer from its first 12 characters.
523
+ const latest = isActiveTurn
524
+ ? state.events?.findLast((item) => item.type === 'assistant-message' && item.turnId === event.turnId)
525
+ : null;
526
+ if (isActiveTurn && (!latest || latest.eventId === event.eventId)) {
527
+ if (state.stream?.key !== key) {
528
+ clearLiveStream();
529
+ state.stream = { key, chatId: state.chat.chatId, turnId: event.turnId, target: text, shown: text, frame: null };
530
+ } else {
531
+ state.stream.target = text;
532
+ }
533
+ flushLiveStream();
534
+ }
535
+ return { text, streaming: false };
536
+ }
537
+ if (!state.chat.activeTurn) {
538
+ clearLiveStream();
539
+ return { text, streaming: false };
540
+ }
408
541
  // Historical stream chunks are stored as deltas too. Only animate the active turn; otherwise
409
542
  // opening a conversation would reset every prior answer and leave the last one half-rendered.
410
- const isActiveTurn = state.chat.activeTurn?.turnId === event.turnId;
411
- if (!isActiveTurn && state.stream?.key !== key) return { text, streaming: false };
543
+ if (!isActiveTurn) return { text, streaming: false };
544
+ const latest = state.events?.findLast((item) => item.type === 'assistant-message' && item.turnId === event.turnId);
545
+ if (latest && latest.eventId !== event.eventId) return { text, streaming: false };
412
546
  if (state.stream?.key !== key) {
413
547
  clearLiveStream();
414
548
  state.stream = { key, chatId: state.chat.chatId, turnId: event.turnId, target: '', shown: '', frame: null };
@@ -476,7 +610,22 @@
476
610
  return node;
477
611
  }
478
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
+
479
627
  function providerChooser() {
628
+ paintComposerDisclosure();
480
629
  // The workspace landing page has no conversation owner. It must never offer a provider,
481
630
  // history, or refresh there: none of those actions has a chat to operate on.
482
631
  // No provider is chosen here (nor on the unscoped landing), so a setup card left from the previous
@@ -484,11 +633,12 @@
484
633
  shell.querySelector('.ai-chat-runtime')?.remove(); stopRuntimePoll();
485
634
  if (!state.scope?.owner) { showUnscoped(); return; }
486
635
  ui.feed.replaceChildren();
636
+ updateOffscreenActivity();
487
637
  const empty = document.createElement('div');
488
638
  empty.className = 'ai-chat-empty';
489
639
  const strong = document.createElement('strong');
490
640
  strong.textContent = state.chats.length ? 'Start a new conversation' : 'Start this conversation';
491
- const copy = document.createElement('div');
641
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
492
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.';
493
643
  const row = document.createElement('div');
494
644
  row.className = 'ai-chat-provider-row';
@@ -501,15 +651,45 @@
501
651
  row.append(choice);
502
652
  }
503
653
  empty.append(strong, copy, row);
654
+ const accounts = document.createElement('div');
655
+ accounts.className = 'ai-chat-provider-accounts';
656
+ accounts.textContent = 'Checking signed-in accounts…';
657
+ empty.append(accounts);
658
+ // There is no chat yet, so no capability probe exists; the runtimes read carries the same sign-in.
659
+ request('/api/terminal-runtimes').then((info) => {
660
+ if (!accounts.isConnected) return;
661
+ accounts.replaceChildren(...['claude', 'codex'].map((provider) => {
662
+ const cell = document.createElement('span');
663
+ const runtime = info?.runtimes?.find((r) => r?.id === provider);
664
+ // Each row carries its OWN answer — including that its status read failed — so this must
665
+ // state that answer rather than assume the read landed. A runtime missing from the list
666
+ // is a known absence, not an unchecked one, hence the flat "not installed" wording.
667
+ cell.textContent = runtime ? providerAccountLabel(provider, runtime.account) : `${providerLabels[provider]} · not installed`;
668
+ return cell;
669
+ }));
670
+ }).catch((error) => {
671
+ // The line disappears rather than guessing; without this the feature vanishing is invisible.
672
+ console.warn('floless: could not read the signed-in accounts for the chooser', error);
673
+ if (accounts.isConnected) accounts.remove();
674
+ });
504
675
  ui.feed.append(empty);
505
676
  ui.title.textContent = 'New conversation';
506
- ui.provider.querySelector('strong').textContent = 'Choose Claude or Codex';
677
+ const providerValue = ui.provider.querySelector('strong');
678
+ providerValue.textContent = 'Choose Claude or Codex';
679
+ delete providerValue.dataset.tip;
680
+ ui.switchAccount.hidden = true;
507
681
  ui.input.disabled = true;
508
682
  ui.attach.disabled = true;
509
683
  ui.send.disabled = true;
510
684
  ui.historyToggle.disabled = false;
511
685
  ui.refresh.disabled = true;
512
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();
513
693
  }
514
694
 
515
695
  function clearProviderChoice() {
@@ -517,16 +697,18 @@
517
697
  }
518
698
 
519
699
  function showUnscoped() {
700
+ paintComposerDisclosure();
520
701
  clearProviderChoice();
521
702
  closeSource();
522
703
  clearLiveStream(true);
523
- 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;
524
705
  ui.feed.replaceChildren();
706
+ updateOffscreenActivity();
525
707
  const empty = document.createElement('div');
526
708
  empty.className = 'ai-chat-empty';
527
709
  const strong = document.createElement('strong');
528
710
  strong.textContent = 'Open a project or workflow';
529
- const copy = document.createElement('div');
711
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
530
712
  copy.textContent = 'Each project or workflow keeps its own chat history in its folder.';
531
713
  empty.append(strong, copy);
532
714
  ui.feed.append(empty);
@@ -842,7 +1024,8 @@
842
1024
  paintHistory(); paintUnread();
843
1025
  if (state.chat?.chatId !== chatId) { announce(announcement); return; }
844
1026
  closeSource(); clearLiveStream(true);
845
- 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();
846
1029
  if (state.chats.length) await selectConversation(state.chats[0].chatId, { focus: true, replaceProviderChoice: true });
847
1030
  else providerChooser();
848
1031
  if (sameScope(snapshot.scope, snapshot.generation)) announce(announcement);
@@ -1054,11 +1237,18 @@
1054
1237
  if (event.providerItemId) item.dataset.providerItemId = event.providerItemId;
1055
1238
  if (event.turnId) item.dataset.turnId = event.turnId;
1056
1239
  const head = document.createElement('div'); head.className = 'ai-chat-message-head';
1057
- 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';
1058
1244
  const time = document.createElement('time'); time.dateTime = event.createdAt; time.textContent = eventTime(event);
1059
- const body = document.createElement('div'); body.className = 'ai-chat-message-body';
1060
- body.innerHTML = markdownHtml(role === 'assistant' ? visibleAssistantText(text) : visibleUserText(text));
1061
- head.append(who, time); item.append(head, body);
1245
+ const visibleText = role === 'assistant' ? visibleAssistantText(text) : visibleUserText(text);
1246
+ head.append(who, time); item.append(head);
1247
+ if (role === 'assistant' || visibleText) {
1248
+ const body = document.createElement('div'); body.className = 'ai-chat-message-body';
1249
+ body.innerHTML = markdownHtml(visibleText);
1250
+ item.append(body);
1251
+ }
1062
1252
  if (role === 'user' && Array.isArray(event.payload?.attachmentIds)) {
1063
1253
  const attachments = event.payload.attachmentIds
1064
1254
  .map((id) => state.chat?.attachments?.find((candidate) => candidate.attachmentId === id))
@@ -1071,9 +1261,81 @@
1071
1261
  item.append(gallery);
1072
1262
  }
1073
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
+ }
1074
1324
  return item;
1075
1325
  }
1076
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
+
1077
1339
  function renderRequestCard(event) {
1078
1340
  const payload = event.payload || {};
1079
1341
  const item = document.createElement('article');
@@ -1106,10 +1368,13 @@
1106
1368
  }
1107
1369
 
1108
1370
  function renderEvent(event) {
1371
+ if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
1109
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);
1110
1374
  if (event.type === 'user-message') return renderMessage(event, 'user', payloadText(event));
1111
1375
  if (event.type === 'assistant-message') return renderMessage(event, 'assistant', payloadText(event), Boolean(event.payload?.delta));
1112
- 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);
1113
1378
  const item = document.createElement('div');
1114
1379
  item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}${event.type === 'knowledge-citation' ? ' knowledge' : ''}`;
1115
1380
  item.dataset.eventSequence = String(event.sequence);
@@ -1119,8 +1384,8 @@
1119
1384
  attachment: 'Attachment', tool: 'AI action', error: 'Error', interrupted: 'Stopped', usage: 'AI usage',
1120
1385
  compaction: 'Conversation summary updated', 'knowledge-citation': 'Knowledge cited', state: 'Status', request: 'Request',
1121
1386
  };
1122
- label.textContent = labels[event.type] || event.type;
1123
1387
  const payload = event.payload || {};
1388
+ label.textContent = event.type === 'error' && payload.outcome === 'not-sent' ? 'Not sent' : labels[event.type] || event.type;
1124
1389
  let detail = event.type === 'error' ? errorMessage(payloadText(event)) : payloadText(event);
1125
1390
  if (!detail && event.type === 'tool') {
1126
1391
  const toolLabels = { provider: 'AI provider', integration: 'Connected service', attachment: 'Attachment', knowledge: 'Knowledge', filesystem: 'Project files' };
@@ -1136,6 +1401,60 @@
1136
1401
  return item;
1137
1402
  }
1138
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
+
1139
1458
  function animatedDots() {
1140
1459
  const dots = document.createElement('span'); dots.className = 'ai-chat-live-dots'; dots.setAttribute('aria-hidden', 'true');
1141
1460
  dots.append(document.createElement('i'), document.createElement('i'), document.createElement('i'));
@@ -1152,19 +1471,27 @@
1152
1471
  }
1153
1472
 
1154
1473
  function announceLiveResponseOnce() {
1155
- const turnId = state.chat?.activeTurn?.turnId || null;
1474
+ const turnId = turnIsVisiblyActive() ? state.chat.activeTurn.turnId : null;
1475
+ const wasResponding = state.liveStatusTurnId !== null;
1156
1476
  if (!turnId) {
1157
1477
  state.liveStatusTurnId = null;
1158
1478
  // The screen-reader announcement is a transient status. Once the durable turn ends,
1159
1479
  // leaving its text behind makes the finished chat sound as though it is still working.
1160
- 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 = '';
1161
1484
  return;
1162
1485
  }
1163
1486
  if (state.liveStatusTurnId === turnId) return;
1164
1487
  state.liveStatusTurnId = turnId;
1165
1488
  const provider = providerLabels[state.chat?.provider] || 'AI';
1166
1489
  ui.status.textContent = '';
1167
- requestAnimationFrame(() => { ui.status.textContent = `${provider} is responding.`; });
1490
+ requestAnimationFrame(() => {
1491
+ // Recovery or completion may land between scheduling and painting this transient sentence.
1492
+ if (!turnIsVisiblyActive() || state.chat?.activeTurn?.turnId !== turnId || state.liveStatusTurnId !== turnId) return;
1493
+ ui.status.textContent = `${provider} is responding.`;
1494
+ });
1168
1495
  }
1169
1496
 
1170
1497
  function renderedAnswerTarget(events, eventId, turnId) {
@@ -1193,28 +1520,35 @@
1193
1520
  target.scrollIntoView({ block: 'center' });
1194
1521
  }
1195
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
+
1196
1544
  function paintEvents(options = {}) {
1197
1545
  announceLiveResponseOnce();
1546
+ const focusedCommand = ui.feed.contains(document.activeElement)
1547
+ ? document.activeElement?.dataset?.commandId : null;
1198
1548
  const nearBottom = ui.feed.scrollHeight - ui.feed.scrollTop - ui.feed.clientHeight < 56;
1199
1549
  ui.feed.replaceChildren();
1200
1550
  if (!state.events.length) {
1201
- const empty = document.createElement('div'); empty.className = 'ai-chat-empty';
1202
- const strong = document.createElement('strong');
1203
- const copy = document.createElement('div');
1204
- if (providerReady()) {
1205
- strong.textContent = 'Ready when you are';
1206
- copy.textContent = `This ${providerLabels[state.chat?.provider] || 'AI'} conversation is stored with ${state.scope?.label || 'this work'}.`;
1207
- } else if (state.capability?.runtime && state.capability.runtime.state !== 'installed') {
1208
- const notice = runtimeNotice(state.chat?.provider, state.capability.runtime);
1209
- strong.textContent = notice.title;
1210
- copy.textContent = state.capability.runtime.state === 'failed'
1211
- ? notice.body
1212
- : 'You can write your first message now. Send becomes available when setup finishes.';
1213
- } else {
1214
- strong.textContent = `${providerLabels[state.chat?.provider] || 'AI'} needs attention`;
1215
- copy.textContent = capabilityMessage(state.chat?.provider, state.capability?.reason);
1216
- }
1217
- empty.append(strong, copy); ui.feed.append(empty);
1551
+ ui.feed.append(emptyFeedNotice());
1218
1552
  } else {
1219
1553
  let assistant = null;
1220
1554
  const flushAssistant = () => {
@@ -1246,31 +1580,174 @@
1246
1580
  }
1247
1581
  flushAssistant();
1248
1582
  // A provider can send text before it finishes tools, usage, or its terminal turn signal.
1249
- // Keep this fixed activity row visible for the full durable turn (and while text drains)
1250
- // so an intermittent stream never looks like a failed response.
1251
- if (turnIsVisiblyActive() || hasPendingLiveStream()) ui.feed.append(renderLiveStatus());
1583
+ // Keep this fixed activity row visible for the full durable turn so an intermittent stream
1584
+ // never looks like a failed response. Recovery deliberately has no live indicator.
1585
+ if (turnIsVisiblyActive()) ui.feed.append(renderLiveStatus());
1252
1586
  }
1587
+ restoreFeedFocus(focusedCommand);
1253
1588
  restoreAnswerJump();
1254
- 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
+ });
1594
+ }
1595
+
1596
+ // The feed's empty state. Four cases, in the order they must win: a sign-in window FloLess
1597
+ // opened from this chat is still the user's to finish (the CLI is signed OUT while it is open —
1598
+ // "Ready when you are" would be a lie for up to two minutes); the provider is ready; the runtime
1599
+ // is still being set up; or the provider needs attention — and when that attention is a sign-in,
1600
+ // the action sits right here (#1484), on the same state machine as the settings-strip button, so
1601
+ // a new user is never told to "sign in first" with nowhere to do it.
1602
+ function emptyFeedNotice() {
1603
+ const empty = document.createElement('div'); empty.className = 'ai-chat-empty';
1604
+ const strong = document.createElement('strong');
1605
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
1606
+ const provider = state.chat?.provider;
1607
+ const label = providerLabels[provider] || 'AI';
1608
+ const pendingSignIn = Boolean(provider && state.signInPending.has(provider));
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).
1612
+ strong.textContent = 'Waiting for sign-in…';
1613
+ // The claude.ai page in the browser keeps its OWN session: it may still show the previous
1614
+ // account with an "Switch account" link of its own, and no CLI verb can clear that. Said
1615
+ // at the one moment it matters, for the one provider it applies to.
1616
+ copy.textContent = `Finish signing in using the window FloLess opened.${provider === 'claude'
1617
+ ? ' If the Claude page in your browser still shows the previous account, use its own Switch account link.' : ''}`;
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));
1623
+ } else if (providerReady()) {
1624
+ strong.textContent = 'Ready when you are';
1625
+ copy.textContent = `This ${label} conversation is stored with ${state.scope?.label || 'this work'}.`;
1626
+ empty.append(strong, copy);
1627
+ } else if (state.capability?.runtime && state.capability.runtime.state !== 'installed') {
1628
+ const notice = runtimeNotice(provider, state.capability.runtime);
1629
+ strong.textContent = notice.title;
1630
+ copy.textContent = state.capability.runtime.state === 'failed'
1631
+ ? notice.body
1632
+ : 'You can write your first message now. Send becomes available when setup finishes.';
1633
+ empty.append(strong, copy);
1634
+ } else {
1635
+ strong.textContent = `${label} needs attention`;
1636
+ copy.textContent = capabilityMessage(provider, state.capability?.reason);
1637
+ empty.append(strong, copy);
1638
+ if (signInNeeded(state.capability?.reason)) empty.append(emptySignInButton(label, false));
1639
+ }
1640
+ return empty;
1641
+ }
1642
+
1643
+ // The same control as the settings strip's, in the empty state: one `switchAccount()`, one
1644
+ // pending set. Only ever a sign-in — the reason that shows it guarantees that — so it never needs
1645
+ // the strip's "Switch account…" label. Its own command id because it is its own carrier, in its
1646
+ // own place.
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) {
1653
+ const signIn = document.createElement('button');
1654
+ signIn.type = 'button';
1655
+ signIn.className = 'ai-chat-provider-switch ai-chat-empty-signin';
1656
+ signIn.dataset.commandId = 'shell.chat-sign-in';
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
+ });
1669
+ return signIn;
1255
1670
  }
1256
1671
 
1257
1672
  function paintApproval() {
1258
- shell.querySelector('.ai-chat-approval')?.remove();
1673
+ paintApprovalScope();
1674
+ const existing = shell.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope)');
1259
1675
  const approval = state.chat?.pendingApproval;
1260
1676
  const deciding = Boolean(approval && state.decidingApprovalIds.has(approval.approvalId));
1261
1677
  shell.dataset.approvalPending = String(Boolean(approval) && !deciding);
1262
1678
  document.dispatchEvent(new CustomEvent('floless:chat-indicator'));
1263
- if (!approval || deciding) return;
1679
+ if (!approval || deciding) { existing?.remove(); return; }
1680
+ // Keep the same buttons during polling so keyboard focus and pointer clicks survive.
1681
+ if (existing?.dataset.approvalId === approval.approvalId) return;
1682
+ existing?.remove();
1264
1683
  const card = document.createElement('section'); card.className = 'ai-chat-approval';
1684
+ card.dataset.approvalId = approval.approvalId;
1265
1685
  const heading = document.createElement('strong'); heading.textContent = 'Approval needed';
1266
1686
  const copy = document.createElement('p'); copy.textContent = approval.summary;
1267
1687
  const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
1268
1688
  const deny = button('Deny', 'shell.chat-approval-deny');
1269
1689
  const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
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}`;
1270
1696
  deny.addEventListener('click', () => decideApproval('deny'));
1271
1697
  allow.addEventListener('click', () => decideApproval('allow'));
1272
- actions.append(deny, allow); card.append(heading, copy, actions);
1273
- 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);
1718
+ }
1719
+
1720
+ function paintApprovalScope() {
1721
+ const existing = shell.querySelector('.ai-chat-approval-scope');
1722
+ const turn = state.chat?.activeTurn;
1723
+ if (!turn?.accessApprovalGranted || !['running', 'awaiting-approval'].includes(state.chat?.state)) {
1724
+ existing?.remove(); return;
1725
+ }
1726
+ const busy = state.revokingApprovalTurns.has(turn.turnId);
1727
+ if (existing?.dataset.turnId === turn.turnId) {
1728
+ const revoke = existing.querySelector('button');
1729
+ revoke.disabled = busy;
1730
+ revoke.setAttribute('aria-busy', String(busy));
1731
+ return;
1732
+ }
1733
+ existing?.remove();
1734
+ const card = document.createElement('section');
1735
+ card.className = 'ai-chat-approval ai-chat-approval-scope';
1736
+ card.dataset.turnId = turn.turnId;
1737
+ const heading = document.createElement('strong');
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.';
1743
+ const revoke = button('Revoke', 'shell.chat-approval-revoke');
1744
+ revoke.dataset.tip = explanation.textContent;
1745
+ revoke.setAttribute('aria-describedby', explanation.id);
1746
+ revoke.disabled = busy;
1747
+ revoke.setAttribute('aria-busy', String(busy));
1748
+ revoke.addEventListener('click', revokeApprovalScope);
1749
+ card.append(heading, revoke, explanation);
1750
+ ui.approvalTray.prepend(card);
1274
1751
  }
1275
1752
 
1276
1753
  // FloLess installs its own tested copy of Claude Code / Codex. While that copy is being set up (or
@@ -1421,6 +1898,9 @@
1421
1898
 
1422
1899
  function paintAttachments() {
1423
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`);
1424
1904
  for (const attachment of state.attachments) {
1425
1905
  const chip = document.createElement('span'); chip.className = 'ai-chat-attachment';
1426
1906
  if (attachment.mediaType.startsWith('image/')) {
@@ -1453,13 +1933,20 @@
1453
1933
  if (!state.capability) return null;
1454
1934
  return state.capability.models.find((model) => model.id === state.chat?.settings.model)
1455
1935
  || preferredModel(state.chat?.provider, state.capability.models)
1936
+ || state.capability.models.find((model) => model.isDefault)
1456
1937
  || state.capability.models[0] || null;
1457
1938
  }
1458
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.
1459
1942
  function preferredModel(provider, models) {
1460
1943
  if (!provider || !Array.isArray(models)) return null;
1461
- const pattern = provider === 'codex' ? /gpt[- .]?5\.6[- .]?terra/i : /opus/i;
1462
- 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;
1463
1950
  }
1464
1951
 
1465
1952
  function preferredSettings(provider, capability) {
@@ -1474,10 +1961,137 @@
1474
1961
  return text ? text.charAt(0).toUpperCase() + text.slice(1) : '';
1475
1962
  }
1476
1963
 
1964
+ // A plan token is an internal id, not a product name — this machine really reports Codex
1965
+ // `plan: "prolite"`, which means nothing to a user. Only plans a person would recognise from
1966
+ // their own bill are shown; anything else is omitted, because the email is the load-bearing part.
1967
+ const planLabels = { free: 'Free', pro: 'Pro', plus: 'Plus', max: 'Max', team: 'Team', enterprise: 'Enterprise' };
1968
+ function planLabel(plan) {
1969
+ return planLabels[String(plan || '').trim().toLowerCase()] || '';
1970
+ }
1971
+
1972
+ // The server answers with exactly one of four things, and the row says which. Anything else —
1973
+ // a missing or null `account`, which is what readCapability's catch synthesises when the HTTP
1974
+ // request itself failed — is 'unknown': FloLess never learned who would answer, and "not signed
1975
+ // in" there would be a claim it never checked. A working install on Bedrock/Vertex or an API key
1976
+ // answers 'no-identity': signed in, with no email to name.
1977
+ function signInAnswer(answer) {
1978
+ const state = answer && answer.state;
1979
+ if (state === 'signed-in' || state === 'signed-out' || state === 'no-identity') return answer;
1980
+ return { state: 'unknown', reason: (answer && answer.reason) || 'no answer' };
1981
+ }
1982
+
1983
+ // The one place `state.capability` becomes something the row can say. A null capability is the
1984
+ // first read still in flight — a phase, not an answer — so it is the only value that is not one
1985
+ // of the four. paintSettings and the empty state both go through here.
1986
+ function capabilityAnswer(capability) {
1987
+ return capability ? signInAnswer(capability.account) : { state: 'checking' };
1988
+ }
1989
+
1990
+ // A stable identity for "is this a different answer than the one we had?". Comparing emails alone
1991
+ // could not see a sign-OUT (both sides are absent), which is why one never propagated.
1992
+ function answerKey(answer) {
1993
+ const settled = signInAnswer(answer);
1994
+ return settled.state === 'signed-in' ? `signed-in:${settled.email}` : settled.state;
1995
+ }
1996
+
1997
+ function providerAccountLabel(provider, answer) {
1998
+ const label = providerLabels[provider] || provider;
1999
+ if (answer && answer.state === 'checking') return `${label} · checking…`;
2000
+ const settled = signInAnswer(answer);
2001
+ if (settled.state === 'signed-out') return `${label} · not signed in`;
2002
+ if (settled.state === 'no-identity') return `${label} · signed in (no account to show)`;
2003
+ if (settled.state === 'unknown') return `${label} · could not check`;
2004
+ const plan = planLabel(settled.plan);
2005
+ return plan ? `${label} · ${settled.email} · ${plan}` : `${label} · ${settled.email}`;
2006
+ }
2007
+
2008
+ async function switchAccount() {
2009
+ const chat = state.chat;
2010
+ if (!chat || state.signInPending.has(chat.provider)) return;
2011
+ const snapshot = captureChat();
2012
+ const before = answerKey(state.capability?.account);
2013
+ state.signInPending.add(chat.provider);
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.
2017
+ paintSettings(); paintEvents();
2018
+ try {
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.`);
2024
+ await waitForSignIn(chat.provider, before);
2025
+ if (sameChat(snapshot)) await loadCapability();
2026
+ } catch (error) {
2027
+ const code = String(error && error.code || '');
2028
+ const worded = SERVER_WORDED_SIGN_IN_CODES.has(code) && typeof error?.message === 'string' && error.message.trim();
2029
+ if (sameChat(snapshot)) {
2030
+ report(error, 'Could not switch account', worded ? { [code]: error.message } : signInMessages);
2031
+ // The server signs the CLI out BEFORE it opens the window, so a launch that failed after that
2032
+ // step left the CLI signed out: re-read, or the feed says "Ready when you are" over a dead Send.
2033
+ await loadCapability();
2034
+ }
2035
+ } finally {
2036
+ state.signInPending.delete(chat.provider);
2037
+ // This runs outside every try above, and the click handler calls switchAccount() with `void`:
2038
+ // a throw from the repaint would surface as an unhandled rejection with nothing to catch it.
2039
+ // The feed's empty state carries the same button and the waiting copy, so it repaints too.
2040
+ try { if (sameChat(snapshot)) { paintSettings(); paintEvents(); updateSendState(); } } catch (error) {
2041
+ console.warn('floless: could not repaint the provider row after a sign-in', error);
2042
+ }
2043
+ }
2044
+ }
2045
+
2046
+ // The sign-in itself happens in the window FloLess opened. Poll the cheap runtimes read (no
2047
+ // provider launch, 10 s server cache) until that provider NAMES a sign-in different from the one
2048
+ // held at click time, or give up. A different sign-in, not "a different email": signing in with
2049
+ // an API key produces no email, and the button would sit disabled for the full two minutes. And
2050
+ // not "any definite change" either: the server signs the CLI out BEFORE the window opens, so
2051
+ // signed-out is what every poll sees while the user is still in it — ending there would offer
2052
+ // "Sign in…" again with the window open (the server refuses that click for its launch cooldown).
2053
+ // And once that sign-out HAS been seen, any named sign-in is the landed one — including the same
2054
+ // account again: a user who changes their mind in the browser must not wait out the deadline.
2055
+ async function waitForSignIn(provider, before, deadlineMs = 120_000, everyMs = 3_000) {
2056
+ const until = Date.now() + deadlineMs;
2057
+ let signedOutSeen = false;
2058
+ while (Date.now() < until) {
2059
+ await new Promise((resolve) => setTimeout(resolve, everyMs));
2060
+ let info = null;
2061
+ try { info = await request('/api/terminal-runtimes'); } catch { continue; }
2062
+ const row = info?.runtimes?.find((runtime) => runtime?.id === provider);
2063
+ if (!row) continue;
2064
+ const answer = signInAnswer(row.account);
2065
+ // An 'unknown' answer is a read that never completed; it is not evidence the window closed.
2066
+ if (answer.state === 'unknown') continue;
2067
+ // A 'signed-out' is FloLess's own doing (above), not the sign-in the user went off to make.
2068
+ if (answer.state === 'signed-out') { signedOutSeen = true; continue; }
2069
+ if (signedOutSeen || answerKey(answer) !== before) return;
2070
+ }
2071
+ }
2072
+
1477
2073
  function paintSettings() {
1478
2074
  const chat = state.chat;
1479
2075
  ui.settingsToggle.disabled = !chat;
1480
- ui.provider.querySelector('strong').textContent = chat ? providerLabels[chat.provider] : '—';
2076
+ const answer = capabilityAnswer(state.capability);
2077
+ const pendingSignIn = Boolean(chat && state.signInPending.has(chat.provider));
2078
+ const accountLabel = chat ? providerAccountLabel(chat.provider, answer) : '—';
2079
+ const providerValue = ui.provider.querySelector('strong');
2080
+ // The value is an aria-live region and this repaints on every 5 s poll: writing an unchanged
2081
+ // string would read the account out to a screen reader again every five seconds.
2082
+ if (providerValue.textContent !== accountLabel) providerValue.textContent = accountLabel;
2083
+ // The tooltip repeats that same text, so keep it in step without a redundant attribute write.
2084
+ if (!chat) delete providerValue.dataset.tip;
2085
+ else if (providerValue.dataset.tip !== accountLabel) providerValue.dataset.tip = accountLabel;
2086
+ ui.switchAccount.hidden = !chat;
2087
+ // Only a parsed negative may invite a sign-in. A read that never completed has not earned the
2088
+ // invitation, and a CLI on Bedrock/Vertex or an API key is signed in already.
2089
+ ui.switchAccount.textContent = pendingSignIn ? 'Waiting for sign-in…'
2090
+ : answer.state === 'signed-out' ? 'Sign in…' : 'Switch account…';
2091
+ ui.switchAccount.disabled = !chat || pendingSignIn || Boolean(chat.activeTurn);
2092
+ const switchBlocked = chat?.activeTurn && !pendingSignIn ? 'Wait for the current AI reply to finish before switching accounts.' : '';
2093
+ if (switchBlocked) { ui.switchAccount.dataset.tip = switchBlocked; ui.switchAccount.dataset.blockedReason = switchBlocked; }
2094
+ else { delete ui.switchAccount.dataset.tip; delete ui.switchAccount.dataset.blockedReason; }
1481
2095
  const model = selectedModel();
1482
2096
  ui.model.querySelector('strong').textContent = chat?.settings.model ? (model?.label || chat.settings.model) : (model?.label || 'Choose model');
1483
2097
  const medium = (model?.efforts || []).find((effort) => effort.toLowerCase() === 'medium');
@@ -1541,6 +2155,8 @@
1541
2155
  }
1542
2156
 
1543
2157
  function paintConversation() {
2158
+ paintComposerDisclosure();
2159
+ paintTeklaChip();
1544
2160
  const chat = state.chat;
1545
2161
  if (!chat) { providerChooser(); paintHistory(); return; }
1546
2162
  ui.historyToggle.disabled = false;
@@ -1549,13 +2165,26 @@
1549
2165
  ui.scope.textContent = `${state.scope.label} · ${providerLabels[chat.provider]}`;
1550
2166
  ui.rename.hidden = Boolean(chat.activeTurn) || Boolean(chat.archivedAt);
1551
2167
  ui.input.disabled = Boolean(chat.archivedAt) || chat.state === 'recovery' || requestExecutionBlocked();
1552
- 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;
1553
2170
  const active = turnIsVisiblyActive(chat);
1554
2171
  ui.stop.hidden = !active || Boolean(chat.activeTurn?.local);
1555
- ui.send.hidden = active;
2172
+ ui.send.hidden = false;
1556
2173
  paintSettings(); paintRecovery(); paintApproval(); paintRuntime(); paintAttachments(); paintEvents(); paintHistory(); updateSendState();
1557
2174
  }
1558
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
+
1559
2188
  function closeSource() {
1560
2189
  if (state.eventReconnectTimer) { clearTimeout(state.eventReconnectTimer); state.eventReconnectTimer = null; }
1561
2190
  if (state.source) { state.source.close(); state.source = null; }
@@ -1608,13 +2237,24 @@
1608
2237
  state.eventReconnectChatId = chatId;
1609
2238
  state.eventReconnectAttempt = 0;
1610
2239
  }
1611
- 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));
1612
2241
  const source = new EventSource(`/api/chat/conversations/${encodeURIComponent(chatId)}/events?${ownerQuery(scope.owner)}&after=${after}`);
1613
2242
  state.source = source;
1614
2243
  source.addEventListener('chat-event', (message) => {
1615
2244
  if (state.chat?.chatId !== chatId) return;
1616
2245
  const event = JSON.parse(message.data);
1617
- 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)) {
1618
2258
  state.events = state.events.filter((item) => !(item.optimistic && item.clientSubmissionId === event.clientSubmissionId));
1619
2259
  }
1620
2260
  if (state.events.some((item) => item.eventId === event.eventId)) return;
@@ -1631,9 +2271,21 @@
1631
2271
  state.chat = { ...state.chat, state: 'completed', activeTurn: null };
1632
2272
  paintConversation();
1633
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
+ }
1634
2285
  paintEvents(); paintUnread();
1635
2286
  if (!document.hidden && !ui.feed.closest('[hidden]')) markRead();
1636
- 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);
1637
2289
  });
1638
2290
  source.addEventListener('ready', () => {
1639
2291
  if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
@@ -1647,6 +2299,21 @@
1647
2299
  };
1648
2300
  }
1649
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
+
1650
2317
  async function ensureSession() {
1651
2318
  if (state.sessionReady) return;
1652
2319
  await request('/api/chat/session');
@@ -1714,10 +2381,14 @@
1714
2381
  closeSource();
1715
2382
  clearLiveStream(true);
1716
2383
  state.chat = null; state.events = []; state.capability = null; state.desktop = null;
1717
- state.attachments = []; state.integrations = null;
2384
+ state.attachments = []; state.followupUnknownId = null; state.integrations = null;
2385
+ updateOffscreenActivity();
1718
2386
  // The header switches to the next conversation now; the previous provider's setup card and composer
1719
2387
  // hint must not stay under it while that conversation opens.
1720
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 });
1721
2392
  ui.title.textContent = listed?.title || 'Opening conversation';
1722
2393
  ui.scope.textContent = listed ? `${state.scope?.label || ''} · ${providerLabels[listed.provider]}` : 'Opening conversation';
1723
2394
  ui.rename.hidden = true;
@@ -1725,12 +2396,12 @@
1725
2396
  ui.stop.hidden = true; ui.send.hidden = false;
1726
2397
  ui.settings.hidden = true; ui.settingsToggle.setAttribute('aria-expanded', 'false');
1727
2398
  ui.recovery.hidden = true;
1728
- shell.querySelector('.ai-chat-approval')?.remove();
2399
+ ui.approvalTray.replaceChildren();
1729
2400
  ui.attachments.replaceChildren();
1730
2401
  ui.feed.replaceChildren();
1731
2402
  const loading = document.createElement('div'); loading.className = 'ai-chat-empty';
1732
2403
  const strong = document.createElement('strong'); strong.textContent = 'Opening conversation';
1733
- const copy = document.createElement('div'); copy.textContent = listed
2404
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy'; copy.textContent = listed
1734
2405
  ? `Loading “${listed.title}”…`
1735
2406
  : 'Loading the selected conversation…';
1736
2407
  loading.append(strong, copy); ui.feed.append(loading);
@@ -1746,6 +2417,9 @@
1746
2417
  // A provider picker is an explicit user choice. Only an action that explicitly replaces it
1747
2418
  // may select a stored chat; background scope refreshes must leave the picker untouched.
1748
2419
  if (state.choosingProvider && options.replaceProviderChoice !== true) return;
2420
+ // Opening an existing conversation abandons an unsent discovery handoff. Only the
2421
+ // conversation created from that chooser should inherit its draft.
2422
+ if (!options.preserveDiscoveryDraft) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; }
1749
2423
  clearProviderChoice();
1750
2424
  const selection = ++state.selectionGeneration;
1751
2425
  const exactAnswer = typeof options.answerEventId === 'string' ? options.answerEventId : null;
@@ -1777,10 +2451,14 @@
1777
2451
  state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
1778
2452
  state.chat = chat;
1779
2453
  state.events = snapshot.events || [];
2454
+ reconcileUnknownFollowupOnSelection(chat);
1780
2455
  state.capability = capability;
1781
2456
  state.desktop = desktop;
1782
2457
  state.attachments = (chat.attachments || []).filter((attachment) => !attachment.turnId);
1783
- 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();
1784
2462
  if (answerTarget) {
1785
2463
  state.answerJump = { chatId, eventId: answerTarget.eventId, expiresAt: Date.now() + 2600 };
1786
2464
  state.answerJumpTimer = setTimeout(() => {
@@ -1788,6 +2466,7 @@
1788
2466
  }, 2600);
1789
2467
  }
1790
2468
  paintConversation(); connectEvents();
2469
+ resumeFilterRequests();
1791
2470
  if (options.applyProviderDefaults || !chat.nativeSessionId) await applyProviderDefaults(chatId);
1792
2471
  // Let the server prepare the provider for the next message while the user types, after the
1793
2472
  // default model and effort are saved so the prepared runtime matches the first message. Best-effort:
@@ -1810,6 +2489,28 @@
1810
2489
  finally { if (selection === state.selectionGeneration) setBusy(false); }
1811
2490
  }
1812
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
+
1813
2514
  async function applyProviderDefaults(chatId) {
1814
2515
  if (!state.chat || state.chat.chatId !== chatId || state.chat.nativeSessionId || !state.capability?.available) return;
1815
2516
  const defaults = preferredSettings(state.chat.provider, state.capability);
@@ -1830,6 +2531,7 @@
1830
2531
  return;
1831
2532
  }
1832
2533
  const generation = ++state.scopeGeneration;
2534
+ if (scopeKey(scope) !== scopeKey(state.scope)) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; state.teklaDraft = null; }
1833
2535
  state.selectionGeneration += 1;
1834
2536
  clearAnswerJump();
1835
2537
  clearLiveStream(true);
@@ -1838,6 +2540,10 @@
1838
2540
  state.scope = scope;
1839
2541
  state.scopeInitialized = true;
1840
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();
1841
2547
  state.historyFilter = 'all'; state.instructorAnswers = []; state.historyLoading = false; state.historyRequestGeneration += 1;
1842
2548
  state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
1843
2549
  if (!scope?.owner) { showUnscoped(); return; }
@@ -1859,6 +2565,7 @@
1859
2565
  // older, stale conversation is being recovered). Do not erase the scope and disable the
1860
2566
  // whole panel: the user can still start a new conversation in the project that is open.
1861
2567
  state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null;
2568
+ updateOffscreenActivity();
1862
2569
  ui.scope.textContent = scope.label;
1863
2570
  ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
1864
2571
  paintHistory(); paintUnread(); providerChooser();
@@ -1891,7 +2598,17 @@
1891
2598
  }),
1892
2599
  });
1893
2600
  state.chats.unshift(chat);
1894
- await selectConversation(chat.chatId, { focus: true, applyProviderDefaults: true, replaceProviderChoice: true });
2601
+ await selectConversation(chat.chatId, { focus: true, applyProviderDefaults: true, replaceProviderChoice: true, preserveDiscoveryDraft: true });
2602
+ if (state.discoveryDraft && state.chat?.chatId === chat.chatId) {
2603
+ ui.input.value = state.discoveryDraft;
2604
+ state.discoveryDraft = null;
2605
+ ui.input.dispatchEvent(new Event('input', { bubbles: true }));
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
+ }
1895
2612
  announce(`${providerLabels[provider]} conversation created.`);
1896
2613
  } catch (error) { report(error, 'Could not start conversation'); }
1897
2614
  finally { setBusy(false); }
@@ -1971,6 +2688,7 @@
1971
2688
  state.historyOpen = open;
1972
2689
  shell.classList.toggle('history-open', open);
1973
2690
  ui.history.hidden = !open;
2691
+ updateOffscreenActivity();
1974
2692
  ui.historyToggle.setAttribute('aria-expanded', String(open));
1975
2693
  if (open) {
1976
2694
  ui.settings.hidden = true;
@@ -1979,7 +2697,7 @@
1979
2697
  if (state.historyFilter === 'instructor-answers') refreshInstructorAnswers(true);
1980
2698
  else refreshArchivedChats();
1981
2699
  } else if (options.focusToggle) ui.historyToggle.focus();
1982
- else ui.input.focus();
2700
+ else if (!options.keepFocus) ui.input.focus();
1983
2701
  }
1984
2702
 
1985
2703
  function closePicker() {
@@ -2025,7 +2743,7 @@
2025
2743
  function modelChoices() {
2026
2744
  const models = state.capability?.models || [];
2027
2745
  return models.map((model) => ({
2028
- id: `model:${model.id}`, label: model.label, meta: '',
2746
+ id: `model:${model.id}`, label: model.label, meta: model.detail || '',
2029
2747
  selected: (state.chat.settings.model || selectedModel()?.id) === model.id, patch: { model: model.id },
2030
2748
  }));
2031
2749
  }
@@ -2140,15 +2858,30 @@
2140
2858
  function updateSendState() {
2141
2859
  const active = turnIsVisiblyActive();
2142
2860
  const recovery = state.chat?.state === 'recovery';
2143
- const frozen = recovery || Boolean(state.chat?.activeTurn) || Boolean(state.chat?.archivedAt);
2861
+ const frozen = recovery || Boolean(state.chat?.activeTurn?.local) || Boolean(state.chat?.archivedAt);
2144
2862
  const blocked = requestExecutionBlocked();
2145
2863
  // A provider FloLess is still setting up cannot take a message; the runtime card explains why.
2146
2864
  const settingUp = Boolean(state.capability?.runtime && state.capability.runtime.state !== 'installed');
2147
- ui.input.disabled = !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
2148
- ui.send.disabled = state.loading || !state.chat || blocked || frozen || !ui.input.value.trim() || settingUp;
2149
- ui.attach.disabled = state.loading || !state.chat || blocked || frozen;
2865
+ const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
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
2869
+ || (!ui.input.value.trim() && state.attachments.length === 0) || settingUp;
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.';
2150
2883
  ui.stop.hidden = !active || Boolean(state.chat?.activeTurn?.local);
2151
- ui.send.hidden = active;
2884
+ ui.send.hidden = false;
2152
2885
  // Session recovery must remain available even while provider capability discovery is loading
2153
2886
  // or has failed; it is the escape hatch for that exact state.
2154
2887
  ui.refresh.disabled = !state.chat;
@@ -2161,22 +2894,100 @@
2161
2894
  ui.input.style.height = `${Math.min(132, ui.input.scrollHeight)}px`;
2162
2895
  }
2163
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
+
2164
2904
  function saveDraftSoon() {
2165
2905
  clearTimeout(state.draftTimer);
2166
2906
  if (!state.chat) return;
2167
2907
  const chatId = state.chat.chatId;
2168
2908
  const draft = ui.input.value;
2169
- 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;
2170
2915
  state.draftTimer = setTimeout(async () => {
2171
2916
  if (state.chat?.chatId !== chatId) return;
2172
2917
  try {
2173
- await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/draft`, {
2174
- method: 'PUT', body: JSON.stringify({ owner: state.scope.owner, draft }),
2175
- });
2918
+ await writeChatDraft(chatId, state.scope.owner, draft);
2176
2919
  } catch (error) { report(error, 'Draft was not saved'); }
2177
2920
  }, 350);
2178
2921
  }
2179
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
+
2180
2991
  function paintSkills() {
2181
2992
  ui.skills.replaceChildren();
2182
2993
  const match = ui.input.value.slice(0, ui.input.selectionStart).match(/(?:^|\s)\/([A-Za-z0-9:_-]*)$/u);
@@ -2201,10 +3012,578 @@
2201
3012
  ui.skills.hidden = false;
2202
3013
  }
2203
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
+
2204
3576
  async function sendTurn() {
2205
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; }
2206
3583
  const snapshot = captureChat();
2207
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;
2208
3587
  const text = ui.input.value.trim();
2209
3588
  const uiContext = currentFloLessContext();
2210
3589
  const chatId = snapshot.chatId;
@@ -2218,12 +3597,17 @@
2218
3597
  payload: { text, attachmentIds }, createdAt: new Date().toISOString(), optimistic: true,
2219
3598
  };
2220
3599
  clearTimeout(state.draftTimer);
3600
+ state.localDraft = { chatId, text: '' };
3601
+ state.backgroundDrafts.delete(chatId);
2221
3602
  state.pendingSubmissionId = clientSubmissionId;
2222
3603
  state.events.push(optimisticEvent);
2223
- state.chat = { ...previousChat, state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
3604
+ state.chat = { ...previousChat, draft: '', state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
2224
3605
  ui.input.value = ''; autosize(); state.attachments = []; paintAttachments();
2225
3606
  setBusy(true); paintConversation(); announce('Message sent.');
2226
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(() => {});
2227
3611
  const result = await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/turns`, {
2228
3612
  method: 'POST', body: JSON.stringify({
2229
3613
  // The server alone appends this context to the provider copy. The submitted text and
@@ -2241,16 +3625,215 @@
2241
3625
  // The server accepts a turn only from a ready provider, so a warning from an earlier check is stale.
2242
3626
  if (!providerReady()) void loadCapability().then(() => { if (sameChat(snapshot)) { paintSettings(); updateSendState(); } });
2243
3627
  } catch (error) {
2244
- if (!sameChat(snapshot)) return;
3628
+ if (!sameChat(snapshot)) {
3629
+ if (initialTurnDefinitelyRefused(error)) await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
3630
+ return;
3631
+ }
2245
3632
  state.pendingSubmissionId = null;
2246
3633
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
2247
3634
  state.chat = previousChat;
2248
3635
  state.attachments = previousAttachments;
2249
- ui.input.value = text; autosize(); paintAttachments(); paintConversation();
3636
+ ui.input.value = text; autosize(); paintAttachments(); saveDraftSoon(); paintConversation();
2250
3637
  report(error, 'Message was not sent');
2251
3638
  } finally { if (sameChat(snapshot)) { setBusy(false); updateSendState(); } }
2252
3639
  }
2253
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
+
2254
3837
  async function stopTurn() {
2255
3838
  if (!state.chat?.activeTurn) return;
2256
3839
  const snapshot = captureChat();
@@ -2401,13 +3984,40 @@
2401
3984
  method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, decision }),
2402
3985
  });
2403
3986
  if (!sameChat(snapshot)) return;
2404
- announce(decision === 'allow' ? 'Approved once.' : 'Action denied.');
3987
+ announce(decision === 'allow-request' ? 'Access auto-approval is on for this request.'
3988
+ : decision === 'allow' ? 'Approved once.' : 'Action denied.');
2405
3989
  await refreshConversation(snapshot.chatId, false);
2406
3990
  } catch (error) {
2407
3991
  if (!sameChat(snapshot)) return;
2408
3992
  report(error, 'Could not apply your choice');
2409
3993
  await refreshConversation(snapshot.chatId, false);
2410
- } finally { state.decidingApprovalIds.delete(approvalId); }
3994
+ } finally {
3995
+ state.decidingApprovalIds.delete(approvalId);
3996
+ if (sameChat(snapshot)) paintApproval();
3997
+ }
3998
+ }
3999
+
4000
+ async function revokeApprovalScope() {
4001
+ const turn = state.chat?.activeTurn;
4002
+ const snapshot = captureChat();
4003
+ if (!snapshot || !turn?.accessApprovalGranted || state.revokingApprovalTurns.has(turn.turnId)) return;
4004
+ state.revokingApprovalTurns.add(turn.turnId);
4005
+ paintApprovalScope();
4006
+ try {
4007
+ await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/approval-scope/revoke`, {
4008
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, turnId: turn.turnId }),
4009
+ });
4010
+ if (!sameChat(snapshot)) return;
4011
+ announce('Auto-approval revoked. Future access actions will ask again. Actions already approved may finish.');
4012
+ await refreshConversation(snapshot.chatId, false);
4013
+ } catch (error) {
4014
+ if (!sameChat(snapshot)) return;
4015
+ report(error, 'Could not revoke auto-approval');
4016
+ await refreshConversation(snapshot.chatId, false);
4017
+ } finally {
4018
+ state.revokingApprovalTurns.delete(turn.turnId);
4019
+ if (sameChat(snapshot)) paintApprovalScope();
4020
+ }
2411
4021
  }
2412
4022
 
2413
4023
  function fileBase64(file) {
@@ -2420,18 +4030,31 @@
2420
4030
  }
2421
4031
 
2422
4032
  async function attachFiles(files) {
2423
- 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;
2424
4034
  const snapshot = captureChat();
2425
4035
  if (!snapshot) return;
4036
+ if (state.uploadingChatIds.has(snapshot.chatId)) return;
2426
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;
2427
4050
  const known = [...new Map([...(state.chat.attachments || []), ...state.attachments]
2428
4051
  .map((attachment) => [attachment.attachmentId, attachment])).values()];
2429
4052
  const existingBytes = known.reduce((sum, item) => sum + (item.bytes || 0), 0);
2430
4053
  if (known.length + incoming.length > 10) { report(new Error('You can attach up to 10 files to this conversation.')); return; }
2431
- if (incoming.some((file) => !allowedTypes.has(file.type))) { report(new Error('Attach a PNG, JPEG, WebP, or PDF')); return; }
2432
4054
  if (incoming.some((file) => file.size > 20 * MB)) { report(new Error('Each attachment must be 20 MB or smaller')); return; }
2433
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; }
2434
- ui.attach.disabled = true;
4056
+ state.uploadingChatIds.add(snapshot.chatId);
4057
+ updateSendState();
2435
4058
  try {
2436
4059
  for (const file of incoming) {
2437
4060
  const data = await fileBase64(file);
@@ -2441,11 +4064,19 @@
2441
4064
  });
2442
4065
  if (!sameChat(snapshot)) return;
2443
4066
  state.attachments.push(attachment);
4067
+ state.chat.attachments = [...(state.chat.attachments || []).filter((item) => item.attachmentId !== attachment.attachmentId), attachment];
4068
+ // Commit each successful upload to the visible composer immediately. A later file in the
4069
+ // same batch can fail, but it must not leave this persisted attachment hidden or Send stale.
4070
+ paintAttachments(); updateSendState();
2444
4071
  }
2445
4072
  if (!sameChat(snapshot)) return;
2446
- paintAttachments(); announce(`${incoming.length} attachment${incoming.length === 1 ? '' : 's'} ready for the next message.`);
4073
+ announce(`${incoming.length} attachment${incoming.length === 1 ? '' : 's'} ready for the next message.`);
2447
4074
  } catch (error) { if (sameChat(snapshot)) report(error, 'Could not attach file'); }
2448
- finally { if (sameChat(snapshot)) ui.attach.disabled = false; ui.file.value = ''; }
4075
+ finally {
4076
+ state.uploadingChatIds.delete(snapshot.chatId);
4077
+ ui.file.value = '';
4078
+ if (sameChat(snapshot)) updateSendState();
4079
+ }
2449
4080
  }
2450
4081
 
2451
4082
  async function pollChats() {
@@ -2486,6 +4117,40 @@
2486
4117
  // so a completed turn removes any stale live activity indicator. With no conversation
2487
4118
  // selected the feed is the Claude/Codex chooser, which a repaint would erase.
2488
4119
  paintHistory(); paintUnread();
4120
+ // A sign-in OR a sign-OUT made from Integrations or from the user's own terminal changes who
4121
+ // answers, and nothing else re-reads it — the row would keep naming the old account for the
4122
+ // whole conversation. Use the cheap runtimes read (no provider launch, 10 s server cache)
4123
+ // rather than re-probing the provider, which would start the CLI every five seconds. While
4124
+ // the account is on screen: the settings strip, or the feed's empty state — which shows the
4125
+ // sign-in too (its Sign in… button, and providerReady()), and the first capability read
4126
+ // after a sign-out made elsewhere can still carry the reader's stale answer. Not for a
4127
+ // conversation with messages and the strip closed: past the 10 s server cache this read
4128
+ // asks both CLIs for their status, and nothing there would show the answer.
4129
+ if (state.chat && (!ui.settings.hidden || !state.events.length)) {
4130
+ const chatId = state.chat.chatId;
4131
+ try {
4132
+ const info = await request('/api/terminal-runtimes');
4133
+ state.accountReadWarned = false;
4134
+ const row = info?.runtimes?.find((runtime) => runtime?.id === state.chat?.provider);
4135
+ const answer = row ? signInAnswer(row.account) : null;
4136
+ // Merge on any DEFINITE answer whose identity differs, not on a present email: an email
4137
+ // is absent both when the user signed out and when they never signed in, so an email
4138
+ // comparison can never see a sign-out. An 'unknown' answer is a read that never
4139
+ // completed, and must not overwrite what the row already knows.
4140
+ if (sameScope(scope, generation) && state.chat?.chatId === chatId && state.capability
4141
+ && answer && answer.state !== 'unknown' && answerKey(answer) !== answerKey(state.capability.account)) {
4142
+ state.capability = { ...state.capability, account: answer };
4143
+ }
4144
+ } catch (error) {
4145
+ // The row keeps its last known account and the next poll tries again — but a silent retry
4146
+ // loop leaves an outage with nothing to diagnose it by. Once per outage, not every 5 s.
4147
+ if (!state.accountReadWarned) {
4148
+ state.accountReadWarned = true;
4149
+ console.warn('floless: could not re-read which account will answer', error);
4150
+ }
4151
+ }
4152
+ if (!sameScope(scope, generation)) return;
4153
+ }
2489
4154
  if (state.chat) { paintSettings(); paintRecovery(); paintApproval(); paintEvents(); updateSendState(); }
2490
4155
  if (state.historyOpen && state.historyFilter === 'instructor-answers') refreshInstructorAnswers();
2491
4156
  } catch { /* SSE or the next poll will recover */ }
@@ -2556,6 +4221,229 @@
2556
4221
  await selectConversation(chatId, { focus: true, replaceProviderChoice: true });
2557
4222
  }
2558
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
+
4429
+ async function openDraft(draft) {
4430
+ if (typeof draft !== 'string' || !draft.trim()) return;
4431
+ await refreshScope();
4432
+ if (!state.scope?.owner) throw new Error('Open a project or workflow before asking AI Chat about a local tool.');
4433
+ window.flolessBridge?.revealAiChat?.();
4434
+ ui.tab.click();
4435
+ if (!state.chat || state.chat.activeTurn || state.chat.archivedAt || state.chat.state === 'recovery') {
4436
+ state.discoveryDraft = draft;
4437
+ beginProviderChoice();
4438
+ providerChooser(); clearReport();
4439
+ return;
4440
+ }
4441
+ const existing = ui.input.value.trim();
4442
+ ui.input.value = existing ? `${existing}\n\n${draft}` : draft;
4443
+ ui.input.dispatchEvent(new Event('input', { bubbles: true }));
4444
+ ui.input.focus();
4445
+ }
4446
+
2559
4447
  async function startProjectIntake(submissionId, payload) {
2560
4448
  await ensureSession();
2561
4449
  return request(`/api/chat/project-intakes/${encodeURIComponent(submissionId)}/start`, {
@@ -2571,17 +4459,15 @@
2571
4459
  }
2572
4460
 
2573
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);
2574
4465
  ui.refresh.addEventListener('click', refreshChatSession);
2575
4466
  ui.history.addEventListener('keydown', (event) => {
2576
4467
  if (event.key === 'Escape') { event.preventDefault(); toggleHistory(false, { focusToggle: true }); }
2577
4468
  });
2578
4469
  ui.newChat.addEventListener('click', () => {
2579
- // A prior async select can still be waiting for capability discovery. Invalidate it before
2580
- // showing the provider choice, otherwise it can put the old conversation back over this view.
2581
- state.selectionGeneration += 1;
2582
- state.choosingProvider = true;
2583
- closeSource(); clearLiveStream(true);
2584
- state.chat = null; state.events = []; state.attachments = []; state.integrations = null; state.capability = null;
4470
+ beginProviderChoice();
2585
4471
  toggleHistory(false); setBusy(false); providerChooser(); clearReport();
2586
4472
  });
2587
4473
  ui.rename.addEventListener('click', beginRename);
@@ -2593,16 +4479,24 @@
2593
4479
  ui.title.addEventListener('blur', () => finishRename(ui.title.textContent?.trim() !== ''));
2594
4480
  ui.settingsToggle.addEventListener('click', () => {
2595
4481
  const open = ui.settings.hidden;
2596
- 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 });
2597
4484
  ui.settings.hidden = !open;
2598
4485
  ui.settingsToggle.setAttribute('aria-expanded', String(open));
2599
4486
  closePicker();
2600
4487
  });
2601
4488
  ui.model.addEventListener('click', () => openPicker('model', ui.model, modelChoices()));
4489
+ ui.switchAccount.addEventListener('click', () => { void switchAccount(); });
2602
4490
  ui.effort.addEventListener('click', () => openPicker('effort', ui.effort, effortChoices()));
2603
4491
  ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
2604
4492
  ui.integrations.addEventListener('click', openIntegrations);
2605
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(); });
2606
4500
  ui.stop.addEventListener('click', stopTurn);
2607
4501
  ui.recoveryStop.addEventListener('click', () => { void (state.recoveryCanEnd ? endRecovery() : stopTurn()); });
2608
4502
  ui.reconcile.addEventListener('click', reconcile);
@@ -2622,7 +4516,10 @@
2622
4516
  ui.tab.addEventListener('click', () => markRead());
2623
4517
  document.addEventListener('visibilitychange', () => { if (!document.hidden) { markRead(); pollChats(); } });
2624
4518
  document.addEventListener('pointerdown', (event) => {
2625
- if (!ui.picker.hidden && !ui.picker.contains(event.target) && !event.target.closest('.ai-chat-setting')) closePicker();
4519
+ // Switch account lives inside the Provider .ai-chat-setting but opens no picker of its own, so
4520
+ // it must not be treated as "clicked the picker's own control" and leave an open list behind.
4521
+ if (!ui.picker.hidden && !ui.picker.contains(event.target)
4522
+ && (!event.target.closest('.ai-chat-setting') || event.target.closest('.ai-chat-provider-switch'))) closePicker();
2626
4523
  });
2627
4524
  window.addEventListener('floless:chat-scope-changed', (event) => {
2628
4525
  const next = event.detail || null;
@@ -2639,9 +4536,9 @@
2639
4536
  }
2640
4537
 
2641
4538
  state.refreshTimer = setInterval(pollChats, 5000);
2642
- 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); });
2643
4540
  window.flolessChat = {
2644
- refreshScope, refreshActivity, refreshIndex, startRequest, openConversation,
4541
+ refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openDraft, openVerifiedTeklaDraft,
2645
4542
  startProjectIntake, resumeProjectIntake,
2646
4543
  currentProvider: () => state.chat?.provider ?? null,
2647
4544
  };