@floless/app 0.140.0 → 0.141.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/web/chat.js CHANGED
@@ -11,27 +11,54 @@
11
11
  settings: el('chat-settings'), provider: el('chat-provider'), switchAccount: el('chat-switch-account'), model: el('chat-model'),
12
12
  effort: el('chat-effort'), permission: el('chat-permission'), integrations: el('chat-integrations'),
13
13
  desktopValue: el('chat-desktop-value'), desktopReason: el('chat-desktop-reason'), picker: el('chat-picker'),
14
- feed: el('chat-feed'), recovery: el('chat-recovery'), recoveryCopy: el('chat-recovery-copy'),
14
+ feed: el('chat-feed'), offscreenActivity: el('chat-offscreen-activity'), recovery: el('chat-recovery'),
15
+ approvalTray: el('chat-approval-tray'), recoveryCopy: el('chat-recovery-copy'),
15
16
  reconcile: el('chat-reconcile'), recoveryStop: el('chat-recovery-stop'), attachments: el('chat-attachments'), skills: el('chat-skills'),
16
17
  composer: el('chat-composer'), input: el('chat-input'), file: el('chat-file'), attach: el('chat-attach'),
17
18
  hint: el('chat-compose-hint'), contextNote: el('chat-compose-context'), stop: el('chat-stop'), send: el('chat-send'), status: el('chat-status'),
19
+ disclosure: el('chat-composer-disclosure'),
18
20
  unread: el('chat-unread'), tab: el('narrative-tab'),
19
21
  context: el('left-chat-context'),
22
+ teklaChip: el('chat-tekla-context'),
20
23
  };
21
24
 
22
25
  const state = {
23
26
  // signInPending is keyed by provider: a wait started in one conversation must not paint an
24
27
  // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
25
- sessionReady: false, scope: null, chats: [], archivedChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
26
- source: null, eventReconnectTimer: null, eventReconnectAttempt: 0, eventReconnectChatId: null, attachments: [], integrations: null, historyOpen: false, historyFilter: 'all', archivedHistoryOpen: false,
28
+ sessionReady: false, scope: null, chats: [], archivedChats: [], unreadableChats: [], 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, historyOpenings: 0, historyFilter: 'all', archivedHistoryOpen: false,
27
30
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
28
- draftTimer: null, refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, choosingProvider: false,
29
- answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: 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,
32
+ answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, historyRename: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
30
33
  stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(), revokingApprovalTurns: new Set(), uploadingChatIds: new Set(),
31
34
  // Latched so the 5 s account poll logs an outage once instead of twelve times a minute; cleared
32
35
  // on the next successful read, so a later, separate outage is logged too.
33
36
  accountReadWarned: false,
37
+ // Drawing Filter requests sent from this composer: those still waiting for an answer (each checked
38
+ // on its own timer), failure notices and the last card refusal, keyed by request.
39
+ filterPending: new Map(), filterNotices: new Map(), filterCardMessages: new Map(),
40
+ filterSending: false,
41
+ // The "not sent" sentence of a Drawing Filter message refused while FloLess sets its AI up, kept in
42
+ // the hint while the setup card still shows the setup it was refused for (#1650): { key, sentence }.
43
+ filterSetupNote: null,
44
+ // A Tekla model library carried over from a Graft receipt but not yet bound to its chat. It is
45
+ // browser-only until Send: opening, editing or removing it never calls the binding route.
46
+ // pendingTeklaLibrary waits for the provider chooser to create the chat it belongs to.
47
+ teklaDraft: null, pendingTeklaLibrary: null, teklaRemoveError: null,
34
48
  };
49
+ // A short-window resize can shrink the bounded tray after a decision card was painted.
50
+ // Keep its actions in view only while the reader was already at the bottom; preserve a
51
+ // deliberate scroll up to inspect the request-wide grant notice.
52
+ function keepApprovalTrayDecisionVisible(tray) {
53
+ let atBottom = true;
54
+ tray.addEventListener('scroll', () => {
55
+ atBottom = tray.scrollTop + tray.clientHeight >= tray.scrollHeight - 2;
56
+ });
57
+ new ResizeObserver(() => {
58
+ if (atBottom) tray.scrollTop = tray.scrollHeight;
59
+ }).observe(tray);
60
+ }
61
+ keepApprovalTrayDecisionVisible(ui.approvalTray);
35
62
  const permissionLabels = {
36
63
  'read-only': 'Read only', 'workspace-write': 'Working folder write', 'full-access': 'Full access',
37
64
  };
@@ -49,6 +76,7 @@
49
76
  const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question' };
50
77
  const requestStatusLabels = { pending: 'Queued', queued: 'Queued', running: 'Running', ready: 'Ready', completed: 'Complete', failed: 'Failed', stopped: 'Stopped' };
51
78
  const allowedTypes = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
79
+ const MAX_IMAGES_PER_MESSAGE = 5;
52
80
  const MB = 1024 * 1024;
53
81
 
54
82
  function ownerQuery(owner = state.scope?.owner) {
@@ -73,8 +101,13 @@
73
101
  response = await fetch(path, init);
74
102
  } catch (error) {
75
103
  if (error?.name === 'TimeoutError' || error?.name === 'AbortError') {
76
- const timeout = new Error('FloLess did not respond in time. Check that the local server is running, then try again.');
104
+ // The server is almost always running but busy when this happens (#1604), so the sentence
105
+ // leads with "try again" and keeps "is it still running?" as the fallback.
106
+ const timeout = new Error('FloLess took too long to respond, most likely because it is busy. Try again in a moment — if it keeps happening, make sure FloLess is still running.');
77
107
  timeout.code = 'local-timeout';
108
+ // Which call timed out, and after how long: the sentence above is for the user, this is for
109
+ // whoever reads the console when it happens (#1604).
110
+ timeout.cause = { path, timeoutMs, name: error.name };
78
111
  throw timeout;
79
112
  }
80
113
  throw error;
@@ -84,6 +117,8 @@
84
117
  if (!response.ok) {
85
118
  const error = new Error(body?.error || body || `Chat request failed (${response.status})`);
86
119
  error.code = body?.code || null;
120
+ error.reason = body?.reason || null;
121
+ error.status = response.status;
87
122
  throw error;
88
123
  }
89
124
  return body;
@@ -112,17 +147,46 @@
112
147
  ui.send.disabled = busy || uploading || !state.chat || blocked
113
148
  || (!ui.input.value.trim() && state.attachments.length === 0) || Boolean(state.chat?.activeTurn);
114
149
  ui.attach.disabled = busy || uploading || !state.chat || blocked || Boolean(state.chat?.activeTurn);
150
+ if (!busy) updateSendState();
115
151
  }
116
152
 
117
153
  function errorMessage(error) {
154
+ // A Drawing Filter refusal is already a complete plain-English sentence written for this moment.
155
+ if (error?.filterRefusal) return error.message;
118
156
  const raw = error instanceof Error ? error.message : String(error);
157
+ if (raw === 'This message was not sent because its queued response was cancelled') {
158
+ return 'You stopped the response before AI could take this queued message. Use Retry sending if you still want to send it.';
159
+ }
160
+ if (raw === 'This message was not sent because FloLess could not start its AI response') {
161
+ return 'FloLess could not start this queued AI response, so the message was not sent. Wait a moment, then use Retry sending.';
162
+ }
119
163
  const code = String(error && error.code || '');
164
+ // request() writes the timeout's sentence itself. Without this it fell through to the generic "could
165
+ // not complete this chat action", which hid the one fact the user could act on (#1604).
166
+ if (code === 'local-timeout' && raw) return raw;
120
167
  const codeMessages = {
121
168
  'chat-origin-refused': 'This chat can only be used from the FloLess app. Reload the page and try again.',
122
169
  'chat-owner-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
123
170
  'chat-cwd-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
124
- 'chat-turn-stale': 'This response is no longer active. Refresh the conversation before trying again.',
171
+ 'chat-turn-stale': 'This AI response just finished. Your draft is still here; press Send again to start a new response.',
172
+ '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.',
173
+ '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.',
174
+ 'chat-followup-queued': 'An earlier message is waiting for AI. Wait for it to send before starting another response.',
175
+ 'chat-followup-unconfirmed': 'Waiting to confirm your earlier message before starting another response. Review its delivery status in this conversation.',
176
+ 'chat-message-too-long': 'This message is too long. Shorten it, then send it again.',
177
+ 'chat-followup-too-large': 'This message is too long. Shorten it, then send it again.',
178
+ '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.',
179
+ 'chat-followup-retry-wait': 'This message can be retried after the current AI response finishes.',
180
+ 'chat-followup-retry-unavailable': 'FloLess can only retry a message confirmed as not sent. Review the conversation and write a new message if needed.',
181
+ 'chat-followup-not-unknown': 'This message’s delivery status changed while you were reviewing it. Refresh the conversation before deciding what to do.',
182
+ 'chat-followup-not-found': 'This message is no longer in this conversation. Refresh the conversation.',
183
+ 'chat-attachment-scope': 'An attached file is no longer available to this message. Add the file again in a new message.',
125
184
  'chat-initiator-unknown': 'FloLess could not identify what started this conversation. Reload the conversation and try again.',
185
+ // Damage the user can act on, unlike the refusals below it: the conversation history lists this
186
+ // same record as a row offering Discard, so the sentence sends them there (#1629). Without an
187
+ // entry here the code fell through to the generic "could not complete this chat action", which
188
+ // hid the one fact they could act on.
189
+ 'chat-record-unreadable': 'This conversation’s saved file is damaged, so FloLess cannot open it. Open the conversation history and discard it there.',
126
190
  'chat-record-unsafe': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
127
191
  'chat-record-invalid': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
128
192
  'chat-session-bindings-corrupt': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
@@ -132,6 +196,7 @@
132
196
  'chat-owner-archived': 'This project or workflow is archived. Restore it before continuing the conversation.',
133
197
  'chat-archived': 'This conversation is archived. Start a new conversation to continue.',
134
198
  'chat-turn-active': 'Stop the active response before changing this conversation.',
199
+ 'chat-message-image-limit': 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.',
135
200
  'chat-send-refused': 'The AI service did not accept this message. Check your sign-in and conversation settings, then try again.',
136
201
  'chat-approval-stale': 'This approval is no longer active. Refresh the conversation.',
137
202
  'chat-provider-identity-changed': 'The connected AI account changed while this response was running. Refresh the conversation and try again.',
@@ -156,8 +221,16 @@
156
221
  'request-chat-not-ready': 'This request is still being prepared. Wait a moment, then try again.',
157
222
  'chat-knowledge-unscoped': 'Knowledge is available only inside a project conversation. Open a project and try again.',
158
223
  'chat-knowledge-page-missing': 'That Knowledge page is no longer available in this project. Refresh the conversation.',
224
+ 'approval-explicit-only': 'This read needs its own approval. Choose Approve once or Deny.',
159
225
  };
226
+ if (code === 'chat-followup-refused' && error?.reason === 'chat-session-required') {
227
+ return 'Your FloLess session expired before this message was sent. Copy the draft, reload, then paste and send it again.';
228
+ }
229
+ if (code === 'chat-followup-refused' && codeMessages[String(error?.reason || '')]) {
230
+ return codeMessages[String(error.reason)];
231
+ }
160
232
  if (codeMessages[code]) return codeMessages[code];
233
+ if (error?.status === 413) return 'This message is too large to send. Shorten it, then try again.';
161
234
  if (code === 'request-chat-owner-mismatch' || /request chat link belongs to another owner/i.test(raw)) {
162
235
  return 'This request is linked to another project or workflow. Open the project or workflow shown on the request, then try again.';
163
236
  }
@@ -256,17 +329,48 @@
256
329
  function report(error, prefix = '', messages = null) {
257
330
  const code = String(error && error.code || '');
258
331
  const message = `${prefix}${prefix ? ': ' : ''}${messages?.[code] || errorMessage(error)}`;
332
+ // Keep the raw cause (#1604): the user-facing sentence deliberately drops it, and without it a
333
+ // failure could only be diagnosed from the server log. A timeout, a network failure or a server
334
+ // error the server did not explain is unexpected, so it is an error. A refusal the server named
335
+ // with its own code — a 4xx, or an expected 5xx such as `chat-provider-unavailable` — is a
336
+ // warning. A check made here in the browser (too many images, a file too large) is neither: the
337
+ // sentence already says everything, so it is not logged.
338
+ const status = Number.isInteger(error?.status) ? error.status : null;
339
+ const unexpected = code === 'local-timeout' || (status !== null && status >= 500 && !code)
340
+ || error?.name === 'TypeError' || error?.name === 'SyntaxError';
341
+ if (unexpected) console.error(`[ai-chat] ${message}`, error?.cause ?? '', error);
342
+ else if (status !== null) console.warn(`[ai-chat] ${message}`, error);
259
343
  announce(message);
260
344
  ui.hint.textContent = message;
261
345
  ui.hint.classList.add('error');
262
346
  }
263
347
 
348
+ // A Drawing Filter message refused while FloLess sets its AI up (#1650) keeps its sentence in the hint
349
+ // while the card still shows that very setup and the refused words are still in the draft, which the
350
+ // sentence says they are. Every repaint asks again, so the sentence ends with the first of those to
351
+ // change (the setup finished, was cancelled or failed another way, another conversation, the words
352
+ // removed) and the card speaks for itself.
353
+ function filterSetupHint() {
354
+ const note = state.filterSetupNote;
355
+ if (!note) return null;
356
+ const status = state.chat ? state.capability?.runtime : null;
357
+ if (status && runtimeCardKey(state.chat.chatId, status) === note.key && ui.input.value.includes(note.text)) return note.sentence;
358
+ state.filterSetupNote = null;
359
+ return null;
360
+ }
361
+
264
362
  function clearReport() {
265
363
  ui.hint.classList.remove('error');
364
+ const filterNote = filterSetupHint();
266
365
  const message = requestExecutionBlocked()
267
366
  ? 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.'
367
+ : state.followupUnknownId || hasUnknownFollowup()
368
+ ? 'FloLess could not confirm this message. Check its status and use the action beside it before sending again.'
369
+ : state.imageLimitChatId === state.chat?.chatId
370
+ && state.attachments.filter(attachment => attachment.mediaType.startsWith('image/')).length >= MAX_IMAGES_PER_MESSAGE
371
+ ? 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.'
268
372
  : state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
269
- ? runtimeNotice(state.chat.provider, state.capability.runtime).body
373
+ ? filterNote || runtimeNotice(state.chat.provider, state.capability.runtime).body
270
374
  : state.chat && !providerReady()
271
375
  ? `${capabilityMessage(state.chat.provider, state.capability?.reason)} You can still write a message; Send will retry the connection.`
272
376
  : state.chat?.state === 'recovery'
@@ -274,14 +378,17 @@
274
378
  : !state.scope?.owner
275
379
  ? 'Open a project or workflow to start chatting.'
276
380
  : 'Enter to send · Shift+Enter for a new line';
277
- if (turnIsVisiblyActive()) {
278
- ui.hint.replaceChildren();
381
+ if (turnIsVisiblyActive() && !state.followupUnknownId && !hasUnknownFollowup()
382
+ && state.imageLimitChatId !== state.chat?.chatId) {
383
+ ui.hint.textContent = 'AI is working · send a follow-up without stopping';
279
384
  ui.hint.classList.remove('working');
280
- ui.hint.setAttribute('aria-label', 'AI is working');
385
+ ui.hint.removeAttribute('aria-label');
281
386
  } else {
282
387
  ui.hint.classList.remove('working');
283
388
  ui.hint.removeAttribute('aria-label');
284
389
  ui.hint.textContent = message;
390
+ // Painted as it was reported, so the poll does not restyle it.
391
+ if (filterNote && message === filterNote) ui.hint.classList.add('error');
285
392
  }
286
393
  }
287
394
 
@@ -303,7 +410,11 @@
303
410
  && capabilityAnswer(state.capability).state !== 'signed-out');
304
411
  }
305
412
 
