@floless/app 0.141.0 → 0.142.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/web/chat.js CHANGED
@@ -25,11 +25,11 @@
25
25
  const state = {
26
26
  // signInPending is keyed by provider: a wait started in one conversation must not paint an
27
27
  // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
28
- sessionReady: false, scope: null, chats: [], archivedChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
29
- source: null, eventReconnectTimer: null, eventReconnectAttempt: 0, eventReconnectChatId: null, attachments: [], imageLimitChatId: null, followupSubmitting: false, followupUnknownId: null, resolvingFollowupIds: new Set(), retryingFollowupIds: new Set(), integrations: null, historyOpen: false, historyFilter: 'all', archivedHistoryOpen: false,
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,
30
30
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
31
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, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
32
+ answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, historyRename: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
33
33
  stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(), revokingApprovalTurns: new Set(), uploadingChatIds: new Set(),
34
34
  // Latched so the 5 s account poll logs an outage once instead of twelve times a minute; cleared
35
35
  // on the next successful read, so a later, separate outage is logged too.
@@ -38,10 +38,16 @@
38
38
  // on its own timer), failure notices and the last card refusal, keyed by request.
39
39
  filterPending: new Map(), filterNotices: new Map(), filterCardMessages: new Map(),
40
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
+ // The last sentence report() put under the box, held there until the person acts on it (#1683):
45
+ // { message, scope, chatId, draft, attachments, blocked }. See heldReport().
46
+ reportHold: null,
41
47
  // A Tekla model library carried over from a Graft receipt but not yet bound to its chat. It is
42
48
  // browser-only until Send: opening, editing or removing it never calls the binding route.
43
49
  // pendingTeklaLibrary waits for the provider chooser to create the chat it belongs to.
44
- teklaDraft: null, pendingTeklaLibrary: null, teklaRemoveError: null,
50
+ teklaDraft: null, pendingTeklaLibrary: null, teklaRemoveError: null, teklaRevokingChatId: null, teklaNewestBinding: new Map(),
45
51
  };
46
52
  // A short-window resize can shrink the bounded tray after a decision card was painted.
47
53
  // Keep its actions in view only while the reader was already at the bottom; preserve a
@@ -98,8 +104,13 @@
98
104
  response = await fetch(path, init);
99
105
  } catch (error) {
100
106
  if (error?.name === 'TimeoutError' || error?.name === 'AbortError') {
101
- const timeout = new Error('FloLess did not respond in time. Check that the local server is running, then try again.');
107
+ // The server is almost always running but busy when this happens (#1604), so the sentence
108
+ // leads with "try again" and keeps "is it still running?" as the fallback.
109
+ 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.');
102
110
  timeout.code = 'local-timeout';
111
+ // Which call timed out, and after how long: the sentence above is for the user, this is for
112
+ // whoever reads the console when it happens (#1604).
113
+ timeout.cause = { path, timeoutMs, name: error.name };
103
114
  throw timeout;
104
115
  }
105
116
  throw error;
@@ -153,6 +164,9 @@
153
164
  return 'FloLess could not start this queued AI response, so the message was not sent. Wait a moment, then use Retry sending.';
154
165
  }
155
166
  const code = String(error && error.code || '');
167
+ // request() writes the timeout's sentence itself. Without this it fell through to the generic "could
168
+ // not complete this chat action", which hid the one fact the user could act on (#1604).
169
+ if (code === 'local-timeout' && raw) return raw;
156
170
  const codeMessages = {
157
171
  'chat-origin-refused': 'This chat can only be used from the FloLess app. Reload the page and try again.',
158
172
  'chat-owner-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
@@ -171,6 +185,11 @@
171
185
  'chat-followup-not-found': 'This message is no longer in this conversation. Refresh the conversation.',
172
186
  'chat-attachment-scope': 'An attached file is no longer available to this message. Add the file again in a new message.',
173
187
  'chat-initiator-unknown': 'FloLess could not identify what started this conversation. Reload the conversation and try again.',
188
+ // Damage the user can act on, unlike the refusals below it: the conversation history lists this
189
+ // same record as a row offering Discard, so the sentence sends them there (#1629). Without an
190
+ // entry here the code fell through to the generic "could not complete this chat action", which
191
+ // hid the one fact they could act on.
192
+ 'chat-record-unreadable': 'This conversation’s saved file is damaged, so FloLess cannot open it. Open the conversation history and discard it there.',
174
193
  'chat-record-unsafe': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
175
194
  'chat-record-invalid': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
176
195
  'chat-session-bindings-corrupt': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
@@ -206,6 +225,8 @@
206
225
  'chat-knowledge-unscoped': 'Knowledge is available only inside a project conversation. Open a project and try again.',
207
226
  'chat-knowledge-page-missing': 'That Knowledge page is no longer available in this project. Refresh the conversation.',
208
227
  'approval-explicit-only': 'This read needs its own approval. Choose Approve once or Deny.',
228
+ 'approval-not-chat-allowable': 'Only Tekla reads can be allowed for the whole chat. Choose Approve once or Deny.',
229
+ 'tekla-allowance-changed': 'The Tekla read permission for this chat changed. Choose again.',
209
230
  };
210
231
  if (code === 'chat-followup-refused' && error?.reason === 'chat-session-required') {
211
232
  return 'Your FloLess session expired before this message was sent. Copy the draft, reload, then paste and send it again.';
@@ -313,13 +334,105 @@
313
334
  function report(error, prefix = '', messages = null) {
314
335
  const code = String(error && error.code || '');
315
336
  const message = `${prefix}${prefix ? ': ' : ''}${messages?.[code] || errorMessage(error)}`;
337
+ // Keep the raw cause (#1604): the user-facing sentence deliberately drops it, and without it a
338
+ // failure could only be diagnosed from the server log. A timeout, a network failure or a server
339
+ // error the server did not explain is unexpected, so it is an error. A refusal the server named
340
+ // with its own code — a 4xx, or an expected 5xx such as `chat-provider-unavailable` — is a
341
+ // warning. A check made here in the browser (too many images, a file too large) is neither: the
342
+ // sentence already says everything, so it is not logged.
343
+ const status = Number.isInteger(error?.status) ? error.status : null;
344
+ const unexpected = code === 'local-timeout' || (status !== null && status >= 500 && !code)
345
+ || error?.name === 'TypeError' || error?.name === 'SyntaxError';
346
+ if (unexpected) console.error(`[ai-chat] ${message}`, error?.cause ?? '', error);
347
+ else if (status !== null) console.warn(`[ai-chat] ${message}`, error);
316
348
  announce(message);
317
349
  ui.hint.textContent = message;
318
350
  ui.hint.classList.add('error');
351
+ holdReport(message);
352
+ }
353
+
354
+ /**
355
+ * Every repaint of the composer (a poll, a status change, the setup card's tick) rewrites the hint,
356
+ * which used to wipe a reported sentence within seconds (#1683). It is the only visible reason nothing
357
+ * happened, so it is held, with what the composer looked like when it was said, until the person acts
358
+ * on it (heldReport). The Drawing Filter setup sentence is not: filterSetupHint gives it its own,
359
+ * longer lifetime, tied to the setup card.
360
+ */
361
+ function holdReport(message) {
362
+ state.reportHold = message === state.filterSetupNote?.sentence ? null : {
363
+ message, scope: scopeKey(state.scope), chatId: state.chat?.chatId ?? null,
364
+ draft: ui.input.value, attachments: attachmentKey(), blocked: sendBlocker(),
365
+ };
366
+ }
367
+
368
+ /** New or resolved send blockers supersede a reported sentence; keep every active reason so a change in either direction counts. */
369
+ function sendBlocker() {
370
+ const reasons = [];
371
+ if (state.chat?.state === 'recovery') reasons.push('recovery');
372
+ if (state.chat?.activeTurn?.local) reasons.push('local-turn');
373
+ if (state.chat?.archivedAt) reasons.push('archived');
374
+ if (requestExecutionBlocked()) reasons.push('execution');
375
+ if (state.followupUnknownId || hasUnknownFollowup()) reasons.push('unknown-followup');
376
+ return reasons.join('|') || null;
377
+ }
378
+
379
+ function attachmentKey() {
380
+ return state.attachments.map((attachment) => attachment.attachmentId).join('\n');
381
+ }
382
+
383
+ /**
384
+ * The reported sentence while nothing has superseded it, else null (and it is dropped for good). The
385
+ * person acting on it ends it: the words in the box changed (typed, sent, restored), the attachments
386
+ * changed, another conversation, or another chat control used (releaseReportOnControl) — each of
387
+ * which either works or reports its own sentence. A blocker that arose since (another AI Chat
388
+ * changing this project, a follow-up FloLess could not confirm) ends it too: that is now the reason.
389
+ */
390
+ function heldReport() {
391
+ const hold = state.reportHold;
392
+ if (!hold) return null;
393
+ const blocker = sendBlocker();
394
+ if (hold.scope === scopeKey(state.scope) && hold.chatId === (state.chat?.chatId ?? null)
395
+ && hold.draft === ui.input.value && hold.attachments === attachmentKey() && blocker === hold.blocked) {
396
+ return hold.message;
397
+ }
398
+ state.reportHold = null;
399
+ return null;
400
+ }
401
+
402
+ /** A click or choice on a chat control is the person acting: it supersedes a held sentence (#1683). */
403
+ function releaseReportOnControl(event) {
404
+ const control = event.target?.closest?.('button, a[href], select, input, [role="button"], [role="option"], [role="menuitem"]');
405
+ if (control && control !== ui.send && !control.disabled && control.getAttribute('aria-disabled') !== 'true') {
406
+ state.reportHold = null;
407
+ clearReport();
408
+ }
409
+ }
410
+
411
+ // A Drawing Filter message refused while FloLess sets its AI up (#1650) keeps its sentence in the hint
412
+ // while the card still shows that very setup and the refused words are still in the draft, which the
413
+ // sentence says they are. Every repaint asks again, so the sentence ends with the first of those to
414
+ // change (the setup finished, was cancelled or failed another way, another conversation, the words
415
+ // removed) and the card speaks for itself.
416
+ function filterSetupHint() {
417
+ const note = state.filterSetupNote;
418
+ if (!note) return null;
419
+ const status = state.chat ? state.capability?.runtime : null;
420
+ if (status && runtimeCardKey(state.chat.chatId, status) === note.key && ui.input.value.includes(note.text)) return note.sentence;
421
+ state.filterSetupNote = null;
422
+ return null;
319
423
  }
320
424
 
321
425
  function clearReport() {
322
426
  ui.hint.classList.remove('error');
427
+ const held = heldReport();
428
+ if (held) {
429
+ ui.hint.classList.remove('working');
430
+ ui.hint.removeAttribute('aria-label');
431
+ ui.hint.textContent = held;
432
+ ui.hint.classList.add('error');
433
+ return;
434
+ }
435
+ const filterNote = filterSetupHint();
323
436
  const message = requestExecutionBlocked()
324
437
  ? 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.'
325
438
  : state.followupUnknownId || hasUnknownFollowup()
@@ -328,7 +441,7 @@
328
441
  && state.attachments.filter(attachment => attachment.mediaType.startsWith('image/')).length >= MAX_IMAGES_PER_MESSAGE
329
442
  ? 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.'
330
443
  : state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
331
- ? runtimeNotice(state.chat.provider, state.capability.runtime).body
444
+ ? filterNote || runtimeNotice(state.chat.provider, state.capability.runtime).body
332
445
  : state.chat && !providerReady()
333
446
  ? `${capabilityMessage(state.chat.provider, state.capability?.reason)} You can still write a message; Send will retry the connection.`
334
447
  : state.chat?.state === 'recovery'
@@ -345,6 +458,8 @@
345
458
  ui.hint.classList.remove('working');
346
459
  ui.hint.removeAttribute('aria-label');
347
460
  ui.hint.textContent = message;
461
+ // Painted as it was reported, so the poll does not restyle it.
462
+ if (filterNote && message === filterNote) ui.hint.classList.add('error');
348
463
  }
349
464
  }
350
465
 
@@ -656,23 +771,9 @@
656
771
  accounts.textContent = 'Checking signed-in accounts…';
657
772
  empty.append(accounts);
658
773
  // There is no chat yet, so no capability probe exists; the runtimes read carries the same sign-in.
659
- request('/api/terminal-runtimes').then((info) => {
660
- if (!accounts.isConnected) return;
661
- accounts.replaceChildren(...['claude', 'codex'].map((provider) => {
662
- const cell = document.createElement('span');
663
- const runtime = info?.runtimes?.find((r) => r?.id === provider);
664
- // Each row carries its OWN answer — including that its status read failed — so this must
665
- // state that answer rather than assume the read landed. A runtime missing from the list
666
- // is a known absence, not an unchecked one, hence the flat "not installed" wording.
667
- cell.textContent = runtime ? providerAccountLabel(provider, runtime.account) : `${providerLabels[provider]} · not installed`;
668
- return cell;
669
- }));
670
- }).catch((error) => {
671
- // The line disappears rather than guessing; without this the feature vanishing is invisible.
672
- console.warn('floless: could not read the signed-in accounts for the chooser', error);
673
- if (accounts.isConnected) accounts.remove();
674
- });
774
+ readChooserAccounts(accounts);
675
775
  ui.feed.append(empty);
776
+ paintUnreadableNotice();
676
777
  ui.title.textContent = 'New conversation';
677
778
  const providerValue = ui.provider.querySelector('strong');
678
779
  providerValue.textContent = 'Choose Claude or Codex';
@@ -692,6 +793,145 @@
692
793
  closePicker();
693
794
  }
694
795
 
