@floless/app 0.174.1 → 0.175.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/autostart.mjs +117 -10
  2. package/dist/floless-server.cjs +2 -2
  3. package/dist/pdf-engine/floless_pdf/__init__.py +7 -3
  4. package/dist/pdf-engine/floless_pdf/backend_pdfium.py +292 -13
  5. package/dist/pdf-engine/floless_pdf/backend_pymupdf.py +25 -3
  6. package/dist/pdf-engine/floless_pdf/images.py +4 -3
  7. package/dist/pdf-engine/floless_pdf/pages.py +136 -0
  8. package/dist/schemas/steel.model.v2.schema.json +44 -1
  9. package/dist/skills/floless-app-approval/SKILL.md +28 -3
  10. package/dist/skills/floless-app-knowledge/SKILL.md +3 -2
  11. package/dist/skills/floless-app-sketches/SKILL.md +71 -0
  12. package/dist/skills/floless-app-sketches/references/steel-plate.md +15 -0
  13. package/dist/skills/floless-app-steel-model/SKILL.md +11 -1
  14. package/dist/skills/floless-app-steel-model/references/elements.md +90 -23
  15. package/dist/skills/floless-app-steel-takeoff/SKILL.md +11 -6
  16. package/dist/web/agents.js +1 -1
  17. package/dist/web/app.css +120 -15
  18. package/dist/web/app.js +89 -38
  19. package/dist/web/aware-hold.js +10 -0
  20. package/dist/web/aware.js +405 -51
  21. package/dist/web/boot-watchdog.js +249 -0
  22. package/dist/web/card-details.js +88 -0
  23. package/dist/web/chat.css +29 -0
  24. package/dist/web/chat.js +430 -128
  25. package/dist/web/commands-connection-design.js +23 -0
  26. package/dist/web/commands-revit.js +3 -0
  27. package/dist/web/commands-shell.js +226 -10
  28. package/dist/web/commands-steel.js +93 -4
  29. package/dist/web/commands-tekla-parser.js +21 -1
  30. package/dist/web/connection-design-editor.html +71 -0
  31. package/dist/web/connection-design-editor.js +794 -61
  32. package/dist/web/connection-design-handles.js +9 -3
  33. package/dist/web/element-approval.js +74 -0
  34. package/dist/web/element-context.js +76 -6
  35. package/dist/web/element-geometry.js +8 -2
  36. package/dist/web/element-holds.js +68 -5
  37. package/dist/web/element-type-actions.js +22 -3
  38. package/dist/web/element-types.js +12 -5
  39. package/dist/web/element-words.js +15 -11
  40. package/dist/web/grid-place.js +51 -0
  41. package/dist/web/guide.js +2 -0
  42. package/dist/web/index.html +13 -16
  43. package/dist/web/instructor.js +5 -2
  44. package/dist/web/missed-routines.js +6 -1
  45. package/dist/web/model-change-findings.js +100 -30
  46. package/dist/web/model-change-review.js +411 -27
  47. package/dist/web/model-clash-check.css +100 -0
  48. package/dist/web/model-clash-check.js +681 -0
  49. package/dist/web/model-clip-box.js +204 -0
  50. package/dist/web/model-clip-list.js +153 -3
  51. package/dist/web/model-clip-session.js +3 -3
  52. package/dist/web/model-clip-three-overlay.js +135 -25
  53. package/dist/web/model-editor.css +2 -0
  54. package/dist/web/model-elements.js +273 -18
  55. package/dist/web/model-fit-checks.js +354 -0
  56. package/dist/web/model-spatial-panel.js +9 -3
  57. package/dist/web/model-spatial-tools.js +12 -3
  58. package/dist/web/model-tekla-selection.js +74 -0
  59. package/dist/web/model-view-query.js +70 -14
  60. package/dist/web/model-viewport-revit-adapter.js +8 -7
  61. package/dist/web/model-viewport-toolbar.js +8 -4
  62. package/dist/web/pages.js +78 -1
  63. package/dist/web/project-history.js +31 -1
  64. package/dist/web/revit-editor.css +34 -1
  65. package/dist/web/revit-editor.js +174 -55
  66. package/dist/web/run-history.js +8 -0
  67. package/dist/web/sketch-editor.js +141 -2
  68. package/dist/web/sketches.js +192 -6
  69. package/dist/web/start-place.js +46 -0
  70. package/dist/web/steel-3d-core.js +70 -0
  71. package/dist/web/steel-3d-view.js +288 -47
  72. package/dist/web/steel-change-review.css +28 -0
  73. package/dist/web/steel-custom-connection.js +6 -0
  74. package/dist/web/steel-editor.html +532 -33
  75. package/dist/web/steel-filter.html +8 -3
  76. package/dist/web/steel-model-checks.css +76 -0
  77. package/dist/web/steel-model-v2-commands.js +17 -0
  78. package/dist/web/steel-view-generation.js +6 -2
  79. package/dist/web/teams.js +259 -19
  80. package/dist/web/tekla-editor.html +1 -0
  81. package/dist/web/terminal-requests.js +6 -0
  82. package/dist/web/vendor/connection-engine.js +886 -91
  83. package/dist/web/workspaces.js +630 -48
  84. package/package.json +2 -1
  85. package/preferences-file.mjs +27 -0
package/dist/web/chat.js CHANGED
@@ -90,7 +90,7 @@
90
90
  // #1859: per message (client submission id), why the open Drawing Filter's selection did not go with it.
91
91
  filterNotShared: new Map(),
92
92
  // The last sentence report() put under the box, held there until the person acts on it (#1683):
93
- // { message, scope, chatId, draft, attachments, blocked }. See heldReport().
93
+ // { message, tone, scope, chatId, draft, attachments, blocked }. See heldReport().
94
94
  reportHold: null,
95
95
  // #3510: a message from the box still in its checks before it shows. See startSendCheck.
96
96
  sendCheck: null,
@@ -180,12 +180,24 @@
180
180
  async function request(path, options = {}) {
181
181
  const scopeGeneration = state.scopeGeneration;
182
182
  const sessionLifecycle = state.sessionLifecycle;
183
- await globalThis.flolessStartupAdmission?.admit(path, { method: options.method, signal: options.signal });
183
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 30000;
184
+ const transportFailure = (cause) => {
185
+ if (cause?.name === 'TimeoutError' || cause?.name === 'AbortError') {
186
+ return Object.assign(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.'),
187
+ { code: 'local-timeout', forPerson: true, cause: { path, timeoutMs, name: cause.name } });
188
+ }
189
+ return Object.assign(new Error('FloLess did not answer the chat request.', { cause }), { code: 'local-unreachable' });
190
+ };
191
+ try {
192
+ await globalThis.flolessStartupAdmission?.admit(path, { method: options.method, signal: options.signal });
193
+ } catch (error) {
194
+ if (error?.code === 'local-timeout' || error?.code === 'chat-page-closed') throw error;
195
+ throw transportFailure(error);
196
+ }
184
197
  // A new scope adopts the server-wide cookie/readiness handshake; scoped reads keep their original owner.
185
198
  if (path === '/api/chat/session') {
186
199
  if (state.sessionDisposed || sessionLifecycle !== state.sessionLifecycle) throw Object.assign(new Error('Chat page is closed.'), { code: 'chat-page-closed' });
187
200
  } else if (scopeGeneration !== state.scopeGeneration) throw Object.assign(new Error('Chat scope changed.'), { code: 'chat-page-closed' });
188
- const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 30000;
189
201
  const init = { credentials: 'same-origin', ...options };
190
202
  delete init.timeoutMs;
191
203
  // Every chat request is local, but a stopped server or a provider capability probe can otherwise
@@ -199,17 +211,7 @@
199
211
  try {
200
212
  response = await fetch(path, init);
201
213
  } catch (error) {
202
- if (error?.name === 'TimeoutError' || error?.name === 'AbortError') {
203
- // The server is almost always running but busy when this happens (#1604), so the sentence
204
- // leads with "try again" and keeps "is it still running?" as the fallback.
205
- 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.');
206
- timeout.code = 'local-timeout'; timeout.forPerson = true;
207
- // Which call timed out, and after how long: the sentence above is for the user, this is for
208
- // whoever reads the console when it happens (#1604).
209
- timeout.cause = { path, timeoutMs, name: error.name };
210
- throw timeout;
211
- }
212
- throw error;
214
+ throw transportFailure(error);
213
215
  }
214
216
  const contentType = response.headers.get('content-type') || '';
215
217
  const readOnly = /^(GET|HEAD)$/.test(String(options.method || 'GET').toUpperCase());
@@ -220,9 +222,16 @@
220
222
  return Object.assign(new Error(failureCopy({ status: response.status, body: { ok: false, code: 'response-unreadable' } }, { retrySafe: readOnly }).text),
221
223
  { code: 'response-unreadable', status: response.status, body: { ok: false, code: 'response-unreadable' } });
222
224
  };
