@floless/app 0.141.0 → 0.141.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/web/chat.js CHANGED
@@ -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,6 +38,9 @@
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,
41
44
  // A Tekla model library carried over from a Graft receipt but not yet bound to its chat. It is
42
45
  // browser-only until Send: opening, editing or removing it never calls the binding route.
43
46
  // pendingTeklaLibrary waits for the provider chooser to create the chat it belongs to.
@@ -98,8 +101,13 @@
98
101
  response = await fetch(path, init);
99
102
  } catch (error) {
100
103
  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.');
104
+ // The server is almost always running but busy when this happens (#1604), so the sentence
105
+ // leads with "try again" and keeps "is it still running?" as the fallback.
106
+ const timeout = new Error('FloLess took too long to respond, most likely because it is busy. Try again in a moment — if it keeps happening, make sure FloLess is still running.');
102
107
  timeout.code = 'local-timeout';
108
+ // Which call timed out, and after how long: the sentence above is for the user, this is for
109
+ // whoever reads the console when it happens (#1604).
110
+ timeout.cause = { path, timeoutMs, name: error.name };
103
111
  throw timeout;
104
112
  }
105
113
  throw error;
@@ -153,6 +161,9 @@
153
161
  return 'FloLess could not start this queued AI response, so the message was not sent. Wait a moment, then use Retry sending.';
154
162
  }
155
163
  const code = String(error && error.code || '');
164
+ // request() writes the timeout's sentence itself. Without this it fell through to the generic "could
165
+ // not complete this chat action", which hid the one fact the user could act on (#1604).
166
+ if (code === 'local-timeout' && raw) return raw;
156
167
  const codeMessages = {
157
168
  'chat-origin-refused': 'This chat can only be used from the FloLess app. Reload the page and try again.',
158
169
  'chat-owner-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
@@ -171,6 +182,11 @@
171
182
  'chat-followup-not-found': 'This message is no longer in this conversation. Refresh the conversation.',
172
183
  'chat-attachment-scope': 'An attached file is no longer available to this message. Add the file again in a new message.',
173
184
  'chat-initiator-unknown': 'FloLess could not identify what started this conversation. Reload the conversation and try again.',
185
+ // Damage the user can act on, unlike the refusals below it: the conversation history lists this
186
+ // same record as a row offering Discard, so the sentence sends them there (#1629). Without an
187
+ // entry here the code fell through to the generic "could not complete this chat action", which
188
+ // hid the one fact they could act on.
189
+ 'chat-record-unreadable': 'This conversation’s saved file is damaged, so FloLess cannot open it. Open the conversation history and discard it there.',
174
190
  'chat-record-unsafe': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
175
191
  'chat-record-invalid': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
176
192
  'chat-session-bindings-corrupt': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
@@ -313,13 +329,39 @@
313
329
  function report(error, prefix = '', messages = null) {
314
330
  const code = String(error && error.code || '');
315
331
  const message = `${prefix}${prefix ? ': ' : ''}${messages?.[code] || errorMessage(error)}`;
332
+ // Keep the raw cause (#1604): the user-facing sentence deliberately drops it, and without it a
333
+ // failure could only be diagnosed from the server log. A timeout, a network failure or a server
334
+ // error the server did not explain is unexpected, so it is an error. A refusal the server named
335
+ // with its own code — a 4xx, or an expected 5xx such as `chat-provider-unavailable` — is a
336
+ // warning. A check made here in the browser (too many images, a file too large) is neither: the
337
+ // sentence already says everything, so it is not logged.
338
+ const status = Number.isInteger(error?.status) ? error.status : null;
339
+ const unexpected = code === 'local-timeout' || (status !== null && status >= 500 && !code)
340
+ || error?.name === 'TypeError' || error?.name === 'SyntaxError';
341
+ if (unexpected) console.error(`[ai-chat] ${message}`, error?.cause ?? '', error);
342
+ else if (status !== null) console.warn(`[ai-chat] ${message}`, error);
316
343
  announce(message);
317
344
  ui.hint.textContent = message;
318
345
  ui.hint.classList.add('error');
319
346
  }
320
347
 
348
+ // A Drawing Filter message refused while FloLess sets its AI up (#1650) keeps its sentence in the hint
349
+ // while the card still shows that very setup and the refused words are still in the draft, which the
350
+ // sentence says they are. Every repaint asks again, so the sentence ends with the first of those to
351
+ // change (the setup finished, was cancelled or failed another way, another conversation, the words
352
+ // removed) and the card speaks for itself.
353
+ function filterSetupHint() {
354
+ const note = state.filterSetupNote;
355
+ if (!note) return null;
356
+ const status = state.chat ? state.capability?.runtime : null;
357
+ if (status && runtimeCardKey(state.chat.chatId, status) === note.key && ui.input.value.includes(note.text)) return note.sentence;
358
+ state.filterSetupNote = null;
359
+ return null;
360
+ }
361
+
321
362
  function clearReport() {
322
363
  ui.hint.classList.remove('error');
364
+ const filterNote = filterSetupHint();
323
365
  const message = requestExecutionBlocked()
324
366
  ? 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.'
325
367
  : state.followupUnknownId || hasUnknownFollowup()
@@ -328,7 +370,7 @@
328
370
  && state.attachments.filter(attachment => attachment.mediaType.startsWith('image/')).length >= MAX_IMAGES_PER_MESSAGE
329
371
  ? 'You can attach up to five images to one message. Remove an image or choose fewer, then try again.'
330
372
  : state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
331
- ? runtimeNotice(state.chat.provider, state.capability.runtime).body
373
+ ? filterNote || runtimeNotice(state.chat.provider, state.capability.runtime).body
332
374
  : state.chat && !providerReady()
333
375
  ? `${capabilityMessage(state.chat.provider, state.capability?.reason)} You can still write a message; Send will retry the connection.`
334
376
  : state.chat?.state === 'recovery'
@@ -345,6 +387,8 @@
345
387
  ui.hint.classList.remove('working');
346
388
  ui.hint.removeAttribute('aria-label');
347
389
  ui.hint.textContent = message;
390
+ // Painted as it was reported, so the poll does not restyle it.
391
+ if (filterNote && message === filterNote) ui.hint.classList.add('error');
348
392
  }
349
393
  }
350
394
 
@@ -656,23 +700,9 @@
656
700
  accounts.textContent = 'Checking signed-in accounts…';
657
701
  empty.append(accounts);
658
702
  // 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
- });
703
+ readChooserAccounts(accounts);
675
704
  ui.feed.append(empty);
705
+ paintUnreadableNotice();
676
706
  ui.title.textContent = 'New conversation';
677
707
  const providerValue = ui.provider.querySelector('strong');
678
708
  providerValue.textContent = 'Choose Claude or Codex';
@@ -692,6 +722,145 @@
692
722
  closePicker();
693
723
  }
694
724
 