796
+ // A project whose only conversations are damaged opens on the Claude / Codex choice, with the
797
+ // History list closed: without this line nothing on screen would say those conversations exist
798
+ // (#1619). Deliberately quiet (dim text, no badge) — the ☷ unread badge means new messages.
799
+ function paintUnreadableNotice() {
800
+ const card = ui.feed.querySelector('.ai-chat-empty');
801
+ const count = state.unreadableChats?.length || 0;
802
+ let notice = card?.querySelector('.ai-chat-unreadable-notice') || null;
803
+ if (!card || !count) { notice?.remove(); return; }
804
+ if (!notice) {
805
+ notice = document.createElement('div'); notice.className = 'ai-chat-unreadable-notice';
806
+ card.append(notice);
807
+ }
808
+ notice.textContent = count === 1
809
+ ? `1 conversation in this ${state.scope.owner.kind} can’t be opened — see History.`
810
+ : `${count} conversations in this ${state.scope.owner.kind} can’t be opened — see History.`;
811
+ }
812
+
813
+ // The waits between re-reads of a chooser account that came back 'unknown' (#1606). The server
814
+ // answers 'unknown' when the CLI status read threw or timed out — a transient answer it replaces
815
+ // on its next read — but nothing else re-reads while the chooser is up: pollChats() has no chat to
816
+ // read for ("no chat, no read"). Without this, one slow first read froze "could not check" under
817
+ // both buttons for as long as the chooser stayed open. Backs off to the last value and repeats it;
818
+ // past the 10 s server cache each read asks the CLI again, so the floor stays at seconds, not ms.
819
+ const CHOOSER_ACCOUNT_RETRY_MS = [2_000, 4_000, 8_000, 16_000, 30_000];
820
+ // The rows a re-read may still change: an account the server could not check yet, and FloLess's own
821
+ // copy of an AI that is not set up yet (#1622). Every other row already says what it knows.
822
+ const CHOOSER_PENDING_STATES = new Set(['unknown', 'setup']);
823
+
824
+ // The one chooser account read in flight, shared by every line that asks while it is pending. A
825
+ // repaint (+ New conversation pressed again, a project reopened) builds a new line while the old
826
+ // line's read may still be waiting on a slow CLI; without this each repaint would add another
827
+ // concurrent request instead of reusing the one already on its way.
828
+ let chooserAccountsRead = null;
829
+ function readChooserRuntimes() {
830
+ if (!chooserAccountsRead) {
831
+ chooserAccountsRead = request('/api/terminal-runtimes')
832
+ .finally(() => { chooserAccountsRead = null; });
833
+ }
834
+ return chooserAccountsRead;
835
+ }
836
+
837
+ // What the chooser says about FloLess's own copy of an AI that is not ready to answer yet (#1622),
838
+ // in the New project dialog's words: until that copy is set up there is no account to check, so
839
+ // "retrying…" would promise an answer that cannot come. Null when the account line applies — no
840
+ // managed copy (the user's install runs), or a copy ready to launch. The state is the shared
841
+ // `chatRuntimeReadiness` (web/aware.js), so this line cannot disagree with what a start would do.
842
+ function chooserSetupLine(provider, runtime) {
843
+ const managed = runtime && runtime.managed && typeof runtime.managed === 'object' ? runtime.managed : null;
844
+ const readiness = managed ? window.flolessBridge?.chatRuntimeReadiness?.(runtime) : null;
845
+ if (!readiness || readiness === 'ready') return null;
846
+ const label = providerLabels[provider];
847
+ // Only a setup still to come can change on its own; a copy FloLess cannot start is a final answer.
848
+ if (readiness === 'setup') {
849
+ if (managed.state === 'preparing') return { text: `${label} · setting up…`, state: 'setup' };
850
+ if (managed.state === 'failed') return { text: `${label} · setup failed, choosing it tries again`, state: 'setup' };
851
+ return { text: `${label} · not set up yet`, state: 'setup' };
852
+ }
853
+ return { text: `${label} · couldn’t be set up`, state: 'unavailable' };
854
+ }
855
+
856
+ function chooserAccountCell(provider, runtime, attempt) {
857
+ const cell = document.createElement('span');
858
+ // A runtime missing from the list is a known absence, not an unchecked one: flat "not installed".
859
+ const answer = runtime ? signInAnswer(runtime.account) : null;
860
+ const setup = runtime ? chooserSetupLine(provider, runtime) : null;
861
+ cell.dataset.provider = provider;
862
+ // A copy FloLess is still to set up is re-read like an unknown account, so the row moves on by
863
+ // itself once the setup lands (started from this chooser, another surface or another window).
864
+ cell.dataset.accountState = setup ? setup.state : answer ? answer.state : 'not-installed';
865
+ if (setup) cell.textContent = setup.text;
866
+ else if (!answer) cell.textContent = `${providerLabels[provider]} · not installed`;
867
+ // While the first few re-reads are still due, say so rather than show a verdict that is about to
868
+ // be replaced; once the backoff has reached its slowest step the row says what it knows — the
869
+ // re-read carries on at that pace and still updates the row in place if an answer lands.
870
+ else if (answer.state === 'unknown' && attempt < CHOOSER_ACCOUNT_RETRY_MS.length - 1) cell.textContent = `${providerLabels[provider]} · retrying…`;
871
+ else cell.textContent = providerAccountLabel(provider, answer);
872
+ return cell;
873
+ }
874
+
875
+ // Reads the chooser's account line, then re-reads it on the backoff above while any row is still
876
+ // 'unknown' and this line is still on screen. One chain per line, strictly sequential — the next
877
+ // read is armed only after the previous one settled — and every read goes through the shared
878
+ // in-flight read above, so neither a chain nor a burst of repaints can overlap requests or pile up
879
+ // sockets. A repaint builds a new line, which disconnects this one and ends its chain at its next
880
+ // step. Only the unknown rows change: each row carries its own answer, and one that was already
881
+ // definite is not re-stated by a later read.
882
+ function readChooserAccounts(accounts, attempt = 0, warned = false) {
883
+ const next = (seenFailure) => {
884
+ const wait = () => setTimeout(() => {
885
+ if (!accounts.isConnected) return;
886
+ // A hidden window or a collapsed chat pane reads nothing, like pollChats(); the chain waits
887
+ // at its current pace and resumes when the line can be seen again.
888
+ if (document.hidden || ui.feed.closest('[hidden]')) { wait(); return; }
889
+ readChooserAccounts(accounts, attempt + 1, seenFailure);
890
+ }, CHOOSER_ACCOUNT_RETRY_MS[Math.min(attempt, CHOOSER_ACCOUNT_RETRY_MS.length - 1)]);
891
+ wait();
892
+ };
893
+ readChooserRuntimes().then((info) => {
894
+ if (!accounts.isConnected) return;
895
+ const cells = ['claude', 'codex'].map((provider) =>
896
+ chooserAccountCell(provider, info?.runtimes?.find((r) => r?.id === provider), attempt));
897
+ const current = [...accounts.querySelectorAll('span')];
898
+ if (current.length !== cells.length) {
899
+ // The first answer replaces the "Checking signed-in accounts…" placeholder.
900
+ accounts.replaceChildren(...cells);
901
+ } else {
902
+ // A re-read: only a row still waiting for an answer takes the new one, in place.
903
+ current.forEach((cell, index) => {
904
+ if (!CHOOSER_PENDING_STATES.has(cell.dataset.accountState)) return;
905
+ const fresh = cells[index];
906
+ cell.dataset.accountState = fresh.dataset.accountState;
907
+ if (cell.textContent !== fresh.textContent) cell.textContent = fresh.textContent;
908
+ });
909
+ }
910
+ if ([...accounts.querySelectorAll('span')].some((cell) => CHOOSER_PENDING_STATES.has(cell.dataset.accountState))) next(warned);
911
+ }).catch((error) => {
912
+ if (!accounts.isConnected) return;
913
+ if (attempt === 0) {
914
+ // The line disappears rather than guessing; without this the feature vanishing is invisible.
915
+ console.warn('floless: could not read the signed-in accounts for the chooser', error);
916
+ accounts.remove();
917
+ return;
918
+ }
919
+ // A re-read that failed outright leaves the rows as they are and tries again at the next step;
920
+ // warned once per line, so a server that went away does not log every half-minute.
921
+ if (!warned) console.warn('floless: could not re-read the signed-in accounts for the chooser', error);
922
+ // Failed re-reads still advance the backoff, so the row must still stop saying "retrying…" at
923
+ // the slowest step — or a server that stopped answering would leave it there for good.
924
+ if (attempt >= CHOOSER_ACCOUNT_RETRY_MS.length - 1) {
925
+ for (const cell of accounts.querySelectorAll('span')) {
926
+ if (cell.dataset.accountState !== 'unknown') continue;
927
+ const label = providerAccountLabel(cell.dataset.provider, { state: 'unknown' });
928
+ if (cell.textContent !== label) cell.textContent = label;
929
+ }
930
+ }
931
+ next(true);
932
+ });
933
+ }
934
+
695
935
  function clearProviderChoice() {
696
936
  state.choosingProvider = false;
697
937
  }
@@ -701,7 +941,7 @@
701
941
  clearProviderChoice();
702
942
  closeSource();
703
943
  clearLiveStream(true);
704
- state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = []; state.followupUnknownId = null;
944
+ state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = []; state.followupUnknownId = null;
705
945
  ui.feed.replaceChildren();
706
946
  updateOffscreenActivity();
707
947
  const empty = document.createElement('div');
@@ -747,12 +987,79 @@
747
987
  function restoreHistoryFocus(commandId) {
748
988
  if (!commandId) return;
749
989
  requestAnimationFrame(() => {
990
+ // Only put back focus the repaint took away. If the person has moved on since (into a row's
991
+ // rename field, say), a late frame must not pull focus out of it — that blur would save
992
+ // the half-typed name (#1582). A hidden tab can hold this frame back for a long time.
993
+ if (document.activeElement && document.activeElement !== document.body) return;
750
994
  [...ui.history.querySelectorAll('[data-command-id]')]
751
995
  .find((candidate) => candidate.dataset.commandId === commandId)?.focus();
752
996
  });
753
997
  }
754
998
 
999
+ // Where keyboard focus goes when a conversation's inline rename ends, so it never falls to the
1000
+ // page: the row's ✎, where the rename began; the row itself when ✎ has been withdrawn (the AI
1001
+ // is replying); the All filter when the row cannot be seen (it left the list, or sits in the
1002
+ // closed Archived list).
1003
+ function focusHistoryConversation(chatId) {
1004
+ const commandId = `shell.chat-history-item#${chatId}`;
1005
+ const row = [...ui.history.querySelectorAll('.ai-chat-history-row')].find((node) => node.dataset.commandId === commandId);
1006
+ const closed = row?.closest('details');
1007
+ const rowSeen = Boolean(row) && (!closed || closed.open)
1008
+ && (typeof row.checkVisibility !== 'function' || row.checkVisibility());
1009
+ const renameButton = rowSeen ? row.querySelector('.ai-chat-history-rename') : null;
1010
+ const renameSeen = Boolean(renameButton) && !renameButton.hidden
1011
+ && (typeof renameButton.checkVisibility !== 'function' || renameButton.checkVisibility());
1012
+ (renameSeen ? renameButton : rowSeen ? row : ui.history.querySelector('.ai-chat-history-filter'))?.focus({ preventScroll: true });
1013
+ }
1014
+
1015
+ // Every history repaint goes through here. The list is rebuilt in the background (the 5 s poll,
1016
+ // SSE, a lifecycle action elsewhere), and rebuilding it removes a history-row rename field —
1017
+ // which fires that field's blur and would save whatever was half-typed (#1582). So carry an open
1018
+ // rename across the rebuild: the SAME input moves into the rebuilt row with its text, caret and
1019
+ // focus intact. Enter, Escape or the person leaving the field ends it — or the conversation
1020
+ // no longer being renamable in this list, which drops the edit unsaved.
755
1021
  function paintHistory() {
1022
+ const rename = state.historyRename;
1023
+ if (!rename) { renderHistory(); return; }
1024
+ const { input } = rename;
1025
+ const hadFocus = document.activeElement === input;
1026
+ const { selectionStart, selectionEnd, selectionDirection } = input;
1027
+ rename.repainting = true;
1028
+ try { renderHistory(); } finally { rename.repainting = false; }
1029
+ if (state.historyRename !== rename) return;
1030
+ const commandId = `shell.chat-history-item#${rename.chatId}`;
1031
+ const row = [...ui.history.querySelectorAll('.ai-chat-history-row')].find((node) => node.dataset.commandId === commandId);
1032
+ const titleNode = row?.querySelector('.ai-chat-history-title');
1033
+ const renameButton = row?.querySelector('.ai-chat-history-rename');
1034
+ // The conversation left the list, was archived, started a turn, or the project changed under
1035
+ // the field: there is nothing left to rename in place, so drop the edit rather than save it.
1036
+ const sameList = sameScope(rename.scope, rename.generation);
1037
+ if (!titleNode || !renameButton || renameButton.hidden || !sameList) {
1038
+ rename.abandon();
1039
+ // The field vanished under the person's typing; say the name was not kept, and why. Not
1040
+ // after a project switch — they left on purpose and are now looking at another list.
1041
+ if (!sameList) return;
1042
+ // The cause is only known when the row is still here; a missing row may be deleted, archived
1043
+ // or filtered out, so that message stays neutral about why.
1044
+ const archived = Boolean(row?.closest('.ai-chat-history-archived'));
1045
+ announce(!row
1046
+ ? '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.'
1047
+ : archived
1048
+ ? 'Rename cancelled. This conversation was archived, so the new name was not saved. Restore it to rename it.'
1049
+ : 'Rename cancelled. The AI started working in this conversation, so the new name was not saved. You can rename it when the reply finishes.');
1050
+ // Keep keyboard focus in the history instead of letting it fall to the page.
1051
+ if (hadFocus) focusHistoryConversation(rename.chatId);
1052
+ return;
1053
+ }
1054
+ row.dataset.renaming = 'true'; renameButton.hidden = true;
1055
+ titleNode.replaceWith(input);
1056
+ if (hadFocus) {
1057
+ input.focus({ preventScroll: true });
1058
+ input.setSelectionRange(selectionStart, selectionEnd, selectionDirection || 'none');
1059
+ }
1060
+ }
1061
+
1062
+ function renderHistory() {
756
1063
  const focusedCommand = ui.history.contains(document.activeElement) ? document.activeElement?.dataset?.commandId : null;
757
1064
  ui.history.replaceChildren();
758
1065
  if (!state.scope) return;
@@ -817,7 +1124,10 @@
817
1124
  }
818
1125
 
819
1126
  const archivedChats = state.archivedChats.filter((chat) => Boolean(chat.archivedAt));
1127
+ const unreadableChats = state.unreadableChats || [];
1128
+ if (unreadableChats.length) appendUnreadableChats(unreadableChats, ui.history);
820
1129
  if (!state.chats.length && !archivedChats.length) {
1130
+ if (unreadableChats.length) { restoreHistoryFocus(focusedCommand); return; }
821
1131
  const empty = document.createElement('div'); empty.className = 'ai-chat-history-empty';
822
1132
  empty.textContent = 'No conversations here yet.';
823
1133
  ui.history.append(empty); return;
@@ -924,6 +1234,83 @@
924
1234
  }
925
1235
  }
926
1236
 
1237
+ // A conversation whose saved file is damaged (#1619). The server knows nothing trustworthy about it
1238
+ // beyond its id — no title, no provider — so the row says what happened and offers the one thing
1239
+ // that can be done here. It opens nothing, so it is not a button; only Discard acts.
1240
+ function appendUnreadableChats(entries, destination) {
1241
+ const group = document.createElement('section'); group.className = 'ai-chat-history-group ai-chat-history-unreadable';
1242
+ group.setAttribute('aria-label', 'Conversations that can’t be opened');
1243
+ const label = document.createElement('div'); label.className = 'ai-chat-history-label'; label.textContent = 'Can’t be opened';
1244
+ group.append(label);
1245
+ for (const entry of entries) {
1246
+ const row = document.createElement('div');
1247
+ row.className = 'ai-chat-history-row unreadable';
1248
+ row.dataset.chatId = entry.chatId;
1249
+ const title = document.createElement('span'); title.className = 'ai-chat-history-title'; title.textContent = 'Conversation can’t be opened';
1250
+ const meta = document.createElement('span'); meta.className = 'ai-chat-history-meta';
1251
+ const changed = entry.changedAt && Number.isFinite(Date.parse(entry.changedAt))
1252
+ ? ` · changed ${formatDay(entry.changedAt) === 'Today' ? eventTime({ createdAt: entry.changedAt }) : formatDay(entry.changedAt)}`
1253
+ : '';
1254
+ meta.textContent = `Saved file is damaged${changed}`;
1255
+ const actions = document.createElement('span'); actions.className = 'ai-chat-history-actions always-on';
1256
+ const discard = document.createElement('button');
1257
+ discard.type = 'button'; discard.className = 'ai-chat-history-action danger'; discard.append(historyActionIcon('delete'));
1258
+ discard.dataset.commandId = `shell.chat-history-discard#${entry.chatId}`;
1259
+ discard.dataset.commandInstanceLabel = `Damaged conversation${changed}`;
1260
+ discard.setAttribute('aria-label', 'Discard damaged conversation');
1261
+ discard.dataset.tip = 'Permanently discard this conversation';
1262
+ discard.addEventListener('click', (event) => {
1263
+ event.preventDefault(); event.stopPropagation(); discardUnreadableConversation(entry, discard);
1264
+ });
1265
+ actions.append(discard);
1266
+ row.append(title, meta, actions);
1267
+ group.append(row);
1268
+ }
1269
+ destination.append(group);
1270
+ }
1271
+
1272
+ async function discardUnreadableConversation(entry, trigger) {
1273
+ const snapshot = captureScope();
1274
+ if (!snapshot) return;
1275
+ const confirm = window.flolessBridge?.formModal;
1276
+ if (!confirm) { report(new Error('Could not open the confirmation dialog'), 'Could not discard conversation'); return; }
1277
+ const approved = await confirm({
1278
+ title: 'Discard this damaged conversation?',
1279
+ 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.',
1280
+ fields: [], okLabel: 'Discard permanently', danger: true, returnFocusTo: trigger,
1281
+ });
1282
+ if (!approved || !sameScope(snapshot.scope, snapshot.generation)) return;
1283
+ trigger.disabled = true;
1284
+ try {
1285
+ await request(`/api/chat/conversations/${encodeURIComponent(entry.chatId)}/discard-unreadable`, {
1286
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner }),
1287
+ });
1288
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1289
+ state.unreadableChats = (state.unreadableChats || []).filter((item) => item.chatId !== entry.chatId);
1290
+ paintHistory(); paintUnreadableNotice();
1291
+ ui.history.querySelector('[aria-pressed="true"]')?.focus({ preventScroll: true });
1292
+ announce('Discarded the damaged conversation.');
1293
+ } catch (error) {
1294
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1295
+ if (error?.code === 'chat-record-readable') {
1296
+ // Repaired on disk (or it was only mid-save): it is a normal conversation again, so keep it.
1297
+ // Say so on screen too — the status region is for screen readers only. After the re-read:
1298
+ // with a conversation open, the poll's composer refresh rewrites the hint line.
1299
+ const kept = 'This conversation can be opened again, so it was kept.';
1300
+ state.unreadableChats = (state.unreadableChats || []).filter((item) => item.chatId !== entry.chatId);
1301
+ paintHistory(); paintUnreadableNotice();
1302
+ await pollChats();
1303
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1304
+ announce(kept);
1305
+ ui.hint.textContent = kept;
1306
+ return;
1307
+ }
1308
+ report(error, 'Could not discard conversation', {
1309
+ '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.`,
1310
+ });
1311
+ } finally { trigger.disabled = false; }
1312
+ }
1313
+
927
1314
  function eventTime(event) {
928
1315
  return new Intl.DateTimeFormat(undefined, { hour: '2-digit', minute: '2-digit' }).format(new Date(event.createdAt));
929
1316
  }
@@ -987,12 +1374,31 @@
987
1374
  titleNode.replaceWith(input);
988
1375
  input.focus(); input.select();
989
1376
  let finished = false;