306
- function currentFloLessContext() {
413
+ function currentSurface() {
414
+ return currentFloLessContext({ surfaceOnly: true }).surface;
415
+ }
416
+
417
+ function currentFloLessContext(options = {}) {
307
418
  const workspaceMode = document.querySelector('#mode-switch [data-mode="workspaces"]')?.getAttribute('aria-selected') === 'true';
308
419
  const workflowMode = document.querySelector('#mode-switch [data-mode="workflows"]')?.getAttribute('aria-selected') === 'true';
309
420
  const reportOpen = document.getElementById('report-modal')?.classList.contains('show') === true;
@@ -322,6 +433,7 @@
322
433
  : editorOpen ? 'model-editor'
323
434
  : workspaceMode ? (workspaceProjectOpen ? workspaceSurface : 'project-list')
324
435
  : dashboardVisible ? 'dashboard' : 'workflow-canvas';
436
+ if (options.surfaceOnly) return { surface };
325
437
  return {
326
438
  mode: workspaceMode ? 'workspaces' : workflowMode ? 'workflows' : 'canvas',
327
439
  surface,
@@ -376,11 +488,23 @@
376
488
 
377
489
  function paintFloLessContext() {
378
490
  if (!ui.contextNote) return;
379
- const context = currentFloLessContext();
380
- ui.contextNote.replaceChildren();
381
- const prefix = document.createElement('strong');
382
- prefix.textContent = 'Sharing with AI: ';
383
- ui.contextNote.append(prefix, document.createTextNode(floLessContextLabel(context)));
491
+ const filter = paintFilterComposer();
492
+ // A Drawing Filter message sends a bounded description of this sheet's controls and text, not
493
+ // the visible page, and says so rather than implying AI sees the whole drawing. This note is also
494
+ // the composer's only mention of which sheet a Drawing Filter message is about.
495
+ const shared = filter.state === 'off'
496
+ ? floLessContextLabel(currentFloLessContext())
497
+ : filter.state === 'ready' ? `Drawing Filter · partial view of ${filter.summary.sheet || 'this sheet'} and its selection`
498
+ : 'Drawing Filter · loading…';
499
+ // A live region: rewritten only when the text changes, or every keystroke would re-announce it.
500
+ if (ui.contextNote.textContent !== `Sharing with AI: ${shared}`) {
501
+ const prefix = document.createElement('strong');
502
+ prefix.textContent = 'Sharing with AI: ';
503
+ ui.contextNote.replaceChildren(prefix, document.createTextNode(shared));
504
+ }
505
+ ui.send.dataset.tip = ui.contextNote.textContent;
506
+ // Leaving or returning to the Drawing Filter changes whether a suggestion can be applied.
507
+ refreshFilterCards();
384
508
  }
385
509
 
386
510
  function commandInstance(value) {
@@ -530,7 +654,22 @@
530
654
  return node;
531
655
  }
532
656
 
657
+ // The composer's disclosure line. Derived from state in ONE place and called from every render
658
+ // entry point, rather than switched on where the chooser is built and off in each of the paths
659
+ // that leave it: a guarantee assembled from N call sites is only as good as the one someone
660
+ // forgets. It shows exactly where the card's own copy would say it — a scoped conversation that
661
+ // has not been started yet — so the sentence is on screen before the first message either way,
662
+ // at every panel height, including the ones where the card itself cannot fit (#1501).
663
+ // `opening` is passed by showConversationLoading, which nulls state.chat while it fetches a
664
+ // conversation the user has already picked. Without it the transient null reads as "no chat
665
+ // chosen yet" and the disclosure flashes on over a conversation that is merely loading — the
666
+ // predicate would be answering a question about state rather than about what the user is doing.
667
+ function paintComposerDisclosure(options = {}) {
668
+ ui.disclosure.hidden = options.opening === true || Boolean(state.chat) || !state.scope?.owner;
669
+ }
670
+
533
671
  function providerChooser() {
672
+ paintComposerDisclosure();
534
673
  // The workspace landing page has no conversation owner. It must never offer a provider,
535
674
  // history, or refresh there: none of those actions has a chat to operate on.
536
675
  // No provider is chosen here (nor on the unscoped landing), so a setup card left from the previous
@@ -538,11 +677,12 @@
538
677
  shell.querySelector('.ai-chat-runtime')?.remove(); stopRuntimePoll();
539
678
  if (!state.scope?.owner) { showUnscoped(); return; }
540
679
  ui.feed.replaceChildren();
680
+ updateOffscreenActivity();
541
681
  const empty = document.createElement('div');
542
682
  empty.className = 'ai-chat-empty';
543
683
  const strong = document.createElement('strong');
544
684
  strong.textContent = state.chats.length ? 'Start a new conversation' : 'Start this conversation';
545
- const copy = document.createElement('div');
685
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
546
686
  copy.textContent = 'FloLess keeps this chat with the project on this computer. Messages and attachments are sent to Claude or Codex through your account.';
547
687
  const row = document.createElement('div');
548
688
  row.className = 'ai-chat-provider-row';
@@ -560,23 +700,9 @@
560
700
  accounts.textContent = 'Checking signed-in accounts…';
561
701
  empty.append(accounts);
562
702
  // There is no chat yet, so no capability probe exists; the runtimes read carries the same sign-in.
563
- request('/api/terminal-runtimes').then((info) => {
564
- if (!accounts.isConnected) return;
565
- accounts.replaceChildren(...['claude', 'codex'].map((provider) => {
566
- const cell = document.createElement('span');
567
- const runtime = info?.runtimes?.find((r) => r?.id === provider);
568
- // Each row carries its OWN answer — including that its status read failed — so this must
569
- // state that answer rather than assume the read landed. A runtime missing from the list
570
- // is a known absence, not an unchecked one, hence the flat "not installed" wording.
571
- cell.textContent = runtime ? providerAccountLabel(provider, runtime.account) : `${providerLabels[provider]} · not installed`;
572
- return cell;
573
- }));
574
- }).catch((error) => {
575
- // The line disappears rather than guessing; without this the feature vanishing is invisible.
576
- console.warn('floless: could not read the signed-in accounts for the chooser', error);
577
- if (accounts.isConnected) accounts.remove();
578
- });
703
+ readChooserAccounts(accounts);
579
704
  ui.feed.append(empty);
705
+ paintUnreadableNotice();
580
706
  ui.title.textContent = 'New conversation';
581
707
  const providerValue = ui.provider.querySelector('strong');
582
708
  providerValue.textContent = 'Choose Claude or Codex';
@@ -588,6 +714,151 @@
588
714
  ui.historyToggle.disabled = false;
589
715
  ui.refresh.disabled = true;
590
716
  ui.settingsToggle.disabled = true;
717
+ // The ⚙ toggle is disabled here, so a strip left open from the previous conversation (+ New
718
+ // conversation pressed with it open) could no longer be closed, and it would take its height from
719
+ // the conversation area the Claude / Codex choice needs (#1554). There is no conversation for its
720
+ // settings to act on, so it closes, as it does on the unscoped landing.
721
+ ui.settings.hidden = true; ui.settingsToggle.setAttribute('aria-expanded', 'false');
722
+ closePicker();
723
+ }
724
+
725
+ // A project whose only conversations are damaged opens on the Claude / Codex choice, with the
726
+ // History list closed: without this line nothing on screen would say those conversations exist
727
+ // (#1619). Deliberately quiet (dim text, no badge) — the ☷ unread badge means new messages.
728
+ function paintUnreadableNotice() {
729
+ const card = ui.feed.querySelector('.ai-chat-empty');
730
+ const count = state.unreadableChats?.length || 0;
731
+ let notice = card?.querySelector('.ai-chat-unreadable-notice') || null;
732
+ if (!card || !count) { notice?.remove(); return; }
733
+ if (!notice) {
734
+ notice = document.createElement('div'); notice.className = 'ai-chat-unreadable-notice';
735
+ card.append(notice);
736
+ }
737
+ notice.textContent = count === 1
738
+ ? `1 conversation in this ${state.scope.owner.kind} can’t be opened — see History.`
739
+ : `${count} conversations in this ${state.scope.owner.kind} can’t be opened — see History.`;
740
+ }
741
+
742
+ // The waits between re-reads of a chooser account that came back 'unknown' (#1606). The server
743
+ // answers 'unknown' when the CLI status read threw or timed out — a transient answer it replaces
744
+ // on its next read — but nothing else re-reads while the chooser is up: pollChats() has no chat to
745
+ // read for ("no chat, no read"). Without this, one slow first read froze "could not check" under
746
+ // both buttons for as long as the chooser stayed open. Backs off to the last value and repeats it;
747
+ // past the 10 s server cache each read asks the CLI again, so the floor stays at seconds, not ms.
748
+ const CHOOSER_ACCOUNT_RETRY_MS = [2_000, 4_000, 8_000, 16_000, 30_000];
749
+ // The rows a re-read may still change: an account the server could not check yet, and FloLess's own
750
+ // copy of an AI that is not set up yet (#1622). Every other row already says what it knows.
751
+ const CHOOSER_PENDING_STATES = new Set(['unknown', 'setup']);
752
+
753
+ // The one chooser account read in flight, shared by every line that asks while it is pending. A
754
+ // repaint (+ New conversation pressed again, a project reopened) builds a new line while the old
755
+ // line's read may still be waiting on a slow CLI; without this each repaint would add another
756
+ // concurrent request instead of reusing the one already on its way.
757
+ let chooserAccountsRead = null;
758
+ function readChooserRuntimes() {
759
+ if (!chooserAccountsRead) {
760
+ chooserAccountsRead = request('/api/terminal-runtimes')
761
+ .finally(() => { chooserAccountsRead = null; });
762
+ }
763
+ return chooserAccountsRead;
764
+ }
765
+
766
+ // What the chooser says about FloLess's own copy of an AI that is not ready to answer yet (#1622),
767
+ // in the New project dialog's words: until that copy is set up there is no account to check, so
768
+ // "retrying…" would promise an answer that cannot come. Null when the account line applies — no
769
+ // managed copy (the user's install runs), or a copy ready to launch. The state is the shared
770
+ // `chatRuntimeReadiness` (web/aware.js), so this line cannot disagree with what a start would do.
771
+ function chooserSetupLine(provider, runtime) {
772
+ const managed = runtime && runtime.managed && typeof runtime.managed === 'object' ? runtime.managed : null;
773
+ const readiness = managed ? window.flolessBridge?.chatRuntimeReadiness?.(runtime) : null;
774
+ if (!readiness || readiness === 'ready') return null;
775
+ const label = providerLabels[provider];
776
+ // Only a setup still to come can change on its own; a copy FloLess cannot start is a final answer.
777
+ if (readiness === 'setup') {
778
+ if (managed.state === 'preparing') return { text: `${label} · setting up…`, state: 'setup' };
779
+ if (managed.state === 'failed') return { text: `${label} · setup failed, choosing it tries again`, state: 'setup' };
780
+ return { text: `${label} · not set up yet`, state: 'setup' };
781
+ }
782
+ return { text: `${label} · couldn’t be set up`, state: 'unavailable' };
783
+ }
784
+
785
+ function chooserAccountCell(provider, runtime, attempt) {
786
+ const cell = document.createElement('span');
787
+ // A runtime missing from the list is a known absence, not an unchecked one: flat "not installed".
788
+ const answer = runtime ? signInAnswer(runtime.account) : null;
789
+ const setup = runtime ? chooserSetupLine(provider, runtime) : null;
790
+ cell.dataset.provider = provider;
791
+ // A copy FloLess is still to set up is re-read like an unknown account, so the row moves on by
792
+ // itself once the setup lands (started from this chooser, another surface or another window).
793
+ cell.dataset.accountState = setup ? setup.state : answer ? answer.state : 'not-installed';
794
+ if (setup) cell.textContent = setup.text;
795
+ else if (!answer) cell.textContent = `${providerLabels[provider]} · not installed`;
796
+ // While the first few re-reads are still due, say so rather than show a verdict that is about to
797
+ // be replaced; once the backoff has reached its slowest step the row says what it knows — the
798
+ // re-read carries on at that pace and still updates the row in place if an answer lands.
799
+ else if (answer.state === 'unknown' && attempt < CHOOSER_ACCOUNT_RETRY_MS.length - 1) cell.textContent = `${providerLabels[provider]} · retrying…`;
800
+ else cell.textContent = providerAccountLabel(provider, answer);
801
+ return cell;
802
+ }
803
+
804
+ // Reads the chooser's account line, then re-reads it on the backoff above while any row is still
805
+ // 'unknown' and this line is still on screen. One chain per line, strictly sequential — the next
806
+ // read is armed only after the previous one settled — and every read goes through the shared
807
+ // in-flight read above, so neither a chain nor a burst of repaints can overlap requests or pile up
808
+ // sockets. A repaint builds a new line, which disconnects this one and ends its chain at its next
809
+ // step. Only the unknown rows change: each row carries its own answer, and one that was already
810
+ // definite is not re-stated by a later read.
811
+ function readChooserAccounts(accounts, attempt = 0, warned = false) {
812
+ const next = (seenFailure) => {
813
+ const wait = () => setTimeout(() => {
814
+ if (!accounts.isConnected) return;
815
+ // A hidden window or a collapsed chat pane reads nothing, like pollChats(); the chain waits
816
+ // at its current pace and resumes when the line can be seen again.
817
+ if (document.hidden || ui.feed.closest('[hidden]')) { wait(); return; }
818
+ readChooserAccounts(accounts, attempt + 1, seenFailure);
819
+ }, CHOOSER_ACCOUNT_RETRY_MS[Math.min(attempt, CHOOSER_ACCOUNT_RETRY_MS.length - 1)]);
820
+ wait();
821
+ };
822
+ readChooserRuntimes().then((info) => {
823
+ if (!accounts.isConnected) return;
824
+ const cells = ['claude', 'codex'].map((provider) =>
825
+ chooserAccountCell(provider, info?.runtimes?.find((r) => r?.id === provider), attempt));
826
+ const current = [...accounts.querySelectorAll('span')];
827
+ if (current.length !== cells.length) {
828
+ // The first answer replaces the "Checking signed-in accounts…" placeholder.
829
+ accounts.replaceChildren(...cells);
830
+ } else {
831
+ // A re-read: only a row still waiting for an answer takes the new one, in place.
832
+ current.forEach((cell, index) => {
833
+ if (!CHOOSER_PENDING_STATES.has(cell.dataset.accountState)) return;
834
+ const fresh = cells[index];
835
+ cell.dataset.accountState = fresh.dataset.accountState;
836
+ if (cell.textContent !== fresh.textContent) cell.textContent = fresh.textContent;
837
+ });
838
+ }
839
+ if ([...accounts.querySelectorAll('span')].some((cell) => CHOOSER_PENDING_STATES.has(cell.dataset.accountState))) next(warned);
840
+ }).catch((error) => {
841
+ if (!accounts.isConnected) return;
842
+ if (attempt === 0) {
843
+ // The line disappears rather than guessing; without this the feature vanishing is invisible.
844
+ console.warn('floless: could not read the signed-in accounts for the chooser', error);
845
+ accounts.remove();
846
+ return;
847
+ }
848
+ // A re-read that failed outright leaves the rows as they are and tries again at the next step;
849
+ // warned once per line, so a server that went away does not log every half-minute.
850
+ if (!warned) console.warn('floless: could not re-read the signed-in accounts for the chooser', error);
851
+ // Failed re-reads still advance the backoff, so the row must still stop saying "retrying…" at
852
+ // the slowest step — or a server that stopped answering would leave it there for good.
853
+ if (attempt >= CHOOSER_ACCOUNT_RETRY_MS.length - 1) {
854
+ for (const cell of accounts.querySelectorAll('span')) {
855
+ if (cell.dataset.accountState !== 'unknown') continue;
856
+ const label = providerAccountLabel(cell.dataset.provider, { state: 'unknown' });
857
+ if (cell.textContent !== label) cell.textContent = label;
858
+ }
859
+ }
860
+ next(true);
861
+ });
591
862
  }
592
863
 
593
864
  function clearProviderChoice() {
@@ -595,16 +866,18 @@
595
866
  }
596
867
 
597
868
  function showUnscoped() {
869
+ paintComposerDisclosure();
598
870
  clearProviderChoice();
599
871
  closeSource();
600
872
  clearLiveStream(true);
601
- state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = [];
873
+ state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = []; state.followupUnknownId = null;
602
874
  ui.feed.replaceChildren();
875
+ updateOffscreenActivity();
603
876
  const empty = document.createElement('div');
604
877
  empty.className = 'ai-chat-empty';
605
878
  const strong = document.createElement('strong');
606
879
  strong.textContent = 'Open a project or workflow';
607
- const copy = document.createElement('div');
880
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
608
881
  copy.textContent = 'Each project or workflow keeps its own chat history in its folder.';
609
882
  empty.append(strong, copy);
610
883
  ui.feed.append(empty);
@@ -643,12 +916,79 @@
643
916
  function restoreHistoryFocus(commandId) {
644
917
  if (!commandId) return;
645
918
  requestAnimationFrame(() => {
919
+ // Only put back focus the repaint took away. If the person has moved on since (into a row's
920
+ // rename field, say), a late frame must not pull focus out of it — that blur would save
921
+ // the half-typed name (#1582). A hidden tab can hold this frame back for a long time.
922
+ if (document.activeElement && document.activeElement !== document.body) return;
646
923
  [...ui.history.querySelectorAll('[data-command-id]')]
647
924
  .find((candidate) => candidate.dataset.commandId === commandId)?.focus();
648
925
  });
649
926
  }
650
927
 
928
+ // Where keyboard focus goes when a conversation's inline rename ends, so it never falls to the
929
+ // page: the row's ✎, where the rename began; the row itself when ✎ has been withdrawn (the AI
930
+ // is replying); the All filter when the row cannot be seen (it left the list, or sits in the
931
+ // closed Archived list).
932
+ function focusHistoryConversation(chatId) {
933
+ const commandId = `shell.chat-history-item#${chatId}`;
934
+ const row = [...ui.history.querySelectorAll('.ai-chat-history-row')].find((node) => node.dataset.commandId === commandId);
935
+ const closed = row?.closest('details');
936
+ const rowSeen = Boolean(row) && (!closed || closed.open)
937
+ && (typeof row.checkVisibility !== 'function' || row.checkVisibility());
938
+ const renameButton = rowSeen ? row.querySelector('.ai-chat-history-rename') : null;
939
+ const renameSeen = Boolean(renameButton) && !renameButton.hidden
940
+ && (typeof renameButton.checkVisibility !== 'function' || renameButton.checkVisibility());
941
+ (renameSeen ? renameButton : rowSeen ? row : ui.history.querySelector('.ai-chat-history-filter'))?.focus({ preventScroll: true });
942
+ }
943
+
944
+ // Every history repaint goes through here. The list is rebuilt in the background (the 5 s poll,
945
+ // SSE, a lifecycle action elsewhere), and rebuilding it removes a history-row rename field —
946
+ // which fires that field's blur and would save whatever was half-typed (#1582). So carry an open
947
+ // rename across the rebuild: the SAME input moves into the rebuilt row with its text, caret and
948
+ // focus intact. Enter, Escape or the person leaving the field ends it — or the conversation
949
+ // no longer being renamable in this list, which drops the edit unsaved.
651
950
  function paintHistory() {
951
+ const rename = state.historyRename;
952
+ if (!rename) { renderHistory(); return; }
953
+ const { input } = rename;
954
+ const hadFocus = document.activeElement === input;
955
+ const { selectionStart, selectionEnd, selectionDirection } = input;
956
+ rename.repainting = true;
957
+ try { renderHistory(); } finally { rename.repainting = false; }
958
+ if (state.historyRename !== rename) return;
959
+ const commandId = `shell.chat-history-item#${rename.chatId}`;
960
+ const row = [...ui.history.querySelectorAll('.ai-chat-history-row')].find((node) => node.dataset.commandId === commandId);
961
+ const titleNode = row?.querySelector('.ai-chat-history-title');
962
+ const renameButton = row?.querySelector('.ai-chat-history-rename');
963
+ // The conversation left the list, was archived, started a turn, or the project changed under
964
+ // the field: there is nothing left to rename in place, so drop the edit rather than save it.
965
+ const sameList = sameScope(rename.scope, rename.generation);
966
+ if (!titleNode || !renameButton || renameButton.hidden || !sameList) {
967
+ rename.abandon();
968
+ // The field vanished under the person's typing; say the name was not kept, and why. Not
969
+ // after a project switch — they left on purpose and are now looking at another list.
970
+ if (!sameList) return;
971
+ // The cause is only known when the row is still here; a missing row may be deleted, archived
972
+ // or filtered out, so that message stays neutral about why.
973
+ const archived = Boolean(row?.closest('.ai-chat-history-archived'));
974
+ announce(!row
975
+ ? 'Rename cancelled. This conversation is no longer in this list, so the new name was not saved. If you archived it, restore it from Archived to rename it.'
976
+ : archived
977
+ ? 'Rename cancelled. This conversation was archived, so the new name was not saved. Restore it to rename it.'
978
+ : 'Rename cancelled. The AI started working in this conversation, so the new name was not saved. You can rename it when the reply finishes.');
979
+ // Keep keyboard focus in the history instead of letting it fall to the page.
980
+ if (hadFocus) focusHistoryConversation(rename.chatId);
981
+ return;
982
+ }
983
+ row.dataset.renaming = 'true'; renameButton.hidden = true;
984
+ titleNode.replaceWith(input);
985
+ if (hadFocus) {
986
+ input.focus({ preventScroll: true });
987
+ input.setSelectionRange(selectionStart, selectionEnd, selectionDirection || 'none');
988
+ }
989
+ }
990
+
991
+ function renderHistory() {
652
992
  const focusedCommand = ui.history.contains(document.activeElement) ? document.activeElement?.dataset?.commandId : null;
653
993
  ui.history.replaceChildren();
654
994
  if (!state.scope) return;
@@ -713,7 +1053,10 @@
713
1053
  }
714
1054
 
715
1055
  const archivedChats = state.archivedChats.filter((chat) => Boolean(chat.archivedAt));
1056
+ const unreadableChats = state.unreadableChats || [];
1057
+ if (unreadableChats.length) appendUnreadableChats(unreadableChats, ui.history);
716
1058
  if (!state.chats.length && !archivedChats.length) {
1059
+ if (unreadableChats.length) { restoreHistoryFocus(focusedCommand); return; }
717
1060
  const empty = document.createElement('div'); empty.className = 'ai-chat-history-empty';
718
1061
  empty.textContent = 'No conversations here yet.';
719
1062
  ui.history.append(empty); return;
@@ -820,6 +1163,83 @@
820
1163
  }
821
1164
  }
822
1165
 
1166
+ // A conversation whose saved file is damaged (#1619). The server knows nothing trustworthy about it
1167
+ // beyond its id — no title, no provider — so the row says what happened and offers the one thing
1168
+ // that can be done here. It opens nothing, so it is not a button; only Discard acts.
1169
+ function appendUnreadableChats(entries, destination) {
1170
+ const group = document.createElement('section'); group.className = 'ai-chat-history-group ai-chat-history-unreadable';
1171
+ group.setAttribute('aria-label', 'Conversations that can’t be opened');
1172
+ const label = document.createElement('div'); label.className = 'ai-chat-history-label'; label.textContent = 'Can’t be opened';
1173
+ group.append(label);
1174
+ for (const entry of entries) {
1175
+ const row = document.createElement('div');
1176
+ row.className = 'ai-chat-history-row unreadable';
1177
+ row.dataset.chatId = entry.chatId;
1178
+ const title = document.createElement('span'); title.className = 'ai-chat-history-title'; title.textContent = 'Conversation can’t be opened';
1179
+ const meta = document.createElement('span'); meta.className = 'ai-chat-history-meta';
1180
+ const changed = entry.changedAt && Number.isFinite(Date.parse(entry.changedAt))
1181
+ ? ` · changed ${formatDay(entry.changedAt) === 'Today' ? eventTime({ createdAt: entry.changedAt }) : formatDay(entry.changedAt)}`
1182
+ : '';
1183
+ meta.textContent = `Saved file is damaged${changed}`;
1184
+ const actions = document.createElement('span'); actions.className = 'ai-chat-history-actions always-on';
1185
+ const discard = document.createElement('button');
1186
+ discard.type = 'button'; discard.className = 'ai-chat-history-action danger'; discard.append(historyActionIcon('delete'));
1187
+ discard.dataset.commandId = `shell.chat-history-discard#${entry.chatId}`;
1188
+ discard.dataset.commandInstanceLabel = `Damaged conversation${changed}`;
1189
+ discard.setAttribute('aria-label', 'Discard damaged conversation');
1190
+ discard.dataset.tip = 'Permanently discard this conversation';
1191
+ discard.addEventListener('click', (event) => {
1192
+ event.preventDefault(); event.stopPropagation(); discardUnreadableConversation(entry, discard);
1193
+ });
1194
+ actions.append(discard);
1195
+ row.append(title, meta, actions);
1196
+ group.append(row);
1197
+ }
1198
+ destination.append(group);
1199
+ }
1200
+
1201
+ async function discardUnreadableConversation(entry, trigger) {
1202
+ const snapshot = captureScope();
1203
+ if (!snapshot) return;
1204
+ const confirm = window.flolessBridge?.formModal;
1205
+ if (!confirm) { report(new Error('Could not open the confirmation dialog'), 'Could not discard conversation'); return; }
1206
+ const approved = await confirm({
1207
+ title: 'Discard this damaged conversation?',
1208
+ sub: 'FloLess can’t read this conversation’s saved file, so it can’t be opened or repaired here. Discarding permanently removes it from this computer. Your other conversations aren’t affected. This can’t be undone.',
1209
+ fields: [], okLabel: 'Discard permanently', danger: true, returnFocusTo: trigger,
1210
+ });
1211
+ if (!approved || !sameScope(snapshot.scope, snapshot.generation)) return;
1212
+ trigger.disabled = true;
1213
+ try {
1214
+ await request(`/api/chat/conversations/${encodeURIComponent(entry.chatId)}/discard-unreadable`, {
1215
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner }),
1216
+ });
1217
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1218
+ state.unreadableChats = (state.unreadableChats || []).filter((item) => item.chatId !== entry.chatId);
1219
+ paintHistory(); paintUnreadableNotice();
1220
+ ui.history.querySelector('[aria-pressed="true"]')?.focus({ preventScroll: true });
1221
+ announce('Discarded the damaged conversation.');
1222
+ } catch (error) {
1223
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1224
+ if (error?.code === 'chat-record-readable') {
1225
+ // Repaired on disk (or it was only mid-save): it is a normal conversation again, so keep it.
1226
+ // Say so on screen too — the status region is for screen readers only. After the re-read:
1227
+ // with a conversation open, the poll's composer refresh rewrites the hint line.
1228
+ const kept = 'This conversation can be opened again, so it was kept.';
1229
+ state.unreadableChats = (state.unreadableChats || []).filter((item) => item.chatId !== entry.chatId);
1230
+ paintHistory(); paintUnreadableNotice();
1231
+ await pollChats();
1232
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1233
+ announce(kept);
1234
+ ui.hint.textContent = kept;
1235
+ return;
1236
+ }
1237
+ report(error, 'Could not discard conversation', {
1238
+ 'chat-owner-archived': `This ${snapshot.scope.owner.kind} is archived, so its conversations can’t be changed. Restore the ${snapshot.scope.owner.kind} to discard this conversation.`,
1239
+ });
1240
+ } finally { trigger.disabled = false; }
1241
+ }
1242
+
823
1243
  function eventTime(event) {
824
1244
  return new Intl.DateTimeFormat(undefined, { hour: '2-digit', minute: '2-digit' }).format(new Date(event.createdAt));
825
1245
  }
@@ -883,12 +1303,31 @@
883
1303
  titleNode.replaceWith(input);
884
1304
  input.focus(); input.select();
885
1305
  let finished = false;
886
- const finish = async (save = true) => {
1306
+ const active = {
1307
+ chatId: chat.chatId, input, scope: snapshot.scope, generation: snapshot.generation, repainting: false,
1308
+ abandon() { finished = true; if (state.historyRename === active) state.historyRename = null; },
1309
+ };
1310
+ state.historyRename = active;
1311
+ // `returnFocus`: the rename ended from the field's own keys, so focus goes back to this
1312
+ // conversation's row instead of falling to the page. Clicking away keeps focus where it went.
1313
+ const finish = async (save = true, { returnFocus = false } = {}) => {
887
1314
  if (finished) return;
888
1315
  finished = true;
1316
+ if (state.historyRename === active) state.historyRename = null;
889
1317
  const title = input.value.trim();
890
- if (!save || !title || title === original) { if (sameScope(snapshot.scope, snapshot.generation)) paintHistory(); return; }
1318
+ if (!save || !title || title === original) {
1319
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1320
+ paintHistory();
1321
+ if (returnFocus) focusHistoryConversation(chat.chatId);
1322
+ return;
1323
+ }
1324
+ // The list this field was opened in has been replaced (another project or workflow, or a
1325
+ // reload of it): never send a rename from a field that no longer belongs to what is shown.
1326
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
891
1327
  input.disabled = true;
1328
+ // The save takes a moment. Only bring focus back if the person has not moved it elsewhere
1329
+ // meanwhile (it is still on the field, or fell to the page when the field was disabled).
1330
+ const focusWaited = () => returnFocus && [input, document.body, null].includes(document.activeElement);
892
1331
  try {
893
1332
  const updated = await request(`/api/chat/conversations/${encodeURIComponent(chat.chatId)}/title`, {
894
1333
  method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, title }),
@@ -900,17 +1339,36 @@
900
1339
  state.chat = updated;
901
1340
  ui.title.textContent = updated.title;
902
1341
  }
903
- paintHistory(); announce('Conversation name saved.');
1342
+ const refocus = focusWaited();
1343
+ paintHistory(); if (refocus) focusHistoryConversation(chat.chatId);
1344
+ announce('Conversation name saved.');
904
1345
  } catch (error) {
905
1346
  if (!sameScope(snapshot.scope, snapshot.generation)) return;
906
- paintHistory(); report(error, 'Could not rename conversation');
1347
+ const refocus = focusWaited();
1348
+ paintHistory(); if (refocus) focusHistoryConversation(chat.chatId);
1349
+ report(error, 'Could not rename conversation');
907
1350
  }
908
1351
  };
1352
+ // The field sits inside the row, whose click opens the conversation. A click in the field (to
1353
+ // move the caret) must stay in the field, or opening the conversation would blur and save it.
1354
+ input.addEventListener('click', (event) => event.stopPropagation());
909
1355
  input.addEventListener('keydown', (event) => {
910
- if (event.key === 'Enter') { event.preventDefault(); finish(true); }
911
- if (event.key === 'Escape') { event.preventDefault(); finish(false); }
1356
+ // While an input method is composing (Japanese, Chinese, Korean…), Enter accepts the
1357
+ // candidate and Escape dismisses it: both belong to the composition, not to the rename.
1358
+ // Older Safari sends that key after the composition ends, with isComposing false and
1359
+ // keyCode 229, so either one marks it.
1360
+ const composing = event.isComposing || event.keyCode === 229;
1361
+ if (event.key === 'Enter' && !composing) { event.preventDefault(); finish(true, { returnFocus: true }); }
1362
+ if (event.key === 'Escape') {
1363
+ // Escape in this field is the field's, never the history's: left to bubble, it would also
1364
+ // reach the history's own Escape and close the whole history (#1603). One press, one action.
1365
+ event.stopPropagation();
1366
+ if (composing) return;
1367
+ event.preventDefault(); finish(false, { returnFocus: true });
1368
+ }
912
1369
  });
913
- input.addEventListener('blur', () => finish(true));
1370
+ // A repaint removing the field is not the person leaving it; paintHistory() puts it back.
1371
+ input.addEventListener('blur', () => { if (!active.repainting) finish(true); });
914
1372
  }
915
1373
 
916
1374
  async function leaveConversationAfterRemoval(chatId, announcement, snapshot) {
@@ -920,9 +1378,12 @@
920
1378
  paintHistory(); paintUnread();
921
1379
  if (state.chat?.chatId !== chatId) { announce(announcement); return; }
922
1380
  closeSource(); clearLiveStream(true);
923
- state.chat = null; state.events = []; state.attachments = []; state.integrations = null;
1381
+ state.chat = null; state.events = []; state.attachments = []; state.followupUnknownId = null; state.integrations = null;
1382
+ updateOffscreenActivity();
924
1383
  if (state.chats.length) await selectConversation(state.chats[0].chatId, { focus: true, replaceProviderChoice: true });
925
- else providerChooser();
1384
+ // The chooser removes the removed conversation's setup card; its hint goes too, as on every other way
1385
+ // to the chooser, so nothing is left saying a message is back in a draft that was just removed.
1386
+ else { providerChooser(); clearReport(); }
926
1387
  if (sameScope(snapshot.scope, snapshot.generation)) announce(announcement);
927
1388
  }
928
1389
 
@@ -1132,7 +1593,10 @@
1132
1593
  if (event.providerItemId) item.dataset.providerItemId = event.providerItemId;
1133
1594
  if (event.turnId) item.dataset.turnId = event.turnId;
1134
1595
  const head = document.createElement('div'); head.className = 'ai-chat-message-head';
1135
- const who = document.createElement('span'); who.textContent = role === 'user' ? 'You' : providerLabels[state.chat?.provider] || 'AI';
1596
+ // A background answer records the runtime that produced it; name that one, not the conversation's.
1597
+ const who = document.createElement('span'); who.textContent = event.payload?.source === 'filter-save'
1598
+ ? 'FloLess' : role === 'user' ? 'You'
1599
+ : providerLabels[event.payload?.provider] || providerLabels[state.chat?.provider] || 'AI';
1136
1600
  const time = document.createElement('time'); time.dateTime = event.createdAt; time.textContent = eventTime(event);
1137
1601
  const visibleText = role === 'assistant' ? visibleAssistantText(text) : visibleUserText(text);
1138
1602
  head.append(who, time); item.append(head);
@@ -1153,9 +1617,81 @@
1153
1617
  item.append(gallery);
1154
1618
  }
1155
1619
  }