725
+ // A project whose only conversations are damaged opens on the Claude / Codex choice, with the
726
+ // History list closed: without this line nothing on screen would say those conversations exist
727
+ // (#1619). Deliberately quiet (dim text, no badge) — the ☷ unread badge means new messages.
728
+ function paintUnreadableNotice() {
729
+ const card = ui.feed.querySelector('.ai-chat-empty');
730
+ const count = state.unreadableChats?.length || 0;
731
+ let notice = card?.querySelector('.ai-chat-unreadable-notice') || null;
732
+ if (!card || !count) { notice?.remove(); return; }
733
+ if (!notice) {
734
+ notice = document.createElement('div'); notice.className = 'ai-chat-unreadable-notice';
735
+ card.append(notice);
736
+ }
737
+ notice.textContent = count === 1
738
+ ? `1 conversation in this ${state.scope.owner.kind} can’t be opened — see History.`
739
+ : `${count} conversations in this ${state.scope.owner.kind} can’t be opened — see History.`;
740
+ }
741
+
742
+ // The waits between re-reads of a chooser account that came back 'unknown' (#1606). The server
743
+ // answers 'unknown' when the CLI status read threw or timed out — a transient answer it replaces
744
+ // on its next read — but nothing else re-reads while the chooser is up: pollChats() has no chat to
745
+ // read for ("no chat, no read"). Without this, one slow first read froze "could not check" under
746
+ // both buttons for as long as the chooser stayed open. Backs off to the last value and repeats it;
747
+ // past the 10 s server cache each read asks the CLI again, so the floor stays at seconds, not ms.
748
+ const CHOOSER_ACCOUNT_RETRY_MS = [2_000, 4_000, 8_000, 16_000, 30_000];
749
+ // The rows a re-read may still change: an account the server could not check yet, and FloLess's own
750
+ // copy of an AI that is not set up yet (#1622). Every other row already says what it knows.
751
+ const CHOOSER_PENDING_STATES = new Set(['unknown', 'setup']);
752
+
753
+ // The one chooser account read in flight, shared by every line that asks while it is pending. A
754
+ // repaint (+ New conversation pressed again, a project reopened) builds a new line while the old
755
+ // line's read may still be waiting on a slow CLI; without this each repaint would add another
756
+ // concurrent request instead of reusing the one already on its way.
757
+ let chooserAccountsRead = null;
758
+ function readChooserRuntimes() {
759
+ if (!chooserAccountsRead) {
760
+ chooserAccountsRead = request('/api/terminal-runtimes')
761
+ .finally(() => { chooserAccountsRead = null; });
762
+ }
763
+ return chooserAccountsRead;
764
+ }
765
+
766
+ // What the chooser says about FloLess's own copy of an AI that is not ready to answer yet (#1622),
767
+ // in the New project dialog's words: until that copy is set up there is no account to check, so
768
+ // "retrying…" would promise an answer that cannot come. Null when the account line applies — no
769
+ // managed copy (the user's install runs), or a copy ready to launch. The state is the shared
770
+ // `chatRuntimeReadiness` (web/aware.js), so this line cannot disagree with what a start would do.
771
+ function chooserSetupLine(provider, runtime) {
772
+ const managed = runtime && runtime.managed && typeof runtime.managed === 'object' ? runtime.managed : null;
773
+ const readiness = managed ? window.flolessBridge?.chatRuntimeReadiness?.(runtime) : null;
774
+ if (!readiness || readiness === 'ready') return null;
775
+ const label = providerLabels[provider];
776
+ // Only a setup still to come can change on its own; a copy FloLess cannot start is a final answer.
777
+ if (readiness === 'setup') {
778
+ if (managed.state === 'preparing') return { text: `${label} · setting up…`, state: 'setup' };
779
+ if (managed.state === 'failed') return { text: `${label} · setup failed, choosing it tries again`, state: 'setup' };
780
+ return { text: `${label} · not set up yet`, state: 'setup' };
781
+ }
782
+ return { text: `${label} · couldn’t be set up`, state: 'unavailable' };
783
+ }
784
+
785
+ function chooserAccountCell(provider, runtime, attempt) {
786
+ const cell = document.createElement('span');
787
+ // A runtime missing from the list is a known absence, not an unchecked one: flat "not installed".
788
+ const answer = runtime ? signInAnswer(runtime.account) : null;
789
+ const setup = runtime ? chooserSetupLine(provider, runtime) : null;
790
+ cell.dataset.provider = provider;
791
+ // A copy FloLess is still to set up is re-read like an unknown account, so the row moves on by
792
+ // itself once the setup lands (started from this chooser, another surface or another window).
793
+ cell.dataset.accountState = setup ? setup.state : answer ? answer.state : 'not-installed';
794
+ if (setup) cell.textContent = setup.text;
795
+ else if (!answer) cell.textContent = `${providerLabels[provider]} · not installed`;
796
+ // While the first few re-reads are still due, say so rather than show a verdict that is about to
797
+ // be replaced; once the backoff has reached its slowest step the row says what it knows — the
798
+ // re-read carries on at that pace and still updates the row in place if an answer lands.
799
+ else if (answer.state === 'unknown' && attempt < CHOOSER_ACCOUNT_RETRY_MS.length - 1) cell.textContent = `${providerLabels[provider]} · retrying…`;
800
+ else cell.textContent = providerAccountLabel(provider, answer);
801
+ return cell;
802
+ }
803
+
804
+ // Reads the chooser's account line, then re-reads it on the backoff above while any row is still
805
+ // 'unknown' and this line is still on screen. One chain per line, strictly sequential — the next
806
+ // read is armed only after the previous one settled — and every read goes through the shared
807
+ // in-flight read above, so neither a chain nor a burst of repaints can overlap requests or pile up
808
+ // sockets. A repaint builds a new line, which disconnects this one and ends its chain at its next
809
+ // step. Only the unknown rows change: each row carries its own answer, and one that was already
810
+ // definite is not re-stated by a later read.
811
+ function readChooserAccounts(accounts, attempt = 0, warned = false) {
812
+ const next = (seenFailure) => {
813
+ const wait = () => setTimeout(() => {
814
+ if (!accounts.isConnected) return;
815
+ // A hidden window or a collapsed chat pane reads nothing, like pollChats(); the chain waits
816
+ // at its current pace and resumes when the line can be seen again.
817
+ if (document.hidden || ui.feed.closest('[hidden]')) { wait(); return; }
818
+ readChooserAccounts(accounts, attempt + 1, seenFailure);
819
+ }, CHOOSER_ACCOUNT_RETRY_MS[Math.min(attempt, CHOOSER_ACCOUNT_RETRY_MS.length - 1)]);
820
+ wait();
821
+ };
822
+ readChooserRuntimes().then((info) => {
823
+ if (!accounts.isConnected) return;
824
+ const cells = ['claude', 'codex'].map((provider) =>
825
+ chooserAccountCell(provider, info?.runtimes?.find((r) => r?.id === provider), attempt));
826
+ const current = [...accounts.querySelectorAll('span')];
827
+ if (current.length !== cells.length) {
828
+ // The first answer replaces the "Checking signed-in accounts…" placeholder.
829
+ accounts.replaceChildren(...cells);
830
+ } else {
831
+ // A re-read: only a row still waiting for an answer takes the new one, in place.
832
+ current.forEach((cell, index) => {
833
+ if (!CHOOSER_PENDING_STATES.has(cell.dataset.accountState)) return;
834
+ const fresh = cells[index];
835
+ cell.dataset.accountState = fresh.dataset.accountState;
836
+ if (cell.textContent !== fresh.textContent) cell.textContent = fresh.textContent;
837
+ });
838
+ }
839
+ if ([...accounts.querySelectorAll('span')].some((cell) => CHOOSER_PENDING_STATES.has(cell.dataset.accountState))) next(warned);
840
+ }).catch((error) => {
841
+ if (!accounts.isConnected) return;
842
+ if (attempt === 0) {
843
+ // The line disappears rather than guessing; without this the feature vanishing is invisible.
844
+ console.warn('floless: could not read the signed-in accounts for the chooser', error);
845
+ accounts.remove();
846
+ return;
847
+ }
848
+ // A re-read that failed outright leaves the rows as they are and tries again at the next step;
849
+ // warned once per line, so a server that went away does not log every half-minute.
850
+ if (!warned) console.warn('floless: could not re-read the signed-in accounts for the chooser', error);
851
+ // Failed re-reads still advance the backoff, so the row must still stop saying "retrying…" at
852
+ // the slowest step — or a server that stopped answering would leave it there for good.
853
+ if (attempt >= CHOOSER_ACCOUNT_RETRY_MS.length - 1) {
854
+ for (const cell of accounts.querySelectorAll('span')) {
855
+ if (cell.dataset.accountState !== 'unknown') continue;
856
+ const label = providerAccountLabel(cell.dataset.provider, { state: 'unknown' });
857
+ if (cell.textContent !== label) cell.textContent = label;
858
+ }
859
+ }
860
+ next(true);
861
+ });
862
+ }
863
+
695
864
  function clearProviderChoice() {
696
865
  state.choosingProvider = false;
697
866
  }
@@ -701,7 +870,7 @@
701
870
  clearProviderChoice();
702
871
  closeSource();
703
872
  clearLiveStream(true);
704
- state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = []; state.followupUnknownId = null;
873
+ state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = []; state.followupUnknownId = null;
705
874
  ui.feed.replaceChildren();
706
875
  updateOffscreenActivity();
707
876
  const empty = document.createElement('div');
@@ -747,12 +916,79 @@
747
916
  function restoreHistoryFocus(commandId) {
748
917
  if (!commandId) return;
749
918
  requestAnimationFrame(() => {
919
+ // Only put back focus the repaint took away. If the person has moved on since (into a row's
920
+ // rename field, say), a late frame must not pull focus out of it — that blur would save
921
+ // the half-typed name (#1582). A hidden tab can hold this frame back for a long time.
922
+ if (document.activeElement && document.activeElement !== document.body) return;
750
923
  [...ui.history.querySelectorAll('[data-command-id]')]
751
924
  .find((candidate) => candidate.dataset.commandId === commandId)?.focus();
752
925
  });
753
926
  }
754
927
 
928
+ // Where keyboard focus goes when a conversation's inline rename ends, so it never falls to the
929
+ // page: the row's ✎, where the rename began; the row itself when ✎ has been withdrawn (the AI
930
+ // is replying); the All filter when the row cannot be seen (it left the list, or sits in the
931
+ // closed Archived list).
932
+ function focusHistoryConversation(chatId) {
933
+ const commandId = `shell.chat-history-item#${chatId}`;
934
+ const row = [...ui.history.querySelectorAll('.ai-chat-history-row')].find((node) => node.dataset.commandId === commandId);
935
+ const closed = row?.closest('details');
936
+ const rowSeen = Boolean(row) && (!closed || closed.open)
937
+ && (typeof row.checkVisibility !== 'function' || row.checkVisibility());
938
+ const renameButton = rowSeen ? row.querySelector('.ai-chat-history-rename') : null;
939
+ const renameSeen = Boolean(renameButton) && !renameButton.hidden
940
+ && (typeof renameButton.checkVisibility !== 'function' || renameButton.checkVisibility());
941
+ (renameSeen ? renameButton : rowSeen ? row : ui.history.querySelector('.ai-chat-history-filter'))?.focus({ preventScroll: true });
942
+ }
943
+
944
+ // Every history repaint goes through here. The list is rebuilt in the background (the 5 s poll,
945
+ // SSE, a lifecycle action elsewhere), and rebuilding it removes a history-row rename field —
946
+ // which fires that field's blur and would save whatever was half-typed (#1582). So carry an open
947
+ // rename across the rebuild: the SAME input moves into the rebuilt row with its text, caret and
948
+ // focus intact. Enter, Escape or the person leaving the field ends it — or the conversation
949
+ // no longer being renamable in this list, which drops the edit unsaved.
755
950
  function paintHistory() {
951
+ const rename = state.historyRename;
952
+ if (!rename) { renderHistory(); return; }
953
+ const { input } = rename;
954
+ const hadFocus = document.activeElement === input;
955
+ const { selectionStart, selectionEnd, selectionDirection } = input;
956
+ rename.repainting = true;
957
+ try { renderHistory(); } finally { rename.repainting = false; }
958
+ if (state.historyRename !== rename) return;
959
+ const commandId = `shell.chat-history-item#${rename.chatId}`;
960
+ const row = [...ui.history.querySelectorAll('.ai-chat-history-row')].find((node) => node.dataset.commandId === commandId);
961
+ const titleNode = row?.querySelector('.ai-chat-history-title');
962
+ const renameButton = row?.querySelector('.ai-chat-history-rename');
963
+ // The conversation left the list, was archived, started a turn, or the project changed under
964
+ // the field: there is nothing left to rename in place, so drop the edit rather than save it.
965
+ const sameList = sameScope(rename.scope, rename.generation);
966
+ if (!titleNode || !renameButton || renameButton.hidden || !sameList) {
967
+ rename.abandon();
968
+ // The field vanished under the person's typing; say the name was not kept, and why. Not
969
+ // after a project switch — they left on purpose and are now looking at another list.
970
+ if (!sameList) return;
971
+ // The cause is only known when the row is still here; a missing row may be deleted, archived
972
+ // or filtered out, so that message stays neutral about why.
973
+ const archived = Boolean(row?.closest('.ai-chat-history-archived'));
974
+ announce(!row
975
+ ? 'Rename cancelled. This conversation is no longer in this list, so the new name was not saved. If you archived it, restore it from Archived to rename it.'
976
+ : archived
977
+ ? 'Rename cancelled. This conversation was archived, so the new name was not saved. Restore it to rename it.'
978
+ : 'Rename cancelled. The AI started working in this conversation, so the new name was not saved. You can rename it when the reply finishes.');
979
+ // Keep keyboard focus in the history instead of letting it fall to the page.
980
+ if (hadFocus) focusHistoryConversation(rename.chatId);
981
+ return;
982
+ }
983
+ row.dataset.renaming = 'true'; renameButton.hidden = true;
984
+ titleNode.replaceWith(input);
985
+ if (hadFocus) {
986
+ input.focus({ preventScroll: true });
987
+ input.setSelectionRange(selectionStart, selectionEnd, selectionDirection || 'none');
988
+ }
989
+ }
990
+
991
+ function renderHistory() {
756
992
  const focusedCommand = ui.history.contains(document.activeElement) ? document.activeElement?.dataset?.commandId : null;
757
993
  ui.history.replaceChildren();
758
994
  if (!state.scope) return;
@@ -817,7 +1053,10 @@
817
1053
  }
818
1054
 
819
1055
  const archivedChats = state.archivedChats.filter((chat) => Boolean(chat.archivedAt));