223
- const body = contentType.includes('application/json')
224
- ? await response.json().catch((cause) => { if (response.ok) throw unreadable(cause); return null; })
225
- : await response.text();
225
+ const isJson = contentType.includes('application/json');
226
+ let body;
227
+ try {
228
+ body = await (isJson ? response.json() : response.text());
229
+ } catch (cause) {
230
+ if (isJson && cause?.name === 'SyntaxError') {
231
+ if (response.ok) throw unreadable(cause);
232
+ body = null;
233
+ } else throw transportFailure(cause);
234
+ }
226
235
  if (!response.ok) {
227
236
  // #3097: the server's own sentence when it wrote one, else the shared one; never "(<status>)". A text answer (an
228
237
  // HTML error page, a proxy's plain text) is not FloLess's JSON, so it goes to the console, never into the message.
@@ -230,7 +239,9 @@
230
239
  if (!json) console.warn('[chat] a request was answered with something other than FloLess JSON', path, response.status, String(body ?? '').slice(0, 200));
231
240
  const said = personText(json);
232
241
  const error = new Error(said || failureCopy({ status: response.status, body: json || {} }, { retrySafe: readOnly }).text);
233
- error.code = body?.code || null;
242
+ error.code = body?.code || (response.status >= 500 && !said ? 'local-unreachable' : null);
243
+ if (error.code === 'local-unreachable') error.cause = { path, status: response.status, body };
244
+ if (said) error.serverSentence = said;
234
245
  error.reason = body?.reason || null;
235
246
  error.recovery = Array.isArray(body?.recovery) ? body.recovery : null;
236
247
  // The subscription gate's answer (state + reason) decides which sign-in sentence errorMessage shows. #3097 3b: the
@@ -341,6 +352,7 @@
341
352
  // request() writes the timeout's sentence itself. Without this it fell through to the generic "could
342
353
  // not complete this chat action", which hid the one fact the user could act on (#1604).
343
354
  if (code === 'local-timeout' && raw) return raw;
355
+ if (code === 'local-unreachable') return 'FloLess didn’t answer for a moment, so this didn’t finish. Check the conversation before trying again.';
344
356
  // #1907: the server marks a not-sent reason it already wrote for the person; it is shown as is.
345
357
  if (code === 'chat-send-refused-plain' && raw) return raw;
346
358
  // A lapsed FloLess sign-in or subscription refuses every chat request with 402. It used to read as "could not
@@ -429,6 +441,10 @@
429
441
  'change-allowance-changed': 'The changes allowed for this chat changed. Choose again.',
430
442
  'tekla-allowance-changed': 'The Tekla read permission for this chat changed. Choose again.',
431
443
  'connector-allowance-changed': 'The connectors allowed for this chat changed. Choose again.',
444
+ // #4032: nothing was recorded or sent, and the card is still waiting for the person.
445
+ 'chat-approval-not-sent': 'FloLess couldn’t save your decision on this card, so it was not sent. Wait a moment, then choose again.',
446
+ // #4032: the card closed with a "Not sent" line; the toast says the same, never "could not confirm".
447
+ 'chat-approval-not-delivered': 'Your decision on this card did not reach the AI, so nothing was done. Send a message asking the AI to propose it again if you still want it.',
432
448
  };
433
449
  // #3255: the conversation is from an earlier opening of this Workspace; reopening does not help, a new one does.
434
450
  // Written out, not the shared constant: several test harnesses lift this function alone.
@@ -440,6 +456,7 @@
440
456
  return codeMessages[String(error.reason)];
441
457
  }
442
458
  if (codeMessages[code]) return codeMessages[code];
459
+ if (error?.serverSentence) return error.serverSentence;
443
460
  if (error?.status === 413) return 'This message is too large to send. Shorten it, then try again.';
444
461
  if (code === 'request-chat-owner-mismatch' || /request chat link belongs to another owner/i.test(raw)) {
445
462
  return 'This request is linked to another project or workflow. Open the project or workflow shown on the request, then try again.';
@@ -578,7 +595,7 @@
578
595
  return `The ${label} chat is not ready on this computer. Reload FloLess and try again.`;
579
596
  }
580
597
 
581
- function report(error, prefix = '', messages = null) {
598
+ function report(error, prefix = '', messages = null, tone = 'error') {
582
599
  if (error?.code === 'chat-page-closed') return;
583
600
  const code = String(error && error.code || '');
584
601
  // #1890 PR 3b: a conversation that moved is not a failure — request() already follows it into its workflow.
@@ -591,15 +608,17 @@
591
608
  // warning. A check made here in the browser (too many images, a file too large) is neither: the
592
609
  // sentence already says everything, so it is not logged.
593
610
  const status = Number.isInteger(error?.status) ? error.status : null;
594
- const unexpected = code === 'local-timeout' || (status !== null && status >= 500 && !code)
611
+ const unexpected = code === 'local-timeout' || code === 'local-unreachable' || (status !== null && status >= 500 && !code)
595
612
  || error?.name === 'TypeError' || error?.name === 'SyntaxError';
596
613
  if (unexpected) console.error(`[ai-chat] ${message}`, error?.cause ?? '', error);
597
614
  else if (status !== null) console.warn(`[ai-chat] ${message}`, error);
598
615
  state.reportLiveMessage = message;
599
616
  announce(message, () => state.reportLiveMessage === message);
600
617
  ui.hint.textContent = message;
601
- ui.hint.classList.add('error');
602
- holdReport(message);
618
+ ui.hint.classList.remove('working', 'error', 'retrying', 'warn');
619
+ ui.hint.removeAttribute('aria-label');
620
+ ui.hint.classList.add(tone);
621
+ holdReport(message, tone);
603
622
  }
604
623
 
605
624
  /**
@@ -608,9 +627,9 @@
608
627
  * happened, so it is held, with what the composer looked like when it was said, until the person acts
609
628
  * on it (heldReport).
610
629
  */
611
- function holdReport(message) {
630
+ function holdReport(message, tone) {
612
631
  state.reportHold = {
613
- message, scope: scopeKey(state.scope), chatId: state.chat?.chatId ?? null,
632
+ message, tone, scope: scopeKey(state.scope), chatId: state.chat?.chatId ?? null,
614
633
  draft: ui.input.value, attachments: attachmentKey(), blocked: sendBlocker(),
615
634
  };
616
635
  }
@@ -659,7 +678,7 @@
659
678
  }
660
679
 
661
680
  function clearReport() {
662
- ui.hint.classList.remove('error');
681
+ ui.hint.classList.remove('error', 'retrying', 'warn');
663
682
  // #3510: Send reads as busy only while a message sent from this very conversation is shown to be on its way; set
664
683
  // before the returns below, so a held report or recovery line elsewhere cannot keep it busy.
665
684
  const check = state.sendCheck;
@@ -670,7 +689,7 @@
670
689
  ui.hint.classList.remove('working');
671
690
  ui.hint.removeAttribute('aria-label');
672
691
  ui.hint.textContent = held;
673
- ui.hint.classList.add('error');
692
+ ui.hint.classList.add(state.reportHold?.tone || 'error');
674
693
  return;
675
694
  }
676
695
  const pending = state.sessionRecoveryHint;
@@ -1424,6 +1443,7 @@
1424
1443
  function showUnscoped() {
1425
1444
  paintComposerDisclosure();
1426
1445
  clearProviderChoice();
1446
+ if (state.refreshRecovery || state.refreshReport) clearRefreshRecovery(state.chat?.chatId);
1427
1447
  closeSource();
1428
1448
  clearLiveStream(true);
1429
1449
  state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.movedChats = []; state.movedChatsKnown = null; state.chat = null; state.events = []; state.capability = null; state.attachments = []; state.followupUnknownId = null;
@@ -1455,7 +1475,7 @@
1455
1475
  paintRecovery(); paintApproval(); paintSettings();
1456
1476
  ui.stop.hidden = true; ui.send.hidden = false;
1457
1477
  ui.rename.hidden = true;
1458
- ui.status.textContent = ''; ui.hint.classList.remove('error');
1478
+ ui.status.textContent = ''; ui.hint.classList.remove('error', 'retrying', 'warn');
1459
1479
  ui.hint.textContent = 'Open a project or workflow to start chatting.';
1460
1480
  paintHistory(); paintUnread();
1461
1481
  }
@@ -2180,6 +2200,7 @@
2180
2200
  state.archivedChats = state.archivedChats.filter((item) => item.chatId !== chatId);
2181
2201
  paintHistory(); paintUnread();
2182
2202
  if (state.chat?.chatId !== chatId) { announce(announcement); return; }
2203
+ if (state.refreshRecovery || state.refreshReport) clearRefreshRecovery(chatId);
2183
2204
  closeSource(); clearLiveStream(true);
2184
2205
  state.chat = null; state.events = []; state.attachments = []; state.followupUnknownId = null; state.integrations = null;
2185
2206
  updateOffscreenActivity();
@@ -2334,6 +2355,19 @@
2334
2355
  let inlineSlots = null;
2335
2356
  const CITE_ANCHOR = /^[a-z0-9-]{1,16}$/;
2336
2357
  const INLINE_DIRECTIVE = /:(cite|assume)\[([^\]\n]{1,120})\]/g;
2358
+ // #4015: one `:cite[...]` may name several sources, `:cite[a,b]` (spaces after commas allowed, at most 6). Read the same
2359
+ // way on the server (`citeMarkerAnchors` in server/chat-citation.ts, kept equal by chat-citation-ui.test.ts). Any
2360
+ // entry that is not an anchor makes the whole marker unreadable, so it stays as the text the AI wrote.
2361
+ const CITE_MARKER_MAX = 6;
2362
+ function citeMarkerAnchors(value) {
2363
+ const parts = String(value).split(',').map((part) => part.trim());
2364
+ return parts.length <= CITE_MARKER_MAX && parts.every((part) => CITE_ANCHOR.test(part)) ? parts : null;
2365
+ }
2366
+ /** Whether a block of answer text marks this anchor, by any readable `:cite[...]` marker in it. */
2367
+ function blockCitesAnchor(block, anchor) {
2368
+ for (const match of block.matchAll(/:cite\[([^\]\n]{1,120})\]/g)) if (citeMarkerAnchors(match[1])?.includes(anchor)) return true;
2369
+ return false;
2370
+ }
2337
2371
 