1620
+ if (role === 'user' && (event.payload?.followup || event.payload?.deliveryState)) {
1621
+ const delivery = followupDelivery(event);
1622
+ const deliveryReceipt = [...state.events].reverse().find((candidate) => candidate.type === 'followup-status'
1623
+ && candidate.clientSubmissionId === event.clientSubmissionId)?.payload;
1624
+ const labels = {
1625
+ pending: 'Waiting to send', sending: 'Sending to AI', accepted: 'Sent to AI',
1626
+ 'queued-next': 'Queued for the next response', 'not-sent': 'Not sent', unknown: 'Delivery unconfirmed',
1627
+ dismissed: 'Continued without resending',
1628
+ };
1629
+ // A later message stays durably pending so it can join the first queued message's
1630
+ // promoted turn. Show why it is waiting while that earlier message is being promoted.
1631
+ const queuedAhead = delivery === 'pending' && state.events.some((candidate) =>
1632
+ candidate.type === 'user-message' && candidate.turnId === event.turnId
1633
+ && candidate.sequence < event.sequence && candidate.payload?.followup
1634
+ && state.events.some((statusEvent) => statusEvent.type === 'followup-status'
1635
+ && statusEvent.clientSubmissionId === candidate.clientSubmissionId
1636
+ && statusEvent.payload?.deliveryState === 'queued-next'));
1637
+ const status = document.createElement('span'); status.className = 'ai-chat-message-delivery';
1638
+ status.textContent = labels[queuedAhead ? 'queued-next' : delivery] || 'Waiting for AI';
1639
+ item.append(status);
1640
+ if (delivery === 'not-sent' && deliveryReceipt?.reason) {
1641
+ const help = document.createElement('span'); help.className = 'ai-chat-message-delivery ai-chat-message-delivery-detail';
1642
+ help.textContent = deliveryReceipt.reason;
1643
+ item.append(help);
1644
+ }
1645
+ if (delivery === 'unknown' && event.clientSubmissionId) {
1646
+ const help = document.createElement('span'); help.className = 'ai-chat-message-delivery ai-chat-message-delivery-detail';
1647
+ help.textContent = 'AI may have received this. Check the conversation before continuing.';
1648
+ const resolve = button(event.optimistic ? 'Review draft and continue' : 'Continue without resending',
1649
+ `shell.chat-followup-resolve-${event.optimistic ? 'local' : 'durable'}#${event.clientSubmissionId}`, 'ai-chat-followup-resolve');
1650
+ resolve.dataset.commandInstanceLabel = visibleText.slice(0, 80) || 'Follow-up';
1651
+ resolve.setAttribute('aria-label', `${resolve.textContent}: ${visibleText.slice(0, 80) || 'follow-up with attachments'}`);
1652
+ resolve.dataset.tip = event.optimistic
1653
+ ? 'Review the draft; sending it again may duplicate a message AI received'
1654
+ : 'Continue despite uncertain delivery; this message will not be resent';
1655
+ resolve.disabled = Boolean(state.resolvingFollowupIds?.has(event.clientSubmissionId));
1656
+ resolve.setAttribute('aria-busy', String(resolve.disabled));
1657
+ if (resolve.disabled) resolve.dataset.blockedReason = 'FloLess is updating this message';
1658
+ resolve.addEventListener('click', () => { void resolveUnknownFollowup(event.clientSubmissionId); });
1659
+ item.append(help, resolve);
1660
+ }
1661
+ if (delivery === 'not-sent' && deliveryReceipt?.retryable !== false
1662
+ && event.clientSubmissionId && !state.chat?.archivedAt
1663
+ && state.chat?.state !== 'recovery'
1664
+ && !state.followupUnknownId && !hasUnknownFollowup()
1665
+ && (!state.chat?.activeTurn || state.chat.activeTurn.turnId === event.turnId)
1666
+ && !state.events.some(candidate => candidate.type === 'user-message'
1667
+ && candidate.payload?.retryOfSubmissionId === event.clientSubmissionId)) {
1668
+ const retry = button(state.retryingFollowupIds?.has(event.clientSubmissionId) ? 'Retrying…' : 'Retry sending',
1669
+ `shell.chat-followup-retry#${event.clientSubmissionId}`, 'ai-chat-followup-resolve');
1670
+ retry.dataset.commandInstanceLabel = visibleText.slice(0, 80) || 'Follow-up with attachments';
1671
+ retry.setAttribute('aria-label', `${retry.textContent}: ${visibleText.slice(0, 80) || 'follow-up with attachments'}`);
1672
+ retry.dataset.tip = 'Send this message and its attached files again; your draft stays as it is';
1673
+ retry.disabled = Boolean(state.retryingFollowupIds?.has(event.clientSubmissionId));
1674
+ retry.setAttribute('aria-busy', String(retry.disabled));
1675
+ if (retry.disabled) retry.dataset.blockedReason = 'FloLess is retrying this message';
1676
+ retry.addEventListener('click', () => { void retryNotSentFollowup(event.clientSubmissionId); });
1677
+ item.append(retry);
1678
+ }
1679
+ }
1156
1680
  return item;
1157
1681
  }
1158
1682
 
1683
+ function followupDelivery(event) {
1684
+ const receipt = [...state.events].reverse().find((candidate) => candidate.type === 'followup-status'
1685
+ && candidate.clientSubmissionId === event.clientSubmissionId);
1686
+ return receipt?.payload?.deliveryState || event.payload?.deliveryState || 'pending';
1687
+ }
1688
+
1689
+ function hasUnknownFollowup() {
1690
+ return state.events.some((event) => event.type === 'user-message'
1691
+ && (event.payload?.followup || event.payload?.deliveryState)
1692
+ && followupDelivery(event) === 'unknown');
1693
+ }
1694
+
1159
1695
  function renderRequestCard(event) {
1160
1696
  const payload = event.payload || {};
1161
1697
  const item = document.createElement('article');
@@ -1188,10 +1724,13 @@
1188
1724
  }
1189
1725
 