1056
+ const unreadableChats = state.unreadableChats || [];
1057
+ if (unreadableChats.length) appendUnreadableChats(unreadableChats, ui.history);
820
1058
  if (!state.chats.length && !archivedChats.length) {
1059
+ if (unreadableChats.length) { restoreHistoryFocus(focusedCommand); return; }
821
1060
  const empty = document.createElement('div'); empty.className = 'ai-chat-history-empty';
822
1061
  empty.textContent = 'No conversations here yet.';
823
1062
  ui.history.append(empty); return;
@@ -924,6 +1163,83 @@
924
1163
  }
925
1164
  }
926
1165
 
1166
+ // A conversation whose saved file is damaged (#1619). The server knows nothing trustworthy about it
1167
+ // beyond its id — no title, no provider — so the row says what happened and offers the one thing
1168
+ // that can be done here. It opens nothing, so it is not a button; only Discard acts.
1169
+ function appendUnreadableChats(entries, destination) {
1170
+ const group = document.createElement('section'); group.className = 'ai-chat-history-group ai-chat-history-unreadable';
1171
+ group.setAttribute('aria-label', 'Conversations that can’t be opened');
1172
+ const label = document.createElement('div'); label.className = 'ai-chat-history-label'; label.textContent = 'Can’t be opened';
1173
+ group.append(label);
1174
+ for (const entry of entries) {
1175
+ const row = document.createElement('div');
1176
+ row.className = 'ai-chat-history-row unreadable';
1177
+ row.dataset.chatId = entry.chatId;
1178
+ const title = document.createElement('span'); title.className = 'ai-chat-history-title'; title.textContent = 'Conversation can’t be opened';
1179
+ const meta = document.createElement('span'); meta.className = 'ai-chat-history-meta';
1180
+ const changed = entry.changedAt && Number.isFinite(Date.parse(entry.changedAt))
1181
+ ? ` · changed ${formatDay(entry.changedAt) === 'Today' ? eventTime({ createdAt: entry.changedAt }) : formatDay(entry.changedAt)}`
1182
+ : '';
1183
+ meta.textContent = `Saved file is damaged${changed}`;
1184
+ const actions = document.createElement('span'); actions.className = 'ai-chat-history-actions always-on';
1185
+ const discard = document.createElement('button');
1186
+ discard.type = 'button'; discard.className = 'ai-chat-history-action danger'; discard.append(historyActionIcon('delete'));
1187
+ discard.dataset.commandId = `shell.chat-history-discard#${entry.chatId}`;
1188
+ discard.dataset.commandInstanceLabel = `Damaged conversation${changed}`;
1189
+ discard.setAttribute('aria-label', 'Discard damaged conversation');
1190
+ discard.dataset.tip = 'Permanently discard this conversation';
1191
+ discard.addEventListener('click', (event) => {
1192
+ event.preventDefault(); event.stopPropagation(); discardUnreadableConversation(entry, discard);
1193
+ });
1194
+ actions.append(discard);
1195
+ row.append(title, meta, actions);
1196
+ group.append(row);
1197
+ }
1198
+ destination.append(group);
1199
+ }
1200
+
1201
+ async function discardUnreadableConversation(entry, trigger) {
1202
+ const snapshot = captureScope();
1203
+ if (!snapshot) return;
1204
+ const confirm = window.flolessBridge?.formModal;
1205
+ if (!confirm) { report(new Error('Could not open the confirmation dialog'), 'Could not discard conversation'); return; }
1206
+ const approved = await confirm({
1207
+ title: 'Discard this damaged conversation?',
1208
+ sub: 'FloLess can’t read this conversation’s saved file, so it can’t be opened or repaired here. Discarding permanently removes it from this computer. Your other conversations aren’t affected. This can’t be undone.',
1209
+ fields: [], okLabel: 'Discard permanently', danger: true, returnFocusTo: trigger,
1210
+ });
1211
+ if (!approved || !sameScope(snapshot.scope, snapshot.generation)) return;
1212
+ trigger.disabled = true;
1213
+ try {
1214
+ await request(`/api/chat/conversations/${encodeURIComponent(entry.chatId)}/discard-unreadable`, {
1215
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner }),
1216
+ });
1217
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1218
+ state.unreadableChats = (state.unreadableChats || []).filter((item) => item.chatId !== entry.chatId);
1219
+ paintHistory(); paintUnreadableNotice();
1220
+ ui.history.querySelector('[aria-pressed="true"]')?.focus({ preventScroll: true });
1221
+ announce('Discarded the damaged conversation.');
1222
+ } catch (error) {
1223
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1224
+ if (error?.code === 'chat-record-readable') {
1225
+ // Repaired on disk (or it was only mid-save): it is a normal conversation again, so keep it.
1226
+ // Say so on screen too — the status region is for screen readers only. After the re-read:
1227
+ // with a conversation open, the poll's composer refresh rewrites the hint line.
1228
+ const kept = 'This conversation can be opened again, so it was kept.';
1229
+ state.unreadableChats = (state.unreadableChats || []).filter((item) => item.chatId !== entry.chatId);
1230
+ paintHistory(); paintUnreadableNotice();
1231
+ await pollChats();
1232
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1233
+ announce(kept);
1234
+ ui.hint.textContent = kept;
1235
+ return;
1236
+ }
1237
+ report(error, 'Could not discard conversation', {
1238
+ 'chat-owner-archived': `This ${snapshot.scope.owner.kind} is archived, so its conversations can’t be changed. Restore the ${snapshot.scope.owner.kind} to discard this conversation.`,
1239
+ });
1240
+ } finally { trigger.disabled = false; }
1241
+ }
1242
+
927
1243
  function eventTime(event) {
928
1244
  return new Intl.DateTimeFormat(undefined, { hour: '2-digit', minute: '2-digit' }).format(new Date(event.createdAt));
929
1245
  }
@@ -987,12 +1303,31 @@
987
1303
  titleNode.replaceWith(input);
988
1304
  input.focus(); input.select();
989
1305
  let finished = false;
990
- const finish = async (save = true) => {
1306
+ const active = {
1307
+ chatId: chat.chatId, input, scope: snapshot.scope, generation: snapshot.generation, repainting: false,
1308
+ abandon() { finished = true; if (state.historyRename === active) state.historyRename = null; },
1309
+ };
1310
+ state.historyRename = active;
1311
+ // `returnFocus`: the rename ended from the field's own keys, so focus goes back to this
1312
+ // conversation's row instead of falling to the page. Clicking away keeps focus where it went.
1313
+ const finish = async (save = true, { returnFocus = false } = {}) => {
991
1314
  if (finished) return;
992
1315
  finished = true;
1316
+ if (state.historyRename === active) state.historyRename = null;
993
1317
  const title = input.value.trim();
994
- if (!save || !title || title === original) { if (sameScope(snapshot.scope, snapshot.generation)) paintHistory(); return; }
1318
+ if (!save || !title || title === original) {
1319
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1320
+ paintHistory();
1321
+ if (returnFocus) focusHistoryConversation(chat.chatId);
1322
+ return;
1323
+ }
1324
+ // The list this field was opened in has been replaced (another project or workflow, or a
1325
+ // reload of it): never send a rename from a field that no longer belongs to what is shown.
1326
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
995
1327
  input.disabled = true;
1328
+ // The save takes a moment. Only bring focus back if the person has not moved it elsewhere
1329
+ // meanwhile (it is still on the field, or fell to the page when the field was disabled).
1330
+ const focusWaited = () => returnFocus && [input, document.body, null].includes(document.activeElement);
996
1331
  try {
997
1332
  const updated = await request(`/api/chat/conversations/${encodeURIComponent(chat.chatId)}/title`, {
998
1333
  method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, title }),
@@ -1004,17 +1339,36 @@
1004
1339
  state.chat = updated;
1005
1340
  ui.title.textContent = updated.title;
1006
1341
  }
1007
- paintHistory(); announce('Conversation name saved.');
1342
+ const refocus = focusWaited();
1343
+ paintHistory(); if (refocus) focusHistoryConversation(chat.chatId);
1344
+ announce('Conversation name saved.');
1008
1345
  } catch (error) {
1009
1346
  if (!sameScope(snapshot.scope, snapshot.generation)) return;
1010
- paintHistory(); report(error, 'Could not rename conversation');
1347
+ const refocus = focusWaited();
1348
+ paintHistory(); if (refocus) focusHistoryConversation(chat.chatId);
1349
+ report(error, 'Could not rename conversation');
1011
1350
  }
1012
1351
  };
1352
+ // The field sits inside the row, whose click opens the conversation. A click in the field (to
1353
+ // move the caret) must stay in the field, or opening the conversation would blur and save it.
1354
+ input.addEventListener('click', (event) => event.stopPropagation());
1013
1355
  input.addEventListener('keydown', (event) => {
1014
- if (event.key === 'Enter') { event.preventDefault(); finish(true); }
1015
- if (event.key === 'Escape') { event.preventDefault(); finish(false); }
1356
+ // While an input method is composing (Japanese, Chinese, Korean…), Enter accepts the
1357
+ // candidate and Escape dismisses it: both belong to the composition, not to the rename.
1358
+ // Older Safari sends that key after the composition ends, with isComposing false and
1359
+ // keyCode 229, so either one marks it.
1360
+ const composing = event.isComposing || event.keyCode === 229;
1361
+ if (event.key === 'Enter' && !composing) { event.preventDefault(); finish(true, { returnFocus: true }); }
1362
+ if (event.key === 'Escape') {
1363
+ // Escape in this field is the field's, never the history's: left to bubble, it would also
1364
+ // reach the history's own Escape and close the whole history (#1603). One press, one action.
1365
+ event.stopPropagation();
1366
+ if (composing) return;
1367
+ event.preventDefault(); finish(false, { returnFocus: true });
1368
+ }
1016
1369
  });
1017
- input.addEventListener('blur', () => finish(true));
1370
+ // A repaint removing the field is not the person leaving it; paintHistory() puts it back.
1371
+ input.addEventListener('blur', () => { if (!active.repainting) finish(true); });
1018
1372
  }
1019
1373
 
1020
1374
  async function leaveConversationAfterRemoval(chatId, announcement, snapshot) {
@@ -1027,7 +1381,9 @@
1027
1381
  state.chat = null; state.events = []; state.attachments = []; state.followupUnknownId = null; state.integrations = null;
1028
1382
  updateOffscreenActivity();
1029
1383
  if (state.chats.length) await selectConversation(state.chats[0].chatId, { focus: true, replaceProviderChoice: true });
1030
- else providerChooser();
1384
+ // The chooser removes the removed conversation's setup card; its hint goes too, as on every other way
1385
+ // to the chooser, so nothing is left saying a message is back in a draft that was just removed.
1386
+ else { providerChooser(); clearReport(); }
1031
1387
  if (sameScope(snapshot.scope, snapshot.generation)) announce(announcement);
1032
1388
  }
1033
1389
 
@@ -1402,9 +1758,10 @@
1402
1758
  }
1403
1759
 