2338
2372
  /*
2339
2373
  * #2725: emphasis by CommonMark's delimiter rules, one line at a time, so a `*` or `_` inside a word stays what it is:
@@ -2413,8 +2447,13 @@
2413
2447
  function markdownRun(text) {
2414
2448
  if (!text) return '';
2415
2449
  const marked = inlineSlots ? text.replace(INLINE_DIRECTIVE, (all, kind, value) => {
2416
- if (kind === 'cite' && !CITE_ANCHOR.test(value)) return all;
2417
- const n = inlineSlots.push(kind === 'cite' ? { kind, anchor: value } : { kind, text: value }) - 1;
2450
+ if (kind === 'cite') {
2451
+ const anchors = citeMarkerAnchors(value);
2452
+ if (!anchors) return all;
2453
+ // One chip per anchor, side by side, where the marker stood.
2454
+ return anchors.map((anchor) => `${inlineSlots.push({ kind, anchor }) - 1}`).join('');
2455
+ }
2456
+ const n = inlineSlots.push({ kind, text: value }) - 1;
2418
2457
  return `${n}`;
2419
2458
  }) : text;
2420
2459
  return markdownEmphasis(escapeMarkdownHtml(marked)).replace(/(\d+)/g, '<span class="ai-chat-inline-slot" data-inline-slot="$1"></span>');
@@ -2886,7 +2925,7 @@
2886
2925
  const held = state.events.find((row) => row.eventId === citationId);
2887
2926
  if (!held || held.turnId !== turnId) return false;
2888
2927
  if (held.type === 'citation') return (held.payload?.entries ?? []).some((entry) => entry?.anchor === anchor);
2889
- return held.type === 'assistant-message' && (answerText(turnId)?.blocks ?? []).some((block) => block.includes(`:cite[${anchor}]`));
2928
+ return held.type === 'assistant-message' && (answerText(turnId)?.blocks ?? []).some((block) => blockCitesAnchor(block, anchor));
2890
2929
  }
2891
2930
 
2892
2931
  /**
@@ -5733,8 +5772,13 @@
5733
5772
  // #2223: a question the AI asked while nobody was watching went unanswered, not declined.
5734
5773
  // #3761: a request FloLess said no to while the reply was stopped or its state unknown was declined, not left unanswered.
5735
5774
  const recoveryDecline = event.payload?.tool === 'approval-dropped' && String(event.payload?.approvalId || '').startsWith('recovery-declined:');
5775
+ // #3913: the person decided this card: FloLess restarted while passing it on, so what the AI received is unknown
5776
+ // (`unconfirmed`), or the decision provably never reached the AI (`not-delivered`). Never "Not answered". #4032: a
5777
+ // card a restart found waiting may have been clicked, so it was dropped, which claims neither (`dropped`).
5778
+ const dropped = event.payload?.tool === 'approval-dropped' ? event.payload?.outcome : null;
5736
5779
  label.textContent = review === 'approved' ? 'Auto-approved' : review ? 'Held back'
5737
5780
  : unattended ? (event.payload?.tool === 'unattended-question' ? 'Not asked'
5781
+ : dropped === 'unconfirmed' ? 'Not confirmed' : dropped === 'not-delivered' ? 'Not sent' : dropped === 'dropped' ? 'Dropped'
5738
5782
  : event.payload?.tool === 'approval-dropped' && !recoveryDecline ? 'Not answered' : 'Declined')
5739
5783
  : unchecked ? 'Not checked' : fresh ? 'New session' : 'Not done';
5740
5784
  item.append(label, document.createTextNode(` · ${event.payload.message}`));
@@ -5801,7 +5845,8 @@
5801
5845
  const change = event.payload.change;
5802
5846
  const label = document.createElement('strong');
5803
5847
  if (event.payload.reason) {
5804
- label.textContent = 'Not changed';
5848
+ // #4102: the decision FloLess made at its last check, never a claim about the files.
5849
+ label.textContent = 'Stopped at the last check';
5805
5850
  item.append(label, document.createTextNode(' · FloLess could not confirm this change could still go ahead. Ask the AI to check the current files and scope, then try again.'));
5806
5851
  return item;
5807
5852
  }
@@ -6270,20 +6315,37 @@
6270
6315
  return awaited.state === 'proposed' && id !== awaits.id ? awaits.waiting : entry.error;
6271
6316
  }
6272
6317
 
6273
- function repaintActionCards(focusProposal) {
6318
+ function repaintActionCards() {
6274
6319
  for (const old of ui.feed?.querySelectorAll('.ai-chat-action-card[data-proposal-id]') || []) {
6275
6320
  const event = state.events.find((known) => known.eventId === old.dataset.eventId);
6276
6321
  if (!event) continue;
6322
+ // #4116: only a card the keyboard is in keeps it; a card settled elsewhere or in the background never takes it.
6323
+ const active = document.activeElement;
6324
+ const held = active && active !== document.body && old.contains(active) ? String(active.dataset?.commandId || '') : null;
6277
6325
  const next = renderActionProposal(event);
6278
- if (next !== old) old.replaceWith(next);
6279
- }
6280
- if (focusProposal) {
6281
- const card = ui.feed?.querySelector(`.ai-chat-action-card[data-proposal-id="${CSS.escape(focusProposal)}"]`);
6282
- const target = card?.querySelector('[data-command-id^="shell.chat-action-stop"]') || card?.querySelector('.ai-chat-action-status');
6283
- target?.focus({ preventScroll: true });
6326
+ if (next === old) continue;
6327
+ old.replaceWith(next);
6328
+ if (held !== null) focusActionCard(next, held);
6284
6329
  }
6285
6330
  }
6286
6331
 
6332
+ /**
6333
+ * #4116: where the keyboard goes in a card that was rebuilt under it: the same button while it is usable (one waiting for
6334
+ * its answer is aria-disabled, so it still is, and so is one a failure put back), else what the card now says: the run's
6335
+ * Stop, the folded card itself (read by its one line, so it is heard once), or its result line, else its first usable
6336
+ * control, else the card.
6337
+ */
6338
+ function focusActionCard(card, commandId) {
6339
+ const usable = (node) => Boolean(node) && !node.disabled && !node.closest('[hidden]');
6340
+ const same = commandId ? [...card.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === commandId) : null;
6341
+ const stop = card.querySelector('[data-command-id^="shell.chat-action-stop"]');
6342
+ const status = card.querySelector('.ai-chat-action-status');
6343
+ const target = (usable(same) && same) || (usable(stop) && stop) || (card.classList.contains('is-collapsed') && card)
6344
+ || (status?.textContent && status) || [...card.querySelectorAll('button')].find(usable) || card;
6345
+ if (target === card) card.tabIndex = -1;
6346
+ target.focus({ preventScroll: true });
6347
+ }
6348
+
6287
6349
  /** A card button. Its Instructor instance is the proposal (two cards for one action never share a carrier), and it
6288
6350
  * is narrated by what the card asks, e.g. "Run dummy-report with its default inputs". */