990
- const finish = async (save = true) => {
1377
+ const active = {
1378
+ chatId: chat.chatId, input, scope: snapshot.scope, generation: snapshot.generation, repainting: false,
1379
+ abandon() { finished = true; if (state.historyRename === active) state.historyRename = null; },
1380
+ };
1381
+ state.historyRename = active;
1382
+ // `returnFocus`: the rename ended from the field's own keys, so focus goes back to this
1383
+ // conversation's row instead of falling to the page. Clicking away keeps focus where it went.
1384
+ const finish = async (save = true, { returnFocus = false } = {}) => {
991
1385
  if (finished) return;
992
1386
  finished = true;
1387
+ if (state.historyRename === active) state.historyRename = null;
993
1388
  const title = input.value.trim();
994
- if (!save || !title || title === original) { if (sameScope(snapshot.scope, snapshot.generation)) paintHistory(); return; }
1389
+ if (!save || !title || title === original) {
1390
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1391
+ paintHistory();
1392
+ if (returnFocus) focusHistoryConversation(chat.chatId);
1393
+ return;
1394
+ }
1395
+ // The list this field was opened in has been replaced (another project or workflow, or a
1396
+ // reload of it): never send a rename from a field that no longer belongs to what is shown.
1397
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
995
1398
  input.disabled = true;
1399
+ // The save takes a moment. Only bring focus back if the person has not moved it elsewhere
1400
+ // meanwhile (it is still on the field, or fell to the page when the field was disabled).
1401
+ const focusWaited = () => returnFocus && [input, document.body, null].includes(document.activeElement);
996
1402
  try {
997
1403
  const updated = await request(`/api/chat/conversations/${encodeURIComponent(chat.chatId)}/title`, {
998
1404
  method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, title }),
@@ -1004,17 +1410,36 @@
1004
1410
  state.chat = updated;
1005
1411
  ui.title.textContent = updated.title;
1006
1412
  }
1007
- paintHistory(); announce('Conversation name saved.');
1413
+ const refocus = focusWaited();
1414
+ paintHistory(); if (refocus) focusHistoryConversation(chat.chatId);
1415
+ announce('Conversation name saved.');
1008
1416
  } catch (error) {
1009
1417
  if (!sameScope(snapshot.scope, snapshot.generation)) return;
1010
- paintHistory(); report(error, 'Could not rename conversation');
1418
+ const refocus = focusWaited();
1419
+ paintHistory(); if (refocus) focusHistoryConversation(chat.chatId);
1420
+ report(error, 'Could not rename conversation');
1011
1421
  }
1012
1422
  };
1423
+ // The field sits inside the row, whose click opens the conversation. A click in the field (to
1424
+ // move the caret) must stay in the field, or opening the conversation would blur and save it.
1425
+ input.addEventListener('click', (event) => event.stopPropagation());
1013
1426
  input.addEventListener('keydown', (event) => {
1014
- if (event.key === 'Enter') { event.preventDefault(); finish(true); }
1015
- if (event.key === 'Escape') { event.preventDefault(); finish(false); }
1427
+ // While an input method is composing (Japanese, Chinese, Korean…), Enter accepts the
1428
+ // candidate and Escape dismisses it: both belong to the composition, not to the rename.
1429
+ // Older Safari sends that key after the composition ends, with isComposing false and
1430
+ // keyCode 229, so either one marks it.
1431
+ const composing = event.isComposing || event.keyCode === 229;
1432
+ if (event.key === 'Enter' && !composing) { event.preventDefault(); finish(true, { returnFocus: true }); }
1433
+ if (event.key === 'Escape') {
1434
+ // Escape in this field is the field's, never the history's: left to bubble, it would also
1435
+ // reach the history's own Escape and close the whole history (#1603). One press, one action.
1436
+ event.stopPropagation();
1437
+ if (composing) return;
1438
+ event.preventDefault(); finish(false, { returnFocus: true });
1439
+ }
1016
1440
  });
1017
- input.addEventListener('blur', () => finish(true));
1441
+ // A repaint removing the field is not the person leaving it; paintHistory() puts it back.
1442
+ input.addEventListener('blur', () => { if (!active.repainting) finish(true); });
1018
1443
  }
1019
1444
 
1020
1445
  async function leaveConversationAfterRemoval(chatId, announcement, snapshot) {
@@ -1027,7 +1452,9 @@
1027
1452
  state.chat = null; state.events = []; state.attachments = []; state.followupUnknownId = null; state.integrations = null;
1028
1453
  updateOffscreenActivity();
1029
1454
  if (state.chats.length) await selectConversation(state.chats[0].chatId, { focus: true, replaceProviderChoice: true });
1030
- else providerChooser();
1455
+ // The chooser removes the removed conversation's setup card; its hint goes too, as on every other way
1456
+ // to the chooser, so nothing is left saying a message is back in a draft that was just removed.
1457
+ else { providerChooser(); clearReport(); }
1031
1458
  if (sameScope(snapshot.scope, snapshot.generation)) announce(announcement);
1032
1459
  }
1033
1460
 
@@ -1261,6 +1688,12 @@
1261
1688
  item.append(gallery);
1262
1689
  }
1263
1690
  }
1691
+ const about = role === 'user' && event.payload?.subjects ? subjectsLine(event.payload?.subjects) : '';
1692
+ if (about) {
1693
+ const line = document.createElement('span'); line.className = 'ai-chat-message-subjects';
1694
+ line.textContent = about;
1695
+ item.append(line);
1696
+ }
1264
1697
  if (role === 'user' && (event.payload?.followup || event.payload?.deliveryState)) {
1265
1698
  const delivery = followupDelivery(event);
1266
1699
  const deliveryReceipt = [...state.events].reverse().find((candidate) => candidate.type === 'followup-status'
@@ -1402,9 +1835,10 @@
1402
1835
  }
1403
1836
 
1404
1837
  // A server-authored receipt of one approved live Tekla read. Deterministic: it shows only what
1405
- // the server recorded, and an unverified read never shows a model name.
1838
+ // the server recorded, and an unverified read never shows a model name or parts.
1406
1839
  function renderTeklaReadEvent(event) {
1407
1840
  const payload = event.payload || {};
1841
+ if (payload.status === 'verified-for-selection-read') return renderTeklaSelectionEvent(event);
1408
1842
  const verified = payload.status === 'verified-for-model-name-read';
1409
1843
  const card = document.createElement('section');
1410
1844
  card.className = `ai-chat-tekla-read ${verified ? 'verified' : 'unverified'}`;
@@ -1445,6 +1879,127 @@
1445
1879
  return card;
1446
1880
  }
1447
1881
 
1882
+ function teklaKg(value) {
1883
+ return new Intl.NumberFormat(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(value);
1884
+ }
1885
+ function teklaCount(value) { return new Intl.NumberFormat().format(value); }
1886
+ function partsWord(count) { return `${teklaCount(count)} ${count === 1 ? 'part' : 'parts'}`; }
1887
+
1888
+ // The count and total line, worded for exactly what the read covered. It sits above the table so a
1889
+ // list that was cut short says so before anyone scrolls.
1890
+ function teklaSelectionSummary(payload, listed) {
1891
+ const count = Number(payload.partCount) || 0;
1892
+ const total = `${teklaKg(Number(payload.totalWeightKg) || 0)} kg`;
1893
+ const missing = Number(payload.weightMissing) || 0;
1894
+ const lines = [];
1895
+ if (payload.complete === false) {
1896
+ 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.`);
1897
+ } else if (payload.truncated) {
1898
+ // "Covers all" only when every part read has a weight; otherwise the next line says who is left out.
1899
+ lines.push(missing > 0
1900
+ ? `Showing ${teklaCount(listed)} of ${partsWord(count)} — the total ${total} covers the ${partsWord(count - missing)} that have a weight.`
1901
+ : `Showing ${teklaCount(listed)} of ${partsWord(count)} — the total covers all ${teklaCount(count)}: ${total}.`);
1902
+ } else {
1903
+ lines.push(`${partsWord(count)} · total ${total}`);
1904
+ }
1905
+ if (missing > 0) lines.push(`Tekla gave no weight for ${partsWord(missing)}; the total leaves ${missing === 1 ? 'it' : 'them'} out.`);
1906
+ return lines;
1907
+ }
1908
+
1909
+ // The selected parts as a compact schedule. A replayed card is history: "when checked", never now.
1910
+ function renderTeklaSelectionEvent(event) {
1911
+ const payload = event.payload || {};
1912
+ const parts = Array.isArray(payload.parts) ? payload.parts : [];
1913
+ const count = Number(payload.partCount) || 0;
1914
+ const others = Number(payload.otherObjectCount) || 0;
1915
+ const card = document.createElement('section');
1916
+ card.className = 'ai-chat-tekla-read verified selection';
1917
+ card.dataset.eventSequence = String(event.sequence);
1918
+ card.dataset.eventId = event.eventId;
1919
+ const heading = document.createElement('strong');
1920
+ heading.textContent = 'Selected in Tekla when checked';
1921
+ card.setAttribute('aria-label', heading.textContent);
1922
+ card.append(heading);
1923
+ const facts = document.createElement('dl');
1924
+ const fact = (name, value) => {
1925
+ if (value === undefined || value === null || value === '') return;
1926
+ const dt = document.createElement('dt'); dt.textContent = name;
1927
+ const dd = document.createElement('dd');
1928
+ if (value instanceof Node) dd.append(value); else dd.textContent = String(value);
1929
+ facts.append(dt, dd);
1930
+ };
1931
+ fact('Model when checked', payload.modelName);
1932
+ fact('Tekla host', `${payload.hostVersion || ''}${Number.isFinite(payload.hostPid) ? ` · PID ${payload.hostPid}` : ''}`);
1933
+ fact('Checked', checkedTime(payload.checkedAt));
1934
+ fact('Library', payload.library);
1935
+ card.append(facts);
1936
+ const note = (text, className, parent = card) => {
1937
+ const line = document.createElement('p');
1938
+ if (className) line.className = className;
1939
+ line.textContent = text;
1940
+ parent.append(line);
1941
+ };
1942
+ // Only the short summary is announced; the table is read on demand through its caption.
1943
+ const summary = document.createElement('div');
1944
+ summary.className = 'ai-chat-tekla-summary';
1945
+ summary.setAttribute('role', 'status');
1946
+ card.append(summary);
1947
+ if (count === 0 && payload.complete === false) {
1948
+ // Stopped before reaching any part: that is not "nothing selected".
1949
+ 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);
1950
+ return card;
1951
+ }
1952
+ if (count === 0) {
1953
+ note(others > 0
1954
+ ? `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.`
1955
+ : 'Nothing was selected in Tekla when checked.', '', summary);
1956
+ return card;
1957
+ }
1958
+ for (const line of teklaSelectionSummary(payload, parts.length)) note(line, '', summary);
1959
+ const scroller = document.createElement('div');
1960
+ scroller.className = 'ai-chat-tekla-parts';
1961
+ // No explicit tab stop: Chromium already makes a scrolling region keyboard-focusable, and the
1962
+ // table carries no command of its own.
1963
+ scroller.setAttribute('role', 'region');
1964
+ scroller.setAttribute('aria-label', `Selected parts, ${parts.length} listed`);
1965
+ const table = document.createElement('table');
1966
+ const caption = document.createElement('caption');
1967
+ caption.className = 'sr-only';
1968
+ caption.textContent = `Parts selected in Tekla when checked (${parts.length} listed of ${count})`;
1969
+ const head = document.createElement('thead');
1970
+ const headRow = document.createElement('tr');
1971
+ for (const [label, numeric] of [['Mark', false], ['Name', false], ['Profile', false], ['Material', false], ['kg', true]]) {
1972
+ const th = document.createElement('th'); th.scope = 'col'; th.textContent = label;
1973
+ if (numeric) { th.className = 'num'; th.setAttribute('aria-label', 'Weight in kilograms'); }
1974
+ headRow.append(th);
1975
+ }
1976
+ head.append(headRow);
1977
+ const body = document.createElement('tbody');
1978
+ for (const part of parts) {
1979
+ const row = document.createElement('tr');
1980
+ for (const key of ['mark', 'name', 'profile', 'material']) {
1981
+ const td = document.createElement('td');
1982
+ const value = typeof part?.[key] === 'string' && part[key] ? part[key] : '';
1983
+ td.textContent = value || '—';
1984
+ td.className = value ? key : `${key} empty`;
1985
+ // Narrow columns cut long text short; the shared tooltip shows the recorded value.
1986
+ if (value) td.dataset.tip = value;
1987
+ row.append(td);
1988
+ }
1989
+ const weight = document.createElement('td'); weight.className = 'num';
1990
+ if (Number.isFinite(part?.weightKg)) weight.textContent = teklaKg(part.weightKg);
1991
+ else { weight.textContent = '—'; weight.classList.add('empty'); weight.setAttribute('aria-label', 'no weight'); }
1992
+ row.append(weight);
1993
+ body.append(row);
1994
+ }
1995
+ table.append(caption, head, body);
1996
+ scroller.append(table);
1997
+ card.append(scroller);
1998
+ note('Selected assemblies are listed by their parts when checked.');
1999
+ 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.`);
2000
+ return card;
2001
+ }
2002
+
1448
2003
  function checkedTime(value) {
1449
2004
  if (typeof value !== 'string' || !value) return '';
1450
2005
  const date = new Date(value);
@@ -1494,7 +2049,8 @@
1494
2049
  });
1495
2050
  }
1496
2051
 
1497
- function renderedAnswerTarget(events, eventId, turnId) {
2052
+ function renderedAnswerTarget(events, eventId, turnId, type = 'assistant-message') {
2053
+ if (type === 'user-message') return events.find((event) => event.eventId === eventId && event.type === 'user-message') || null;
1498
2054
  if (turnId) {
1499
2055
  return [...events].reverse().find((event) => event.turnId === turnId && event.type === 'assistant-message') || null;
1500
2056
  }
@@ -1677,17 +2233,24 @@
1677
2233
  shell.dataset.approvalPending = String(Boolean(approval) && !deciding);
1678
2234
  document.dispatchEvent(new CustomEvent('floless:chat-indicator'));
1679
2235
  if (!approval || deciding) { existing?.remove(); return; }
1680
- // Keep the same buttons during polling so keyboard focus and pointer clicks survive.
1681
- if (existing?.dataset.approvalId === approval.approvalId) return;
2236
+ // Keep the same buttons during polling so keyboard focus and pointer clicks survive. A Tekla card
2237
+ // also carries the permission view it offers "Allow for this chat" on, so a change repaints it.
2238
+ const teklaBinding = teklaAllowableApproval(approval) ? currentTeklaBinding(state.chat) : null;
2239
+ const allowanceRevision = teklaBinding ? String(teklaAllowanceRevision(teklaBinding)) : '';
2240
+ if (existing?.dataset.approvalId === approval.approvalId && (existing.dataset.allowanceRevision || '') === allowanceRevision) return;
2241
+ // A permission change repaints the same approval: keep keyboard focus on the same control.
2242
+ const refocus = existing?.dataset.approvalId === approval.approvalId && existing.contains(document.activeElement)
2243
+ ? document.activeElement.dataset?.commandId : null;
1682
2244
  existing?.remove();
1683
2245
  const card = document.createElement('section'); card.className = 'ai-chat-approval';
1684
2246
  card.dataset.approvalId = approval.approvalId;
2247
+ if (teklaBinding) card.dataset.allowanceRevision = allowanceRevision;
1685
2248
  const heading = document.createElement('strong'); heading.textContent = 'Approval needed';
1686
2249
  const copy = document.createElement('p'); copy.textContent = approval.summary;
1687
2250
  const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
1688
2251
  const deny = button('Deny', 'shell.chat-approval-deny');
1689
2252
  const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
1690
- // A Tekla model read needs its own decision every time, so a request-wide grant is not offered.
2253
+ // A Tekla read is never covered by a request-wide grant; it may instead be allowed for the whole chat (below).
1691
2254
  const explicitOnly = approvalIsExplicitOnly(approval);
1692
2255
  const allowRequest = explicitOnly ? null : button('Approve for this request', 'shell.chat-approval-request', 'allow');
1693
2256
  const scope = document.createElement('span');
@@ -1696,16 +2259,29 @@
1696
2259
  deny.addEventListener('click', () => decideApproval('deny'));
1697
2260
  allow.addEventListener('click', () => decideApproval('allow'));
1698
2261
  if (allowRequest) {
1699
- scope.textContent = 'Approve access actions until this response finishes. Your permission setting stays unchanged. Review checkpoints and Tekla model reads still ask every time.';
2262
+ scope.textContent = 'Approve access actions until this response finishes. Your permission setting stays unchanged. Review checkpoints still ask every time, and Tekla reads ask unless you allow them for this chat.';
1700
2263
  allowRequest.dataset.tip = scope.textContent;
1701
2264
  allowRequest.setAttribute('aria-describedby', scope.id);
1702
2265
  allowRequest.addEventListener('click', () => decideApproval('allow-request'));
1703
2266
  actions.append(deny, allow, allowRequest); card.append(heading, copy, actions, scope);
2267
+ } else if (teklaBinding) {
2268
+ // A Tekla read may instead be allowed for the whole chat, covering every read the chat is bound for.
2269
+ card.dataset.explicitOnly = 'true';
2270
+ const allowChat = button('Allow for this chat', 'shell.chat-tekla-allow-chat', 'allow');
2271
+ const help = document.createElement('span');
2272
+ help.className = 'sr-only';
2273
+ help.id = `chat-approval-tekla-scope-help-${approval.approvalId}`;
2274
+ help.textContent = `Let Chat read ${teklaReadsCopy(teklaBinding.operations, ' and ')} whenever it asks in this conversation, without asking you each time. FloLess still checks Tekla live and shows every result. Revoke it from the Tekla box above the message.`;
2275
+ allowChat.dataset.tip = help.textContent;
2276
+ allowChat.setAttribute('aria-describedby', help.id);
2277
+ allowChat.addEventListener('click', () => decideApproval('allow-chat', Number(allowanceRevision)));
2278
+ actions.append(deny, allow, allowChat); card.append(heading, copy, actions, help);
1704
2279
  } else {
1705
2280
  card.dataset.explicitOnly = 'true';
1706
2281
  actions.append(deny, allow); card.append(heading, copy, actions);
1707
2282
  }
1708
2283
  ui.approvalTray.append(card);
2284
+ if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
1709
2285
  // When a request-wide grant notice is also present, keep the decision nearest the composer.
1710
2286
  ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
1711
2287
  }
@@ -1739,7 +2315,7 @@
1739
2315
  const explanation = document.createElement('span');
1740
2316
  explanation.className = 'sr-only';
1741
2317
  explanation.id = `chat-approval-scope-help-${turn.turnId}`;
1742
- explanation.textContent = 'Your permission setting is unchanged. Review checkpoints and Tekla model reads still ask every time. Revoke asks before future access actions in this request; actions already approved may finish.';
2318
+ explanation.textContent = 'Your permission setting is unchanged. Review checkpoints still ask every time, and Tekla reads ask unless you allow them for this chat. Revoke asks before future access actions in this request; actions already approved may finish.';
1743
2319
  const revoke = button('Revoke', 'shell.chat-approval-revoke');
1744
2320
  revoke.dataset.tip = explanation.textContent;
1745
2321
  revoke.setAttribute('aria-describedby', explanation.id);
@@ -1799,6 +2375,12 @@
1799
2375
  };