1190
1726
  function renderEvent(event) {
1727
+ if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
1191
1728
  if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
1729
+ if (event.type === 'assistant-message' && event.payload?.filterAi && !event.payload?.delta) return renderFilterAnswer(event);
1192
1730
  if (event.type === 'user-message') return renderMessage(event, 'user', payloadText(event));
1193
1731
  if (event.type === 'assistant-message') return renderMessage(event, 'assistant', payloadText(event), Boolean(event.payload?.delta));
1194
- if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state') return null;
1732
+ if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state' || event.type === 'followup-status') return null;
1733
+ if (event.type === 'tekla-read') return renderTeklaReadEvent(event);
1195
1734
  const item = document.createElement('div');
1196
1735
  item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}${event.type === 'knowledge-citation' ? ' knowledge' : ''}`;
1197
1736
  item.dataset.eventSequence = String(event.sequence);
@@ -1201,8 +1740,8 @@
1201
1740
  attachment: 'Attachment', tool: 'AI action', error: 'Error', interrupted: 'Stopped', usage: 'AI usage',
1202
1741
  compaction: 'Conversation summary updated', 'knowledge-citation': 'Knowledge cited', state: 'Status', request: 'Request',
1203
1742
  };
1204
- label.textContent = labels[event.type] || event.type;
1205
1743
  const payload = event.payload || {};
1744
+ label.textContent = event.type === 'error' && payload.outcome === 'not-sent' ? 'Not sent' : labels[event.type] || event.type;
1206
1745
  let detail = event.type === 'error' ? errorMessage(payloadText(event)) : payloadText(event);
1207
1746
  if (!detail && event.type === 'tool') {
1208
1747
  const toolLabels = { provider: 'AI provider', integration: 'Connected service', attachment: 'Attachment', knowledge: 'Knowledge', filesystem: 'Project files' };
@@ -1218,6 +1757,182 @@
1218
1757
  return item;
1219
1758
  }
1220
1759
 
1760
+ // A server-authored receipt of one approved live Tekla read. Deterministic: it shows only what
1761
+ // the server recorded, and an unverified read never shows a model name or parts.
1762
+ function renderTeklaReadEvent(event) {
1763
+ const payload = event.payload || {};
1764
+ if (payload.status === 'verified-for-selection-read') return renderTeklaSelectionEvent(event);
1765
+ const verified = payload.status === 'verified-for-model-name-read';
1766
+ const card = document.createElement('section');
1767
+ card.className = `ai-chat-tekla-read ${verified ? 'verified' : 'unverified'}`;
1768
+ card.setAttribute('role', 'status');
1769
+ card.dataset.eventSequence = String(event.sequence);
1770
+ card.dataset.eventId = event.eventId;
1771
+ const heading = document.createElement('strong');
1772
+ heading.textContent = verified ? 'Verified for model-name read' : 'Could not verify this read';
1773
+ card.setAttribute('aria-label', heading.textContent);
1774
+ card.append(heading);
1775
+ const facts = document.createElement('dl');
1776
+ const fact = (name, value) => {
1777
+ if (value === undefined || value === null || value === '') return;
1778
+ const dt = document.createElement('dt'); dt.textContent = name;
1779
+ const dd = document.createElement('dd');
1780
+ if (value instanceof Node) dd.append(value); else dd.textContent = String(value);
1781
+ facts.append(dt, dd);
1782
+ };
1783
+ if (verified) {
1784
+ fact('Operation', payload.operation);
1785
+ // A replayed receipt is history: the name is what was open at the check, not what is open now.
1786
+ fact('Model when checked', payload.modelName);
1787
+ fact('Tekla host', `${payload.hostVersion || ''}${Number.isFinite(payload.hostPid) ? ` · PID ${payload.hostPid}` : ''}`);
1788
+ fact('Library', payload.library);
1789
+ fact('Checked', checkedTime(payload.checkedAt));
1790
+ card.append(facts);
1791
+ const note = document.createElement('p'); note.textContent = 'The generated agent\'s commands remain unverified.';
1792
+ card.append(note);
1793
+ } else {
1794
+ const message = document.createElement('p');
1795
+ message.textContent = typeof payload.message === 'string' && payload.message.trim()
1796
+ ? payload.message : 'FloLess could not complete this read.';
1797
+ card.append(message);
1798
+ fact('Library', payload.library);
1799
+ fact('Checked', checkedTime(payload.checkedAt));
1800
+ if (facts.childElementCount) card.append(facts);
1801
+ }
1802
+ return card;
1803
+ }
1804
+
1805
+ function teklaKg(value) {
1806
+ return new Intl.NumberFormat(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(value);
1807
+ }
1808
+ function teklaCount(value) { return new Intl.NumberFormat().format(value); }
1809
+ function partsWord(count) { return `${teklaCount(count)} ${count === 1 ? 'part' : 'parts'}`; }
1810
+
1811
+ // The count and total line, worded for exactly what the read covered. It sits above the table so a
1812
+ // list that was cut short says so before anyone scrolls.
1813
+ function teklaSelectionSummary(payload, listed) {
1814
+ const count = Number(payload.partCount) || 0;
1815
+ const total = `${teklaKg(Number(payload.totalWeightKg) || 0)} kg`;
1816
+ const missing = Number(payload.weightMissing) || 0;
1817
+ const lines = [];
1818
+ if (payload.complete === false) {
1819
+ lines.push(`${partsWord(count)} read, ${total} — the selection is larger than FloLess reads at once, so it stopped part-way and these cover only the parts it read. Select fewer objects for a full total.`);
1820
+ } else if (payload.truncated) {
1821
+ // "Covers all" only when every part read has a weight; otherwise the next line says who is left out.
1822
+ lines.push(missing > 0
1823
+ ? `Showing ${teklaCount(listed)} of ${partsWord(count)} — the total ${total} covers the ${partsWord(count - missing)} that have a weight.`
1824
+ : `Showing ${teklaCount(listed)} of ${partsWord(count)} — the total covers all ${teklaCount(count)}: ${total}.`);
1825
+ } else {
1826
+ lines.push(`${partsWord(count)} · total ${total}`);
1827
+ }
1828
+ if (missing > 0) lines.push(`Tekla gave no weight for ${partsWord(missing)}; the total leaves ${missing === 1 ? 'it' : 'them'} out.`);
1829
+ return lines;
1830
+ }
1831
+
1832
+ // The selected parts as a compact schedule. A replayed card is history: "when checked", never now.
1833
+ function renderTeklaSelectionEvent(event) {
1834
+ const payload = event.payload || {};
1835
+ const parts = Array.isArray(payload.parts) ? payload.parts : [];
1836
+ const count = Number(payload.partCount) || 0;
1837
+ const others = Number(payload.otherObjectCount) || 0;
1838
+ const card = document.createElement('section');
1839
+ card.className = 'ai-chat-tekla-read verified selection';
1840
+ card.dataset.eventSequence = String(event.sequence);
1841
+ card.dataset.eventId = event.eventId;
1842
+ const heading = document.createElement('strong');
1843
+ heading.textContent = 'Selected in Tekla when checked';
1844
+ card.setAttribute('aria-label', heading.textContent);
1845
+ card.append(heading);
1846
+ const facts = document.createElement('dl');
1847
+ const fact = (name, value) => {
1848
+ if (value === undefined || value === null || value === '') return;
1849
+ const dt = document.createElement('dt'); dt.textContent = name;
1850
+ const dd = document.createElement('dd');
1851
+ if (value instanceof Node) dd.append(value); else dd.textContent = String(value);
1852
+ facts.append(dt, dd);
1853
+ };
1854
+ fact('Model when checked', payload.modelName);
1855
+ fact('Tekla host', `${payload.hostVersion || ''}${Number.isFinite(payload.hostPid) ? ` · PID ${payload.hostPid}` : ''}`);
1856
+ fact('Checked', checkedTime(payload.checkedAt));
1857
+ fact('Library', payload.library);
1858
+ card.append(facts);
1859
+ const note = (text, className, parent = card) => {
1860
+ const line = document.createElement('p');
1861
+ if (className) line.className = className;
1862
+ line.textContent = text;
1863
+ parent.append(line);
1864
+ };
1865
+ // Only the short summary is announced; the table is read on demand through its caption.
1866
+ const summary = document.createElement('div');
1867
+ summary.className = 'ai-chat-tekla-summary';
1868
+ summary.setAttribute('role', 'status');
1869
+ card.append(summary);
1870
+ if (count === 0 && payload.complete === false) {
1871
+ // Stopped before reaching any part: that is not "nothing selected".
1872
+ note(`The selection is larger than FloLess reads at once, so it stopped before reaching any part${others > 0 ? ` (${teklaCount(others)} other ${others === 1 ? 'object' : 'objects'} read)` : ''}. Select fewer objects, then ask again.`, '', summary);
1873
+ return card;
1874
+ }
1875
+ if (count === 0) {
1876
+ note(others > 0
1877
+ ? `No parts were selected in Tekla when checked. ${teklaCount(others)} other selected ${others === 1 ? 'object is' : 'objects are'} not a part (bolts, welds and similar), so nothing is listed.`
1878
+ : 'Nothing was selected in Tekla when checked.', '', summary);
1879
+ return card;
1880
+ }
1881
+ for (const line of teklaSelectionSummary(payload, parts.length)) note(line, '', summary);
1882
+ const scroller = document.createElement('div');
1883
+ scroller.className = 'ai-chat-tekla-parts';
1884
+ // No explicit tab stop: Chromium already makes a scrolling region keyboard-focusable, and the
1885
+ // table carries no command of its own.
1886
+ scroller.setAttribute('role', 'region');
1887
+ scroller.setAttribute('aria-label', `Selected parts, ${parts.length} listed`);
1888
+ const table = document.createElement('table');
1889
+ const caption = document.createElement('caption');
1890
+ caption.className = 'sr-only';
1891
+ caption.textContent = `Parts selected in Tekla when checked (${parts.length} listed of ${count})`;
1892
+ const head = document.createElement('thead');
1893
+ const headRow = document.createElement('tr');
1894
+ for (const [label, numeric] of [['Mark', false], ['Name', false], ['Profile', false], ['Material', false], ['kg', true]]) {
1895
+ const th = document.createElement('th'); th.scope = 'col'; th.textContent = label;
1896
+ if (numeric) { th.className = 'num'; th.setAttribute('aria-label', 'Weight in kilograms'); }
1897
+ headRow.append(th);
1898
+ }
1899
+ head.append(headRow);
1900
+ const body = document.createElement('tbody');
1901
+ for (const part of parts) {
1902
+ const row = document.createElement('tr');
1903
+ for (const key of ['mark', 'name', 'profile', 'material']) {
1904
+ const td = document.createElement('td');
1905
+ const value = typeof part?.[key] === 'string' && part[key] ? part[key] : '';
1906
+ td.textContent = value || '—';
1907
+ td.className = value ? key : `${key} empty`;
1908
+ // Narrow columns cut long text short; the shared tooltip shows the recorded value.
1909
+ if (value) td.dataset.tip = value;
1910
+ row.append(td);
1911
+ }
1912
+ const weight = document.createElement('td'); weight.className = 'num';
1913
+ if (Number.isFinite(part?.weightKg)) weight.textContent = teklaKg(part.weightKg);
1914
+ else { weight.textContent = '—'; weight.classList.add('empty'); weight.setAttribute('aria-label', 'no weight'); }
1915
+ row.append(weight);
1916
+ body.append(row);
1917
+ }
1918
+ table.append(caption, head, body);
1919
+ scroller.append(table);
1920
+ card.append(scroller);
1921
+ note('Selected assemblies are listed by their parts when checked.');
1922
+ if (others > 0) note(`${teklaCount(others)} other selected ${others === 1 ? 'object is' : 'objects are'} not a part (bolts, welds and similar) and ${others === 1 ? 'is' : 'are'} not listed.`);
1923
+ return card;
1924
+ }
1925
+
1926
+ function checkedTime(value) {
1927
+ if (typeof value !== 'string' || !value) return '';
1928
+ const date = new Date(value);
1929
+ if (Number.isNaN(date.getTime())) return value;
1930
+ const time = document.createElement('time');
1931
+ time.dateTime = value;
1932
+ time.textContent = date.toLocaleString([], { dateStyle: 'medium', timeStyle: 'medium' });
1933
+ return time;
1934
+ }
1935
+
1221
1936
  function animatedDots() {
1222
1937
  const dots = document.createElement('span'); dots.className = 'ai-chat-live-dots'; dots.setAttribute('aria-hidden', 'true');
1223
1938
  dots.append(document.createElement('i'), document.createElement('i'), document.createElement('i'));
@@ -1235,11 +1950,15 @@
1235
1950
 
1236
1951
  function announceLiveResponseOnce() {
1237
1952
  const turnId = turnIsVisiblyActive() ? state.chat.activeTurn.turnId : null;
1953
+ const wasResponding = state.liveStatusTurnId !== null;
1238
1954
  if (!turnId) {
1239
1955
  state.liveStatusTurnId = null;
1240
1956
  // The screen-reader announcement is a transient status. Once the durable turn ends,
1241
1957
  // leaving its text behind makes the finished chat sound as though it is still working.
1242
- ui.status.textContent = '';
1958
+ // Cleared once, when that turn ends — not on every idle repaint: the 5 s poll repaints the
1959
+ // feed, and wiping the live region there erased other announcements, such as the pending
1960
+ // sign-in's, before a screen reader had read them (#1514).
1961
+ if (wasResponding) ui.status.textContent = '';
1243
1962
  return;
1244
1963
  }
1245
1964
  if (state.liveStatusTurnId === turnId) return;
@@ -1279,8 +1998,31 @@
1279
1998
  target.scrollIntoView({ block: 'center' });
1280
1999
  }
1281
2000
 
2001
+ function updateOffscreenActivity() {
2002
+ const liveDots = ui.feed.querySelector('.ai-chat-live-status .ai-chat-live-dots');
2003
+ // Showing the badge claims a row below the feed. Require enough room for that row before
2004
+ // showing it, otherwise ResizeObserver could alternate between show and hide in a short pane.
2005
+ const minimumFeedHeight = ui.offscreenActivity.hidden ? 88 : 48;
2006
+ ui.offscreenActivity.hidden = !turnIsVisiblyActive() || state.historyOpen || !liveDots
2007
+ || ui.feed.clientHeight < minimumFeedHeight
2008
+ || liveDots.getBoundingClientRect().bottom <= ui.feed.getBoundingClientRect().bottom;
2009
+ }
2010
+
2011
+ // paintEvents rebuilds every control in the feed, so a control that held keyboard focus is put
2012
+ // back on its replacement. The empty state's sign-in is one of them: the repaint that follows its
2013
+ // own click would otherwise drop focus to the page just as it turns to "Sign-in window open".
2014
+ // That button is `aria-disabled`, not `disabled`, so it passes the filter (#1514).
2015
+ function restoreFeedFocus(focusedCommand) {
2016
+ if (!focusedCommand?.startsWith('shell.chat-followup-') && !focusedCommand?.startsWith('shell.chat-filter-')
2017
+ && focusedCommand !== 'shell.chat-sign-in') return;
2018
+ [...ui.feed.querySelectorAll('[data-command-id]')]
2019
+ .find(control => control.dataset.commandId === focusedCommand && !control.disabled)?.focus({ preventScroll: true });
2020
+ }
2021
+
1282
2022
  function paintEvents(options = {}) {
1283
2023
  announceLiveResponseOnce();
2024
+ const focusedCommand = ui.feed.contains(document.activeElement)
2025
+ ? document.activeElement?.dataset?.commandId : null;
1284
2026
  const nearBottom = ui.feed.scrollHeight - ui.feed.scrollTop - ui.feed.clientHeight < 56;
1285
2027
  ui.feed.replaceChildren();
1286
2028
  if (!state.events.length) {
@@ -1320,8 +2062,13 @@
1320
2062
  // never looks like a failed response. Recovery deliberately has no live indicator.
1321
2063
  if (turnIsVisiblyActive()) ui.feed.append(renderLiveStatus());
1322
2064
  }
2065
+ restoreFeedFocus(focusedCommand);
1323
2066
  restoreAnswerJump();
1324
- if (!state.answerJump && (nearBottom || options.forceBottom)) requestAnimationFrame(() => { ui.feed.scrollTop = ui.feed.scrollHeight; });
2067
+ updateOffscreenActivity();
2068
+ if (!state.answerJump && (nearBottom || options.forceBottom)) requestAnimationFrame(() => {
2069
+ ui.feed.scrollTop = ui.feed.scrollHeight;
2070
+ updateOffscreenActivity();
2071
+ });
1325
2072
  }
1326
2073
 
1327
2074
  // The feed's empty state. Four cases, in the order they must win: a sign-in window FloLess
@@ -1333,18 +2080,24 @@
1333
2080
  function emptyFeedNotice() {
1334
2081
  const empty = document.createElement('div'); empty.className = 'ai-chat-empty';
1335
2082
  const strong = document.createElement('strong');
1336
- const copy = document.createElement('div');
2083
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
1337
2084
  const provider = state.chat?.provider;
1338
2085
  const label = providerLabels[provider] || 'AI';
1339
2086
  const pendingSignIn = Boolean(provider && state.signInPending.has(provider));
1340
2087
  if (pendingSignIn) {
2088
+ // The title names the STATE and the button names the OBJECT (the open window), so the card
2089
+ // never says the same phrase twice (#1516).
1341
2090
  strong.textContent = 'Waiting for sign-in…';
1342
2091
  // The claude.ai page in the browser keeps its OWN session: it may still show the previous
1343
2092
  // account with an "Switch account" link of its own, and no CLI verb can clear that. Said
1344
2093
  // at the one moment it matters, for the one provider it applies to.
1345
2094
  copy.textContent = `Finish signing in using the window FloLess opened.${provider === 'claude'
1346
2095
  ? ' If the Claude page in your browser still shows the previous account, use its own Switch account link.' : ''}`;
1347
- empty.append(strong, copy, emptySignInButton(label, true));
2096
+ // The button's accessible description. A short panel hides this prose (chat.css), but a node
2097
+ // referenced by aria-describedby still describes even when it is not painted, so the reason
2098
+ // the button is inert reaches a screen reader at every height (#1514).
2099
+ copy.id = 'chat-empty-signin-help';
2100
+ empty.append(strong, copy, emptySignInButton(label, true, copy.id));
1348
2101
  } else if (providerReady()) {
1349
2102
  strong.textContent = 'Ready when you are';
1350
2103
  copy.textContent = `This ${label} conversation is stored with ${state.scope?.label || 'this work'}.`;
@@ -1369,16 +2122,28 @@
1369
2122
  // pending set. Only ever a sign-in — the reason that shows it guarantees that — so it never needs
1370
2123
  // the strip's "Switch account…" label. Its own command id because it is its own carrier, in its
1371
2124
  // own place.
1372
- function emptySignInButton(label, pending) {
2125
+ //
2126
+ // While the window is open the button is inert but NOT `disabled` (#1514): a disabled button
2127
+ // cannot take focus, and in a short panel it is the only thing left in the card, so keyboard and
2128
+ // screen-reader users found nothing at all. It is `aria-disabled` instead — reachable, named for
2129
+ // the window it is waiting on, described by the card's prose, and refusing its own click.
2130
+ function emptySignInButton(label, pending, describedBy) {
1373
2131
  const signIn = document.createElement('button');
1374
2132
  signIn.type = 'button';
1375
2133
  signIn.className = 'ai-chat-provider-switch ai-chat-empty-signin';
1376
2134
  signIn.dataset.commandId = 'shell.chat-sign-in';
1377
- signIn.setAttribute('aria-label', `Sign in to ${label}`);
1378
- signIn.textContent = pending ? 'Waiting for sign-in…' : 'Sign in…';
1379
- signIn.disabled = pending;
1380
- if (pending) signIn.dataset.blockedReason = 'Waiting for the sign-in window.';
1381
- signIn.addEventListener('click', () => { void switchAccount(); });
2135
+ // The accessible name contains the visible label word for word (WCAG 2.5.3, label in name).
2136
+ signIn.setAttribute('aria-label', pending ? `${label} sign-in window open` : `Sign in to ${label}`);
2137
+ signIn.textContent = pending ? 'Sign-in window open' : 'Sign in…';
2138
+ if (pending) {
2139
+ signIn.setAttribute('aria-disabled', 'true');
2140
+ signIn.dataset.blockedReason = 'Finish signing in using the window FloLess opened.';
2141
+ if (describedBy) signIn.setAttribute('aria-describedby', describedBy);
2142
+ }
2143
+ signIn.addEventListener('click', (event) => {
2144
+ if (signIn.getAttribute('aria-disabled') === 'true') { event.preventDefault(); return; }
2145
+ void switchAccount();
2146
+ });
1382
2147
  return signIn;
1383
2148
  }
1384
2149
 
@@ -1400,15 +2165,34 @@
1400
2165
  const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
1401
2166
  const deny = button('Deny', 'shell.chat-approval-deny');
1402
2167
  const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
1403
- const allowRequest = button('Approve for this request', 'shell.chat-approval-request', 'allow');
1404
- allowRequest.dataset.tip = 'Approve access actions until this response finishes. Your permission setting stays unchanged.';
1405
- const scope = document.createElement('p');
1406
- scope.textContent = 'Request approval lasts until this response finishes. Review checkpoints still need your decision.';
2168
+ // A Tekla model read needs its own decision every time, so a request-wide grant is not offered.
2169
+ const explicitOnly = approvalIsExplicitOnly(approval);
2170
+ const allowRequest = explicitOnly ? null : button('Approve for this request', 'shell.chat-approval-request', 'allow');
2171
+ const scope = document.createElement('span');
2172
+ scope.className = 'sr-only';
2173
+ scope.id = `chat-approval-request-help-${approval.approvalId}`;
1407
2174
  deny.addEventListener('click', () => decideApproval('deny'));
1408
2175
  allow.addEventListener('click', () => decideApproval('allow'));
1409
- allowRequest.addEventListener('click', () => decideApproval('allow-request'));
1410
- actions.append(deny, allow, allowRequest); card.append(heading, copy, scope, actions);
1411
- shell.insertBefore(card, ui.recovery);
2176
+ if (allowRequest) {
2177
+ scope.textContent = 'Approve access actions until this response finishes. Your permission setting stays unchanged. Review checkpoints and Tekla model reads still ask every time.';
2178
+ allowRequest.dataset.tip = scope.textContent;
2179
+ allowRequest.setAttribute('aria-describedby', scope.id);
2180
+ allowRequest.addEventListener('click', () => decideApproval('allow-request'));
2181
+ actions.append(deny, allow, allowRequest); card.append(heading, copy, actions, scope);
2182
+ } else {
2183
+ card.dataset.explicitOnly = 'true';
2184
+ actions.append(deny, allow); card.append(heading, copy, actions);
2185
+ }
2186
+ ui.approvalTray.append(card);
2187
+ // When a request-wide grant notice is also present, keep the decision nearest the composer.
2188
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
2189
+ }
2190
+
2191
+ function approvalIsExplicitOnly(approval) {
2192
+ if (!approval) return false;
2193
+ if (approval.explicitOnly === true) return true;
2194
+ return state.events.some((event) => event.type === 'approval-requested'
2195
+ && event.payload?.approvalId === approval.approvalId && event.payload?.explicitOnly === true);
1412
2196
  }
1413
2197
 
1414
2198
  function paintApprovalScope() {
@@ -1429,19 +2213,19 @@
1429
2213
  card.className = 'ai-chat-approval ai-chat-approval-scope';
1430
2214
  card.dataset.turnId = turn.turnId;
1431
2215
  const heading = document.createElement('strong');
1432
- heading.textContent = 'Access auto-approval on for this request';
1433
- const copy = document.createElement('p');
1434
- copy.textContent = 'Your permission setting is unchanged. Review checkpoints still need your decision.';
1435
- const note = document.createElement('p');
1436
- note.textContent = 'Actions already approved may finish.';
1437
- const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
2216
+ heading.textContent = 'Auto-approval on · this request';
2217
+ const explanation = document.createElement('span');
2218
+ explanation.className = 'sr-only';
2219
+ explanation.id = `chat-approval-scope-help-${turn.turnId}`;
2220
+ explanation.textContent = 'Your permission setting is unchanged. Review checkpoints and Tekla model reads still ask every time. Revoke asks before future access actions in this request; actions already approved may finish.';
1438
2221
  const revoke = button('Revoke', 'shell.chat-approval-revoke');
1439
- revoke.dataset.tip = 'Ask before future access actions in this request.';
2222
+ revoke.dataset.tip = explanation.textContent;
2223
+ revoke.setAttribute('aria-describedby', explanation.id);
1440
2224
  revoke.disabled = busy;
1441
2225
  revoke.setAttribute('aria-busy', String(busy));
1442
2226
  revoke.addEventListener('click', revokeApprovalScope);
1443
- actions.append(revoke); card.append(heading, copy, note, actions);
1444
- shell.insertBefore(card, ui.recovery);
2227
+ card.append(heading, revoke, explanation);
2228
+ ui.approvalTray.prepend(card);
1445
2229
  }
1446
2230
 
1447
2231
  // FloLess installs its own tested copy of Claude Code / Codex. While that copy is being set up (or
@@ -1493,6 +2277,12 @@
1493
2277
  };
1494
2278
  }
1495
2279
 
2280
+ // What the setup card shows for one conversation: the card is rebuilt, and a Drawing Filter "not sent"
2281
+ // sentence dropped from the hint, only when this changes.
2282
+ function runtimeCardKey(chatId, status) {
2283
+ return `${chatId}:${status.state}:${status.owner || ''}:${status.code || ''}:${status.retryable ? 1 : 0}`;
2284
+ }
2285
+
1496
2286
  function paintRuntime() {
1497
2287
  const existing = shell.querySelector('.ai-chat-runtime');
1498
2288
  const status = state.chat ? state.capability?.runtime : null;
@@ -1501,7 +2291,7 @@
1501
2291
  const settingUp = status.state === 'preparing' || status.state === 'not-installed';
1502
2292
  // Polls repeat the same state every two seconds; rebuilding the card each time would swap its button
1503
2293
  // out from under the pointer (a lost click) and drop keyboard focus. Rebuild only when it changes.
1504
- const key = `${state.chat.chatId}:${status.state}:${status.owner || ''}:${status.code || ''}:${status.retryable ? 1 : 0}`;
2294
+ const key = runtimeCardKey(state.chat.chatId, status);
1505
2295
  if (existing?.dataset.runtimeKey === key && existing.isConnected) { if (settingUp) startRuntimePoll(); return; }
1506
2296
  existing?.remove();
1507
2297
  const card = document.createElement('section');
@@ -1592,6 +2382,9 @@
1592
2382
 
1593
2383
  function paintAttachments() {
1594
2384
  ui.attachments.replaceChildren();
2385
+ const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length;
2386
+ ui.attach.dataset.tip = `Attach image or PDF · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images in this message`;
2387
+ ui.attach.setAttribute('aria-label', `Attach image or PDF · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images`);
1595
2388
  for (const attachment of state.attachments) {
1596
2389
  const chip = document.createElement('span'); chip.className = 'ai-chat-attachment';
1597
2390
  if (attachment.mediaType.startsWith('image/')) {
@@ -1624,13 +2417,20 @@
1624
2417
  if (!state.capability) return null;
1625
2418
  return state.capability.models.find((model) => model.id === state.chat?.settings.model)
1626
2419
  || preferredModel(state.chat?.provider, state.capability.models)
2420
+ || state.capability.models.find((model) => model.isDefault)
1627
2421
  || state.capability.models[0] || null;
1628
2422
  }
1629
2423
 
2424
+ // In order of preference; keep in step with PREFERRED_MODELS in server/chat-routes.ts. Without
2425
+ // GPT-6-Sol nothing is preferred, so the provider's own default row is shown and used.
1630
2426
  function preferredModel(provider, models) {
1631
2427
  if (!provider || !Array.isArray(models)) return null;
1632
- const pattern = provider === 'codex' ? /gpt[- .]?5\.6[- .]?terra/i : /opus/i;
1633
- return models.find((model) => pattern.test(`${model.id} ${model.label}`)) || null;
2428
+ const patterns = provider === 'codex' ? [/gpt[- .]?6[- .]?sol/i] : [/opus[- .]?5\.5/i, /opus/i];
2429
+ for (const pattern of patterns) {
2430
+ const found = models.find((model) => pattern.test(`${model.id} ${model.label}`));
2431
+ if (found) return found;
2432
+ }
2433
+ return null;
1634
2434
  }
1635
2435
 
1636
2436
  function preferredSettings(provider, capability) {
@@ -1695,11 +2495,16 @@
1695
2495
  const snapshot = captureChat();
1696
2496
  const before = answerKey(state.capability?.account);
1697
2497
  state.signInPending.add(chat.provider);
1698
- // Both carriers of this action flip to "Waiting for sign-in…" at the click, not at the next
1699
- // 5 s poll: the empty state's button is the one a new user just pressed.
2498
+ // Both carriers of this action flip to waiting at the click, not at the next 5 s poll — the
2499
+ // settings strip to "Waiting for sign-in…", the empty state to its "Waiting for sign-in…" title
2500
+ // over a "Sign-in window open" button: that button is the one a new user just pressed.
1700
2501
  paintSettings(); paintEvents();
1701
2502
  try {
1702
2503
  await request(`/api/terminal-runtimes/${encodeURIComponent(chat.provider)}/sign-in`, { method: 'POST' });
2504
+ // Announced once, through the panel's live region, so it reaches a screen reader however
2505
+ // much of the empty state a short panel still paints (#1514). Only now: before this await
2506
+ // resolves there is no window to point at.
2507
+ if (sameChat(snapshot)) announce(`Waiting for sign-in. Finish signing in to ${providerLabels[chat.provider] || 'AI'} using the window FloLess opened.`);
1703
2508
  await waitForSignIn(chat.provider, before);
1704
2509
  if (sameChat(snapshot)) await loadCapability();
1705
2510
  } catch (error) {
@@ -1834,6 +2639,8 @@
1834
2639
  }
1835
2640
 
1836
2641
  function paintConversation() {
2642
+ paintComposerDisclosure();
2643
+ paintTeklaChip();
1837
2644
  const chat = state.chat;
1838
2645
  if (!chat) { providerChooser(); paintHistory(); return; }
1839
2646
  ui.historyToggle.disabled = false;
@@ -1842,13 +2649,26 @@
1842
2649
  ui.scope.textContent = `${state.scope.label} · ${providerLabels[chat.provider]}`;
1843
2650
  ui.rename.hidden = Boolean(chat.activeTurn) || Boolean(chat.archivedAt);
1844
2651
  ui.input.disabled = Boolean(chat.archivedAt) || chat.state === 'recovery' || requestExecutionBlocked();
1845
- if (ui.input.value !== chat.draft && document.activeElement !== ui.input) ui.input.value = chat.draft || '';
2652
+ const draft = draftForChat(chat);
2653
+ if (ui.input.value !== draft && document.activeElement !== ui.input) ui.input.value = draft;
1846
2654
  const active = turnIsVisiblyActive(chat);
1847
2655
  ui.stop.hidden = !active || Boolean(chat.activeTurn?.local);
1848
- ui.send.hidden = active;
2656
+ ui.send.hidden = false;
1849
2657
  paintSettings(); paintRecovery(); paintApproval(); paintRuntime(); paintAttachments(); paintEvents(); paintHistory(); updateSendState();
1850
2658
  }
1851
2659
 
2660
+ function draftForChat(chat) {
2661
+ if (state.backgroundDrafts.has(chat.chatId)) {
2662
+ const recovered = state.backgroundDrafts.get(chat.chatId);
2663
+ if (chat.draft === recovered) state.backgroundDrafts.delete(chat.chatId);
2664
+ return recovered;
2665
+ }
2666
+ const local = state.localDraft;
2667
+ // A refresh can arrive after typing but before the debounced draft write commits.
2668
+ // Keep the local edit through older in-flight refreshes when focus leaves the composer.
2669
+ return local?.chatId === chat.chatId ? local.text : chat.draft || '';
2670
+ }
2671
+
1852
2672
  function closeSource() {
1853
2673
  if (state.eventReconnectTimer) { clearTimeout(state.eventReconnectTimer); state.eventReconnectTimer = null; }
1854
2674
  if (state.source) { state.source.close(); state.source = null; }
@@ -1901,13 +2721,24 @@
1901
2721
  state.eventReconnectChatId = chatId;
1902
2722
  state.eventReconnectAttempt = 0;
1903
2723
  }
1904
- const after = state.events.reduce((max, event) => Math.max(max, event.sequence || 0), 0);
2724
+ const after = Math.floor(state.events.reduce((max, event) => Math.max(max, event.sequence || 0), 0));
1905
2725
  const source = new EventSource(`/api/chat/conversations/${encodeURIComponent(chatId)}/events?${ownerQuery(scope.owner)}&after=${after}`);
1906
2726
  state.source = source;
1907
2727
  source.addEventListener('chat-event', (message) => {
1908
2728
  if (state.chat?.chatId !== chatId) return;
1909
2729
  const event = JSON.parse(message.data);
1910
- if (event.clientSubmissionId) {
2730
+ if (state.followupUnknownId === event.clientSubmissionId
2731
+ && event.type === 'user-message'
2732
+ && event.payload?.deliveryState !== 'unknown') {
2733
+ state.followupUnknownId = null;
2734
+ state.unknownFollowups.delete(chatId);
2735
+ clearConfirmedUnknownDraft(event, chatId);
2736
+ updateSendState();
2737
+ }
2738
+ // A status can precede the durable user message. Keep the uncertain row and
2739
+ // draft blocked until that message confirms which submission the server saved.
2740
+ if (event.clientSubmissionId && !(event.type === 'followup-status'
2741
+ && state.followupUnknownId === event.clientSubmissionId)) {
1911
2742
  state.events = state.events.filter((item) => !(item.optimistic && item.clientSubmissionId === event.clientSubmissionId));
1912
2743
  }
1913
2744
  if (state.events.some((item) => item.eventId === event.eventId)) return;
@@ -1924,9 +2755,21 @@
1924
2755
  state.chat = { ...state.chat, state: 'completed', activeTurn: null };
1925
2756
  paintConversation();
1926
2757
  }
2758
+ if (event.type === 'followup-status') {
2759
+ const notices = {
2760
+ accepted: 'Follow-up sent to AI.',
2761
+ 'queued-next': 'Follow-up queued for the next AI response.',
2762
+ 'not-sent': event.payload?.reason || (event.payload?.retryable === false
2763
+ ? 'This message was not sent. Review the conversation before writing a new message.'
2764
+ : 'This message was not sent. Use Retry sending if you still want to send it.'),
2765
+ 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.',
2766
+ };
2767
+ if (notices[event.payload?.deliveryState]) announce(notices[event.payload.deliveryState]);
2768
+ }
1927
2769
  paintEvents(); paintUnread();
1928
2770
  if (!document.hidden && !ui.feed.closest('[hidden]')) markRead();
1929
- if (['approval-requested', 'approval-decided', 'error', 'interrupted', 'state'].includes(event.type)) refreshConversation(chatId, false);
2771
+ if (['approval-requested', 'approval-decided', 'error', 'interrupted', 'state', 'followup-status'].includes(event.type)
2772
+ || (event.type === 'user-message' && event.payload?.followup)) refreshConversation(chatId, false);
1930
2773
  });
1931
2774
  source.addEventListener('ready', () => {
1932
2775
  if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
@@ -1940,6 +2783,21 @@
1940
2783
  };
1941
2784
  }
1942
2785
 
2786
+ function clearConfirmedUnknownDraft(event, chatId) {
2787
+ const confirmed = String(event.payload?.text || '').trim();
2788
+ if (state.backgroundDrafts.get(chatId)?.trim() === confirmed) state.backgroundDrafts.delete(chatId);
2789
+ const used = new Set(event.payload?.attachmentIds || []);
2790
+ state.attachments = state.attachments.filter(item => !used.has(item.attachmentId));
2791
+ paintAttachments(); updateSendState();
2792
+ if (ui.input.value.trim() !== confirmed) return;
2793
+ clearTimeout(state.draftTimer);
2794
+ ui.input.value = '';
2795
+ state.localDraft = { chatId, text: '' };
2796
+ if (state.chat?.chatId === chatId) state.chat.draft = '';
2797
+ autosize(); paintAttachments(); updateSendState();
2798
+ void writeChatDraft(chatId, state.scope.owner, '').catch(error => report(error, 'Draft was not saved'));
2799
+ }
2800
+
1943
2801
  async function ensureSession() {
1944
2802
  if (state.sessionReady) return;
1945
2803
  await request('/api/chat/session');
@@ -1957,7 +2815,7 @@
1957
2815
  // Claude or Codex as "not ready".
1958
2816
  return await request(`/api/chat/providers/${chat.provider}?${ownerQuery()}&chatId=${encodeURIComponent(chat.chatId)}`);
1959
2817
  } catch (error) {
1960
- return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error) };
2818
+ return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error), readFailed: true };
1961
2819
  }
1962
2820
  }
1963
2821
 
@@ -2007,10 +2865,14 @@
2007
2865
  closeSource();
2008
2866
  clearLiveStream(true);
2009
2867
  state.chat = null; state.events = []; state.capability = null; state.desktop = null;
2010
- state.attachments = []; state.integrations = null;
2868
+ state.attachments = []; state.followupUnknownId = null; state.integrations = null;
2869
+ updateOffscreenActivity();
2011
2870
  // The header switches to the next conversation now; the previous provider's setup card and composer
2012
2871
  // hint must not stay under it while that conversation opens.
2013
2872
  paintRuntime(); clearReport();
2873
+ // The user picked a conversation; they are not choosing a provider. state.chat is null only
2874
+ // because this function cleared it, so the predicate has to be told rather than left to infer.
2875
+ paintComposerDisclosure({ opening: true });
2014
2876
  ui.title.textContent = listed?.title || 'Opening conversation';
2015
2877
  ui.scope.textContent = listed ? `${state.scope?.label || ''} · ${providerLabels[listed.provider]}` : 'Opening conversation';
2016
2878
  ui.rename.hidden = true;
@@ -2018,12 +2880,12 @@
2018
2880
  ui.stop.hidden = true; ui.send.hidden = false;
2019
2881
  ui.settings.hidden = true; ui.settingsToggle.setAttribute('aria-expanded', 'false');
2020
2882
  ui.recovery.hidden = true;
2021
- shell.querySelector('.ai-chat-approval')?.remove();
2883
+ ui.approvalTray.replaceChildren();
2022
2884
  ui.attachments.replaceChildren();
2023
2885
  ui.feed.replaceChildren();
2024
2886
  const loading = document.createElement('div'); loading.className = 'ai-chat-empty';
2025
2887
  const strong = document.createElement('strong'); strong.textContent = 'Opening conversation';
2026
- const copy = document.createElement('div'); copy.textContent = listed
2888
+ const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy'; copy.textContent = listed
2027
2889
  ? `Loading “${listed.title}”…`
2028
2890
  : 'Loading the selected conversation…';
2029
2891
  loading.append(strong, copy); ui.feed.append(loading);
@@ -2041,18 +2903,25 @@
2041
2903
  if (state.choosingProvider && options.replaceProviderChoice !== true) return;
2042
2904
  // Opening an existing conversation abandons an unsent discovery handoff. Only the
2043
2905
  // conversation created from that chooser should inherit its draft.
2044
- if (!options.preserveDiscoveryDraft) state.discoveryDraft = null;
2906
+ if (!options.preserveDiscoveryDraft) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; }
2045
2907
  clearProviderChoice();
2046
2908
  const selection = ++state.selectionGeneration;
2047
2909
  const exactAnswer = typeof options.answerEventId === 'string' ? options.answerEventId : null;
2048
2910
  clearAnswerJump();
2049
2911
  if (!exactAnswer) {
2050
2912
  closeSource(); closePicker();
2051
- state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
2913
+ closeHistoryPanel();
2052
2914
  }
2915
+ // The provider check below can take seconds, and the conversation already looks open while it
2916
+ // runs, so a person may reopen the history (to rename another row, say) before it ends. What
2917
+ // the late step may still do depends on whether they did: remember the history's opening count
2918
+ // and where focus sits now, and compare both when the check returns (#1646).
2919
+ const historyOpenings = state.historyOpenings;
2920
+ const focusAtStart = document.activeElement;
2053
2921
  const generation = state.scopeGeneration;
2054
2922
  showConversationLoading(chatId);
2055
2923
  setBusy(true);
2924
+ let failure = null;
2056
2925
  try {
2057
2926
  const [chat, snapshot] = await Promise.all([
2058
2927
  request(`/api/chat/conversations/${encodeURIComponent(chatId)}?${ownerQuery()}`),
@@ -2069,14 +2938,21 @@
2069
2938
  }
2070
2939
  const [capability, desktop] = await Promise.all([readCapability(chat), readDesktopCapability(chat)]);
2071
2940
  if (generation !== state.scopeGeneration || selection !== state.selectionGeneration) return;
2941
+ // Reopened while this conversation was opening: the person has moved on to the history, so
2942
+ // it stays open — with any rename in it — and focus stays where they put it (#1646).
2943
+ const historyReopened = state.historyOpenings !== historyOpenings;
2072
2944
  closeSource(); closePicker();
2073
- state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
2945
+ if (!historyReopened) closeHistoryPanel();
2074
2946
  state.chat = chat;
2075
2947
  state.events = snapshot.events || [];
2948
+ reconcileUnknownFollowupOnSelection(chat);
2076
2949
  state.capability = capability;
2077
2950
  state.desktop = desktop;
2078
2951
  state.attachments = (chat.attachments || []).filter((attachment) => !attachment.turnId);
2079
- ui.input.value = chat.draft || '';
2952
+ ui.input.value = draftForChat(chat);
2953
+ // A cached draft may be newer than the server draft after a fast switch.
2954
+ // Save it now, even if the user does not type again after reopening.
2955
+ if (state.backgroundDrafts.has(chatId) && draftFitsStorage(state.scope.owner, ui.input.value)) saveDraftSoon();
2080
2956
  if (answerTarget) {
2081
2957
  state.answerJump = { chatId, eventId: answerTarget.eventId, expiresAt: Date.now() + 2600 };
2082
2958
  state.answerJumpTimer = setTimeout(() => {
@@ -2084,6 +2960,7 @@
2084
2960
  }, 2600);
2085
2961
  }
2086
2962
  paintConversation(); connectEvents();
2963
+ resumeFilterRequests();
2087
2964
  if (options.applyProviderDefaults || !chat.nativeSessionId) await applyProviderDefaults(chatId);
2088
2965
  // Let the server prepare the provider for the next message while the user types, after the
2089
2966
  // default model and effort are saved so the prepared runtime matches the first message. Best-effort:
@@ -2096,14 +2973,47 @@
2096
2973
  announce(`Opened Instructor answer in ${state.chat.title}.`);
2097
2974
  } else {
2098
2975
  markRead();
2099
- if (options.focus) ui.input.focus();
2976
+ // Only move focus when nothing has taken it since the selection began: the history was not
2977
+ // reopened (checked again here, because applyProviderDefaults awaited another round-trip
2978
+ // after the close above), and focus is still where the selection left it or nowhere at all.
2979
+ const reopenedSinceStart = state.historyOpenings !== historyOpenings;
2980
+ const focusNow = document.activeElement;
2981
+ const focusUntouched = !focusNow || focusNow === document.body || focusNow === focusAtStart;
2982
+ if (options.focus && !reopenedSinceStart && focusUntouched) ui.input.focus();
2983
+ // Focus stayed in the reopened history, so nothing else tells a screen reader it finished.
2984
+ else if (reopenedSinceStart) announce(`Opened ${state.chat.title}.`);
2100
2985
  }
2101
2986
  } catch (error) {
2102
- if (generation === state.scopeGeneration && selection === state.selectionGeneration) {
2103
- report(error, 'Could not open conversation');
2104
- }
2987
+ failure = error;
2105
2988
  }
2106
2989
  finally { if (selection === state.selectionGeneration) setBusy(false); }
2990
+ // Reported AFTER setBusy: its composer refresh rewrites the hint, which erased this sentence the
2991
+ // moment it appeared and left only "Opening conversation…" on screen (#1604).
2992
+ if (failure && generation === state.scopeGeneration && selection === state.selectionGeneration) {
2993
+ report(failure, 'Could not open conversation');
2994
+ }
2995
+ }
2996
+
2997
+ function reconcileUnknownFollowupOnSelection(chat) {
2998
+ const chatId = chat.chatId;
2999
+ const uncertain = state.unknownFollowups.get(chatId);
3000
+ if (!uncertain) return;
3001
+ const confirmed = state.events.some(event => event.type === 'user-message'
3002
+ && event.clientSubmissionId === uncertain.submissionId);
3003
+ if (confirmed) {
3004
+ state.unknownFollowups.delete(chatId);
3005
+ if (state.backgroundDrafts.get(chatId)?.trim() === uncertain.text.trim()) state.backgroundDrafts.delete(chatId);
3006
+ if ((state.localDraft?.chatId === chatId && state.localDraft.text.trim() === uncertain.text.trim())
3007
+ || chat.draft?.trim() === uncertain.text.trim()) {
3008
+ state.localDraft = { chatId, text: '' };
3009
+ chat.draft = '';
3010
+ void writeChatDraft(chatId, state.scope.owner, '').catch(error => report(error, 'Draft was not saved'));
3011
+ }
3012
+ } else {
3013
+ state.followupUnknownId = uncertain.submissionId;
3014
+ if (!state.events.some(event => event.type === 'user-message'
3015
+ && event.clientSubmissionId === uncertain.submissionId)) state.events.push(uncertain.event);
3016
+ }
2107
3017
  }
2108
3018
 
2109
3019
  async function applyProviderDefaults(chatId) {
@@ -2126,7 +3036,11 @@
2126
3036
  return;
2127
3037
  }
2128
3038
  const generation = ++state.scopeGeneration;
2129
- if (scopeKey(scope) !== scopeKey(state.scope)) state.discoveryDraft = null;
3039
+ // An open history-row rename belongs to the list being replaced. End it before the history is
3040
+ // hidden below: hiding the focused field blurs it, and blur must not save a half-typed name
3041
+ // into the conversation the person just navigated away from (#1582).
3042
+ state.historyRename?.abandon();
3043
+ if (scopeKey(scope) !== scopeKey(state.scope)) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; state.teklaDraft = null; }
2130
3044
  state.selectionGeneration += 1;
2131
3045
  clearAnswerJump();
2132
3046
  clearLiveStream(true);
@@ -2134,9 +3048,13 @@
2134
3048
  clearProviderChoice();
2135
3049
  state.scope = scope;
2136
3050
  state.scopeInitialized = true;
2137
- state.chat = null; state.chats = []; state.archivedChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
3051
+ state.chat = null; state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
3052
+ // A published filter answer still lands in its own project's conversation; reopening it resumes.
3053
+ for (const entry of state.filterPending.values()) clearTimeout(entry.timer);
3054
+ state.filterPending.clear(); state.filterNotices.clear(); state.filterCardMessages.clear();
3055
+ updateOffscreenActivity();
2138
3056
  state.historyFilter = 'all'; state.instructorAnswers = []; state.historyLoading = false; state.historyRequestGeneration += 1;
2139
- state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
3057
+ closeHistoryPanel();
2140
3058
  if (!scope?.owner) { showUnscoped(); return; }
2141
3059
  ui.scope.textContent = scope.label;
2142
3060
  ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
@@ -2146,6 +3064,7 @@
2146
3064
  const result = await request(`/api/chat/conversations?${ownerQuery(scope.owner)}`);
2147
3065
  if (generation !== state.scopeGeneration) return;
2148
3066
  state.chats = result.chats || [];
3067
+ state.unreadableChats = result.unreadableChats || [];
2149
3068
  seedReadCursors(state.chats, scope.owner);
2150
3069
  paintHistory(); paintUnread();
2151
3070
  if (state.chats.length) await selectConversation(state.chats[0].chatId);
@@ -2155,7 +3074,8 @@
2155
3074
  // A history read can fail independently of the selected project (for example while an
2156
3075
  // older, stale conversation is being recovered). Do not erase the scope and disable the
2157
3076
  // whole panel: the user can still start a new conversation in the project that is open.
2158
- state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null;
3077
+ state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null;
3078
+ updateOffscreenActivity();
2159
3079
  ui.scope.textContent = scope.label;
2160
3080
  ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
2161
3081
  paintHistory(); paintUnread(); providerChooser();
@@ -2194,6 +3114,11 @@
2194
3114
  state.discoveryDraft = null;
2195
3115
  ui.input.dispatchEvent(new Event('input', { bubbles: true }));
2196
3116
  }
3117
+ if (state.pendingTeklaLibrary && state.chat?.chatId === chat.chatId) {
3118
+ state.teklaDraft = { chatId: chat.chatId, library: state.pendingTeklaLibrary, status: 'draft', error: null };
3119
+ state.pendingTeklaLibrary = null;
3120
+ paintTeklaChip();
3121
+ }
2197
3122
  announce(`${providerLabels[provider]} conversation created.`);
2198
3123
  } catch (error) { report(error, 'Could not start conversation'); }
2199
3124
  finally { setBusy(false); }
@@ -2208,6 +3133,7 @@
2208
3133
  const result = await request(`/api/chat/conversations?${ownerQuery()}&filter=instructor-answers`);
2209
3134
  if (requestGeneration !== state.historyRequestGeneration || scopeGeneration !== state.scopeGeneration) return;
2210
3135
  state.chats = result.chats || [];
3136
+ state.unreadableChats = result.unreadableChats || [];
2211
3137
  state.instructorAnswers = result.instructorAnswers || [];
2212
3138
  } catch (error) {
2213
3139
  if (requestGeneration === state.historyRequestGeneration) report(error, 'Could not load Instructor answers');
@@ -2268,11 +3194,26 @@
2268
3194
  else ui.history.querySelector('[aria-pressed="true"]')?.focus();
2269
3195
  }
2270
3196
 
3197
+ // Closes the history from anywhere other than its own toggle, and keeps everything toggleHistory
3198
+ // keeps in step: the toggle's aria-expanded (#1641) and the offscreen-activity line. An open row
3199
+ // rename is abandoned first, as loadScope does (#1582): hiding the focused field blurs it, and a
3200
+ // blur must never save a half-typed name. Focus is left alone; each caller decides that.
3201
+ function closeHistoryPanel() {
3202
+ state.historyRename?.abandon();
3203
+ state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
3204
+ ui.historyToggle.setAttribute('aria-expanded', 'false');
3205
+ updateOffscreenActivity();
3206
+ }
3207
+
2271
3208
  function toggleHistory(force, options = {}) {
2272
3209
  const open = force === undefined ? !state.historyOpen : Boolean(force);
3210
+ // Counts every opening, so a conversation still opening in the background can tell the person
3211
+ // reopened the history after it began (#1646).
3212
+ if (open) state.historyOpenings += 1;
2273
3213
  state.historyOpen = open;
2274
3214
  shell.classList.toggle('history-open', open);
2275
3215
  ui.history.hidden = !open;
3216
+ updateOffscreenActivity();
2276
3217
  ui.historyToggle.setAttribute('aria-expanded', String(open));
2277
3218
  if (open) {
2278
3219
  ui.settings.hidden = true;
@@ -2281,7 +3222,7 @@
2281
3222
  if (state.historyFilter === 'instructor-answers') refreshInstructorAnswers(true);
2282
3223
  else refreshArchivedChats();
2283
3224
  } else if (options.focusToggle) ui.historyToggle.focus();
2284
- else ui.input.focus();
3225
+ else if (!options.keepFocus) ui.input.focus();
2285
3226
  }
2286
3227
 
2287
3228
  function closePicker() {
@@ -2327,7 +3268,7 @@
2327
3268
  function modelChoices() {
2328
3269
  const models = state.capability?.models || [];
2329
3270
  return models.map((model) => ({
2330
- id: `model:${model.id}`, label: model.label, meta: '',
3271
+ id: `model:${model.id}`, label: model.label, meta: model.detail || '',
2331
3272
  selected: (state.chat.settings.model || selectedModel()?.id) === model.id, patch: { model: model.id },
2332
3273
  }));
2333
3274
  }
@@ -2442,17 +3383,30 @@
2442
3383
  function updateSendState() {
2443
3384
  const active = turnIsVisiblyActive();
2444
3385
  const recovery = state.chat?.state === 'recovery';
2445
- const frozen = recovery || Boolean(state.chat?.activeTurn) || Boolean(state.chat?.archivedAt);
3386
+ const frozen = recovery || Boolean(state.chat?.activeTurn?.local) || Boolean(state.chat?.archivedAt);
2446
3387
  const blocked = requestExecutionBlocked();
2447
3388
  // A provider FloLess is still setting up cannot take a message; the runtime card explains why.
2448
3389
  const settingUp = Boolean(state.capability?.runtime && state.capability.runtime.state !== 'installed');
2449
3390
  const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
2450
- ui.input.disabled = !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
2451
- ui.send.disabled = state.loading || uploading || !state.chat || blocked || frozen
3391
+ ui.input.disabled = state.followupSubmitting || !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
3392
+ const filterMode = paintFilterComposer().state !== 'off';
3393
+ ui.send.disabled = state.loading || state.followupSubmitting || state.filterSending || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
2452
3394
  || (!ui.input.value.trim() && state.attachments.length === 0) || settingUp;
2453
- ui.attach.disabled = state.loading || uploading || !state.chat || blocked || frozen;
3395
+ // Drawing Filter messages carry the filter's own context, never attached files.
3396
+ ui.attach.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
3397
+ || filterMode;
3398
+ const unknownReason = state.followupUnknownId || hasUnknownFollowup()
3399
+ ? 'FloLess could not confirm a follow-up. Review that message before sending or attaching another file.' : null;
3400
+ const sendingReason = state.followupSubmitting
3401
+ ? 'FloLess is saving this message. Wait for its delivery status before sending another.'
3402
+ : state.filterSending ? 'FloLess is sending this message to the Drawing Filter. Wait for it to appear before sending another.' : null;
3403
+ for (const control of [ui.send, ui.attach]) {
3404
+ if (unknownReason || sendingReason) control.dataset.blockedReason = unknownReason || sendingReason;
3405
+ else delete control.dataset.blockedReason;
3406
+ }
3407
+ if (filterMode && !unknownReason && !sendingReason) ui.attach.dataset.blockedReason = 'Drawing Filter messages do not include attachments. Attach files from another tab.';
2454
3408
  ui.stop.hidden = !active || Boolean(state.chat?.activeTurn?.local);
2455
- ui.send.hidden = active;
3409
+ ui.send.hidden = false;
2456
3410
  // Session recovery must remain available even while provider capability discovery is loading
2457
3411
  // or has failed; it is the escape hatch for that exact state.
2458
3412
  ui.refresh.disabled = !state.chat;
@@ -2465,22 +3419,110 @@
2465
3419
  ui.input.style.height = `${Math.min(132, ui.input.scrollHeight)}px`;
2466
3420
  }
2467
3421
 
3422
+ function draftFitsStorage(owner, draft) {
3423
+ const encoder = new TextEncoder();
3424
+ // Match CHAT_STORE_LIMITS.maxDraftBytes and the draft route's bodyLimit.
3425
+ return !draft.includes('\u0000') && encoder.encode(draft).length <= 128 * 1024
3426
+ && encoder.encode(JSON.stringify({ owner, draft })).length <= 129 * 1024;
3427
+ }
3428
+
2468
3429
  function saveDraftSoon() {
2469
3430
  clearTimeout(state.draftTimer);
2470
3431
  if (!state.chat) return;
2471
3432
  const chatId = state.chat.chatId;
2472
3433
  const draft = ui.input.value;
2473
- state.chat.draft = draft;
3434
+ state.localDraft = { chatId, text: draft };
3435
+ state.draftVersions.set(chatId, (state.draftVersions.get(chatId) || 0) + 1);
3436
+ // Keep the newest local text until the matching server write succeeds.
3437
+ // This also preserves an unsavable draft when the user switches chats.
3438
+ state.backgroundDrafts.set(chatId, draft);
3439
+ if (!draftFitsStorage(state.scope.owner, draft)) return;
2474
3440
  state.draftTimer = setTimeout(async () => {
2475
3441
  if (state.chat?.chatId !== chatId) return;
2476
3442
  try {
2477
- await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/draft`, {
2478
- method: 'PUT', body: JSON.stringify({ owner: state.scope.owner, draft }),
2479
- });
3443
+ await writeChatDraft(chatId, state.scope.owner, draft);
2480
3444
  } catch (error) { report(error, 'Draft was not saved'); }