1404
1760
  // 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.
1761
+ // the server recorded, and an unverified read never shows a model name or parts.
1406
1762
  function renderTeklaReadEvent(event) {
1407
1763
  const payload = event.payload || {};
1764
+ if (payload.status === 'verified-for-selection-read') return renderTeklaSelectionEvent(event);
1408
1765
  const verified = payload.status === 'verified-for-model-name-read';
1409
1766
  const card = document.createElement('section');
1410
1767
  card.className = `ai-chat-tekla-read ${verified ? 'verified' : 'unverified'}`;
@@ -1445,6 +1802,127 @@
1445
1802
  return card;
1446
1803
  }
1447
1804
 
1805
+ function teklaKg(value) {
1806
+ return new Intl.NumberFormat(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(value);
1807
+ }
1808
+ function teklaCount(value) { return new Intl.NumberFormat().format(value); }
1809
+ function partsWord(count) { return `${teklaCount(count)} ${count === 1 ? 'part' : 'parts'}`; }
1810
+
1811
+ // The count and total line, worded for exactly what the read covered. It sits above the table so a
1812
+ // list that was cut short says so before anyone scrolls.
1813
+ function teklaSelectionSummary(payload, listed) {
1814
+ const count = Number(payload.partCount) || 0;
1815
+ const total = `${teklaKg(Number(payload.totalWeightKg) || 0)} kg`;
1816
+ const missing = Number(payload.weightMissing) || 0;
1817
+ const lines = [];
1818
+ if (payload.complete === false) {
1819
+ lines.push(`${partsWord(count)} read, ${total} — the selection is larger than FloLess reads at once, so it stopped part-way and these cover only the parts it read. Select fewer objects for a full total.`);
1820
+ } else if (payload.truncated) {
1821
+ // "Covers all" only when every part read has a weight; otherwise the next line says who is left out.
1822
+ lines.push(missing > 0
1823
+ ? `Showing ${teklaCount(listed)} of ${partsWord(count)} — the total ${total} covers the ${partsWord(count - missing)} that have a weight.`
1824
+ : `Showing ${teklaCount(listed)} of ${partsWord(count)} — the total covers all ${teklaCount(count)}: ${total}.`);
1825
+ } else {
1826
+ lines.push(`${partsWord(count)} · total ${total}`);
1827
+ }
1828
+ if (missing > 0) lines.push(`Tekla gave no weight for ${partsWord(missing)}; the total leaves ${missing === 1 ? 'it' : 'them'} out.`);
1829
+ return lines;
1830
+ }
1831
+
1832
+ // The selected parts as a compact schedule. A replayed card is history: "when checked", never now.
1833
+ function renderTeklaSelectionEvent(event) {
1834
+ const payload = event.payload || {};
1835
+ const parts = Array.isArray(payload.parts) ? payload.parts : [];
1836
+ const count = Number(payload.partCount) || 0;
1837
+ const others = Number(payload.otherObjectCount) || 0;
1838
+ const card = document.createElement('section');
1839
+ card.className = 'ai-chat-tekla-read verified selection';
1840
+ card.dataset.eventSequence = String(event.sequence);
1841
+ card.dataset.eventId = event.eventId;
1842
+ const heading = document.createElement('strong');
1843
+ heading.textContent = 'Selected in Tekla when checked';
1844
+ card.setAttribute('aria-label', heading.textContent);
1845
+ card.append(heading);
1846
+ const facts = document.createElement('dl');
1847
+ const fact = (name, value) => {
1848
+ if (value === undefined || value === null || value === '') return;
1849
+ const dt = document.createElement('dt'); dt.textContent = name;
1850
+ const dd = document.createElement('dd');
1851
+ if (value instanceof Node) dd.append(value); else dd.textContent = String(value);
1852
+ facts.append(dt, dd);
1853
+ };
1854
+ fact('Model when checked', payload.modelName);
1855
+ fact('Tekla host', `${payload.hostVersion || ''}${Number.isFinite(payload.hostPid) ? ` · PID ${payload.hostPid}` : ''}`);
1856
+ fact('Checked', checkedTime(payload.checkedAt));
1857
+ fact('Library', payload.library);
1858
+ card.append(facts);
1859
+ const note = (text, className, parent = card) => {
1860
+ const line = document.createElement('p');
1861
+ if (className) line.className = className;
1862
+ line.textContent = text;
1863
+ parent.append(line);
1864
+ };
1865
+ // Only the short summary is announced; the table is read on demand through its caption.
1866
+ const summary = document.createElement('div');
1867
+ summary.className = 'ai-chat-tekla-summary';
1868
+ summary.setAttribute('role', 'status');
1869
+ card.append(summary);
1870
+ if (count === 0 && payload.complete === false) {
1871
+ // Stopped before reaching any part: that is not "nothing selected".
1872
+ note(`The selection is larger than FloLess reads at once, so it stopped before reaching any part${others > 0 ? ` (${teklaCount(others)} other ${others === 1 ? 'object' : 'objects'} read)` : ''}. Select fewer objects, then ask again.`, '', summary);
1873
+ return card;
1874
+ }
1875
+ if (count === 0) {
1876
+ note(others > 0
1877
+ ? `No parts were selected in Tekla when checked. ${teklaCount(others)} other selected ${others === 1 ? 'object is' : 'objects are'} not a part (bolts, welds and similar), so nothing is listed.`
1878
+ : 'Nothing was selected in Tekla when checked.', '', summary);
1879
+ return card;
1880
+ }
1881
+ for (const line of teklaSelectionSummary(payload, parts.length)) note(line, '', summary);
1882
+ const scroller = document.createElement('div');
1883
+ scroller.className = 'ai-chat-tekla-parts';
1884
+ // No explicit tab stop: Chromium already makes a scrolling region keyboard-focusable, and the
1885
+ // table carries no command of its own.
1886
+ scroller.setAttribute('role', 'region');
1887
+ scroller.setAttribute('aria-label', `Selected parts, ${parts.length} listed`);
1888
+ const table = document.createElement('table');
1889
+ const caption = document.createElement('caption');
1890
+ caption.className = 'sr-only';
1891
+ caption.textContent = `Parts selected in Tekla when checked (${parts.length} listed of ${count})`;
1892
+ const head = document.createElement('thead');
1893
+ const headRow = document.createElement('tr');
1894
+ for (const [label, numeric] of [['Mark', false], ['Name', false], ['Profile', false], ['Material', false], ['kg', true]]) {
1895
+ const th = document.createElement('th'); th.scope = 'col'; th.textContent = label;
1896
+ if (numeric) { th.className = 'num'; th.setAttribute('aria-label', 'Weight in kilograms'); }
1897
+ headRow.append(th);
1898
+ }
1899
+ head.append(headRow);
1900
+ const body = document.createElement('tbody');
1901
+ for (const part of parts) {
1902
+ const row = document.createElement('tr');
1903
+ for (const key of ['mark', 'name', 'profile', 'material']) {
1904
+ const td = document.createElement('td');
1905
+ const value = typeof part?.[key] === 'string' && part[key] ? part[key] : '';
1906
+ td.textContent = value || '—';
1907
+ td.className = value ? key : `${key} empty`;
1908
+ // Narrow columns cut long text short; the shared tooltip shows the recorded value.
1909
+ if (value) td.dataset.tip = value;
1910
+ row.append(td);
1911
+ }
1912
+ const weight = document.createElement('td'); weight.className = 'num';
1913
+ if (Number.isFinite(part?.weightKg)) weight.textContent = teklaKg(part.weightKg);
1914
+ else { weight.textContent = '—'; weight.classList.add('empty'); weight.setAttribute('aria-label', 'no weight'); }
1915
+ row.append(weight);
1916
+ body.append(row);
1917
+ }
1918
+ table.append(caption, head, body);
1919
+ scroller.append(table);
1920
+ card.append(scroller);
1921
+ note('Selected assemblies are listed by their parts when checked.');
1922
+ if (others > 0) note(`${teklaCount(others)} other selected ${others === 1 ? 'object is' : 'objects are'} not a part (bolts, welds and similar) and ${others === 1 ? 'is' : 'are'} not listed.`);
1923
+ return card;
1924
+ }
1925
+
1448
1926
  function checkedTime(value) {
1449
1927
  if (typeof value !== 'string' || !value) return '';
1450
1928
  const date = new Date(value);
@@ -1799,6 +2277,12 @@
1799
2277
  };
1800
2278
  }
1801
2279
 
2280
+ // What the setup card shows for one conversation: the card is rebuilt, and a Drawing Filter "not sent"
2281
+ // sentence dropped from the hint, only when this changes.
2282
+ function runtimeCardKey(chatId, status) {
2283
+ return `${chatId}:${status.state}:${status.owner || ''}:${status.code || ''}:${status.retryable ? 1 : 0}`;
2284
+ }
2285
+
1802
2286
  function paintRuntime() {
1803
2287
  const existing = shell.querySelector('.ai-chat-runtime');
1804
2288
  const status = state.chat ? state.capability?.runtime : null;
@@ -1807,7 +2291,7 @@
1807
2291
  const settingUp = status.state === 'preparing' || status.state === 'not-installed';
1808
2292
  // Polls repeat the same state every two seconds; rebuilding the card each time would swap its button
1809
2293
  // 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}`;
2294
+ const key = runtimeCardKey(state.chat.chatId, status);
1811
2295
  if (existing?.dataset.runtimeKey === key && existing.isConnected) { if (settingUp) startRuntimePoll(); return; }
1812
2296
  existing?.remove();
1813
2297
  const card = document.createElement('section');
@@ -2331,7 +2815,7 @@
2331
2815
  // Claude or Codex as "not ready".
2332
2816
  return await request(`/api/chat/providers/${chat.provider}?${ownerQuery()}&chatId=${encodeURIComponent(chat.chatId)}`);
2333
2817
  } catch (error) {
2334
- return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error) };
2818
+ return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error), readFailed: true };
2335
2819
  }
2336
2820
  }
2337
2821
 
@@ -2426,11 +2910,18 @@
2426
2910
  clearAnswerJump();
2427
2911
  if (!exactAnswer) {
2428
2912
  closeSource(); closePicker();
2429
- state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
2430
- }
2913
+ closeHistoryPanel();
2914
+ }
2915
+ // The provider check below can take seconds, and the conversation already looks open while it
2916
+ // runs, so a person may reopen the history (to rename another row, say) before it ends. What
2917
+ // the late step may still do depends on whether they did: remember the history's opening count
2918
+ // and where focus sits now, and compare both when the check returns (#1646).
2919
+ const historyOpenings = state.historyOpenings;
2920
+ const focusAtStart = document.activeElement;
2431
2921
  const generation = state.scopeGeneration;
2432
2922
  showConversationLoading(chatId);
2433
2923
  setBusy(true);