1800
2376
  }
1801
2377
 
2378
+ // What the setup card shows for one conversation: the card is rebuilt, and a Drawing Filter "not sent"
2379
+ // sentence dropped from the hint, only when this changes.
2380
+ function runtimeCardKey(chatId, status) {
2381
+ return `${chatId}:${status.state}:${status.owner || ''}:${status.code || ''}:${status.retryable ? 1 : 0}`;
2382
+ }
2383
+
1802
2384
  function paintRuntime() {
1803
2385
  const existing = shell.querySelector('.ai-chat-runtime');
1804
2386
  const status = state.chat ? state.capability?.runtime : null;
@@ -1807,7 +2389,7 @@
1807
2389
  const settingUp = status.state === 'preparing' || status.state === 'not-installed';
1808
2390
  // Polls repeat the same state every two seconds; rebuilding the card each time would swap its button
1809
2391
  // out from under the pointer (a lost click) and drop keyboard focus. Rebuild only when it changes.
1810
- const key = `${state.chat.chatId}:${status.state}:${status.owner || ''}:${status.code || ''}:${status.retryable ? 1 : 0}`;
2392
+ const key = runtimeCardKey(state.chat.chatId, status);
1811
2393
  if (existing?.dataset.runtimeKey === key && existing.isConnected) { if (settingUp) startRuntimePoll(); return; }
1812
2394
  existing?.remove();
1813
2395
  const card = document.createElement('section');
@@ -1896,11 +2478,106 @@
1896
2478
  }).catch(() => {});
1897
2479
  }
1898
2480
 
2481
+ /**
2482
+ * What the paperclip says it takes, right now.
2483
+ *
2484
+ * SEPARATE FROM `paintAttachments` BECAUSE IT DEPENDS ON THE SURFACE, NOT ONLY ON THE
2485
+ * ATTACHMENTS. On the Drawing Filter the answer is written by a headless AI that can only look at
2486
+ * pictures, so a PDF is refused — and that has to be on the control BEFORE the message is typed,
2487
+ * not at Send. `paintAttachments` runs when the attachments change; opening the Drawing Filter
2488
+ * changes neither, so a tooltip painted only there keeps the previous surface's wording. Measured
2489
+ * in the browser: the filter reported ready on S-203 while the paperclip still offered PDFs.
2490
+ * `updateSendState` runs on every repaint, including the surface switch, so both call this.
2491
+ */
2492
+ function paintAttachControl() {
2493
+ const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length;
2494
+ const kinds = filterSurface().state === 'off' ? 'image or PDF' : 'a picture';
2495
+ ui.attach.dataset.tip = `Attach ${kinds} · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images in this message`;
2496
+ ui.attach.setAttribute('aria-label', `Attach ${kinds} · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images`);
2497
+ }
2498
+
2499
+ /* #1653: the Steel Model objects selected when a question is sent are attached to it. The pill shows what
2500
+ would go with the next NEW question — never with a follow-up to a running response, never on the Drawing
2501
+ Filter, never in a workflow's conversation — and one click leaves them out until the selection changes. */
2502
+ const MAX_LISTED_SUBJECTS = 200;
2503
+ const MAX_SUBJECT_SAMPLE = 50;
2504
+
2505
+ function subjectsKey(selection) {
2506
+ return selection ? `${selection.source}|${selection.key || selection.items.map((item) => `${item.kind}:${item.id}`).sort().join('\n')}` : '';
2507
+ }
2508
+
2509
+ function composerSelection() {
2510
+ if (!state.chat || state.scope?.owner?.kind !== 'project' || turnIsVisiblyActive()) return null;
2511
+ if (filterSurface().state !== 'off') return null;
2512
+ let selection = null;
2513
+ try { selection = window.flolessLeftPane?.readSelection?.() || null; } catch { selection = null; }
2514
+ if (!selection || selection.source !== 'steel' || !selection.items?.length) return null;
2515
+ if (state.subjectsDismissed && state.subjectsDismissed === subjectsKey(selection)) return null;
2516
+ return selection;
2517
+ }
2518
+
2519
+ /** The selection as the server stores it: up to 200 objects one by one, more as a counted sample. */
2520
+ function subjectsPayload(selection) {
2521
+ if (!selection) return null;
2522
+ const pick = (item) => ({ kind: item.kind, id: item.id, label: item.label });
2523
+ if (selection.total > MAX_LISTED_SUBJECTS) {
2524
+ return { source: selection.source, revision: selection.revision, group: { count: selection.total, sample: selection.items.slice(0, MAX_SUBJECT_SAMPLE).map(pick) } };
2525
+ }
2526
+ return { source: selection.source, revision: selection.revision, items: selection.items.slice(0, MAX_LISTED_SUBJECTS).map(pick) };
2527
+ }
2528
+
2529
+ function subjectLabels(items, total, shown = 3) {
2530
+ const names = items.slice(0, shown).map((item) => item.label || item.id);
2531
+ const more = total - names.length;
2532
+ return more > 0 ? `${names.join(', ')} and ${more} more` : names.join(', ');
2533
+ }
2534
+
2535
+ /** The line under a sent question naming what it was about, or '' — for a listed selection or a counted group. */
2536
+ function subjectsLine(subjects) {
2537
+ if (!subjects || typeof subjects !== 'object') return '';
2538
+ const listed = Array.isArray(subjects.items) ? subjects.items : Array.isArray(subjects.group?.sample) ? subjects.group.sample : [];
2539
+ const count = Array.isArray(subjects.items) ? subjects.items.length : Number(subjects.group?.count) || listed.length;
2540
+ if (!count) return '';
2541
+ return `About ${count} Steel object${count === 1 ? '' : 's'}${listed.length ? `: ${subjectLabels(listed, count)}` : ''}`;
2542
+ }
2543
+
2544
+ // A question was saved with objects: the model editor's object card reads its links again.
2545
+ function subjectLinksSaved(subjects) {
2546
+ if (!subjects) return;
2547
+ try { window.flolessLeftPane?.chatLinksChanged?.(); } catch { /* the card refreshes on its next read */ }
2548
+ }
2549
+
2550
+ function paintSubjectsPill() {
2551
+ const selection = composerSelection();
2552
+ if (!selection) return false;
2553
+ const count = selection.total;
2554
+ const chip = document.createElement('span'); chip.className = 'ai-chat-attachment ai-chat-subjects';
2555
+ const label = button(`${count} object${count === 1 ? '' : 's'} selected`, 'shell.chat-subjects', 'ai-chat-subjects-label');
2556
+ label.dataset.tip = count > MAX_LISTED_SUBJECTS
2557
+ ? `More than ${MAX_LISTED_SUBJECTS} objects are selected, so FloLess attaches them to your next question as one set instead of listing each one.`
2558
+ : `${subjectLabels(selection.items, count, 5)}. Attached to your next question.`;
2559
+ label.setAttribute('aria-label', `${count} Steel Model object${count === 1 ? '' : 's'} selected, attached to your next question`);
2560
+ label.addEventListener('click', () => { announce(label.dataset.tip); });
2561
+ const remove = button('×', 'shell.chat-subjects-remove');
2562
+ remove.setAttribute('aria-label', 'Leave the selected objects out of your next question');
2563
+ remove.dataset.tip = 'Leave out of the next question';
2564
+ remove.addEventListener('click', () => {
2565
+ state.subjectsDismissed = subjectsKey(selection);
2566
+ paintAttachments();
2567
+ ui.input.focus();
2568
+ announce('The selected objects will not be attached to your next question.');
2569
+ });
2570
+ chip.append(label, remove);
2571
+ ui.attachments.append(chip);
2572
+ return true;
2573
+ }
2574
+
1899
2575
  function paintAttachments() {
1900
2576
  ui.attachments.replaceChildren();
1901
- const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length;
1902
- ui.attach.dataset.tip = `Attach image or PDF · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images in this message`;
1903
- ui.attach.setAttribute('aria-label', `Attach image or PDF · ${imageCount} of ${MAX_IMAGES_PER_MESSAGE} images`);
2577
+ const pill = paintSubjectsPill();
2578
+ // paintAttachControl, not the two lines #1653 had here: it says the same thing but asks the
2579
+ // SURFACE what may be attached, so the Drawing Filter reads “Attach a picture” (#1681).
2580
+ paintAttachControl();
1904
2581
  for (const attachment of state.attachments) {
1905
2582
  const chip = document.createElement('span'); chip.className = 'ai-chat-attachment';
1906
2583
  if (attachment.mediaType.startsWith('image/')) {
@@ -1926,7 +2603,7 @@
1926
2603
  });
1927
2604
  chip.append(name, remove); ui.attachments.append(chip);
1928
2605
  }
1929
- ui.attachments.hidden = state.attachments.length === 0;
2606
+ ui.attachments.hidden = state.attachments.length === 0 && !pill;
1930
2607
  }
1931
2608
 
1932
2609
  function selectedModel() {
@@ -2331,7 +3008,7 @@
2331
3008
  // Claude or Codex as "not ready".
2332
3009
  return await request(`/api/chat/providers/${chat.provider}?${ownerQuery()}&chatId=${encodeURIComponent(chat.chatId)}`);
2333
3010
  } catch (error) {
2334
- return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error) };
3011
+ return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error), readFailed: true };
2335
3012
  }
2336
3013
  }
2337
3014
 
@@ -2422,15 +3099,24 @@
2422
3099
  if (!options.preserveDiscoveryDraft) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; }
2423
3100
  clearProviderChoice();
2424
3101
  const selection = ++state.selectionGeneration;
2425
- const exactAnswer = typeof options.answerEventId === 'string' ? options.answerEventId : null;
3102
+ // An Instructor answer, or a question an object card links to (#1653): both open at that one message.
3103
+ const exactQuestion = typeof options.messageEventId === 'string' ? options.messageEventId : null;
3104
+ const exactAnswer = exactQuestion || (typeof options.answerEventId === 'string' ? options.answerEventId : null);
2426
3105
  clearAnswerJump();
2427
3106
  if (!exactAnswer) {
2428
3107
  closeSource(); closePicker();
2429
- state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
2430
- }
3108
+ closeHistoryPanel();
3109
+ }
3110
+ // The provider check below can take seconds, and the conversation already looks open while it
3111
+ // runs, so a person may reopen the history (to rename another row, say) before it ends. What
3112
+ // the late step may still do depends on whether they did: remember the history's opening count
3113
+ // and where focus sits now, and compare both when the check returns (#1646).
3114
+ const historyOpenings = state.historyOpenings;
3115
+ const focusAtStart = document.activeElement;
2431
3116
  const generation = state.scopeGeneration;
2432
3117
  showConversationLoading(chatId);
2433
3118
  setBusy(true);
3119
+ let failure = null;
2434
3120
  try {
2435
3121
  const [chat, snapshot] = await Promise.all([
2436
3122
  request(`/api/chat/conversations/${encodeURIComponent(chatId)}?${ownerQuery()}`),
@@ -2439,16 +3125,23 @@
2439
3125
  if (generation !== state.scopeGeneration || selection !== state.selectionGeneration) return;
2440
3126
  const answerTarget = exactAnswer
2441
3127
  ? renderedAnswerTarget(snapshot.events || [], exactAnswer,
2442
- typeof options.answerTurnId === 'string' ? options.answerTurnId : null)
3128
+ exactQuestion ? null : typeof options.answerTurnId === 'string' ? options.answerTurnId : null,
3129
+ exactQuestion ? 'user-message' : 'assistant-message')
2443
3130
  : null;
2444
3131
  if (exactAnswer && !answerTarget) {
2445
- announce('That Instructor answer is no longer available.');
3132
+ const gone = exactQuestion ? 'That question is no longer in this conversation.' : 'That Instructor answer is no longer available.';
3133
+ announce(gone);
3134
+ // A question is opened from an object card in the model panel, away from the chat's own status line.
3135
+ if (exactQuestion) window.showToast?.(gone, 'info');
2446
3136
  return;
2447
3137
  }
2448
3138
  const [capability, desktop] = await Promise.all([readCapability(chat), readDesktopCapability(chat)]);
2449
3139
  if (generation !== state.scopeGeneration || selection !== state.selectionGeneration) return;
3140
+ // Reopened while this conversation was opening: the person has moved on to the history, so
3141
+ // it stays open — with any rename in it — and focus stays where they put it (#1646).
3142
+ const historyReopened = state.historyOpenings !== historyOpenings;
2450
3143
  closeSource(); closePicker();
2451
- state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
3144
+ if (!historyReopened) closeHistoryPanel();
2452
3145
  state.chat = chat;
2453
3146
  state.events = snapshot.events || [];
2454
3147
  reconcileUnknownFollowupOnSelection(chat);
@@ -2476,17 +3169,28 @@
2476
3169
  }).catch(() => { /* a missed warm-up only means a slower first message */ });
2477
3170
  if (answerTarget) {
2478
3171
  markReadThrough(chat, answerTarget.sequence);
2479
- announce(`Opened Instructor answer in ${state.chat.title}.`);
3172
+ announce(exactQuestion ? `Opened your question in ${state.chat.title}.` : `Opened Instructor answer in ${state.chat.title}.`);
2480
3173
  } else {
2481
3174
  markRead();
2482
- if (options.focus) ui.input.focus();
3175
+ // Only move focus when nothing has taken it since the selection began: the history was not
3176
+ // reopened (checked again here, because applyProviderDefaults awaited another round-trip
3177
+ // after the close above), and focus is still where the selection left it or nowhere at all.
3178
+ const reopenedSinceStart = state.historyOpenings !== historyOpenings;
3179
+ const focusNow = document.activeElement;
3180
+ const focusUntouched = !focusNow || focusNow === document.body || focusNow === focusAtStart;
3181
+ if (options.focus && !reopenedSinceStart && focusUntouched) ui.input.focus();
3182
+ // Focus stayed in the reopened history, so nothing else tells a screen reader it finished.
3183
+ else if (reopenedSinceStart) announce(`Opened ${state.chat.title}.`);
2483
3184
  }
2484
3185
  } catch (error) {
2485
- if (generation === state.scopeGeneration && selection === state.selectionGeneration) {
2486
- report(error, 'Could not open conversation');
2487
- }
3186
+ failure = error;
2488
3187
  }
2489
3188
  finally { if (selection === state.selectionGeneration) setBusy(false); }
3189
+ // Reported AFTER setBusy: its composer refresh rewrites the hint, which erased this sentence the
3190
+ // moment it appeared and left only "Opening conversation…" on screen (#1604).
3191
+ if (failure && generation === state.scopeGeneration && selection === state.selectionGeneration) {
3192
+ report(failure, 'Could not open conversation');
3193
+ }
2490
3194
  }
2491
3195
 
2492
3196
  function reconcileUnknownFollowupOnSelection(chat) {
@@ -2531,21 +3235,27 @@
2531
3235
  return;
2532
3236
  }
2533
3237
  const generation = ++state.scopeGeneration;
3238
+ // An open history-row rename belongs to the list being replaced. End it before the history is
3239
+ // hidden below: hiding the focused field blurs it, and blur must not save a half-typed name
3240
+ // into the conversation the person just navigated away from (#1582).
3241
+ state.historyRename?.abandon();
2534
3242
  if (scopeKey(scope) !== scopeKey(state.scope)) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; state.teklaDraft = null; }
2535
3243
  state.selectionGeneration += 1;
2536
3244
  clearAnswerJump();
2537
3245
  clearLiveStream(true);
2538
3246
  closeSource(); closePicker();
2539
3247
  clearProviderChoice();
3248
+ const scopeChanged = scopeKey(scope) !== scopeKey(state.scope);
2540
3249
  state.scope = scope;
2541
3250
  state.scopeInitialized = true;
2542
- state.chat = null; state.chats = []; state.archivedChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
3251
+ if (scopeChanged) { try { window.flolessLeftPane?.chatLinksChanged?.(); } catch { /* the card refreshes on its next read */ } }
3252
+ state.chat = null; state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
2543
3253
  // A published filter answer still lands in its own project's conversation; reopening it resumes.
2544
3254
  for (const entry of state.filterPending.values()) clearTimeout(entry.timer);
2545
3255
  state.filterPending.clear(); state.filterNotices.clear(); state.filterCardMessages.clear();
2546
3256
  updateOffscreenActivity();
2547
3257
  state.historyFilter = 'all'; state.instructorAnswers = []; state.historyLoading = false; state.historyRequestGeneration += 1;