2481
3445
  }, 350);
2482
3446
  }
2483
3447
 
3448
+ async function writeChatDraft(chatId, owner, draft) {
3449
+ if (!draftFitsStorage(owner, draft)) return;
3450
+ const version = state.draftVersions.get(chatId) || 0;
3451
+ const previous = state.draftWrites.get(chatId) || Promise.resolve();
3452
+ const write = previous.catch(() => {}).then(() => request(`/api/chat/conversations/${encodeURIComponent(chatId)}/draft`, {
3453
+ method: 'PUT', body: JSON.stringify({ owner, draft }),
3454
+ }));
3455
+ state.draftWrites.set(chatId, write);
3456
+ try {
3457
+ await write;
3458
+ if (state.draftVersions.get(chatId) === version && state.backgroundDrafts.get(chatId) === draft) state.backgroundDrafts.delete(chatId);
3459
+ }
3460
+ finally { if (state.draftWrites.get(chatId) === write) state.draftWrites.delete(chatId); }
3461
+ }
3462
+
3463
+ // The options replace the plain "not sent" words when the caller knows better what happened (a Drawing
3464
+ // Filter message AI did not start on, #1643, which the conversation still shows): `announcement` for
3465
+ // the words coming back, `mergeLabel` and `mergedAnnouncement` when newer typing is kept above them.
3466
+ // A merged draft always asks for a review.
3467
+ async function restoreBackgroundDraft(snapshot, text, submissionId, { announcement, mergeLabel = 'Earlier unsent message:', mergedAnnouncement } = {}) {
3468
+ let existing = '';
3469
+ if (state.chat?.chatId === snapshot.chatId) {
3470
+ if (state.events.some(event => event.type === 'user-message' && event.clientSubmissionId === submissionId)) return;
3471
+ existing = ui.input.value;
3472
+ } else {
3473
+ // The user can type and save a newer draft in A, leave A again, and only
3474
+ // then receive A's refusal. Read A's latest saved draft before restoring.
3475
+ try {
3476
+ await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
3477
+ const latest = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}?${ownerQuery(snapshot.scope.owner)}`);
3478
+ existing = latest.draft || '';
3479
+ } catch (error) { console.error('[chat] could not read the newer draft before restoration:', error); }
3480
+ // A pending local draft is the full composer value and is newer than a
3481
+ // server draft from before the debounce. Use it once, never append it to
3482
+ // an older prefix or append the same local value a second time.
3483
+ if (state.backgroundDrafts.has(snapshot.chatId)) existing = state.backgroundDrafts.get(snapshot.chatId);
3484
+ if (state.localDraft?.chatId === snapshot.chatId) existing = state.localDraft.text;
3485
+ }
3486
+ // A can become selected again, or receive newer typing, while the draft
3487
+ // read above is in flight. Recheck the live composer after the await.
3488
+ if (state.chat?.chatId === snapshot.chatId) {
3489
+ if (state.events.some(event => event.type === 'user-message' && event.clientSubmissionId === submissionId)) return;
3490
+ existing = ui.input.value;
3491
+ } else if (state.localDraft?.chatId === snapshot.chatId) {
3492
+ existing = state.localDraft.text;
3493
+ }
3494
+ const merged = Boolean(existing.trim() && existing.trim() !== text.trim());
3495
+ if (merged) text = `${existing}\n\n${mergeLabel}\n${text}`;
3496
+ if (state.chat?.chatId === snapshot.chatId) {
3497
+ clearTimeout(state.draftTimer);
3498
+ if (ui.input.value !== text) {
3499
+ ui.input.value = text;
3500
+ autosize(); updateSendState();
3501
+ }
3502
+ announce(merged ? mergedAnnouncement || 'An earlier unsent message was added to your draft. Review it before sending.'
3503
+ : announcement || 'The message was not sent. Its text is back in your draft.');
3504
+ state.localDraft = { chatId: snapshot.chatId, text };
3505
+ }
3506
+ state.draftVersions.set(snapshot.chatId, (state.draftVersions.get(snapshot.chatId) || 0) + 1);
3507
+ state.backgroundDrafts.set(snapshot.chatId, text);
3508
+ try {
3509
+ await writeChatDraft(snapshot.chatId, snapshot.scope.owner, text);
3510
+ } catch (error) { console.error('[chat] could not save a refused message as a draft:', error); }
3511
+ }
3512
+
3513
+ function initialTurnDefinitelyRefused(error) {
3514
+ return sessionNeedsRenewal(error) || error?.status === 413 || error?.status === 400
3515
+ // `chat-record-unreadable` is deliberately NOT here, though POST /turns reads the conversation
3516
+ // at the start and a refusal there IS provably unsent (#1629). The same code also escapes the
3517
+ // route AFTER the turn is durable and dispatched — listChatEvents and the reply's own readChat
3518
+ // both re-read the record once the user-message event is published — and the browser cannot
3519
+ // tell the two apart. Handing the text back then would send it twice; losing it from the
3520
+ // composer, which is what a torn record has always done, only costs the retype.
3521
+ || ['chat-provider-unavailable', 'chat-turn-active', 'chat-turn-settling', 'chat-followup-queued', 'chat-followup-unconfirmed',
3522
+ 'chat-owner-busy', 'chat-host-busy', 'chat-attachment-scope',
3523
+ 'chat-root-stale', 'chat-archived'].includes(String(error?.code || ''));
3524
+ }
3525
+
2484
3526
  function paintSkills() {
2485
3527
  ui.skills.replaceChildren();
2486
3528
  const match = ui.input.value.slice(0, ui.input.selectionStart).match(/(?:^|\s)\/([A-Za-z0-9:_-]*)$/u);
@@ -2505,10 +3547,683 @@
2505
3547
  ui.skills.hidden = false;
2506
3548
  }
2507
3549
 
3550
+ // ── Drawing Filter help ────────────────────────────────────────────────────────────────────────
3551
+ // While the Drawing Filter is the visible surface, this composer sends a read-only guide request
3552
+ // about the filter instead of a normal turn, and its answer is published into this conversation.
3553
+ // The filter page (its iframe) owns the drawing, the selection and every Apply / Undo / Keep guard;
3554
+ // for anything about the drawing this chat only relays through `window.__floFilterAi`. The chat owns
3555
+ // linking, starting and polling the request itself.
3556
+ // There is no mode to choose: the person just asks or says what to change. Every message is sent as
3557
+ // a request that may suggest ticks, and a review card appears only when the answer does.
3558
+ const FILTER_PENDING = 'AI is reading the filter…';
3559
+ const FILTER_NOT_OPEN = 'Open Drawing Filter to use this suggestion.';
3560
+ // Mirrors the filter page's own FILTER_AI_UNKNOWN: with no page at all, its records are gone too.
3561
+ 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.';
3562
+ // Codes the start route (/api/chat/requests/:id/start) returns before it writes a link; a 400 counts
3563
+ // too, and an expired chat session is renewed and retried. Only when every attempt was definitely
3564
+ // refused does sendFilterAi clean the request up. After any other failure the request is never
3565
+ // deleted: it continues only if Requests shows the link, and otherwise stays in Requests.
3566
+ const FILTER_LINK_REFUSALS = new Set(['request-chat-unavailable', 'request-chat-owner-changed']);
3567
+ const FILTER_LINK_REFUSAL_COPY = {
3568
+ // One code for several causes (a reply started, archived, another provider), so no cause is named.
3569
+ '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.',
3570
+ 'request-chat-owner-changed': 'The project changed while FloLess was sending this. Open the project again, then send it once more. Nothing was sent.',
3571
+ };
3572
+ const FILTER_CREATE_TIMEOUT = 'FloLess did not answer in time, so this request may not have started. Check Requests before sending it again.';
3573
+ // One cause-free pair for every failed answer check: a slow server, a dropped connection and a bug
3574
+ // look the same from here.
3575
+ const FILTER_CHECK_RETRY = 'FloLess could not check the answer yet. Trying again.';
3576
+ 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.';
3577
+ let filterBridgeWarned = false;
3578
+
3579
+ function filterRefusal(message) {
3580
+ return Object.assign(new Error(message), { filterRefusal: true });
3581
+ }
3582
+
3583
+ /** A broken filter page is a bug worth one console line, not a silent "still loading" forever. */
3584
+ function warnFilterBridge(error) {
3585
+ if (filterBridgeWarned) return;
3586
+ filterBridgeWarned = true;
3587
+ console.error('[chat] the Drawing Filter page did not answer AI Chat:', error);
3588
+ }
3589
+
3590
+ /**
3591
+ * Whether the composer is in Drawing Filter mode depends on the visible surface. A filter page that
3592
+ * has not finished loading means 'loading' (Send refuses, never a normal turn); only the page's own
3593
+ * empty screen ('unavailable') drops back to a normal chat.
3594
+ */
3595
+ function filterSurface() {
3596
+ if (currentSurface() !== 'drawing-filter') return { state: 'off' };
3597
+ const frame = document.getElementById('ws-frame-drawings');
3598
+ if (!frame || !String(frame.dataset.want || '').startsWith('/steel-filter.html')) return { state: 'off' };
3599
+ let bridge = null;
3600
+ let summary = null;
3601
+ try {
3602
+ bridge = frame.contentWindow?.__floFilterAi || null;
3603
+ summary = bridge ? bridge.summary() : null;
3604
+ } catch (error) { warnFilterBridge(error); bridge = null; summary = null; }
3605
+ if (!bridge || !summary || summary.state === 'loading') return { state: 'loading' };
3606
+ if (summary.state !== 'ready') return { state: 'off' };
3607
+ return { state: 'ready', bridge, summary };
3608
+ }
3609
+
3610
+ /**
3611
+ * The composer's view of the Drawing Filter surface; returns it for the caller.
3612
+ *
3613
+ * It no longer rewrites the placeholder. One composer, one prompt: owner ruling, Pawel 2026-09-25 —
3614
+ * a second wording here made the same box look like a different box on one screen, for a mode the
3615
+ * person did not choose and cannot see the edges of.
3616
+ *
3617
+ * The mode is still real: Send routes a filter message through the Drawing Filter's own request
3618
+ * path rather than as a normal chat turn — a change request whose answer proposes ticks for the
3619
+ * person to review, run with read-only runtime options. (Not "a read-only question": `sendFilterAi`
3620
+ * hard-codes `kind = 'change'`, and a comment on this screen saying otherwise is how the next
3621
+ * reader gets it backwards.) What still announces it is `paintFloLessContext`'s "Sharing with AI:
3622
+ * Drawing Filter · partial view of <sheet> and its selection" — which is the better cue anyway,
3623
+ * because it NAMES THE SHEET, and it sits directly under the box. (The compose hint does not: its
3624
+ * chain in `clearReport` has no filter branch, and the attach control's blocked reason only speaks
3625
+ * once someone tries to attach. An earlier draft of this comment credited the hint; it was wrong.)
3626
+ */
3627
+ function paintFilterComposer() {
3628
+ return filterSurface();
3629
+ }
3630
+
3631
+ function filterPendingIn(chatId) {
3632
+ return [...state.filterPending.values()].some((entry) => entry.chatId === chatId);
3633
+ }
3634
+
3635
+ function filterAnswered(requestId) {
3636
+ return state.events.some((event) => event.type === 'assistant-message' && event.payload?.requestId === requestId);
3637
+ }
3638
+
3639
+ /** Why a filter message cannot be sent right now, or null. Checked before the draft is touched. */
3640
+ function filterSendRefusal(surface, text) {
3641
+ const chat = state.chat;
3642
+ if (surface.state !== 'ready') return 'The Drawing Filter is still loading. Wait until its layers appear, then send again. Nothing was sent.';
3643
+ if (turnIsVisiblyActive(chat) || chat.activeTurn) return 'Wait for the current AI reply to finish before asking about the filter. Your message was not sent.';
3644
+ if (filterPendingIn(chat.chatId)) return 'Wait for the current Drawing Filter answer before sending another. Your message was not sent.';
3645
+ 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.';
3646
+ // Counted exactly as the filter page counts it, so the two limits can never disagree.
3647
+ if (text.length > 300) return 'Shorten your message to 300 characters, then send it again. Nothing was sent.';
3648
+ return null;
3649
+ }
3650
+
3651
+ function filterAccessFailure(status, detail) {
3652
+ if (status === 401 || detail?.reason === 'session-expired') return 'Your FloLess sign-in expired. Sign in again, then send your message again. Nothing changed.';
3653
+ if (detail?.reason === 'signed-out') return 'You are signed out of FloLess. Sign in, then send your message again. Nothing changed.';
3654
+ 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.';
3655
+ if (detail?.reason === 'no-subscription') return 'Your FloLess subscription is not active. Restore access, then send your message again. Nothing changed.';
3656
+ return 'FloLess could not access this answer. Check your sign-in and project access, then send your message again. Nothing changed.';
3657
+ }
3658
+
3659
+ /**
3660
+ * Start the read-only guide run. Resolves 'started', 'unconfirmed' (checking), or { refused: message }.
3661
+ * `notStarted: true` on a refusal means no AI can have started on it, so its words can be given back;
3662
+ * `runtime` is then the setup status when FloLess setting its AI up was the cause (#1650, #1643).
3663
+ */
3664
+ async function startFilterRun(requestId, runtime) {
3665
+ const controller = new AbortController();
3666
+ const deadline = setTimeout(() => controller.abort(), 15000);
3667
+ let started;
3668
+ try {
3669
+ started = await fetch(`/api/requests/${encodeURIComponent(requestId)}/run`, {
3670
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ runtime }), signal: controller.signal,
3671
+ });
3672
+ } catch { clearTimeout(deadline); return 'unconfirmed'; } // the server may have accepted it before the reply was lost
3673
+ if (started.ok) { clearTimeout(deadline); return 'started'; }
3674
+ const detail = await started.json().catch(() => null);
3675
+ clearTimeout(deadline);
3676
+ if (started.status === 409 && detail?.code === 'running') return 'started';
3677
+ // The run route flags a refusal it made before anything started (#1650, #1643). Definite even as a
3678
+ // 5xx; one without its notice is not trusted, and falls through to the rules below.
3679
+ if (detail?.notStarted === true && typeof detail.notice === 'string' && detail.notice) {
3680
+ return { refused: detail.notice, notStarted: true, runtime: detail.runtime ?? null };
3681
+ }
3682
+ if (detail?.code === 'filter-ai-provider-mismatch' && typeof detail.error === 'string') return { refused: detail.error };
3683
+ if ((started.status === 409 && !detail) || started.status >= 500) return 'unconfirmed';
3684
+ // The sign-in and licence check refuses before the route runs, so nothing started either.
3685
+ if ([401, 402, 403].includes(started.status)) return { refused: filterAccessFailure(started.status, detail), notStarted: true };
3686
+ // Several refusals land here, each with a different cause, so the sentence names none of them.
3687
+ return { refused: 'FloLess could not start AI for this request. Nothing changed. Send it again from AI Chat.' };
3688
+ }
3689
+
3690
+ /**
3691
+ * Request events (the linked question and the published answer) are written straight to the
3692
+ * conversation store and never reach the live event stream, so read them back explicitly.
3693
+ * Resolves true once the conversation was read.
3694
+ */
3695
+ async function mergeFilterEvents(chatId) {
3696
+ if (state.chat?.chatId !== chatId || !state.scope?.owner) return false;
3697
+ const snapshot = captureChat();
3698
+ const path = `/api/chat/conversations/${encodeURIComponent(chatId)}/events-snapshot?${ownerQuery(snapshot.scope.owner)}`;
3699
+ let listed;
3700
+ try {
3701
+ try { listed = await request(path); }
3702
+ catch (error) {
3703
+ // The chat session is short-lived; renew it once, as refreshConversation does.
3704
+ if (!sessionNeedsRenewal(error)) throw error;
3705
+ state.sessionReady = false;
3706
+ await ensureSession();
3707
+ listed = await request(path);
3708
+ }
3709
+ } catch (error) {
3710
+ console.error('[chat] could not read back the Drawing Filter messages:', error);
3711
+ return false;
3712
+ }
3713
+ if (!sameChat(snapshot)) return false;
3714
+ let added = false;
3715
+ for (const event of listed.events || []) {
3716
+ if (state.events.some((item) => item.eventId === event.eventId)) continue;
3717
+ state.events.push(event); added = true;
3718
+ }
3719
+ if (added) {
3720
+ state.events.sort((a, b) => a.sequence - b.sequence);
3721
+ state.chat.lastEventSequence = Math.max(state.chat.lastEventSequence || 0, ...state.events.map((event) => event.sequence || 0));
3722
+ paintEvents({ forceBottom: true });
3723
+ }
3724
+ return true;
3725
+ }
3726
+
3727
+ /** After an uncertain link: true only when Requests records this request linked to this conversation. */
3728
+ async function filterRequestLinked(requestId, chatId) {
3729
+ // Send stays blocked meanwhile, so this read is bounded; a slow list simply proves nothing.
3730
+ const listed = await fetch('/api/requests', { signal: AbortSignal.timeout(30000) })
3731
+ .then((response) => (response.ok ? response.json() : null)).catch(() => null);
3732
+ const row = Array.isArray(listed?.requests) ? listed.requests.find((candidate) => candidate?.id === requestId) : null;
3733
+ return row?.chatConversation?.chatId === chatId;
3734
+ }
3735
+
3736
+ function finishFilterPending(entry, notice) {
3737
+ if (state.filterPending.get(entry.requestId) !== entry) return false;
3738
+ state.filterPending.delete(entry.requestId);
3739
+ if (notice) { state.filterNotices.set(entry.requestId, notice); announce(notice); }
3740
+ if (state.chat?.chatId === entry.chatId) { paintEvents(); updateSendState(); }
3741
+ return true;
3742
+ }
3743
+
3744
+ function filterPollRecovered(entry) {
3745
+ entry.failures = 0;
3746
+ if (entry.retryNote) { entry.retryNote = ''; if (state.chat?.chatId === entry.chatId) paintEvents(); }
3747
+ }
3748
+
3749
+ function filterPollFailure(entry, stopped = FILTER_CHECK_STOPPED, retrying = FILTER_CHECK_RETRY) {
3750
+ entry.failures += 1;
3751
+ if (entry.failures >= 3) { finishFilterPending(entry, stopped); return; }
3752
+ entry.retryNote = retrying;
3753
+ if (state.chat?.chatId === entry.chatId) paintEvents();
3754
+ }
3755
+
3756
+ /**
3757
+ * Check one pending request again after `delay`. Each request runs its own chain of checks, started
3758
+ * once by sendFilterAi or resumeFilterRequests, so a slow or broken request never holds up another.
3759
+ */
3760
+ function scheduleFilterPoll(entry, delay = 2000) {
3761
+ clearTimeout(entry.timer);
3762
+ entry.timer = setTimeout(() => { void pollFilterRequest(entry); }, delay);
3763
+ }
3764
+
3765
+ /** One bounded check of one request. While the request is still pending, the next check is scheduled. */
3766
+ async function pollFilterRequest(entry) {
3767
+ const current = () => state.filterPending.get(entry.requestId) === entry;
3768
+ try {
3769
+ const query = new URLSearchParams({ app: entry.appId || '', ...(entry.project ? { project: entry.project } : {}) });
3770
+ const response = await fetch(`/api/filter-ai-answer/${encodeURIComponent(entry.requestId)}?${query}`,
3771
+ { signal: AbortSignal.timeout(15000) }).catch(() => null);
3772
+ if (!current()) return;
3773
+ if (!response) { filterPollFailure(entry); return; }
3774
+ if (response.status === 401 || response.status === 403) { finishFilterPending(entry, filterAccessFailure(response.status)); return; }
3775
+ if (response.status === 402) {
3776
+ const detail = await response.json().catch(() => null);
3777
+ if (current()) finishFilterPending(entry, filterAccessFailure(402, detail));
3778
+ return;
3779
+ }
3780
+ const result = response.ok ? await response.json().catch(() => null) : null;
3781
+ if (!current()) return;
3782
+ 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; }
3783
+ if (!result) { filterPollFailure(entry); return; }
3784
+ if (result.state === 'waiting') { filterPollRecovered(entry); return; }
3785
+ if (result.state === 'failed') { finishFilterPending(entry, result.error || 'AI could not answer this. Send it again. The filter has not changed.'); return; }
3786
+ // Reading Requests is what publishes a validated answer into its linked conversation. It lists
3787
+ // every request and can be slow on a busy machine, so its bound is generous.
3788
+ const listed = await fetch('/api/requests', { signal: AbortSignal.timeout(90000) })
3789
+ .then((res) => (res.ok ? res.json() : null)).catch(() => null);
3790
+ if (!current()) return;
3791
+ if (!Array.isArray(listed?.chatPublications)) {
3792
+ filterPollFailure(entry,
3793
+ '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.',
3794
+ 'The answer is ready. FloLess could not confirm whether it was added yet. Trying again.');
3795
+ return;
3796
+ }
3797
+ filterPollRecovered(entry);
3798
+ const published = listed.chatPublications.some((publication) => publication?.requestId === entry.requestId);
3799
+ const here = state.chat?.chatId === entry.chatId;
3800
+ if (here) await mergeFilterEvents(entry.chatId);
3801
+ if (!current()) return;
3802
+ // Done once the answer is on screen, or published into a conversation that is not open here.
3803
+ if ((here && filterAnswered(entry.requestId)) || (!here && published)) { finishFilterPending(entry, null); return; }
3804
+ // Publication and the read-back can lag the answer; the next checks try again before saying so.
3805
+ entry.readBack = (entry.readBack || 0) + 1;
3806
+ if (entry.readBack < 5) return;
3807
+ finishFilterPending(entry, published
3808
+ ? 'The answer was added to this conversation but could not be shown here. Reopen the conversation to see it.'
3809
+ : 'The answer is ready but FloLess could not add it to this conversation. Open Requests to read it.');
3810
+ } catch (error) {
3811
+ // A bug in this check counts as a failed check, so it still stops after three instead of looping.
3812
+ console.error('[chat] checking a Drawing Filter answer failed:', error);
3813
+ if (current()) filterPollFailure(entry);
3814
+ } finally {
3815
+ if (current()) scheduleFilterPoll(entry);
3816
+ }
3817
+ }
3818
+
3819
+ /**
3820
+ * After a reload or reopening a project conversation, keep watching its unanswered filter requests:
3821
+ * the newest five that show neither an answer nor a failure notice from this page session.
3822
+ */
3823
+ function resumeFilterRequests() {
3824
+ const chat = state.chat;
3825
+ if (!chat || state.scope?.owner?.kind !== 'project') return;
3826
+ const unanswered = state.events.filter((event) => event.type === 'user-message' && event.payload?.filterAi
3827
+ && event.payload.requestId && !filterAnswered(event.payload.requestId)
3828
+ && !state.filterPending.has(event.payload.requestId) && !state.filterNotices.has(event.payload.requestId)).slice(-5);
3829
+ for (const event of unanswered) {
3830
+ const entry = {
3831
+ requestId: event.payload.requestId, chatId: chat.chatId, kind: event.payload.filterAi.kind,
3832
+ appId: event.payload.filterAi.appId || '', project: state.scope.owner.projectId, failures: 0, note: '',
3833
+ };
3834
+ state.filterPending.set(entry.requestId, entry);
3835
+ scheduleFilterPoll(entry, 0);
3836
+ }
3837
+ }
3838
+
3839
+ /**
3840
+ * Hand a setup status to this conversation's own setup card (#1650): the card polls it, explains it,
3841
+ * offers Cancel or Try again, and keeps Send locked until the AI is set up. Only for the conversation
3842
+ * that sent the message, while it is still that AI's, and only for a status the card can show.
3843
+ */
3844
+ function adoptRuntimeStatus(snapshot, provider, status) {
3845
+ if (!status || typeof status !== 'object' || !['preparing', 'not-installed', 'failed'].includes(status.state)
3846
+ || !sameChat(snapshot) || !state.capability || state.chat?.provider !== provider) return false;
3847
+ state.capability = { ...state.capability, runtime: status };
3848
+ paintRuntime();
3849
+ return true;
3850
+ }
3851
+
3852
+ /** Why a Drawing Filter message was not sent while its AI is set up. The status decides; without one, no cause is claimed. */
3853
+ function filterSetupSentence(provider, status) {
3854
+ const name = providerLabels[provider] || 'the AI';
3855
+ if (status?.state === 'preparing' || status?.state === 'not-installed') {
3856
+ return `FloLess is setting up ${name}, so this message was not sent. It is back in your draft; send it once setup finishes.`;
3857
+ }
3858
+ if (status?.state === 'failed') return `${providerLabels[provider] || 'The AI'} could not be set up, so this message was not sent. It is back in your draft.`;
3859
+ // No status, a failed call (one that timed out may still have started the setup), or a state this
3860
+ // build cannot name.
3861
+ return `FloLess could not confirm that it is setting up ${name}, so this message was not sent. It is back in your draft; try again.`;
3862
+ }
3863
+
3864
+ /**
3865
+ * Ask FloLess to set up the conversation's own AI, through the setup card's Retry route (idempotent).
3866
+ * Resolves `{ installed: true }` when it already is, else the sentence to refuse the message with,
3867
+ * having handed the status to the card. It never waits for the setup: the card carries that wait.
3868
+ * `text` is the refused message, which the refusal puts back in the draft.
3869
+ */
3870
+ async function prepareFilterRuntime(snapshot, provider, text) {
3871
+ let status = null;
3872
+ try {
3873
+ status = (await request(`/api/managed-runtimes/${encodeURIComponent(provider)}/prepare`, { method: 'POST', body: '{}', timeoutMs: 10000 }))?.runtime || null;
3874
+ } catch (error) { console.warn('[chat] could not ask FloLess to set up the Drawing Filter AI:', error); }
3875
+ if (status?.state === 'installed') return { installed: true };
3876
+ const sentence = filterSetupSentence(provider, status);
3877
+ // The card's status check repaints the hint every two seconds; the sentence stays there while the
3878
+ // card shows the setup it was refused for and the words are in the draft (filterSetupHint), not only
3879
+ // until the first repaint.
3880
+ if (adoptRuntimeStatus(snapshot, provider, status)) {
3881
+ state.filterSetupNote = { key: runtimeCardKey(snapshot.chatId, status), sentence, text };
3882
+ }
3883
+ return { installed: false, sentence };
3884
+ }
3885
+
3886
+ async function sendFilterAi(surface) {
3887
+ const snapshot = captureChat();
3888
+ if (!snapshot || state.filterSending) return;
3889
+ const chat = state.chat;
3890
+ const kind = 'change';
3891
+ const text = ui.input.value.trim();
3892
+ if (!text) return;
3893
+ const refusal = filterSendRefusal(surface, text);
3894
+ if (refusal) { report(filterRefusal(refusal)); return; }
3895
+ // The draft is set aside before the first await, as a normal Send does: anything typed from here
3896
+ // on is newer than the submitted message and must survive whatever happens to it.
3897
+ // restoreBackgroundDraft skips a message the conversation already shows under this id; a Drawing
3898
+ // Filter message carries none, so a fresh id means the refused text is always given back.
3899
+ const submissionId = crypto.randomUUID();
3900
+ clearTimeout(state.draftTimer);
3901
+ state.localDraft = { chatId: snapshot.chatId, text: '' };
3902
+ state.backgroundDrafts.delete(snapshot.chatId);
3903
+ ui.input.value = ''; autosize();
3904
+ state.filterSending = true; updateSendState();
3905
+ let requestId = null;
3906
+ let failure = null;
3907
+ try {
3908
+ await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
3909
+ // Decided from what launching this conversation's own AI would see NOW, a read of its own (#1650):
3910
+ // the rows AI Chat was painted from can say "set up" for a copy of FloLess's that has gone since.
3911
+ // It answers only with this conversation's own provider, never a silently substituted one.
3912
+ // The read logs its own network and shape failures; a rejection here is a fault in the bridge.
3913
+ const launch = await window.flolessBridge?.filterRuntimeLaunch?.(chat.provider).catch((error) => {
3914
+ console.error('[chat] the Drawing Filter could not read which AI can start:', error);
3915
+ return null;
3916
+ });
3917
+ if (!launch || launch.readiness === 'unchecked') {
3918
+ throw filterRefusal('FloLess could not check which AI can answer Drawing Filter messages. Try again in a moment. Nothing was sent.');
3919
+ }
3920
+ if (launch.readiness === 'setup') {
3921
+ // FloLess has to set its own copy up first. Nothing is created: the setup starts, this
3922
+ // conversation's setup card shows it and keeps Send locked until it lands, and the words go back.
3923
+ const setup = await prepareFilterRuntime(snapshot, chat.provider, text);
3924
+ if (!setup.installed) throw filterRefusal(setup.sentence);
3925
+ // It finished between the read and the prepare: send as usual.
3926
+ } else if (launch.readiness !== 'ready') {
3927
+ 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.`);
3928
+ }
3929
+ // The promise belongs to the filter page. A page thrown away mid-request never settles it, so
3930
+ // the chat keeps its own deadline rather than leaving Send blocked in every conversation.
3931
+ const created = await Promise.race([
3932
+ surface.bridge.createRequest(kind, text),
3933
+ new Promise((resolve) => { setTimeout(resolve, 20000, { ok: false, message: FILTER_CREATE_TIMEOUT }); }),
3934
+ ]);
3935
+ if (!created?.ok) {
3936
+ throw filterRefusal([401, 402, 403].includes(created?.status)
3937
+ ? filterAccessFailure(created.status, { reason: created.reason })
3938
+ : created?.message || 'FloLess could not start this request. Nothing was sent.');
3939
+ }
3940
+ requestId = created.request.id;
3941
+ let linked = false;
3942
+ let uncertain = false;
3943
+ let linkError = null;
3944
+ for (let attempt = 0; attempt < 2 && !linked; attempt++) {
3945
+ try {
3946
+ await request(`/api/chat/requests/${encodeURIComponent(requestId)}/start`, {
3947
+ method: 'POST', timeoutMs: 10000,
3948
+ body: JSON.stringify({ provider: chat.provider, mode: 'discuss', chatId: snapshot.chatId, expectedOwner: snapshot.scope.owner }),
3949
+ });
3950
+ linked = true;
3951
+ } catch (error) {
3952
+ linkError = error;
3953
+ if (sessionNeedsRenewal(error)) { state.sessionReady = false; await ensureSession().catch(() => {}); continue; }
3954
+ // A definite refusal stops retrying. It only proves nothing was linked when no earlier attempt
3955
+ // was uncertain: a retry's refusal can follow a first attempt that did persist the link
3956
+ // (another tab started a turn). `uncertain` never resets.
3957
+ if (FILTER_LINK_REFUSALS.has(String(error?.code || '')) || error?.status === 400) break;
3958
+ uncertain = true;
3959
+ }
3960
+ }
3961
+ if (!linked && uncertain) {
3962
+ // Only proof of the link lets it continue. No link yet proves nothing: the lost attempt may still
3963
+ // be writing it, so nothing is deleted and the request stays in Requests.
3964
+ if (!(await filterRequestLinked(requestId, snapshot.chatId))) {
3965
+ throw filterRefusal('FloLess could not confirm whether this message reached AI Chat. Check Requests before sending it again.');
3966
+ }
3967
+ linked = true;
3968
+ }
3969
+ if (!linked) {
3970
+ try { surface.bridge.forget(requestId); } catch { /* the filter reloaded; it has no record */ }
3971
+ const cleared = await fetch(`/api/requests/${encodeURIComponent(requestId)}`, { method: 'DELETE', signal: AbortSignal.timeout(10000) })
3972
+ .then((response) => response.ok).catch(() => false);
3973
+ const why = FILTER_LINK_REFUSAL_COPY[String(linkError?.code || '')]
3974
+ || 'FloLess could not add this message to the conversation. Nothing was sent. Send it again.';
3975
+ throw filterRefusal(cleared ? why : `${why} The unsent request is still listed in Requests; you can clear it there.`);
3976
+ }
3977
+ // Linked durably, but the saved draft still holds the sent words. Rewrite it now rather than on
3978
+ // saveDraftSoon's debounce, so a reload cannot bring the sent message back; the composer's current
3979
+ // text (empty, or typed during creation or linking) is what survives.
3980
+ const draft = sameChat(snapshot) ? ui.input.value : state.backgroundDrafts.get(snapshot.chatId) ?? '';
3981
+ if (sameChat(snapshot)) {
3982
+ clearTimeout(state.draftTimer);
3983
+ state.localDraft = { chatId: snapshot.chatId, text: draft };
3984
+ }
3985
+ state.draftVersions.set(snapshot.chatId, (state.draftVersions.get(snapshot.chatId) || 0) + 1);
3986
+ state.backgroundDrafts.set(snapshot.chatId, draft);
3987
+ if (draftFitsStorage(snapshot.scope.owner, draft)) {
3988
+ void writeChatDraft(snapshot.chatId, snapshot.scope.owner, draft)
3989
+ .catch((error) => { if (sameChat(snapshot)) report(error, 'Draft was not saved'); });
3990
+ }
3991
+ const entry = { requestId, chatId: snapshot.chatId, kind, appId: created.request.appId || '', project: created.request.project || '', failures: 0, note: '' };
3992
+ state.filterPending.set(requestId, entry);
3993
+ state.filterNotices.delete(requestId);
3994
+ // Start AI first, so nothing between the link and the run can leave a linked request unstarted.
3995
+ const started = await startFilterRun(requestId, chat.provider);
3996
+ await mergeFilterEvents(snapshot.chatId);
3997
+ if (started?.refused) {
3998
+ finishFilterPending(entry, started.refused);
3999
+ if (started.notStarted) {
4000
+ // Nothing started, so the words come back to the draft; the conversation also keeps them, with
4001
+ // the notice under them. The setup card shows when FloLess setting its AI up was the cause,
4002
+ // first: it announces itself, and the live region keeps only its last line, so that line is the
4003
+ // whole notice (what happened, why, what next) and then where the words are. The message is in
4004
+ // the conversation, so a merge never calls it unsent. A refusal that is not flagged (another
4005
+ // owner's message) or a lost reply gives nothing back.
4006
+ adoptRuntimeStatus(snapshot, chat.provider, started.runtime);
4007
+ await restoreBackgroundDraft(snapshot, text, submissionId, {
4008
+ announcement: `${started.refused} Its text is back in your draft.`,
4009
+ mergeLabel: 'Earlier message AI did not start on:',
4010
+ mergedAnnouncement: `${started.refused} Its text was added to your draft. Review it before sending.`,
4011
+ });
4012
+ }
4013
+ return;
4014
+ }
4015
+ if (started === 'unconfirmed') entry.note = 'Checking whether AI started…';
4016
+ announce(FILTER_PENDING);
4017
+ if (sameChat(snapshot)) paintEvents({ forceBottom: true });
4018
+ scheduleFilterPoll(entry, 0);
4019
+ } catch (error) {
4020
+ failure = error;
4021
+ await restoreBackgroundDraft(snapshot, text, submissionId);
4022
+ } finally {
4023
+ state.filterSending = false;
4024
+ // updateSendState() repaints the hint, so the refusal is reported after it, not before.
4025
+ if (sameChat(snapshot)) {
4026
+ updateSendState();
4027
+ if (failure) report(failure, failure.filterRefusal ? '' : 'Message was not sent');
4028
+ }
4029
+ }
4030
+ }
4031
+
4032
+ function filterChangeLabel(item) {
4033
+ if (item.dimension === 'thickness') return `line weight ${item.value} pt`;
4034
+ return `${item.dimension} ${item.value}`;
4035
+ }
4036
+
4037
+ function filterModeLabel(value) {
4038
+ return String(value).split('+').map((dim) => ({ thickness: 'line weight', layer: 'layer', color: 'color' }[dim] || dim)).join(', ');
4039
+ }
4040
+
4041
+ /**
4042
+ * Ask the filter page about one suggestion. Its record is read even while another tab is showing,
4043
+ * so the card shows what this page did with it; acting on it needs the Drawing Filter visible (`open`).
4044
+ * No page at all (not opened since this window loaded, or reloading) means the page that recorded
4045
+ * the suggestion is gone, exactly like an unknown record.
4046
+ */
4047
+ function inspectFilterSuggestion(requestId, proposal) {
4048
+ let bridge = null;
4049
+ try { bridge = document.getElementById('ws-frame-drawings')?.contentWindow?.__floFilterAi || null; }
4050
+ catch (error) { warnFilterBridge(error); }
4051
+ let info = null;
4052
+ try { info = bridge ? bridge.inspect(requestId, proposal) : null; } catch (error) { warnFilterBridge(error); }
4053
+ if (!info) return { known: false, applicable: false, reason: FILTER_PAGE_GONE, open: false };
4054
+ const open = filterSurface().state === 'ready';
4055
+ // An unknown record keeps its own reason: opening the Drawing Filter would not bring it back.
4056
+ if (open || !info.known) return { ...info, open };
4057
+ return { ...info, open, applicable: false, reason: FILTER_NOT_OPEN };
4058
+ }
4059
+
4060
+ function filterActionButton(label, action, requestId, className, blockedReason) {
4061
+ const control = button(label, `shell.chat-filter-${action}#${requestId}`, className);
4062
+ control.dataset.commandInstanceLabel = 'Drawing Filter suggestion';
4063
+ if (blockedReason) {
4064
+ control.setAttribute('aria-disabled', 'true');
4065
+ control.dataset.tip = blockedReason;
4066
+ control.dataset.blockedReason = blockedReason;
4067
+ }
4068
+ return control;
4069
+ }
4070
+
4071
+ function paintFilterSuggestion(card, event) {
4072
+ const requestId = String(event.payload.requestId || '');
4073
+ const proposal = event.payload.filterAi.proposal;
4074
+ const hasChanges = proposal.changes.length > 0 || proposal.mode !== null;
4075
+ const info = inspectFilterSuggestion(requestId, proposal);
4076
+ const disposition = info.known ? info.disposition : 'pending';
4077
+ // An unknown record (reload, another window) claims no outcome, only that it predates this view.
4078
+ // "not saved" only while this suggestion's own Undo is live: Save and later edits retire it.
4079
+ const chip = card.querySelector('.ai-chat-filter-state');
4080
+ chip.textContent = !info.known ? 'from an earlier view' : {
4081
+ applied: info.undo ? 'applied, not saved' : 'applied', kept: 'not applied', undone: 'undone',
4082
+ }[disposition] || 'not applied';
4083
+ const status = card.querySelector('.ai-chat-filter-note');
4084
+ const override = state.filterCardMessages.get(requestId);
4085
+ // Why Apply is unavailable is visible text, not only the button's tooltip. The exception is a card
4086
+ // from an earlier view, which offers nothing at all: its chip says so, the tooltip says why, and
4087
+ // the reason stays readable to a screen reader instead of repeating on every old card.
4088
+ const earlier = !info.known && hasChanges && !override;
4089
+ if (earlier) chip.dataset.tip = info.reason || FILTER_PAGE_GONE; else delete chip.dataset.tip;
4090
+ status.classList.toggle('sr-only', earlier);
4091
+ status.textContent = override || (disposition !== 'pending' ? info.note : '')
4092
+ || (!hasChanges ? 'No selection changes suggested.' : info.applicable ? '' : info.reason || FILTER_NOT_OPEN);
4093
+ const actions = card.querySelector('.ai-chat-filter-actions');
4094
+ // Repaints run on every filter change; keep keyboard focus on the same control when it survives.
4095
+ const focused = actions.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
4096
+ actions.replaceChildren();
4097
+ if (!info.known) {
4098
+ // Nothing here can act on a suggestion this page never recorded; the note says why.
4099
+ } else if (disposition === 'pending' && hasChanges) {
4100
+ const unavailable = info.applicable ? null : info.reason || FILTER_NOT_OPEN;
4101
+ const keep = filterActionButton('Keep current', 'keep', requestId, 'ai-chat-filter-keep', info.known && info.open ? null : unavailable);
4102
+ const apply = filterActionButton('Apply selection', 'apply', requestId, 'ai-chat-filter-apply', unavailable);
4103
+ keep.addEventListener('click', () => runFilterSuggestionAction('keep', event));
4104
+ apply.addEventListener('click', () => runFilterSuggestionAction('apply', event));
4105
+ actions.append(keep, apply);
4106
+ } else if (disposition === 'applied' && info.undo) {
4107
+ const undo = filterActionButton('Undo', 'undo', requestId, 'ai-chat-filter-keep', info.open ? null : FILTER_NOT_OPEN);
4108
+ undo.addEventListener('click', () => runFilterSuggestionAction('undo', event));
4109
+ actions.append(undo);
4110
+ }
4111
+ actions.hidden = !actions.childNodes.length;
4112
+ if (focused) [...actions.children].find((control) => control.dataset.commandId === focused)?.focus({ preventScroll: true });
4113
+ }
4114
+
4115
+ function runFilterSuggestionAction(action, event) {
4116
+ const requestId = String(event.payload.requestId || '');
4117
+ // Re-resolve the page at click time: the frame may have reloaded since this card was painted.
4118
+ const surface = filterSurface();
4119
+ let result;
4120
+ if (surface.state !== 'ready') result = { ok: false, message: FILTER_NOT_OPEN };
4121
+ else {
4122
+ try {
4123
+ result = action === 'apply' ? surface.bridge.apply(requestId, event.payload.filterAi.proposal)
4124
+ : action === 'undo' ? surface.bridge.undo(requestId) : surface.bridge.keep(requestId);
4125
+ } catch (error) {
4126
+ console.error('[chat] the Drawing Filter could not finish a suggestion action:', error);
4127
+ 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.' };
4128
+ }
4129
+ }
4130
+ if (result?.ok) state.filterCardMessages.delete(requestId);
4131
+ else state.filterCardMessages.set(requestId, result?.message || FILTER_NOT_OPEN);
4132
+ announce(result?.message || FILTER_NOT_OPEN);
4133
+ refreshFilterCards();
4134
+ const card = ui.feed.querySelector(`.ai-chat-filter-card[data-request-id="${CSS.escape(requestId)}"]`);
4135
+ (card?.querySelector('.ai-chat-filter-actions button') || card?.querySelector('.ai-chat-filter-note'))?.focus({ preventScroll: true });
4136
+ }
4137
+
4138
+ function renderFilterSuggestion(event) {
4139
+ const proposal = event.payload.filterAi.proposal;
4140
+ const card = document.createElement('section');
4141
+ card.className = 'ai-chat-filter-card';
4142
+ card.dataset.requestId = String(event.payload.requestId || '');
4143
+ card.dataset.eventId = event.eventId;
4144
+ card.setAttribute('aria-label', 'Suggested filter changes');
4145
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
4146
+ const title = document.createElement('strong'); title.textContent = 'Suggested filter changes';
4147
+ const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state';
4148
+ head.append(title, chip);
4149
+ const list = document.createElement('ul'); list.className = 'ai-chat-filter-changes';
4150
+ for (const item of proposal.changes) {
4151
+ const row = document.createElement('li'); row.className = `ai-chat-filter-change ${item.on ? 'include' : 'exclude'}`;
4152
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-filter-change-glyph'; glyph.setAttribute('aria-hidden', 'true');
4153
+ row.append(glyph, document.createTextNode(`${item.on ? 'Include' : 'Exclude'} ${filterChangeLabel(item)}`));
4154
+ list.append(row);
4155
+ }
4156
+ if (proposal.mode !== null) {
4157
+ const row = document.createElement('li'); row.className = 'ai-chat-filter-change match';
4158
+ const glyph = document.createElement('span'); glyph.className = 'ai-chat-filter-change-glyph'; glyph.setAttribute('aria-hidden', 'true');
4159
+ row.append(glyph, document.createTextNode(`Match on ${filterModeLabel(proposal.mode)}`));
4160
+ list.append(row);
4161
+ }
4162
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-note'; note.tabIndex = -1;
4163
+ note.setAttribute('role', 'status');
4164
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
4165
+ card.append(head);
4166
+ if (list.childNodes.length) card.append(list);
4167
+ card.append(note, actions);
4168
+ paintFilterSuggestion(card, event);
4169
+ return card;
4170
+ }
4171
+
4172
+ function renderFilterAnswer(event) {
4173
+ const filterAi = event.payload.filterAi;
4174
+ const proposal = filterAi.kind === 'change' ? filterAi.proposal : null;
4175
+ const item = renderMessage(event, 'assistant', proposal ? proposal.explanation : payloadText(event));
4176
+ // An answer is just the message; the review card appears only when it suggests ticks.
4177
+ if (proposal && (proposal.changes.length || proposal.mode !== null)) item.append(renderFilterSuggestion(event));
4178
+ return item;
4179
+ }
4180
+
4181
+ function renderFilterQuestion(event) {
4182
+ // The person's own words, like any message; only a wait or a failure adds a line under them.
4183
+ const item = renderMessage(event, 'user', payloadText(event));
4184
+ const requestId = String(event.payload.requestId || '');
4185
+ const pending = state.filterPending.get(requestId);
4186
+ const notice = state.filterNotices.get(requestId);
4187
+ if (pending && !filterAnswered(requestId)) {
4188
+ const live = document.createElement('div'); live.className = 'ai-chat-live-status ai-chat-filter-pending';
4189
+ const label = document.createElement('span'); label.className = 'ai-chat-live-label';
4190
+ label.textContent = pending.retryNote || pending.note || FILTER_PENDING;
4191
+ live.append(animatedDots(), label);
4192
+ item.append(live);
4193
+ } else if (notice && !filterAnswered(requestId)) {
4194
+ const failed = document.createElement('p'); failed.className = 'ai-chat-filter-notice'; failed.setAttribute('role', 'status');
4195
+ failed.textContent = notice;
4196
+ item.append(failed);
4197
+ }
4198
+ return item;
4199
+ }
4200
+
4201
+ /** Re-read the live filter state for every visible suggestion card, in place. */
4202
+ function refreshFilterCards() {
4203
+ for (const card of ui.feed.querySelectorAll('.ai-chat-filter-card')) {
4204
+ const event = state.events.find((candidate) => candidate.eventId === card.dataset.eventId);
4205
+ if (event?.payload?.filterAi?.proposal) paintFilterSuggestion(card, event);
4206
+ }
4207
+ }
4208
+
2508
4209
  async function sendTurn() {
2509
4210
  if (!state.chat || ui.send.disabled) return;
4211
+ // On the Drawing Filter, Send asks about the filter; a filter-intended message is never sent as a
4212
+ // normal turn, not even while the filter page is still loading.
4213
+ const filter = filterSurface();
4214
+ if (filter.state !== 'off') { await sendFilterAi(filter); return; }
4215
+ if (turnIsVisiblyActive() && !state.chat.activeTurn?.local) {
4216
+ const followup = await sendFollowup();
4217
+ if (followup?.outcome !== 'turn-ended') return;
4218
+ // #1616: the response finished while this follow-up was on its way, so the server refused it
4219
+ // before saving anything. Re-read the conversation and, if it is now idle and the composer still
4220
+ // holds exactly that message, send it once as a new turn instead of asking for a second click.
4221
+ if (!(await resendAfterTurnEnded(followup))) return;
4222
+ }
2510
4223
  const snapshot = captureChat();
2511
4224
  if (!snapshot) return;
4225
+ // Bind a carried-over Tekla library first; a refused binding keeps the message unsent.
4226
+ if (!(await bindPendingTeklaRead(snapshot))) return;
2512
4227
  const text = ui.input.value.trim();
2513
4228
  const uiContext = currentFloLessContext();
2514
4229
  const chatId = snapshot.chatId;
@@ -2522,12 +4237,17 @@
2522
4237
  payload: { text, attachmentIds }, createdAt: new Date().toISOString(), optimistic: true,
2523
4238
  };