6289
6351
  function actionButton(label, commandId, proposalId, summary, className = '') {
@@ -6576,18 +6638,38 @@
6576
6638
  const entry = actionCards.get(proposalId);
6577
6639
  if (!entry || entry.busy || state.chat?.earlierOpening) return;
6578
6640
  const title = String(event.payload?.title || 'the action');
6579
- entry.busy = verb; entry.error = ''; entry.waitingOn = null;
6641
+ entry.busy = verb; entry.pressed = verb; entry.error = ''; entry.waitingOn = null; entry.slow = '';
6580
6642
  repaintActionCards();
6581
- let focus = proposalId;
6643
+ // #3878: a click FloLess has not answered in 4 seconds (a busy computer can hold one far longer) says so, once, in the
6644
+ // card's own status line. That line is already on screen, so writing into it is announced politely a single time; a
6645
+ // repaint while it waits paints the same words (paintActionProposal), and the answer clears them.
6646
+ // Only a card still showing its buttons says it: one another window settled meanwhile keeps its own line.
6647
+ const slow = setTimeout(() => {
6648
+ if (entry.busy !== verb) return;
6649
+ entry.slow = 'Still waiting for FloLess. It can take longer when this computer is busy.';
6650
+ const live = ['proposed', 'executing'].includes(entry.node?.dataset.state) && !state.chat?.earlierOpening;
6651
+ const line = live ? entry.node.querySelector('.ai-chat-action-status') : null;
6652
+ if (line) line.textContent = entry.slow;
6653
+ }, 4000);
6654
+ // #4116: what a Not now or Stop that went through says, once the card is painted (finally, below).
6655
+ let said = '';
6582
6656
  try {
6583
6657
  // Add-ons S2b: a confirm carries what the person ticked on the card (the server refuses one that misses a tick).
6584
6658
  const acks = event.payload?.acknowledgements;
6585
6659
  const { ok, body } = await sendActionProposal(proposalId, verb,
6586
6660
  verb === 'confirm' && Array.isArray(acks) && acks.length && window.flolessCardAcks ? window.flolessCardAcks.body(acks, entry.ticks || new Set()) : {});
6661
+ // FloLess answered: a step this window takes next (below) may wait on the person, not on FloLess.
6662
+ clearTimeout(slow);
6663
+ if (entry.slow) {
6664
+ const line = entry.node?.querySelector('.ai-chat-action-status');
6665
+ if (line && line.textContent === entry.slow) line.textContent = '';
6666
+ entry.slow = '';
6667
+ }
6587
6668
  if (ok) {
6588
6669
  entry.local = { state: body.proposal?.state || (verb === 'decline' ? 'declined' : 'executing'), result: body.proposal?.result || null, supersededBy: null };
6589
6670
  keepTick(entry, body.proposal?.acknowledged);
6590
- announce(verb === 'confirm' ? `${title}: started.` : verb === 'decline' ? `Not now: ${title}.` : `Asked ${title} to stop.`);
6671
+ if (verb === 'confirm') announce(`${title}: started.`);
6672
+ else said = verb === 'decline' ? `Not now: ${title}.` : `Asked ${title} to stop.`;
6591
6673
  // #2290: a step only this window may take (its route checks the window's own origin) is taken here, now that the
6592
6674
  // person confirmed it: the same flow the menu or the Requests button runs.
6593
6675
  if (verb === 'confirm' && event.payload?.browserStep) {
@@ -6612,16 +6694,23 @@
6612
6694
  // window confirming it) is then not outranked by this answer's "proposed".
6613
6695
  if (body.proposal?.state && body.code !== 'waiting') entry.local = { state: body.proposal.state, result: body.proposal.result || null, supersededBy: body.proposal.supersededBy || null };
6614
6696
  keepTick(entry, body.proposal?.acknowledged);
6615
- entry.error = body.error || 'FloLess could not do that just now. Try again in a moment.';
6697
+ entry.error = body.error || (verb === 'decline'
6698
+ ? 'FloLess could not set this aside just now. The suggestion is still here, so try Not now again in a moment.'
6699
+ : 'FloLess could not do that just now. Try again in a moment.');
6616
6700
  // #3238: "confirm that card first". The line then follows that card (actionStatusLine), so it never goes stale.
6617
6701
  const awaits = body.code === 'waiting' ? body.awaits : null;
6618
6702
  if (awaits && ['id', 'waiting', 'running', 'done'].every((key) => typeof awaits[key] === 'string')) entry.waitingOn = awaits;
6619
6703
  }
6620
6704
  } catch {
6621
- entry.error = 'FloLess could not be reached. Check that it is still running, then try again.';
6705
+ entry.error = verb === 'decline'
6706
+ ? 'FloLess could not be reached, so this was not set aside. Check that it is still running, then try again.'
6707
+ : 'FloLess could not be reached. Check that it is still running, then try again.';
6622
6708
  } finally {
6623
- entry.busy = '';
6624
- repaintActionCards(focus);
6709
+ clearTimeout(slow);
6710
+ entry.busy = ''; entry.slow = '';
6711
+ repaintActionCards();
6712
+ // #4116: the keyboard that landed on the folded card hears its line ("Not now: …"); saying it again would say it twice.
6713
+ if (said && !(entry.node?.classList.contains('is-collapsed') && document.activeElement === entry.node)) announce(said);
6625
6714
  }
6626
6715
  }
6627
6716
 
@@ -6646,20 +6735,48 @@
6646
6735
  status.className = 'ai-chat-filter-note ai-chat-action-status';
6647
6736
  status.setAttribute('role', 'status');
6648
6737
  status.tabIndex = -1;
6738
+ status.id = `chat-action-status-${proposalId}`;
6649
6739
  const titleId = `chat-action-title-${proposalId}`;
6650
6740
  card.setAttribute('aria-labelledby', titleId);
6741
+ // #3878: a click FloLess has been slow to answer says so (actOnProposal), whichever button it was.
6742
+ const waiting = entry.busy ? entry.slow || '' : '';
6743
+ /**
6744
+ * #4116: a card button while a click waits, and after. The pressed one keeps the keyboard, so it is aria-disabled (a
6745
+ * `disabled` button drops it to the page; actOnProposal ignores a second press), and the others are disabled. Once a
6746
+ * failure puts the card back, the pressed one is described by the status line, so the keyboard back on it hears why.
6747
+ */
6748
+ const pressable = (control, verb, blocked = false) => {
6749
+ if (entry.busy === verb) {
6750
+ control.setAttribute('aria-disabled', 'true');
6751
+ control.setAttribute('aria-busy', 'true');
6752
+ } else control.disabled = Boolean(entry.busy) || blocked;
6753
+ if (!entry.busy && entry.error && entry.pressed === verb) {
6754
+ control.setAttribute('aria-describedby', [control.getAttribute('aria-describedby'), status.id].filter(Boolean).join(' '));
6755
+ }
6756
+ return control;
6757
+ };
6758
+ // #3878: Not now while its answer is on the way says so, as Do it does ("Working…").
6759
+ const notNowButton = (tip) => {
6760
+ const control = actionButton(entry.busy === 'decline' ? 'Setting aside…' : 'Not now', 'shell.chat-action-not-now', proposalId, summaryText);
6761
+ control.dataset.tip = tip;
6762
+ return pressable(control, 'decline');
6763
+ };
6651
6764
 
6652
6765
  // Finished, set aside or replaced: one quiet line that says honestly what happened.
6653
6766
  // #3238: a card that waited for another card, which ended without making what it needed, says why.
6654
6767
  const ended = current.result?.code === 'card-ended' && typeof current.result.message === 'string' ? current.result.message.trim() : '';
6768
+ // #3647: a card ended because what it was composed from changed has NO newer card; it says why and what to do next.
6769
+ const recomposed = current.result?.code === 'changed-recompose' && typeof current.result.message === 'string' ? current.result.message.trim() : '';
6655
6770
  const collapsed = {
6656
6771
  declined: `Not now: ${title}`,
6657
6772
  expired: ended ? `Offer ended: ${title}. ${ended}` : `Offer ended: ${title}. Ask again if you still want it.`,
6658
- superseded: `Replaced by a newer suggestion: ${title}`,
6773
+ superseded: recomposed ? `Ended: ${title}. ${recomposed}` : `Replaced by a newer suggestion: ${title}`,
6659
6774
  cancelled: `Stopped: ${title}. Work already sent to the host may remain.`,
6660
6775
  }[current.state];
6661
6776
  if (collapsed) {
6662
6777
  card.classList.add('is-collapsed');
6778
+ // #4116: the keyboard that pressed Not now or Stop lands on the folded card (repaintActionCards), never a Tab stop.
6779
+ card.tabIndex = -1;
6663
6780
  const line = document.createElement('p');
6664
6781
  line.className = 'ai-chat-action-line';
6665
6782
  line.id = titleId;
@@ -6713,6 +6830,9 @@
6713
6830
  summary.className = 'ai-chat-action-summary';
6714
6831
  summary.textContent = summaryText;
6715
6832
  card.append(summary);
6833
+ // Sketches S1c (#3648, plan §6.3, §8): every claim the card makes, uncut, grouped by kind in a themed scrolling list.
6834
+ const detailsNode = window.flolessCardDetails?.render(payload.details, proposalId, { live: current.state === 'proposed' }) ?? null;
6835
+ if (detailsNode) card.append(detailsNode);
6716
6836
  // #2521 row 3a: what confirming agrees to (a Quick model read), whole and on its own line: the summary is cut to its
6717
6837
  // limit, terms never are.
6718
6838
  if (payload.terms) {
@@ -6791,6 +6911,17 @@
6791
6911
  if (current.state === 'unknown') {
6792
6912
  status.textContent = 'FloLess restarted while this was running, so how it ended is not known. Check the result, and ask the AI to suggest it again if you still want it.';
6793
6913
  card.append(status);
6914
+ // S1c (plan §8): a conversion from a sketch is checked where its state is shown, in the sketch.
6915
+ const subject = payload.details?.subject;
6916
+ if (subject?.kind === 'sketch' && typeof subject.sketchId === 'string' && window.flolessSketches?.open) {
6917
+ const row = document.createElement('div');
6918
+ row.className = 'ai-chat-filter-actions';
6919
+ const open = actionButton('Open the sketch', 'shell.chat-action-open-sketch', proposalId, summaryText);
6920
+ open.dataset.tip = 'Open Sketches on this sketch: each shape says whether its plate is in the model now.';
6921
+ open.addEventListener('click', () => window.flolessSketches.open(typeof subject.projectId === 'string' ? subject.projectId : undefined, subject.sketchId));
6922
+ row.append(open);
6923
+ card.append(row);
6924
+ }
6794
6925
  return card;
6795
6926
  }
6796
6927
  if (payload.riskReason) {
@@ -6815,11 +6946,11 @@
6815
6946
  actions.className = 'ai-chat-filter-actions';
6816
6947
  if (current.state === 'executing') {
6817
6948
  // A window step whose report did not land stays running here; what the window said (what to press) still shows.
6818
- status.textContent = actionStatusLine(entry, current) || (actionId === 'workflows.run' || actionId === 'routines.run' ? 'Running…' : 'Working…');
6949
+ status.textContent = waiting || actionStatusLine(entry, current) || (actionId === 'workflows.run' || actionId === 'routines.run' ? 'Running…' : 'Working…');
6819
6950
  if (actionId === 'workflows.run') {
6820
- const stop = actionButton('Stop', 'shell.chat-action-stop', proposalId, summaryText);
6951
+ const stop = actionButton(entry.busy === 'cancel' ? 'Stopping…' : 'Stop', 'shell.chat-action-stop', proposalId, summaryText);
6821
6952
  stop.dataset.tip = 'Asks the run to stop. Work already sent to the host may remain.';
6822
- stop.disabled = Boolean(entry.busy);
6953
+ pressable(stop, 'cancel');
6823
6954
  stop.addEventListener('click', () => { void actOnProposal(event, proposalId, 'cancel'); });
6824
6955
  actions.append(stop);
6825
6956
  }
@@ -6839,9 +6970,7 @@
6839
6970
  catch (error) { entry.error = error?.message || 'FloLess couldn’t open that from here.'; }
6840
6971
  if (entry.error) { status.textContent = entry.error; }
6841
6972
  });
6842
- const later = actionButton('Not now', 'shell.chat-action-not-now', proposalId, summaryText);
6843
- later.dataset.tip = 'Sets this suggestion aside. Nothing changes.';
6844
- later.disabled = Boolean(entry.busy);
6973
+ const later = notNowButton('Sets this suggestion aside. Nothing changes.');
6845
6974
  later.addEventListener('click', () => { void actOnProposal(event, proposalId, 'decline'); });
6846
6975
  actions.append(later, open);
6847
6976
  const note = document.createElement('p');
@@ -6849,29 +6978,26 @@
6849
6978
  // #2811: the one question this dialog asks only the person, said on the card that takes them there.
6850
6979
  note.textContent = screen.view === 'new-project' ? 'In the dialog, only you decide whether the AI may choose the Drawing Filter, and who picks the model origin. Nothing is made until you press Create.'
6851
6980
  : 'Only you can do this. Nothing runs from here.';
6852
- status.textContent = entry.error;
6981
+ status.textContent = waiting || entry.error;
6853
6982
  card.append(actions, note, status);
6854
6983
  return card;
6855
6984
  }
6856
- const later = actionButton('Not now', 'shell.chat-action-not-now', proposalId, summaryText);
6857
- later.dataset.tip = 'Sets this suggestion aside. Nothing runs.';
6858
- later.disabled = Boolean(entry.busy);
6985
+ const later = notNowButton('Sets this suggestion aside. Nothing runs.');
6859
6986
  later.addEventListener('click', () => { void actOnProposal(event, proposalId, 'decline'); });
6860
6987
  const confirm = actionButton(entry.busy === 'confirm' ? 'Working…' : (ACTION_CONFIRM_VERBS[actionId] || 'Do it'), 'shell.chat-action-confirm', proposalId, summaryText, 'ai-chat-filter-apply');
6861
6988
  confirm.dataset.tip = risk === 'destructive' ? 'Runs it now, for real. FloLess checks first that nothing changed since this was suggested.'
6862
6989
  : 'Makes this change now. FloLess checks first that nothing changed since this was suggested.';
6863
- confirm.disabled = Boolean(entry.busy) || (ackList.length > 0 && !(window.flolessCardAcks?.allTicked(ackList, entry.ticks || new Set())));
6864
6990
  ackConfirm = confirm;
6865
6991
  const acksBox = card.querySelector('.card-acks[id]');
6866
6992
  if (acksBox) confirm.setAttribute('aria-describedby', acksBox.id);
6867
- if (entry.busy === 'confirm') confirm.setAttribute('aria-busy', 'true');
6993
+ pressable(confirm, 'confirm', ackList.length > 0 && !(window.flolessCardAcks?.allTicked(ackList, entry.ticks || new Set())));
6868
6994
  confirm.addEventListener('click', () => { void actOnProposal(event, proposalId, 'confirm'); });
6869
6995
  actions.append(later, confirm);
6870
6996
  const meta = document.createElement('p');
6871
6997
  meta.className = 'ai-chat-filter-note ai-chat-action-meta';
6872
6998
  meta.textContent = payload.revision === 'bound' ? 'Checked against how it is now; if it changes first, you will be asked again.'
6873
6999
  : 'Acts on things as they are when you confirm.';
6874
- status.textContent = actionStatusLine(entry, current);
7000
+ status.textContent = waiting || actionStatusLine(entry, current);
6875
7001
  card.append(actions, meta, status);
6876
7002
  return card;
6877
7003
  }
@@ -7640,6 +7766,14 @@
7640
7766
  'human-only': 'A person does this in FloLess, so FloLess didn’t run it for the AI. Nothing changed.',
7641
7767
  'in-browser': 'This runs only when you confirm its card, so FloLess didn’t run it here. Nothing changed.',
7642
7768
  };