2548
- state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
3258
+ closeHistoryPanel();
2549
3259
  if (!scope?.owner) { showUnscoped(); return; }
2550
3260
  ui.scope.textContent = scope.label;
2551
3261
  ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
@@ -2555,6 +3265,7 @@
2555
3265
  const result = await request(`/api/chat/conversations?${ownerQuery(scope.owner)}`);
2556
3266
  if (generation !== state.scopeGeneration) return;
2557
3267
  state.chats = result.chats || [];
3268
+ state.unreadableChats = result.unreadableChats || [];
2558
3269
  seedReadCursors(state.chats, scope.owner);
2559
3270
  paintHistory(); paintUnread();
2560
3271
  if (state.chats.length) await selectConversation(state.chats[0].chatId);
@@ -2564,7 +3275,7 @@
2564
3275
  // A history read can fail independently of the selected project (for example while an
2565
3276
  // older, stale conversation is being recovered). Do not erase the scope and disable the
2566
3277
  // whole panel: the user can still start a new conversation in the project that is open.
2567
- state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null;
3278
+ state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null;
2568
3279
  updateOffscreenActivity();
2569
3280
  ui.scope.textContent = scope.label;
2570
3281
  ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
@@ -2623,6 +3334,7 @@
2623
3334
  const result = await request(`/api/chat/conversations?${ownerQuery()}&filter=instructor-answers`);
2624
3335
  if (requestGeneration !== state.historyRequestGeneration || scopeGeneration !== state.scopeGeneration) return;
2625
3336
  state.chats = result.chats || [];
3337
+ state.unreadableChats = result.unreadableChats || [];
2626
3338
  state.instructorAnswers = result.instructorAnswers || [];
2627
3339
  } catch (error) {
2628
3340
  if (requestGeneration === state.historyRequestGeneration) report(error, 'Could not load Instructor answers');
@@ -2683,8 +3395,22 @@
2683
3395
  else ui.history.querySelector('[aria-pressed="true"]')?.focus();
2684
3396
  }
2685
3397
 
3398
+ // Closes the history from anywhere other than its own toggle, and keeps everything toggleHistory
3399
+ // keeps in step: the toggle's aria-expanded (#1641) and the offscreen-activity line. An open row
3400
+ // rename is abandoned first, as loadScope does (#1582): hiding the focused field blurs it, and a
3401
+ // blur must never save a half-typed name. Focus is left alone; each caller decides that.
3402
+ function closeHistoryPanel() {
3403
+ state.historyRename?.abandon();
3404
+ state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
3405
+ ui.historyToggle.setAttribute('aria-expanded', 'false');
3406
+ updateOffscreenActivity();
3407
+ }
3408
+
2686
3409
  function toggleHistory(force, options = {}) {
2687
3410
  const open = force === undefined ? !state.historyOpen : Boolean(force);
3411
+ // Counts every opening, so a conversation still opening in the background can tell the person
3412
+ // reopened the history after it began (#1646).
3413
+ if (open) state.historyOpenings += 1;
2688
3414
  state.historyOpen = open;
2689
3415
  shell.classList.toggle('history-open', open);
2690
3416
  ui.history.hidden = !open;
@@ -2864,12 +3590,19 @@
2864
3590
  const settingUp = Boolean(state.capability?.runtime && state.capability.runtime.state !== 'installed');
2865
3591
  const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
2866
3592
  ui.input.disabled = state.followupSubmitting || !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
2867
- const filterMode = paintFilterComposer().state !== 'off';
2868
3593
  ui.send.disabled = state.loading || state.followupSubmitting || state.filterSending || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
2869
3594
  || (!ui.input.value.trim() && state.attachments.length === 0) || settingUp;
2870
- // Drawing Filter messages carry the filter's own context, never attached files.
2871
- ui.attach.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
2872
- || filterMode;
3595
+ // A Drawing Filter message carries the filter's own context AND whatever pictures the person
3596
+ // attached (#1681). The paperclip used to be disabled here, which is the "I can't add
3597
+ // attachments" in that issue; the only attachment rule left is the one in `filterSendRefusal`,
3598
+ // and it is about the file type, not about the surface.
3599
+ // `state.filterSending` belongs here BECAUSE the shared tooltip below already stamps "wait for it
3600
+ // to appear" on this control: without it the paperclip says blocked and stays clickable, and a
3601
+ // picture attached mid-send is not in the set `sendFilterAi` puts back if the send fails.
3602
+ ui.attach.disabled = state.loading || state.followupSubmitting || state.filterSending || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen;
3603
+ // Repainted here too: this runs on a surface switch, which changes what may be attached without
3604
+ // changing the attachments themselves.
3605
+ paintAttachControl();
2873
3606
  const unknownReason = state.followupUnknownId || hasUnknownFollowup()
2874
3607
  ? 'FloLess could not confirm a follow-up. Review that message before sending or attaching another file.' : null;
2875
3608
  const sendingReason = state.followupSubmitting
@@ -2879,7 +3612,6 @@
2879
3612
  if (unknownReason || sendingReason) control.dataset.blockedReason = unknownReason || sendingReason;
2880
3613
  else delete control.dataset.blockedReason;
2881
3614
  }
2882
- if (filterMode && !unknownReason && !sendingReason) ui.attach.dataset.blockedReason = 'Drawing Filter messages do not include attachments. Attach files from another tab.';
2883
3615
  ui.stop.hidden = !active || Boolean(state.chat?.activeTurn?.local);
2884
3616
  ui.send.hidden = false;
2885
3617
  // Session recovery must remain available even while provider capability discovery is loading
@@ -2935,7 +3667,11 @@
2935
3667
  finally { if (state.draftWrites.get(chatId) === write) state.draftWrites.delete(chatId); }
2936
3668
  }
2937
3669
 
2938
- async function restoreBackgroundDraft(snapshot, text, submissionId) {
3670
+ // The options replace the plain "not sent" words when the caller knows better what happened (a Drawing
3671
+ // Filter message AI did not start on, #1643, which the conversation still shows): `announcement` for
3672
+ // the words coming back, `mergeLabel` and `mergedAnnouncement` when newer typing is kept above them.
3673
+ // A merged draft always asks for a review.
3674
+ async function restoreBackgroundDraft(snapshot, text, submissionId, { announcement, mergeLabel = 'Earlier unsent message:', mergedAnnouncement } = {}) {
2939
3675
  let existing = '';
2940
3676
  if (state.chat?.chatId === snapshot.chatId) {
2941
3677
  if (state.events.some(event => event.type === 'user-message' && event.clientSubmissionId === submissionId)) return;
@@ -2963,15 +3699,15 @@
2963
3699
  existing = state.localDraft.text;
2964
3700
  }
2965
3701
  const merged = Boolean(existing.trim() && existing.trim() !== text.trim());
2966
- if (merged) text = `${existing}\n\nEarlier unsent message:\n${text}`;
3702
+ if (merged) text = `${existing}\n\n${mergeLabel}\n${text}`;
2967
3703
  if (state.chat?.chatId === snapshot.chatId) {
2968
3704
  clearTimeout(state.draftTimer);
2969
3705
  if (ui.input.value !== text) {
2970
3706
  ui.input.value = text;
2971
3707
  autosize(); updateSendState();
2972
3708
  }
2973
- announce(merged ? 'An earlier unsent message was added to your draft. Review it before sending.'
2974
- : 'The message was not sent. Its text is back in your draft.');
3709
+ announce(merged ? mergedAnnouncement || 'An earlier unsent message was added to your draft. Review it before sending.'
3710
+ : announcement || 'The message was not sent. Its text is back in your draft.');
2975
3711
  state.localDraft = { chatId: snapshot.chatId, text };
2976
3712
  }
2977
3713
  state.draftVersions.set(snapshot.chatId, (state.draftVersions.get(snapshot.chatId) || 0) + 1);
@@ -2983,6 +3719,12 @@
2983
3719
 
2984
3720
  function initialTurnDefinitelyRefused(error) {
2985
3721
  return sessionNeedsRenewal(error) || error?.status === 413 || error?.status === 400
3722
+ // `chat-record-unreadable` is deliberately NOT here, though POST /turns reads the conversation
3723
+ // at the start and a refusal there IS provably unsent (#1629). The same code also escapes the
3724
+ // route AFTER the turn is durable and dispatched — listChatEvents and the reply's own readChat
3725
+ // both re-read the record once the user-message event is published — and the browser cannot
3726
+ // tell the two apart. Handing the text back then would send it twice; losing it from the
3727
+ // composer, which is what a torn record has always done, only costs the retype.
2986
3728
  || ['chat-provider-unavailable', 'chat-turn-active', 'chat-turn-settling', 'chat-followup-queued', 'chat-followup-unconfirmed',
2987
3729
  'chat-owner-busy', 'chat-host-busy', 'chat-attachment-scope',
2988
3730
  'chat-root-stale', 'chat-archived'].includes(String(error?.code || ''));
@@ -3020,9 +3762,7 @@
3020
3762
  // linking, starting and polling the request itself.
3021
3763
  // There is no mode to choose: the person just asks or says what to change. Every message is sent as
3022
3764
  // a request that may suggest ticks, and a review card appears only when the answer does.
3023
- const FILTER_PLACEHOLDER = 'Ask about this filter, or say what to change…';
3024
3765
  const FILTER_PENDING = 'AI is reading the filter…';
3025
- const DEFAULT_PLACEHOLDER = ui.input.placeholder;
3026
3766
  const FILTER_NOT_OPEN = 'Open Drawing Filter to use this suggestion.';
3027
3767
  // Mirrors the filter page's own FILTER_AI_UNKNOWN: with no page at all, its records are gone too.
3028
3768
  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.';
@@ -3074,11 +3814,25 @@
3074
3814
  return { state: 'ready', bridge, summary };
3075
3815
  }
3076
3816
 
3077
- /** The composer's only Drawing Filter cue is its placeholder; returns the surface for the caller. */
3817
+ /**
3818
+ * The composer's view of the Drawing Filter surface; returns it for the caller.
3819
+ *
3820
+ * It no longer rewrites the placeholder. One composer, one prompt: owner ruling, Pawel 2026-09-25 —
3821
+ * a second wording here made the same box look like a different box on one screen, for a mode the
3822
+ * person did not choose and cannot see the edges of.
3823
+ *
3824
+ * The mode is still real: Send routes a filter message through the Drawing Filter's own request
3825
+ * path rather than as a normal chat turn — a change request whose answer proposes ticks for the
3826
+ * person to review, run with read-only runtime options. (Not "a read-only question": `sendFilterAi`
3827
+ * hard-codes `kind = 'change'`, and a comment on this screen saying otherwise is how the next
3828
+ * reader gets it backwards.) What still announces it is `paintFloLessContext`'s "Sharing with AI:
3829
+ * Drawing Filter · partial view of <sheet> and its selection" — which is the better cue anyway,
3830
+ * because it NAMES THE SHEET, and it sits directly under the box. (The compose hint does not: its
3831
+ * chain in `clearReport` has no filter branch, and the attach control's blocked reason only speaks
3832
+ * once someone tries to attach. An earlier draft of this comment credited the hint; it was wrong.)
3833
+ */
3078
3834
  function paintFilterComposer() {
3079
- const surface = filterSurface();
3080
- ui.input.placeholder = surface.state === 'off' ? DEFAULT_PLACEHOLDER : FILTER_PLACEHOLDER;
3081
- return surface;
3835
+ return filterSurface();
3082
3836
  }
3083
3837
 
3084
3838
  function filterPendingIn(chatId) {
@@ -3089,15 +3843,42 @@
3089
3843
  return state.events.some((event) => event.type === 'assistant-message' && event.payload?.requestId === requestId);
3090
3844
  }
3091
3845
 
3846
+ /**
3847
+ * The only length limit on a Drawing Filter message, and the same number the server enforces
3848
+ * (`MAX_SUBJECT_CHARS` in `server/instructor-request.ts`).
3849
+ *
3850
+ * It was 300 — short enough that an ordinary question naming two layers was refused, which is the
3851
+ * complaint #1681 opens with. It is deliberately still A limit: the message becomes the request's
3852
+ * subject, and an unbounded field there is its own failure.
3853
+ */
3854
+ const FILTER_MESSAGE_LIMIT = 4000;
3855
+
3092
3856
  /** Why a filter message cannot be sent right now, or null. Checked before the draft is touched. */
3093
3857
  function filterSendRefusal(surface, text) {
3094
3858
  const chat = state.chat;
3095
3859
  if (surface.state !== 'ready') return 'The Drawing Filter is still loading. Wait until its layers appear, then send again. Nothing was sent.';
3096
3860
  if (turnIsVisiblyActive(chat) || chat.activeTurn) return 'Wait for the current AI reply to finish before asking about the filter. Your message was not sent.';
3097
3861
  if (filterPendingIn(chat.chatId)) return 'Wait for the current Drawing Filter answer before sending another. Your message was not sent.';
3098
- if (state.attachments.length) return 'Attachments are not sent with Drawing Filter messages. Remove them to send this message, or send them from another tab.';
3862
+ // Pictures ride along (#1681). A PDF cannot: the AI answering a Drawing Filter message looks at
3863
+ // images handed to it on the command line and has no file access of its own, so a PDF here would
3864
+ // be stored and never opened. Say that plainly rather than accept it and answer around it.
3865
+ const nonImage = state.attachments.find((item) => !String(item.mediaType || '').startsWith('image/'));
3866
+ if (nonImage) {
3867
+ return `“${nonImage.fileName}” can’t be sent with a Drawing Filter message — the AI answering here can only look at pictures. `
3868
+ + 'Attach a screenshot of the page you mean, or ask about it in the main conversation instead. Nothing was sent.';
3869
+ }
3870
+ // A PICTURE ONLY REACHES CODEX. It travels on the command line of the headless run, and a
3871
+ // read-only Claude run has no tool that could open one and a relay that returns text only — so
3872
+ // on a Claude conversation the answer would be written having seen nothing. The run route
3873
+ // refuses this too, but by then a request exists and has to be unwound; the independent QA saw
3874
+ // exactly that, with a queued request and an "attachment ready" composer. Refuse here, before
3875
+ // anything is created.
3876
+ if (state.attachments.length && chat.provider !== 'codex') {
3877
+ return `${providerLabels[chat.provider] || 'This AI'} can’t be shown a picture in a Drawing Filter message. `
3878
+ + 'Remove the picture to send the question on its own, or ask in a conversation with the other AI. Nothing was sent.';
3879
+ }
3099
3880
  // Counted exactly as the filter page counts it, so the two limits can never disagree.
3100
- if (text.length > 300) return 'Shorten your message to 300 characters, then send it again. Nothing was sent.';
3881
+ if (text.length > FILTER_MESSAGE_LIMIT) return `Shorten your message to ${FILTER_MESSAGE_LIMIT} characters, then send it again. Nothing was sent.`;
3101
3882
  return null;
3102
3883
  }
3103
3884
 
@@ -3109,7 +3890,11 @@
3109
3890
  return 'FloLess could not access this answer. Check your sign-in and project access, then send your message again. Nothing changed.';
3110
3891
  }
3111
3892
 
3112
- /** Start the read-only guide run. Resolves 'started', 'unconfirmed' (checking), or { refused: message }. */
3893
+ /**
3894
+ * Start the read-only guide run. Resolves 'started', 'unconfirmed' (checking), or { refused: message }.
3895
+ * `notStarted: true` on a refusal means no AI can have started on it, so its words can be given back;
3896
+ * `runtime` is then the setup status when FloLess setting its AI up was the cause (#1650, #1643).
3897
+ */
3113
3898
  async function startFilterRun(requestId, runtime) {
3114
3899
  const controller = new AbortController();
3115
3900
  const deadline = setTimeout(() => controller.abort(), 15000);
@@ -3123,9 +3908,15 @@
3123
3908
  const detail = await started.json().catch(() => null);
3124
3909
  clearTimeout(deadline);
3125
3910
  if (started.status === 409 && detail?.code === 'running') return 'started';
3911
+ // The run route flags a refusal it made before anything started (#1650, #1643). Definite even as a
3912
+ // 5xx; one without its notice is not trusted, and falls through to the rules below.
3913
+ if (detail?.notStarted === true && typeof detail.notice === 'string' && detail.notice) {
3914
+ return { refused: detail.notice, notStarted: true, runtime: detail.runtime ?? null };
3915
+ }
3126
3916
  if (detail?.code === 'filter-ai-provider-mismatch' && typeof detail.error === 'string') return { refused: detail.error };
3127
3917
  if ((started.status === 409 && !detail) || started.status >= 500) return 'unconfirmed';
3128
- if ([401, 402, 403].includes(started.status)) return { refused: filterAccessFailure(started.status, detail) };
3918
+ // The sign-in and licence check refuses before the route runs, so nothing started either.
3919
+ if ([401, 402, 403].includes(started.status)) return { refused: filterAccessFailure(started.status, detail), notStarted: true };
3129
3920
  // Several refusals land here, each with a different cause, so the sentence names none of them.
3130
3921
  return { refused: 'FloLess could not start AI for this request. Nothing changed. Send it again from AI Chat.' };
3131
3922
  }
@@ -3279,6 +4070,124 @@
3279
4070
  }
3280
4071
  }
3281
4072
 