2524
4239
  clearTimeout(state.draftTimer);
4240
+ state.localDraft = { chatId, text: '' };
4241
+ state.backgroundDrafts.delete(chatId);
2525
4242
  state.pendingSubmissionId = clientSubmissionId;
2526
4243
  state.events.push(optimisticEvent);
2527
- state.chat = { ...previousChat, state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
4244
+ state.chat = { ...previousChat, draft: '', state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
2528
4245
  ui.input.value = ''; autosize(); state.attachments = []; paintAttachments();
2529
4246
  setBusy(true); paintConversation(); announce('Message sent.');
2530
4247
  try {
4248
+ // A debounced save already in flight must finish before the server clears
4249
+ // the draft while admitting this message.
4250
+ await state.draftWrites.get(chatId)?.catch(() => {});
2531
4251
  const result = await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/turns`, {
2532
4252
  method: 'POST', body: JSON.stringify({
2533
4253
  // The server alone appends this context to the provider copy. The submitted text and
@@ -2545,16 +4265,244 @@
2545
4265
  // The server accepts a turn only from a ready provider, so a warning from an earlier check is stale.
2546
4266
  if (!providerReady()) void loadCapability().then(() => { if (sameChat(snapshot)) { paintSettings(); updateSendState(); } });
2547
4267
  } catch (error) {
2548
- if (!sameChat(snapshot)) return;
4268
+ if (!sameChat(snapshot)) {
4269
+ if (initialTurnDefinitelyRefused(error)) await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
4270
+ return;
4271
+ }
2549
4272
  state.pendingSubmissionId = null;
2550
4273
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
2551
4274
  state.chat = previousChat;
2552
4275
  state.attachments = previousAttachments;
2553
- ui.input.value = text; autosize(); paintAttachments(); paintConversation();
4276
+ ui.input.value = text; autosize(); paintAttachments(); saveDraftSoon(); paintConversation();
2554
4277
  report(error, 'Message was not sent');
2555
4278
  } finally { if (sameChat(snapshot)) { setBusy(false); updateSendState(); } }
2556
4279
  }
2557
4280
 
4281
+ /**
4282
+ * A follow-up refused with `chat-turn-stale` was never saved (the route answers `chat-followup-unknown`
4283
+ * for anything it did save), so sending the same text as a new turn cannot duplicate it. Send stays
4284
+ * disabled while the conversation is re-read, and the new turn happens at most once: it goes ahead
4285
+ * only when the refreshed chat is idle and the draft is unchanged: the same text, and the same files,
4286
+ * since the re-read replaces the composer's files with the server's list. It also needs Send to be
4287
+ * usable, which already rules out recovery, an unconfirmed message, an upload and a provider still
4288
+ * being set up. Otherwise the original notice is shown and the draft stays for the user to decide.
4289
+ */
4290
+ async function resendAfterTurnEnded({ snapshot, text, attachmentIds, error }) {
4291
+ state.followupSubmitting = true;
4292
+ updateSendState();
4293
+ try { await refreshConversation(snapshot.chatId); }
4294
+ finally { state.followupSubmitting = false; }
4295
+ if (!sameChat(snapshot)) return false;
4296
+ updateSendState();
4297
+ if (!turnIsVisiblyActive() && !ui.send.disabled
4298
+ && ui.input.value.trim() === text
4299
+ && JSON.stringify(state.attachments.map((item) => item.attachmentId)) === JSON.stringify(attachmentIds)) return true;
4300
+ report(error, '');
4301
+ return false;
4302
+ }
4303
+
4304
+ function followupDefinitelyRefused(error) {
4305
+ // Session rejection and body-size rejection happen before the route can save a row.
4306
+ return ['chat-followup-refused', 'chat-followup-save-failed'].includes(String(error?.code || ''))
4307
+ || sessionNeedsRenewal(error) || error?.status === 413;
4308
+ }
4309
+
4310
+ async function sendFollowup() {
4311
+ if (!state.chat || !turnIsVisiblyActive() || state.followupSubmitting) return;
4312
+ const snapshot = captureChat();
4313
+ if (!snapshot) return;
4314
+ const text = ui.input.value.trim();
4315
+ const attachmentIds = state.attachments.map((item) => item.attachmentId);
4316
+ if (!text && !attachmentIds.length) return;
4317
+ if (new TextEncoder().encode(text).length > 128 * 1024) {
4318
+ report({ code: 'chat-message-too-long' }, 'Message was not sent');
4319
+ return;
4320
+ }
4321
+ const clientSubmissionId = crypto.randomUUID();
4322
+ const previousAttachments = state.attachments;
4323
+ let failedDelivery = null;
4324
+ let outcome = null;
4325
+ const optimisticEvent = {
4326
+ eventId: `local:${clientSubmissionId}`,
4327
+ sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
4328
+ chatId: snapshot.chatId, turnId: state.chat.activeTurn.turnId, clientSubmissionId,
4329
+ providerItemId: null, type: 'user-message',
4330
+ payload: { text, attachmentIds, followup: true, deliveryState: 'pending' },
4331
+ createdAt: new Date().toISOString(), optimistic: true,
4332
+ };
4333
+ clearTimeout(state.draftTimer);
4334
+ state.localDraft = { chatId: snapshot.chatId, text: '' };
4335
+ state.backgroundDrafts.delete(snapshot.chatId);
4336
+ state.followupSubmitting = true;
4337
+ state.chat.draft = '';
4338
+ state.events.push(optimisticEvent);
4339
+ ui.input.value = ''; autosize(); state.attachments = []; paintAttachments();
4340
+ paintEvents({ forceBottom: true }); updateSendState();
4341
+ try {
4342
+ await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
4343
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups`, {
4344
+ method: 'POST', body: JSON.stringify({
4345
+ owner: snapshot.scope.owner, clientSubmissionId, text,
4346
+ uiContext: currentFloLessContext(), attachmentIds,
4347
+ }),
4348
+ });
4349
+ if (!sameChat(snapshot)) return;
4350
+ state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
4351
+ for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
4352
+ state.events.sort((a, b) => a.sequence - b.sequence);
4353
+ state.chat = result.chat;
4354
+ announce(result.followup?.deliveryState === 'queued-next'
4355
+ ? 'Message queued for the next AI response.'
4356
+ : result.followup?.deliveryState === 'accepted'
4357
+ ? 'Follow-up sent to AI.'
4358
+ : result.followup?.deliveryState === 'not-sent'
4359
+ ? (result.followup?.deliveryFailure?.reason || 'FloLess could not finish saving this message. Use Retry sending if you still want to send it.')
4360
+ : 'Follow-up saved. Waiting for AI.');
4361
+ paintConversation();
4362
+ } catch (error) {
4363
+ if (!sameChat(snapshot)) {
4364
+ if (followupDefinitelyRefused(error)) await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
4365
+ else {
4366
+ optimisticEvent.payload.deliveryState = 'unknown';
4367
+ state.unknownFollowups.set(snapshot.chatId, { submissionId: clientSubmissionId, text, event: optimisticEvent });
4368
+ // The user may have selected A → B → A while this request was in flight.
4369
+ // The second A snapshot ran before the uncertain result existed, so reconcile it now.
4370
+ if (sameScope(snapshot.scope, snapshot.generation) && state.chat?.chatId === snapshot.chatId) {
4371
+ reconcileUnknownFollowupOnSelection(state.chat);
4372
+ paintEvents(); updateSendState();
4373
+ }
4374
+ }
4375
+ return;
4376
+ }
4377
+ if (state.events.some((event) => !event.optimistic && event.clientSubmissionId === clientSubmissionId
4378
+ && event.type === 'user-message')) {
4379
+ state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
4380
+ announce('Follow-up saved. Waiting for AI.'); paintEvents();
4381
+ return;
4382
+ }
4383
+ const definitiveRefusal = followupDefinitelyRefused(error);
4384
+ // A lost HTTP reply does not prove the provider missed the message. Keep the submission
4385
+ // visible and block another send until the saved receipt or a deliberate user action resolves it.
4386
+ if (definitiveRefusal) state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
4387
+ else {
4388
+ optimisticEvent.payload.deliveryState = 'unknown';
4389
+ state.followupUnknownId = clientSubmissionId;
4390
+ state.unknownFollowups.set(snapshot.chatId, { submissionId: clientSubmissionId, text, event: optimisticEvent });
4391
+ }
4392
+ // An uncertain request may already own these files. Keep them on its
4393
+ // message, and restore chips only when the server definitely refused it.
4394
+ state.attachments = definitiveRefusal ? previousAttachments : [];
4395
+ ui.input.value = text; autosize(); paintAttachments(); paintEvents();
4396
+ if (definitiveRefusal) saveDraftSoon();
4397
+ else state.localDraft = { chatId: snapshot.chatId, text };
4398
+ // The response ended before this arrived (#1616). sendTurn resends it as a new turn, and
4399
+ // shows this refusal only if it cannot.
4400
+ if (definitiveRefusal && error?.code === 'chat-followup-refused' && error?.reason === 'chat-turn-stale') {
4401
+ outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, error };
4402
+ } else failedDelivery = { error, prefix: definitiveRefusal ? '' : 'Could not confirm the follow-up' };
4403
+ } finally {
4404
+ state.followupSubmitting = false;
4405
+ if (sameChat(snapshot)) {
4406
+ updateSendState();
4407
+ if (failedDelivery) report(failedDelivery.error, failedDelivery.prefix);
4408
+ if (document.activeElement === document.body || document.activeElement === ui.send) ui.input.focus();
4409
+ }
4410
+ }
4411
+ return outcome;
4412
+ }
4413
+
4414
+ async function resolveUnknownFollowup(clientSubmissionId) {
4415
+ if (!state.chat || !clientSubmissionId) return;
4416
+ if (state.resolvingFollowupIds.has(clientSubmissionId)) return;
4417
+ const optimistic = state.events.find((event) => event.optimistic && event.clientSubmissionId === clientSubmissionId);
4418
+ if (optimistic) {
4419
+ optimistic.payload.deliveryState = 'dismissed';
4420
+ state.followupUnknownId = null;
4421
+ state.unknownFollowups.delete(state.chat.chatId);
4422
+ announce('Delivery is still unconfirmed. Review the draft before sending; sending it again may duplicate a message AI received.'
4423
+ + (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.' : ''));
4424
+ paintEvents(); updateSendState();
4425
+ if (!ui.input.disabled) ui.input.focus();
4426
+ return;
4427
+ }
4428
+ const snapshot = captureChat();
4429
+ if (!snapshot) return;
4430
+ state.resolvingFollowupIds.add(clientSubmissionId);
4431
+ const button = [...ui.feed.querySelectorAll('.ai-chat-followup-resolve')]
4432
+ .find((candidate) => candidate.closest('[data-event-id]')?.dataset.eventId
4433
+ === state.events.find((event) => event.clientSubmissionId === clientSubmissionId && event.type === 'user-message')?.eventId);
4434
+ const focusAfterSuccess = document.activeElement === button;
4435
+ let resolved = false;
4436
+ if (button) button.disabled = true;
4437
+ try {
4438
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups/${encodeURIComponent(clientSubmissionId)}/resolve`, {
4439
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, resolution: 'continue-without-resending' }),
4440
+ });
4441
+ if (!sameChat(snapshot)) return;
4442
+ state.followupUnknownId = null;
4443
+ state.chat = result.chat;
4444
+ for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
4445
+ state.events.sort((a, b) => a.sequence - b.sequence);
4446
+ announce(result.followup?.deliveryState === 'accepted'
4447
+ ? 'AI had received this follow-up. You can continue.'
4448
+ : 'Delivery remains unconfirmed. FloLess will not resend this follow-up. You can continue.');
4449
+ paintConversation();
4450
+ resolved = true;
4451
+ } catch (error) {
4452
+ if (sameChat(snapshot)) { if (button) button.disabled = false; report(error, 'Could not continue without resending'); }
4453
+ } finally {
4454
+ state.resolvingFollowupIds.delete(clientSubmissionId);
4455
+ if (sameChat(snapshot)) {
4456
+ paintEvents();
4457
+ if (resolved && focusAfterSuccess && document.activeElement === document.body && !ui.input.disabled) ui.input.focus();
4458
+ }
4459
+ }
4460
+ }
4461
+
4462
+ async function retryNotSentFollowup(clientSubmissionId) {
4463
+ if (!state.chat || !clientSubmissionId || state.retryingFollowupIds.has(clientSubmissionId)) return;
4464
+ const snapshot = captureChat();
4465
+ if (!snapshot) return;
4466
+ const commandId = `shell.chat-followup-retry#${clientSubmissionId}`;
4467
+ const restoreFocusOnFailure = document.activeElement?.dataset?.commandId === commandId;
4468
+ let failed = false;
4469
+ let succeeded = false;
4470
+ state.retryingFollowupIds.add(clientSubmissionId);
4471
+ paintEvents();
4472
+ announce('Retrying this message. Your draft stays here.');
4473
+ try {
4474
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups/${encodeURIComponent(clientSubmissionId)}/retry`, {
4475
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner }),
4476
+ });
4477
+ if (!sameChat(snapshot)) return;
4478
+ state.chat = result.chat;
4479
+ for (const event of result.events || []) if (!state.events.some(item => item.eventId === event.eventId)) state.events.push(event);
4480
+ state.events.sort((a, b) => a.sequence - b.sequence);
4481
+ announce(result.followup?.deliveryState === 'accepted' ? 'Retry sent to AI.'
4482
+ : result.followup?.deliveryState === 'not-sent'
4483
+ ? (result.followup?.deliveryFailure?.reason || 'FloLess could not start this retry. Check the conversation, then use Retry sending if you still want to send it.')
4484
+ : 'Retry queued for AI. Your draft is unchanged.');
4485
+ paintConversation();
4486
+ succeeded = true;
4487
+ } catch (error) {
4488
+ failed = true;
4489
+ if (sameChat(snapshot)) report(error,
4490
+ followupDefinitelyRefused(error)
4491
+ || ['chat-followup-queued', 'chat-followup-retry-wait', 'chat-followup-retry-unavailable', 'chat-attachment-scope'].includes(String(error?.code || ''))
4492
+ ? '' : 'Could not confirm the retry. Check the conversation before retrying again');
4493
+ } finally {
4494
+ state.retryingFollowupIds.delete(clientSubmissionId);
4495
+ if (sameChat(snapshot)) {
4496
+ paintEvents();
4497
+ if (failed && restoreFocusOnFailure) {
4498
+ [...ui.feed.querySelectorAll('.ai-chat-followup-resolve')]
4499
+ .find(button => button.dataset.commandId === commandId)?.focus();
4500
+ }
4501
+ if (succeeded && restoreFocusOnFailure && document.activeElement === document.body && !ui.input.disabled) ui.input.focus();
4502
+ }
4503
+ }
4504
+ }
4505
+
2558
4506
  async function stopTurn() {
2559
4507
  if (!state.chat?.activeTurn) return;
2560
4508
  const snapshot = captureChat();
@@ -2597,6 +4545,7 @@
2597
4545
  const chatId = snapshot.chatId;
2598
4546
  ui.refresh.disabled = true;
2599
4547
  announce('Refreshing this chat session…');
4548
+ let failure = null;
2600
4549
  try {
2601
4550
  // Re-read before stopping: the browser can retain an old activeTurn after a server restart.
2602
4551
  // That avoids sending a redundant stop for a response the durable conversation already completed.
@@ -2613,8 +4562,10 @@
2613
4562
  await selectConversation(chatId, { focus: false });
2614
4563
  if (!sameChat(snapshot)) return;
2615
4564
  announce('Chat session refreshed.');
2616
- } catch (error) { if (sameChat(snapshot)) report(error, 'Could not refresh this chat session'); }
4565
+ } catch (error) { failure = error; }
2617
4566
  finally { if (sameChat(snapshot)) { ui.refresh.disabled = false; updateSendState(); } }
4567
+ // After updateSendState, which rewrites the composer hint and used to erase this sentence (#1604).
4568
+ if (failure && sameChat(snapshot)) report(failure, 'Could not refresh this chat session');
2618
4569
  }
2619
4570
 
2620
4571
  async function endRecovery() {
@@ -2751,16 +4702,27 @@
2751
4702
  }
2752
4703
 
2753
4704
  async function attachFiles(files) {
2754
- if (!state.chat || state.chat.activeTurn) return;
4705
+ if (!state.chat || state.chat.activeTurn?.local || state.chat.state === 'recovery' || state.followupSubmitting || state.followupUnknownId || hasUnknownFollowup()) return;
2755
4706
  const snapshot = captureChat();
2756
4707
  if (!snapshot) return;
2757
4708
  if (state.uploadingChatIds.has(snapshot.chatId)) return;
2758
4709
  const incoming = [...files];
4710
+ // Reset the native chooser even when validation rejects this batch. After the user removes
4711
+ // an image, selecting that same file again must fire a fresh change event.
4712
+ ui.file.value = '';
4713
+ if (incoming.some((file) => !allowedTypes.has(file.type))) { report(new Error('Attach a PNG, JPEG, WebP, or PDF')); return; }
4714
+ const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length
4715
+ + incoming.filter((file) => file.type.startsWith('image/')).length;
4716
+ if (imageCount > MAX_IMAGES_PER_MESSAGE) {
4717
+ state.imageLimitChatId = snapshot.chatId;
4718
+ report({ code: 'chat-message-image-limit' });
4719
+ return;
4720
+ }
4721
+ state.imageLimitChatId = null;
2759
4722
  const known = [...new Map([...(state.chat.attachments || []), ...state.attachments]
2760
4723
  .map((attachment) => [attachment.attachmentId, attachment])).values()];
2761
4724
  const existingBytes = known.reduce((sum, item) => sum + (item.bytes || 0), 0);
2762
4725
  if (known.length + incoming.length > 10) { report(new Error('You can attach up to 10 files to this conversation.')); return; }
2763
- if (incoming.some((file) => !allowedTypes.has(file.type))) { report(new Error('Attach a PNG, JPEG, WebP, or PDF')); return; }
2764
4726
  if (incoming.some((file) => file.size > 20 * MB)) { report(new Error('Each attachment must be 20 MB or smaller')); return; }
2765
4727
  if (existingBytes + incoming.reduce((sum, file) => sum + file.size, 0) > 50 * MB) { report(new Error('Attachments must stay within 50 MB per conversation')); return; }
2766
4728
  state.uploadingChatIds.add(snapshot.chatId);
@@ -2789,6 +4751,15 @@
2789
4751
  }
2790
4752
  }
2791
4753
 
4754
+ // The background tick. It skips while the previous list is still loading, never stacking one behind
4755
+ // it (#1604): stacked polls hold the browser's few connections to FloLess, and the conversation
4756
+ // itself then cannot load.
4757
+ async function pollChatsTick() {
4758
+ if (state.chatPollInFlight) return;
4759
+ state.chatPollInFlight = true;
4760
+ try { await pollChats(); } finally { state.chatPollInFlight = false; }
4761
+ }
4762
+
2792
4763
  async function pollChats() {
2793
4764
  if (!state.scope || document.hidden) return;
2794
4765
  const scope = state.scope;
@@ -2811,6 +4782,7 @@
2811
4782
  }
2812
4783
  if (!sameScope(scope, generation)) return;
2813
4784
  state.chats = result.chats || [];
4785
+ state.unreadableChats = result.unreadableChats || [];
2814
4786
  const active = state.chats.find((item) => item.chatId === state.chat?.chatId);
2815
4787
  if (active && state.chat) {
2816
4788
  // An event-stream completion can win the race against this list request. Never let a
@@ -2826,7 +4798,7 @@
2826
4798
  // Polling can clear activeTurn after the feed was painted by SSE. Repaint the feed
2827
4799
  // so a completed turn removes any stale live activity indicator. With no conversation
2828
4800
  // selected the feed is the Claude/Codex chooser, which a repaint would erase.
2829
- paintHistory(); paintUnread();
4801
+ paintHistory(); paintUnread(); paintUnreadableNotice();
2830
4802
  // A sign-in OR a sign-OUT made from Integrations or from the user's own terminal changes who
2831
4803
  // answers, and nothing else re-reads it — the row would keep naming the old account for the
2832
4804
  // whole conversation. Use the cheap runtimes read (no provider launch, 10 s server cache)
@@ -2861,11 +4833,37 @@
2861
4833
  }
2862
4834
  if (!sameScope(scope, generation)) return;
2863
4835
  }
4836
+ await recheckManagedCopy(scope, generation);
4837
+ if (!sameScope(scope, generation)) return;
2864
4838
  if (state.chat) { paintSettings(); paintRecovery(); paintApproval(); paintEvents(); updateSendState(); }
2865
4839
  if (state.historyOpen && state.historyFilter === 'instructor-answers') refreshInstructorAnswers();
2866
4840
  } catch { /* SSE or the next poll will recover */ }
2867
4841
  }
2868
4842
 
4843
+ // #1657: FloLess's own copy of this conversation's AI can be moved away, or start re-installing, while
4844
+ // the conversation is open — and nothing else re-reads the capability, so the chat kept an enabled
4845
+ // Send and no setup card. The managed-runtimes read is cheap (no CLI launch). Only when this AI's copy
4846
+ // CHANGES into a state that is not installed is the capability re-read; the server re-checks that copy
4847
+ // on every read, so the answer carries the setup status the card is painted from. Once the card is up,
4848
+ // its own runtime poll takes over (and re-reads the capability when setup finishes).
4849
+ async function recheckManagedCopy(scope, generation) {
4850
+ const chat = state.chat;
4851
+ if (!chat || !state.capability || state.capability.runtime) return;
4852
+ let body;
4853
+ try { body = await request('/api/managed-runtimes', { timeoutMs: 10000 }); } catch { return; }
4854
+ if (!sameScope(scope, generation) || state.chat?.chatId !== chat.chatId) return;
4855
+ const row = (body?.runtimes || []).find((entry) => entry?.runtime === chat.provider);
4856
+ if (!row) return;
4857
+ const seen = `${chat.chatId}:${row.state}`;
4858
+ if (row.state === 'installed' || row.state === 'unsupported-platform') { state.managedCopySeen = seen; return; }
4859
+ if (state.managedCopySeen === seen) return;
4860
+ await loadCapability();
4861
+ if (!sameScope(scope, generation) || state.chat?.chatId !== chat.chatId) return;
4862
+ // Only an answer the server gave settles this state: a failed read is tried again on the next tick.
4863
+ if (!state.capability?.readFailed) state.managedCopySeen = seen;
4864
+ paintRuntime();
4865
+ }
4866
+
2869
4867
  function refreshActivity() {
2870
4868
  paintConversation();
2871
4869
  }
@@ -2887,6 +4885,8 @@
2887
4885
  paintHistory(); paintUnread();
2888
4886
  }
2889
4887
 
4888
+ // Longer than the server's capability-check bound (CAPABILITY_PROBE_TIMEOUT_MS, 12 s) plus its locks.
4889
+ const REQUEST_START_TIMEOUT_MS = 30000;
2890
4890
  async function startRequest(requestId, provider, mode = 'start') {
2891
4891
  if (!state.scope?.owner) throw new Error('Open the Request’s project or workflow before starting its chat.');
2892
4892
  if (provider !== 'claude' && provider !== 'codex') throw new Error('Choose Claude or Codex for this chat.');
@@ -2898,8 +4898,12 @@
2898
4898
  }
2899
4899
  const currentChatId = state.chat && state.chat.provider === provider && !state.chat.activeTurn
2900
4900
  && !state.chat.archivedAt && state.chat.state !== 'recovery' ? state.chat.chatId : undefined;
4901
+ // Starting a Request waits for the AI's capability check (up to 12 s on the server, longer when
4902
+ // it first launches a copy FloLess has only just set up), so a shorter wait here reported
4903
+ // "Couldn't start" for a start that went on to succeed (#1607 QA). The Requests list says
4904
+ // "Still opening…" after 4 s, so the longer wait is not a silent one.
2901
4905
  const result = await request(`/api/chat/requests/${encodeURIComponent(requestId)}/start`, {
2902
- method: 'POST', timeoutMs: 10000,
4906
+ method: 'POST', timeoutMs: REQUEST_START_TIMEOUT_MS,
2903
4907
  body: JSON.stringify({ provider, mode, chatId: currentChatId, expectedOwner: scope.owner }),
2904
4908
  });
2905
4909
  if (!sameScope(scope, generation)) {
@@ -2931,6 +4935,238 @@
2931
4935
  await selectConversation(chatId, { focus: true, replaceProviderChoice: true });
2932
4936
  }
2933
4937
 
4938
+ const TEKLA_OPERATION = 'Tekla.Structures.Model.Model.GetInfo().ModelName';
4939
+
4940
+ function teklaDraftForChat(chat = state.chat) {
4941
+ const draft = state.teklaDraft;
4942
+ return draft && chat && draft.chatId === chat.chatId ? draft : null;
4943
+ }
4944
+
4945
+ function teklaBindingFrozen(chat) {
4946
+ return Boolean(chat?.nativeSessionId || chat?.activeTurn || chat?.archivedAt);
4947
+ }
4948
+
4949
+ // The chip states what the binding permits — never that anything is verified. The live check
4950
+ // happens on each approved read, and its own receipt card says whether it verified.
4951
+ function paintTeklaChip() {
4952
+ const node = ui.teklaChip;
4953
+ if (!node) return;
4954
+ const chat = state.chat;
4955
+ const draft = teklaDraftForChat(chat);
4956
+ const bound = chat?.teklaModelRead || null;
4957
+ const library = draft?.library || bound;
4958
+ if (!chat || !library) {
4959
+ if (!node.hidden || node.childElementCount) { node.replaceChildren(); node.hidden = true; delete node.dataset.key; }
4960
+ return;
4961
+ }
4962
+ const status = draft ? draft.status : 'bound';
4963
+ const frozen = !draft && teklaBindingFrozen(chat);
4964
+ const error = draft?.error || (state.teklaRemoveError?.chatId === chat.chatId ? state.teklaRemoveError.message : null);
4965
+ const reads = teklaReadsCopy(library.operations);
4966
+ const key = [chat.chatId, library.sourcePath, library.hostVersion, reads, status, frozen, error || ''].join('|');
4967
+ // Keep the same Remove button across polls so keyboard focus survives a repaint.
4968
+ if (node.dataset.key === key && !node.hidden) return;
4969
+ node.dataset.key = key;
4970
+ node.replaceChildren();
4971
+ node.hidden = false;
4972
+ node.dataset.state = error ? 'error' : status;
4973
+ const chip = document.createElement('div'); chip.className = 'ai-chat-tekla-chip';
4974
+ const copy = document.createElement('span'); copy.className = 'ai-chat-tekla-chip-copy';
4975
+ copy.id = `chat-tekla-context-copy-${chat.chatId}`;
4976
+ const lead = document.createElement('strong'); lead.textContent = `Tekla ${library.hostVersion} model library`;
4977
+ copy.append(lead, document.createTextNode(` · Chat may ask to read ${reads} — FloLess asks you first and checks live each time`));
4978
+ if (status === 'bound') {
4979
+ const suffix = document.createElement('span'); suffix.className = 'ai-chat-tekla-chip-state';
4980
+ suffix.textContent = ' · added to this chat';
4981
+ copy.append(suffix);
4982
+ } else if (status === 'binding') {
4983
+ const suffix = document.createElement('span'); suffix.className = 'ai-chat-tekla-chip-state';
4984
+ suffix.textContent = ' · adding…';
4985
+ copy.append(suffix);
4986
+ }
4987
+ chip.dataset.tip = library.sourcePath;
4988
+ chip.append(copy);
4989
+ if (!frozen) {
4990
+ const remove = button(status === 'removing' ? 'Removing…' : 'Remove', 'shell.chat-tekla-remove', 'ai-chat-tekla-remove');
4991
+ remove.setAttribute('aria-label', `Remove Tekla ${library.hostVersion} model library from this chat`);
4992
+ remove.setAttribute('aria-describedby', copy.id);
4993
+ const busy = status === 'binding' || status === 'removing';
4994
+ remove.disabled = busy;
4995
+ remove.setAttribute('aria-busy', String(busy));
4996
+ 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.';
4997
+ remove.addEventListener('click', () => { void removeTeklaChip(); });
4998
+ chip.append(remove);
4999
+ }
5000
+ node.append(chip);
5001
+ if (error) {
5002
+ const reason = document.createElement('p'); reason.className = 'ai-chat-tekla-error';
5003
+ reason.setAttribute('role', 'alert');
5004
+ reason.textContent = error;
5005
+ node.append(reason);
5006
+ }
5007
+ }
5008
+
5009
+ async function removeTeklaChip() {
5010
+ const chat = state.chat;
5011
+ if (!chat) return;
5012
+ state.teklaRemoveError = null;
5013
+ const draft = teklaDraftForChat(chat);
5014
+ if (draft && draft.status !== 'binding') {
5015
+ // Not bound yet: forgetting it is purely local. Nothing is sent and no route is called.
5016
+ state.teklaDraft = null;
5017
+ paintTeklaChip(); ui.input.focus(); announce('Tekla model library removed from this draft.');
5018
+ return;
5019
+ }
5020
+ if (!chat.teklaModelRead || teklaBindingFrozen(chat)) { paintTeklaChip(); return; }
5021
+ const snapshot = captureChat();
5022
+ if (!snapshot) return;
5023
+ state.teklaDraft = { chatId: chat.chatId, library: chat.teklaModelRead, status: 'removing', error: null };
5024
+ paintTeklaChip();
5025
+ try {
5026
+ const updated = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/tekla-model-read`, {
5027
+ method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, library: null }),
5028
+ });
5029
+ if (!sameChat(snapshot)) return;
5030
+ state.teklaDraft = null;
5031
+ // Only the server's own chat record, with no library left, may say it is gone; anything else is a failure.
5032
+ if (!updated || updated.chatId !== snapshot.chatId || updated.teklaModelRead != null) {
5033
+ state.teklaRemoveError = { chatId: snapshot.chatId, message: 'FloLess could not confirm the library was removed. Try again.' };
5034
+ paintTeklaChip();
5035
+ return;
5036
+ }
5037
+ state.chat = { ...state.chat, ...updated };
5038
+ paintTeklaChip(); ui.input.focus(); announce('Tekla model library removed from this chat.');
5039
+ } catch (error) {
5040
+ if (!sameChat(snapshot)) return;
5041
+ state.teklaDraft = null;
5042
+ state.teklaRemoveError = { chatId: snapshot.chatId, message: errorMessage(error) };
5043
+ paintTeklaChip();
5044
+ }
5045
+ }
5046
+
5047
+ // The reads a library binding permits, as the chip names them. A binding stored before the
5048
+ // selection read existed has no list and permits the model name only.
5049
+ // The closed list the server accepts, in its canonical order: [model name, selection].
5050
+ function teklaChatReads() {
5051
+ return ['Tekla.Structures.Model.Model.GetInfo().ModelName', 'Tekla.Structures.Model.UI.ModelObjectSelector.GetSelectedObjects()'];
5052
+ }
5053
+ function teklaReadsCopy(operations) {
5054
+ const [modelRead, selectionRead] = teklaChatReads();
5055
+ const list = Array.isArray(operations) ? operations : [modelRead];
5056
+ const names = [];
5057
+ if (list.includes(modelRead)) names.push('the open model name');
5058
+ if (list.includes(selectionRead)) names.push('the parts you have selected');
5059
+ return names.join(' or ');
5060
+ }
5061
+ function sameTeklaReads(a, b) {
5062
+ const [modelRead] = teklaChatReads();
5063
+ const left = Array.isArray(a) ? a : [modelRead];
5064
+ const right = Array.isArray(b) ? b : [modelRead];
5065
+ return left.length === right.length && left.every((operation) => right.includes(operation));
5066
+ }
5067
+
5068
+ // Returns true when the message may be sent: nothing pending, or the binding was stored.
5069
+ async function bindPendingTeklaRead(snapshot) {
5070
+ const draft = teklaDraftForChat();
5071
+ if (draft && (draft.status === 'binding' || draft.status === 'removing')) {
5072
+ announce('Wait for the Tekla library change to finish, then send.');
5073
+ return false;
5074
+ }
5075
+ if (!draft || draft.status !== 'draft') return !draft || draft.status === 'bound';
5076
+ const bound = state.chat?.teklaModelRead;
5077
+ if (bound && bound.sourcePath === draft.library.sourcePath && bound.hostVersion === draft.library.hostVersion
5078
+ && sameTeklaReads(bound.operations, draft.library.operations)) {
5079
+ state.teklaDraft = null; paintTeklaChip(); return true;
5080
+ }
5081
+ draft.status = 'binding'; draft.error = null;
5082
+ paintTeklaChip(); setBusy(true);
5083
+ try {
5084
+ const updated = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/tekla-model-read`, {
5085
+ method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, library: draft.library }),
5086
+ });
5087
+ if (!sameChat(snapshot)) return false;
5088
+ // Never invent the binding locally: only the server's own record of THIS library for this chat counts.
5089
+ const stored = updated && updated.chatId === snapshot.chatId ? updated.teklaModelRead : null;
5090
+ if (!stored || stored.sourcePath !== draft.library.sourcePath || stored.hostVersion !== draft.library.hostVersion
5091
+ || !sameTeklaReads(stored.operations, draft.library.operations)) {
5092
+ draft.status = 'draft';
5093
+ draft.error = 'Message not sent. FloLess could not confirm the Tekla library was added to this chat. Try again.';
5094
+ paintTeklaChip();
5095
+ return false;
5096
+ }
5097
+ if (state.teklaDraft === draft) state.teklaDraft = null;
5098
+ state.teklaRemoveError = null;
5099
+ state.chat = { ...state.chat, ...updated };
5100
+ paintTeklaChip();
5101
+ return true;
5102
+ } catch (error) {
5103
+ if (!sameChat(snapshot)) return false;
5104
+ draft.status = 'draft';
5105
+ draft.error = `Message not sent. ${errorMessage(error)}`;
5106
+ paintTeklaChip();
5107
+ return false;
5108
+ } finally { if (sameChat(snapshot)) setBusy(false); }
5109
+ }
5110
+
5111
+ function teklaDraftText(receipt) {
5112
+ const when = typeof receipt.verifiedAt === 'string' ? new Date(receipt.verifiedAt) : null;
5113
+ // The same readable form the transcript's receipt card uses, not a raw ISO timestamp.
5114
+ const checked = when && !Number.isNaN(when.getTime())
5115
+ ? `, checked ${when.toLocaleString([], { dateStyle: 'medium', timeStyle: 'medium' })}` : '';
5116
+ // The earlier model name is deliberately left out: the open model may have changed since, and
5117
+ // the AI would repeat a stale name as current. A fresh read shows the name at that moment.
5118
+ return `Earlier FloLess check: reading the open model name through the Tekla model library at ${receipt.sourcePath} `
5119
+ + `worked (Tekla ${receipt.hostVersion}${checked}). The generated agent's commands remain unverified. `
5120
+ + 'You can ask to read the open model name or the parts I have selected in Tekla. Help me use these reads in this project.';
5121
+ }
5122
+
5123
+ // Leave the selected conversation for the Claude/Codex choice. A prior async select can still be
5124
+ // waiting for capability discovery, and the poll repaints whatever `state.chat` holds: invalidate
5125
+ // the one and clear the other, or the old conversation is painted back over the chooser.
5126
+ function beginProviderChoice() {
5127
+ state.selectionGeneration += 1;
5128
+ state.choosingProvider = true;
5129
+ closeSource(); clearLiveStream(true);
5130
+ state.chat = null; state.events = []; state.attachments = []; state.integrations = null; state.capability = null;
5131
+ updateOffscreenActivity();
5132
+ // The left chat's library chip ("added to this chat") must not linger over the chooser.
5133
+ paintTeklaChip();
5134
+ }
5135
+
5136
+ // Graft receipt → unsent Chat draft. Opening performs no binding, sends nothing and never
5137
+ // touches Tekla: the binding is stored only when the user presses Send.
5138
+ async function openVerifiedTeklaDraft(receipt) {
5139
+ // `plainEnglish` marks errors written for the user, so the Graft dialog can show them as-is.
5140
+ if (!receipt || typeof receipt.sourcePath !== 'string' || !receipt.sourcePath
5141
+ || typeof receipt.hostVersion !== 'string' || !receipt.hostVersion) {
5142
+ 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 });
5143
+ }
5144
+ // The chip lists exactly these reads, and Send binds exactly these: nothing defaults to more.
5145
+ const library = { sourcePath: receipt.sourcePath, hostVersion: receipt.hostVersion, operations: teklaChatReads() };
5146
+ const draft = teklaDraftText(receipt);
5147
+ await refreshScope();
5148
+ if (!state.scope?.owner) throw Object.assign(new Error('Open a project or workflow before continuing in AI Chat.'), { plainEnglish: true });
5149
+ window.flolessBridge?.revealAiChat?.();
5150
+ ui.tab.click();
5151
+ const chat = state.chat;
5152
+ // The binding is frozen once a provider session exists, so only a chat that has never
5153
+ // started a provider session, and is not busy, can take it. Otherwise start a new chat.
5154
+ if (!chat || chat.nativeSessionId || chat.activeTurn || chat.archivedAt || chat.state === 'recovery') {
5155
+ state.discoveryDraft = draft;
5156
+ state.pendingTeklaLibrary = library;
5157
+ beginProviderChoice();
5158
+ providerChooser(); clearReport();
5159
+ return;
5160
+ }
5161
+ state.teklaRemoveError = null;
5162
+ state.teklaDraft = { chatId: chat.chatId, library, status: 'draft', error: null };
5163
+ const existing = ui.input.value.trim();
5164
+ ui.input.value = existing ? `${existing}\n\n${draft}` : draft;
5165
+ ui.input.dispatchEvent(new Event('input', { bubbles: true }));
5166
+ paintTeklaChip();
5167
+ ui.input.focus();
5168
+ }
5169
+
2934
5170
  async function openDraft(draft) {
2935
5171
  if (typeof draft !== 'string' || !draft.trim()) return;
2936
5172
  await refreshScope();
@@ -2939,8 +5175,8 @@
2939
5175
  ui.tab.click();
2940
5176
  if (!state.chat || state.chat.activeTurn || state.chat.archivedAt || state.chat.state === 'recovery') {
2941
5177
  state.discoveryDraft = draft;
2942
- state.choosingProvider = true;
2943
- providerChooser();
5178
+ beginProviderChoice();
5179
+ providerChooser(); clearReport();
2944
5180
  return;
2945
5181
  }
2946
5182
  const existing = ui.input.value.trim();
@@ -2964,17 +5200,16 @@
2964
5200
  }