7769
+ // #4051: a project reference outside this chat's scope, told apart. FloLess refused it either way; these say why in
7770
+ // the person's words. A folder name for one of this chat's own projects is a quiet note: the AI usually corrects itself.
7771
+ const PROJECT_SCOPE_MISS_REASONS = {
7772
+ 'wrong-name': 'The AI used the folder name of a project this chat works on instead of its id, so FloLess didn’t run that step. The AI can try again with the right id. Nothing changed.',
7773
+ unknown: 'The AI used a project reference that isn’t one of this chat’s projects, so FloLess didn’t run that step. Nothing changed.',
7774
+ outside: 'The AI asked about another project, one this chat isn’t working on, so FloLess didn’t run it. Nothing changed.',
7775
+ unchecked: 'The AI used a project reference that isn’t one of this chat’s projects, so FloLess didn’t run that step. FloLess also could not check that project reference just now. Nothing changed.',
7776
+ };
7643
7777
  const actionNotRun = (payload) => payload.outcome === 'rejected' && payload.code !== 'action-definition';
7644
7778
  const payload = event.payload || {};
7645
7779
  if (payload.outcome === 'ok' && payload.card?.kind === 'page' && payload.card.home && payload.card.pageId) return renderPageCard(event);
@@ -7669,9 +7803,12 @@
7669
7803
  // were addressed to the AI (which field to fix, which action lists the ids) and would read as jargon here.
7670
7804
  const inputMessage = payload.code === 'invalid-input' && payload.forPerson === true && typeof payload.message === 'string'
7671
7805
  ? payload.message.trim() : '';
7806
+ // Only a string names a case: Object.hasOwn would coerce an array or object from a damaged saved row into a key (or throw).
7807
+ const scopeMissText = payload.code === 'out-of-scope' && typeof payload.scopeMiss === 'string' && Object.hasOwn(PROJECT_SCOPE_MISS_REASONS, payload.scopeMiss)
7808
+ ? PROJECT_SCOPE_MISS_REASONS[payload.scopeMiss] : '';
7672
7809
  const reasonText = outcome === 'not-run'
7673
7810
  ? (inputMessage ? `${inputMessage}${/[.!?…]$/.test(inputMessage) ? '' : '.'} FloLess didn’t run it, so nothing changed.`
7674
- : ACTION_NOT_RUN_REASONS[payload.code] || 'FloLess didn’t run it. Nothing changed.')
7811
+ : scopeMissText || ACTION_NOT_RUN_REASONS[payload.code] || 'FloLess didn’t run it. Nothing changed.')
7675
7812
  : outcome === 'failed' && payload.message ? String(payload.message) : '';
7676
7813
  if (reasonText) {
7677
7814
  const reason = document.createElement('span');
@@ -7809,6 +7946,31 @@
7809
7946
  return item;
7810
7947
  }
7811
7948
 
7949
+ /**
7950
+ * #4102: the claim of a person's decision on an action card that FloLess could not confirm reached the AI, from the
7951
+ * conversation record (`decisionClaims`), or null. Only `unconfirmed` changes the receipt; a pending, delivered or
7952
+ * missing claim keeps the decision-only one. Automatic decisions (#4153) and questions are not read here.
7953
+ */
7954
+ function unconfirmedClaim(event) {
7955
+ const payload = event?.payload;
7956
+ if (event?.type !== 'approval-decided' || !payload || payload.automatic === true || payload.kind === 'question') return null;
7957
+ const claims = Array.isArray(state.chat?.decisionClaims) ? state.chat.decisionClaims : [];
7958
+ return claims.find((claim) => claim?.approvalId === payload.approvalId && claim.delivery === 'unconfirmed') || null;
7959
+ }
7960
+
7961
+ /** #4102: the amber "Not confirmed" row of such a decision, in neutral words (never approved, denied, or what was handed over). */
7962
+ function renderNotConfirmedReceipt(event, claim) {
7963
+ const item = document.createElement('div');
7964
+ item.className = 'ai-chat-event auto-review held';
7965
+ item.dataset.eventSequence = String(event.sequence);
7966
+ item.dataset.eventId = event.eventId;
7967
+ const label = document.createElement('strong');
7968
+ label.textContent = 'Not confirmed';
7969
+ const what = String(claim.summary || '').slice(0, 200);
7970
+ item.append(label, document.createTextNode(` · FloLess could not confirm the AI received your decision${what ? ` on “${what}”` : ''}. Check whether it was done, and ask the AI to propose it again if needed.`));
7971
+ return item;
7972
+ }
7973
+
7812
7974
  /** One line for a decided workflow create (#1890 PR 3a): approved, denied, or stopped at FloLess's last check. */