2924
+ let failure = null;
2434
2925
  try {
2435
2926
  const [chat, snapshot] = await Promise.all([
2436
2927
  request(`/api/chat/conversations/${encodeURIComponent(chatId)}?${ownerQuery()}`),
@@ -2447,8 +2938,11 @@
2447
2938
  }
2448
2939
  const [capability, desktop] = await Promise.all([readCapability(chat), readDesktopCapability(chat)]);
2449
2940
  if (generation !== state.scopeGeneration || selection !== state.selectionGeneration) return;
2941
+ // Reopened while this conversation was opening: the person has moved on to the history, so
2942
+ // it stays open — with any rename in it — and focus stays where they put it (#1646).
2943
+ const historyReopened = state.historyOpenings !== historyOpenings;
2450
2944
  closeSource(); closePicker();
2451
- state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
2945
+ if (!historyReopened) closeHistoryPanel();
2452
2946
  state.chat = chat;
2453
2947
  state.events = snapshot.events || [];
2454
2948
  reconcileUnknownFollowupOnSelection(chat);
@@ -2479,14 +2973,25 @@
2479
2973
  announce(`Opened Instructor answer in ${state.chat.title}.`);
2480
2974
  } else {
2481
2975
  markRead();
2482
- if (options.focus) ui.input.focus();
2976
+ // Only move focus when nothing has taken it since the selection began: the history was not
2977
+ // reopened (checked again here, because applyProviderDefaults awaited another round-trip
2978
+ // after the close above), and focus is still where the selection left it or nowhere at all.
2979
+ const reopenedSinceStart = state.historyOpenings !== historyOpenings;
2980
+ const focusNow = document.activeElement;
2981
+ const focusUntouched = !focusNow || focusNow === document.body || focusNow === focusAtStart;
2982
+ if (options.focus && !reopenedSinceStart && focusUntouched) ui.input.focus();
2983
+ // Focus stayed in the reopened history, so nothing else tells a screen reader it finished.
2984
+ else if (reopenedSinceStart) announce(`Opened ${state.chat.title}.`);
2483
2985
  }
2484
2986
  } catch (error) {
2485
- if (generation === state.scopeGeneration && selection === state.selectionGeneration) {
2486
- report(error, 'Could not open conversation');
2487
- }
2987
+ failure = error;
2488
2988
  }
2489
2989
  finally { if (selection === state.selectionGeneration) setBusy(false); }
2990
+ // Reported AFTER setBusy: its composer refresh rewrites the hint, which erased this sentence the
2991
+ // moment it appeared and left only "Opening conversation…" on screen (#1604).
2992
+ if (failure && generation === state.scopeGeneration && selection === state.selectionGeneration) {
2993
+ report(failure, 'Could not open conversation');
2994
+ }
2490
2995
  }
2491
2996
 
2492
2997
  function reconcileUnknownFollowupOnSelection(chat) {
@@ -2531,6 +3036,10 @@
2531
3036
  return;
2532
3037
  }
2533
3038
  const generation = ++state.scopeGeneration;
3039
+ // An open history-row rename belongs to the list being replaced. End it before the history is
3040
+ // hidden below: hiding the focused field blurs it, and blur must not save a half-typed name
3041
+ // into the conversation the person just navigated away from (#1582).
3042
+ state.historyRename?.abandon();
2534
3043
  if (scopeKey(scope) !== scopeKey(state.scope)) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; state.teklaDraft = null; }
2535
3044
  state.selectionGeneration += 1;
2536
3045
  clearAnswerJump();
@@ -2539,13 +3048,13 @@
2539
3048
  clearProviderChoice();
2540
3049
  state.scope = scope;
2541
3050
  state.scopeInitialized = true;
2542
- state.chat = null; state.chats = []; state.archivedChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
3051
+ state.chat = null; state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
2543
3052
  // A published filter answer still lands in its own project's conversation; reopening it resumes.
2544
3053
  for (const entry of state.filterPending.values()) clearTimeout(entry.timer);
2545
3054
  state.filterPending.clear(); state.filterNotices.clear(); state.filterCardMessages.clear();
2546
3055
  updateOffscreenActivity();
2547
3056
  state.historyFilter = 'all'; state.instructorAnswers = []; state.historyLoading = false; state.historyRequestGeneration += 1;
2548
- state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
3057
+ closeHistoryPanel();
2549
3058
  if (!scope?.owner) { showUnscoped(); return; }
2550
3059
  ui.scope.textContent = scope.label;
2551
3060
  ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
@@ -2555,6 +3064,7 @@
2555
3064
  const result = await request(`/api/chat/conversations?${ownerQuery(scope.owner)}`);
2556
3065
  if (generation !== state.scopeGeneration) return;
2557
3066
  state.chats = result.chats || [];
3067
+ state.unreadableChats = result.unreadableChats || [];
2558
3068
  seedReadCursors(state.chats, scope.owner);
2559
3069
  paintHistory(); paintUnread();
2560
3070
  if (state.chats.length) await selectConversation(state.chats[0].chatId);
@@ -2564,7 +3074,7 @@
2564
3074
  // A history read can fail independently of the selected project (for example while an
2565
3075
  // older, stale conversation is being recovered). Do not erase the scope and disable the
2566
3076
  // 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;
3077
+ state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null;
2568
3078
  updateOffscreenActivity();
2569
3079
  ui.scope.textContent = scope.label;
2570
3080
  ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
@@ -2623,6 +3133,7 @@
2623
3133
  const result = await request(`/api/chat/conversations?${ownerQuery()}&filter=instructor-answers`);
2624
3134
  if (requestGeneration !== state.historyRequestGeneration || scopeGeneration !== state.scopeGeneration) return;
2625
3135
  state.chats = result.chats || [];
3136
+ state.unreadableChats = result.unreadableChats || [];
2626
3137
  state.instructorAnswers = result.instructorAnswers || [];
2627
3138
  } catch (error) {
2628
3139
  if (requestGeneration === state.historyRequestGeneration) report(error, 'Could not load Instructor answers');
@@ -2683,8 +3194,22 @@
2683
3194
  else ui.history.querySelector('[aria-pressed="true"]')?.focus();
2684
3195
  }
2685
3196
 
3197
+ // Closes the history from anywhere other than its own toggle, and keeps everything toggleHistory
3198
+ // keeps in step: the toggle's aria-expanded (#1641) and the offscreen-activity line. An open row
3199
+ // rename is abandoned first, as loadScope does (#1582): hiding the focused field blurs it, and a
3200
+ // blur must never save a half-typed name. Focus is left alone; each caller decides that.
3201
+ function closeHistoryPanel() {
3202
+ state.historyRename?.abandon();
3203
+ state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
3204
+ ui.historyToggle.setAttribute('aria-expanded', 'false');
3205
+ updateOffscreenActivity();
3206
+ }
3207
+
2686
3208
  function toggleHistory(force, options = {}) {
2687
3209
  const open = force === undefined ? !state.historyOpen : Boolean(force);
3210
+ // Counts every opening, so a conversation still opening in the background can tell the person
3211
+ // reopened the history after it began (#1646).
3212
+ if (open) state.historyOpenings += 1;
2688
3213
  state.historyOpen = open;
2689
3214
  shell.classList.toggle('history-open', open);
2690
3215
  ui.history.hidden = !open;
@@ -2935,7 +3460,11 @@
2935
3460
  finally { if (state.draftWrites.get(chatId) === write) state.draftWrites.delete(chatId); }
2936
3461
  }
2937
3462
 