2965
5201
 
2966
5202
  ui.historyToggle.addEventListener('click', () => toggleHistory());
5203
+ ui.feed.addEventListener('scroll', updateOffscreenActivity, { passive: true });
5204
+ const activityResizeObserver = new ResizeObserver(updateOffscreenActivity);
5205
+ activityResizeObserver.observe(ui.feed);
2967
5206
  ui.refresh.addEventListener('click', refreshChatSession);
2968
- ui.history.addEventListener('keydown', (event) => {
5207
+ function closeHistoryOnEscape(event) {
2969
5208
  if (event.key === 'Escape') { event.preventDefault(); toggleHistory(false, { focusToggle: true }); }
2970
- });
5209
+ }
5210
+ ui.history.addEventListener('keydown', closeHistoryOnEscape);
2971
5211
  ui.newChat.addEventListener('click', () => {
2972
- // A prior async select can still be waiting for capability discovery. Invalidate it before
2973
- // showing the provider choice, otherwise it can put the old conversation back over this view.
2974
- state.selectionGeneration += 1;
2975
- state.choosingProvider = true;
2976
- closeSource(); clearLiveStream(true);
2977
- state.chat = null; state.events = []; state.attachments = []; state.integrations = null; state.capability = null;
5212
+ beginProviderChoice();
2978
5213
  toggleHistory(false); setBusy(false); providerChooser(); clearReport();
2979
5214
  });