4073
+ /**
4074
+ * Hand a setup status to this conversation's own setup card (#1650): the card polls it, explains it,
4075
+ * offers Cancel or Try again, and keeps Send locked until the AI is set up. Only for the conversation
4076
+ * that sent the message, while it is still that AI's, and only for a status the card can show.
4077
+ */
4078
+ function adoptRuntimeStatus(snapshot, provider, status) {
4079
+ if (!status || typeof status !== 'object' || !['preparing', 'not-installed', 'failed'].includes(status.state)
4080
+ || !sameChat(snapshot) || !state.capability || state.chat?.provider !== provider) return false;
4081
+ state.capability = { ...state.capability, runtime: status };
4082
+ paintRuntime();
4083
+ return true;
4084
+ }
4085
+
4086
+ /** Why a Drawing Filter message was not sent while its AI is set up. The status decides; without one, no cause is claimed. */
4087
+ function filterSetupSentence(provider, status) {
4088
+ const name = providerLabels[provider] || 'the AI';
4089
+ if (status?.state === 'preparing' || status?.state === 'not-installed') {
4090
+ return `FloLess is setting up ${name}, so this message was not sent. It is back in your draft; send it once setup finishes.`;
4091
+ }
4092
+ 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.`;
4093
+ // No status, a failed call (one that timed out may still have started the setup), or a state this
4094
+ // build cannot name.
4095
+ 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.`;
4096
+ }
4097
+
4098
+ /**
4099
+ * Ask FloLess to set up the conversation's own AI, through the setup card's Retry route (idempotent).
4100
+ * Resolves `{ installed: true }` when it already is, else the sentence to refuse the message with,
4101
+ * having handed the status to the card. It never waits for the setup: the card carries that wait.
4102
+ * `text` is the refused message, which the refusal puts back in the draft.
4103
+ */
4104
+ async function prepareFilterRuntime(snapshot, provider, text) {
4105
+ let status = null;
4106
+ try {
4107
+ status = (await request(`/api/managed-runtimes/${encodeURIComponent(provider)}/prepare`, { method: 'POST', body: '{}', timeoutMs: 10000 }))?.runtime || null;
4108
+ } catch (error) { console.warn('[chat] could not ask FloLess to set up the Drawing Filter AI:', error); }
4109
+ if (status?.state === 'installed') return { installed: true };
4110
+ const sentence = filterSetupSentence(provider, status);
4111
+ // The card's status check repaints the hint every two seconds; the sentence stays there while the
4112
+ // card shows the setup it was refused for and the words are in the draft (filterSetupHint), not only
4113
+ // until the first repaint.
4114
+ if (adoptRuntimeStatus(snapshot, provider, status)) {
4115
+ state.filterSetupNote = { key: runtimeCardKey(snapshot.chatId, status), sentence, text };
4116
+ }
4117
+ return { installed: false, sentence };
4118
+ }
4119
+
4120
+ /**
4121
+ * Read the pictures on the composer into the data URLs `/api/guide` stores beside the request.
4122
+ *
4123
+ * A COPY, ON PURPOSE. The headless run gets its own leased file under the requests directory —
4124
+ * it never reaches into the conversation's attachment store — so the picture the AI was shown
4125
+ * stays exactly the picture that was attached, whatever happens to the chat afterwards.
4126
+ *
4127
+ * Throws a refusal on the first unreadable one rather than sending a shorter list: a message that
4128
+ * quietly carries two of three pictures is answered as if the third never existed.
4129
+ */
4130
+ async function filterAiPictures(attachments, chatId, owner) {
4131
+ const pictures = [];
4132
+ for (const attachment of attachments) {
4133
+ let dataUrl;
4134
+ try {
4135
+ const response = await fetch(
4136
+ `/api/chat/conversations/${encodeURIComponent(chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}?${ownerQuery(owner)}`,
4137
+ { signal: AbortSignal.timeout(20000) });
4138
+ if (!response.ok) throw new Error(`attachment read failed (${response.status})`);
4139
+ const blob = await response.blob();
4140
+ dataUrl = await new Promise((resolve, reject) => {
4141
+ const reader = new FileReader();
4142
+ reader.onerror = () => reject(reader.error || new Error('attachment could not be read'));
4143
+ reader.onload = () => resolve(String(reader.result || ''));
4144
+ reader.readAsDataURL(blob);
4145
+ });
4146
+ } catch (error) {
4147
+ console.error('[chat] a Drawing Filter attachment could not be read:', error);
4148
+ throw filterRefusal(`FloLess could not read “${attachment.fileName}”, so nothing was sent. Attach it again, then send the message.`);
4149
+ }
4150
+ pictures.push({ name: attachment.fileName, dataUrl, role: 'reference' });
4151
+ }
4152
+ return pictures;
4153
+ }
4154
+
4155
+ /**
4156
+ * Drop the composer rows whose bytes are now copied onto the request.
4157
+ *
4158
+ * Local state alone is not enough: reopening the conversation repaints the composer from the
4159
+ * chat's own pending attachments, so a row left behind would come back and be sent twice.
4160
+ */
4161
+ async function discardSentFilterAttachments(attachments, chatId, owner) {
4162
+ const cleared = new Set();
4163
+ const stranded = [];
4164
+ for (const attachment of attachments) {
4165
+ try {
4166
+ await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}`, {
4167
+ method: 'DELETE', timeoutMs: 10000, body: JSON.stringify({ owner }),
4168
+ });
4169
+ cleared.add(attachment.attachmentId);
4170
+ } catch (error) {
4171
+ console.warn('[chat] a sent Drawing Filter attachment was not cleared:', error);
4172
+ stranded.push(attachment.fileName);
4173
+ }
4174
+ }
4175
+ // BOTH LISTS, as the chip's own remove handler does. `state.chat.attachments` is what the
4176
+ // conversation-wide budget counts (ten files, fifty megabytes), so pruning only the composer
4177
+ // would spend that budget on pictures that no longer exist and refuse the next real one.
4178
+ if (state.chat?.chatId === chatId) {
4179
+ state.chat.attachments = (state.chat.attachments || []).filter((item) => !cleared.has(item.attachmentId));
4180
+ }
4181
+ // A row that would not delete is still on the server, and the composer is repainted from the
4182
+ // server on the next refresh — so it comes back and rides the person's NEXT, unrelated message.
4183
+ // They are the only one who can clear it, so say so rather than leaving it in the console.
4184
+ if (stranded.length) {
4185
+ report(filterRefusal(`Your message was sent, but ${stranded.map((name) => `“${name}”`).join(' and ')} `
4186
+ + `${stranded.length > 1 ? 'are' : 'is'} still attached to this conversation. Remove `
4187
+ + `${stranded.length > 1 ? 'them' : 'it'} from the box below so ${stranded.length > 1 ? 'they do' : 'it does'} not go with your next message.`));
4188
+ }
4189
+ }
4190
+
3282
4191
  async function sendFilterAi(surface) {
3283
4192
  const snapshot = captureChat();
3284
4193
  if (!snapshot || state.filterSending) return;
@@ -3296,25 +4205,49 @@
3296
4205
  clearTimeout(state.draftTimer);
3297
4206
  state.localDraft = { chatId: snapshot.chatId, text: '' };
3298
4207
  state.backgroundDrafts.delete(snapshot.chatId);
4208
+ // Captured before the composer is cleared, and put back by the catch below if nothing was sent —
4209
+ // the same contract the words get.
4210
+ const attached = state.attachments.slice();
4211
+ // Set the moment the rows are handed to the server for deletion, so the catch below never offers
4212
+ // back a chip whose record is gone — its preview would 404 and every later send would refuse.
4213
+ let discarded = false;
3299
4214
  ui.input.value = ''; autosize();
4215
+ state.attachments = []; paintAttachments();
3300
4216
  state.filterSending = true; updateSendState();
3301
4217
  let requestId = null;
3302
4218
  let failure = null;
3303
4219
  try {
3304
4220
  await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
3305
- const options = await window.flolessBridge?.readOnlyRequestOptions?.().catch(() => null);
3306
- if (!Array.isArray(options?.found)) {
4221
+ // Decided from what launching this conversation's own AI would see NOW, a read of its own (#1650):
4222
+ // the rows AI Chat was painted from can say "set up" for a copy of FloLess's that has gone since.
4223
+ // It answers only with this conversation's own provider, never a silently substituted one.
4224
+ // The read logs its own network and shape failures; a rejection here is a fault in the bridge.
4225
+ const launch = await window.flolessBridge?.filterRuntimeLaunch?.(chat.provider).catch((error) => {
4226
+ console.error('[chat] the Drawing Filter could not read which AI can start:', error);
4227
+ return null;
4228
+ });
4229
+ if (!launch || launch.readiness === 'unchecked') {
3307
4230
  throw filterRefusal('FloLess could not check which AI can answer Drawing Filter messages. Try again in a moment. Nothing was sent.');
3308
4231
  }
3309
- // Answer only with this conversation's own provider, never a silently substituted one.
3310
- if (!options.found.some((runtime) => runtime?.id === chat.provider)) {
4232
+ if (launch.readiness === 'setup') {
4233
+ // FloLess has to set its own copy up first. Nothing is created: the setup starts, this
4234
+ // conversation's setup card shows it and keeps Send locked until it lands, and the words go back.
4235
+ const setup = await prepareFilterRuntime(snapshot, chat.provider, text);
4236
+ if (!setup.installed) throw filterRefusal(setup.sentence);
4237
+ // It finished between the read and the prepare: send as usual.
4238
+ } else if (launch.readiness !== 'ready') {
3311
4239
  throw filterRefusal(`${providerLabels[chat.provider] || 'This AI'} cannot answer Drawing Filter messages on this computer yet. Check it in Integrations, or start a conversation with the other provider. Nothing was sent.`);
3312
4240
  }
3313
4241
  // The promise belongs to the filter page. A page thrown away mid-request never settles it, so
3314
4242
  // the chat keeps its own deadline rather than leaving Send blocked in every conversation.
4243
+ const pictures = attached.length ? await filterAiPictures(attached, snapshot.chatId, snapshot.scope.owner) : [];
3315
4244
  const created = await Promise.race([
3316
- surface.bridge.createRequest(kind, text),
3317
- new Promise((resolve) => { setTimeout(resolve, 20000, { ok: false, message: FILTER_CREATE_TIMEOUT }); }),
4245
+ surface.bridge.createRequest(kind, text, pictures),
4246
+ // ONE DEADLINE, and it must not be shorter than the filter page's own: that page waits 60s
4247
+ // when pictures ride in the body (they are megabytes, not a few hundred bytes of narration).
4248
+ // Racing it at 20s declared failure while the request was still being written, leaving a real
4249
+ // request in Requests while the composer invited a retry that would duplicate it.
4250
+ new Promise((resolve) => { setTimeout(resolve, pictures.length ? 60000 : 20000, { ok: false, message: FILTER_CREATE_TIMEOUT }); }),
3318
4251
  ]);
3319
4252
  if (!created?.ok) {
3320
4253
  throw filterRefusal([401, 402, 403].includes(created?.status)
@@ -3372,19 +4305,52 @@
3372
4305
  void writeChatDraft(snapshot.chatId, snapshot.scope.owner, draft)
3373
4306
  .catch((error) => { if (sameChat(snapshot)) report(error, 'Draft was not saved'); });
3374
4307
  }
4308
+ // The bytes are on the request now, so the composer rows have done their job.
3375
4309
  const entry = { requestId, chatId: snapshot.chatId, kind, appId: created.request.appId || '', project: created.request.project || '', failures: 0, note: '' };
3376
4310
  state.filterPending.set(requestId, entry);
3377
4311
  state.filterNotices.delete(requestId);
3378
4312
  // Start AI first, so nothing between the link and the run can leave a linked request unstarted.
3379
4313
  const started = await startFilterRun(requestId, chat.provider);
3380
4314
  await mergeFilterEvents(snapshot.chatId);
3381
- if (started?.refused) { finishFilterPending(entry, started.refused); return; }
4315
+ if (started?.refused) {
4316
+ finishFilterPending(entry, started.refused);
4317
+ if (started.notStarted) {
4318
+ // Nothing started, so the words come back to the draft; the conversation also keeps them, with
4319
+ // the notice under them. The setup card shows when FloLess setting its AI up was the cause,
4320
+ // first: it announces itself, and the live region keeps only its last line, so that line is the
4321
+ // whole notice (what happened, why, what next) and then where the words are. The message is in
4322
+ // the conversation, so a merge never calls it unsent. A refusal that is not flagged (another
4323
+ // owner's message) or a lost reply gives nothing back.
4324
+ adoptRuntimeStatus(snapshot, chat.provider, started.runtime);
4325
+ await restoreBackgroundDraft(snapshot, text, submissionId, {
4326
+ announcement: `${started.refused} Its text is back in your draft.`,
4327
+ mergeLabel: 'Earlier message AI did not start on:',
4328
+ mergedAnnouncement: `${started.refused} Its text was added to your draft. Review it before sending.`,
4329
+ });
4330
+ }
4331
+ return;
4332
+ }
4333
+ // The bytes are on the request AND the run is under way, so the composer rows have done their
4334
+ // job. Deliberately after `startFilterRun`: a refusal above gives the pictures back with the
4335
+ // words, which it could not do once these rows are gone.
4336
+ if (attached.length) { discarded = true; await discardSentFilterAttachments(attached, snapshot.chatId, snapshot.scope.owner); }
3382
4337
  if (started === 'unconfirmed') entry.note = 'Checking whether AI started…';
3383
4338
  announce(FILTER_PENDING);
3384
4339
  if (sameChat(snapshot)) paintEvents({ forceBottom: true });
3385
4340
  scheduleFilterPoll(entry, 0);
3386
4341
  } catch (error) {
3387
4342
  failure = error;
4343
+ // Nothing was sent, so the pictures go back to the composer with the words — but ONLY while
4344
+ // their server records still exist. Several awaits run after the discard (the run start, the
4345
+ // event merge, a refusal's own restore), and a throw in any of them lands here; handing back
4346
+ // deleted rows would render chips whose previews 404 and make every later send refuse.
4347
+ // MERGED, not assigned: a second tab's row can reach this state, and overwriting would make it
4348
+ // disappear from the composer with nothing said.
4349
+ if (attached.length && !discarded && sameChat(snapshot)) {
4350
+ const returning = new Set(attached.map((item) => item.attachmentId));
4351
+ state.attachments = [...attached, ...state.attachments.filter((item) => !returning.has(item.attachmentId))];
4352
+ paintAttachments();
4353
+ }
3388
4354
  await restoreBackgroundDraft(snapshot, text, submissionId);
3389
4355
  } finally {
3390
4356
  state.filterSending = false;
@@ -3579,7 +4545,18 @@
3579
4545
  // normal turn, not even while the filter page is still loading.
3580
4546
  const filter = filterSurface();
3581
4547
  if (filter.state !== 'off') { await sendFilterAi(filter); return; }
3582
- if (turnIsVisiblyActive() && !state.chat.activeTurn?.local) { await sendFollowup(); return; }
4548
+ // Decided once, at the click, from what the pill showed: a follow-up that falls back to a new turn below
4549
+ // must not attach objects the person was never shown (#1653).
4550
+ const subjects = subjectsPayload(composerSelection());
4551
+ const subjectsField = subjects ? { subjects } : {};
4552
+ if (turnIsVisiblyActive() && !state.chat.activeTurn?.local) {
4553
+ const followup = await sendFollowup();
4554
+ if (followup?.outcome !== 'turn-ended') return;
4555
+ // #1616: the response finished while this follow-up was on its way, so the server refused it
4556
+ // before saving anything. Re-read the conversation and, if it is now idle and the composer still
4557
+ // holds exactly that message, send it once as a new turn instead of asking for a second click.
4558
+ if (!(await resendAfterTurnEnded(followup))) return;
4559
+ }
3583
4560
  const snapshot = captureChat();
3584
4561
  if (!snapshot) return;
3585
4562
  // Bind a carried-over Tekla library first; a refused binding keeps the message unsent.
@@ -3594,7 +4571,7 @@
3594
4571
  const optimisticEvent = {
3595
4572
  eventId: `local:${clientSubmissionId}`, sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
3596
4573
  chatId, turnId: clientSubmissionId, clientSubmissionId, providerItemId: null, type: 'user-message',
3597
- payload: { text, attachmentIds }, createdAt: new Date().toISOString(), optimistic: true,
4574
+ payload: { text, attachmentIds, ...subjectsField }, createdAt: new Date().toISOString(), optimistic: true,
3598
4575
  };
3599
4576
  clearTimeout(state.draftTimer);
3600
4577
  state.localDraft = { chatId, text: '' };
@@ -3613,10 +4590,11 @@
3613
4590
  // The server alone appends this context to the provider copy. The submitted text and
3614
4591
  // durable transcript must remain exactly what the user typed.
3615
4592
  owner: snapshot.scope.owner, clientSubmissionId, text, displayText: text, uiContext, attachmentIds,
3616
- modifying: previousChat.settings.permissionProfile !== 'read-only',
4593
+ modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField,
3617
4594
  }),
3618
4595
  });
3619
- if (!sameChat(snapshot)) return;
4596
+ if (!sameChat(snapshot)) return void subjectLinksSaved(subjects);
4597
+ subjectLinksSaved(subjects);
3620
4598
  state.pendingSubmissionId = null;
3621
4599
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
3622
4600
  state.chat = result.chat;
@@ -3638,6 +4616,29 @@
3638
4616
  } finally { if (sameChat(snapshot)) { setBusy(false); updateSendState(); } }
3639
4617
  }
3640
4618
 
4619
+ /**
4620
+ * A follow-up refused with `chat-turn-stale` was never saved (the route answers `chat-followup-unknown`
4621
+ * for anything it did save), so sending the same text as a new turn cannot duplicate it. Send stays
4622
+ * disabled while the conversation is re-read, and the new turn happens at most once: it goes ahead
4623
+ * only when the refreshed chat is idle and the draft is unchanged: the same text, and the same files,
4624
+ * since the re-read replaces the composer's files with the server's list. It also needs Send to be
4625
+ * usable, which already rules out recovery, an unconfirmed message, an upload and a provider still
4626
+ * being set up. Otherwise the original notice is shown and the draft stays for the user to decide.
4627
+ */
4628
+ async function resendAfterTurnEnded({ snapshot, text, attachmentIds, error }) {
4629
+ state.followupSubmitting = true;
4630
+ updateSendState();
4631
+ try { await refreshConversation(snapshot.chatId); }
4632
+ finally { state.followupSubmitting = false; }
4633
+ if (!sameChat(snapshot)) return false;
4634
+ updateSendState();
4635
+ if (!turnIsVisiblyActive() && !ui.send.disabled
4636
+ && ui.input.value.trim() === text
4637
+ && JSON.stringify(state.attachments.map((item) => item.attachmentId)) === JSON.stringify(attachmentIds)) return true;
4638
+ report(error, '');
4639
+ return false;
4640
+ }
4641
+
3641
4642
  function followupDefinitelyRefused(error) {
3642
4643
  // Session rejection and body-size rejection happen before the route can save a row.
3643
4644
  return ['chat-followup-refused', 'chat-followup-save-failed'].includes(String(error?.code || ''))
@@ -3658,6 +4659,7 @@
3658
4659
  const clientSubmissionId = crypto.randomUUID();
3659
4660
  const previousAttachments = state.attachments;
3660
4661
  let failedDelivery = null;
4662
+ let outcome = null;
3661
4663
  const optimisticEvent = {
3662
4664
  eventId: `local:${clientSubmissionId}`,
3663
4665
  sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
@@ -3731,7 +4733,11 @@
3731
4733
  ui.input.value = text; autosize(); paintAttachments(); paintEvents();
3732
4734
  if (definitiveRefusal) saveDraftSoon();
3733
4735
  else state.localDraft = { chatId: snapshot.chatId, text };
3734
- failedDelivery = { error, prefix: definitiveRefusal ? '' : 'Could not confirm the follow-up' };
4736
+ // The response ended before this arrived (#1616). sendTurn resends it as a new turn, and
4737
+ // shows this refusal only if it cannot.
4738
+ if (definitiveRefusal && error?.code === 'chat-followup-refused' && error?.reason === 'chat-turn-stale') {
4739
+ outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, error };
4740
+ } else failedDelivery = { error, prefix: definitiveRefusal ? '' : 'Could not confirm the follow-up' };
3735
4741
  } finally {
3736
4742
  state.followupSubmitting = false;
3737
4743
  if (sameChat(snapshot)) {
@@ -3740,6 +4746,7 @@
3740
4746
  if (document.activeElement === document.body || document.activeElement === ui.send) ui.input.focus();
3741
4747
  }
3742
4748
  }
4749
+ return outcome;
3743
4750
  }
3744
4751
 
3745
4752
  async function resolveUnknownFollowup(clientSubmissionId) {
@@ -3876,6 +4883,7 @@
3876
4883
  const chatId = snapshot.chatId;
3877
4884
  ui.refresh.disabled = true;
3878
4885
  announce('Refreshing this chat session…');
4886
+ let failure = null;
3879
4887
  try {
3880
4888
  // Re-read before stopping: the browser can retain an old activeTurn after a server restart.
3881
4889
  // That avoids sending a redundant stop for a response the durable conversation already completed.
@@ -3892,8 +4900,10 @@
3892
4900
  await selectConversation(chatId, { focus: false });
3893
4901
  if (!sameChat(snapshot)) return;
3894
4902
  announce('Chat session refreshed.');
3895
- } catch (error) { if (sameChat(snapshot)) report(error, 'Could not refresh this chat session'); }
4903
+ } catch (error) { failure = error; }
3896
4904
  finally { if (sameChat(snapshot)) { ui.refresh.disabled = false; updateSendState(); } }
4905
+ // After updateSendState, which rewrites the composer hint and used to erase this sentence (#1604).
4906
+ if (failure && sameChat(snapshot)) report(failure, 'Could not refresh this chat session');
3897
4907
  }
3898
4908
 
3899
4909
  async function endRecovery() {
@@ -3966,7 +4976,7 @@
3966
4976
  }
3967
4977
  }
3968
4978
 
3969
- async function decideApproval(decision) {
4979
+ async function decideApproval(decision, allowanceRevision) {
3970
4980
  const approval = state.chat?.pendingApproval;
3971
4981
  if (!approval) return;
3972
4982
  const snapshot = captureChat();
@@ -3981,11 +4991,13 @@
3981
4991
  announce('Applying your choice…');
3982
4992
  try {
3983
4993
  await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/approvals/${encodeURIComponent(approvalId)}`, {
3984
- method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, decision }),
4994
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, decision,
4995
+ ...(decision === 'allow-chat' ? { allowanceRevision } : {}) }),
3985
4996
  });