2938
- async function restoreBackgroundDraft(snapshot, text, submissionId) {
3463
+ // The options replace the plain "not sent" words when the caller knows better what happened (a Drawing
3464
+ // Filter message AI did not start on, #1643, which the conversation still shows): `announcement` for
3465
+ // the words coming back, `mergeLabel` and `mergedAnnouncement` when newer typing is kept above them.
3466
+ // A merged draft always asks for a review.
3467
+ async function restoreBackgroundDraft(snapshot, text, submissionId, { announcement, mergeLabel = 'Earlier unsent message:', mergedAnnouncement } = {}) {
2939
3468
  let existing = '';
2940
3469
  if (state.chat?.chatId === snapshot.chatId) {
2941
3470
  if (state.events.some(event => event.type === 'user-message' && event.clientSubmissionId === submissionId)) return;
@@ -2963,15 +3492,15 @@
2963
3492
  existing = state.localDraft.text;
2964
3493
  }
2965
3494
  const merged = Boolean(existing.trim() && existing.trim() !== text.trim());
2966
- if (merged) text = `${existing}\n\nEarlier unsent message:\n${text}`;
3495
+ if (merged) text = `${existing}\n\n${mergeLabel}\n${text}`;
2967
3496
  if (state.chat?.chatId === snapshot.chatId) {
2968
3497
  clearTimeout(state.draftTimer);
2969
3498
  if (ui.input.value !== text) {
2970
3499
  ui.input.value = text;
2971
3500
  autosize(); updateSendState();
2972
3501
  }
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.');
3502
+ announce(merged ? mergedAnnouncement || 'An earlier unsent message was added to your draft. Review it before sending.'
3503
+ : announcement || 'The message was not sent. Its text is back in your draft.');
2975
3504
  state.localDraft = { chatId: snapshot.chatId, text };
2976
3505
  }
2977
3506
  state.draftVersions.set(snapshot.chatId, (state.draftVersions.get(snapshot.chatId) || 0) + 1);
@@ -2983,6 +3512,12 @@
2983
3512
 
2984
3513
  function initialTurnDefinitelyRefused(error) {
2985
3514
  return sessionNeedsRenewal(error) || error?.status === 413 || error?.status === 400
3515
+ // `chat-record-unreadable` is deliberately NOT here, though POST /turns reads the conversation
3516
+ // at the start and a refusal there IS provably unsent (#1629). The same code also escapes the
3517
+ // route AFTER the turn is durable and dispatched — listChatEvents and the reply's own readChat
3518
+ // both re-read the record once the user-message event is published — and the browser cannot
3519
+ // tell the two apart. Handing the text back then would send it twice; losing it from the
3520
+ // composer, which is what a torn record has always done, only costs the retype.
2986
3521
  || ['chat-provider-unavailable', 'chat-turn-active', 'chat-turn-settling', 'chat-followup-queued', 'chat-followup-unconfirmed',
2987
3522
  'chat-owner-busy', 'chat-host-busy', 'chat-attachment-scope',
2988
3523
  'chat-root-stale', 'chat-archived'].includes(String(error?.code || ''));
@@ -3020,9 +3555,7 @@
3020
3555
  // linking, starting and polling the request itself.
3021
3556
  // There is no mode to choose: the person just asks or says what to change. Every message is sent as
3022
3557
  // 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
3558
  const FILTER_PENDING = 'AI is reading the filter…';
3025
- const DEFAULT_PLACEHOLDER = ui.input.placeholder;
3026
3559
  const FILTER_NOT_OPEN = 'Open Drawing Filter to use this suggestion.';
3027
3560
  // Mirrors the filter page's own FILTER_AI_UNKNOWN: with no page at all, its records are gone too.
3028
3561
  const FILTER_PAGE_GONE = 'This suggestion was made before the Drawing Filter was last opened or reloaded. Ask again from the current filter to apply it.';
@@ -3074,11 +3607,25 @@
3074
3607
  return { state: 'ready', bridge, summary };
3075
3608
  }
3076
3609
 
3077
- /** The composer's only Drawing Filter cue is its placeholder; returns the surface for the caller. */
3610
+ /**
3611
+ * The composer's view of the Drawing Filter surface; returns it for the caller.
3612
+ *
3613
+ * It no longer rewrites the placeholder. One composer, one prompt: owner ruling, Pawel 2026-09-25 —
3614
+ * a second wording here made the same box look like a different box on one screen, for a mode the
3615
+ * person did not choose and cannot see the edges of.
3616
+ *
3617
+ * The mode is still real: Send routes a filter message through the Drawing Filter's own request
3618
+ * path rather than as a normal chat turn — a change request whose answer proposes ticks for the
3619
+ * person to review, run with read-only runtime options. (Not "a read-only question": `sendFilterAi`
3620
+ * hard-codes `kind = 'change'`, and a comment on this screen saying otherwise is how the next
3621
+ * reader gets it backwards.) What still announces it is `paintFloLessContext`'s "Sharing with AI:
3622
+ * Drawing Filter · partial view of <sheet> and its selection" — which is the better cue anyway,
3623
+ * because it NAMES THE SHEET, and it sits directly under the box. (The compose hint does not: its
3624
+ * chain in `clearReport` has no filter branch, and the attach control's blocked reason only speaks
3625
+ * once someone tries to attach. An earlier draft of this comment credited the hint; it was wrong.)
3626
+ */
3078
3627
  function paintFilterComposer() {
3079
- const surface = filterSurface();
3080
- ui.input.placeholder = surface.state === 'off' ? DEFAULT_PLACEHOLDER : FILTER_PLACEHOLDER;
3081
- return surface;
3628
+ return filterSurface();
3082
3629
  }
3083
3630
 
3084
3631
  function filterPendingIn(chatId) {
@@ -3109,7 +3656,11 @@
3109
3656
  return 'FloLess could not access this answer. Check your sign-in and project access, then send your message again. Nothing changed.';
3110
3657
  }
3111
3658
 
3112
- /** Start the read-only guide run. Resolves 'started', 'unconfirmed' (checking), or { refused: message }. */
3659
+ /**
3660
+ * Start the read-only guide run. Resolves 'started', 'unconfirmed' (checking), or { refused: message }.
3661
+ * `notStarted: true` on a refusal means no AI can have started on it, so its words can be given back;
3662
+ * `runtime` is then the setup status when FloLess setting its AI up was the cause (#1650, #1643).
3663
+ */
3113
3664
  async function startFilterRun(requestId, runtime) {
3114
3665
  const controller = new AbortController();
3115
3666
  const deadline = setTimeout(() => controller.abort(), 15000);
@@ -3123,9 +3674,15 @@
3123
3674
  const detail = await started.json().catch(() => null);
3124
3675
  clearTimeout(deadline);
3125
3676
  if (started.status === 409 && detail?.code === 'running') return 'started';
3677
+ // The run route flags a refusal it made before anything started (#1650, #1643). Definite even as a
3678
+ // 5xx; one without its notice is not trusted, and falls through to the rules below.
3679
+ if (detail?.notStarted === true && typeof detail.notice === 'string' && detail.notice) {
3680
+ return { refused: detail.notice, notStarted: true, runtime: detail.runtime ?? null };
3681
+ }
3126
3682
  if (detail?.code === 'filter-ai-provider-mismatch' && typeof detail.error === 'string') return { refused: detail.error };
3127
3683
  if ((started.status === 409 && !detail) || started.status >= 500) return 'unconfirmed';
3128
- if ([401, 402, 403].includes(started.status)) return { refused: filterAccessFailure(started.status, detail) };
3684
+ // The sign-in and licence check refuses before the route runs, so nothing started either.
3685
+ if ([401, 402, 403].includes(started.status)) return { refused: filterAccessFailure(started.status, detail), notStarted: true };
3129
3686
  // Several refusals land here, each with a different cause, so the sentence names none of them.
3130
3687
  return { refused: 'FloLess could not start AI for this request. Nothing changed. Send it again from AI Chat.' };
3131
3688
  }
@@ -3279,6 +3836,53 @@
3279
3836
  }
3280
3837
  }
3281
3838
 