2980
5215
  ui.rename.addEventListener('click', beginRename);
@@ -2986,7 +5221,8 @@
2986
5221
  ui.title.addEventListener('blur', () => finishRename(ui.title.textContent?.trim() !== ''));
2987
5222
  ui.settingsToggle.addEventListener('click', () => {
2988
5223
  const open = ui.settings.hidden;
2989
- if (open) toggleHistory(false);
5224
+ // Switching from History to Settings: the composer is about to be hidden, so focus stays here.
5225
+ if (open) toggleHistory(false, { keepFocus: true });
2990
5226
  ui.settings.hidden = !open;
2991
5227
  ui.settingsToggle.setAttribute('aria-expanded', String(open));
2992
5228
  closePicker();
@@ -2997,6 +5233,12 @@
2997
5233
  ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
2998
5234
  ui.integrations.addEventListener('click', openIntegrations);
2999
5235
  ui.send.addEventListener('click', sendTurn);
5236
+ // The Drawing Filter page reports every change that can alter what the chat shows about it.
5237
+ window.addEventListener('floless:filter-ai-changed', () => {
5238
+ state.filterCardMessages.clear();
5239
+ paintFloLessContext(); refreshFilterCards(); updateSendState();
5240
+ });
5241
+ document.getElementById('ws-frame-drawings')?.addEventListener('load', () => { paintFloLessContext(); refreshFilterCards(); updateSendState(); });
3000
5242
  ui.stop.addEventListener('click', stopTurn);
3001
5243
  ui.recoveryStop.addEventListener('click', () => { void (state.recoveryCanEnd ? endRecovery() : stopTurn()); });
3002
5244
  ui.reconcile.addEventListener('click', reconcile);
@@ -3014,7 +5256,7 @@
3014
5256
  if (files.length) { event.preventDefault(); attachFiles(files); }
3015
5257
  });
3016
5258
  ui.tab.addEventListener('click', () => markRead());
3017
- document.addEventListener('visibilitychange', () => { if (!document.hidden) { markRead(); pollChats(); } });
5259
+ document.addEventListener('visibilitychange', () => { if (!document.hidden) { markRead(); void pollChatsTick(); } });
3018
5260
  document.addEventListener('pointerdown', (event) => {
3019
5261
  // Switch account lives inside the Provider .ai-chat-setting but opens no picker of its own, so
3020
5262
  // it must not be treated as "clicked the picker's own control" and leave an open list behind.
@@ -3035,12 +5277,18 @@
3035
5277
  if (node) contextObserver.observe(node, { attributes: true, childList: id === 'ws-step-tabs', subtree: id === 'ws-step-tabs' });
3036
5278
  }
3037
5279
 
3038
- state.refreshTimer = setInterval(pollChats, 5000);
3039
- window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
5280
+ state.refreshTimer = setInterval(pollChatsTick, 5000);
5281
+ window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); activityResizeObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
3040
5282
  window.flolessChat = {
3041
- refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openDraft,
5283
+ refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openDraft, openVerifiedTeklaDraft,
3042
5284
  startProjectIntake, resumeProjectIntake,
3043
5285
  currentProvider: () => state.chat?.provider ?? null,
5286
+ // The New project dialog's AI choice (#1605) words each provider's sign-in the way this
5287
+ // panel's own chooser does, so the two ways into a conversation read the same.
5288
+ providerAccountLabel,
5289
+ // The setup card's own sentences, so a start that sets FloLess's copy up first (#1607) says
5290
+ // exactly what this panel would.
5291
+ runtimeNotice,
3044
5292
  };
3045
5293
  window.dispatchEvent(new CustomEvent('floless:chat-ready'));
3046
5294
  paintFloLessContext();