7813
7975
  function renderCreateReceipt(event) {
7814
7976
  const item = document.createElement('div');
@@ -7818,14 +7980,15 @@
7818
7980
  const create = event.payload.create;
7819
7981
  const label = document.createElement('strong');
7820
7982
  const what = `the workflow “${create.name}” ${createWhere(create)}`;
7983
+ // #4102: the receipt states the decision, never a result: whether the workflow was created is the AI's reply to report.
7821
7984
  if (event.payload.reason) {
7822
- label.textContent = 'Not created';
7985
+ label.textContent = 'Stopped at the last check';
7823
7986
  item.append(label, document.createTextNode(` · ${event.payload.reason}`));
7824
7987
  } else if (event.payload.decision === 'allow') {
7825
7988
  label.textContent = 'Approved once';
7826
7989
  item.append(label, document.createTextNode(` · Create ${what}`));
7827
7990
  } else {
7828
- label.textContent = 'Not created';
7991
+ label.textContent = 'Denied';
7829
7992
  item.append(label, document.createTextNode(` · ${what}`));
7830
7993
  }
7831
7994
  return item;
@@ -8853,6 +9016,9 @@
8853
9016
  if (event.type === 'next-move') return state.chat?.earlierOpening ? null : window.flolessGuide?.renderNextMove?.(event) || null;
8854
9017
  // #2185: what came of a card's button repaints that card; it is never a line of its own.
8855
9018
  if (event.type === 'next-move-update') { window.flolessGuide?.applyMoveUpdate?.(event); return null; }
9019
+ // #4102: a person's decision FloLess could not confirm reached the AI says so first, whatever its receipt would be.
9020
+ const notConfirmed = unconfirmedClaim(event);
9021
+ if (notConfirmed) return renderNotConfirmedReceipt(event, notConfirmed);
8856
9022
  if (event.type === 'approval-decided' && event.payload?.automatic === true && event.payload?.connectionCheck) return renderConnectionCheckAllowed(event);
8857
9023
  // #2223 Revision 6: a question whose words already streamed carries only its card (above the message box): no empty bubble.
8858
9024
  if (event.type === 'assistant-message' && event.payload?.asyncQuestion && !payloadText(event)) return null;
@@ -8873,6 +9039,8 @@
8873
9039
  if (event.type === 'tekla-read') return renderTeklaReadEvent(event);
8874
9040
  if (event.type === 'height-question') return renderHeightQuestion(event);
8875
9041
  if (event.type === 'setup-question') return renderSetupQuestion(event);
9042
+ const expiredApproval = event.type === 'interrupted' && event.payload?.reason === 'approval-expired-on-restart';
9043
+ if (expiredApproval && hasApprovalSettlement(event.payload.approvalId, { includeDropped: true })) return null;
8876
9044
  const item = document.createElement('div');
8877
9045
  item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}`;
8878
9046
  item.dataset.eventSequence = String(event.sequence);
@@ -8931,7 +9099,8 @@
8931
9099
  item.append(label, document.createTextNode(` ${shown}${reason}${pdf}`));
8932
9100
  return item;
8933
9101
  }
8934
- label.textContent = event.type === 'error' && payload.outcome === 'not-sent' ? 'Not sent' : labels[event.type] || event.type;
9102
+ label.textContent = expiredApproval ? 'Not answered'
9103
+ : event.type === 'error' && payload.outcome === 'not-sent' ? 'Not sent' : labels[event.type] || event.type;
8935
9104
  // #1907: a not-sent reason the server wrote for the person (`plain`) is shown as is.
8936
9105
  let detail = event.type === 'error'
8937
9106
  ? (payload.plain === true && typeof payload.message === 'string' && payload.message ? payload.message : errorRowMessage(event))
@@ -8941,7 +9110,8 @@
8941
9110
  const statusLabels = { started: 'started', completed: 'completed', failed: 'failed', denied: 'not allowed' };
8942
9111
  detail = [toolLabels[payload.tool] || 'AI action', statusLabels[payload.status] || payload.status].filter(Boolean).join(' · ');
8943
9112
  }
8944
- if (!detail && event.type === 'interrupted') detail = 'The AI response was interrupted.';
9113
+ if (expiredApproval) detail = 'The AI session ended before this question was answered.';
9114
+ else if (!detail && event.type === 'interrupted') detail = 'The AI response was interrupted.';
8945
9115
  if (!detail && event.type === 'usage') {
8946
9116
  detail = 'Usage updated';
8947
9117
  }
@@ -12151,13 +12321,20 @@
12151
12321
  card.append(hide);
12152
12322
  }
12153
12323
 
12324
+ function hasApprovalSettlement(approvalId, { includeDropped = false } = {}) {
12325
+ return Boolean(approvalId && state.events.some(event =>
12326
+ event.payload?.approvalId === approvalId && (event.type === 'approval-decided'
12327
+ || (includeDropped && event.type === 'tool' && event.payload.tool === 'approval-dropped'))));
12328
+ }
12329
+
12154
12330
  function paintApproval() {
12155
12331
  clearSettledQuestionDrafts(state.events, state.chat);
12156
12332
  paintApprovalScope();
12157
12333
  // A hidden drawing question's one line holds the slot like its card does, so an approval or question replaces it too.
12158
12334
  // Only the tray's own line: a card hidden in the conversation leaves one too (#2678), and it is not this slot's.
12159
12335
  const existing = shell.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope), .ai-chat-approval-tray > .ai-chat-hidden-line');
12160
- const approval = state.chat?.pendingApproval;
12336
+ const pending = state.chat?.pendingApproval;
12337
+ const approval = pending && !hasApprovalSettlement(pending.approvalId) ? pending : null;
12161
12338
  const deciding = Boolean(approval && state.decidingApprovalIds.has(approval.approvalId));
12162
12339
  shell.dataset.approvalPending = String(Boolean(approval) && !deciding);
12163
12340
  // #2223 Revision 6: a question Codex asked without waiting, while no approval holds the slot — a blocking question or an
@@ -14298,6 +14475,7 @@
14298
14475
  function closeSource() {
14299
14476
  if (state.eventReconnectTimer) { clearTimeout(state.eventReconnectTimer); state.eventReconnectTimer = null; }
14300
14477
  if (state.source) { state.source.close(); state.source = null; }
14478
+ state.eventReconnectBlockedSource = null;
14301
14479
  }
14302
14480
 
14303
14481
  function sameScope(scope, generation) {
@@ -14325,16 +14503,32 @@
14325
14503
 
14326
14504
  function scheduleEventReconnect(chatId, scope, generation) {
14327
14505
  // EventSource permanently closes on the 401 emitted after a local-server restart. It does not
14328
- // retry a closed stream itself, so renew the short-lived UI session and reconnect once.
14329
- if (state.eventReconnectTimer || state.eventReconnectAttempt >= 1
14330
- || state.chat?.chatId !== chatId || !sameScope(scope, generation)) return;
14331
- state.eventReconnectAttempt += 1;
14332
- state.eventReconnectTimer = setTimeout(async () => {
14333
- state.eventReconnectTimer = null;
14334
- if (state.chat?.chatId !== chatId || !sameScope(scope, generation)) return;
14335
- state.sessionReady = false;
14336
- await refreshConversation(chatId, true);
14337
- }, 300);
14506
+ // retry a closed stream itself. Retry transport failures from this loop alone.
14507
+ const snapshot = captureChat();
14508
+ const source = state.source;
14509
+ if (state.eventReconnectTimer || source?.readyState !== EventSource.CLOSED || source === state.eventReconnectBlockedSource
14510
+ || snapshot?.chatId !== chatId || !sameScope(scope, generation)) return;
14511
+ const recovery = state.refreshRecovery;
14512
+ if (recovery && recovery.timer !== null) {
14513
+ clearTimeout(recovery.timer);
14514
+ recovery.timer = null;
14515
+ }
14516
+ const timer = setTimeout(async () => {
14517
+ try {
14518
+ if (!sameChat(snapshot) || state.source !== source || source.readyState !== EventSource.CLOSED) return;
14519
+ state.sessionReady = false;
14520
+ await refreshConversation(chatId, true);
14521
+ } finally {
14522
+ // connectEvents/closeSource may have replaced this timer while the read was in flight.
14523
+ if (state.eventReconnectTimer === timer) {
14524
+ state.eventReconnectTimer = null;
14525
+ if (state.source === source && sameChat(snapshot) && state.refreshRecovery) {
14526
+ scheduleEventReconnect(chatId, scope, generation);
14527
+ }
14528
+ }
14529
+ }
14530
+ }, transportRetryDelay(state.eventReconnectAttempt++));
14531
+ state.eventReconnectTimer = timer;
14338
14532
  }
14339
14533
 
14340
14534
  function connectEvents() {
@@ -14409,7 +14603,7 @@
14409
14603
  }
14410
14604
  paintEvents(); paintUnread();
14411
14605
  // #2223 Revision 6: a message that asks a question without waiting opens its card; the person's next message closes it.
14412
- if (event.type === 'user-message' || event.payload?.asyncQuestion) paintApproval();
14606
+ if (event.type === 'user-message' || event.type === 'approval-decided' || event.payload?.asyncQuestion) paintApproval();
14413
14607
  if (!document.hidden && !ui.feed.closest('[hidden]')) markRead();
14414
14608
  if (['approval-requested', 'approval-decided', 'error', 'interrupted', 'state', 'followup-status'].includes(event.type)
14415
14609
  || (event.type === 'user-message' && event.payload?.followup)) {
@@ -14427,6 +14621,13 @@
14427
14621
  try { payload = JSON.parse(message.data); } catch { return; }
14428
14622
  if (payload?.to?.chatId) void followMovedChat(payload.to);
14429
14623
  });
14624
+ // #4102: a decision's delivery state changed on the server (FloLess could not confirm it): read the record again.
14625
+ source.addEventListener('card-update', (message) => {
14626
+ if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
14627
+ let payload = null;
14628
+ try { payload = JSON.parse(message.data); } catch { return; }
14629
+ if (payload?.chatId === chatId) refreshConversation(chatId, false);
14630
+ });
14430
14631
  source.addEventListener('ready', () => {
14431
14632
  if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
14432
14633
  state.eventReconnectAttempt = 0;
@@ -14434,7 +14635,7 @@
14434
14635
  });
14435
14636
  source.onerror = () => {
14436
14637
  if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
14437
- ui.hint.textContent = 'Reconnecting to this conversation…';
14638
+ if (!heldReport()) ui.hint.textContent = 'Reconnecting to this conversation…';
14438
14639
  paintEvents();
14439
14640
  if (source.readyState === EventSource.CLOSED) scheduleEventReconnect(chatId, scope, generation);
14440
14641
  };
@@ -14487,6 +14688,7 @@
14487
14688
  }
14488
14689
 
14489
14690
  function disposeChatSession() {
14691
+ if (state.refreshRecovery || state.refreshReport) clearRefreshRecovery(state.chat?.chatId);
14490
14692
  state.sessionDisposed = true; state.sessionLifecycle += 1; state.sessionReady = false;
14491
14693
  state.sessionOperation?.cancel();
14492
14694
  state.sessionOperation = null;
@@ -14543,8 +14745,8 @@
14543
14745
  }
14544
14746
 
14545
14747
  function sessionNeedsRenewal(error) {
14546
- return error?.code === 'chat-session-required'
14547
- || /chat UI session is missing or expired/i.test(error instanceof Error ? error.message : String(error));
14748
+ return error?.status === 401 && (error.code === 'chat-session-required'
14749
+ || /chat UI session is missing or expired/i.test(error.message));
14548
14750
  }
14549
14751
 
14550
14752
  async function readCapability(chat) {
@@ -14602,41 +14804,119 @@
14602
14804
  }, CAPABILITY_RECHECK_MS[attempt]);
14603
14805
  }
14604
14806
 
14605
- async function refreshConversation(chatId, reconnect = false) {
14807
+ function transportRetryDelay(attempt) {
14808
+ const delays = [2000, 4000, 8000, 15000];
14809
+ return delays[Math.min(attempt, delays.length - 1)];
14810
+ }
14811
+
14812
+ function clearRefreshRecovery(chatId) {
14813
+ state.refreshReadGeneration = (state.refreshReadGeneration || 0) + 1;
14814
+ clearTimeout(state.refreshRecovery?.timer);
14815
+ state.refreshRecovery = null;
14816
+ const hold = state.refreshReport;
14817
+ if (!hold || hold.chatId !== chatId) return;
14818
+ state.refreshReport = null;
14819
+ if (state.reportHold !== hold) return;
14820
+ state.reportHold = null;
14821
+ if (state.reportLiveMessage === hold.message) retireReportAnnouncement();
14822
+ clearReport();
14823
+ }
14824
+
14825
+ function reportRefreshFailure(error, snapshot, prefix = 'Could not refresh chat') {
14826
+ const code = error?.code;
14827
+ const transport = code === 'local-unreachable' || code === 'local-timeout';
14828
+ const previous = state.reportHold;
14829
+ const unrelatedReport = previous && previous !== state.refreshReport;
14830
+ const closedStream = state.source?.readyState === EventSource.CLOSED;
14831
+ if (transport) {
14832
+ if (closedStream && state.source === state.eventReconnectBlockedSource) return;
14833
+ if (!state.refreshRecovery) state.refreshRecovery = { since: Date.now(), attempt: 0, timer: null };
14834
+ const recovery = state.refreshRecovery;
14835
+ const delayed = Date.now() - recovery.since >= 60000;
14836
+ const message = delayed
14837
+ ? 'FloLess hasn’t answered for a minute, so this conversation hasn’t refreshed. Your messages are still here. Press ↻ to try now, or restart FloLess from the tray.'
14838
+ : 'FloLess didn’t answer, so this conversation hasn’t refreshed. Your messages are still here. Trying again…';
14839
+ if (closedStream) {
14840
+ scheduleEventReconnect(snapshot.chatId, snapshot.scope, snapshot.generation);
14841
+ } else if (recovery.timer === null) {
14842
+ recovery.timer = setTimeout(async () => {
14843
+ if (state.refreshRecovery !== recovery) return;
14844
+ recovery.timer = null;
14845
+ if (sameChat(snapshot)) {
14846
+ await refreshConversation(snapshot.chatId, !state.source || state.source.readyState === EventSource.CLOSED);
14847
+ }
14848
+ }, transportRetryDelay(recovery.attempt++));
14849
+ }
14850
+ // Keep a newer composer report, and announce the outage only when its wording changes.
14851
+ if (unrelatedReport || previous?.message === message) return;
14852
+ report(error, '', { [code]: message }, delayed ? 'warn' : 'retrying');
14853
+ } else {
14854
+ clearTimeout(state.refreshRecovery?.timer);
14855
+ state.refreshRecovery = null;
14856
+ if (closedStream) {
14857
+ if (state.source === state.eventReconnectBlockedSource) return;
14858
+ state.eventReconnectBlockedSource = state.source;
14859
+ clearTimeout(state.eventReconnectTimer);
14860
+ state.eventReconnectTimer = null;
14861
+ }
14862
+ if (unrelatedReport) return;
14863
+ report(error, prefix);
14864
+ }
14865
+ if (state.reportHold !== previous) state.refreshReport = state.reportHold;
14866
+ }
14867
+
14868
+ async function refreshConversation(chatId, reconnect = false, { fresh = false } = {}) {
14606
14869
  const snapshot = captureChat();
14607
- if (!snapshot || snapshot.chatId !== chatId) return;
14608
- try {
14609
- const path = `/api/chat/conversations/${encodeURIComponent(chatId)}?${ownerQuery(snapshot.scope.owner)}`;
14610
- let chat;
14870
+ if (!snapshot || snapshot.chatId !== chatId) return false;
14871
+ // A poll, retry timer and stream reconnect can all ask for the same conversation read.
14872
+ // Header refresh needs a newer read before deciding whether to stop a turn.
14873
+ const pending = state.refreshInFlight;
14874
+ if (!fresh && pending && sameChat(pending.snapshot)) {
14875
+ pending.reconnect ||= reconnect;
14876
+ return pending.promise;
14877
+ }
14878
+ const flight = { snapshot, reconnect, promise: null };
14879
+ state.refreshInFlight = flight;
14880
+ const current = () => sameChat(snapshot) && state.refreshInFlight === flight;
14881
+ flight.promise = (async () => {
14882
+ const readGeneration = state.refreshReadGeneration;
14611
14883
  try {
14612
- chat = await request(path);
14884
+ const path = `/api/chat/conversations/${encodeURIComponent(chatId)}?${ownerQuery(snapshot.scope.owner)}`;
14885
+ let chat;
14886
+ try {
14887
+ chat = await request(path);
14888
+ } catch (error) {
14889
+ // The server session is deliberately short-lived. A completed turn must not remain
14890
+ // visually active just because the first reconciliation request used an old cookie.
14891
+ if (!sessionNeedsRenewal(error)) throw error;
14892
+ if (!current()) return false;
14893
+ state.sessionReady = false;
14894
+ await ensureSession();
14895
+ if (!current()) return false;
14896
+ chat = await request(path);
14897
+ }
14898
+ if (!current()) return false;
14899
+ state.chat = chat;
14900
+ // #2223 Revision 6: a file on the open question card's answer goes with that answer, not with the box's next message.
14901
+ state.attachments = composerDrafts(chat);
14902
+ const index = state.chats.findIndex((item) => item.chatId === chatId);
14903
+ if (index >= 0) state.chats[index] = chat;
14904
+ clearRefreshRecovery(chatId);
14905
+ paintConversation();
14906
+ if (flight.reconnect) connectEvents();
14907
+ return true;
14613
14908
  } catch (error) {
14614
- // The server session is deliberately short-lived. A completed turn must not remain
14615
- // visually active just because the first reconciliation request used an old cookie.
14616
- if (!sessionNeedsRenewal(error)) throw error;
14617
- state.sessionReady = false;
14618
- await ensureSession();
14619
- if (!sameChat(snapshot)) return;
14620
- chat = await request(path);
14909
+ if (current() && readGeneration === state.refreshReadGeneration) reportRefreshFailure(error, snapshot);
14910
+ return false;
14621
14911
  }
14622
- if (!sameChat(snapshot)) return;
14623
- state.chat = chat;
14624
- // #2223 Revision 6: a file on the open question card's answer goes with that answer, not with the box's next message.
14625
- state.attachments = composerDrafts(chat);
14626
- const index = state.chats.findIndex((item) => item.chatId === chatId);
14627
- if (index >= 0) state.chats[index] = chat;
14628
- paintConversation();
14629
- if (reconnect) connectEvents();
14630
- } catch (error) {
14631
- if (!sameChat(snapshot)) return;
14632
- // #3123: a timeout here means FloLess is busy, not stopped, and what the person already sees stays.
14633
- if (error?.code === 'local-timeout') report(error, '', { 'local-timeout': 'FloLess is busy, so this conversation hasn’t refreshed yet. Your messages are still here. Reopen the conversation in a moment to see anything new.' });
14634
- else report(error, 'Could not refresh chat');
14635
- }
14912
+ })();
14913
+ try { return await flight.promise; }
14914
+ finally { if (state.refreshInFlight === flight) state.refreshInFlight = null; }
14636
14915
  }
14637
14916
 
14638
14917
  // #3580: with a scope and no conversation yet, this is a project (workflow, workspace) whose list is still loading.
14639
14918
  function showConversationLoading(chatId, scope = null) {
14919
+ if (state.refreshRecovery || state.refreshReport) clearRefreshRecovery(state.chat?.chatId);
14640
14920
  const listed = chatId ? state.chats.find((chat) => chat.chatId === chatId) : null;
14641
14921
  closeSource();
14642
14922
  clearLiveStream(true);
@@ -14676,8 +14956,7 @@
14676
14956
 
14677
14957
  async function selectConversation(chatId, options = {}) {
14678
14958
  if (!state.scope) return;
14679
- // An explicit re-open is allowed to try a new event stream after the single automatic retry
14680
- // was exhausted during a local-server outage. It never resets a background reconnect loop.
14959
+ // An explicit re-open starts its own event stream at the initial retry delay.
14681
14960
  state.eventReconnectChatId = chatId;
14682
14961
  state.eventReconnectAttempt = 0;
14683
14962
  // A provider picker is an explicit user choice. Only an action that explicitly replaces it
@@ -14687,6 +14966,7 @@
14687
14966
  // conversation created from that chooser should inherit its draft.
14688
14967
  if (!options.preserveDiscoveryDraft) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; }
14689
14968
  clearProviderChoice();
14969
+ if (state.refreshRecovery || state.refreshReport) clearRefreshRecovery(state.chat?.chatId);
14690
14970
  const selection = ++state.selectionGeneration;
14691
14971
  // An Instructor answer, or a question an object card links to (#1653): both open at that one message.
14692
14972
  const exactQuestion = typeof options.messageEventId === 'string' ? options.messageEventId : null;
@@ -14837,6 +15117,7 @@
14837
15117
  // into the conversation the person just navigated away from (#1582).
14838
15118
  state.historyRename?.abandon();
14839
15119
  if (scopeKey(scope) !== scopeKey(state.scope)) { state.discoveryDraft = null; state.pendingTeklaLibrary = null; state.teklaDraft = null; }
15120
+ if (state.refreshRecovery || state.refreshReport) clearRefreshRecovery(state.chat?.chatId);
14840
15121
  state.selectionGeneration += 1;
14841
15122
  clearAnswerJump();
14842
15123
  clearLiveStream(true);
@@ -16490,8 +16771,8 @@
16490
16771
  state.chat = { ...previousChat, draft: given ? previousChat.draft : '', state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
16491
16772
  if (!given) { ui.input.value = ''; autosize(); state.attachments = []; if (mentionItems.length) state.mentions = { ...state.mentions, [chatId]: liveMentions().slice(20) }; paintAttachments(); }
16492
16773
  setBusy(true); paintConversation();
16493
- const mentionsLeft = given ? 0 : liveMentions().length;
16494
- announce(mentionsLeft ? `Message sent. ${mentionsLeft} more ${mentionsLeft === 1 ? 'mention stays' : 'mentions stay'} above the box for your next message: one message carries up to 20.` : 'Message sent.');
16774
+ announce('Sending…', () => sameChat(snapshot) && state.pendingSubmissionId === clientSubmissionId);
16775
+ const projectWait = state.projectBusy;
16495
16776
  try {
16496
16777
  // A debounced save already in flight must finish before the server clears
16497
16778
  // the draft while admitting this message.
@@ -16526,15 +16807,21 @@
16526
16807
  if (given) keepComposerDraft();
16527
16808
  for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
16528
16809
  paintConversation();
16810
+ const mentionsLeft = given ? 0 : liveMentions().length;
16811
+ announce(mentionsLeft ? `Message sent. ${mentionsLeft} more ${mentionsLeft === 1 ? 'mention stays' : 'mentions stay'} above the box for your next message: one message carries up to 20.` : 'Message sent.');
16529
16812
  // The server accepts a turn only from a ready provider, so a warning from an earlier check is stale.
16530
16813
  if (!providerReady()) void loadCapability().then(() => { if (sameChat(snapshot)) { paintSettings(); updateSendState(); } });
16531
16814
  if (given) return { sent: true };
16532
16815
  } catch (error) {
16533
- const unconfirmedAnswer = 'FloLess is busy and hasn’t confirmed your answer reached the AI yet. Check the conversation before you answer again.';
16816
+ const lostConnection = error?.code === 'local-unreachable';
16817
+ const deliveryUnknown = lostConnection || error?.code === 'local-timeout';
16818
+ if (deliveryUnknown && projectWait && state.projectBusy === projectWait) endProjectBusy();
16819
+ const unconfirmedMessage = 'FloLess didn’t answer, so it can’t confirm this message was sent. Check the conversation before sending it again.';
16820
+ const unconfirmedAnswer = lostConnection ? unconfirmedMessage : 'FloLess is busy and hasn’t confirmed your answer reached the AI yet. Check the conversation before you answer again.';
16534
16821
  if (!sameChat(snapshot)) {
16535
- // #2957: a timed-out send is as unconfirmed after the person moved on; it waits as unconfirmed in its own
16822
+ // #2957: a send with a lost reply waits as unconfirmed in its own
16536
16823
  // conversation (reconcileUnknownFollowupOnSelection), and is settled there if that conversation is open again.
16537
- if (error?.code === 'local-timeout') {
16824
+ if (deliveryUnknown) {
16538
16825
  optimisticEvent.payload.deliveryState = 'unknown';
16539
16826
  state.unknownFollowups.set(chatId, { submissionId: clientSubmissionId, text, event: optimisticEvent });
16540
16827
  // Open again through another project counts too (a new scope generation, the same owner): by owner, not generation.
@@ -16553,10 +16840,9 @@
16553
16840
  return;
16554
16841
  }
16555
16842
  state.pendingSubmissionId = null;
16556
- // #2957: the browser stopped waiting, but the server keeps working on the message, so it may already be in the
16557
- // conversation. A timed-out send is unconfirmed, never "not sent": the message stays visible as unconfirmed, and
16558
- // its user-message event or the person's "Review draft and continue" settles it, as for an uncertain follow-up.
16559
- if (error?.code === 'local-timeout') {
16843
+ // #2957: a lost reply may follow server acceptance. Keep the message visible until its event arrives
16844
+ // or the person resolves it, as with an uncertain follow-up.
16845
+ if (deliveryUnknown) {
16560
16846
  const arrived = state.events.some((event) => !event.optimistic && event.type === 'user-message'
16561
16847
  && event.clientSubmissionId === clientSubmissionId);
16562
16848
  state.chat = previousChat;
@@ -16564,7 +16850,7 @@
16564
16850
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
16565
16851
  paintConversation();
16566
16852
  refreshConversation(chatId, false);
16567
- announce('FloLess was slow to answer, but your message went through.');
16853
+ announce(lostConnection ? 'Message sent.' : 'FloLess was slow to answer, but your message went through.');
16568
16854
  return given ? { sent: true } : undefined;
16569
16855
  }
16570
16856
  optimisticEvent.payload.deliveryState = 'unknown';
@@ -16577,7 +16863,7 @@
16577
16863
  // The words come back so nothing is lost, but are not saved as a draft: the message may already be on its way.
16578
16864
  // Its files and mentions stay with the message that may have gone.
16579
16865
  ui.input.value = text; autosize(); state.localDraft = { chatId, text }; paintConversation();
16580
- report(error, '', { 'local-timeout': 'FloLess is busy and hasn’t confirmed your message yet. It will appear here if it went through. Check before sending it again.' });
16866
+ report(error, '', { 'local-unreachable': unconfirmedMessage, 'local-timeout': 'FloLess is busy and hasn’t confirmed your message yet. It will appear here if it went through. Check before sending it again.' });
16581
16867
  return;
16582
16868
  }
16583
16869
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
@@ -17005,6 +17291,8 @@
17005
17291
  : 'Follow-up saved. Waiting for AI.') + leftNote);
17006
17292
  paintConversation();
17007
17293
  } catch (error) {
17294
+ const transport = error?.code === 'local-unreachable' || error?.code === 'local-timeout';
17295
+ const unconfirmed = 'FloLess didn’t answer, so it can’t confirm this message was sent. Check the conversation before sending it again.';
17008
17296
  if (!sameChat(snapshot)) {
17009
17297
  if (given && followupDefinitelyRefused(error)) return notSent();
17010
17298
  if (followupDefinitelyRefused(error)) {
@@ -17021,7 +17309,7 @@
17021
17309
  paintEvents(); updateSendState();
17022
17310
  }
17023
17311
  }
17024
- return notSent();
17312
+ return notSent(transport ? unconfirmed : undefined);
17025
17313
  }
17026
17314
  if (state.events.some((event) => !event.optimistic && event.clientSubmissionId === clientSubmissionId
17027
17315
  && event.type === 'user-message')) {
@@ -17055,13 +17343,14 @@
17055
17343
  outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, mentionsKey: mentionItems.map((item) => item.key).join('\n'), error, given };
17056
17344
  } else if (given) {
17057
17345
  outcome = notSent(definitiveRefusal ? givenRefusal(error)
17058
- : 'FloLess couldn’t confirm your answer reached the AI. Check the conversation before you answer again.');
17059
- } else failedDelivery = { error, prefix: definitiveRefusal ? '' : 'Could not confirm the follow-up' };
17346
+ : transport ? unconfirmed : 'FloLess couldn’t confirm your answer reached the AI. Check the conversation before you answer again.');
17347
+ } else failedDelivery = { error, prefix: definitiveRefusal || transport ? '' : 'Could not confirm the follow-up',
17348
+ messages: transport ? { [error.code]: unconfirmed } : null };
17060
17349
  } finally {
17061
17350
  state.followupSubmitting = false;
17062
17351
  if (sameChat(snapshot)) {
17063
17352
  updateSendState();
17064
- if (failedDelivery) report(failedDelivery.error, failedDelivery.prefix);
17353
+ if (failedDelivery) report(failedDelivery.error, failedDelivery.prefix, failedDelivery.messages);
17065
17354
  if (document.activeElement === document.body || document.activeElement === ui.send) ui.input.focus();
17066
17355
  }
17067
17356
  }
@@ -17245,8 +17534,8 @@
17245
17534
  state.sessionReady = false;
17246
17535
  await ensureSession();
17247
17536
  if (!sameChat(snapshot)) return;
17248
- await refreshConversation(chatId, false);
17249
- if (!sameChat(snapshot)) return;
17537
+ const refreshed = await refreshConversation(chatId, false, { fresh: true });
17538
+ if (!refreshed || !sameChat(snapshot)) return;
17250
17539
  if (state.chat.activeTurn && !state.chat.activeTurn.local) {
17251
17540
  await stopTurn();
17252
17541
  if (!sameChat(snapshot) || state.chat.activeTurn) return;
@@ -17255,9 +17544,15 @@
17255
17544
  if (!sameChat(snapshot)) return;
17256
17545
  announce('Chat session refreshed.');
17257
17546
  } catch (error) { failure = error; }
17258
- finally { if (sameChat(snapshot)) { ui.refresh.disabled = false; updateSendState(); } }
17547
+ finally {
17548
+ if (sameChat(snapshot)) {
17549
+ if (!state.source) connectEvents();
17550
+ ui.refresh.disabled = false;
17551
+ updateSendState();
17552
+ }
17553
+ }
17259
17554
  // After updateSendState, which rewrites the composer hint and used to erase this sentence (#1604).
17260
- if (failure && sameChat(snapshot)) report(failure, 'Could not refresh this chat session');
17555
+ if (failure && sameChat(snapshot)) reportRefreshFailure(failure, snapshot, 'Could not refresh this chat session');
17261
17556
  }
17262
17557
 
17263
17558
  async function endRecovery() {
@@ -17697,8 +17992,14 @@
17697
17992
  const fetchedSequence = Number(active.lastEventSequence) || 0;
17698
17993
  if (fetchedSequence >= knownSequence) Object.assign(state.chat, active);
17699
17994
  }
17995
+ const closedStream = state.source && state.source.readyState === EventSource.CLOSED
17996
+ && state.source !== state.eventReconnectBlockedSource;
17997
+ if (state.chat && (state.refreshRecovery || closedStream)) {
17998
+ await refreshConversation(state.chat.chatId, !state.source || closedStream);
17999
+ if (!sameScope(scope, generation)) return;
18000
+ }
17700
18001
  // A Tekla read allowance granted or revoked in another window changes only the chat record,
17701
- // never the event stream: this poll is how the Tekla box and any open card learn of it.
18002
+ // so the Tekla box and any open card learn of it from this poll.
17702
18003
  paintTeklaChip();
17703
18004
  // SSE delivers messages immediately, while this poll is what confirms that the provider has
17704
18005
  // finished. Keep the Rename chat control in step with that durable active-turn state.
@@ -18813,6 +19114,7 @@
18813
19114
  // waiting for capability discovery, and the poll repaints whatever `state.chat` holds: invalidate
18814
19115
  // the one and clear the other, or the old conversation is painted back over the chooser.
18815
19116
  function beginProviderChoice() {
19117
+ if (state.refreshRecovery || state.refreshReport) clearRefreshRecovery(state.chat?.chatId);
18816
19118
  state.selectionGeneration += 1;
18817
19119
  state.choosingProvider = true;
18818
19120
  closeSource(); clearLiveStream(true);