3839
+ /**
3840
+ * Hand a setup status to this conversation's own setup card (#1650): the card polls it, explains it,
3841
+ * offers Cancel or Try again, and keeps Send locked until the AI is set up. Only for the conversation
3842
+ * that sent the message, while it is still that AI's, and only for a status the card can show.
3843
+ */
3844
+ function adoptRuntimeStatus(snapshot, provider, status) {
3845
+ if (!status || typeof status !== 'object' || !['preparing', 'not-installed', 'failed'].includes(status.state)
3846
+ || !sameChat(snapshot) || !state.capability || state.chat?.provider !== provider) return false;
3847
+ state.capability = { ...state.capability, runtime: status };
3848
+ paintRuntime();
3849
+ return true;
3850
+ }
3851
+
3852
+ /** Why a Drawing Filter message was not sent while its AI is set up. The status decides; without one, no cause is claimed. */
3853
+ function filterSetupSentence(provider, status) {
3854
+ const name = providerLabels[provider] || 'the AI';
3855
+ if (status?.state === 'preparing' || status?.state === 'not-installed') {
3856
+ return `FloLess is setting up ${name}, so this message was not sent. It is back in your draft; send it once setup finishes.`;
3857
+ }
3858
+ if (status?.state === 'failed') return `${providerLabels[provider] || 'The AI'} could not be set up, so this message was not sent. It is back in your draft.`;
3859
+ // No status, a failed call (one that timed out may still have started the setup), or a state this
3860
+ // build cannot name.
3861
+ return `FloLess could not confirm that it is setting up ${name}, so this message was not sent. It is back in your draft; try again.`;
3862
+ }
3863
+
3864
+ /**
3865
+ * Ask FloLess to set up the conversation's own AI, through the setup card's Retry route (idempotent).
3866
+ * Resolves `{ installed: true }` when it already is, else the sentence to refuse the message with,
3867
+ * having handed the status to the card. It never waits for the setup: the card carries that wait.
3868
+ * `text` is the refused message, which the refusal puts back in the draft.
3869
+ */
3870
+ async function prepareFilterRuntime(snapshot, provider, text) {
3871
+ let status = null;
3872
+ try {
3873
+ status = (await request(`/api/managed-runtimes/${encodeURIComponent(provider)}/prepare`, { method: 'POST', body: '{}', timeoutMs: 10000 }))?.runtime || null;
3874
+ } catch (error) { console.warn('[chat] could not ask FloLess to set up the Drawing Filter AI:', error); }
3875
+ if (status?.state === 'installed') return { installed: true };
3876
+ const sentence = filterSetupSentence(provider, status);
3877
+ // The card's status check repaints the hint every two seconds; the sentence stays there while the
3878
+ // card shows the setup it was refused for and the words are in the draft (filterSetupHint), not only
3879
+ // until the first repaint.
3880
+ if (adoptRuntimeStatus(snapshot, provider, status)) {
3881
+ state.filterSetupNote = { key: runtimeCardKey(snapshot.chatId, status), sentence, text };
3882
+ }
3883
+ return { installed: false, sentence };
3884
+ }
3885
+
3282
3886
  async function sendFilterAi(surface) {
3283
3887
  const snapshot = captureChat();
3284
3888
  if (!snapshot || state.filterSending) return;
@@ -3302,12 +3906,24 @@
3302
3906
  let failure = null;
3303
3907
  try {
3304
3908
  await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
3305
- const options = await window.flolessBridge?.readOnlyRequestOptions?.().catch(() => null);
3306
- if (!Array.isArray(options?.found)) {
3909
+ // Decided from what launching this conversation's own AI would see NOW, a read of its own (#1650):
3910
+ // the rows AI Chat was painted from can say "set up" for a copy of FloLess's that has gone since.
3911
+ // It answers only with this conversation's own provider, never a silently substituted one.
3912
+ // The read logs its own network and shape failures; a rejection here is a fault in the bridge.
3913
+ const launch = await window.flolessBridge?.filterRuntimeLaunch?.(chat.provider).catch((error) => {
3914
+ console.error('[chat] the Drawing Filter could not read which AI can start:', error);
3915
+ return null;
3916
+ });
3917
+ if (!launch || launch.readiness === 'unchecked') {
3307
3918
  throw filterRefusal('FloLess could not check which AI can answer Drawing Filter messages. Try again in a moment. Nothing was sent.');
3308
3919
  }
3309
- // Answer only with this conversation's own provider, never a silently substituted one.
3310
- if (!options.found.some((runtime) => runtime?.id === chat.provider)) {
3920
+ if (launch.readiness === 'setup') {
3921
+ // FloLess has to set its own copy up first. Nothing is created: the setup starts, this
3922
+ // conversation's setup card shows it and keeps Send locked until it lands, and the words go back.
3923
+ const setup = await prepareFilterRuntime(snapshot, chat.provider, text);
3924
+ if (!setup.installed) throw filterRefusal(setup.sentence);
3925
+ // It finished between the read and the prepare: send as usual.
3926
+ } else if (launch.readiness !== 'ready') {
3311
3927
  throw filterRefusal(`${providerLabels[chat.provider] || 'This AI'} cannot answer Drawing Filter messages on this computer yet. Check it in Integrations, or start a conversation with the other provider. Nothing was sent.`);
3312
3928
  }
3313
3929
  // The promise belongs to the filter page. A page thrown away mid-request never settles it, so
@@ -3378,7 +3994,24 @@
3378
3994
  // Start AI first, so nothing between the link and the run can leave a linked request unstarted.
3379
3995
  const started = await startFilterRun(requestId, chat.provider);
3380
3996
  await mergeFilterEvents(snapshot.chatId);
3381
- if (started?.refused) { finishFilterPending(entry, started.refused); return; }
3997
+ if (started?.refused) {
3998
+ finishFilterPending(entry, started.refused);
3999
+ if (started.notStarted) {
4000
+ // Nothing started, so the words come back to the draft; the conversation also keeps them, with
4001
+ // the notice under them. The setup card shows when FloLess setting its AI up was the cause,
4002
+ // first: it announces itself, and the live region keeps only its last line, so that line is the
4003
+ // whole notice (what happened, why, what next) and then where the words are. The message is in
4004
+ // the conversation, so a merge never calls it unsent. A refusal that is not flagged (another
4005
+ // owner's message) or a lost reply gives nothing back.
4006
+ adoptRuntimeStatus(snapshot, chat.provider, started.runtime);
4007
+ await restoreBackgroundDraft(snapshot, text, submissionId, {
4008
+ announcement: `${started.refused} Its text is back in your draft.`,
4009
+ mergeLabel: 'Earlier message AI did not start on:',
4010
+ mergedAnnouncement: `${started.refused} Its text was added to your draft. Review it before sending.`,
4011
+ });
4012
+ }
4013
+ return;
4014
+ }
3382
4015
  if (started === 'unconfirmed') entry.note = 'Checking whether AI started…';
3383
4016
  announce(FILTER_PENDING);
3384
4017
  if (sameChat(snapshot)) paintEvents({ forceBottom: true });
@@ -3579,7 +4212,14 @@
3579
4212
  // normal turn, not even while the filter page is still loading.
3580
4213
  const filter = filterSurface();
3581
4214
  if (filter.state !== 'off') { await sendFilterAi(filter); return; }
3582
- if (turnIsVisiblyActive() && !state.chat.activeTurn?.local) { await sendFollowup(); return; }
4215
+ if (turnIsVisiblyActive() && !state.chat.activeTurn?.local) {
4216
+ const followup = await sendFollowup();
4217
+ if (followup?.outcome !== 'turn-ended') return;
4218
+ // #1616: the response finished while this follow-up was on its way, so the server refused it
4219
+ // before saving anything. Re-read the conversation and, if it is now idle and the composer still
4220
+ // holds exactly that message, send it once as a new turn instead of asking for a second click.
4221
+ if (!(await resendAfterTurnEnded(followup))) return;
4222
+ }
3583
4223
  const snapshot = captureChat();
3584
4224
  if (!snapshot) return;
3585
4225
  // Bind a carried-over Tekla library first; a refused binding keeps the message unsent.
@@ -3638,6 +4278,29 @@
3638
4278
  } finally { if (sameChat(snapshot)) { setBusy(false); updateSendState(); } }
3639
4279
  }
3640
4280
 
4281
+ /**
4282
+ * A follow-up refused with `chat-turn-stale` was never saved (the route answers `chat-followup-unknown`
4283
+ * for anything it did save), so sending the same text as a new turn cannot duplicate it. Send stays
4284
+ * disabled while the conversation is re-read, and the new turn happens at most once: it goes ahead
4285
+ * only when the refreshed chat is idle and the draft is unchanged: the same text, and the same files,
4286
+ * since the re-read replaces the composer's files with the server's list. It also needs Send to be
4287
+ * usable, which already rules out recovery, an unconfirmed message, an upload and a provider still
4288
+ * being set up. Otherwise the original notice is shown and the draft stays for the user to decide.
4289
+ */
4290
+ async function resendAfterTurnEnded({ snapshot, text, attachmentIds, error }) {
4291
+ state.followupSubmitting = true;
4292
+ updateSendState();
4293
+ try { await refreshConversation(snapshot.chatId); }
4294
+ finally { state.followupSubmitting = false; }
4295
+ if (!sameChat(snapshot)) return false;
4296
+ updateSendState();
4297
+ if (!turnIsVisiblyActive() && !ui.send.disabled
4298
+ && ui.input.value.trim() === text
4299
+ && JSON.stringify(state.attachments.map((item) => item.attachmentId)) === JSON.stringify(attachmentIds)) return true;
4300
+ report(error, '');
4301
+ return false;
4302
+ }
4303
+
3641
4304
  function followupDefinitelyRefused(error) {
3642
4305
  // Session rejection and body-size rejection happen before the route can save a row.
3643
4306
  return ['chat-followup-refused', 'chat-followup-save-failed'].includes(String(error?.code || ''))
@@ -3658,6 +4321,7 @@
3658
4321
  const clientSubmissionId = crypto.randomUUID();
3659
4322
  const previousAttachments = state.attachments;
3660
4323
  let failedDelivery = null;
4324
+ let outcome = null;
3661
4325
  const optimisticEvent = {
3662
4326
  eventId: `local:${clientSubmissionId}`,
3663
4327
  sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
@@ -3731,7 +4395,11 @@
3731
4395
  ui.input.value = text; autosize(); paintAttachments(); paintEvents();
3732
4396
  if (definitiveRefusal) saveDraftSoon();
3733
4397
  else state.localDraft = { chatId: snapshot.chatId, text };
3734
- failedDelivery = { error, prefix: definitiveRefusal ? '' : 'Could not confirm the follow-up' };
4398
+ // The response ended before this arrived (#1616). sendTurn resends it as a new turn, and
4399
+ // shows this refusal only if it cannot.
4400
+ if (definitiveRefusal && error?.code === 'chat-followup-refused' && error?.reason === 'chat-turn-stale') {
4401
+ outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, error };
4402
+ } else failedDelivery = { error, prefix: definitiveRefusal ? '' : 'Could not confirm the follow-up' };
3735
4403
  } finally {
3736
4404
  state.followupSubmitting = false;
3737
4405
  if (sameChat(snapshot)) {
@@ -3740,6 +4408,7 @@
3740
4408
  if (document.activeElement === document.body || document.activeElement === ui.send) ui.input.focus();
3741
4409
  }
3742
4410
  }
4411
+ return outcome;
3743
4412
  }
3744
4413
 
3745
4414
  async function resolveUnknownFollowup(clientSubmissionId) {
@@ -3876,6 +4545,7 @@
3876
4545
  const chatId = snapshot.chatId;
3877
4546
  ui.refresh.disabled = true;
3878
4547
  announce('Refreshing this chat session…');
4548
+ let failure = null;
3879
4549
  try {
3880
4550
  // Re-read before stopping: the browser can retain an old activeTurn after a server restart.
3881
4551
  // That avoids sending a redundant stop for a response the durable conversation already completed.
@@ -3892,8 +4562,10 @@
3892
4562
  await selectConversation(chatId, { focus: false });
3893
4563
  if (!sameChat(snapshot)) return;
3894
4564
  announce('Chat session refreshed.');
3895
- } catch (error) { if (sameChat(snapshot)) report(error, 'Could not refresh this chat session'); }
4565
+ } catch (error) { failure = error; }
3896
4566
  finally { if (sameChat(snapshot)) { ui.refresh.disabled = false; updateSendState(); } }
4567
+ // After updateSendState, which rewrites the composer hint and used to erase this sentence (#1604).
4568
+ if (failure && sameChat(snapshot)) report(failure, 'Could not refresh this chat session');
3897
4569
  }
3898
4570
 
3899
4571
  async function endRecovery() {
@@ -4079,6 +4751,15 @@
4079
4751
  }
4080
4752
  }
4081
4753
 
4754
+ // The background tick. It skips while the previous list is still loading, never stacking one behind
4755
+ // it (#1604): stacked polls hold the browser's few connections to FloLess, and the conversation
4756
+ // itself then cannot load.
4757
+ async function pollChatsTick() {
4758
+ if (state.chatPollInFlight) return;
4759
+ state.chatPollInFlight = true;
4760
+ try { await pollChats(); } finally { state.chatPollInFlight = false; }
4761
+ }
4762
+
4082
4763
  async function pollChats() {
4083
4764
  if (!state.scope || document.hidden) return;
4084
4765
  const scope = state.scope;
@@ -4101,6 +4782,7 @@
4101
4782
  }
4102
4783
  if (!sameScope(scope, generation)) return;
4103
4784
  state.chats = result.chats || [];
4785
+ state.unreadableChats = result.unreadableChats || [];
4104
4786
  const active = state.chats.find((item) => item.chatId === state.chat?.chatId);
4105
4787
  if (active && state.chat) {
4106
4788
  // An event-stream completion can win the race against this list request. Never let a
@@ -4116,7 +4798,7 @@
4116
4798
  // Polling can clear activeTurn after the feed was painted by SSE. Repaint the feed
4117
4799
  // so a completed turn removes any stale live activity indicator. With no conversation
4118
4800
  // selected the feed is the Claude/Codex chooser, which a repaint would erase.
4119
- paintHistory(); paintUnread();
4801
+ paintHistory(); paintUnread(); paintUnreadableNotice();
4120
4802
  // A sign-in OR a sign-OUT made from Integrations or from the user's own terminal changes who
4121
4803
  // answers, and nothing else re-reads it — the row would keep naming the old account for the
4122
4804
  // whole conversation. Use the cheap runtimes read (no provider launch, 10 s server cache)
@@ -4151,11 +4833,37 @@
4151
4833
  }
4152
4834
  if (!sameScope(scope, generation)) return;
4153
4835
  }
4836
+ await recheckManagedCopy(scope, generation);
4837
+ if (!sameScope(scope, generation)) return;
4154
4838
  if (state.chat) { paintSettings(); paintRecovery(); paintApproval(); paintEvents(); updateSendState(); }
4155
4839
  if (state.historyOpen && state.historyFilter === 'instructor-answers') refreshInstructorAnswers();
4156
4840
  } catch { /* SSE or the next poll will recover */ }
4157
4841
  }
4158
4842
 
4843
+ // #1657: FloLess's own copy of this conversation's AI can be moved away, or start re-installing, while
4844
+ // the conversation is open — and nothing else re-reads the capability, so the chat kept an enabled
4845
+ // Send and no setup card. The managed-runtimes read is cheap (no CLI launch). Only when this AI's copy
4846
+ // CHANGES into a state that is not installed is the capability re-read; the server re-checks that copy
4847
+ // on every read, so the answer carries the setup status the card is painted from. Once the card is up,
4848
+ // its own runtime poll takes over (and re-reads the capability when setup finishes).
4849
+ async function recheckManagedCopy(scope, generation) {
4850
+ const chat = state.chat;
4851
+ if (!chat || !state.capability || state.capability.runtime) return;
4852
+ let body;
4853
+ try { body = await request('/api/managed-runtimes', { timeoutMs: 10000 }); } catch { return; }
4854
+ if (!sameScope(scope, generation) || state.chat?.chatId !== chat.chatId) return;
4855
+ const row = (body?.runtimes || []).find((entry) => entry?.runtime === chat.provider);
4856
+ if (!row) return;
4857
+ const seen = `${chat.chatId}:${row.state}`;
4858
+ if (row.state === 'installed' || row.state === 'unsupported-platform') { state.managedCopySeen = seen; return; }
4859
+ if (state.managedCopySeen === seen) return;
4860
+ await loadCapability();
4861
+ if (!sameScope(scope, generation) || state.chat?.chatId !== chat.chatId) return;
4862
+ // Only an answer the server gave settles this state: a failed read is tried again on the next tick.
4863
+ if (!state.capability?.readFailed) state.managedCopySeen = seen;
4864
+ paintRuntime();
4865
+ }
4866
+
4159
4867
  function refreshActivity() {
4160
4868
  paintConversation();
4161
4869
  }
@@ -4177,6 +4885,8 @@
4177
4885
  paintHistory(); paintUnread();