3986
4997
  if (!sameChat(snapshot)) return;
3987
4998
  announce(decision === 'allow-request' ? 'Access auto-approval is on for this request.'
3988
- : decision === 'allow' ? 'Approved once.' : 'Action denied.');
4999
+ : decision === 'allow-chat' ? 'Tekla reads are allowed for this chat. Revoke them from the Tekla box above the message.'
5000
+ : decision === 'allow' ? 'Approved once.' : 'Action denied.');
3989
5001
  await refreshConversation(snapshot.chatId, false);
3990
5002
  } catch (error) {
3991
5003
  if (!sameChat(snapshot)) return;
@@ -4029,6 +5041,28 @@
4029
5041
  });
4030
5042
  }
4031
5043
 
5044
+ /**
5045
+ * Why these files cannot be attached on the surface the person is on, or null.
5046
+ *
5047
+ * REFUSED AT THE CHOOSER, not at Send. The AI answering a Drawing Filter message is handed
5048
+ * pictures on a command line and has no way to open a document, so a PDF attached there could
5049
+ * only be uploaded, counted against the conversation's budget, and then refused after the whole
5050
+ * message had been written around it. `paintAttachControl` already says "Attach a picture" on that
5051
+ * surface; this is the half that makes the control's word good.
5052
+ *
5053
+ * A NAMED FUNCTION rather than an inline block, because `attachFiles` is held to a guard that
5054
+ * requires its `captureChat()` and `sameChat(snapshot)` to stay within reach of each other — the
5055
+ * ownership pattern every in-flight action follows. Inlining this pushed them apart and turned
5056
+ * that guard red, which is the guard doing its job.
5057
+ */
5058
+ function filterAttachRefusal(incoming) {
5059
+ if (filterSurface().state === 'off') return null;
5060
+ const document = incoming.find((file) => !String(file.type || '').startsWith('image/'));
5061
+ if (!document) return null;
5062
+ return `“${document.name}” can’t be sent with a Drawing Filter message — the AI answering here can only look at pictures. `
5063
+ + 'Attach a screenshot of the page you mean, or ask about it in the main conversation instead. Nothing was attached.';
5064
+ }
5065
+
4032
5066
  async function attachFiles(files) {
4033
5067
  if (!state.chat || state.chat.activeTurn?.local || state.chat.state === 'recovery' || state.followupSubmitting || state.followupUnknownId || hasUnknownFollowup()) return;
4034
5068
  const snapshot = captureChat();
@@ -4039,6 +5073,8 @@
4039
5073
  // an image, selecting that same file again must fire a fresh change event.
4040
5074
  ui.file.value = '';
4041
5075
  if (incoming.some((file) => !allowedTypes.has(file.type))) { report(new Error('Attach a PNG, JPEG, WebP, or PDF')); return; }
5076
+ const filterRefused = filterAttachRefusal(incoming);
5077
+ if (filterRefused) { report(filterRefusal(filterRefused)); return; }
4042
5078
  const imageCount = state.attachments.filter((attachment) => attachment.mediaType.startsWith('image/')).length
4043
5079
  + incoming.filter((file) => file.type.startsWith('image/')).length;
4044
5080
  if (imageCount > MAX_IMAGES_PER_MESSAGE) {
@@ -4079,6 +5115,15 @@
4079
5115
  }
4080
5116
  }
4081
5117
 
5118
+ // The background tick. It skips while the previous list is still loading, never stacking one behind
5119
+ // it (#1604): stacked polls hold the browser's few connections to FloLess, and the conversation
5120
+ // itself then cannot load.
5121
+ async function pollChatsTick() {
5122
+ if (state.chatPollInFlight) return;
5123
+ state.chatPollInFlight = true;
5124
+ try { await pollChats(); } finally { state.chatPollInFlight = false; }
5125
+ }
5126
+
4082
5127
  async function pollChats() {
4083
5128
  if (!state.scope || document.hidden) return;
4084
5129
  const scope = state.scope;
@@ -4101,6 +5146,7 @@
4101
5146
  }
4102
5147
  if (!sameScope(scope, generation)) return;
4103
5148
  state.chats = result.chats || [];
5149
+ state.unreadableChats = result.unreadableChats || [];
4104
5150
  const active = state.chats.find((item) => item.chatId === state.chat?.chatId);
4105
5151
  if (active && state.chat) {
4106
5152
  // An event-stream completion can win the race against this list request. Never let a
@@ -4110,13 +5156,16 @@
4110
5156
  const fetchedSequence = Number(active.lastEventSequence) || 0;
4111
5157
  if (fetchedSequence >= knownSequence) Object.assign(state.chat, active);
4112
5158
  }
5159
+ // A Tekla read allowance granted or revoked in another window changes only the chat record,
5160
+ // never the event stream: this poll is how the Tekla box and any open card learn of it.
5161
+ paintTeklaChip();
4113
5162
  // SSE delivers messages immediately, while this poll is what confirms that the provider has
4114
5163
  // finished. Keep the Rename chat control in step with that durable active-turn state.
4115
5164
  ui.rename.hidden = !state.chat || Boolean(state.chat.activeTurn) || Boolean(state.chat.archivedAt);
4116
5165
  // Polling can clear activeTurn after the feed was painted by SSE. Repaint the feed
4117
5166
  // so a completed turn removes any stale live activity indicator. With no conversation
4118
5167
  // selected the feed is the Claude/Codex chooser, which a repaint would erase.
4119
- paintHistory(); paintUnread();
5168
+ paintHistory(); paintUnread(); paintUnreadableNotice();
4120
5169
  // A sign-in OR a sign-OUT made from Integrations or from the user's own terminal changes who
4121
5170
  // answers, and nothing else re-reads it — the row would keep naming the old account for the
4122
5171
  // whole conversation. Use the cheap runtimes read (no provider launch, 10 s server cache)
@@ -4151,11 +5200,37 @@
4151
5200
  }
4152
5201
  if (!sameScope(scope, generation)) return;
4153
5202
  }
5203
+ await recheckManagedCopy(scope, generation);
5204
+ if (!sameScope(scope, generation)) return;
4154
5205
  if (state.chat) { paintSettings(); paintRecovery(); paintApproval(); paintEvents(); updateSendState(); }
4155
5206
  if (state.historyOpen && state.historyFilter === 'instructor-answers') refreshInstructorAnswers();
4156
5207
  } catch { /* SSE or the next poll will recover */ }
4157
5208
  }
4158
5209
 
5210
+ // #1657: FloLess's own copy of this conversation's AI can be moved away, or start re-installing, while
5211
+ // the conversation is open — and nothing else re-reads the capability, so the chat kept an enabled
5212
+ // Send and no setup card. The managed-runtimes read is cheap (no CLI launch). Only when this AI's copy
5213
+ // CHANGES into a state that is not installed is the capability re-read; the server re-checks that copy
5214
+ // on every read, so the answer carries the setup status the card is painted from. Once the card is up,
5215
+ // its own runtime poll takes over (and re-reads the capability when setup finishes).
5216
+ async function recheckManagedCopy(scope, generation) {
5217
+ const chat = state.chat;
5218
+ if (!chat || !state.capability || state.capability.runtime) return;
5219
+ let body;
5220
+ try { body = await request('/api/managed-runtimes', { timeoutMs: 10000 }); } catch { return; }
5221
+ if (!sameScope(scope, generation) || state.chat?.chatId !== chat.chatId) return;
5222
+ const row = (body?.runtimes || []).find((entry) => entry?.runtime === chat.provider);
5223
+ if (!row) return;
5224
+ const seen = `${chat.chatId}:${row.state}`;
5225
+ if (row.state === 'installed' || row.state === 'unsupported-platform') { state.managedCopySeen = seen; return; }
5226
+ if (state.managedCopySeen === seen) return;
5227
+ await loadCapability();
5228
+ if (!sameScope(scope, generation) || state.chat?.chatId !== chat.chatId) return;
5229
+ // Only an answer the server gave settles this state: a failed read is tried again on the next tick.
5230
+ if (!state.capability?.readFailed) state.managedCopySeen = seen;
5231
+ paintRuntime();
5232
+ }
5233
+
4159
5234
  function refreshActivity() {
4160
5235
  paintConversation();
4161
5236
  }
@@ -4177,6 +5252,8 @@
4177
5252
  paintHistory(); paintUnread();
4178
5253
  }
4179
5254
 
5255
+ // Longer than the server's capability-check bound (CAPABILITY_PROBE_TIMEOUT_MS, 12 s) plus its locks.
5256
+ const REQUEST_START_TIMEOUT_MS = 30000;
4180
5257
  async function startRequest(requestId, provider, mode = 'start') {
4181
5258
  if (!state.scope?.owner) throw new Error('Open the Request’s project or workflow before starting its chat.');
4182
5259
  if (provider !== 'claude' && provider !== 'codex') throw new Error('Choose Claude or Codex for this chat.');
@@ -4188,8 +5265,12 @@
4188
5265
  }
4189
5266
  const currentChatId = state.chat && state.chat.provider === provider && !state.chat.activeTurn
4190
5267
  && !state.chat.archivedAt && state.chat.state !== 'recovery' ? state.chat.chatId : undefined;
5268
+ // Starting a Request waits for the AI's capability check (up to 12 s on the server, longer when
5269
+ // it first launches a copy FloLess has only just set up), so a shorter wait here reported
5270
+ // "Couldn't start" for a start that went on to succeed (#1607 QA). The Requests list says
5271
+ // "Still opening…" after 4 s, so the longer wait is not a silent one.
4191
5272
  const result = await request(`/api/chat/requests/${encodeURIComponent(requestId)}/start`, {
4192
- method: 'POST', timeoutMs: 10000,
5273
+ method: 'POST', timeoutMs: REQUEST_START_TIMEOUT_MS,
4193
5274
  body: JSON.stringify({ provider, mode, chatId: currentChatId, expectedOwner: scope.owner }),
4194
5275
  });
4195
5276
  if (!sameScope(scope, generation)) {
@@ -4210,15 +5291,20 @@
4210
5291
  return result;
4211
5292
  }
4212
5293
 