4178
4886
  }
4179
4887
 
4888
+ // Longer than the server's capability-check bound (CAPABILITY_PROBE_TIMEOUT_MS, 12 s) plus its locks.
4889
+ const REQUEST_START_TIMEOUT_MS = 30000;
4180
4890
  async function startRequest(requestId, provider, mode = 'start') {
4181
4891
  if (!state.scope?.owner) throw new Error('Open the Request’s project or workflow before starting its chat.');
4182
4892
  if (provider !== 'claude' && provider !== 'codex') throw new Error('Choose Claude or Codex for this chat.');
@@ -4188,8 +4898,12 @@
4188
4898
  }
4189
4899
  const currentChatId = state.chat && state.chat.provider === provider && !state.chat.activeTurn
4190
4900
  && !state.chat.archivedAt && state.chat.state !== 'recovery' ? state.chat.chatId : undefined;
4901
+ // Starting a Request waits for the AI's capability check (up to 12 s on the server, longer when
4902
+ // it first launches a copy FloLess has only just set up), so a shorter wait here reported
4903
+ // "Couldn't start" for a start that went on to succeed (#1607 QA). The Requests list says
4904
+ // "Still opening…" after 4 s, so the longer wait is not a silent one.
4191
4905
  const result = await request(`/api/chat/requests/${encodeURIComponent(requestId)}/start`, {
4192
- method: 'POST', timeoutMs: 10000,
4906
+ method: 'POST', timeoutMs: REQUEST_START_TIMEOUT_MS,
4193
4907
  body: JSON.stringify({ provider, mode, chatId: currentChatId, expectedOwner: scope.owner }),
4194
4908
  });
4195
4909
  if (!sameScope(scope, generation)) {
@@ -4248,7 +4962,8 @@
4248
4962
  const status = draft ? draft.status : 'bound';
4249
4963
  const frozen = !draft && teklaBindingFrozen(chat);
4250
4964
  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('|');
4965
+ const reads = teklaReadsCopy(library.operations);
4966
+ const key = [chat.chatId, library.sourcePath, library.hostVersion, reads, status, frozen, error || ''].join('|');
4252
4967
  // Keep the same Remove button across polls so keyboard focus survives a repaint.
4253
4968
  if (node.dataset.key === key && !node.hidden) return;
4254
4969
  node.dataset.key = key;
@@ -4259,7 +4974,7 @@
4259
4974
  const copy = document.createElement('span'); copy.className = 'ai-chat-tekla-chip-copy';
4260
4975
  copy.id = `chat-tekla-context-copy-${chat.chatId}`;
4261
4976
  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'));
4977
+ copy.append(lead, document.createTextNode(` · Chat may ask to read ${reads} — FloLess asks you first and checks live each time`));
4263
4978
  if (status === 'bound') {
4264
4979
  const suffix = document.createElement('span'); suffix.className = 'ai-chat-tekla-chip-state';
4265
4980
  suffix.textContent = ' · added to this chat';
@@ -4329,6 +5044,27 @@
4329
5044
  }
4330
5045
  }
4331
5046
 
5047
+ // The reads a library binding permits, as the chip names them. A binding stored before the
5048
+ // selection read existed has no list and permits the model name only.
5049
+ // The closed list the server accepts, in its canonical order: [model name, selection].
5050
+ function teklaChatReads() {
5051
+ return ['Tekla.Structures.Model.Model.GetInfo().ModelName', 'Tekla.Structures.Model.UI.ModelObjectSelector.GetSelectedObjects()'];
5052
+ }
5053
+ function teklaReadsCopy(operations) {
5054
+ const [modelRead, selectionRead] = teklaChatReads();
5055
+ const list = Array.isArray(operations) ? operations : [modelRead];
5056
+ const names = [];
5057
+ if (list.includes(modelRead)) names.push('the open model name');
5058
+ if (list.includes(selectionRead)) names.push('the parts you have selected');
5059
+ return names.join(' or ');
5060
+ }
5061
+ function sameTeklaReads(a, b) {
5062
+ const [modelRead] = teklaChatReads();
5063
+ const left = Array.isArray(a) ? a : [modelRead];
5064
+ const right = Array.isArray(b) ? b : [modelRead];
5065
+ return left.length === right.length && left.every((operation) => right.includes(operation));
5066
+ }
5067
+
4332
5068
  // Returns true when the message may be sent: nothing pending, or the binding was stored.
4333
5069
  async function bindPendingTeklaRead(snapshot) {
4334
5070
  const draft = teklaDraftForChat();
@@ -4338,7 +5074,8 @@
4338
5074
  }
4339
5075
  if (!draft || draft.status !== 'draft') return !draft || draft.status === 'bound';
4340
5076
  const bound = state.chat?.teklaModelRead;
4341
- if (bound && bound.sourcePath === draft.library.sourcePath && bound.hostVersion === draft.library.hostVersion) {
5077
+ if (bound && bound.sourcePath === draft.library.sourcePath && bound.hostVersion === draft.library.hostVersion
5078
+ && sameTeklaReads(bound.operations, draft.library.operations)) {
4342
5079
  state.teklaDraft = null; paintTeklaChip(); return true;
4343
5080
  }
4344
5081
  draft.status = 'binding'; draft.error = null;
@@ -4350,7 +5087,8 @@
4350
5087
  if (!sameChat(snapshot)) return false;
4351
5088
  // Never invent the binding locally: only the server's own record of THIS library for this chat counts.
4352
5089
  const stored = updated && updated.chatId === snapshot.chatId ? updated.teklaModelRead : null;
4353
- if (!stored || stored.sourcePath !== draft.library.sourcePath || stored.hostVersion !== draft.library.hostVersion) {
5090
+ if (!stored || stored.sourcePath !== draft.library.sourcePath || stored.hostVersion !== draft.library.hostVersion
5091
+ || !sameTeklaReads(stored.operations, draft.library.operations)) {
4354
5092
  draft.status = 'draft';
4355
5093
  draft.error = 'Message not sent. FloLess could not confirm the Tekla library was added to this chat. Try again.';
4356
5094
  paintTeklaChip();
@@ -4379,7 +5117,7 @@
4379
5117
  // the AI would repeat a stale name as current. A fresh read shows the name at that moment.
4380
5118
  return `Earlier FloLess check: reading the open model name through the Tekla model library at ${receipt.sourcePath} `
4381
5119
  + `worked (Tekla ${receipt.hostVersion}${checked}). The generated agent's commands remain unverified. `
4382
- + 'Help me use this read in this project.';
5120
+ + 'You can ask to read the open model name or the parts I have selected in Tekla. Help me use these reads in this project.';
4383
5121
  }
4384
5122
 
4385
5123
  // Leave the selected conversation for the Claude/Codex choice. A prior async select can still be
@@ -4391,6 +5129,8 @@
4391
5129
  closeSource(); clearLiveStream(true);
4392
5130
  state.chat = null; state.events = []; state.attachments = []; state.integrations = null; state.capability = null;
4393
5131
  updateOffscreenActivity();
5132
+ // The left chat's library chip ("added to this chat") must not linger over the chooser.
5133
+ paintTeklaChip();
4394
5134
  }
4395
5135
 
4396
5136
  // Graft receipt → unsent Chat draft. Opening performs no binding, sends nothing and never
@@ -4401,7 +5141,8 @@
4401
5141
  || typeof receipt.hostVersion !== 'string' || !receipt.hostVersion) {
4402
5142
  throw Object.assign(new Error('FloLess could not read the result of the model check. Check the model read again, then continue in AI Chat.'), { plainEnglish: true });
4403
5143
  }
4404
- const library = { sourcePath: receipt.sourcePath, hostVersion: receipt.hostVersion };
5144
+ // The chip lists exactly these reads, and Send binds exactly these: nothing defaults to more.
5145
+ const library = { sourcePath: receipt.sourcePath, hostVersion: receipt.hostVersion, operations: teklaChatReads() };
4405
5146
  const draft = teklaDraftText(receipt);
4406
5147
  await refreshScope();
4407
5148
  if (!state.scope?.owner) throw Object.assign(new Error('Open a project or workflow before continuing in AI Chat.'), { plainEnglish: true });
@@ -4463,9 +5204,10 @@
4463
5204
  const activityResizeObserver = new ResizeObserver(updateOffscreenActivity);
4464
5205
  activityResizeObserver.observe(ui.feed);
4465
5206
  ui.refresh.addEventListener('click', refreshChatSession);
4466
- ui.history.addEventListener('keydown', (event) => {
5207
+ function closeHistoryOnEscape(event) {
4467
5208
  if (event.key === 'Escape') { event.preventDefault(); toggleHistory(false, { focusToggle: true }); }
4468
- });
5209
+ }
5210
+ ui.history.addEventListener('keydown', closeHistoryOnEscape);
4469
5211
  ui.newChat.addEventListener('click', () => {
4470
5212
  beginProviderChoice();
4471
5213
  toggleHistory(false); setBusy(false); providerChooser(); clearReport();
@@ -4514,7 +5256,7 @@
4514
5256
  if (files.length) { event.preventDefault(); attachFiles(files); }
4515
5257
  });
4516
5258
  ui.tab.addEventListener('click', () => markRead());
4517
- document.addEventListener('visibilitychange', () => { if (!document.hidden) { markRead(); pollChats(); } });
5259
+ document.addEventListener('visibilitychange', () => { if (!document.hidden) { markRead(); void pollChatsTick(); } });
4518
5260
  document.addEventListener('pointerdown', (event) => {
4519
5261
  // Switch account lives inside the Provider .ai-chat-setting but opens no picker of its own, so
4520
5262
  // it must not be treated as "clicked the picker's own control" and leave an open list behind.
@@ -4535,12 +5277,18 @@
4535
5277
  if (node) contextObserver.observe(node, { attributes: true, childList: id === 'ws-step-tabs', subtree: id === 'ws-step-tabs' });
4536
5278
  }
4537
5279
 
4538
- state.refreshTimer = setInterval(pollChats, 5000);
5280
+ state.refreshTimer = setInterval(pollChatsTick, 5000);
4539
5281
  window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); activityResizeObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
4540
5282
  window.flolessChat = {
4541
5283
  refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openDraft, openVerifiedTeklaDraft,
4542
5284
  startProjectIntake, resumeProjectIntake,
4543
5285
  currentProvider: () => state.chat?.provider ?? null,
5286
+ // The New project dialog's AI choice (#1605) words each provider's sign-in the way this
5287
+ // panel's own chooser does, so the two ways into a conversation read the same.
5288
+ providerAccountLabel,
5289
+ // The setup card's own sentences, so a start that sets FloLess's copy up first (#1607) says
5290
+ // exactly what this panel would.
5291
+ runtimeNotice,
4544
5292
  };
4545
5293
  window.dispatchEvent(new CustomEvent('floless:chat-ready'));
4546
5294
  paintFloLessContext();