4213
- async function openConversation(chatId) {
5294
+ async function openConversation(chatId, options = {}) {
4214
5295
  await refreshScope();
4215
5296
  if (!state.scope?.owner) throw new Error('Open this conversation’s project or workflow, then try again.');
5297
+ // An object card names its project; a conversation is only ever asked for in that project's scope (#1653).
5298
+ if (typeof options.projectId === 'string' && (state.scope.owner.kind !== 'project' || state.scope.owner.projectId !== options.projectId)) {
5299
+ throw new Error('Open this project in Workspaces to see that conversation.');
5300
+ }
4216
5301
  window.flolessBridge?.revealAiChat?.();
4217
5302
  ui.tab.click();
4218
5303
  const listed = await request(`/api/chat/conversations?${ownerQuery()}`);
4219
5304
  state.chats = listed.chats || [];
4220
5305
  paintHistory(); paintUnread();
4221
- await selectConversation(chatId, { focus: true, replaceProviderChoice: true });
5306
+ const messageEventId = typeof options.messageEventId === 'string' ? options.messageEventId : undefined;
5307
+ await selectConversation(chatId, { focus: !messageEventId, replaceProviderChoice: true, ...(messageEventId ? { messageEventId } : {}) });
4222
5308
  }
4223
5309
 
4224
5310
  const TEKLA_OPERATION = 'Tekla.Structures.Model.Model.GetInfo().ModelName';
@@ -4239,7 +5325,7 @@
4239
5325
  if (!node) return;
4240
5326
  const chat = state.chat;
4241
5327
  const draft = teklaDraftForChat(chat);
4242
- const bound = chat?.teklaModelRead || null;
5328
+ const bound = currentTeklaBinding(chat);
4243
5329
  const library = draft?.library || bound;
4244
5330
  if (!chat || !library) {
4245
5331
  if (!node.hidden || node.childElementCount) { node.replaceChildren(); node.hidden = true; delete node.dataset.key; }
@@ -4248,7 +5334,12 @@
4248
5334
  const status = draft ? draft.status : 'bound';
4249
5335
  const frozen = !draft && teklaBindingFrozen(chat);
4250
5336
  const error = draft?.error || (state.teklaRemoveError?.chatId === chat.chatId ? state.teklaRemoveError.message : null);
4251
- const key = [chat.chatId, library.sourcePath, library.hostVersion, status, frozen, error || ''].join('|');
5337
+ const reads = teklaReadsCopy(library.operations);
5338
+ // A standing allowance exists only on the server's bound record, never on a local draft.
5339
+ const allowed = !draft && Boolean(bound?.allowedForChat);
5340
+ const revoking = allowed && state.teklaRevokingChatId === chat.chatId;
5341
+ const key = [chat.chatId, library.sourcePath, library.hostVersion, reads, status, frozen, error || '',
5342
+ allowed, revoking, teklaAllowanceRevision(bound)].join('|');
4252
5343
  // Keep the same Remove button across polls so keyboard focus survives a repaint.
4253
5344
  if (node.dataset.key === key && !node.hidden) return;
4254
5345
  node.dataset.key = key;
@@ -4259,8 +5350,14 @@
4259
5350
  const copy = document.createElement('span'); copy.className = 'ai-chat-tekla-chip-copy';
4260
5351
  copy.id = `chat-tekla-context-copy-${chat.chatId}`;
4261
5352
  const lead = document.createElement('strong'); lead.textContent = `Tekla ${library.hostVersion} model library`;
4262
- copy.append(lead, document.createTextNode(' · Chat may ask to read the open model name — FloLess asks you first and checks live each time'));
4263
- if (status === 'bound') {
5353
+ copy.append(lead, document.createTextNode(allowed
5354
+ ? ` · Chat may ask to read ${reads} — FloLess checks live each time and shows every result`
5355
+ : ` · Chat may ask to read ${reads} — FloLess asks you first and checks live each time`));
5356
+ if (allowed) {
5357
+ const pill = document.createElement('span'); pill.className = 'ai-chat-tekla-allowed';
5358
+ pill.textContent = 'Allowed for this chat';
5359
+ copy.append(document.createTextNode(' '), pill);
5360
+ } else if (status === 'bound') {
4264
5361
  const suffix = document.createElement('span'); suffix.className = 'ai-chat-tekla-chip-state';
4265
5362
  suffix.textContent = ' · added to this chat';
4266
5363
  copy.append(suffix);
@@ -4282,6 +5379,17 @@
4282
5379
  remove.addEventListener('click', () => { void removeTeklaChip(); });
4283
5380
  chip.append(remove);
4284
5381
  }
5382
+ if (allowed) {
5383
+ const revoke = button(revoking ? 'Revoking…' : 'Revoke', 'shell.chat-tekla-allowance-revoke', 'ai-chat-tekla-remove');
5384
+ revoke.setAttribute('aria-label', 'Revoke allowing Tekla reads in this chat');
5385
+ revoke.setAttribute('aria-describedby', copy.id);
5386
+ revoke.dataset.tip = 'Chat will ask you again before each Tekla read. A read already running may finish.';
5387
+ revoke.disabled = revoking;
5388
+ revoke.setAttribute('aria-busy', String(revoking));
5389
+ if (revoking) revoke.dataset.blockedReason = 'FloLess is revoking this permission.';
5390
+ revoke.addEventListener('click', () => { void revokeTeklaAllowance(); });
5391
+ chip.append(revoke);
5392
+ }
4285
5393
  node.append(chip);
4286
5394
  if (error) {
4287
5395
  const reason = document.createElement('p'); reason.className = 'ai-chat-tekla-error';
@@ -4329,6 +5437,94 @@
4329
5437
  }
4330
5438
  }
4331
5439
 
5440
+ // Ends this chat's standing Tekla read allowance. Nothing to confirm: it only removes permission.
5441
+ async function revokeTeklaAllowance() {
5442
+ const chat = state.chat;
5443
+ const snapshot = captureChat();
5444
+ // Revoke is idempotent on the server, so a click always asks it: a local view that already reads
5445
+ // "not allowed" must never turn Revoke into a silent no-op while the server still allows reads.
5446
+ if (!chat?.teklaModelRead || !snapshot || state.teklaRevokingChatId === chat.chatId) return;
5447
+ state.teklaRemoveError = null;
5448
+ state.teklaRevokingChatId = chat.chatId;
5449
+ paintTeklaChip();
5450
+ try {
5451
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/tekla-model-read/allowance/revoke`, {
5452
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner }),
5453
+ });
5454
+ if (!sameChat(snapshot)) return;
5455
+ // Only the server's own record, with no allowance left, may say it ended.
5456
+ const updated = result?.chat;
5457
+ if (!updated || updated.chatId !== snapshot.chatId || updated.teklaModelRead?.allowedForChat) {
5458
+ state.teklaRemoveError = { chatId: snapshot.chatId, message: 'FloLess could not confirm that Tekla reads will ask again. Try Revoke again.' };
5459
+ return;
5460
+ }
5461
+ state.chat = { ...state.chat, teklaModelRead: updated.teklaModelRead };
5462
+ currentTeklaBinding(state.chat);
5463
+ announce('Tekla reads will ask you again in this chat.');
5464
+ } catch (error) {
5465
+ if (!sameChat(snapshot)) return;
5466
+ state.teklaRemoveError = { chatId: snapshot.chatId, message: errorMessage(error) };
5467
+ } finally {
5468
+ if (state.teklaRevokingChatId === snapshot.chatId) state.teklaRevokingChatId = null;
5469
+ if (sameChat(snapshot)) {
5470
+ const hadFocus = ui.teklaChip?.contains(document.activeElement);
5471
+ paintTeklaChip();
5472
+ // The Revoke button is gone: keep focus in the Tekla box instead of dropping it to the page.
5473
+ if (hadFocus || document.activeElement === document.body) {
5474
+ const target = ui.teklaChip?.querySelector('[data-command-id="shell.chat-tekla-allowance-revoke"]')
5475
+ || ui.teklaChip?.querySelector('.ai-chat-tekla-chip-copy');
5476
+ if (target && !target.matches('button')) target.setAttribute('tabindex', '-1');
5477
+ target?.focus();
5478
+ }
5479
+ }
5480
+ }
5481
+ }
5482
+
5483
+ // A pending approval that may be allowed for the whole chat: a Tekla read the bound library permits.
5484
+ function teklaAllowableApproval(approval) {
5485
+ const binding = currentTeklaBinding(state.chat);
5486
+ const tool = approval?.tool ?? state.events?.find((event) => event.type === 'approval-requested'
5487
+ && event.payload?.approvalId === approval?.approvalId)?.payload?.tool;
5488
+ return Boolean(binding && approvalIsExplicitOnly(approval) && typeof tool === 'string'
5489
+ && tool.startsWith('floless_tekla_') && !teklaDraftForChat(state.chat));
5490
+ }
5491
+ // The chat's Tekla binding, never older than one this page has already seen. A poll that left before
5492
+ // a grant or revoke can land after it; the allowance revision only ever rises for one binding, so the
5493
+ // higher one is the newer truth and a stale snapshot cannot bring back a revoked pill.
5494
+ function currentTeklaBinding(chat) {
5495
+ const binding = chat?.teklaModelRead || null;
5496
+ if (!binding) return null;
5497
+ const key = `${chat.chatId}|${binding.sourcePath}|${binding.boundAt}`;
5498
+ const seen = state.teklaNewestBinding.get(key);
5499
+ if (seen && teklaAllowanceRevision(seen) > teklaAllowanceRevision(binding)) return seen;
5500
+ state.teklaNewestBinding.set(key, binding);
5501
+ return binding;
5502
+ }
5503
+ function teklaAllowanceRevision(binding) {
5504
+ return Number.isSafeInteger(binding?.allowanceRevision) ? binding.allowanceRevision : 0;
5505
+ }
5506
+
5507
+ // The reads a library binding permits, as the chip names them. A binding stored before the
5508
+ // selection read existed has no list and permits the model name only.
5509
+ // The closed list the server accepts, in its canonical order: [model name, selection].
5510
+ function teklaChatReads() {
5511
+ return ['Tekla.Structures.Model.Model.GetInfo().ModelName', 'Tekla.Structures.Model.UI.ModelObjectSelector.GetSelectedObjects()'];
5512
+ }
5513
+ function teklaReadsCopy(operations, joiner = ' or ') {
5514
+ const [modelRead, selectionRead] = teklaChatReads();
5515
+ const list = Array.isArray(operations) ? operations : [modelRead];
5516
+ const names = [];
5517
+ if (list.includes(modelRead)) names.push('the open model name');
5518
+ if (list.includes(selectionRead)) names.push('the parts you have selected');
5519
+ return names.join(joiner);
5520
+ }
5521
+ function sameTeklaReads(a, b) {
5522
+ const [modelRead] = teklaChatReads();
5523
+ const left = Array.isArray(a) ? a : [modelRead];
5524
+ const right = Array.isArray(b) ? b : [modelRead];
5525
+ return left.length === right.length && left.every((operation) => right.includes(operation));
5526
+ }
5527
+
4332
5528
  // Returns true when the message may be sent: nothing pending, or the binding was stored.
4333
5529
  async function bindPendingTeklaRead(snapshot) {
4334
5530
  const draft = teklaDraftForChat();
@@ -4338,7 +5534,8 @@
4338
5534
  }
4339
5535
  if (!draft || draft.status !== 'draft') return !draft || draft.status === 'bound';
4340
5536
  const bound = state.chat?.teklaModelRead;
4341
- if (bound && bound.sourcePath === draft.library.sourcePath && bound.hostVersion === draft.library.hostVersion) {
5537
+ if (bound && bound.sourcePath === draft.library.sourcePath && bound.hostVersion === draft.library.hostVersion
5538
+ && sameTeklaReads(bound.operations, draft.library.operations)) {
4342
5539
  state.teklaDraft = null; paintTeklaChip(); return true;
4343
5540
  }
4344
5541
  draft.status = 'binding'; draft.error = null;
@@ -4350,7 +5547,8 @@
4350
5547
  if (!sameChat(snapshot)) return false;
4351
5548
  // Never invent the binding locally: only the server's own record of THIS library for this chat counts.
4352
5549
  const stored = updated && updated.chatId === snapshot.chatId ? updated.teklaModelRead : null;
4353
- if (!stored || stored.sourcePath !== draft.library.sourcePath || stored.hostVersion !== draft.library.hostVersion) {
5550
+ if (!stored || stored.sourcePath !== draft.library.sourcePath || stored.hostVersion !== draft.library.hostVersion
5551
+ || !sameTeklaReads(stored.operations, draft.library.operations)) {
4354
5552
  draft.status = 'draft';
4355
5553
  draft.error = 'Message not sent. FloLess could not confirm the Tekla library was added to this chat. Try again.';
4356
5554
  paintTeklaChip();
@@ -4379,7 +5577,7 @@
4379
5577
  // the AI would repeat a stale name as current. A fresh read shows the name at that moment.
4380
5578
  return `Earlier FloLess check: reading the open model name through the Tekla model library at ${receipt.sourcePath} `
4381
5579
  + `worked (Tekla ${receipt.hostVersion}${checked}). The generated agent's commands remain unverified. `
4382
- + 'Help me use this read in this project.';
5580
+ + '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.';
4383
5581
  }
4384
5582
 
4385
5583
  // Leave the selected conversation for the Claude/Codex choice. A prior async select can still be
@@ -4391,6 +5589,8 @@
4391
5589
  closeSource(); clearLiveStream(true);
4392
5590
  state.chat = null; state.events = []; state.attachments = []; state.integrations = null; state.capability = null;
4393
5591
  updateOffscreenActivity();
5592
+ // The left chat's library chip ("added to this chat") must not linger over the chooser.
5593
+ paintTeklaChip();
4394
5594
  }
4395
5595
 
4396
5596
  // Graft receipt → unsent Chat draft. Opening performs no binding, sends nothing and never
@@ -4401,7 +5601,8 @@
4401
5601
  || typeof receipt.hostVersion !== 'string' || !receipt.hostVersion) {
4402
5602
  throw Object.assign(new Error('FloLess could not read the result of the model check. Check the model read again, then continue in AI Chat.'), { plainEnglish: true });
4403
5603
  }
4404
- const library = { sourcePath: receipt.sourcePath, hostVersion: receipt.hostVersion };
5604
+ // The chip lists exactly these reads, and Send binds exactly these: nothing defaults to more.
5605
+ const library = { sourcePath: receipt.sourcePath, hostVersion: receipt.hostVersion, operations: teklaChatReads() };
4405
5606
  const draft = teklaDraftText(receipt);
4406
5607
  await refreshScope();
4407
5608
  if (!state.scope?.owner) throw Object.assign(new Error('Open a project or workflow before continuing in AI Chat.'), { plainEnglish: true });
@@ -4463,9 +5664,10 @@
4463
5664
  const activityResizeObserver = new ResizeObserver(updateOffscreenActivity);
4464
5665
  activityResizeObserver.observe(ui.feed);
4465
5666
  ui.refresh.addEventListener('click', refreshChatSession);
4466
- ui.history.addEventListener('keydown', (event) => {
5667
+ function closeHistoryOnEscape(event) {
4467
5668
  if (event.key === 'Escape') { event.preventDefault(); toggleHistory(false, { focusToggle: true }); }
4468
- });
5669
+ }
5670
+ ui.history.addEventListener('keydown', closeHistoryOnEscape);
4469
5671
  ui.newChat.addEventListener('click', () => {
4470
5672
  beginProviderChoice();
4471
5673
  toggleHistory(false); setBusy(false); providerChooser(); clearReport();
@@ -4492,6 +5694,9 @@
4492
5694
  ui.integrations.addEventListener('click', openIntegrations);
4493
5695
  ui.send.addEventListener('click', sendTurn);
4494
5696
  // The Drawing Filter page reports every change that can alter what the chat shows about it.
5697
+ // The surface decides what may be attached, so repaint the paperclip the moment the step changes
5698
+ // rather than waiting for the next unrelated repaint.
5699
+ window.addEventListener('floless:workspace-step-changed', () => { paintAttachControl(); });
4495
5700
  window.addEventListener('floless:filter-ai-changed', () => {
4496
5701
  state.filterCardMessages.clear();
4497
5702
  paintFloLessContext(); refreshFilterCards(); updateSendState();
@@ -4507,6 +5712,8 @@
4507
5712
  if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); sendTurn(); }
4508
5713
  else if (event.key === 'Escape') { ui.skills.hidden = true; closePicker(); }
4509
5714
  });
5715
+ // Capture phase: the control's own handler runs after, so a sentence it reports is held afresh.
5716
+ shell.addEventListener('click', releaseReportOnControl, true);
4510
5717
  shell.addEventListener('dragover', (event) => { if (event.dataTransfer?.types.includes('Files')) event.preventDefault(); });
4511
5718
  shell.addEventListener('drop', (event) => { if (event.dataTransfer?.files?.length) { event.preventDefault(); attachFiles(event.dataTransfer.files); } });
4512
5719
  ui.input.addEventListener('paste', (event) => {
@@ -4514,7 +5721,7 @@
4514
5721
  if (files.length) { event.preventDefault(); attachFiles(files); }
4515
5722
  });
4516
5723
  ui.tab.addEventListener('click', () => markRead());
4517
- document.addEventListener('visibilitychange', () => { if (!document.hidden) { markRead(); pollChats(); } });
5724
+ document.addEventListener('visibilitychange', () => { if (!document.hidden) { markRead(); void pollChatsTick(); } });
4518
5725
  document.addEventListener('pointerdown', (event) => {
4519
5726
  // Switch account lives inside the Provider .ai-chat-setting but opens no picker of its own, so
4520
5727
  // it must not be treated as "clicked the picker's own control" and leave an open list behind.
@@ -4535,12 +5742,27 @@
4535
5742
  if (node) contextObserver.observe(node, { attributes: true, childList: id === 'ws-step-tabs', subtree: id === 'ws-step-tabs' });
4536
5743
  }
4537
5744
 
4538
- state.refreshTimer = setInterval(pollChats, 5000);
5745
+ state.refreshTimer = setInterval(pollChatsTick, 5000);
4539
5746
  window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); activityResizeObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
5747
+ // A new selection is a new decision: a pill left out for the old one comes back for it.
5748
+ window.addEventListener('floless:model-selection', () => {
5749
+ let selection = null;
5750
+ try { selection = window.flolessLeftPane?.readSelection?.() || null; } catch { selection = null; }
5751
+ if (state.subjectsDismissed && subjectsKey(selection) !== state.subjectsDismissed) state.subjectsDismissed = null;
5752
+ paintAttachments();
5753
+ });
4540
5754
  window.flolessChat = {
4541
5755
  refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openDraft, openVerifiedTeklaDraft,
4542
5756
  startProjectIntake, resumeProjectIntake,
4543
5757
  currentProvider: () => state.chat?.provider ?? null,
5758
+ // The project this panel's conversations belong to; an object card offers Show in chat only for it (#1653).
5759
+ scopeProjectId: () => (state.scope?.owner?.kind === 'project' ? state.scope.owner.projectId : null),
5760
+ // The New project dialog's AI choice (#1605) words each provider's sign-in the way this
5761
+ // panel's own chooser does, so the two ways into a conversation read the same.
5762
+ providerAccountLabel,
5763
+ // The setup card's own sentences, so a start that sets FloLess's copy up first (#1607) says
5764
+ // exactly what this panel would.
5765
+ runtimeNotice,
4544
5766
  };
4545
5767
  window.dispatchEvent(new CustomEvent('floless:chat-ready'));
4546
5768
  paintFloLessContext();